Repository: baidubce/app-builder Branch: master Commit: 1373b758244c Files: 882 Total size: 9.4 MB Directory structure: gitextract_900dxzul/ ├── .env_template ├── .github/ │ └── workflows/ │ └── python-package.yml ├── CONTRIBUTING.md ├── LICENSE ├── NEW_README.md ├── README.md ├── cookbooks/ │ ├── README.md │ ├── advanced_application/ │ │ ├── agent_speech.ipynb │ │ └── cloud_deploy.ipynb │ ├── agent_builder.ipynb │ ├── appbuilder_trace/ │ │ └── trace.ipynb │ ├── components/ │ │ ├── agent_runtime.ipynb │ │ ├── asr.ipynb │ │ ├── gbi.ipynb │ │ ├── general_ocr.ipynb │ │ ├── object_recognize.ipynb │ │ ├── rag_with_baidusearch.ipynb │ │ ├── text_generation.ipynb │ │ ├── translate.ipynb │ │ └── vdb_retriever.ipynb │ ├── end2end_application/ │ │ ├── agent/ │ │ │ ├── appbuilder_client.ipynb │ │ │ ├── chatflow.ipynb │ │ │ ├── tool_call.ipynb │ │ │ └── tool_choice.ipynb │ │ └── rag/ │ │ ├── console_dataset.ipynb │ │ ├── console_rag.ipynb │ │ ├── qa_system_1_dataset.ipynb │ │ ├── qa_system_2_dialogue.ipynb │ │ └── rag.ipynb │ ├── live_broadcast_material/ │ │ ├── 2024_05_16/ │ │ │ ├── agent_run.py │ │ │ ├── chatbot.py │ │ │ ├── service_deploy.py │ │ │ └── two_agent.py │ │ ├── 2024_08_22/ │ │ │ ├── README.md │ │ │ ├── knowledgebase.ipynb │ │ │ ├── tool_call_1.ipynb │ │ │ ├── tool_call_2.ipynb │ │ │ ├── tool_call_3.ipynb │ │ │ ├── tool_call_4.ipynb │ │ │ └── trace.ipynb │ │ └── 2024_12_18/ │ │ └── rag_knowledgebase_01.ipynb │ ├── mcp/ │ │ ├── app_mcp_server.ipynb │ │ ├── baidu_map.ipynb │ │ ├── client.ipynb │ │ ├── knowledge_base_mcp_server.ipynb │ │ └── server.ipynb │ └── pipeline/ │ ├── assistant.ipynb │ ├── assistant_function_call.ipynb │ ├── file.ipynb │ ├── message.ipynb │ ├── run.ipynb │ └── thread.ipynb ├── docs/ │ ├── Application/ │ │ ├── Agent/ │ │ │ ├── BasicKnowledge/ │ │ │ │ └── agent.md │ │ │ ├── ToolCall/ │ │ │ │ └── tool_call.md │ │ │ ├── ToolChoice/ │ │ │ │ └── tool_choice.md │ │ │ └── UseOfficialComponents/ │ │ │ └── use_official_components.md │ │ └── RAG/ │ │ ├── BasicKnowledge/ │ │ │ └── rag.md │ │ └── DatasetManage/ │ │ └── dataset_manage.md │ ├── BasisModule/ │ │ ├── Components/ │ │ │ ├── Components.md │ │ │ ├── animal_recognize/ │ │ │ │ └── README.md │ │ │ ├── asr/ │ │ │ │ └── README.md │ │ │ ├── dish_recognize/ │ │ │ │ └── README.md │ │ │ ├── doc_crop_enhance/ │ │ │ │ └── README.md │ │ │ ├── doc_format_converter/ │ │ │ │ └── README.md │ │ │ ├── doc_parser/ │ │ │ │ └── README.md │ │ │ ├── doc_splitter/ │ │ │ │ └── README.md │ │ │ ├── document_understanding/ │ │ │ │ └── README.md │ │ │ ├── embeddings/ │ │ │ │ └── README.md │ │ │ ├── extract_table/ │ │ │ │ └── README.md │ │ │ ├── gbi/ │ │ │ │ ├── nl2sql/ │ │ │ │ │ └── README.md │ │ │ │ └── select_table/ │ │ │ │ └── README.md │ │ │ ├── general_ocr/ │ │ │ │ └── README.md │ │ │ ├── handwrite_ocr/ │ │ │ │ └── README.md │ │ │ ├── image_understand/ │ │ │ │ └── README.md │ │ │ ├── landmark_recognize/ │ │ │ │ └── README.md │ │ │ ├── llms/ │ │ │ │ ├── dialog_summary/ │ │ │ │ │ └── README.md │ │ │ │ ├── hallucination_detection/ │ │ │ │ │ └── README.md │ │ │ │ ├── is_complex_query/ │ │ │ │ │ └── README.md │ │ │ │ ├── mrc/ │ │ │ │ │ └── README.md │ │ │ │ ├── nl2pandas/ │ │ │ │ │ └── README.md │ │ │ │ ├── oral_query_generation/ │ │ │ │ │ └── README.md │ │ │ │ ├── playground/ │ │ │ │ │ └── README.md │ │ │ │ ├── qa_pair_mining/ │ │ │ │ │ └── README.md │ │ │ │ ├── query_decomposition/ │ │ │ │ │ └── README.md │ │ │ │ ├── query_rewrite/ │ │ │ │ │ └── README.md │ │ │ │ ├── similar_question/ │ │ │ │ │ └── README.md │ │ │ │ ├── style_rewrite/ │ │ │ │ │ └── README.md │ │ │ │ ├── style_writing/ │ │ │ │ │ └── README.md │ │ │ │ └── tag_extraction/ │ │ │ │ └── README.md │ │ │ ├── matching/ │ │ │ │ └── README.md │ │ │ ├── mix_card_ocr/ │ │ │ │ └── README.md │ │ │ ├── object_recognize/ │ │ │ │ └── README.md │ │ │ ├── plant_recognize/ │ │ │ │ └── README.md │ │ │ ├── ppt_generation_from_file/ │ │ │ │ └── README.md │ │ │ ├── ppt_generation_from_instruction/ │ │ │ │ └── README.md │ │ │ ├── ppt_generation_from_paper/ │ │ │ │ └── README.md │ │ │ ├── qrcode_ocr/ │ │ │ │ └── README.md │ │ │ ├── rag_with_baidu_search/ │ │ │ │ └── README.md │ │ │ ├── rag_with_baidu_search_pro/ │ │ │ │ └── README.md │ │ │ ├── retriever/ │ │ │ │ ├── README.md │ │ │ │ ├── baidu_vdb/ │ │ │ │ │ └── README.md │ │ │ │ ├── bes/ │ │ │ │ │ └── README.md │ │ │ │ └── reranker/ │ │ │ │ └── README.md │ │ │ ├── table_ocr/ │ │ │ │ └── README.md │ │ │ ├── text_to_image/ │ │ │ │ └── README.md │ │ │ ├── translate/ │ │ │ │ └── README.md │ │ │ ├── tree_mind/ │ │ │ │ └── README.md │ │ │ └── tts/ │ │ │ └── README.md │ │ ├── Deployment/ │ │ │ ├── AgentChainlit.md │ │ │ ├── agentruntime.md │ │ │ ├── cloud.md │ │ │ ├── flask.md │ │ │ └── usersession.md │ │ ├── Model/ │ │ │ └── get_model_list.md │ │ ├── Platform/ │ │ │ ├── Application/ │ │ │ │ ├── appbuilder_client.md │ │ │ │ └── get_app_list.md │ │ │ ├── CustomComponents/ │ │ │ │ ├── component_client.md │ │ │ │ └── components.md │ │ │ └── KnowledgeBase/ │ │ │ └── knowledgebase.md │ │ └── Trace/ │ │ ├── Debug.md │ │ ├── README.md │ │ ├── basic.md │ │ └── phoenix_method.md │ ├── DevelopGuide/ │ │ ├── AdvancedDevelopment/ │ │ │ └── README.md │ │ ├── ChangeLog/ │ │ │ └── changelog.md │ │ ├── EnvironmentalParameters/ │ │ │ └── env.md │ │ ├── ErrorMessage/ │ │ │ └── error_message.md │ │ └── HowToContributeCode/ │ │ └── README.md │ ├── QuickStart/ │ │ ├── CurrentlySupportedProgrammingLanguages/ │ │ │ └── README.md │ │ ├── ExamplesOfIndustrialPracticeApplications/ │ │ │ └── README.md │ │ └── StartFirstAINativeApplication/ │ │ ├── README.md │ │ └── install.md │ ├── README.md │ ├── README_en.md │ ├── README_ja.md │ └── Tools/ │ ├── DocPass/ │ │ └── DocPass.md │ ├── JavaAPI/ │ │ ├── JavaAPI.md │ │ ├── READEME.md │ │ └── java_api_update.sh │ ├── MarkdownSh/ │ │ ├── markdown2rst.py │ │ └── markdown_parse.py │ └── SphinxSh/ │ ├── Makefile │ ├── PythonAPI.md │ ├── READEME.md │ ├── appbuilder.core.rst │ ├── get_components_md.py │ ├── make.bat │ ├── requirements.txt │ ├── source/ │ │ ├── conf.py │ │ └── index.rst │ ├── update_doc.sh │ ├── update_lib.py │ └── update_rst.py ├── go/ │ ├── appbuilder/ │ │ ├── agent_builder.go │ │ ├── agent_builder_data.go │ │ ├── agent_builder_data_test.go │ │ ├── agent_builder_test.go │ │ ├── app_builder_client.go │ │ ├── app_builder_client_data.go │ │ ├── app_builder_client_test.go │ │ ├── component_client.go │ │ ├── component_client_data.go │ │ ├── component_client_test.go │ │ ├── config.go │ │ ├── dataset.go │ │ ├── dataset_data.go │ │ ├── dataset_test.go │ │ ├── go.mod │ │ ├── go.sum │ │ ├── knowledge_base.go │ │ ├── knowledge_base_data.go │ │ ├── knowledge_base_test.go │ │ ├── rag.go │ │ ├── rag_data.go │ │ ├── rag_test.go │ │ └── util.go │ └── run_go_test.sh ├── java/ │ ├── parse_tests_and_coverage.py │ ├── pom.xml │ ├── print_coverage.sh │ └── src/ │ ├── main/ │ │ └── java/ │ │ └── com/ │ │ └── baidubce/ │ │ └── appbuilder/ │ │ ├── base/ │ │ │ ├── component/ │ │ │ │ └── Component.java │ │ │ ├── config/ │ │ │ │ └── AppBuilderConfig.java │ │ │ ├── exception/ │ │ │ │ └── AppBuilderServerException.java │ │ │ └── utils/ │ │ │ ├── http/ │ │ │ │ ├── HttpClient.java │ │ │ │ └── HttpResponse.java │ │ │ ├── iterator/ │ │ │ │ └── StreamIterator.java │ │ │ └── json/ │ │ │ └── JsonUtils.java │ │ ├── console/ │ │ │ ├── agentbuilder/ │ │ │ │ └── AgentBuilder.java │ │ │ ├── aisearch/ │ │ │ │ └── AISearch.java │ │ │ ├── appbuilderclient/ │ │ │ │ ├── App.java │ │ │ │ ├── AppBuilderClient.java │ │ │ │ └── AppList.java │ │ │ ├── componentclient/ │ │ │ │ └── ComponentClient.java │ │ │ ├── dataset/ │ │ │ │ └── Dataset.java │ │ │ ├── knowledgebase/ │ │ │ │ └── Knowledgebase.java │ │ │ └── rag/ │ │ │ └── RAG.java │ │ └── model/ │ │ ├── agentbuilder/ │ │ │ ├── AgentBuilderIterator.java │ │ │ ├── AgentBuilderResponse.java │ │ │ ├── AgentBuilderResult.java │ │ │ ├── ConversationResponse.java │ │ │ ├── Event.java │ │ │ ├── EventContent.java │ │ │ └── FileUploadResponse.java │ │ ├── aisearch/ │ │ │ ├── AISearchIterator.java │ │ │ ├── AISearchRequest.java │ │ │ └── AISearchResponse.java │ │ ├── appbuilderclient/ │ │ │ ├── App.java │ │ │ ├── AppBuilderClientFeedbackRequest.java │ │ │ ├── AppBuilderClientFeedbackResponse.java │ │ │ ├── AppBuilderClientIterator.java │ │ │ ├── AppBuilderClientResponse.java │ │ │ ├── AppBuilderClientResult.java │ │ │ ├── AppBuilderClientRunRequest.java │ │ │ ├── AppDescribeRequest.java │ │ │ ├── AppDescribeResponse.java │ │ │ ├── AppListRequest.java │ │ │ ├── AppListResponse.java │ │ │ ├── AppsDescribeRequest.java │ │ │ ├── AppsDescribeResponse.java │ │ │ ├── ConversationResponse.java │ │ │ ├── Event.java │ │ │ ├── EventContent.java │ │ │ ├── FileUploadResponse.java │ │ │ └── ToolCall.java │ │ ├── componentclient/ │ │ │ ├── ComponentClientIterator.java │ │ │ ├── ComponentClientRunRequest.java │ │ │ └── ComponentClientRunResponse.java │ │ ├── dataset/ │ │ │ ├── DatasetCreateResponse.java │ │ │ ├── DatasetCreateResult.java │ │ │ ├── DocumentAddResponse.java │ │ │ ├── DocumentAddResult.java │ │ │ ├── DocumentDeleteResponse.java │ │ │ ├── DocumentListData.java │ │ │ ├── DocumentListResponse.java │ │ │ ├── DocumentListResult.java │ │ │ ├── FileUploadResponse.java │ │ │ └── FileUploadResult.java │ │ ├── knowledgebase/ │ │ │ ├── ChunkCreateRequest.java │ │ │ ├── ChunkCreateResponse.java │ │ │ ├── ChunkDeleteRequest.java │ │ │ ├── ChunkDescribeRequest.java │ │ │ ├── ChunkDescribeResponse.java │ │ │ ├── ChunkModifyRequest.java │ │ │ ├── ChunksDescribeRequest.java │ │ │ ├── ChunksDescribeResponse.java │ │ │ ├── Document.java │ │ │ ├── DocumentAddRequest.java │ │ │ ├── DocumentAddResponse.java │ │ │ ├── DocumentDeleteRequest.java │ │ │ ├── DocumentDeleteResponse.java │ │ │ ├── DocumentDescribeResponse.java │ │ │ ├── DocumentListRequest.java │ │ │ ├── DocumentListResponse.java │ │ │ ├── DocumentsCreateRequest.java │ │ │ ├── DocumentsCreateResponse.java │ │ │ ├── DocumentsDescribeRequest.java │ │ │ ├── DocumentsDescribeResponse.java │ │ │ ├── DocumentsUploadResponse.java │ │ │ ├── FileUploadResponse.java │ │ │ ├── KnowledgeBaseConfig.java │ │ │ ├── KnowledgeBaseDetail.java │ │ │ ├── KnowledgeBaseDetailRequest.java │ │ │ ├── KnowledgeBaseListRequest.java │ │ │ ├── KnowledgeBaseListResponse.java │ │ │ ├── KnowledgeBaseModifyRequest.java │ │ │ ├── QueryKnowledgeBaseRequest.java │ │ │ └── QueryKnowledgeBaseResponse.java │ │ └── rag/ │ │ ├── EventContent.java │ │ ├── RAGIterator.java │ │ ├── RAGResponse.java │ │ └── RAGResult.java │ └── test/ │ └── java/ │ └── com/ │ └── baidubce/ │ └── appbuilder/ │ ├── AISearchTest.java │ ├── AgentBuilderTest.java │ ├── AppBuilderClientTest.java │ ├── ComponentClientTest.java │ ├── DatasetTest.java │ ├── KnowledgebaseTest.java │ ├── RAGTest.java │ ├── base/ │ │ ├── exception/ │ │ │ └── AppBuilderServerExceptionTest.java │ │ └── utils/ │ │ └── json/ │ │ └── JsonUtilsTest.java │ ├── files/ │ │ ├── query_knowledgebase.json │ │ └── toolcall.json │ └── model/ │ ├── agentbuilder/ │ │ ├── AgentBuilderResponseTest.java │ │ ├── AgentBuilderResultTest.java │ │ ├── ConversationResponseTest.java │ │ ├── EventContentTest.java │ │ ├── EventTest.java │ │ └── FileUploadResponseTest.java │ ├── appbuilderclient/ │ │ ├── AppBuilderClientResponseTest.java │ │ ├── AppBuilderClientRunRequestTest.java │ │ ├── AppListRequestTest.java │ │ ├── AppListResponseTest.java │ │ ├── AppTest.java │ │ ├── ConversationResponseTest.java │ │ ├── EventContentTest.java │ │ ├── EventTest.java │ │ ├── FileUploadResponseTest.java │ │ └── ToolCallTest.java │ ├── dataset/ │ │ ├── DatasetCreateResultTest.java │ │ ├── DocumentAddResultTest.java │ │ ├── DocumentListDataTest.java │ │ ├── DocumentListResponseTest.java │ │ ├── DocumentListResultTest.java │ │ ├── FileUploadResponseTest.java │ │ ├── FileUploadResultTest.java │ │ └── ResponseTest.java │ ├── knowledgebase/ │ │ ├── ChunkCreateRequestTest.java │ │ ├── ChunkCreateResponseTest.java │ │ ├── ChunkDeleteRequestTest.java │ │ ├── ChunkDescribeRequestTest.java │ │ ├── ChunkDescribeResponseTest.java │ │ ├── ChunkModifyRequestTest.java │ │ ├── ChunksDescribeRequestTest.java │ │ ├── ChunksDescribeResponseTest.java │ │ ├── DocumentAddRequestTest.java │ │ ├── DocumentDeleteRequestTest.java │ │ ├── DocumentDeleteResponseTest.java │ │ ├── DocumentListRequestTest.java │ │ ├── DocumentListResponseTest.java │ │ ├── DocumentTest.java │ │ ├── DocumentsCreateRequestTest.java │ │ ├── FileUploadResponseTest.java │ │ ├── KnowledgeBaseConfigTest.java │ │ ├── KnowledgeBaseDetailRequestTest.java │ │ ├── KnowledgeBaseDetailTest.java │ │ ├── KnowledgeBaseListRequestTest.java │ │ ├── KnowledgeBaseListResponseTest.java │ │ └── KnowledgeBaseModifyRequestTest.java │ └── rag/ │ ├── EventContentTest.java │ ├── RAGResponseTest.java │ └── RAGResultTest.java ├── mkdocs.yml ├── python/ │ ├── __init__.py │ ├── core/ │ │ ├── __init__.py │ │ ├── _client.py │ │ ├── _exception.py │ │ ├── _session.py │ │ ├── agent.py │ │ ├── assistant/ │ │ │ ├── __init__.py │ │ │ ├── assistants/ │ │ │ │ ├── __init__.py │ │ │ │ ├── assistants.py │ │ │ │ └── files.py │ │ │ ├── base.py │ │ │ ├── threads/ │ │ │ │ ├── __init__.py │ │ │ │ ├── messages/ │ │ │ │ │ ├── __init__.py │ │ │ │ │ └── messages.py │ │ │ │ ├── runs/ │ │ │ │ │ ├── __init__.py │ │ │ │ │ ├── runs.py │ │ │ │ │ ├── steps.py │ │ │ │ │ └── stream_helper.py │ │ │ │ └── threads.py │ │ │ └── type/ │ │ │ ├── __init__.py │ │ │ ├── assistant_type.py │ │ │ ├── public_type.py │ │ │ └── thread_type.py │ │ ├── component.py │ │ ├── components/ │ │ │ ├── __init__.py │ │ │ ├── animal_recognize/ │ │ │ │ ├── README.md │ │ │ │ ├── __init__.py │ │ │ │ ├── component.py │ │ │ │ └── model.py │ │ │ ├── asr/ │ │ │ │ ├── README.md │ │ │ │ ├── __init__.py │ │ │ │ ├── component.py │ │ │ │ └── model.py │ │ │ ├── dish_recognize/ │ │ │ │ ├── README.md │ │ │ │ ├── __init__.py │ │ │ │ ├── component.py │ │ │ │ └── model.py │ │ │ ├── doc_crop_enhance/ │ │ │ │ ├── README.md │ │ │ │ ├── __init__.py │ │ │ │ ├── component.py │ │ │ │ └── model.py │ │ │ ├── doc_format_converter/ │ │ │ │ ├── README.md │ │ │ │ ├── __init__.py │ │ │ │ ├── component.py │ │ │ │ └── model.py │ │ │ ├── doc_parser/ │ │ │ │ ├── README.md │ │ │ │ ├── __init__.py │ │ │ │ ├── base.py │ │ │ │ └── component.py │ │ │ ├── doc_splitter/ │ │ │ │ ├── README.md │ │ │ │ ├── __init__.py │ │ │ │ └── component.py │ │ │ ├── document_understanding/ │ │ │ │ ├── README.md │ │ │ │ ├── __init__.py │ │ │ │ ├── base.py │ │ │ │ └── component.py │ │ │ ├── embeddings/ │ │ │ │ ├── README.md │ │ │ │ ├── __init__.py │ │ │ │ ├── base.py │ │ │ │ └── component.py │ │ │ ├── extract_table/ │ │ │ │ ├── README.md │ │ │ │ ├── __init__.py │ │ │ │ └── component.py │ │ │ ├── gbi/ │ │ │ │ ├── __init__.py │ │ │ │ ├── basic.py │ │ │ │ ├── nl2sql/ │ │ │ │ │ ├── README.md │ │ │ │ │ ├── __init__.py │ │ │ │ │ ├── base.py │ │ │ │ │ └── component.py │ │ │ │ └── select_table/ │ │ │ │ ├── README.md │ │ │ │ ├── __init__.py │ │ │ │ ├── base.py │ │ │ │ └── component.py │ │ │ ├── general_ocr/ │ │ │ │ ├── README.md │ │ │ │ ├── __init__.py │ │ │ │ ├── component.py │ │ │ │ └── model.py │ │ │ ├── handwrite_ocr/ │ │ │ │ ├── README.md │ │ │ │ ├── __init__.py │ │ │ │ ├── component.py │ │ │ │ └── model.py │ │ │ ├── image_understand/ │ │ │ │ ├── README.md │ │ │ │ ├── __init__.py │ │ │ │ ├── component.py │ │ │ │ └── model.py │ │ │ ├── landmark_recognize/ │ │ │ │ ├── README.md │ │ │ │ ├── __init__.py │ │ │ │ ├── component.py │ │ │ │ └── model.py │ │ │ ├── llms/ │ │ │ │ ├── __init__.py │ │ │ │ ├── base.py │ │ │ │ ├── dialog_summary/ │ │ │ │ │ ├── README.md │ │ │ │ │ ├── __init__.py │ │ │ │ │ ├── base.py │ │ │ │ │ └── component.py │ │ │ │ ├── hallucination_detection/ │ │ │ │ │ ├── README.md │ │ │ │ │ ├── __init__.py │ │ │ │ │ ├── base.py │ │ │ │ │ └── component.py │ │ │ │ ├── is_complex_query/ │ │ │ │ │ ├── README.md │ │ │ │ │ ├── __init__.py │ │ │ │ │ ├── base.py │ │ │ │ │ └── component.py │ │ │ │ ├── mrc/ │ │ │ │ │ ├── README.md │ │ │ │ │ ├── __init__.py │ │ │ │ │ ├── base.py │ │ │ │ │ └── component.py │ │ │ │ ├── nl2pandas/ │ │ │ │ │ ├── README.md │ │ │ │ │ ├── __init__.py │ │ │ │ │ ├── base.py │ │ │ │ │ └── component.py │ │ │ │ ├── oral_query_generation/ │ │ │ │ │ ├── README.md │ │ │ │ │ ├── __init__.py │ │ │ │ │ ├── base.py │ │ │ │ │ └── component.py │ │ │ │ ├── playground/ │ │ │ │ │ ├── README.md │ │ │ │ │ ├── __init__.py │ │ │ │ │ ├── base.py │ │ │ │ │ └── component.py │ │ │ │ ├── qa_pair_mining/ │ │ │ │ │ ├── README.md │ │ │ │ │ ├── __init__.py │ │ │ │ │ ├── base.py │ │ │ │ │ └── component.py │ │ │ │ ├── query_decomposition/ │ │ │ │ │ ├── README.md │ │ │ │ │ ├── __init__.py │ │ │ │ │ ├── base.py │ │ │ │ │ └── component.py │ │ │ │ ├── query_rewrite/ │ │ │ │ │ ├── README.md │ │ │ │ │ ├── __init__.py │ │ │ │ │ ├── base.py │ │ │ │ │ └── component.py │ │ │ │ ├── similar_question/ │ │ │ │ │ ├── README.md │ │ │ │ │ ├── __init__.py │ │ │ │ │ ├── base.py │ │ │ │ │ └── component.py │ │ │ │ ├── style_rewrite/ │ │ │ │ │ ├── README.md │ │ │ │ │ ├── __init__.py │ │ │ │ │ ├── base.py │ │ │ │ │ └── component.py │ │ │ │ ├── style_writing/ │ │ │ │ │ ├── README.md │ │ │ │ │ ├── __init__.py │ │ │ │ │ ├── base.py │ │ │ │ │ └── component.py │ │ │ │ └── tag_extraction/ │ │ │ │ ├── README.md │ │ │ │ ├── __init__.py │ │ │ │ ├── base.py │ │ │ │ └── component.py │ │ │ ├── matching/ │ │ │ │ ├── README.md │ │ │ │ ├── __init__.py │ │ │ │ ├── base.py │ │ │ │ └── component.py │ │ │ ├── mix_card_ocr/ │ │ │ │ ├── README.md │ │ │ │ ├── __init__.py │ │ │ │ ├── component.py │ │ │ │ └── model.py │ │ │ ├── object_recognize/ │ │ │ │ ├── README.md │ │ │ │ ├── __init__.py │ │ │ │ ├── component.py │ │ │ │ └── model.py │ │ │ ├── plant_recognize/ │ │ │ │ ├── README.md │ │ │ │ ├── __init__.py │ │ │ │ ├── component.py │ │ │ │ └── model.py │ │ │ ├── ppt_generation_from_file/ │ │ │ │ ├── README.md │ │ │ │ ├── __init__.py │ │ │ │ ├── base.py │ │ │ │ └── component.py │ │ │ ├── ppt_generation_from_instruction/ │ │ │ │ ├── README.md │ │ │ │ ├── __init__.py │ │ │ │ ├── base.py │ │ │ │ └── component.py │ │ │ ├── ppt_generation_from_paper/ │ │ │ │ ├── README.md │ │ │ │ ├── __init__.py │ │ │ │ ├── base.py │ │ │ │ └── component.py │ │ │ ├── qrcode_ocr/ │ │ │ │ ├── README.md │ │ │ │ ├── __init__.py │ │ │ │ ├── component.py │ │ │ │ └── model.py │ │ │ ├── rag_with_baidu_search/ │ │ │ │ ├── README.md │ │ │ │ ├── __init__.py │ │ │ │ ├── component.py │ │ │ │ └── model.py │ │ │ ├── rag_with_baidu_search_pro/ │ │ │ │ ├── README.md │ │ │ │ ├── __init__.py │ │ │ │ ├── component.py │ │ │ │ └── model.py │ │ │ ├── retriever/ │ │ │ │ ├── README.md │ │ │ │ ├── __init__.py │ │ │ │ ├── baidu_vdb/ │ │ │ │ │ ├── README.md │ │ │ │ │ ├── __init__.py │ │ │ │ │ ├── component.py │ │ │ │ │ └── model.py │ │ │ │ ├── bes/ │ │ │ │ │ ├── README.md │ │ │ │ │ ├── __init__.py │ │ │ │ │ └── component.py │ │ │ │ └── reranker/ │ │ │ │ ├── README.md │ │ │ │ ├── __init__.py │ │ │ │ ├── component.py │ │ │ │ └── model.py │ │ │ ├── table_ocr/ │ │ │ │ ├── README.md │ │ │ │ ├── __init__.py │ │ │ │ ├── component.py │ │ │ │ └── model.py │ │ │ ├── text_to_image/ │ │ │ │ ├── README.md │ │ │ │ ├── __init__.py │ │ │ │ ├── component.py │ │ │ │ └── model.py │ │ │ ├── translate/ │ │ │ │ ├── README.md │ │ │ │ ├── __init__.py │ │ │ │ ├── component.py │ │ │ │ └── model.py │ │ │ ├── tree_mind/ │ │ │ │ ├── README.md │ │ │ │ ├── __init__.py │ │ │ │ ├── component.py │ │ │ │ └── model.py │ │ │ ├── tts/ │ │ │ │ ├── README.md │ │ │ │ ├── __init__.py │ │ │ │ ├── component.py │ │ │ │ └── model.py │ │ │ └── v2/ │ │ │ ├── __init__.py │ │ │ ├── animal_recognize/ │ │ │ │ ├── __init__.py │ │ │ │ └── component.py │ │ │ ├── asr/ │ │ │ │ ├── __init__.py │ │ │ │ └── component.py │ │ │ ├── general_ocr/ │ │ │ │ ├── __init__.py │ │ │ │ └── component.py │ │ │ ├── handwrite_ocr/ │ │ │ │ ├── __init__.py │ │ │ │ ├── component.py │ │ │ │ └── model.py │ │ │ ├── image_understand/ │ │ │ │ ├── __init__.py │ │ │ │ └── component.py │ │ │ ├── llms/ │ │ │ │ ├── __init__.py │ │ │ │ ├── dialog_summary/ │ │ │ │ │ ├── __init__.py │ │ │ │ │ └── component.py │ │ │ │ ├── hallucination_detection/ │ │ │ │ │ ├── __init__.py │ │ │ │ │ └── component.py │ │ │ │ ├── is_complex_query/ │ │ │ │ │ ├── __init__.py │ │ │ │ │ └── component.py │ │ │ │ ├── mrc/ │ │ │ │ │ ├── __init__.py │ │ │ │ │ └── component.py │ │ │ │ ├── nl2pandas/ │ │ │ │ │ ├── __init__.py │ │ │ │ │ └── component.py │ │ │ │ ├── oral_query_generation/ │ │ │ │ │ ├── __init__.py │ │ │ │ │ └── component.py │ │ │ │ ├── qa_pair_mining/ │ │ │ │ │ ├── __init__.py │ │ │ │ │ └── component.py │ │ │ │ ├── query_decomposition/ │ │ │ │ │ ├── __init__.py │ │ │ │ │ └── component.py │ │ │ │ ├── query_rewrite/ │ │ │ │ │ ├── __init__.py │ │ │ │ │ └── component.py │ │ │ │ ├── similar_question/ │ │ │ │ │ ├── __init__.py │ │ │ │ │ └── component.py │ │ │ │ ├── style_rewrite/ │ │ │ │ │ ├── __init__.py │ │ │ │ │ └── component.py │ │ │ │ ├── style_writing/ │ │ │ │ │ ├── __init__.py │ │ │ │ │ └── component.py │ │ │ │ └── tag_extraction/ │ │ │ │ ├── __init__.py │ │ │ │ └── component.py │ │ │ ├── mix_card_ocr/ │ │ │ │ ├── __init__.py │ │ │ │ ├── component.py │ │ │ │ └── model.py │ │ │ ├── object_recognize/ │ │ │ │ ├── __init__.py │ │ │ │ └── component.py │ │ │ ├── plant_recognize/ │ │ │ │ ├── __init__.py │ │ │ │ └── component.py │ │ │ ├── qrcode_ocr/ │ │ │ │ ├── __init__.py │ │ │ │ ├── component.py │ │ │ │ └── model.py │ │ │ ├── table_ocr/ │ │ │ │ ├── __init__.py │ │ │ │ └── component.py │ │ │ ├── text_to_image/ │ │ │ │ ├── __init__.py │ │ │ │ └── component.py │ │ │ ├── translate/ │ │ │ │ ├── __init__.py │ │ │ │ └── component.py │ │ │ └── tree_mind/ │ │ │ ├── __init__.py │ │ │ ├── component.py │ │ │ └── model.py │ │ ├── console/ │ │ │ ├── __init__.py │ │ │ ├── ai_search/ │ │ │ │ ├── __init__.py │ │ │ │ ├── ai_search.py │ │ │ │ └── data_class.py │ │ │ ├── appbuilder_client/ │ │ │ │ ├── __init__.py │ │ │ │ ├── appbuilder_client.py │ │ │ │ ├── async_appbuilder_client.py │ │ │ │ ├── async_event_handler.py │ │ │ │ ├── data_class.py │ │ │ │ └── event_handler.py │ │ │ ├── base.py │ │ │ ├── component_client/ │ │ │ │ ├── __init__.py │ │ │ │ ├── component_client.py │ │ │ │ └── data_class.py │ │ │ ├── dataset/ │ │ │ │ ├── __init__.py │ │ │ │ ├── dataset.py │ │ │ │ └── model.py │ │ │ ├── knowledge_base/ │ │ │ │ ├── __init__.py │ │ │ │ ├── data_class.py │ │ │ │ └── knowledge_base.py │ │ │ └── rag/ │ │ │ ├── __init__.py │ │ │ └── rag.py │ │ ├── constants.py │ │ ├── context.py │ │ ├── functional.py │ │ ├── manifest/ │ │ │ ├── __init__.py │ │ │ ├── manifest_decorator.py │ │ │ ├── manifest_signature.py │ │ │ └── models.py │ │ ├── message.py │ │ ├── session_message.py │ │ ├── user_session.py │ │ └── utils.py │ ├── mcp_server/ │ │ ├── README.md │ │ ├── __init__.py │ │ ├── ai_search/ │ │ │ ├── README.md │ │ │ ├── __init__.py │ │ │ └── ai_search_server.py │ │ ├── app/ │ │ │ ├── README.md │ │ │ ├── __init__.py │ │ │ └── app_server.py │ │ ├── client.py │ │ ├── http_client.py │ │ ├── knowledge_base/ │ │ │ ├── README.md │ │ │ ├── __init__.py │ │ │ └── knowledge_base_server.py │ │ ├── openapi.py │ │ ├── server.py │ │ └── sse.py │ ├── tests/ │ │ ├── __init__.py │ │ ├── component_check.py │ │ ├── component_collector.py │ │ ├── component_schemas.py │ │ ├── component_tool_eval_cases.py │ │ ├── data/ │ │ │ ├── ghes-3.0.json │ │ │ ├── ghes-3.0.yaml │ │ │ ├── mcp_component_server_sample.py │ │ │ ├── mcp_knowledge_base_case.txt │ │ │ ├── mcp_official_server_sample.py │ │ │ └── qa_demo.xlsx │ │ ├── parallel_ut_run.py │ │ ├── print_components_error_info.py │ │ ├── pytest_config.py │ │ ├── pytest_utils.py │ │ ├── run_python_test.sh │ │ ├── sed_str.py │ │ ├── test_agent.py │ │ ├── test_ai_search.py │ │ ├── test_ai_search_stream.py │ │ ├── test_all_components.py │ │ ├── test_animal_recognize.py │ │ ├── test_appbuilder_assistant_trace.py │ │ ├── test_appbuilder_client.py │ │ ├── test_appbuilder_client_app_detail.py │ │ ├── test_appbuilder_client_app_list.py │ │ ├── test_appbuilder_client_chatflow.py │ │ ├── test_appbuilder_client_chatflow_event_handler.py │ │ ├── test_appbuilder_client_chatflow_event_handler_v2.py │ │ ├── test_appbuilder_client_custom_metadata.py │ │ ├── test_appbuilder_client_feedback.py │ │ ├── test_appbuilder_client_follow_up_query.py │ │ ├── test_appbuilder_client_mcp.py │ │ ├── test_appbuilder_client_mcp_component.py │ │ ├── test_appbuilder_client_mcp_official.py │ │ ├── test_appbuilder_client_parameters.py │ │ ├── test_appbuilder_client_run_with_handler.py │ │ ├── test_appbuilder_client_toolcall.py │ │ ├── test_appbuilder_client_toolcall_event_handler.py │ │ ├── test_appbuilder_client_toolcall_event_handler_error.py │ │ ├── test_appbuilder_client_toolcall_event_handler_stream.py │ │ ├── test_appbuilder_client_toolcall_event_handler_v2.py │ │ ├── test_appbuilder_client_toolcall_event_handler_v3.py │ │ ├── test_appbuilder_client_toolcall_stream.py │ │ ├── test_appbuilder_client_toolcall_v2.py │ │ ├── test_appbuilder_client_toolcall_v3.py │ │ ├── test_appbuilder_client_trace.py │ │ ├── test_appbuilder_components_trace.py │ │ ├── test_appbuilder_core_components_retriever.py │ │ ├── test_appbuilder_sentry_trace_off.py │ │ ├── test_appbuilder_sentry_trace_on.py │ │ ├── test_appbuilder_trace_raise_error.py │ │ ├── test_asr.py │ │ ├── test_assistant_basic_import.py │ │ ├── test_assistant_class_assistans.py │ │ ├── test_assistant_class_files.py │ │ ├── test_assistant_class_messages.py │ │ ├── test_assistant_class_runs.py │ │ ├── test_assistant_class_runs_v2.py │ │ ├── test_assistant_class_threads.py │ │ ├── test_assistant_e2e_funccall.py │ │ ├── test_assistant_e2e_funccall_component.py │ │ ├── test_assistant_e2e_run.py │ │ ├── test_assistant_e2e_stream_cancel.py │ │ ├── test_assistant_e2e_stream_event_handler.py │ │ ├── test_assistant_e2e_stream_event_handler_v2.py │ │ ├── test_assistant_e2e_stream_funccall.py │ │ ├── test_assistant_e2e_stream_run.py │ │ ├── test_async_appbuilder_client.py │ │ ├── test_async_appbuilder_client_chatflow.py │ │ ├── test_async_appbuilder_client_custom_metadata.py │ │ ├── test_async_appbuilder_client_follow_up_query.py │ │ ├── test_async_appbuilder_client_parameters.py │ │ ├── test_async_appbuilder_client_toolcall.py │ │ ├── test_base_component.py │ │ ├── test_bes_retriever.py │ │ ├── test_component_client.py │ │ ├── test_component_is_async.py │ │ ├── test_console_dataset.py │ │ ├── test_console_rag.py │ │ ├── test_core_agent.py │ │ ├── test_core_client.py │ │ ├── test_core_components_baidu_vdb_retriever.py │ │ ├── test_core_components_doc.py │ │ ├── test_core_components_embedding.py │ │ ├── test_core_components_table.py │ │ ├── test_core_components_tts.py │ │ ├── test_core_console_base.py │ │ ├── test_core_session.py │ │ ├── test_core_user_session.py │ │ ├── test_core_utils.py │ │ ├── test_dialog_summary.py │ │ ├── test_dish_recognize.py │ │ ├── test_doc_crop_enhance.py │ │ ├── test_doc_format_converter.py │ │ ├── test_doc_parser.py │ │ ├── test_doc_splitter.py │ │ ├── test_document_understanding.py │ │ ├── test_embedding.py │ │ ├── test_extract_table.py │ │ ├── test_gbi_nl2sql.py │ │ ├── test_gbi_select_table.py │ │ ├── test_general_ocr.py │ │ ├── test_get_app_list.py │ │ ├── test_get_model_list.py │ │ ├── test_hallucination_detection.py │ │ ├── test_handwrite_ocr.py │ │ ├── test_image_understand.py │ │ ├── test_is_complex_query.py │ │ ├── test_knowledge_base.py │ │ ├── test_landmark_recognize.py │ │ ├── test_langchain_adapter_run.py │ │ ├── test_langchain_adapter_tool_eval.py │ │ ├── test_langchain_error.py │ │ ├── test_llm_base.py │ │ ├── test_log_set_log_config.py │ │ ├── test_manifest.py │ │ ├── test_manifest_decorator.py │ │ ├── test_manifest_signature.py │ │ ├── test_matching.py │ │ ├── test_mcp_ai_search_stdio.py │ │ ├── test_mcp_app_server_stdio.py │ │ ├── test_mcp_rag_stdio.py │ │ ├── test_message.py │ │ ├── test_mix_card_ocr.py │ │ ├── test_mrc.py │ │ ├── test_nl2pandas.py │ │ ├── test_object_recognize.py │ │ ├── test_openapi_convert.py │ │ ├── test_oral_query_generation.py │ │ ├── test_plant_recognize.py │ │ ├── test_playground.py │ │ ├── test_ppt_generation_from_file.py │ │ ├── test_ppt_generation_from_instruction.py │ │ ├── test_ppt_generation_from_paper.py │ │ ├── test_private_llm_component.py │ │ ├── test_qa_aicape_animal_rec.py │ │ ├── test_qa_aicape_doc_crop_enhance.py │ │ ├── test_qa_aicape_handwriting_ocr.py │ │ ├── test_qa_aicape_image_understand.py │ │ ├── test_qa_aicape_mixcard_ocr.py │ │ ├── test_qa_aicape_plant_rec.py │ │ ├── test_qa_aicape_qrcode_orc.py │ │ ├── test_qa_aicape_table_ocr.py │ │ ├── test_qa_doc_parser_extract_table_from_doc.py │ │ ├── test_qa_llm_dialog_summary.py │ │ ├── test_qa_llm_get_qianfan_model_list.py │ │ ├── test_qa_llm_is_complex_query.py │ │ ├── test_qa_llm_matching.py │ │ ├── test_qa_llm_oral_query_generation.py │ │ ├── test_qa_llm_paddle_speech_tts.py │ │ ├── test_qa_llm_pandas.py │ │ ├── test_qa_llm_query_decomposition.py │ │ ├── test_qa_llm_style_rewrite.py │ │ ├── test_qa_pair_mining.py │ │ ├── test_qrcode_ocr.py │ │ ├── test_query_decomposition.py │ │ ├── test_query_rewrite.py │ │ ├── test_rag_baidu_search.py │ │ ├── test_rag_baidu_search_pro.py │ │ ├── test_rerank.py │ │ ├── test_similar_question.py │ │ ├── test_style_rewrite.py │ │ ├── test_style_writing.py │ │ ├── test_table_ocr.py │ │ ├── test_tag_extraction.py │ │ ├── test_text_to_image.py │ │ ├── test_trace.py │ │ ├── test_trace_skip_raise_error.py │ │ ├── test_translate.py │ │ ├── test_treemind.py │ │ ├── test_tts.py │ │ ├── test_utils.py │ │ ├── test_utils_collector.py │ │ ├── test_utils_logger.py │ │ ├── test_utils_logging_util.py │ │ ├── test_v2_animal_recognize.py │ │ ├── test_v2_asr.py │ │ ├── test_v2_component_trace.py │ │ ├── test_v2_dialog_summary.py │ │ ├── test_v2_general_ocr.py │ │ ├── test_v2_hallucination_detection.py │ │ ├── test_v2_handwrite_ocr.py │ │ ├── test_v2_image_understand.py │ │ ├── test_v2_is_complex_query.py │ │ ├── test_v2_mix_card_ocr.py │ │ ├── test_v2_mrc.py │ │ ├── test_v2_nl2pandas.py │ │ ├── test_v2_object_recognition.py │ │ ├── test_v2_oral_query_generat.py │ │ ├── test_v2_plant_recognize.py │ │ ├── test_v2_qa_pair_mining.py │ │ ├── test_v2_qrcode_ocr.py │ │ ├── test_v2_query_decomposition.py │ │ ├── test_v2_query_rewrite.py │ │ ├── test_v2_similar_question.py │ │ ├── test_v2_style_rewrite.py │ │ ├── test_v2_style_writing.py │ │ ├── test_v2_table_ocr.py │ │ ├── test_v2_tag_extraction.py │ │ ├── test_v2_text_to_image.py │ │ ├── test_v2_translate.py │ │ ├── test_v2_treemind.py │ │ ├── test_vdb_retriever.py │ │ └── title_splitter.docx │ └── utils/ │ ├── __init__.py │ ├── _bcc.py │ ├── bce_deploy.py │ ├── chainlit.md │ ├── collector.py │ ├── func_utils.py │ ├── json_schema_to_model.py │ ├── logger_file_headler.py │ ├── logger_util.py │ ├── model_util.py │ ├── sse_util.py │ └── trace/ │ ├── __init__.py │ ├── _function.py │ ├── phoenix_wrapper.py │ ├── tracer.py │ └── tracer_wrapper.py ├── requirements.txt └── setup.py ================================================ FILE CONTENTS ================================================ ================================================ FILE: .env_template ================================================ # rename this file to .env APPBUILDER_TOKEN=your-token APPBUILDER_TOKEN_V2=your-token BAIDU_VDB_API_KEY=your-token INSTANCE_ID=your-token DATASET_ID=your-token APPBUILDER_TOKEN_DOC_FORMAT=your-token ================================================ FILE: .github/workflows/python-package.yml ================================================ # This workflow will install Python dependencies, run tests and lint with a variety of Python versions # For more information see: https://docs.github.com/en/actions/automating-builds-and-tests/building-and-testing-python name: Python package on: workflow_dispatch: push: branches: [ "master" ] pull_request: branches: [ "master" ] jobs: Pylint: runs-on: ubuntu-latest strategy: fail-fast: false matrix: python-version: ["3.12.5"] steps: - uses: actions/checkout@v3 - name: Set up Python ${{ matrix.python-version }} uses: actions/setup-python@v3 with: python-version: ${{ matrix.python-version }} - name: Install dependencies run: | python -m pip install --upgrade pip python -m pip install flake8 pytest python -m pip install chainlit~=1.0.200 flask~=2.3.2 flask-restful==0.3.9 if [ -f requirements.txt ]; then pip install -r requirements.txt; fi - name: Lint with flake8 run: | # stop the build if there are Python syntax errors or undefined names flake8 . --count --select=E9,F63,F7,F82 --show-source --statistics # exit-zero treats all errors as warnings. The GitHub editor is 127 chars wide flake8 . --count --exit-zero --max-complexity=10 --max-line-length=127 --statistics Python312-CI-Tests: runs-on: ubuntu-latest env: APPBUILDER_TOKEN: ${{ secrets.APPBUILDER_TOKEN }} APPBUILDER_TOKEN_V2: ${{ secrets.APPBUILDER_TOKEN_V2 }} BAIDU_VDB_API_KEY: ${{ secrets.BAIDU_VDB_API_KEY }} INSTANCE_ID: ${{ secrets.INSTANCE_ID }} DATASET_ID: ${{ secrets.DATASET_ID }} APPBUILDER_TOKEN_DOC_FORMAT: ${{ secrets.APPBUILDER_TOKEN_DOC_FORMAT }} strategy: fail-fast: false matrix: python-version: ["3.12"] steps: - uses: actions/checkout@v4 with: ref: ${{ github.event.pull_request.head.sha }} - name: Set up Python ${{ matrix.python-version }} uses: actions/setup-python@v3 with: python-version: ${{ matrix.python-version }} - name: Print ENV run: | env ls pwd - name: Git Clone And Checkout Branch run: | fork_repo="https://github.com/$GITHUB_ACTOR/app-builder.git" mkdir cicd cd cicd git clone $fork_repo cd app-builder git checkout $GITHUB_HEAD_REF git remote add upstream https://github.com/baidubce/app-builder.git git fetch upstream git remote -v git status # 找到当前分支与 upstream/master 的共同祖先提交 merge_base=$(git merge-base HEAD upstream/master) echo "merge_base=$merge_base" # 比较当前分支与 merge_base 之间的差异 changed_files=$(git diff --name-only --diff-filter=ACMRT $merge_base) changed_files_py_sh=$(git diff --name-only --diff-filter=ACMRT $merge_base -- $(find python -type f \( -name '*.py' -o -name '*.sh' \))) echo "发生更改的文件为:" echo "$changed_files" echo "发生更改的py/sh文件为:" if [ -n "$changed_files_py_sh" ]; then export APPBUILDER_PYTHON_TESTS=True echo "$changed_files_py_sh" else export APPBUILDER_PYTHON_TESTS=False echo "没有检测到Python或Shell文件被更改" fi echo "APPBUILDER_PYTHON_TESTS=$APPBUILDER_PYTHON_TESTS" >> $GITHUB_ENV pwd - name: Install dependencies run: | echo $APPBUILDER_PYTHON_TESTS if [ "$APPBUILDER_PYTHON_TESTS" = "False" ]; then echo "环境变量APPBUILDER_PYTHON_TESTS为False,没有检测到Python或Shell文件被更改,跳过Install dependencies部分。" else echo "检测到Python或Shell文件被更改(根据环境变量APPBUILDER_PYTHON_TESTS),准备启动单元测试Install dependencies部分..." cd cicd/app-builder pwd sudo apt-get update sudo apt-get install ffmpeg libavcodec-extra python3 -m ensurepip --upgrade python3 -m pip install --upgrade pip python3 -m pip install "setuptools<=76.1.0" python3 -m pip install wheel python3 -m pip install coverage python3 -m pip install diff-cover python3 -m pip install pydub python3 -m pip install SQLAlchemy==2.0.31 python3 -m pip install chainlit~=1.0.200 flask~=2.3.2 flask-restful==0.3.9 python3 -m pip install opentelemetry-exporter-otlp==1.23.0 opentelemetry-instrumentation==0.44b0 opentelemetry-sdk==1.23.0 opentelemetry-api==1.23.0 python3 -m pip install pandas==2.2.2 python3 -m pip install mcp ; true fi - name: Build whl run: | echo $APPBUILDER_PYTHON_TESTS if [ "$APPBUILDER_PYTHON_TESTS" = "False" ]; then echo "环境变量APPBUILDER_PYTHON_TESTS为False,没有检测到Python或Shell文件被更改,跳过Build whl部分。" else echo "检测到Python或Shell文件被更改(根据环境变量APPBUILDER_PYTHON_TESTS),准备启动单元测试Build whl部分..." cd cicd/app-builder pwd python3 setup.py bdist_wheel python3 -m pip uninstall -y appbuilder-sdk python3 -m pip install dist/*.whl fi - name: Test with unittest run: | echo $APPBUILDER_PYTHON_TESTS if [ "$APPBUILDER_PYTHON_TESTS" = "False" ]; then echo "环境变量APPBUILDER_PYTHON_TESTS为False,没有检测到Python或Shell文件被更改,跳过Test with unittest部分。" else echo "检测到Python或Shell文件被更改(根据环境变量APPBUILDER_PYTHON_TESTS),准备启动单元测试Test with unittest部分..." cd cicd/app-builder pwd sh python/tests/run_python_test.sh fi Python39-CI-Tests: runs-on: ubuntu-latest env: APPBUILDER_TOKEN: ${{ secrets.APPBUILDER_TOKEN }} APPBUILDER_TOKEN_V2: ${{ secrets.APPBUILDER_TOKEN_V2 }} BAIDU_VDB_API_KEY: ${{ secrets.BAIDU_VDB_API_KEY }} INSTANCE_ID: ${{ secrets.INSTANCE_ID }} DATASET_ID: ${{ secrets.DATASET_ID }} APPBUILDER_TOKEN_DOC_FORMAT: ${{ secrets.APPBUILDER_TOKEN_DOC_FORMAT }} strategy: fail-fast: false matrix: python-version: ["3.9"] steps: - uses: actions/checkout@v4 with: ref: ${{ github.event.pull_request.head.sha }} - name: Set up Python ${{ matrix.python-version }} uses: actions/setup-python@v3 with: python-version: ${{ matrix.python-version }} - name: Print ENV run: | env ls pwd - name: Git Clone And Checkout Branch run: | fork_repo="https://github.com/$GITHUB_ACTOR/app-builder.git" mkdir cicd cd cicd git clone $fork_repo cd app-builder git checkout $GITHUB_HEAD_REF git remote add upstream https://github.com/baidubce/app-builder.git git fetch upstream git remote -v git status # 找到当前分支与 upstream/master 的共同祖先提交 merge_base=$(git merge-base HEAD upstream/master) echo "merge_base=$merge_base" # 比较当前分支与 merge_base 之间的差异 changed_files=$(git diff --name-only --diff-filter=ACMRT $merge_base) changed_files_py_sh=$(git diff --name-only --diff-filter=ACMRT $merge_base -- $(find python -type f \( -name '*.py' -o -name '*.sh' \))) echo "发生更改的文件为:" echo "$changed_files" echo "发生更改的py/sh文件为:" if [ -n "$changed_files_py_sh" ]; then export APPBUILDER_PYTHON_TESTS=True echo "$changed_files_py_sh" else export APPBUILDER_PYTHON_TESTS=False echo "没有检测到Python或Shell文件被更改" fi echo "APPBUILDER_PYTHON_TESTS=$APPBUILDER_PYTHON_TESTS" >> $GITHUB_ENV pwd - name: Install dependencies run: | echo $APPBUILDER_PYTHON_TESTS if [ "$APPBUILDER_PYTHON_TESTS" = "False" ]; then echo "环境变量APPBUILDER_PYTHON_TESTS为False,没有检测到Python或Shell文件被更改,跳过Install dependencies部分。" else echo "检测到Python或Shell文件被更改(根据环境变量APPBUILDER_PYTHON_TESTS),准备启动单元测试Install dependencies部分..." cd cicd/app-builder pwd sudo apt-get update sudo apt-get install ffmpeg libavcodec-extra python3 -m ensurepip --upgrade python3 -m pip install --upgrade pip python3 -m pip install "setuptools<=76.1.0" python3 -m pip install wheel python3 -m pip install coverage python3 -m pip install diff-cover python3 -m pip install pydub python3 -m pip install SQLAlchemy==2.0.31 python3 -m pip install chainlit~=1.0.200 flask~=2.3.2 flask-restful==0.3.9 python3 -m pip install opentelemetry-exporter-otlp==1.23.0 opentelemetry-instrumentation==0.44b0 opentelemetry-sdk==1.23.0 opentelemetry-api==1.23.0 python3 -m pip install pandas==2.2.2 fi - name: Build whl run: | echo $APPBUILDER_PYTHON_TESTS if [ "$APPBUILDER_PYTHON_TESTS" = "False" ]; then echo "环境变量APPBUILDER_PYTHON_TESTS为False,没有检测到Python或Shell文件被更改,跳过Build whl部分。" else echo "检测到Python或Shell文件被更改(根据环境变量APPBUILDER_PYTHON_TESTS),准备启动单元测试Build whl部分..." cd cicd/app-builder pwd python3 setup.py bdist_wheel python3 -m pip uninstall -y appbuilder-sdk python3 -m pip install dist/*.whl fi - name: Test with unittest run: | echo $APPBUILDER_PYTHON_TESTS if [ "$APPBUILDER_PYTHON_TESTS" = "False" ]; then echo "环境变量APPBUILDER_PYTHON_TESTS为False,没有检测到Python或Shell文件被更改,跳过Test with unittest部分。" else echo "检测到Python或Shell文件被更改(根据环境变量APPBUILDER_PYTHON_TESTS),准备启动单元测试Test with unittest部分..." cd cicd/app-builder pwd sh python/tests/run_python_test.sh fi Go-Test-CI: runs-on: ubuntu-latest env: APPBUILDER_TOKEN: ${{ secrets.APPBUILDER_TOKEN }} APPBUILDER_TOKEN_V2: ${{ secrets.APPBUILDER_TOKEN_V2 }} BAIDU_VDB_API_KEY: ${{ secrets.BAIDU_VDB_API_KEY }} INSTANCE_ID: ${{ secrets.INSTANCE_ID }} DATASET_ID: ${{ secrets.DATASET_ID }} APPBUILDER_TOKEN_DOC_FORMAT: ${{ secrets.APPBUILDER_TOKEN_DOC_FORMAT }} APPBUILDER_TOKEN_V3: ${{ secrets.APPBUILDER_TOKEN_V3 }} DATASET_ID_V3: ${{ secrets.DATASET_ID_V3 }} DOCUMENT_ID_V3: ${{ secrets.DOCUMENT_ID_V3 }} strategy: fail-fast: false matrix: go-version: ['1.18'] max-parallel: 2 steps: - name: Checkout code uses: actions/checkout@v3 with: ref: ${{ github.event.pull_request.head.sha }} - name: Set up Go uses: actions/setup-go@v3 with: go-version: ${{ matrix.go-version }} - name: Git Clone And Checkout Branch run: | fork_repo="https://github.com/$GITHUB_ACTOR/app-builder.git" mkdir cicd cd cicd git clone $fork_repo cd app-builder echo "github_head的值为:" echo $GITHUB_HEAD_REF git checkout $GITHUB_HEAD_REF git remote add upstream https://github.com/baidubce/app-builder.git git fetch upstream git remote -v git status # 找到当前分支与 upstream/master 的共同祖先提交 merge_base=$(git merge-base HEAD upstream/master) echo "merge_base=$merge_base" # 比较当前分支与 merge_base 之间的差异 changed_files=$(git diff --name-only --diff-filter=ACMRT $merge_base) changed_files_go=$(git diff --name-only --diff-filter=ACMRT $merge_base -- 'go/**') echo "发生更改的文件为:" echo "$changed_files" echo "发生更改的Go相关文件为:" if [ -n "$changed_files_go" ]; then export APPBUILDER_GO_TESTS=True echo "$changed_files_go" else export APPBUILDER_GO_TESTS=False echo "没有检测到Go或Shell文件被更改" fi echo "APPBUILDER_GO_TESTS=$APPBUILDER_GO_TESTS" >> $GITHUB_ENV - name: Install dependencies and tools run: | echo $APPBUILDER_GO_TESTS if [ "$APPBUILDER_GO_TESTS" = "False" ]; then echo "环境变量APPBUILDER_GO_TESTS为False,没有检测到Go文件被更改,跳过Install dependencies and tools部分。" else echo "检测到Go文件被更改,准备启动Install dependencies and tools部分..." cd cicd/app-builder/go/appbuilder go mod tidy go get github.com/axw/gocov/gocov # 安装增量覆盖率工具 # 安装 golangci-lint curl -sSfL https://raw.githubusercontent.com/golangci/golangci-lint/master/install.sh | sh -s -- -b $(go env GOPATH)/bin v1.53.3 echo "$GOPATH/bin" >> $GITHUB_PATH fi - name: Run tests and calculate incremental coverage run: | echo $APPBUILDER_GO_TESTS if [ "$APPBUILDER_GO_TESTS" = "False" ]; then echo "环境变量APPBUILDER_GO_TESTS为False,没有检测到Go文件被更改,跳过Run tests部分。" else echo "检测到Go文件被更改,准备启动Run tests部分..." cd cicd/app-builder/go # 运行测试并生成覆盖率报告 chmod +x run_go_test.sh ./run_go_test.sh fi shell: bash Java-CI-Tests: runs-on: ubuntu-latest env: APPBUILDER_TOKEN: ${{ secrets.APPBUILDER_TOKEN }} APPBUILDER_TOKEN_V2: ${{ secrets.APPBUILDER_TOKEN_V2 }} BAIDU_VDB_API_KEY: ${{ secrets.BAIDU_VDB_API_KEY }} INSTANCE_ID: ${{ secrets.INSTANCE_ID }} DATASET_ID: ${{ secrets.DATASET_ID }} APPBUILDER_TOKEN_DOC_FORMAT: ${{ secrets.APPBUILDER_TOKEN_DOC_FORMAT }} APPBUILDER_TOKEN_V3: ${{ secrets.APPBUILDER_TOKEN_V3 }} DATASET_ID_V3: ${{ secrets.DATASET_ID_V3 }} DOCUMENT_ID_V3: ${{ secrets.DOCUMENT_ID_V3 }} strategy: fail-fast: false matrix: java-version: ['8'] # 使用 Java 11 和 17 作为示例 steps: - name: Checkout code uses: actions/checkout@v3 with: ref: ${{ github.event.pull_request.head.sha }} - name: Set up JDK ${{ matrix.java-version }} uses: actions/setup-java@v3 with: java-version: ${{ matrix.java-version }} distribution: 'temurin' - name: Print ENV run: | env ls pwd - name: Git Clone And Checkout Branch run: | fork_repo="https://github.com/$GITHUB_ACTOR/app-builder.git" mkdir cicd cd cicd git clone $fork_repo cd app-builder git checkout $GITHUB_HEAD_REF git remote add upstream https://github.com/baidubce/app-builder.git git fetch upstream git remote -v git status # 找到当前分支与 upstream/master 的共同祖先提交 merge_base=$(git merge-base HEAD upstream/master) echo "merge_base=$merge_base" # 比较当前分支与 merge_base 之间的差异 changed_files=$(git diff --name-only --diff-filter=ACMRT $merge_base) changed_files_java=$(git diff --name-only --diff-filter=ACMRT $merge_base -- 'java/**') echo "发生更改的文件为:" echo "$changed_files" echo "发生更改的Java相关文件为:" if [ -n "$changed_files_java" ]; then export APPBUILDER_JAVA_TESTS=True echo "$changed_files_java" else export APPBUILDER_JAVA_TESTS=False echo "没有检测到Java文件被更改" fi echo "APPBUILDER_JAVA_TESTS=$APPBUILDER_JAVA_TESTS" >> $GITHUB_ENV pwd - name: Install Python dependencies run: | python -m pip install --upgrade pip pip install gitpython lxml - name: Install dependencies run: | echo $APPBUILDER_JAVA_TESTS if [ "$APPBUILDER_JAVA_TESTS" = "False" ]; then echo "环境变量APPBUILDER_JAVA_TESTS为False,没有检测到Java文件被更改,跳过Install dependencies部分。" else echo "检测到Java文件被更改(根据环境变量APPBUILDER_JAVA_TESTS),准备启动单元测试Install dependencies部分..." cd cicd/app-builder/java mvn clean install -DskipTests fi - name: Run Java tests with Jacoco if: env.APPBUILDER_JAVA_TESTS == 'True' run: | echo "检测到Java文件被更改(根据环境变量APPBUILDER_JAVA_TESTS),准备启动Run Java tests with Jacoco部分..." cd cicd/app-builder/java bash print_coverage.sh ================================================ FILE: CONTRIBUTING.md ================================================ # Contributing to AppBuilder Thanks for your interest in contributing to AppBuilder! Please follow these guidelines to make the contribution process easy and effective for everyone involved. ## Contributing Guide for python SDK ### Development Clone the source code from Github ``` git clone https://github.com/baidubce/app-builder.git ``` Use `pip` to install from source ```shell cd appbuilder pip install -e . ``` `-e` means "editable mode" in pip. With "editable mode" all changes to python code will immediately become effective in the current environment. ### Testing We highly recommend writing tests for new features or bug fixes and ensure all tests passing before submitting a PR. AppBuilder uses [unittest](https://docs.python.org/3/library/unittest.html) as the test framework, requires no 3rd party dependencies to install. Before running tests, make sure add the following environment variables: ```shell export TEST_CASE=CPU_PARALLEL export APPBUILDER_TOKEN= ``` To run all existing test cases together, run ``` pip install -e .[all] sh appbuilder/tests/run_python_test.sh ``` If you only want to run specific test file, e.g.: ``` python appbuilder/tests/test_playground.py ``` To debug tests in vs code update .env file to roo folder of the project: ``` APPBUILDER_TOKEN= APPBUILDER_TOKEN_V2= TEST_CASE=CPU_SERIAL ``` and add/update `.vscode/settings.json` file with the following content: ``` { "python.testing.unittestArgs": [ "-v", "-s", "./python", "-p", "test*.py" ], "python.testing.unittestEnabled": true, "python.envFile": "${workspaceFolder}/.env" } ``` ================================================ FILE: LICENSE ================================================ Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright (c) 2023 Baidu, Inc. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ================================================ FILE: NEW_README.md ================================================
logo
[![License](https://img.shields.io/badge/license-Apache%202-blue.svg)](LICENSE) ![Supported Python versions](https://img.shields.io/badge/python-3.9+-orange.svg) ![Supported OSs](https://img.shields.io/badge/os-linux%2C%20win%2C%20mac-yellow.svg)
简体中文 | [English](./docs/README_en.md) | [日本語](./docs/README_ja.md)
## 🚀 欢迎使用 AppBuilder-SDK AppBuilder-SDK 是百度智能云千帆AppBuilder面向AI原生应用开发者提供的一站式开发平台客户端SDK。无论你是AI新手还是资深开发者,都能在这里找到适合你的AI应用开发方案。 ### ✨ 为什么选择 AppBuilder-SDK? | 特性 | 描述 | 优势 | |------|------|------| | 丰富的AI能力 | 40+个百度生态优质组件 | 开箱即用,无需重复开发 | | 灵活的部署方式 | 支持本地、云端、API等多种部署 | 适应不同场景需求 | | 完整的开发工具 | 提供监控、调试、追踪等工具 | 提升开发效率 | | 活跃的社区支持 | 微信交流群、Github社区 | 快速解决问题 | ### 🎯 我能用 AppBuilder-SDK 做什么? #### 1. 构建智能应用 - **RAG应用**:构建基于知识库的智能问答系统,支持文档解析、切片、向量化、检索等完整流程 - **Agent应用**:开发具有自主决策能力的AI助手,支持工具调用、多轮对话、状态管理 - **工作流应用**:通过可视化编排或代码方式构建复杂的AI处理流程 #### 2. 调用AI能力 - **大模型调用**:支持多种大模型,可自定义prompt - **组件调用**:40+个百度生态优质组件 - **MCP组件**:支持将本地组件转换为MCP服务 #### 3. 部署与监控 - **多种部署方式**:支持Flask、Chainlit、公有云部署 - **完整的监控工具**:提供可视化Tracing、DebugLog等 ### 🛠️ 快速开始 #### 1. 环境要求 - Python >= 3.9 - 使用MCP组件功能需要 Python >= 3.12 - 支持的操作系统:Linux、Windows、MacOS #### 2. 安装SDK ```bash python3 -m pip install --upgrade appbuilder-sdk ``` #### 3. 选择你的开发路径
quickstart-flow
| 开发路径 | 适合人群 | 推荐文档 | |---------|---------|---------| | 新手入门 | 刚接触AI开发 | [快速开始指南](./docs/QuickStart/StartFirstAINativeApplication/README.md) | | 组件开发 | 想开发自定义组件 | [MCP组件开发指南](./cookbooks/mcp/server.ipynb) | | 应用开发 | 已有AI开发经验 | [应用开发指南](./docs/Application/README.md) | ### 📚 学习资源 #### 1. 基础教程 - [组件使用示例](./cookbooks/components/README.md) - [工作流编排指南](./cookbooks/pipeline/README.md) - [端到端应用示例](./cookbooks/end2end_application/README.md) #### 2. 进阶教程 - [MCP组件开发](./cookbooks/mcp/README.md) - [公有云部署](./cookbooks/advanced_application/cloud_deploy.ipynb) - [性能优化指南](./docs/DevelopGuide/AdvancedDevelopment/README.md) ### 🔥 最新特性:MCP组件支持 AppBuilder-SDK 最新版本支持将本地组件转换为MCP服务,实现端云组件联动。主要特性包括: | 特性 | 描述 | 文档链接 | |------|------|---------| | 组件服务化 | 将本地组件转换为MCP服务 | [MCP组件开发指南](./cookbooks/mcp/server.ipynb) | | 端云联动 | 实现本地组件与云端组件的联动 | [端云组件联动示例](./cookbooks/end2end_application/agent/tool_call.ipynb) | ### 💡 快速示例 #### 1. 调用大模型 ```python import appbuilder import os # 设置环境中的TOKEN os.environ["APPBUILDER_TOKEN"] = "your-token-here" # 定义prompt模板 template_str = "你扮演{role}, 请回答我的问题。\n\n问题:{question}。\n\n回答:" # 定义输入,调用playground组件 input = appbuilder.Message({"role": "java工程师", "question": "请简要回答java语言的内存回收机制是什么,要求100字以内"}) playground = appbuilder.Playground(prompt_template=template_str, model="DeepSeek-V3.1") # 以打字机的方式,流式展示大模型回答内容 output = playground(input, stream=True, temperature=1e-10) for stream_message in output.content: print(stream_message) ``` #### 2. 调用能力组件 ```python import appbuilder import os # 设置环境中的TOKEN os.environ["APPBUILDER_TOKEN"] = "your-token-here" # 创建组件实例 rag_with_baidu_search_pro = appbuilder.RagWithBaiduSearchPro(model="DeepSeek-V3.1") # 执行组件 input = appbuilder.Message("9.11和9.8哪个大") result = rag_with_baidu_search_pro.run( message=input, instruction=appbuilder.Message("你是专业知识助手")) # 输出运行结果 print(result.model_dump_json(indent=4)) ``` #### 3. 使用MCP组件 ```python import os from appbuilder.mcp_server.server import MCPComponentServer from appbuilder.core.components.v2 import Translation, Text2Image os.environ['APPBUILDER_TOKEN'] = 'your-token-here' # 定义server server = MCPComponentServer(name="AB Component Server") # 初始化组件实例 translation = Translation() text2image = Text2Image() # 把组件作为tool添加到server server.add_component(translation) server.add_component(text2image) # 启动server server.run() ``` ### 🤝 加入社区

加入我们的微信交流群

wechat
- [Github Issue](https://github.com/baidubce/app-builder/issues): 提交问题、报告bug、建议新特性 - [百度智能云千帆社区](https://cloud.baidu.com/qianfandev): 参与社区活动、获取最新资讯 ### 📄 文档导航 - [完整文档目录](./docs/README.md) - [API参考](./docs/API/README.md) - [更新日志](./docs/DevelopGuide/ChangeLog/changelog.md) - [常见问题](./docs/DevelopGuide/ErrorMessage/error_message.md) ## License AppBuilder-SDK遵循Apache-2.0开源协议。 ================================================ FILE: README.md ================================================
logo
[![License](https://img.shields.io/badge/license-Apache%202-blue.svg)](LICENSE) ![Supported Python versions](https://img.shields.io/badge/python-3.9+-orange.svg) ![Supported OSs](https://img.shields.io/badge/os-linux%2C%20win%2C%20mac-yellow.svg)
简体中文 | [English](./docs/README_en.md) | [日本語](./docs/README_ja.md)
## 什么是AppBuilder-SDK 百度智能云千帆AppBuilder-SDK是[百度智能云千帆AppBuilder](https://appbuilder.cloud.baidu.com/)面向AI原生应用开发者提供的一站式开发平台的客户端SDK。 ### AppBuilder-SDK 有哪些功能? 百度智能云千帆AppBuilder-SDK提供了以下AI应用开发者的必备功能: - **调用** - 调用大模型,可自由调用您在[百度智能云千帆大模型平台](https://qianfan.cloud.baidu.com/)的模型,开发并调优prompt - 调用能力组件,提供40+个源于百度生态的[优质组件](https://cloud.baidu.com/doc/AppBuilder/s/Glqb6dfiz#3%E3%80%81%E5%BC%80%E9%80%9A%E7%BB%84%E4%BB%B6%E6%9C%8D%E5%8A%A1),赋能Agent应用 - 调用AI原生应用,通过[AppBuilderClient](/docs/BasisModule/Platform/Application/appbuilder_client.md)可访问并管理在百度智能云千帆AppBuilder[网页端](https://console.bce.baidu.com/ai_apaas/app)发布的AI原生应用,并可注册本地函数联动端云组件 - **编排** - 配置知识库,通过[KnowledgeBase](/docs/BasisModule/Platform/KnowledgeBase/knowledgebase.md)管理知识库,进行文档及知识切片的增删改查,配合[网页端](https://console.bce.baidu.com/ai_apaas/app)开发产业级的`RAG`应用 - 编排工作流,提供了`Message`、`Component`、`AgentRuntime`多级工作流抽象,实现工作流编排,并可与LangChain、OpenAI等业界生态能力打通 - **监控** - 提供了可视化Tracing、详细DebugLog等监控工具,助力开发者在生产环境应用 - **部署** - `AgentRuntime`支持部署为基于`Flask`与`gunicorn`的API服务 - `AgentRuntime`支持部署为基于`Chainlit`的对话框交互前端 - 提供了`appbuilder_bce_deploy`工具,可快速部署程序到百度云,提供公网API服务,联动AppBuilder工作流 ### 使用 AppBuilder-SDK 可以构建什么应用? #### **产业级RAG应用** AppBuilder-SDK提供多类型组件,覆盖以下构建产业级`RAG`应用的完整步骤: - 文档解析(Parser) - 文档切片(Chunker) - 切片向量化(Embedding) - 索引构建(Indexing) - 切片召回(Retrieval) - 答案生成(Answer Generation) AppBuilder-SDK不仅提供了百度智能云提供的基础能力组件,同时提供经过深度优化的大模型高级能力组件,可以组合下表提供的原子能力组件,构建个性化的RAG应用[RAG 原子能力 CookBook](./cookbooks/end2end_application/rag/rag.ipynb): | 阶段 |组件名称 | 组件类型 |组件链接 | |--------|--------|--------|---| | 文档解析 | 文档矫正增强 (DocCropEnhance) | 基础能力组件 | [链接](./python/core/components/doc_crop_enhance/README.md) | | 文档解析 | 文档格式转换 (DocFormatConverter) | 基础能力组件 | [链接](./python/core/components/doc_format_converter/README.md)| | 文档解析 | 文档解析(DocParser)| 基础能力组件 | [链接](./python/core/components/doc_parser/README.md) | | 文档解析 | 表格抽取组件(ExtractTableFromDoc)| 基础能力组件 | [链接](./python/core/components/extract_table/README.md) | | 文档解析 | 通用文字识别-高精度版(GeneralOCR)| 基础能力组件 | [链接](./python/core/components/general_ocr/README.md) | | 文档切片 | 文档切分(DocSplitter)| 基础能力组件 | [链接](./python/core/components/doc_splitter/README.md) | | 切片向量化 | 向量计算(Embedding) | 基础能力组件 | [链接](./python/core/components/embeddings/README.md) | | 索引构建及切片召回 | 向量检索-VectorDB(BaiduVectorDBRetriever) | 基础能力组件 | [链接](./python/core/components/retriever/baidu_vdb/README.md) | | 索引构建及切片召回 | 向量检索-BES(BaiduElasticSearchRetriever) | 基础能力组件 | [链接](./python/core/components/retriever/bes/README.md) | | 文档切片及答案生成 | 问答对挖掘(QAPairMining)| 高级能力组件 | [链接](./python/core/components/llms/qa_pair_mining/README.md) | | 文档切片及答案生成 | 相似问生成(SimilarQuestion)| 高级能力组件 | [链接](./python/core/components/llms/similar_question/README.md) | | 答案生成| 标签抽取(TagExtraction)| 高级能力组件 | [链接](./python/core/components/llms/tag_extraction/README.md) | | 答案生成 | 复杂Query判定(IsComplexQuery)| 高级能力组件 | [链接](./python/core/components/llms/is_complex_query/README.md) | | 答案生成 | 复杂Query分解(QueryDecomposition)| 高级能力组件 | [链接](./python/core/components/llms/query_decomposition/README.md) | | 答案生成 | 多轮改写 (QueryRewrite)| 高级能力组件 | [链接](./python/core/components/llms/query_rewrite/README.md) | | 答案生成 | 阅读理解问答(MRC)| 高级能力组件 | [链接](./python/core/components/llms/mrc/README.md) | | 答案生成 | 幻觉检测(Hallucination Detection)| 高级能力组件 | [链接](./python/core/components/llms/hallucination_detection/README.md) | ## 如何安装AppBuilder-SDK #### 百度智能云千帆AppBuilder-SDK 最新版本 1.1.0 (2025-06-20) 百度智能云千帆AppBuilder-SDK 更新记录&最新特性请查阅我们的[版本说明](/docs/DevelopGuide/ChangeLog/changelog.md) - `Python`版本安装,要求Python版本 >= `3.9` ```bash python3 -m pip install --upgrade appbuilder-sdk ``` - `Java` 及 `Go` 版本安装,以及通过`Docker`镜像使用,请查阅[安装说明](/docs/QuickStart/StartFirstAINativeApplication/install.md) ## 快速开始你的AI原生应用开发之旅 > - 请在`>=3.9`的Python环境安装`appbuilder-sdk`后使用该端到端应用示例 > - 示例中使用请替换为您的个人Token ### 1. 调用大模型 - 使用`Playground`组件可自由调用,您在百度智能云千帆大模型平台有权限的任何模型,并可自定义`prompt`模板 与 模型参数 #### 代码示例 ```python import appbuilder import os # 设置环境中的TOKEN,请替换为您的个人TOKEN os.environ["APPBUILDER_TOKEN"] = "your api key" # 定义prompt模板 template_str = "你扮演{role}, 请回答我的问题。\n\n问题:{question}。\n\n回答:" # 定义输入,调用playground组件 input = appbuilder.Message({"role": "java工程师", "question": "请简要回答java语言的内存回收机制是什么,要求100字以内"}) playground = appbuilder.Playground(prompt_template=template_str, model="DeepSeek-V3.1") # 以打字机的方式,流式展示大模型回答内容 output = playground(input, stream=True, temperature=1e-10) for stream_message in output.content: print(stream_message) # 流式输出结束后,可再次打印完整的大模型对话结果,除回答内容外,还包括token的用量情况 print(output.model_dump_json(indent=4)) ``` #### 回答展示 ```shell Java语言的 内存回收机制是通过垃圾回收器(Garbage Collector)来实现的。 垃圾回收器会自动检测不再使用的对象,并释放其占用的内存空间,从而确保系统的内存不会被耗尽。 Java提供了多种垃圾回收器,如串行回收器、并行回收器、CMS回收器和G1回收器等,以满足不同场景下的性能需求 。 { "content": "Java语言的内存回收机制是通过垃圾回收器(Garbage Collector)来实现的。垃圾回收器会自动检测不再使用的对象,并释放其占用的内存空间,从而确保系统的内存不会被耗尽。Java提供了多种垃圾回收器,如串行回收器、并行回收器、CMS回收器和G1回收器等,以满足不同场景下的性能需求。", "name": "msg", "mtype": "dict", "id": "2bbee989-40e3-45e4-9802-e144cdc829a9", "extra": {}, "token_usage": { "prompt_tokens": 35, "completion_tokens": 70, "total_tokens": 105 } } ``` ### 2. 调用能力组件 - SDK提供了40+个源于百度生态的优质组件,列表可见[组件列表](https://cloud.baidu.com/doc/AppBuilder/s/Glqb6dfiz#3%E3%80%81%E5%BC%80%E9%80%9A%E7%BB%84%E4%BB%B6%E6%9C%8D%E5%8A%A1), 调用前需要申领[免费试用额度](https://console.bce.baidu.com/ai-engine/old/#/ai/ocr/overview/resource/list) - 示例中的组件为`RAG with Baidu Search增强版`, 结合百度搜索的搜索引擎技术和ERNIE模型的语义理解能力,可以更准确地理解用户的搜索意图,并提供与搜索查询相关性更高的搜索结果 #### 代码示例 ```python import appbuilder import os # 设置环境中的TOKEN,使用请替换为您的个人TOKEN os.environ["APPBUILDER_TOKEN"] = "your api key" rag_with_baidu_search_pro = appbuilder.RagWithBaiduSearchPro(model="DeepSeek-V3.1") input = appbuilder.Message("9.11和9.8哪个大") result = rag_with_baidu_search_pro.run( message=input, instruction=appbuilder.Message("你是专业知识助手")) # 输出运行结果 print(result.model_dump_json(indent=4)) ``` #### 回答展示 ```shell { "content": "9.11小于9.8。在比较两个小数的大小时,需要逐位比较它们的数值,包括整数部分和小数部分。对于9.11和9.8,整数部分都是9,所以需要在小数部分进行比较。小数点后的第一位是1和8,显然1小于8,所以9.11小于9.8。", "name": "msg", "mtype": "dict", "id": "eb31b7de-dd6a-485f-adb9-1f7921a6f4bf", "extra": { "search_baidu": [ { "content": "大模型‘智商’受质疑:9.11 vs 9...", "icon": "https://appbuilder.bj.bcebos.com/baidu-search-rag-pro/icon/souhu.ico", "url": "https://m.sohu.com/a/793754123_121924584/", "ref_id": "2", "site_name": "搜狐网", "title": "大模型‘智商’受质疑:9.11 vs 9.8的比较揭示AI理解能力的..." }, { "content": "究竟|9.11比9.8大?大模型们为何会...", "icon": "https://appbuilder.bj.bcebos.com/baidu-search-rag-pro/icon/tencent.svg.png", "url": "https://new.qq.com/rain/a/20240717A07JLV00", "ref_id": "4", "site_name": "腾讯网", "title": "究竟|9.11比9.8大?大模型们为何会在小学数学题上集体..." }, ... ] }, "token_usage": { "completion_tokens": 77, "prompt_tokens": 2008, "total_tokens": 2085 } } ``` ### 3. 调用AI原生应用 - 示例中的应用为:[说唱导师](https://appbuilder.baidu.com/s/3qfjXy7k),点击该连接在网页端试用 #### 代码示例 ```python import appbuilder import os # 设置环境中的TOKEN,请替换为您的个人TOKEN os.environ["APPBUILDER_TOKEN"] = "your api key" # 从AppBuilder网页获取并传入应用ID,以下为说唱导师应用ID app_id = "4678492a-5864-472e-810a-654538d3503c" app_builder_client = appbuilder.AppBuilderClient(app_id) conversation_id = app_builder_client.create_conversation() answer = app_builder_client.run(conversation_id, "以“上班狼狈却又追逐梦想“为主题进行一首说唱创作,保持押韵, 控制在200字以内") print(answer.content.answer) ``` #### 回答展示 ```shell 好的,我们来以“上班狼狈却又追逐梦想”为主题,进行一段简短的说唱创作。这里是一个简单的示例,你可以根据自己的感觉进行调整: Intro: 朝九晚五,生活重压, 狼狈上班,却心怀梦想, 每一天,都是新的挑战, 为了那未来,我奋发向前。 Verse 1: 穿上西装,打好领带, 步入人群,去追逐名利, 虽然狼狈,却不曾言败, 因为心中,有梦想在激励。 Hook: 上班狼狈,却不曾放弃, 追逐梦想,是我心中的火炬, 照亮前路,指引我前行, 无论多难,我都要坚持到底。 这首小曲儿以“上班狼狈却又追逐梦想”为主题,通过押韵的方式表达了上班族虽然生活艰辛,但依然怀揣梦想,勇往直前的精神。希望你喜欢! ``` #### 更多示例 - 更多AI原生应用示例,请浏览[应用广场](https://console.bce.baidu.com/ai_apaas/appCenter) - 更多代码Cookbook,请浏览 [Cookbooks](./cookbooks/README.md),我们有以下cookbook推荐您优先阅读: | 应用类型 |应用链接 | 推荐理由 | |--|--|--| | 基础能力组件 | [通用文字识别](/cookbooks/components/general_ocr.ipynb) | 体验百度AI开放平台提供的通用文字识别-高精度版的精准识别结果 | | 基础能力组件 | [基础组件服务化](/cookbooks/components/agent_runtime.ipynb) | 基础组件可通过flask实现服务化部署 或 通过chainlit实现可交互的前端部署,集成到您的系统中 | | 流程编排 | [Assistant SDK](/cookbooks/pipeline/assistant_function_call.ipynb) | 学习如何纯代码态搭建一个Agent应用,并实现自定义工作流程及FunctionCall | | 端到端应用 | [AppBuilder Client SDK](/cookbooks/agent_builder.ipynb) | 使用AppBuilder网页端创建并发布一个Agent应用后,通过AppBuilderClient SDK集成到你的系统中 | | 端到端应用 | [Agent应用-工作流Agent](/cookbooks/end2end_application/agent/chatflow.ipynb) | 使用AppBuilder网页端创建并发布一个工作流Agent应用后,通过AppBuilderClient SDK集成到你的系统中 | | 端到端应用 | [通过AppBuilder-ToolCall功能实现端云组件联动的Agent](/cookbooks/end2end_application/agent/tool_call.ipynb) | 学习Agent、FunctionCall的知识,并构造调用本地组件的Agent | | 端到端应用 | [简历筛选小助手](/cookbooks/end2end_application/rag/rag.ipynb) | 通过对本地简历库的简历进行解析、切片、创建索引,实现基于JD进行简历筛选,并对筛选的Top1简历进行总结 | | 端到端应用 | [企业级问答系统](/cookbooks/end2end_application/rag/qa_system_2_dialogue.ipynb) | 学习如何通过SDK与网页平台搭配,实现离线知识库生产与在线问答 | | 进阶应用 | [使用appbuilder_bce_deploy部署公有云服务](/cookbooks/advanced_application/cloud_deploy.ipynb) | 一键将自己的服务部署到百度智能云,部署后可以自动生成公网ip,联动工作流的API节点 | | 进阶应用 | [使用appbuilder_trace_server实现对使用状态的跟踪](/cookbooks/appbuilder_trace/trace.ipynb) | 使用Appbuilder-SDK Trace功能实现对组件、应用调用情况的追踪| ## 百度智能云千帆AppBuilder-SDK 能力全景图
wechat
## 用户文档 ## Github 文档 - [首页](https://github.com/baidubce/app-builder/blob/master/docs/README.md) - 快速上手: - 开始你的第一个AI原生应用: - [安装](https://github.com/baidubce/app-builder/blob/master/docs/QuickStart/StartFirstAINativeApplication/install.md) - [快速开始](https://github.com/baidubce/app-builder/blob/master/docs/QuickStart/StartFirstAINativeApplication/README.md) - 产业实践应用范例: - [SDK使用示例](https://github.com/baidubce/app-builder/blob/master/docs/QuickStart/ExamplesOfIndustrialPracticeApplications/README.md) - [SDK当前支持的编程语言](https://github.com/baidubce/app-builder/blob/master/docs/QuickStart/CurrentlySupportedProgrammingLanguages/README.md) - 基础: - 模型: - [获取模型列表](https://github.com/baidubce/app-builder/blob/master/docs/BasisModule/Model/get_model_list.md) - [组件](https://github.com/baidubce/app-builder/blob/master/docs/BasisModule/Components) - 监控: - [TRACE基础功能](https://github.com/baidubce/app-builder/blob/master/docs/BasisModule/Trace/basic.md) - [TRACE拓展功能](https://github.com/baidubce/app-builder/blob/master/docs/BasisModule/Trace/phoenix_method.md) - 部署: - [交互式前端部署](https://github.com/baidubce/app-builder/blob/master/docs/BasisModule/Deployment/AgentChainlit.md) - [公有云部署](https://github.com/baidubce/app-builder/blob/master/docs/BasisModule/Deployment/cloud.md) - [API 访问](https://github.com/baidubce/app-builder/blob/master/docs/BasisModule/Deployment/flask.md) - [AgentRuntime](https://github.com/baidubce/app-builder/blob/master/docs/BasisModule/Deployment/agentruntime.md) - [UserSession](https://github.com/baidubce/app-builder/blob/master/docs/BasisModule/Deployment/usersession.md) - 平台: - 应用: - [AppBuilderClient组件](https://github.com/baidubce/app-builder/blob/master/docs/BasisModule/Platform/Application/appbuilder_client.md) - [获取AppBuilder已发布的应用列表](https://github.com/baidubce/app-builder/blob/master/docs/BasisModule/Platform/Application/get_app_list.md) - 知识库: - [知识库组件](https://github.com/baidubce/app-builder/blob/master/docs/BasisModule/Platform/KnowledgeBase/knowledgebase.md) - 自定义组件: - [基础能力组件](https://github.com/baidubce/app-builder/blob/master/docs/BasisModule/Platform/CustomComponents/components.md) - 应用: - Agent: - [基础知识](https://github.com/baidubce/app-builder/blob/master/docs/Application/Agent/BasicKnowledge/agent.md) - [使用官方组件](https://github.com/baidubce/app-builder/blob/master/docs/Application/Agent/UseOfficialComponents/use_official_components.md) - [ToolCall](https://github.com/baidubce/app-builder/blob/master/docs/Application/Agent/ToolCall/tool_call.md) - [ToolChoice](https://github.com/baidubce/app-builder/blob/master/docs/Application/Agent/ToolChoice/tool_choice.md) - [使用异步和流式加速客户端调用](https://github.com/baidubce/app-builder/blob/master/docs/Tools/DocPass/DocPass.md) - RAG: - [基础知识](https://github.com/baidubce/app-builder/blob/master/docs/Application/RAG/BasicKnowledge/rag.md) - [知识库管理](https://github.com/baidubce/app-builder/blob/master/docs/Application/RAG/DatasetManage/dataset_manage.md) - [Reference信息处理](https://github.com/baidubce/app-builder/blob/master/docs/Tools/DocPass/DocPass.md) - Workflow: - [基础知识](https://github.com/baidubce/app-builder/blob/master/docs/Tools/DocPass/DocPass.md) - [从零使用Workflow组装一个RAG应用](https://github.com/baidubce/app-builder/blob/master/docs/Tools/DocPass/DocPass.md) - [从零使用Workflow组装一个Agent应用](https://github.com/baidubce/app-builder/blob/master/docs/Tools/DocPass/DocPass.md) - 开发者指南: - [如何贡献代码](https://github.com/baidubce/app-builder/blob/master/docs/DevelopGuide/HowToContributeCode/README.md) - [二次开发](https://github.com/baidubce/app-builder/blob/master/docs/DevelopGuide/AdvancedDevelopment/README.md) - [版本升级日志](https://github.com/baidubce/app-builder/blob/master/docs/DevelopGuide/ChangeLog/changelog.md) - [错误信息](https://github.com/baidubce/app-builder/blob/master/docs/DevelopGuide/ErrorMessage/error_message.md) - [环境参数](https://github.com/baidubce/app-builder/blob/master/docs/DevelopGuide/EnvironmentalParameters/env.md) ## 开源社区与活动

百度智能云千帆AppBuilder-SDK微信交流群

wechat
- [Github Issue](https://github.com/baidubce/app-builder/issues): 提交安装/使用问题、报告bug、建议新特性、沟通开发计划等 - [百度智能云千帆社区](https://cloud.baidu.com/qianfandev) ## License AppBuilder-SDK遵循Apache-2.0开源协议。 ================================================ FILE: cookbooks/README.md ================================================ # AppBuilder-SDK Cookbook ## Cookbook目录 ### 基础组件 - [短语音识别组件-asr](/cookbooks/components/asr.ipynb) - [gbi - 自动选表问表](/cookbooks/components/gbi.ipynb) - [general_ocr - 通用文字识别](/cookbooks/components/general_ocr.ipynb) - [object_recognize - 通用物体识别](/cookbooks/components/object_recognize.ipynb) - [rag_with_baidusearch - 百度搜索](/cookbooks/components/rag_with_baidusearch.ipynb) - [text_generation - 文本生成](/cookbooks/components/text_generation.ipynb) - [translate - 文本翻译](/cookbooks/components/translate.ipynb) - [vdb_retriever - VectorDB向量存储](/cookbooks/components/vdb_retriever.ipynb) ### 流程编排 - [基于AssistantSDK 实现FunctionCall](/cookbooks/pipeline/assistant_function_call.ipynb) - [AssistantSDK assistant函数演示](/cookbooks/pipeline/assistant.ipynb) - [AssistantSDK file函数演示](/cookbooks/pipeline/file.ipynb) - [AssistantSDK message函数演示](/cookbooks/pipeline/message.ipynb) - [AssistantSDK run函数演示](/cookbooks/pipeline/run.ipynb) - [AssistantSDK thread函数演示](/cookbooks/pipeline/thread.ipynb) ### 端到端应用 - [Agent应用](/cookbooks/end2end_application/agent/appbuilder_client.ipynb) - [Agent应用-工作流Agent](/cookbooks/end2end_application/agent/chatflow.ipynb) - [RAG应用-简历筛选小助手](/cookbooks/end2end_application/rag/rag.ipynb) - [RAG应用-问答助手](/cookbooks/end2end_application/rag/console_rag.ipynb) - [RAG应用-企业问答系统-离线知识生产](/cookbooks/end2end_application/rag/qa_system_1_dataset.ipynb) - [RAG应用-企业问答系统-在线问答流程](/cookbooks/end2end_application/rag/qa_system_2_dialogue.ipynb) - [知识库操作助手](/cookbooks/end2end_application/rag/console_dataset.ipynb) - [通过AppBuilder-ToolCall功能实现端云组件联动的Agent](/cookbooks/end2end_application/agent/tool_call.ipynb) ### 进阶应用 - [公有云部署](/cookbooks/advanced_application/cloud_deploy.ipynb) ### 辅助工具 - [Appbuilder-Trace工具](/cookbooks/appbuilder_trace/trace.ipynb) ================================================ FILE: cookbooks/advanced_application/agent_speech.ipynb ================================================ { "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# 实时语音对话能力\n", "**注意⚠️:实时语音功能目前处于内测阶段,使用过程中有任何问题,欢迎提issue或微信群反馈~**\n", "\n", "## 目标\n", "实现一个实时语音对话功能,支持多种语音音色。用户可以参考cookbook代码,通过AppBuilder-SDK将实时语音功能很好地融入自己的平台、应用中。\n", "\n", "## 实现原理\n", "通过循环不断处理用户的语音,将语音转文本,然后进行对话,最后将对话结果通过TTS进行播报。。\n", "* 使用大模型的 ASR 进行语音转文本。\n", "* 使用用户自己创建的Agent进行对话,适配用户的应用场景,并具有上下文理解能力。\n", "* 使用大模型的 TTS 进行文本转语音并进行播报。\n", "\n", "## 前置条件\n", "* 使用内置ASR、TTS组件之前,请先开通组件服务并够买额度,可参考[开通组件服务](https://cloud.baidu.com/doc/AppBuilder/s/Glqb6dfiz#3%E3%80%81%E5%BC%80%E9%80%9A%E7%BB%84%E4%BB%B6%E6%9C%8D%E5%8A%A1)\n", "* pip安装pyaudio、webrtcvad依赖包\n", "* 给程序开放麦克风权限\n", "* 创建好自己的Agent应用\n", "\n", "## 示例代码" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Copyright (c) 2024 Baidu, Inc. All Rights Reserved.\n", "#\n", "# Licensed under the Apache License, Version 2.0 (the \"License\");\n", "# you may not use this file except in compliance with the License.\n", "# You may obtain a copy of the License at\n", "#\n", "# http://www.apache.org/licenses/LICENSE-2.0\n", "#\n", "# Unless required by applicable law or agreed to in writing, software\n", "# distributed under the License is distributed on an \"AS IS\" BASIS,\n", "# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n", "# See the License for the specific language governing permissions and\n", "# limitations under the License.\n", "\n", "import os\n", "import time\n", "import wave\n", "import sys\n", "import pyaudio\n", "import webrtcvad\n", "import appbuilder\n", "import re\n", "\n", "# 请前往千帆AppBuilder官网创建密钥,流程详见:https://cloud.baidu.com/doc/AppBuilder/s/Olq6grrt6#1%E3%80%81%E5%88%9B%E5%BB%BA%E5%AF%86%E9%92%A5\n", "# 设置环境变量\n", "os.environ[\"APPBUILDER_TOKEN\"] = (\n", " \"...\"\n", ")\n", "# 已发布AppBuilder应用的ID\n", "app_id = \"...\"\n", "appbuilder.logger.setLoglevel(\"ERROR\")\n", "\n", "CHUNK = 1024\n", "FORMAT = pyaudio.paInt16\n", "CHANNELS = 1 if sys.platform == \"darwin\" else 2\n", "RATE = 16000\n", "DURATION = 30 # ms\n", "CHUNK = RATE // 1000 * DURATION\n", "\n", "\n", "class Chatbot:\n", " def __init__(self):\n", " self.p = pyaudio.PyAudio()\n", " self.tts = appbuilder.TTS()\n", " self.asr = appbuilder.ASR()\n", " self.agent = appbuilder.AppBuilderClient(app_id)\n", " self.conversation_id = self.agent.create_conversation()\n", "\n", " def run(self):\n", " self.run_tts_and_play_audio(\n", " \"我是你的专属聊天机器人,如果你有什么问题,可以直接问我\"\n", " )\n", " while True:\n", " # Record\n", " audio_path = \"output.wav\"\n", " print(\"开始记录音频...\")\n", " if self.record_audio(audio_path) < 1000:\n", " time.sleep(1)\n", " continue\n", " print(\"音频记录结束\")\n", "\n", " # ASR\n", " print(\"开始执行ASR...\")\n", " query = self.run_asr(audio_path)\n", " print(\"结束执行ASR\")\n", "\n", " # Agent\n", " print(\"query: \", query)\n", " if len(query) == 0:\n", " continue\n", " answer = self.run_agent(query)\n", " results = re.findall(r\"(https?://[^\\s]+)\", answer)\n", " for result in results:\n", " print(\"链接地址:\", result)\n", " answer = answer.replace(result, \"\")\n", " print(\"answer:\", answer)\n", "\n", " # TTS\n", " print(\"开始执行TTS并播报...\")\n", " self.run_tts_and_play_audio(answer)\n", " print(\"结束TTS并播报结束\")\n", "\n", " def record_audio(self, path):\n", " with wave.open(path, \"wb\") as wf:\n", " wf.setnchannels(CHANNELS)\n", " wf.setsampwidth(self.p.get_sample_size(FORMAT))\n", " wf.setframerate(RATE)\n", " stream = self.p.open(\n", " format=FORMAT, channels=CHANNELS, rate=RATE, input=True\n", " )\n", " vad = webrtcvad.Vad(1)\n", " not_speech_times = 0\n", " speech_times = 0\n", " total_times = 0\n", " start_up_times = 33 * 5 # 初始时间设置为5秒\n", " history_speech_times = 0\n", " while True:\n", " if history_speech_times > 33 * 10:\n", " break\n", " data = stream.read(CHUNK, False)\n", " if vad.is_speech(data, RATE):\n", " speech_times += 1\n", " wf.writeframes(data)\n", " else:\n", " not_speech_times += 1\n", " total_times += 1\n", " if total_times >= start_up_times:\n", " history_speech_times += speech_times\n", " # 模拟滑窗重新开始计数\n", " if float(not_speech_times) / float(total_times) > 0.7:\n", " break\n", " not_speech_times = 0\n", " speech_times = 0\n", " total_times = 0\n", " start_up_times = start_up_times / 2\n", " if start_up_times < 33:\n", " start_up_times = 33\n", " stream.close()\n", " return history_speech_times * DURATION\n", "\n", " def run_tts_and_play_audio(self, text: str):\n", " # AppBuilder内置的TTS使用文档,用户可根据文档调整参数:https://github.com/baidubce/app-builder/tree/master/python/core/components/tts\n", " msg = self.tts.run(\n", " appbuilder.Message(content={\"text\": text}),\n", " speed=5,\n", " pitch=5,\n", " volume=5,\n", " person=0,\n", " audio_type=\"pcm\",\n", " model=\"paddlespeech-tts\",\n", " stream=True,\n", " )\n", " stream = self.p.open(\n", " format=self.p.get_format_from_width(2),\n", " channels=1,\n", " rate=24000,\n", " output=True,\n", " frames_per_buffer=2048,\n", " )\n", " for pcm in msg.content:\n", " stream.write(pcm)\n", " stream.stop_stream()\n", " stream.close()\n", "\n", " # AppBuilder内置的ASR使用文档,用户可根据文档调整参数:https://github.com/baidubce/app-builder/blob/master/python/core/components/asr/README.md\n", " def run_asr(self, audio_path: str):\n", " with open(audio_path, \"rb\") as f:\n", " content_data = {\"audio_format\": \"wav\", \"raw_audio\": f.read(), \"rate\": 16000}\n", " msg = appbuilder.Message(content_data)\n", " out = self.asr.run(msg)\n", " text = out.content[\"result\"][0]\n", " return text\n", "\n", " def run_agent(self, query):\n", " msg = self.agent.run(self.conversation_id, query, stream=True)\n", " answer = \"\"\n", " for content in msg.content:\n", " answer += content.answer\n", " return answer\n", "\n", "\n", "if __name__ == \"__main__\":\n", " chatbot = Chatbot()\n", " chatbot.run()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 使用方法\n", "\n", "直接运行程序即可。\n", "\n", "用户也可以将下面的功能模块替换成自己的其他实现或模型:\n", "* record_audio: 录音\n", "* run_asr: 语音识别语音识别,[AppBuilder ASR组件使用文档](https://github.com/baidubce/app-builder/blob/master/python/core/components/asr/README.md)\n", "* run_agent: Agent对话功能,[AppBuilder TTS组件使用文档](https://github.com/baidubce/app-builder/blob/master/python/core/components/tts/README.md)\n", "* run_tts_and_play_audio:回复的语音生成并播报\n", "\n", "**AppBuilder TTS组件参数**\n", "| 参数名称 | 参数类型 | 是否必须 | 描述 | 示例值 |\n", "|------------|---------|------|------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|-------------------------------------|\n", "| message | String | 是 | 待转成语音的文本 | Message(content={\"text\": \"需合成的文本\"}) |\n", "| model | String | 否 | 默认是`baidu-tts`模型,可选值:`paddlespeech-tts`、`baidu-tts` | paddlespeech-tts |\n", "| speed | Integer | 否 | 语音语速,默认是5中等语速,取值范围在0~15之间,仅当模型为`baidu-tts`参数有效,如果模型为`paddlespeech-tts`,参数自动失效 | 5 |\n", "| pitch | Integer | 否 | 语音音调,默认是5中等音调,取值范围在0~15之间,仅当模型为`baidu-tts`参数有效,如果模型为`paddlespeech-tts`,参数自动失效 | 5 |\n", "| volume | Integer | 否 | 语音音量,默认是5中等音量,取值范围在0~15之间,,仅当模型为`baidu-tts`参数有效,如果模型为`paddlespeech-tts`,参数自动失效 | 5 |\n", "| person | Integer | 否 | 语音人物特征,默认是0(度小美),普通音库可选值包括: 0(度小美)、1(度小宇)、3(度逍遥-基础)、4(度丫丫);精品音库包括:5003(度逍遥-精品)、5118(度小鹿)、106(度博文)、110(度小童)、111(度小萌)、103(度米朵)、5(度小娇);臻品音库包括:4003(度逍遥-情感男声)、4106(度博文-专业男主播)、4115(度小贤-电台男主播)、4119(度小鹿-甜美女声)、4105(度灵儿-清激女声)、4117(度小乔-活泼女声)、4100(度小雯-活力女主播)、4103(度米朵-可爱女声)、4144(度姗姗-娱乐女声)、4278(度小贝-知识女主播)、4143(度清风-配音男声)、4140(度小新-专业女主播)、4129(度小彦-知识男主播)、4149(度星河-广告男声)、4254(度小清-广告女声)、4206(度博文-综艺男声)、4226(南方-电台女主播)。仅当模型为`baidu-tts`参数有效,如果模型为`paddlespeech-tts`,参数自动失效 | 0 |\n", "| audio_type | String | 否 | 音频文件格式,如果使用`baidu-tts`模型可选`mp3`, `wav`; 如果使用`paddlespeech-tts`模型非流式返回,参数只能设为`wav`;如果使用`paddlespeech-tts`模型流式返回,参数只能设为`pcm` | wav |\n", "| stream | Bool | 否 | 默认是False, 目前`paddlespeech-tts`模型支持流式返回,`baidu-tts`模型不支持流式返回 | False |\n", "| retry | Integer | 否 | HTTP重试次数 | 3 |\n", "| timeout | Integer | 否 | HTTP超时时间 | 5 |" ] } ], "metadata": { "language_info": { "name": "python" } }, "nbformat": 4, "nbformat_minor": 2 } ================================================ FILE: cookbooks/advanced_application/cloud_deploy.ipynb ================================================ { "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# 公有云部署AppBuilderSDK\n", "**注意⚠️:部署上云功能目前处于内测阶段,使用过程中有任何问题,欢迎提issue或微信群反馈~**\n", "\n", "\n", "## 目标\n", "一键将自己的服务部署到公有云上,目前支持百度智能云。部署后可以自动生成公网ip,无需额外配置。具体可以用来解决以下问题:\n", "* 在百度云部署的WebService,可以引入到AppBuilder工作流中的API节点,形成应用中嵌套应用,构建能够解决复杂业务问题的工作流。\n", "* 可将自己本地复杂的服务、组件、模型等,方便快捷地上云,并与AppBuilder形成联动。\n", "* 构建自己的公网对话服务。" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "\n", "## 部署\n", "### 前置操作:\n", "* 在百度智能云完成实名认证,并开通bos服务:\n", " * https://cloud.baidu.com/doc/BOS/s/Jk4xttg03#%E5%BC%80%E9%80%9Abos%E6%9C%8D%E5%8A%A1\n", "* 您需要在钱包中至少充值100元,用于bcc服务、bos服务费用\n", " * 云服务费用标准:https://cloud.baidu.com/product-price/bcc.html\n", " * 默认配置使用最便宜的bcc.e1.c2m2,并且使用按量付费\n", " * bos存储服务费用标准:https://cloud.baidu.com/product-price/bos.html\n", "* 通过如下步骤获得您的AK/SK信息:\n", " * https://cloud.baidu.com/doc/Reference/s/9jwvz2egb\n", "* 部署的AppBuilder >= 0.9.0\n", "\n", "### 部署流程:\n", "通过下面三步执行部署:\n", "* Step1 以下面的yaml文件为模板创建config.yaml,完善并创建配置文件\n", " * 最小修改范围:ak、sk、admin_pass、run_cmd、local_dir、APPBUILDER_TOKEN\n", "```yaml\n", "bce_config:\n", " host: \"http://bcc.bj.baidubce.com\"\n", " bos_host: \"bj.bcebos.com\"\n", " # 前置操作获取的ak、sk\n", " ak: \"\"\n", " sk: \"\"\n", " spec: \"bcc.e1.c2m2\"\n", " root_disk_size_in_gb: 20\n", " # 服务器密码,根据实际使用设置\n", " admin_pass: \"\"\n", " security_group_id: \"\"\n", " zone_name: cn-bj-d\n", "\n", "appbuilder_config:\n", " # 本地用来打包的代码路径,根据实际使用修改\n", " local_dir: \"./sample\"\n", " workspace: \"/home/work/appbuilder\"\n", "\n", " # 服务的运行命令,根据实际使用修改\n", " run_cmd: \"python3 sample.py\"\n", "\n", "env:\n", " APPBUILDER_LOGLEVEL: debug\n", " APPBUILDER_TOKEN: \"\"\n", "```\n", "* Step2 编写自己的服务运行代码(以组件服务为例)" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "vscode": { "languageId": "plaintext" } }, "outputs": [], "source": [ "# 创建配置中的local_dir目录\n", "mkdir sample\n", "touch sample/sample.py" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "vscode": { "languageId": "plaintext" } }, "outputs": [], "source": [ "# 编写服务运行代码\n", "# sample/sample.py\n", "import appbuilder\n", "\n", "component = appbuilder.Playground(prompt_template=\"{query}\", model=\"ERNIE-Bot\")\n", "agent = appbuilder.AgentRuntime(component=component)\n", "agent.serve(port=8091)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "* Step3 执行部署" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "vscode": { "languageId": "plaintext" } }, "outputs": [], "source": [ "# ./config.yaml为第一步创建的config.yaml文件\n", "appbuilder_bce_deploy --conf ./config.yaml\n", "\n", "# 执行后取日志\"deployment finished! public ip:\"后的ip为部署实例的公网ip \n", "# 若部署结果不符合预期,使用自己配置的\"admin_pass\"登陆服务器进行调试,具体参考文档:https://cloud.baidu.com/doc/BCC/s/Hkbblll70" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### 示例:Component服务,接入AppBuilder工作流\n", "示例代码" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "vscode": { "languageId": "plaintext" } }, "outputs": [], "source": [ "import appbuilder\n", "\n", "component = appbuilder.Playground(prompt_template=\"{query}\", model=\"ERNIE-Bot\")\n", "agent = appbuilder.AgentRuntime(component=component)\n", "agent.serve(port=8091)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "示例请求" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "vscode": { "languageId": "plaintext" } }, "outputs": [], "source": [ "# public_ip为部署获取的实例公网IP\n", "curl --location 'http://{public_ip}:8091/chat' \\\n", "--header 'Content-Type: application/json' \\\n", "--data '{\n", " \"message\": \"海淀区的面积是多少\",\n", " \"stream\": false\n", "}'" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "通过API节点接入Appbuilder工作流,用于创建组件\n", "* 操作参考:https://cloud.baidu.com/doc/AppBuilder/s/glv0f48qe\n", "* API接入调试成功\n", "\n", "\"drawing\"" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### 示例:随时随地的对话服务 \n", "**⚠️示例仅提供demo,实际业务需增加鉴权等能力**\n", "\n", "\n", "示例代码" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "vscode": { "languageId": "plaintext" } }, "outputs": [], "source": [ "import appbuilder\n", "\n", "\n", "component = appbuilder.Playground(prompt_template=\"{query}\", model=\"ERNIE-Bot\")\n", "\n", "agent = appbuilder.AgentRuntime(component=component)\n", "agent.chainlit_demo(port=8091)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "示例效果" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "\"drawing\"" ] } ], "metadata": { "language_info": { "name": "python" } }, "nbformat": 4, "nbformat_minor": 2 } ================================================ FILE: cookbooks/agent_builder.ipynb ================================================ { "cells": [ { "attachments": {}, "cell_type": "markdown", "id": "42eace26869295fb", "metadata": { "collapsed": false }, "source": [ "# Console AppBuilderClient使用示例\n", "\n", "整体使用流程包括以下两个环节:\n", "\n", "1. 在[百度智能云千帆AppBuilder官网](https://cloud.baidu.com/product/AppBuilder)创建并发布应用、获取应用ID、获取密钥\n", "2. 引用AppBuilderSDK代码,初始化AppBuilderClient实例、创建会话、上传文档(可选)、执行对话\n", "\n", "以下分别提供三个样例,快递查询小助手、植物识别小助手、篮球教练来说明使用流程,注意以下流程用到的密钥可在图示位置中获取:\n", "\"drawing\"\n", "\n", "\n", "## 1. 快递查询小助手\n", "\n", "[ 快递查询小助手](https://appbuilder.baidu.com/s/KVSXK)一键体验\n", "\n", "### 1.1 Console端应用配置与发布\n", "1 进入[百度智能云千帆AppBuilder官网](https://cloud.baidu.com/product/AppBuilder),配置智能体指令、选择相应的工具组件、发布应用\n", "\n", "\"drawing\"\n", "\n", "2 获取应用ID\n", "\"drawing\"\n", "\n", "### 1.2 SDK代码调用示例" ] }, { "cell_type": "code", "execution_count": null, "id": "a6a9e2ba6159a8e4", "metadata": { "collapsed": false, "is_executing": true }, "outputs": [], "source": [ "import appbuilder\n", "import os\n", "# 注意以下示例正确运行依赖的条件包括:\n", "# 1. 在百度智能云千帆AppBuilder官网使用AppBuilderClient创建应用且应用已发布\n", "# 2. 密钥正确有效\n", "# 3. 密钥需要与发布应用正确对应,即需要使用发布应用的账户下的密钥\n", "\n", "# 配置密钥与应用ID\n", "os.environ[\"APPBUILDER_TOKEN\"] =\"secret_key\"\n", "app_id = \"35f4fed3-d530-4dad-bc8e-f2150a4450be\"\n", "\n", "# 初始化Agent\n", "builder = appbuilder.AppBuilderClient(app_id)\n", "\n", "# 创建会话ID\n", "conversation_id = builder.create_conversation()\n", "\n", "# 执行对话\n", "msg = builder.run(conversation_id, \"我的快递单号是:9858485940100; 请查询下此快递的状态\")\n", "print(\"快递查询助理回答内容:\", msg.content.answer)\n", "\n", "# 执行流式对话\n", "msg = builder.run(conversation_id, \"使用语音播报快递当前状态\", stream=True)\n", "for content in msg.content:\n", " for ev in content.events:\n", " if ev.content_type == \"audio\":\n", " print(\"快递查询助理生成的音频播放地址:\", ev.detail[\"audio\"])" ] }, { "cell_type": "markdown", "id": "3e462991dab3283d", "metadata": { "collapsed": false }, "source": [ "## 2. 植物识别小助手\n", "[植物识别小助手](https://appbuilder.baidu.com/s/50zyD)一键体验\n", "\n", "### 2.1 Console端应用配置与发布\n", "1 进入[百度智能云千帆AppBuilder官网](https://cloud.baidu.com/product/AppBuilder),配置智能体指令、选择相应的工具组件、发布应用\n", "\"drawing\"\n", "\n", "2 获取应用ID, 同1.1\n", "\n", "### 2.2 SDK代码调用示例" ] }, { "cell_type": "code", "execution_count": null, "id": "4d051395a2aa1d11", "metadata": { "collapsed": false, "is_executing": true }, "outputs": [], "source": [ "import os\n", "import appbuilder\n", "\n", "# 注意以下示例正确运行依赖的条件包括:\n", "# 1. 在百度智能云千帆AppBuilder官网使用AppBuilderClient创建应用且应用已发布\n", "# 2. 密钥正确有效\n", "# 3. 密钥需要与发布的应用正确对应,即需要使用发布应用的账户下的密钥\n", "\n", "# 配置密钥与应用ID\n", "os.environ[\"APPBUILDER_TOKEN\"] =\"...\"\n", "app_id = \"7016e0d3-451b-4a47-a818-dc0a16d4b496\" \n", "\n", "# 初始化Agent实例\n", "builder = appbuilder.AppBuilderClient(app_id)\n", "\n", "# 创建会话ID\n", "conversation_id = builder.create_conversation()\n", "\n", "# 上传植物图片\n", "file_id = builder.upload_local_file(conversation_id, \"./app_builder_resources/tree.png\" )\n", "\n", "# 植物识别\n", "msg = builder.run(conversation_id, \"请识别图中的植物类别\", file_ids=[file_id])\n", "print(\"植物识别助理回答内容:\", msg.content.answer)" ] }, { "cell_type": "markdown", "id": "c112f09d6ce35d10", "metadata": { "collapsed": false }, "source": [ "## 3. 篮球教练\n", "[篮球教练知识增强检索](https://appbuilder.baidu.com/s/RCVEn)一键体验\n", "\n", "### 3.1 Console端应用配置与发布\n", "1 进入[百度智能云千帆AppBuilder官网](https://cloud.baidu.com/product/AppBuilder),配置智能体指令、上传文档并关联知识库、发布应用\n", "\"drawing\"\n", "\n", "2 获取应用ID, 同1.1\n", "\n", "### 3.2 SDK代码调用示例" ] }, { "cell_type": "code", "execution_count": null, "id": "65e488aa883cf94e", "metadata": { "collapsed": false, "is_executing": true }, "outputs": [], "source": [ "import os\n", "import appbuilder\n", "\n", "# 注意以下示例正确运行依赖的条件包括:\n", "# 1. 在百度智能云千帆AppBuilder官网使用AppBuilderClient创建应用且应用已发布\n", "# 2. 密钥正确有效\n", "# 3. 密钥需要与发布的应用正确对应,即需要使用发布应用的账户下的密钥\n", "\n", "# 配置密钥与应用ID\n", "os.environ[\"APPBUILDER_TOKEN\"] =\"...\"\n", "app_id = \"4316a7cb-b6b2-4448-b6fa-ff131c484ec9\" \n", "\n", "# 初始化Agent实例\n", "builder = appbuilder.AppBuilderClient(app_id)\n", "\n", "# 创建会话ID\n", "conversation_id = builder.create_conversation()\n", "\n", "# 执行对话\n", "msg = builder.run(conversation_id, \"突破技巧中如何运用胯下变向?\", )\n", "print(\"篮球教练回答内容:\", msg.content.answer)" ] } ], "metadata": { "kernelspec": { "display_name": "Python 3 (ipykernel)", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.11.8" } }, "nbformat": 4, "nbformat_minor": 5 } ================================================ FILE: cookbooks/appbuilder_trace/trace.ipynb ================================================ { "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# 使用Appbuilder-SDK Trace框架实现对Client的跟踪\n", "\n", "- 如果没有安装phoenix,需要先安装phoenix,这里建议使用清华源镜像安装,推荐使用4.5.0版本" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "vscode": { "languageId": "shellscript" } }, "outputs": [], "source": [ "python3 -m pip install arize-phoenix==4.5.0 -i https://pypi.tuna.tsinghua.edu.cn/simple" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "- 启动phoenix服务" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "vscode": { "languageId": "shellscript" } }, "outputs": [], "source": [ "appbuilder_trace_server" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "- ctrl+鼠标左键点击http://localhost:8080/进入可视化界面,跟踪的信息将在这里可视化展示\n", "![phoenix可视化界面](https://bj.bcebos.com/v1/appbuilder-sdk-components/Phoenix%E5%8F%AF%E8%A7%86%E5%8C%96%E7%95%8C%E9%9D%A2%EF%BC%881%EF%BC%89.png?authorization=bce-auth-v1%2FALTAKGa8m4qCUasgoljdEDAzLm%2F2024-07-22T04%3A41%3A00Z%2F-1%2Fhost%2F19a246ca50757aa64a3ccabfac0c8cd93730a08599201dd81e9de9bb2f9bb2a3)\n", "- 使用ctrl+c停止phoenix服务\n", "\n", "### 启动Appbuilder-SDK TRACE" ] }, { "cell_type": "code", "execution_count": 1, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[2024-07-03 11:10:00,040.040] tracer.py [line:128] INFO [main-9857193014994891849] OTLPSpanExporter endpoint: http://localhost:8080/v1/traces\n" ] } ], "source": [ "from appbuilder import AppBuilderTracer\n", "tracer=AppBuilderTracer(\n", " enable_phoenix = True,\n", " enable_console = False,\n", " )" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "- enable_phoenix:是否启动phoenix可视化跟踪\n", "- enable_console:是否将trace信息反馈到控制台" ] }, { "cell_type": "code", "execution_count": 2, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[2024-07-03 11:10:03,800.800] tracer.py [line:162] INFO [main-13600015437371441059] AppBuilder Starting trace...\n", "answer='' events=[Event(code=0, message='', status='done', event_type='function_call', content_type='function_call', detail={'text': {'arguments': {}, 'component_code': 'ChatAgent', 'component_name': '聊天助手'}}, usage=None)]\n", "answer='' events=[Event(code=0, message='', status='preparing', event_type='ChatAgent', content_type='status', detail={}, usage=None)]\n", "answer='作为植物' events=[Event(code=0, message='', status='running', event_type='ChatAgent', content_type='text', detail={'text': '作为植物'}, usage=Usage(prompt_tokens=77, completion_tokens=0, total_tokens=77, name='ERNIE-4.0-8K'))]\n", "answer='识别专家,我可以帮助您识别各种植物种类。' events=[Event(code=0, message='', status='running', event_type='ChatAgent', content_type='text', detail={'text': '识别专家,我可以帮助您识别各种植物种类。'}, usage=Usage(prompt_tokens=77, completion_tokens=0, total_tokens=77, name='ERNIE-4.0-8K'))]\n", "answer='如果您提供植物的图片或详细描述,我可以利用植物识别组件来分析并确定植物的种类,为您提供准确、专业的识别结果。' events=[Event(code=0, message='', status='running', event_type='ChatAgent', content_type='text', detail={'text': '如果您提供植物的图片或详细描述,我可以利用植物识别组件来分析并确定植物的种类,为您提供准确、专业的识别结果。'}, usage=Usage(prompt_tokens=77, completion_tokens=0, total_tokens=77, name='ERNIE-4.0-8K'))]\n", "answer='无论是常见的花卉、树木,还是稀有的植物品种,我都可以尽力为您提供识别服务。' events=[Event(code=0, message='', status='running', event_type='ChatAgent', content_type='text', detail={'text': '无论是常见的花卉、树木,还是稀有的植物品种,我都可以尽力为您提供识别服务。'}, usage=Usage(prompt_tokens=77, completion_tokens=0, total_tokens=77, name='ERNIE-4.0-8K'))]\n", "answer='' events=[Event(code=0, message='', status='done', event_type='ChatAgent', content_type='text', detail={'text': ''}, usage=Usage(prompt_tokens=77, completion_tokens=60, total_tokens=137, name='ERNIE-4.0-8K'))]\n", "answer='' events=[Event(code=0, message='', status='success', event_type='ChatAgent', content_type='status', detail={}, usage=None)]\n", "answer='' events=[]\n", "[2024-07-03 11:10:11,965.965] tracer.py [line:166] INFO [main-9471189008456186581] AppBuilder Ending trace...\n" ] }, { "name": "stderr", "output_type": "stream", "text": [ "INFO:appbuilder:AppBuilder Ending trace...\n" ] } ], "source": [ "# 启动trace \n", "import os\n", "import appbuilder\n", "\n", "tracer.start_trace()\n", "\n", "# 这里将APPBUILDER_TOKEN与app_id更换为你的APPBUILDER_TOKEN和app_id\n", "os.environ[\"APPBUILDER_TOKEN\"] = \"YOUR_APPBUILDER_TOKEN\"\n", "app_id = \"YOUR_APP_ID\"\n", "\n", "builder = appbuilder.AppBuilderClient(app_id)\n", "conversation_id = builder.create_conversation()\n", "msg = builder.run(conversation_id=conversation_id, query=\"你可以做什么?\",stream=True)\n", "\n", "for m in msg.content:\n", " print(m)\n", "\n", "# 结束trace\n", "tracer.end_trace()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### phoneix可视化跟踪界面展示\n", "![phoenix可视化页面展示结果](https://bj.bcebos.com/v1/appbuilder-sdk-components/Phoenix%E5%8F%AF%E8%A7%86%E5%8C%96%E7%95%8C%E9%9D%A2%EF%BC%882%EF%BC%89.png?authorization=bce-auth-v1%2FALTAKGa8m4qCUasgoljdEDAzLm%2F2024-07-22T04%3A41%3A31Z%2F-1%2Fhost%2F86460e40ecab90c50168da46ca0cf79f6179696943e1a1546f9a9ce6d34b8063)\n", "- 可以在可视化界面查看跟踪信息如Client组件的调用链路,输入输出、消耗token数等信息\n", "- 点击某个调用链路,可以查看该调用链路详细信息,流式运行过程,HTTP-POST节点展示curl命令\n", "![phoenix可视化页面节点展示结果](https://bj.bcebos.com/v1/appbuilder-sdk-components/Phoenix%E5%8F%AF%E8%A7%86%E5%8C%96%E7%95%8C%E9%9D%A2%EF%BC%883%EF%BC%89.png?authorization=bce-auth-v1%2FALTAKGa8m4qCUasgoljdEDAzLm%2F2024-07-22T04%3A41%3A46Z%2F-1%2Fhost%2F096835857c7de8714250a260a0373e69938c91d5452e3955d3f4b2ca298b8bcc)" ] } ], "metadata": { "kernelspec": { "display_name": "Python 3", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.9.12" } }, "nbformat": 4, "nbformat_minor": 2 } ================================================ FILE: cookbooks/components/agent_runtime.ipynb ================================================ { "cells": [ { "attachments": {}, "cell_type": "markdown", "id": "f802e64d-4eaa-445d-a48a-1042a91bc394", "metadata": { "tags": [] }, "source": [ "# 基于AgentRuntime服务化组件\n", "\n", "## 目标\n", "使用 AgentRuntime 对组件进行服务化。\n", "\n", "AgentRuntime 是对组件(Component)的服务化封装,具体有如下几个功能:\n", "- 一键服务化组件: 使得组件能够以服务的形式运行,支持 API 调用和对话框交互。\n", "- Session 数据管理: 提供 Session 数据的管理功能,允许跟踪和存储用户会话数据。\n", "- 请求时鉴权: 支持在请求时进行认证,确保安全性。\n", "\n", "\n", "## 准备工作\n", "### 安装Python SDK\n", "\n", "appbuilder 支持使用 pip 安装(要求Python >= 3.8),并且 AgentRuntime 服务化组件依赖 `appbuilder-sdk[serve]`" ] }, { "cell_type": "code", "execution_count": null, "id": "2939356f-61c2-42e9-9e0c-fc6729c193f6", "metadata": { "vscode": { "languageId": "shellscript" } }, "outputs": [], "source": [ "pip install appbuilder-sdk 'appbuilder-sdk[serve]'" ] }, { "attachments": {}, "cell_type": "markdown", "id": "aeb2fa55-075f-48df-a9fb-8b40d9900684", "metadata": {}, "source": [ "## 基本用法\n", "\n", "### 快速开始\n", "\n", "下面的示例会基于 Playground 组件,在 8091 端口部署 Web 服务: " ] }, { "cell_type": "code", "execution_count": null, "id": "41559341-fd7a-478c-a08b-1477d79e9d41", "metadata": { "ExecuteTime": { "end_time": "2023-12-18T06:24:26.982459Z", "start_time": "2023-12-18T06:23:53.771345Z" } }, "outputs": [], "source": [ "import os\n", "import appbuilder\n", "\n", "# 使用组件之前,请前往千帆AppBuilder官网创建密钥,流程详见:https://cloud.baidu.com/doc/AppBuilder/s/Olq6grrt6#1、创建密钥\n", "os.environ[\"APPBUILDER_TOKEN\"] = '...'\n", "\n", "component = appbuilder.Playground(\n", " prompt_template=\"{query}\",\n", " model=\"ERNIE-Bot\"\n", ")\n", "\n", "agent = appbuilder.AgentRuntime(component=component)\n", "agent.serve(port=8091)" ] }, { "cell_type": "markdown", "id": "b71e24eb", "metadata": {}, "source": [ "通过 Shell 命令测试启动的服务, 请求 Body 为组件 run 方法的入参:\n" ] }, { "cell_type": "code", "execution_count": null, "id": "12c71fa5", "metadata": { "vscode": { "languageId": "shellscript" } }, "outputs": [], "source": [ "curl --location 'http://0.0.0.0:8091/chat' \\\n", "--header 'Content-Type: application/json' \\\n", "--data '{\n", " \"message\": \"海淀区的面积是多少\",\n", " \"stream\": false\n", "}'" ] }, { "attachments": {}, "cell_type": "markdown", "id": "5fc5bc38-6bc5-4187-a8fd-f802d77d89fa", "metadata": {}, "source": [ "## AgentRuntime 参数说明" ] }, { "cell_type": "markdown", "id": "c2364c35", "metadata": {}, "source": [ "### 1. 类初始化参数说明\n", "\n", "AgentRuntime 初始化接受两个参数。\n", "\n", "| 参数名称 | 参数类型 | 是否必须 | 描述 | 示例值 |\n", "|--|--|--|--|--|\n", "| component | Component | 是 | 可运行的 Component, 该 Component 需要实现 run(message, stream, **args) 方法。 | Playground(prompt_template=\"{query}\", model=\"ERNIE-Bot\") |\n", "| user_session_config | sqlalchemy.engine.URL\\|Str\\|None | 否 | 会话 Session 数据存储的数据库配置,遵循 sqlalchemy 后端定义,可参考[文档](https://docs.sqlalchemy.org/en/20/core/engines.html#backend-specific-urls)。默认使用 sqlite:///user_session.db,即本地的 SQLite 存储 | \"sqlite:///user_session.db\" |" ] }, { "cell_type": "markdown", "id": "62e1af06", "metadata": {}, "source": [ "### 2. API 服务参数\n", "\n", "#### 2.1 请求参数\n", "\n", "**接口定义**\n", "\n", "| URL | Method |\n", "|--|--|\n", "| /chat | POST |\n", "\n", "**Header 参数**\n", "\n", "| 参数名称 | 是否必须 | 描述 | 示例值 |\n", "|--|--|--|--|\n", "| Content-Type | 是 | 必须设置为\"application/json\" | \"application/json\" |\n", "| X-Appbuilder-Token | 否 | 开启请求时认证能力时需要带入 APPBUILDER_TOKEN 进行鉴权 | 前往千帆AppBuilder官网创建密钥,流程详见[文档](https://cloud.baidu.com/doc/AppBuilder/s/Olq6grrt6#1、创建密钥) |\n", "\n", "**Body 参数**\n", "\n", "| 参数名称 | 参数类型 | 是否必须 | 描述 | 示例值 |\n", "|--|--|--|--|--|\n", "| message | Any | 是 | 透传到 component 的 run 方法的 message 参数 | \"海淀区的面积是多少\" |\n", "| stream | Bool | 否 | 是否流式调用。透传到 component 的 run 方法的 stream 参数。默认为 false | false |\n", "| session_id | Str | 否 | 用于标示同一个会话(Session)。如果不传该值,后端会自动生成 session_id,在响应参数中返回 | \"99680089-5acb-4298-9ade-a1a3f6c28102\" |\n", "| 其他参数 | Any | 否 | 透传到 component 的 run 方法 | - |\n", "\n", "\n", "#### 2.2 响应参数\n", "分为非流式响应和流式响应。\n", "\n", "**非流式响应**\n", "\n", "| 参数名称 | 参数类型 | 描述 | 示例值 |\n", "|--|--|--|--|\n", "| code | Int | 错误码。值为0表示成功,否则为失败。非0错误详见错误码部分描述 | 0 |\n", "| message | Str | 错误信息描述。 | \"Missing input variable query in message ['海淀区的面积是多少']\" |\n", "| result | Object | 请求结果 | - |\n", "| + answer_message | Object | 组件返回值,由返回的 Message 序列化得到 | {\"content\":\"海淀区是北京市的一个区,位于北京市主城区西部和西北部,东与西城区、朝阳区相邻,南与丰台区毗连,西与石景山区、门头沟区交界,北与昌平区接壤。海淀区的面积为**431平方千米**,约占北京市总面积的2.6%。\",\"extra\":{},\"id\":\"6b4e5019-a708-4bc5-a6ec-595fb4285677\",\"mtype\":\"dict\",\"name\":\"msg\"} |\n", "| + session_id | Str | 用于标示同一个会话(Session) | \"99680089-5acb-4298-9ade-a1a3f6c28102\" |\n", "\n", "**流式响应**\n", "\n", "流式数据以追加的形式返回。流式和非流式的数据结构一致,不再描述。\n", "\n", "#### 2.3 响应示例\n", "\n", "分为非流式响应和流式响应。\n", "\n", "**非流式响应**\n", "\n", "```shell\n", "{\n", " \"code\": 0,\n", " \"message\": \"\",\n", " \"result\": {\n", " \"answer_message\": {\n", " \"content\": \"海淀区是北京市的一个区,位于北京市主城区西部和西北部,东与西城区、朝阳区相邻,南与丰台区毗连,西与石景山区、门头沟区交界,北与昌平区接壤。海淀区的面积为**431平方千米**,约占北京市总面积的2.6%。\",\n", " \"extra\": {},\n", " \"id\": \"6b4e5019-a708-4bc5-a6ec-595fb4285677\",\n", " \"mtype\": \"dict\",\n", " \"name\": \"msg\"\n", " },\n", " \"session_id\": \"99680089-5acb-4298-9ade-a1a3f6c28102\"\n", " }\n", "}\n", "```\n", "\n", "**流式响应**\n", "\n", "```shell\n", "data: {\"code\": 0, \"message\": \"\", \"result\": {\"session_id\": \"663303a9-d83d-481f-a084-872ece87989c\", \"answer_message\": {\"content\": \"海淀区\", \"extra\": {}}}}\n", "\n", "data: {\"code\": 0, \"message\": \"\", \"result\": {\"session_id\": \"663303a9-d83d-481f-a084-872ece87989c\", \"answer_message\": {\"content\": \",隶属于北京市,位于北京市主城区西部和西北部,东与西城区、朝阳区相邻,南与丰台区毗连,\", \"extra\": {}}}}\n", "\n", "data: {\"code\": 0, \"message\": \"\", \"result\": {\"session_id\": \"663303a9-d83d-481f-a084-872ece87989c\", \"answer_message\": {\"content\": \"西与石景山区、门头沟区交界,北与昌平区接壤,总面积**431平方千米**。\", \"extra\": {}}}}\n", "\n", "data: {\"code\": 0, \"message\": \"\", \"result\": {\"session_id\": \"663303a9-d83d-481f-a084-872ece87989c\", \"answer_message\": {\"content\": \"\", \"extra\": {}}}}\n", "```\n", "\n", "#### 2.4 错误码\n", "| 错误码 | 描述 |\n", "|--|--|\n", "| 400 | 客户端请求参数错误 |\n", "| 1000 | 服务端执行错误 |" ] }, { "cell_type": "markdown", "id": "61923b00", "metadata": {}, "source": [ "## 高级用法" ] }, { "cell_type": "markdown", "id": "a2303c76", "metadata": {}, "source": [ "### 1. 一键服务化组件 \n", "AgentRuntime 可以快速组件以服务的形式运行,支持 API 调用和对话框交互。\n", "\n", "**1.1 API调用**\n", "\n", "API 调用的基础用法在快速开始小结已经给出,这里不再赘述。\n", "\n", "下面介绍使用 `gunicorn` 启动生产级 Web 服务的方法,`gunicorn` 是一个适用于 UNIX 的 Python WSGI HTTP 服务器,详见[项目链接](https://github.com/benoitc/gunicorn)。\n", "\n", "首先创建 `app.py` 文件,暴露 Flask App:" ] }, { "cell_type": "code", "execution_count": null, "id": "fde5cc94", "metadata": {}, "outputs": [], "source": [ "import os\n", "import appbuilder\n", "\n", "# 使用组件之前,请前往千帆AppBuilder官网创建密钥,流程详见:https://cloud.baidu.com/doc/AppBuilder/s/Olq6grrt6#1、创建密钥\n", "os.environ[\"APPBUILDER_TOKEN\"] = '...'\n", "\n", "def get_flask_app():\n", " component = appbuilder.Playground(\n", " prompt_template=\"{query}\",\n", " model=\"ERNIE-Bot\"\n", " )\n", " agent = appbuilder.AgentRuntime(component=component)\n", " return agent.create_flask_app()" ] }, { "cell_type": "markdown", "id": "a41ef57b", "metadata": {}, "source": [ "基于 `gunicorn` 启动生产级服务:" ] }, { "cell_type": "code", "execution_count": null, "id": "2077833f", "metadata": { "vscode": { "languageId": "shellscript" } }, "outputs": [], "source": [ "# 服务工作进程数\n", "SERVER_WORKER_AMOUNT=8\n", "# 服务工作进程启动方式\n", "SERVER_WORKER_CLASS=gevent\n", "# 服务超时时间\n", "GUNICORN_TIMEOUT=60\n", "\n", "gunicorn \\\n", " --bind \"0.0.0.0:8091\" \\\n", " --workers ${SERVER_WORKER_AMOUNT} \\\n", " --worker-class ${SERVER_WORKER_CLASS} \\\n", " --timeout ${GUNICORN_TIMEOUT} \\\n", " \"app:get_flask_app()\"" ] }, { "cell_type": "markdown", "id": "673c7565", "metadata": {}, "source": [ "**1.2 对话框交互**\n", "\n", "基于 chainlit 的对话框交互对被服务化的组件的 message 参数更加严格,要求能够接受 Str 的基础类型。\n", "\n", "执行下面的代码,会启动一个 chainlit 页面,页面地址:0.0.0.0:8091" ] }, { "cell_type": "code", "execution_count": null, "id": "e485544f", "metadata": {}, "outputs": [], "source": [ "import os\n", "import appbuilder\n", "\n", "# 使用组件之前,请前往千帆AppBuilder官网创建密钥,流程详见:https://cloud.baidu.com/doc/AppBuilder/s/Olq6grrt6#1、创建密钥\n", "os.environ[\"APPBUILDER_TOKEN\"] = '...'\n", "\n", "component = appbuilder.Playground(\n", " prompt_template=\"{query}\",\n", " model=\"ERNIE-Bot\"\n", ")\n", "\n", "agent = appbuilder.AgentRuntime(component=component)\n", "agent.chainlit_demo(port=8091)" ] }, { "cell_type": "markdown", "id": "4d63bece", "metadata": {}, "source": [ "Chainlit Demo页面示意图如下所示,\n", "\n", "![chainlit demo](image/agent_runtime_with_chainlit_demo.png)" ] }, { "cell_type": "markdown", "id": "a074f367", "metadata": {}, "source": [ "**1.3 对话框交互AppBuilderClient**\n", "\n", "基于 chainlit 的对话框交互AppBuilderClient,可实现对话交互。支持工作流Agent、自主规划Agent应用。\n", "\n", "执行下面的代码,会启动一个 chainlit 页面,页面地址:0.0.0.0:8091。可在页面上上传文档(可选)、执行对话。" ] }, { "cell_type": "code", "execution_count": null, "id": "0a75e035", "metadata": {}, "outputs": [], "source": [ "import os\n", "import appbuilder\n", "\n", "# 使用组件之前,请前往千帆AppBuilder官网创建密钥,流程详见:https://cloud.baidu.com/doc/AppBuilder/s/Olq6grrt6#1、创建密钥\n", "os.environ[\"APPBUILDER_TOKEN\"] = \"...\"\n", "# 使用之前,在官网个人空间获取应用ID,如下图\n", "app_id= \"...\"\n", "client = appbuilder.AppBuilderClient(app_id)\n", "agent = appbuilder.AgentRuntime(client)\n", "agent.chainlit_agent(port=8091)" ] }, { "cell_type": "markdown", "id": "d5162e29", "metadata": {}, "source": [ "在官网个人空间获取应用ID\n", "![get app_id](../app_builder_resources/app_id.png)\n", "\n", "使用服务上传文件并对话示例图如下所示\n", "![chainlit demo](./image/agent_runtime_with_chainlit_agent.png)\n", "\n", "使用工作流Agent应用对话示例如下图所示\n", "![chainlit demo](./image/agent_runtime_with_chainlit_chatflow.png)" ] }, { "cell_type": "markdown", "id": "2392f46d", "metadata": {}, "source": [ "### 2. Session 数据管理\n", "AgentRuntime 提供 Session 数据的管理功能,允许跟踪和存储用户会话数据。一般只有在二次开发的组件需要使用该能力。\n", "\n", "**2.1 二次开发组件**\n", "\n", "二次开发的组件需要重写组件的 run(message, stream, **args)方法,并且至少需要有 message 和 stream 两个参数。\n", "\n", "下面基于 QueryRewrite 和 Playground 两个组件,开发 PlaygroundWithHistory 组件,该组件需要对会话数据进行操作。\n", "\n", "当使用 Component 独立运行时,会话数据会被存储于内存。\n" ] }, { "cell_type": "code", "execution_count": null, "id": "079048e3", "metadata": {}, "outputs": [], "source": [ "import os\n", "import logging\n", "from appbuilder.core.component import Component\n", "from appbuilder import (\n", " AgentRuntime, UserSession, Message, QueryRewrite, Playground,\n", ")\n", "\n", "# 使用组件之前,请前往千帆AppBuilder官网创建密钥,流程详见:https://cloud.baidu.com/doc/AppBuilder/s/Olq6grrt6#1、创建密钥\n", "os.environ[\"APPBUILDER_TOKEN\"] = '...'\n", "\n", "class PlaygroundWithHistory(Component):\n", " def __init__(self):\n", " super().__init__()\n", " self.query_rewrite = QueryRewrite(model=\"DeepSeek-V3.1\")\n", " self.playground = Playground(\n", " prompt_template=\"{query}\",\n", " model=\"ERNIE-Bot\"\n", " )\n", "\n", " def run(self, message: Message, stream: bool=False):\n", " user_session = UserSession()\n", " # 获取 Session 历史数据\n", " history_queries = user_session.get_history(\"query\", limit=1)\n", " history_answers = user_session.get_history(\"answer\", limit=1)\n", "\n", " # query 改写\n", " if history_queries and history_answers:\n", " history = []\n", " for query, answer in zip(history_queries, history_answers):\n", " history.extend([query.content, answer.content])\n", " logging.info(f\"history: {history}\")\n", " message = self.query_rewrite(\n", " Message(history + [message.content]), rewrite_type=\"带机器人回复\")\n", " logging.info(f\"message: {message}\") \n", "\n", " # 执行 playground\n", " answer = self.playground.run(message, stream)\n", "\n", " # 保存本轮数据\n", " user_session.append({\n", " \"query\": message,\n", " \"answer\": answer,\n", " }) \n", " return answer\n", "\n", "# component 可以独立运行,session数据会被保存于内存\n", "playground_with_history_component = PlaygroundWithHistory()\n", "print(playground_with_history_component.run(Message(\"海淀区的面积是多少\"), stream=False))" ] }, { "cell_type": "markdown", "id": "480fd56d", "metadata": {}, "source": [ "**2.2 会话数据存储数据库**\n", "\n", "使用 AgentRuntime 对 Component 服务化,会话数据会被存储于数据库。\n", "下面的代码以 SQLite 为例展示该能力,更多数据库配置详见[文档](https://docs.sqlalchemy.org/en/20/core/engines.html#backend-specific-urls)" ] }, { "cell_type": "code", "execution_count": null, "id": "111b11de", "metadata": {}, "outputs": [], "source": [ "user_session_config = \"sqlite:///foo.db\"\n", "agent = appbuilder.AgentRuntime(\n", " component=playground_with_history_component, \n", " user_session_config=user_session_config)\n", "agent.serve(port=8091)" ] }, { "cell_type": "markdown", "id": "e7dc38ec", "metadata": {}, "source": [ "### 3. 请求时鉴权\n", "AgentRuntime 支持在请求时进行认证,确保安全性。\n", "\n", "使用该能力,在初始化组件时需要设置 lazy 鉴权:" ] }, { "cell_type": "code", "execution_count": null, "id": "2125bf4f", "metadata": {}, "outputs": [], "source": [ "import appbuilder\n", "\n", "# 无需配置 APPBUILDER_TOKEN 环境变量\n", "\n", "component = appbuilder.Playground(\n", " prompt_template=\"{query}\",\n", " model=\"ERNIE-Bot\",\n", " lazy_certification=True, # 设置 lazy 鉴权,在创建时不进行认证\n", ")\n", "\n", "agent = appbuilder.AgentRuntime(component=component)\n", "agent.serve(port=8091)" ] }, { "cell_type": "markdown", "id": "bbf35a0a", "metadata": {}, "source": [ "当初始化组件时进行了 lazy 鉴权,请求时请求头必须带上 `X-Appbuilder-Token` (即Appbuilder密钥,获取流程详见[千帆AppBuilder官网创建密钥](https://cloud.baidu.com/doc/AppBuilder/s/Olq6grrt6#1、创建密钥))进行鉴权:" ] }, { "cell_type": "code", "execution_count": null, "id": "60dcfa37", "metadata": { "vscode": { "languageId": "shellscript" } }, "outputs": [], "source": [ "curl --location 'http://0.0.0.0:8091/chat' \\\n", " --header 'Content-Type: application/json' \\\n", " --header 'X-Appbuilder-Token: ...' \\\n", " --data '{\n", " \"message\": \"海淀区的面积是多少\",\n", " \"stream\": false\n", " }'" ] }, { "cell_type": "markdown", "id": "f8584416", "metadata": {}, "source": [ "### 4. 查看user_session.db储存信息\n", "\n", "\n", "使用该能力,查看用户对话信息。" ] }, { "cell_type": "code", "execution_count": 83, "id": "9bbeb156", "metadata": { "vscode": { "languageId": "shellscript" } }, "outputs": [], "source": [ "import sqlite3 \n", " \n", "# 连接到 SQLite 数据库 \n", "# 如果文件不存在,会自动在当前目录创建: \n", "user_session_path = '本地user_session.db地址' \n", "conn = sqlite3.connect(user_session_path) \n", "cursor = conn.cursor() " ] }, { "cell_type": "markdown", "id": "54cce03b", "metadata": {}, "source": [ "执行 SQL 语句,列出SQLite数据库中的所有表" ] }, { "cell_type": "code", "execution_count": 85, "id": "f4ca2963", "metadata": { "vscode": { "languageId": "shellscript" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[('appbuilder_session_messages',)]\n" ] } ], "source": [ "# 执行一条 SQL 语句,列出所有表 \n", "cursor.execute(\"SELECT name FROM sqlite_master WHERE type='table';\") \n", "print(cursor.fetchall()) " ] }, { "cell_type": "markdown", "id": "e5b838f4", "metadata": {}, "source": [ "查询appbuilder_session_messages表的列信息,appbuilder_session_messages表的列信息为:\n", "- id\n", "- session_id\n", "- request_id\n", "- message_key\n", "- message_value\n", "- created_at\n", "- updated_at\n", "- deleted" ] }, { "cell_type": "code", "execution_count": 79, "id": "1ac388d7", "metadata": { "vscode": { "languageId": "shellscript" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "id\n", "session_id\n", "request_id\n", "message_key\n", "message_value\n", "created_at\n", "updated_at\n", "deleted\n" ] } ], "source": [ "cursor.execute(\"PRAGMA table_info(appbuilder_session_messages);\") \n", "columns_info = cursor.fetchall() \n", "\n", "column_names = [info[1] for info in columns_info] # info[1]是列名的位置 \n", "for column_name in column_names: \n", " print(column_name) " ] }, { "cell_type": "markdown", "id": "3965454f", "metadata": {}, "source": [ "查询表中的特定数据【以message_value信息为例】\n", "输出content、id、token_usage等信息" ] }, { "cell_type": "code", "execution_count": 80, "id": "2e6d9e45", "metadata": { "vscode": { "languageId": "shellscript" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "{'content': '你好', 'name': 'msg', 'mtype': 'str', 'id': '90c8d150-c7b9-44a4-ac77-50dd61ee329a'}\n", "{'content': '你好,我是百度研发的知识增强大语言模型,中文名是文心一言,英文名是ERNIE Bot。我能够与人对话互动,回答问题,协助创作,高效便捷地帮助人们获取信息、知识和灵感。', 'name': 'msg', 'mtype': 'dict', 'id': '0fc6c5f7-23bf-4f25-8555-69b4155908b7', 'extra': {}, 'token_usage': {'prompt_tokens': 2, 'completion_tokens': 42, 'total_tokens': 44}}\n", "{'content': '请介绍一下你自己', 'name': 'msg', 'mtype': 'dict', 'id': '4f5cf6d1-976e-456e-a632-93c4b2550523', 'extra': {'search_db': [{'content': '带机器人回复:请你扮演一个智能搜索改写补全机器人,请根据User的搜索历史以及对应的搜索结果,对最后一句话先进行主语继承改写,然后进行上下文信息补全,注意:不要改变原文的意思,答案要尽可能简洁,不要直接回答该问题,不要输出多于的内容。\\\\n\\\\n例子:\\\\n搜索历史:\\\\nUser:今天上午你干嘛了\\\\nAssistant:去打篮球啦\\\\nUser:好玩吗?\\\\n答案:\\\\n打篮球好玩吗?', 'dataset_id': '1f777fa3-26db-4237-98d5-075abc07a84f', 'dataset_name': '多轮改写Prompt', 'document_id': '92e0f30d-1f30-46f0-8377-59ab0fb6eb93', 'document_name': '多轮改写prompt_带机器人回复.txt', 'id': '61657591-f610-44f0-84ec-67cedcb66447', 'mock_id': '1', 'position': 0, 'score': 0.511053, 'sentences': [{'content': '带机器人回复:请你扮演一个智能搜索改写补全机器人,请根据User的搜索历史以及对应的搜索结果,对最后一句话先进行主语继承改写,然后进行上下文信息补全,注意:不要改变原文的意思,答案要尽可能简洁,不要直接回答该问题,不要输出多于的内容。\\\\n\\\\n例子:\\\\n搜索历史:\\\\nUser:今天上午你干嘛了\\\\nAssistant:去打篮球啦\\\\nUser:好玩吗?', 'id': '1f777fa3-26db-4237-98d5-075abc07a84f-5992356ea8c0c05485388623218e134e-975ec17bbf8206762df7cfb24a5cd85e-97468bdaf0accef718118a2b742d5cc0', 'score': 0.628708, 'source': None}], 'title': '多轮改写prompt_带机器人回复.txt', 'tokens': 0, 'type': 'engine', 'word_count': 188}]}, 'token_usage': {'prompt_tokens': 321, 'completion_tokens': 3, 'total_tokens': 324}}\n", "{'content': '您好,我是文心一言,英文名是ERNIE Bot。我能够与人对话互动,回答问题,协助创作,高效便捷地帮助人们获取信息、知识和灵感。', 'name': 'msg', 'mtype': 'dict', 'id': 'f769c850-f4e5-4d02-a62a-766fd8c8132e', 'extra': {}, 'token_usage': {'prompt_tokens': 4, 'completion_tokens': 33, 'total_tokens': 37}}\n", "{'content': '介绍一下baidu公司', 'name': 'msg', 'mtype': 'dict', 'id': '0ff3b298-7f01-4036-927d-722e00afaf33', 'extra': {'search_db': [{'content': '带机器人回复:请你扮演一个智能搜索改写补全机器人,请根据User的搜索历史以及对应的搜索结果,对最后一句话先进行主语继承改写,然后进行上下文信息补全,注意:不要改变原文的意思,答案要尽可能简洁,不要直接回答该问题,不要输出多于的内容。\\\\n\\\\n例子:\\\\n搜索历史:\\\\nUser:今天上午你干嘛了\\\\nAssistant:去打篮球啦\\\\nUser:好玩吗?\\\\n答案:\\\\n打篮球好玩吗?', 'dataset_id': '1f777fa3-26db-4237-98d5-075abc07a84f', 'dataset_name': '多轮改写Prompt', 'document_id': '92e0f30d-1f30-46f0-8377-59ab0fb6eb93', 'document_name': '多轮改写prompt_带机器人回复.txt', 'id': '61657591-f610-44f0-84ec-67cedcb66447', 'mock_id': '1', 'position': 0, 'score': 0.511053, 'sentences': [{'content': '带机器人回复:请你扮演一个智能搜索改写补全机器人,请根据User的搜索历史以及对应的搜索结果,对最后一句话先进行主语继承改写,然后进行上下文信息补全,注意:不要改变原文的意思,答案要尽可能简洁,不要直接回答该问题,不要输出多于的内容。\\\\n\\\\n例子:\\\\n搜索历史:\\\\nUser:今天上午你干嘛了\\\\nAssistant:去打篮球啦\\\\nUser:好玩吗?', 'id': '1f777fa3-26db-4237-98d5-075abc07a84f-5992356ea8c0c05485388623218e134e-975ec17bbf8206762df7cfb24a5cd85e-97468bdaf0accef718118a2b742d5cc0', 'score': 0.628708, 'source': None}], 'title': '多轮改写prompt_带机器人回复.txt', 'tokens': 0, 'type': 'engine', 'word_count': 188}]}, 'token_usage': {'prompt_tokens': 910, 'completion_tokens': 3, 'total_tokens': 913}}\n", "{'content': '百度公司是中国最大的互联网搜索引擎提供商之一,也是全球领先的AI公司。以下是对百度的详细介绍:\\n\\n一、公司概况\\n\\n百度(BIDU)是一家提供中文搜索引擎的公司,由李彦宏于2000年1月在北京中关村创立。经过多年的发展,百度已经从单一的搜索引擎服务商成功转型为内容生态与人工智能(AI)融合的互联网公司。百度的使命是“用科技让复杂的世界更简单”,其核心价值观包括“简单可依赖”。\\n\\n二、主要业务与产品\\n\\n1. 搜索业务:百度搜索是中国最大的中文搜索引擎,每天响应来自全球各地的搜索请求。除了传统的网页、图片、视频等搜索结果外,还提供了知识图谱、语音搜索等创新功能。\\n2. 移动生态业务:百度APP是百度移动生态的核心产品,围绕看、搜、听、问、购等核心场景为用户提供服务。此外,百度还拥有信息流、智能小程序、百度知道、百度文库等一系列移动生态产品。\\n3. 智能云业务:百度智能云是百度提供的云计算服务平台,为企业提供计算、存储、网络等基础设施服务以及人工智能、大数据等中间件服务。\\n4. 智能驾驶业务:百度在自动驾驶领域具有领先地位,其Apollo自动驾驶平台已经发展出多种商业模式,包括自动驾驶技术解决方案、百度造车以及共享无人车等。\\n\\n三、财务状况与业绩表现\\n\\n根据百度发布的财报显示,其业绩表现亮眼。例如,在2023年,百度总营收达到了显著的水平,其中百度核心收入同比增长。这主要得益于公司在广告市场的持续领先地位以及非在线营销收入的增长。同时,百度在研发投入方面也保持了较高水平,以推动其AI技术的持续创新和发展。\\n\\n四、AI技术与创新\\n\\n百度在AI技术方面取得了显著成果。其文心大模型已经升级到4.0版本,用户规模超过了1亿。这一技术使得百度具备了与全球领先的AI产品相媲美的能力。此外,百度还在文字生成视频等领域进行了战略投资,以进一步拓展其业务范围并加强在AI领域的领先地位。\\n\\n综上所述,百度公司作为中国最大的互联网搜索引擎提供商和全球领先的AI公司之一,凭借其强大的技术实力和创新能力,在搜索、移动生态、智能云和智能驾驶等领域取得了显著的成果。', 'name': 'msg', 'mtype': 'dict', 'id': 'c4f02188-1206-4c02-be8e-1c5481428003', 'extra': {}, 'token_usage': {'prompt_tokens': 4, 'completion_tokens': 456, 'total_tokens': 460}}\n" ] } ], "source": [ "import json\n", "cursor.execute(\"SELECT message_value FROM appbuilder_session_messages;\") \n", "for row in cursor.fetchall(): \n", " print(json.loads(row[0]))" ] }, { "cell_type": "markdown", "id": "5ff82880", "metadata": {}, "source": [ "以id查询相关的agent_runtime信息" ] }, { "cell_type": "code", "execution_count": 87, "id": "e79e2554", "metadata": { "vscode": { "languageId": "shellscript" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "16010b88-d766-4524-81ee-37f96ceadb4d\n", "b2c9d058-4475-4258-ad90-4334f3d024d5\n", "0bdafb3d-f7e3-4187-bc1d-63cf51fbda29\n", "query\n", "{'content': '你好', 'name': 'msg', 'mtype': 'str', 'id': '90c8d150-c7b9-44a4-ac77-50dd61ee329a'}\n", "2024-07-30 15:01:10.949475\n", "2024-07-30 15:01:10.949485\n", "0\n", "4bd85fd0-2e5c-4de1-a47e-ea122f7e928c\n", "b2c9d058-4475-4258-ad90-4334f3d024d5\n", "0bdafb3d-f7e3-4187-bc1d-63cf51fbda29\n", "answer\n", "{'content': '你好,我是百度研发的知识增强大语言模型,中文名是文心一言,英文名是ERNIE Bot。我能够与人对话互动,回答问题,协助创作,高效便捷地帮助人们获取信息、知识和灵感。', 'name': 'msg', 'mtype': 'dict', 'id': '0fc6c5f7-23bf-4f25-8555-69b4155908b7', 'extra': {}, 'token_usage': {'prompt_tokens': 2, 'completion_tokens': 42, 'total_tokens': 44}}\n", "2024-07-30 15:01:10.955875\n", "2024-07-30 15:01:10.955884\n", "0\n", "d6e433fc-ef4d-4ade-9a63-fec600e95481\n", "b2c9d058-4475-4258-ad90-4334f3d024d5\n", "6300b76b-2307-4ed3-9f6d-e61dfc621ff8\n", "query\n", "{'content': '请介绍一下你自己', 'name': 'msg', 'mtype': 'dict', 'id': '4f5cf6d1-976e-456e-a632-93c4b2550523', 'extra': {'search_db': [{'content': '带机器人回复:请你扮演一个智能搜索改写补全机器人,请根据User的搜索历史以及对应的搜索结果,对最后一句话先进行主语继承改写,然后进行上下文信息补全,注意:不要改变原文的意思,答案要尽可能简洁,不要直接回答该问题,不要输出多于的内容。\\\\n\\\\n例子:\\\\n搜索历史:\\\\nUser:今天上午你干嘛了\\\\nAssistant:去打篮球啦\\\\nUser:好玩吗?\\\\n答案:\\\\n打篮球好玩吗?', 'dataset_id': '1f777fa3-26db-4237-98d5-075abc07a84f', 'dataset_name': '多轮改写Prompt', 'document_id': '92e0f30d-1f30-46f0-8377-59ab0fb6eb93', 'document_name': '多轮改写prompt_带机器人回复.txt', 'id': '61657591-f610-44f0-84ec-67cedcb66447', 'mock_id': '1', 'position': 0, 'score': 0.511053, 'sentences': [{'content': '带机器人回复:请你扮演一个智能搜索改写补全机器人,请根据User的搜索历史以及对应的搜索结果,对最后一句话先进行主语继承改写,然后进行上下文信息补全,注意:不要改变原文的意思,答案要尽可能简洁,不要直接回答该问题,不要输出多于的内容。\\\\n\\\\n例子:\\\\n搜索历史:\\\\nUser:今天上午你干嘛了\\\\nAssistant:去打篮球啦\\\\nUser:好玩吗?', 'id': '1f777fa3-26db-4237-98d5-075abc07a84f-5992356ea8c0c05485388623218e134e-975ec17bbf8206762df7cfb24a5cd85e-97468bdaf0accef718118a2b742d5cc0', 'score': 0.628708, 'source': None}], 'title': '多轮改写prompt_带机器人回复.txt', 'tokens': 0, 'type': 'engine', 'word_count': 188}]}, 'token_usage': {'prompt_tokens': 321, 'completion_tokens': 3, 'total_tokens': 324}}\n", "2024-07-30 15:01:19.161269\n", "2024-07-30 15:01:19.161272\n", "0\n", "f0d76f00-93be-4d7c-a6b3-a9583fd677ad\n", "b2c9d058-4475-4258-ad90-4334f3d024d5\n", "6300b76b-2307-4ed3-9f6d-e61dfc621ff8\n", "answer\n", "{'content': '您好,我是文心一言,英文名是ERNIE Bot。我能够与人对话互动,回答问题,协助创作,高效便捷地帮助人们获取信息、知识和灵感。', 'name': 'msg', 'mtype': 'dict', 'id': 'f769c850-f4e5-4d02-a62a-766fd8c8132e', 'extra': {}, 'token_usage': {'prompt_tokens': 4, 'completion_tokens': 33, 'total_tokens': 37}}\n", "2024-07-30 15:01:19.163405\n", "2024-07-30 15:01:19.163411\n", "0\n", "936c394a-a3fa-48fd-a72f-b1778ebc35e4\n", "b2c9d058-4475-4258-ad90-4334f3d024d5\n", "5eb09e91-6496-44d9-9303-a4790e97f61c\n", "query\n", "{'content': '介绍一下baidu公司', 'name': 'msg', 'mtype': 'dict', 'id': '0ff3b298-7f01-4036-927d-722e00afaf33', 'extra': {'search_db': [{'content': '带机器人回复:请你扮演一个智能搜索改写补全机器人,请根据User的搜索历史以及对应的搜索结果,对最后一句话先进行主语继承改写,然后进行上下文信息补全,注意:不要改变原文的意思,答案要尽可能简洁,不要直接回答该问题,不要输出多于的内容。\\\\n\\\\n例子:\\\\n搜索历史:\\\\nUser:今天上午你干嘛了\\\\nAssistant:去打篮球啦\\\\nUser:好玩吗?\\\\n答案:\\\\n打篮球好玩吗?', 'dataset_id': '1f777fa3-26db-4237-98d5-075abc07a84f', 'dataset_name': '多轮改写Prompt', 'document_id': '92e0f30d-1f30-46f0-8377-59ab0fb6eb93', 'document_name': '多轮改写prompt_带机器人回复.txt', 'id': '61657591-f610-44f0-84ec-67cedcb66447', 'mock_id': '1', 'position': 0, 'score': 0.511053, 'sentences': [{'content': '带机器人回复:请你扮演一个智能搜索改写补全机器人,请根据User的搜索历史以及对应的搜索结果,对最后一句话先进行主语继承改写,然后进行上下文信息补全,注意:不要改变原文的意思,答案要尽可能简洁,不要直接回答该问题,不要输出多于的内容。\\\\n\\\\n例子:\\\\n搜索历史:\\\\nUser:今天上午你干嘛了\\\\nAssistant:去打篮球啦\\\\nUser:好玩吗?', 'id': '1f777fa3-26db-4237-98d5-075abc07a84f-5992356ea8c0c05485388623218e134e-975ec17bbf8206762df7cfb24a5cd85e-97468bdaf0accef718118a2b742d5cc0', 'score': 0.628708, 'source': None}], 'title': '多轮改写prompt_带机器人回复.txt', 'tokens': 0, 'type': 'engine', 'word_count': 188}]}, 'token_usage': {'prompt_tokens': 910, 'completion_tokens': 3, 'total_tokens': 913}}\n", "2024-07-30 15:02:21.551493\n", "2024-07-30 15:02:21.551529\n", "0\n", "5cd9d7ef-e26f-48ca-bd55-de2861cd4e84\n", "b2c9d058-4475-4258-ad90-4334f3d024d5\n", "5eb09e91-6496-44d9-9303-a4790e97f61c\n", "answer\n", "{'content': '百度公司是中国最大的互联网搜索引擎提供商之一,也是全球领先的AI公司。以下是对百度的详细介绍:\\n\\n一、公司概况\\n\\n百度(BIDU)是一家提供中文搜索引擎的公司,由李彦宏于2000年1月在北京中关村创立。经过多年的发展,百度已经从单一的搜索引擎服务商成功转型为内容生态与人工智能(AI)融合的互联网公司。百度的使命是“用科技让复杂的世界更简单”,其核心价值观包括“简单可依赖”。\\n\\n二、主要业务与产品\\n\\n1. 搜索业务:百度搜索是中国最大的中文搜索引擎,每天响应来自全球各地的搜索请求。除了传统的网页、图片、视频等搜索结果外,还提供了知识图谱、语音搜索等创新功能。\\n2. 移动生态业务:百度APP是百度移动生态的核心产品,围绕看、搜、听、问、购等核心场景为用户提供服务。此外,百度还拥有信息流、智能小程序、百度知道、百度文库等一系列移动生态产品。\\n3. 智能云业务:百度智能云是百度提供的云计算服务平台,为企业提供计算、存储、网络等基础设施服务以及人工智能、大数据等中间件服务。\\n4. 智能驾驶业务:百度在自动驾驶领域具有领先地位,其Apollo自动驾驶平台已经发展出多种商业模式,包括自动驾驶技术解决方案、百度造车以及共享无人车等。\\n\\n三、财务状况与业绩表现\\n\\n根据百度发布的财报显示,其业绩表现亮眼。例如,在2023年,百度总营收达到了显著的水平,其中百度核心收入同比增长。这主要得益于公司在广告市场的持续领先地位以及非在线营销收入的增长。同时,百度在研发投入方面也保持了较高水平,以推动其AI技术的持续创新和发展。\\n\\n四、AI技术与创新\\n\\n百度在AI技术方面取得了显著成果。其文心大模型已经升级到4.0版本,用户规模超过了1亿。这一技术使得百度具备了与全球领先的AI产品相媲美的能力。此外,百度还在文字生成视频等领域进行了战略投资,以进一步拓展其业务范围并加强在AI领域的领先地位。\\n\\n综上所述,百度公司作为中国最大的互联网搜索引擎提供商和全球领先的AI公司之一,凭借其强大的技术实力和创新能力,在搜索、移动生态、智能云和智能驾驶等领域取得了显著的成果。', 'name': 'msg', 'mtype': 'dict', 'id': 'c4f02188-1206-4c02-be8e-1c5481428003', 'extra': {}, 'token_usage': {'prompt_tokens': 4, 'completion_tokens': 456, 'total_tokens': 460}}\n", "2024-07-30 15:02:21.557667\n", "2024-07-30 15:02:21.557671\n", "0\n" ] } ], "source": [ "cursor.execute(\"SELECT * FROM appbuilder_session_messages WHERE session_id = 'b2c9d058-4475-4258-ad90-4334f3d024d5';\") \n", "for tuple in cursor.fetchall():\n", " for message in tuple:\n", " try: \n", " message = json.loads(message)\n", " print(message)\n", " except:\n", " print(message)" ] } ], "metadata": { "kernelspec": { "display_name": "Python 3 (ipykernel)", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.9.12" } }, "nbformat": 4, "nbformat_minor": 5 } ================================================ FILE: cookbooks/components/asr.ipynb ================================================ { "cells": [ { "cell_type": "markdown", "metadata": { "collapsed": true, "pycharm": { "name": "#%% md\n" } }, "source": [ "# 短语音识别组件\n", "\n", "## 目标\n", "使用短语音识别组件对输入的语音文件进行识别,返回识别的文字。\n", "\n", "## 准备工作\n", "### 平台注册\n", "1.先在appbuilder平台注册,获取token\n", "\n", "2.安装appbuilder-sdk" ] }, { "cell_type": "code", "execution_count": null, "outputs": [], "source": [ "!pip install appbuilder-sdk" ], "metadata": { "collapsed": false, "pycharm": { "name": "#%%\n" } } }, { "cell_type": "markdown", "source": [ "## 基本用法\n", "\n", "### 快速开始\n", "\n", "下面是短语音识别的代码示例:" ], "metadata": { "collapsed": false } }, { "cell_type": "code", "execution_count": null, "outputs": [], "source": [ "import os\n", "import requests\n", "import appbuilder\n", "# 设置环境变量和初始化\n", "# 请前往千帆AppBuilder官网创建密钥,流程详见:https://cloud.baidu.com/doc/AppBuilder/s/Olq6grrt6#1%E3%80%81%E5%88%9B%E5%BB%BA%E5%AF%86%E9%92%A5\n", "os.environ[\"APPBUILDER_TOKEN\"] = \"...\"\n", "\n", "asr = appbuilder.ASR()\n", "\n", "audio_file_url = \"https://bj.bcebos.com/v1/appbuilder/asr_test.pcm?authorization=bce-auth-v1\" \\\n", " \"%2FALTAKGa8m4qCUasgoljdEDAzLm%2F2024-01-11T10%3A56%3A41Z%2F-1%2Fhost\" \\\n", " \"%2Fa6c4d2ca8a3f0259f4cae8ae3fa98a9f75afde1a063eaec04847c99ab7d1e411\"\n", "audio_data = requests.get(audio_file_url).content\n", "content_data = {\"audio_format\": \"pcm\", \"raw_audio\": audio_data, \"rate\": 16000}\n", "msg = appbuilder.Message(content_data)\n", "out = asr.run(msg)\n", "print(out.content)" ], "metadata": { "collapsed": false, "pycharm": { "name": "#%%\n" } } }, { "cell_type": "markdown", "source": [ "## 参数说明\n", "\n", "### 鉴权配置\n", "使用组件之前,请首先申请并设置鉴权参数,可参考[组件使用流程](https://cloud.baidu.com/doc/AppBuilder/s/Olq6grrt6#1%E3%80%81%E5%88%9B%E5%BB%BA%E5%AF%86%E9%92%A5)。\n", "```python\n", "# 设置环境中的TOKEN,以下示例略\n", "os.environ[\"APPBUILDER_TOKEN\"] = \"bce-YOURTOKEN\"\n", "```\n", "\n", "### 初始化参数\n", "\n", "无\n", "\n", "### 调用参数\n", "\n", "|参数名称 |参数类型 |是否必须 |描述 | 示例值 |\n", "|--------|--------|--------|----|--------|\n", "|message |String |是 |输入的消息,用于模型的主要输入内容。这是一个必需的参数| Message(content={\"raw_audio\": b\"...\"}) |\n", "|audio_format|String|是 |定义语言文件的格式,包括\"pcm\"、\"wav\"、\"amr\"、\"m4a\",默认值为\"pcm\"| pcm |\n", "|rate|Integer|是 |定义录音采样率,固定值16000| 16000 |\n", "|timeout| Float | 否 | HTTP超时时间,单位:秒 |1|\n", "|retry|Integer|是 |HTTP重试次数| 3 |\n", "\n", "### 响应参数\n", "|参数名称 | 参数类型 |描述 |示例值|\n", "|--------|--------------|----|------|\n", "|result | List[String] |返回结果|[\"北京科技馆。\"]|\n", "\n", "### 响应示例\n", "```json\n", "{\"result\": [\"北京科技馆。\"]}\n", "```\n", "### 错误码\n", "| 错误码 |描述|\n", "|---|---|\n", "| 0 |success|\n", "| 2000 |data empty|" ], "metadata": { "collapsed": false, "pycharm": { "name": "#%% md\n" } } } ], "metadata": { "kernelspec": { "display_name": "Python 3", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 2 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython2", "version": "2.7.6" } }, "nbformat": 4, "nbformat_minor": 0 } ================================================ FILE: cookbooks/components/gbi.ipynb ================================================ { "cells": [ { "cell_type": "markdown", "id": "f802e64d-4eaa-445d-a48a-1042a91bc394", "metadata": { "tags": [] }, "source": [ "# GBI\n", "\n", "## 目标\n", "通过 GBI sdk 接口完成选表和问表的能力。 \n", "\n", "## 准备工作\n", "### 平台注册\n", "1.先在appbuilder平台注册,获取token\n", "2.安装appbuilder-sdk" ] }, { "cell_type": "code", "execution_count": 1, "id": "2939356f-61c2-42e9-9e0c-fc6729c193f6", "metadata": {}, "outputs": [], "source": [ "# !pip install appbuilder-sdk" ] }, { "cell_type": "code", "execution_count": 18, "id": "4ccff03b-1567-4e8b-8e1f-9a5032690406", "metadata": {}, "outputs": [], "source": [ "import logging\n", "import os\n", "\n", "# 设置环境变量\n", "os.environ[\"APPBUILDER_TOKEN\"] = \"***\"\n" ] }, { "cell_type": "markdown", "id": "aeb2fa55-075f-48df-a9fb-8b40d9900684", "metadata": {}, "source": [ "## 开发过程" ] }, { "cell_type": "markdown", "id": "1c3c5cee", "metadata": {}, "source": [ "### 设置表的 schema" ] }, { "cell_type": "code", "execution_count": 3, "id": "d7d6440c", "metadata": {}, "outputs": [], "source": [ "SUPER_MARKET_SCHEMA = \"\"\"\n", "```\n", "CREATE TABLE `supper_market_info` (\n", " `订单编号` varchar(32) DEFAULT NULL,\n", " `订单日期` date DEFAULT NULL,\n", " `邮寄方式` varchar(32) DEFAULT NULL,\n", " `地区` varchar(32) DEFAULT NULL,\n", " `省份` varchar(32) DEFAULT NULL,\n", " `客户类型` varchar(32) DEFAULT NULL,\n", " `客户名称` varchar(32) DEFAULT NULL,\n", " `商品类别` varchar(32) DEFAULT NULL,\n", " `制造商` varchar(32) DEFAULT NULL,\n", " `商品名称` varchar(32) DEFAULT NULL,\n", " `数量` int(11) DEFAULT NULL,\n", " `销售额` int(11) DEFAULT NULL,\n", " `利润` int(11) DEFAULT NULL\n", ") ENGINE=InnoDB DEFAULT CHARSET=utf8mb4\n", "```\n", "\"\"\"\n", "\n", "PRODUCT_SALES_INFO = \"\"\"\n", "现有 mysql 表 product_sales_info, \n", "该表的用途是: 产品收入表\n", "```\n", "CREATE TABLE `product_sales_info` (\n", " `年` int,\n", " `月` int,\n", " `产品名称` varchar,\n", " `收入` decimal,\n", " `非交付成本` decimal,\n", " `含交付毛利` decimal\n", ")\n", "```\n", "\"\"\"\n", "\n", "# schema 和表名的映射\n", "SCHEMA_MAPPING = {\n", " \"supper_market_info\": SUPER_MARKET_SCHEMA,\n", " \"PRODUCT_SALES_INFO\": PRODUCT_SALES_INFO\n", "}" ] }, { "cell_type": "markdown", "id": "463254a1", "metadata": {}, "source": [ "设置表的描述用于选表" ] }, { "cell_type": "code", "execution_count": 4, "id": "7fefcae1", "metadata": {}, "outputs": [], "source": [ "table_descriptions = {\n", " \"supper_market_info\": \"超市营收明细表,包含超市各种信息等\",\n", " \"product_sales_info\": \"产品销售表\"\n", "}" ] }, { "cell_type": "markdown", "id": "a0aff843", "metadata": {}, "source": [ "### 选表" ] }, { "cell_type": "code", "execution_count": 19, "id": "41559341-fd7a-478c-a08b-1477d79e9d41", "metadata": { "ExecuteTime": { "end_time": "2023-12-18T06:24:26.982459Z", "start_time": "2023-12-18T06:23:53.771345Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "选的表是: ['supper_market_info']\n" ] } ], "source": [ "import appbuilder\n", "from appbuilder.core.message import Message\n", "from appbuilder.core.components.gbi.basic import SessionRecord\n", "\n", "# 生成问表对象\n", "select_table = appbuilder.SelectTable(model_name=\"ERNIE-Bot 4.0\", table_descriptions=table_descriptions)\n", "query = \"列出超市中的所有数据\"\n", "msg = Message({\"query\": query})\n", "select_table_result_message = select_table(msg)\n", "print(f\"选的表是: {select_table_result_message.content}\")" ] }, { "cell_type": "markdown", "id": "16a8aa38-7a33-4e27-bca4-00900cfe1641", "metadata": {}, "source": [ "### 问表\n", "基于上面选出的表,通过获取表的 schema 进行问表" ] }, { "cell_type": "code", "execution_count": 6, "id": "9f45ef5f-6206-4b31-83c4-3c8eb2c86925", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "sql: SELECT * FROM supper_market_info;\n", "-----------------\n", "llm result: ```sql\n", "SELECT * FROM supper_market_info;\n", "```\n" ] } ], "source": [ "table_schemas = [SCHEMA_MAPPING[table_name] for table_name in select_table_result_message.content]\n", "gbi_nl2sql = appbuilder.NL2Sql(model_name=\"ERNIE-Bot 4.0\", table_schemas=table_schemas)\n", "nl2sql_result_message = gbi_nl2sql(Message({\"query\": \"列出超市中的所有数据\"}))\n", "print(f\"sql: {nl2sql_result_message.content.sql}\")\n", "print(\"-----------------\")\n", "print(f\"llm result: {nl2sql_result_message.content.llm_result}\")" ] }, { "cell_type": "markdown", "id": "b0409c46-e8c7-403a-a827-fcdc8e717be6", "metadata": {}, "source": [ "设置 session" ] }, { "cell_type": "code", "execution_count": 7, "id": "a23b8cad-f426-4074-9311-c2c33aaea07b", "metadata": {}, "outputs": [], "source": [ "session = list()\n", "session.append(SessionRecord(query=query, answer=nl2sql_result_message.content))" ] }, { "cell_type": "markdown", "id": "22b3d877-f61f-4958-a084-7507a3017e17", "metadata": {}, "source": [ "再次问表" ] }, { "cell_type": "code", "execution_count": 8, "id": "2adcb091-fb53-4364-b4d8-20564439ff51", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "sql: SELECT * FROM supper_market_info WHERE 商品类别 = '水果'\n", "-----------------\n", "llm result: ```sql\n", "SELECT * FROM supper_market_info WHERE 商品类别 = '水果'\n", "```\n" ] } ], "source": [ "nl2sql_result_message2 = gbi_nl2sql(Message({\"query\": \"查看商品类别是水果的所有数据\", \n", " \"session\": session}))\n", "print(f\"sql: {nl2sql_result_message2.content.sql}\")\n", "print(\"-----------------\")\n", "print(f\"llm result: {nl2sql_result_message2.content.llm_result}\")" ] }, { "cell_type": "markdown", "id": "9e0609ae-f2bc-43d3-9023-14e9f8618158", "metadata": {}, "source": [ "### 增加列选优化\n", "实际上数据中 \"商品类别\" 存储的是 \"新鲜水果\", 那么就可以通过列选的限制来优化 sql." ] }, { "cell_type": "code", "execution_count": 9, "id": "2a7c7923-019e-4660-9e36-4431e9d2f3a6", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "sql: SELECT * FROM supper_market_info WHERE 商品类别 = '新鲜水果'\n", "-----------------\n", "llm result: ```sql\n", "SELECT * FROM supper_market_info WHERE 商品类别 = '新鲜水果'\n", "```\n" ] } ], "source": [ "from appbuilder.core.components.gbi.basic import ColumnItem\n", "\n", "\n", "column_constraint = [ColumnItem(ori_value=\"水果\", \n", " column_name=\"商品类别\", \n", " column_value=\"新鲜水果\", \n", " table_name=\"supper_market_info\", \n", " is_like=False)]\n", "\n", "nl2sql_result_message2 = gbi_nl2sql(Message({\"query\": \"查看商品类别是水果的所有数据\",\n", " \"column_constraint\": column_constraint}))\n", "\n", "print(f\"sql: {nl2sql_result_message2.content.sql}\")\n", "print(\"-----------------\")\n", "print(f\"llm result: {nl2sql_result_message2.content.llm_result}\")" ] }, { "cell_type": "markdown", "id": "8385312c-aea1-42cd-b61b-a8d36f4f0665", "metadata": {}, "source": [ "从上面我们看到,商品类别不在是 \"水果\" 而是 修订为 \"新鲜水果\"" ] }, { "cell_type": "markdown", "id": "6e98c414-8b2b-4187-a270-3117a4f431ff", "metadata": {}, "source": [ "### 增加知识优化\n", "当计算某些特殊知识的时候,大模型是不知道的,所以需要告诉大模型具体的知识,比如:\n", "利润率的计算方式: 利润/销售额\n", "可以将该知识注入。具体示例如下:" ] }, { "cell_type": "code", "execution_count": 10, "id": "cade4693-29dc-431c-bf84-c6dc09104294", "metadata": {}, "outputs": [], "source": [ "# 注入知识\n", "gbi_nl2sql.knowledge[\"利润率\"] = \"计算方式: 利润/销售额\"" ] }, { "cell_type": "code", "execution_count": 11, "id": "1dc181e8-47a1-4b82-8bb5-ce3339be53f6", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "sql: SELECT 商品类别, SUM(利润)/SUM(销售额) AS 利润率\n", "FROM supper_market_info\n", "WHERE 商品类别 = '日用品'\n", "GROUP BY 商品类别\n", "-----------------\n", "llm result: ```sql\n", "SELECT 商品类别, SUM(利润)/SUM(销售额) AS 利润率\n", "FROM supper_market_info\n", "WHERE 商品类别 = '日用品'\n", "GROUP BY 商品类别\n", "```\n" ] } ], "source": [ "nl2sql_result_message3 = gbi_nl2sql(Message({\"query\": \"列出商品类别是日用品的利润率\"}))\n", "print(f\"sql: {nl2sql_result_message3.content.sql}\")\n", "print(\"-----------------\")\n", "print(f\"llm result: {nl2sql_result_message3.content.llm_result}\")" ] }, { "cell_type": "markdown", "id": "c5570cd9-dbaf-45cd-ab03-1a7f92e7d0d4", "metadata": {}, "source": [ "## 调整 prompt 模版\n", "有时候,我们希望定义自己的prompt, 选表和问表两个环节都支持 prompt 模版的定制化,但是必须遵循对应的 prompt 模版的格式。" ] }, { "cell_type": "markdown", "id": "6e3d4967-2b4c-437d-9d72-fb1b94bdcf59", "metadata": {}, "source": [ "### 选表 prompt 调整\n", "选表的 prompt template, 必须包含 \n", "1. {num} - 表的数量, 注意 {num} 有两个地方出现\n", "2. {table_desc} - 表的描述\n", "3. {query} - query\n", "\n", "注意: {num}, {table_desc}, {query} 表示的是占位符,**用户不需要在自定义的 prompt template 中将这些值填充上**,gbi 系统会自动根据 SelectTable 构造函数中提交的参数进行填充这些占位符,从而产生最后的给大模型的 prompt。注意 prompt template 和 prompt 的区别。\n", "\n", "* prompt template - 是带有占位符的 prompt, gbi 会根据具体参数填充到这些占位符,形成最终的 prompt\n", "* promt - 是将 prompt template 填充完占位符的结果。\n", "\n", "用户可以使用这些占位符重新设置自己的 prompt 模版,从而达到修改 prompt 的目的。\n", "具体请参考下面的 prompt template 示例:" ] }, { "cell_type": "code", "execution_count": 12, "id": "2ae6ffbc-4237-4fb2-8168-480b81bfd873", "metadata": {}, "outputs": [], "source": [ "SELECT_TABLE_PROMPT_TEMPLATE = \"\"\"\n", "你是一个专业的业务人员,下面有{num}张表,具体表名如下:\n", "{table_desc}\n", "请根据问题帮我选择上述1-{num}种的其中相关表并返回,可以为多表,也可以为单表,\n", "返回多张表请用“,”隔开\n", "返回格式请参考如下示例:\n", "问题:有多少个审核通过的投运单?\n", "回答: ```DWD_MAT_OPERATION```\n", "请严格参考示例只不要返回无关内容,直接给出最终答案后面的内容,分析步骤不要输出\n", "问题:{query}\n", "回答:\n", "\"\"\"" ] }, { "cell_type": "code", "execution_count": 13, "id": "2bbbb375-6659-4ef0-82ff-a4ace9fdd4f0", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "选的表是: ['supper_market_info']\n" ] } ], "source": [ "select_table4 = appbuilder.SelectTable(model_name=\"ERNIE-Bot 4.0\", \n", " table_descriptions=table_descriptions,\n", " prompt_template=SELECT_TABLE_PROMPT_TEMPLATE)\n", "\n", "select_table_result_message4 = select_table4(Message({\"query\":\"列出超市中的所有数据\"}))\n", "print(f\"选的表是: {select_table_result_message4.content}\")" ] }, { "cell_type": "markdown", "id": "4f3fd089-613b-4bdd-95ac-c87f89c0fc61", "metadata": {}, "source": [ "## 问表 prompt 调整\n", "问表的 prompt template 必须包含:\n", "1. {schema} - 表的 schema 信息, gbi系统使用构建 NL2Sql 对象的 table_schemas 成员来填充该占位符,在构造函数中需要填充该参数。\n", "2. {instrument} - 列选限制的信息, gbi系统会使用 `NL2Sql.__call__` 函数的 Message 中的 column_constraint 参数来填充该占位符\n", "3. {kg} - 知识, gbi系统使用构建 NL2Sql 对象的 knowledge 成员来填充该占位符,在构造函数中需要填充该参数。\n", "4. {date} - 时间, gbi系统会自动填充该占位符, 用户不需要提供\n", "5. {history_prompt} - 历史, gbi系统会使用 `NL2Sql.__call__` 函数的 Message 中的 session 参数来填充该占位符\n", "6. {query} - 当前问题, gbi系统会使用 `NL2Sql.__call__` 函数的 Message 中的 query 参数来填充该占位符\n", "\n", "\n", "注意: {schema}, {instrument}, {kg}, {date}, {history_prompt}, {query} 表示的是占位符,**用户不需要在自定义的 prompt template 中将这些值填充上**,gbi 系统会自动根据 `NL2Sql.__call__` 函数中提交的参数 或者 Nl2sql 的成员变量 进行填充这些占位符,从而产生最后的给大模型的 prompt。注意 prompt template 和 prompt 的区别。\n", "\n", "* prompt template - 是带有占位符的 prompt, gbi 会根据具体参数填充到这些占位符,形成最终的 prompt\n", "* promt - 是将 prompt template 填充完占位符的结果。\n", "\n", "用户可以使用这些占位符重新设置自己的 prompt 模版,从而达到修改 prompt 的目的。\n", "具体请参考下面的 prompt template 示例:" ] }, { "cell_type": "code", "execution_count": 14, "id": "323fbe75-62ca-44ab-9ca2-9f747939a2b5", "metadata": {}, "outputs": [], "source": [ "NL2SQL_PROMPT_TEMPLATE = \"\"\"\n", " MySql 表 Schema 如下:\n", " {schema}\n", " 请根据用户当前问题,联系历史信息,仅编写1个sql,其中 sql 语句需要使用```sql ```这种 markdown 形式给出。\n", " 请参考列选信息:\n", " {instrument}\n", " 请参考知识:\n", " {kg}\n", " 当前时间:{date}\n", " 历史信息如下:\n", " {history_prompt}\n", " 当前问题:\"{query}\"\n", " 回答:\n", "\"\"\"" ] }, { "cell_type": "code", "execution_count": 15, "id": "52436f03-e01c-456a-aaa0-5a7f1afcd9d2", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "sql: SELECT * FROM supper_market_info WHERE 商品类别 = '水果'\n", "-----------------\n", "llm result: ```sql\n", "SELECT * FROM supper_market_info WHERE 商品类别 = '水果'\n", "```\n" ] } ], "source": [ "\n", "gbi_nl2sql5 = appbuilder.NL2Sql(model_name=\"ERNIE-Bot 4.0\", table_schemas=table_schemas, prompt_template=NL2SQL_PROMPT_TEMPLATE)\n", "nl2sql_result_message5 = gbi_nl2sql5(Message({\"query\": \"查看商品类别是水果的所有数据\"}))\n", "print(f\"sql: {nl2sql_result_message5.content.sql}\")\n", "print(\"-----------------\")\n", "print(f\"llm result: {nl2sql_result_message5.content.llm_result}\")" ] } ], "metadata": { "kernelspec": { "display_name": "Python 3 (ipykernel)", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.10.11" } }, "nbformat": 4, "nbformat_minor": 5 } ================================================ FILE: cookbooks/components/general_ocr.ipynb ================================================ { "cells": [ { "cell_type": "markdown", "source": [ "# 通用文字识别-高精度版组件\n", "\n", "## 目标\n", "使用通用文字识别-高精度版组件对图片上的全部文字内容进行检测识别。\n", "\n", "## 准备工作\n", "### 平台注册\n", "1.先在appbuilder平台注册,获取token\n", "\n", "2.安装appbuilder-sdk" ], "metadata": { "collapsed": false } }, { "cell_type": "code", "execution_count": null, "outputs": [], "source": [ "!pip install appbuilder-sdk" ], "metadata": { "collapsed": false, "pycharm": { "name": "#%%\n" } } }, { "cell_type": "markdown", "source": [ "## 基本用法\n", "\n", "### 快速开始\n", "\n", "以下是一个简单的例子来演示如何开始使用GeneralOCR组件:" ], "metadata": { "collapsed": false, "pycharm": { "name": "#%% md\n" } } }, { "cell_type": "code", "execution_count": null, "outputs": [], "source": [ "import os\n", "import appbuilder\n", "import requests\n", "\n", "# 请前往千帆AppBuilder官网创建密钥,流程详见:https://cloud.baidu.com/doc/AppBuilder/s/Olq6grrt6#1%E3%80%81%E5%88%9B%E5%BB%BA%E5%AF%86%E9%92%A5\n", "os.environ[\"APPBUILDER_TOKEN\"] = '...'\n", "# 从BOS读取样例图片\n", "image_url = \"https://bj.bcebos.com/v1/appbuilder/general_ocr_test.png?\"\\\n", " \"authorization=bce-auth-v1%2FALTAKGa8m4qCUasgoljdEDAzLm%2F2024-01-\"\\\n", " \"11T10%3A59%3A17Z%2F-1%2Fhost%2F081bf7bcccbda5207c82a4de074628b04ae\"\\\n", " \"857a27513734d765495f89ffa5f73\"\n", "raw_image = requests.get(image_url).content\n", "general_ocr = appbuilder.GeneralOCR()\n", "out = general_ocr.run(appbuilder.Message(content={\"raw_image\": raw_image}))\n", "print(out.content)" ], "metadata": { "collapsed": false, "pycharm": { "name": "#%%\n" } } }, { "cell_type": "markdown", "source": [ "## 参数说明\n", "\n", "### 鉴权说明\n", "使用组件之前,请首先申请并设置鉴权参数,可参考[组件使用流程](https://cloud.baidu.com/doc/AppBuilder/s/Olq6grrt6#1%E3%80%81%E5%88%9B%E5%BB%BA%E5%AF%86%E9%92%A5)。\n", "```python\n", "# 设置环境中的TOKEN,以下示例略\n", "os.environ[\"APPBUILDER_TOKEN\"] = \"bce-YOURTOKEN\"\n", "```\n", "\n", "### 初始化参数\n", "\n", "无\n", "\n", "### 调用参数\n", "\n", "| 参数名称 | 参数类型 | 是否必须 | 描述 | 示例值 |\n", "|---------|---------|------|-----------------------------|------------------------------------------------|\n", "| message | String | 是 | 输入的消息,用于模型的主要输入内容。这是一个必需的参数 | Message(content={\"raw_image\": b\"待识别的图片字节流数据\"}) |\n", "|timeout| Float | 否 | HTTP超时时间,单位:秒 |1|\n", "| retry | Integer | 否 | HTTP重试次数 | 3 |\n", "\n", "### 响应参数\n", "| 参数名称 | 参数类型 | 描述 | 示例值 |\n", "|--------------|---------|---------|---------------------------------------------------|\n", "| words_result | Array[] | 返回结果 | [{\"words\":\"一站式企业级大模型平台,提供先进的生成式AI生产及应用全流程开发工具链\"}] |\n", "| + words | String | 识别结果字符串 | \"百度智能云千帆大模型平台\" |\n", "\n", "### 响应示例\n", "#### 示例图片\n", "![示例图片](./image/general_ocr示例.png)\n", "#### 识别结果\n", "```json\n", "{\n", " \"words_result\":[\n", " {\n", " \"words\":\"一站式企业级大模型平台,提供先进的生成式AI生产及应用全流程开发工具链\"\n", " },\n", " {\n", " \"words\":\"百度智能云千帆大模型平台\"\n", " },\n", " {\n", " \"words\":\"文心大模型4.0已正式发布,个人和企业客户可通过百度智能云千帆大模型平台接入使用\"\n", " },\n", " {\n", " \"words\":\"立即使用\"\n", " },\n", " {\n", " \"words\":\"在线体验\"\n", " },\n", " {\n", " \"words\":\"使用文档\"\n", " },\n", " {\n", " \"words\":\"定价说明\"\n", " },\n", " {\n", " \"words\":\"千帆社区\"\n", " },\n", " {\n", " \"words\":\"常见概念、使用指导\"\n", " },\n", " {\n", " \"words\":\"定价、计费方式、计量说明\"\n", " },\n", " {\n", " \"words\":\"大模型开发学习、交流社区\"\n", " }\n", " ]\n", "}\n", "```\n" ], "metadata": { "collapsed": false, "pycharm": { "name": "#%% md\n" } } } ], "metadata": { "kernelspec": { "display_name": "Python 3", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 2 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython2", "version": "2.7.6" } }, "nbformat": 4, "nbformat_minor": 0 } ================================================ FILE: cookbooks/components/object_recognize.ipynb ================================================ { "cells": [ { "cell_type": "markdown", "metadata": { "collapsed": true, "pycharm": { "name": "#%% md\n" } }, "source": [ "# 通用物体和场景识别-高级版组件\n", "\n", "## 目标\n", "使用通用物体和场景识别-高级版组件对图片上的物品或场景进行识别。\n", "\n", "## 准备工作\n", "### 平台注册\n", "1.先在appbuilder平台注册,获取token\n", "\n", "2.安装appbuilder-sdk" ] }, { "cell_type": "code", "execution_count": null, "outputs": [], "source": [ "!pip install appbuilder-sdk" ], "metadata": { "collapsed": false, "pycharm": { "name": "#%%\n" } } }, { "cell_type": "markdown", "source": [ "## 基本用法\n", "\n", "### 快速开始\n", "\n", "以下是一个简单的例子来演示如何开始使用ObjectRecognition组件:" ], "metadata": { "collapsed": false } }, { "cell_type": "code", "execution_count": null, "outputs": [], "source": [ "import os\n", "import appbuilder\n", "import requests\n", "\n", "# 请前往千帆AppBuilder官网创建密钥,流程详见:https://cloud.baidu.com/doc/AppBuilder/s/Olq6grrt6#1%E3%80%81%E5%88%9B%E5%BB%BA%E5%AF%86%E9%92%A5\n", "os.environ[\"APPBUILDER_TOKEN\"] = '...'\n", "\n", "# 从BOS读取样例图片\n", "image_url = \"https://bj.bcebos.com/v1/appbuilder/object_recognize_test.png?\"\\\n", " \"authorization=bce-auth-v1%2FALTAKGa8m4qCUasgoljdEDAzLm%2F2024-01-\"\\\n", " \"11T11%3A00%3A19Z%2F-1%2Fhost%2F2c31bf29205f61e58df661dc80af31a1dc\"\\\n", " \"1ba1de0a8f072bc5a87102bd32f9e3\"\n", "raw_image = requests.get(image_url).content\n", "# 创建物体识别组件实例\n", "object_recognition = appbuilder.ObjectRecognition()\n", "# 执行识别操作并获取结果\n", "out = object_recognition.run(appbuilder.Message(content={\"raw_image\": raw_image}))\n", "print(out.content)" ], "metadata": { "collapsed": false, "pycharm": { "name": "#%%\n" } } }, { "cell_type": "markdown", "source": [ "## 参数说明\n", "\n", "### 鉴权说明\n", "使用组件之前,请首先申请并设置鉴权参数,可参考[组件使用流程](https://cloud.baidu.com/doc/AppBuilder/s/Olq6grrt6#1%E3%80%81%E5%88%9B%E5%BB%BA%E5%AF%86%E9%92%A5)。\n", "```python\n", "# 设置环境中的TOKEN,以下示例略\n", "os.environ[\"APPBUILDER_TOKEN\"] = \"bce-YOURTOKEN\"\n", "```\n", "\n", "### 初始化参数\n", "无\n", "\n", "### 调用参数\n", "\n", "| 参数名称 | 参数类型 | 是否必须 | 描述 | 示例值 |\n", "|---------|---------|------|-----------------------------|------------------------------------------------|\n", "| message | String | 是 | 输入的消息,用于模型的主要输入内容。这是一个必需的参数 | Message(content={\"raw_image\": b\"待识别的图片字节流数据\"}) |\n", "|timeout| Float | 否 | HTTP超时时间,单位:秒 |1|\n", "| retry | Integer | 否 | HTTP重试次数 | 3 |\n", "\n", "### 响应参数\n", "| 参数名称 | 参数类型 | 描述 | 示例值 |\n", "|----------|---------|-------------|-----------------------------------------------------|\n", "| result | Array[] | 返回结果 | [{\"keyword\":\"苹果\",\"score\":0.961247,\"root\":\"植物-蔷薇科\"}] |\n", "| +keyword | String | 图片中的物体或场景名称 | \"苹果\" |\n", "| +score\t | Float | 置信度 | 0.961247 |\n", "| +root\t | String | 识别结果的上层标签 | \"植物-蔷薇科\" |\n", "\n", "\n", "### 响应示例\n", "#### 示例图片\n", "![示例图片](./image/object_recognize示例.png)\n", "#### 识别结果\n", "```json\n", "{\n", " \"result\":[\n", " {\n", " \"keyword\":\"苹果\",\n", " \"score\":0.961247,\n", " \"root\":\"植物-蔷薇科\"\n", " },\n", " {\n", " \"keyword\":\"姬娜果\",\n", " \"score\":0.740838,\n", " \"root\":\"植物-其它\"\n", " },\n", " {\n", " \"keyword\":\"梨子\",\n", " \"score\":0.392218,\n", " \"root\":\"商品-水果\"\n", " },\n", " {\n", " \"keyword\":\"车厘子\",\n", " \"score\":0.193986,\n", " \"root\":\"植物-其它\"\n", " },\n", " {\n", " \"keyword\":\"石榴\",\n", " \"score\":0.000239,\n", " \"root\":\"植物-千屈菜科\"\n", " }\n", " ]\n", "}\n", "```\n", "\n", "\n" ], "metadata": { "collapsed": false, "pycharm": { "name": "#%% md\n" } } } ], "metadata": { "kernelspec": { "display_name": "Python 3", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 2 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython2", "version": "2.7.6" } }, "nbformat": 4, "nbformat_minor": 0 } ================================================ FILE: cookbooks/components/rag_with_baidusearch.ipynb ================================================ { "cells": [ { "attachments": {}, "cell_type": "markdown", "id": "f802e64d-4eaa-445d-a48a-1042a91bc394", "metadata": { "tags": [] }, "source": [ "# 百度搜索通用问答机器人\n", "\n", "## 目标\n", "使用百度搜索,无需自建知识库,对用户的请求进行回答。\n", "\n", "用户可通过自定义人设来创建自己的问答机器人服务,并可通过开关配置拒答、澄清反问、重点强调、友好度提升、溯源等能力。\n", "\n", "## 准备工作\n", "### 平台注册\n", "\n", "1.先在appbuilder平台注册,获取token\n", "\n", "2.安装appbuilder-sdk" ] }, { "cell_type": "code", "execution_count": null, "id": "2939356f-61c2-42e9-9e0c-fc6729c193f6", "metadata": {}, "outputs": [], "source": [ "!pip install appbuilder-sdk" ] }, { "cell_type": "code", "execution_count": null, "id": "4ccff03b-1567-4e8b-8e1f-9a5032690406", "metadata": {}, "outputs": [], "source": [ "import os\n", "\n", "# 设置环境变量\n", "os.environ[\"APPBUILDER_TOKEN\"] = \"...\"\n", "\n", "print(\"init done\")\n" ] }, { "attachments": {}, "cell_type": "markdown", "id": "aeb2fa55-075f-48df-a9fb-8b40d9900684", "metadata": {}, "source": [ "## 开发过程\n", "### 配置 RAGWithBaiduSearch 组件" ] }, { "cell_type": "code", "execution_count": null, "id": "41559341-fd7a-478c-a08b-1477d79e9d41", "metadata": { "ExecuteTime": { "end_time": "2023-12-18T06:24:26.982459Z", "start_time": "2023-12-18T06:23:53.771345Z" } }, "outputs": [], "source": [ "import appbuilder\n", "\n", "# 人设指令\n", "instruction = appbuilder.Message(\"你是问答助手,在回答问题前需要加上“很高兴为您解答“\")\n", "\n", "# 能力开关\n", "reject = False # 拒答\n", "clarify = False # 澄清反问\n", "highlight = True # 重点强调\n", "friendly = False # 友好度提升\n", "cite = True # 溯源\n", "\n", "# 使用 DeepSeek-V3.1 模型\n", "component = appbuilder.RAGWithBaiduSearch(model=\"DeepSeek-V3.1\")\n", "query = appbuilder.Message(\"海淀区的面积是多少\")\n", "\n", "answer = component.run(\n", " query, instruction=instruction, reject=reject, clarify=clarify, highlight=highlight, friendly=friendly, cite=cite, stream=False)\n", "\n", "print(f\"问答结果: {answer.content}\")\n", "print(f\"检索返回: {answer.extra}\")" ] }, { "attachments": {}, "cell_type": "markdown", "id": "5fc5bc38-6bc5-4187-a8fd-f802d77d89fa", "metadata": {}, "source": [ "### (可选) 使用 AgentRuntime 启动 chainlit 页面调试\n", "这部分代码依赖 `appbuilder-sdk[serve]`,如果没有安装,可以执行下面的命令安装:" ] }, { "cell_type": "code", "execution_count": null, "id": "a10737ec", "metadata": {}, "outputs": [], "source": [ "!pip install 'appbuilder-sdk[serve]'" ] }, { "attachments": {}, "cell_type": "markdown", "id": "16a3abb2", "metadata": {}, "source": [ "执行下面的代码,会启动一个 chainlit 页面,页面地址:0.0.0.0:8091" ] }, { "cell_type": "code", "execution_count": null, "id": "d514a628-5ae3-4269-aada-eaf8b21c3793", "metadata": {}, "outputs": [], "source": [ "agent = appbuilder.AgentRuntime(component=component)\n", "# 启动 chainlit 服务\n", "agent.chainlit_demo(port=8091)" ] }, { "attachments": {}, "cell_type": "markdown", "id": "16a8aa38-7a33-4e27-bca4-00900cfe1641", "metadata": {}, "source": [ "### (可选) 使用 AgentRuntime 启动 HTTP 服务\n", "这部分代码依赖 `appbuilder-sdk[serve]`,如果没有安装,可以执行下面的命令安装:" ] }, { "cell_type": "code", "execution_count": null, "id": "f449fcb6", "metadata": {}, "outputs": [], "source": [ "!pip install 'appbuilder-sdk[serve]'" ] }, { "attachments": {}, "cell_type": "markdown", "id": "d795f905", "metadata": {}, "source": [ "执行下面的代码,会启动一个 HTTP 服务" ] }, { "cell_type": "code", "execution_count": null, "id": "9f45ef5f-6206-4b31-83c4-3c8eb2c86925", "metadata": {}, "outputs": [], "source": [ "agent.serve(port=8092)" ] }, { "attachments": {}, "cell_type": "markdown", "id": "ccd4c48f", "metadata": {}, "source": [ "测试服务" ] }, { "cell_type": "code", "execution_count": null, "id": "7313e122-5199-4c90-bc6c-ad04e206ccc9", "metadata": { "vscode": { "languageId": "shellscript" } }, "outputs": [], "source": [ "curl --location 'http://0.0.0.0:8092/chat' \\\n", "--header 'Content-Type: application/json' \\\n", "--data '{\n", " \"message\": \"海淀区的面积是多少\",\n", " \"stream\": false\n", "}'" ] } ], "metadata": { "kernelspec": { "display_name": "Python 3 (ipykernel)", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.8.9" } }, "nbformat": 4, "nbformat_minor": 5 } ================================================ FILE: cookbooks/components/text_generation.ipynb ================================================ { "cells": [ { "attachments": {}, "cell_type": "markdown", "metadata": {}, "source": [ "# 文本生成\n", "\n", "## 说明\n", "本文展示了如何使用appbuilder内置组件以及如何快速构建全新的文本生成组件。以下是一个在营销场景下生成各种文本内容的样例。\n", "\n", "## 概览\n", "具体地,本样例按照以下流程进行文本生成:\n", "1. 使用**空模板**构建一个全新的文本生成组件:商品信息生成组件。\n", "2. 输入一个商品,使用新构建的商品信息生成组件生成该商品的商品信息。\n", "3. 基于生成的商品信息,使用内置的**问答对挖掘**组件生成问答对。生成的问答对可用于客服等。\n", "4. 基于生成的商品信息,使用内置的**风格写作**组件为该商品生成一份【小红书】文案。\n", "5. 使用内置的**标签抽取**组件对生成的文案进行标签抽取。抽取出的标签可用于检索文案。\n", "\n", "以下我们会演示如何实现我们自己的定制化能力。" ] }, { "attachments": {}, "cell_type": "markdown", "metadata": {}, "source": [ "## 流程演示\n", "### Step 0: 安装Python SDK\n", "我们的appbuilder支持使用pip安装(要求Python >= 3.8):" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "vscode": { "languageId": "shellscript" } }, "outputs": [], "source": [ "pip install appbuilder-sdk" ] }, { "attachments": {}, "cell_type": "markdown", "metadata": {}, "source": [ "代码中需要配置用户的`APPBUILDER_TOKEN`。" ] }, { "cell_type": "code", "execution_count": 1, "metadata": {}, "outputs": [], "source": [ "import os\n", "\n", "# 设置环境变量\n", "os.environ['APPBUILDER_TOKEN'] = '...'" ] }, { "attachments": {}, "cell_type": "markdown", "metadata": {}, "source": [ "安装成功后,我们就可以搭建我们自己的能力了。" ] }, { "attachments": {}, "cell_type": "markdown", "metadata": {}, "source": [ "### Step 1: 商品信息生成\n", "基于appbuilder提供的**空模板**,用户可以自定义文本生成组件以解决多样化的需求。这里我们构建一个**商品信息生成**组件以生成商品信息:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "from appbuilder import Message, Playground\n", "\n", "# 输入到大模型中的prompt的模板\n", "prompt_template = \\\n", "'''输入商品名,我需要你为我生成该商品的商品信息。\n", "\n", "要求:\n", "- 你生成的商品信息应该包含多方面信息。\n", "- 开头和结尾不需要有其他与商品信息无关的内容。\n", "\n", "商品名:{product_name}\n", "商品信息:\n", "'''\n", "# 创建商品信息生成组件\n", "product_information_generation = Playground(prompt_template=prompt_template, model='DeepSeek-V3.1')\n", "\n", "# 获取商品信息\n", "# 填充prompt_template参数的参数映射表,需要与prompt_template对应\n", "prompt_template_kwargs = {\n", " 'product_name': '特斯拉Model Y'\n", "}\n", "response = product_information_generation(Message(prompt_template_kwargs), stream=False, temperature=0.5)\n", "product_information = response.content\n", "print(f'商品信息:\\n{product_information}')" ] }, { "attachments": {}, "cell_type": "markdown", "metadata": {}, "source": [ "输出结果:\n", "\n", "```\n", "商品信息:\n", "特斯拉Model Y是一款电动汽车,它拥有许多独特的功能和特性。以下是它的主要特点和优势:\n", "\n", "特斯拉Model Y是一款电动汽车,它采用纯电力驱动,没有排放和噪音污染,具有零启动加速、零延迟、零维护的特性。\n", "特斯拉Model Y拥有先进的自动驾驶技术,可以自动识别交通状况并做出相应的反应,大大提高了驾驶安全性。\n", "特斯拉Model Y的电池寿命长,充电效率高,可以在短时间内将电池充满,同时支持快速充电和慢充两种方式。\n", "特斯拉Model Y的外观设计独特,线条流畅,充满未来感,内部空间宽敞,乘坐舒适。\n", "特斯拉Model Y的价格相对较高,但性价比高,是一款非常值得购买的汽车。\n", "\n", "总之,特斯拉Model Y是一款集未来科技、安全性、舒适性和实用性于一体的电动汽车。\n", "```" ] }, { "attachments": {}, "cell_type": "markdown", "metadata": {}, "source": [ "### Step 2: 问答对生成\n", "基于Step 1生成的商品信息我们生成一些问答对,这里我们使用内置的**问答对生成**组件。" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "from appbuilder import QAPairMining\n", "\n", "# 初始化问答对生成组件\n", "qa_pair_mining = QAPairMining(model='DeepSeek-V3.1')\n", "\n", "# 获取问答对\n", "response = qa_pair_mining(Message(product_information), stream=False, temperature=1e-10)\n", "qa_pairs = response.content\n", "print(f'问答对:\\n{qa_pairs}')" ] }, { "attachments": {}, "cell_type": "markdown", "metadata": {}, "source": [ "输出结果:\n", "\n", "```\n", "问答对:\n", "问题:特斯拉Model Y有什么特点?\n", "答案:特斯拉Model Y是一款电动汽车,它采用纯电力驱动,没有排放和噪音污染,具有零启动加速、零延迟、零维护的特性。\n", "\n", "问题:特斯拉Model Y有什么优势?\n", "答案:特斯拉Model Y拥有先进的自动驾驶技术,可以自动识别交通状况并做出相应的反应,大大提高了驾驶安全性。\n", "\n", "问题:特斯拉Model Y的电池寿命如何?\n", "答案:特斯拉Model Y的电池寿命长,充电效率高,可以在短时间内将电池充满,同时支持快速充电和慢充两种方式。\n", "\n", "问题:特斯拉Model Y的外观设计如何?\n", "答案:特斯拉Model Y的外观设计独特,线条流畅,充满未来感,内部空间宽敞,乘坐舒适。\n", "\n", "问题:特斯拉Model Y的价格是多少?\n", "答案:特斯拉Model Y的价格相对较高,但性价比高,是一款非常值得购买的汽车。\n", "```" ] }, { "attachments": {}, "cell_type": "markdown", "metadata": {}, "source": [ "### Step 3: 营销文案生成\n", "基于Step 1生成的商品信息生成【小红书】文案,这里我们使用内置的**风格写作**组件。" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "from appbuilder import StyleWriting\n", "\n", "# 构造query\n", "query = \\\n", "f'''请你基于以下商品信息生成文案:\n", "{product_information}\n", "'''\n", "\n", "# 初始化风格写作组件\n", "style_writing = StyleWriting(model='DeepSeek-V3.1')\n", "\n", "# 获取小红书文案\n", "response = style_writing(Message(query), style_query='小红书', length=300)\n", "copywriting = response.content\n", "print(f'文案:\\n{copywriting}')" ] }, { "attachments": {}, "cell_type": "markdown", "metadata": {}, "source": [ "输出结果:\n", "\n", "```\n", "【特斯拉Model Y,一款值得拥有的未来科技之车!🚀】\n", "\n", "🚗Model Y作为一款电动汽车,具有许多独特的功能和特性。它采用纯电力驱动,没有排放和噪音污染,具有零启动加速、零延迟、零维护的特性。在城市道路上行驶,它就像是一阵清风,让你轻松应对各种交通状况。💨\n", "\n", "🚗特斯拉Model Y还拥有先进的自动驾驶技术,可以自动识别交通状况并做出相应的反应,大大提高了驾驶安全性。在行驶过程中,它就像是一位智能助手,为你提供安全、舒适的驾驶体验。🛡️\n", "\n", "🚗Model Y的电池寿命长,充电效率高,可以在短时间内将电池充满,同时支持快速充电和慢充两种方式。无论是长途旅行还是城市代步,它都能满足你的需求。⚡\n", "\n", "🚗Model Y的外观设计独特,线条流畅,充满未来感,内部空间宽敞,乘坐舒适。无论是驾驶还是乘坐,都能感受到它的豪华与舒适。🌟\n", "\n", "💰虽然价格相对较高,但性价比高,是一款非常值得购买的汽车。它不仅是一款车,更是一种生活方式的体现。🚗\n", "\n", "#未来科技 #特斯拉 #安全性 #舒适性 #实用性 #电动汽车\n", "```" ] }, { "attachments": {}, "cell_type": "markdown", "metadata": {}, "source": [ "### Step 4: 标签抽取\n", "基于Step 3生成的文案进行标签抽取,这里我们使用内置的**标签抽取**组件。" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "from appbuilder import TagExtraction\n", "\n", "# 初始化标签抽取组件\n", "tag_extraction = TagExtraction(model='DeepSeek-V3.1')\n", "\n", "# 获取标签\n", "response = tag_extraction(Message(copywriting), stream=False, temperature=1e-10)\n", "tags = response.content\n", "print(f'标签:\\n{tags}')" ] }, { "attachments": {}, "cell_type": "markdown", "metadata": {}, "source": [ "输出结果:\n", "\n", "```\n", "标签:\n", "1.特斯拉\n", "2.Model Y\n", "3.未来科技\n", "4.纯电力驱动\n", "5.自动驾驶\n", "6.电池寿命\n", "7.充电效率\n", "8.外观设计\n", "9.内部空间\n", "10.性价比\n", "```" ] } ], "metadata": { "kernelspec": { "display_name": "base", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.8.8" }, "orig_nbformat": 4, "vscode": { "interpreter": { "hash": "bf58028eab835c8b5fcb0ca40b311fc21e6cba5ccf47f1b42d31ca2545cde380" } } }, "nbformat": 4, "nbformat_minor": 2 } ================================================ FILE: cookbooks/components/translate.ipynb ================================================ { "cells": [ { "cell_type": "markdown", "metadata": { "collapsed": true, "pycharm": { "name": "#%% md\n" } }, "source": [ "# 文本翻译-通用版组件\n", "\n", "## 目标\n", "使用文本翻译组件将文本翻译成目标语言。\n", "\n", "## 准备工作\n", "### 平台注册\n", "1.先在appbuilder平台注册,获取token\n", "\n", "2.安装appbuilder-sdk" ] }, { "cell_type": "code", "execution_count": null, "outputs": [], "source": [ "!pip install appbuilder-sdk" ], "metadata": { "collapsed": false, "pycharm": { "name": "#%%\n" } } }, { "cell_type": "markdown", "source": [ "## 基本用法\n", "\n", "### 快速开始\n", "\n", "通过如下示例代码可以快速开始使用文本翻译组件:" ], "metadata": { "collapsed": false, "pycharm": { "name": "#%% md\n" } } }, { "cell_type": "code", "execution_count": null, "outputs": [], "source": [ "import os\n", "import appbuilder\n", "\n", "# 请前往千帆AppBuilder官网创建密钥,流程详见:https://cloud.baidu.com/doc/AppBuilder/s/Olq6grrt6#1%E3%80%81%E5%88%9B%E5%BB%BA%E5%AF%86%E9%92%A5\n", "os.environ[\"APPBUILDER_TOKEN\"] = '...'\n", "\n", "translate = appbuilder.Translation()\n", "resp = translate(appbuilder.Message(\"你好\\n中国\"), from_lang=\"zh\", to_lang=\"en\")\n", "# 输出{'from_lang': 'zh', 'to_lang': 'en', 'trans_result': [{'src': '你好', 'dst': 'hello'}, {'src': '中国', 'dst': 'China'}]}\n", "print(resp.content)" ], "metadata": { "collapsed": false, "pycharm": { "name": "#%%\n" } } }, { "cell_type": "markdown", "source": [ "## 参数说明\n", "\n", "### 鉴权配置\n", "\n", "使用组件之前,请首先申请并设置鉴权参数,可参考[组件使用流程](https://cloud.baidu.com/doc/AppBuilder/s/Olq6grrt6#1%E3%80%81%E5%88%9B%E5%BB%BA%E5%AF%86%E9%92%A5)。\n", "\n", "```python\n", "# 设置环境中的TOKEN,以下示例略\n", "os.environ[\"APPBUILDER_TOKEN\"] = \"bce-YOURTOKEN\"\n", "```\n", "\n", "### 初始化参数说明\n", "\n", "无\n", "\n", "### 调用参数说明\n", "\n", "|参数名称 |参数类型 |是否必须 |描述 | 示例值 |\n", "|--------|--------|--------|----|--------|\n", "|message |obj:Message |是 |输入的请求翻译文本| Message(\"你好\") |\n", "|from_lang|String|否 |翻译的源语言,默认为`auto`,表示自动检测语言。| zh |\n", "|to_lang|Integer|否 |需要翻译的目标语言,默认为`en`,表示英语。| en |\n", "|timeout| Float | 否 | HTTP超时时间,单位:秒 |1|\n", "|retry|Integer|否 |HTTP重试次数| 3 |\n", "\n", "### 响应参数\n", "\n", "|参数名称 |参数类型 |描述 |示例值|\n", "|--------|--------|----|------|\n", "|from_lang |String |翻译源语言| zh|\n", "|to_lang |String |翻译目标语言|en|\n", "|trans_result |List[Object] |返回结果|[{'src': '你好', 'dst': 'hello'}]|\n", "|trans_result[0].src |String |源文本|你好|\n", "|trans_result[0].dst |String |目标文本|hello|\n", "\n", "### 响应示例\n", "\n", "```json\n", "{\n", " \"from_lang\": \"zh\",\n", " \"to_lang\": \"en\",\n", " \"trans_result\": [\n", " {\n", " \"src\": \"你好\",\n", " \"dst\": \"hello\"\n", " }\n", " ]\n", "}\n", "```\n", "## 语种列表\n", "\n", "|名称 |代码 |语种检测|\n", "|----|-----|------|\n", "| 阿拉伯语 | ara | 是 |\n", "| 爱尔兰语 | gle | 是 |\n", "| 奥克语 | oci | 是 |\n", "| 阿尔巴尼亚语 | alb | 是 |\n", "| 阿尔及利亚阿拉伯语 | arq | 否 |\n", "| 阿肯语 | aka | 否 |\n", "| 阿拉贡语 | arg | 否 |\n", "| 阿姆哈拉语 | amh | 是 |\n", "| 阿萨姆语 | asm | 是 |\n", "| 艾马拉语 | aym | 否 |\n", "| 阿塞拜疆语 | aze | 是 |\n", "| 阿斯图里亚斯语 | ast | 是 |\n", "| 奥塞梯语 | oss | 否 |\n", "| 爱沙尼亚语 | est | 是 |\n", "| 奥杰布瓦语 | oji | 否 |\n", "| 奥里亚语 | ori | 是 |\n", "| 奥罗莫语 | orm | 否 |\n", "| 波兰语 | pl | 是 |\n", "| 波斯语 | per | 是 |\n", "| 布列塔尼语 | bre | 是 |\n", "| 巴什基尔语 | bak | 否 |\n", "| 巴斯克语 | baq | 是 |\n", "| 巴西葡萄牙语 | pot | 否 |\n", "| 白俄罗斯语 | bel | 是 |\n", "| 柏柏尔语 | ber | 是 |\n", "| 邦板牙语 | pam | 否 |\n", "| 保加利亚语 | bul | 是 |\n", "| 北方萨米语 | sme | 否 |\n", "| 北索托语 | ped | 否 |\n", "| 本巴语 | bem | 否 |\n", "| 比林语 | bli | 否 |\n", "| 比斯拉马语 | bis | 否 |\n", "| 俾路支语 | bal | 否 |\n", "| 冰岛语 | ice | 是 |\n", "| 波斯尼亚语 | bos | 是 |\n", "| 博杰普尔语 | bho | 否 |\n", "| 楚瓦什语 | chv | 否 |\n", "| 聪加语 | tso | 否 |\n", "| 丹麦语 | dan | 是 |\n", "| 德语 | de | 是 |\n", "| 鞑靼语 | tat | 是 |\n", "| 掸语 | sha | 否 |\n", "| 德顿语 | tet | 否 |\n", "| 迪维希语 | div | 否 |\n", "| 低地德语 | log | 是 |\n", "| 俄语 | ru | 是 |\n", "| 法语 | fra | 是 |\n", "| 菲律宾语 | fil | 是 |\n", "| 芬兰语 | fin | 是 |\n", "| 梵语 | san | 否 |\n", "| 弗留利语 | fri | 否 |\n", "| 富拉尼语 | ful | 否 |\n", "| 法罗语 | fao | 否 |\n", "| 盖尔语 | gla | 否 |\n", "| 刚果语 | kon | 否 |\n", "| 高地索布语 | ups | 否 |\n", "| 高棉语 | hkm | 是 |\n", "| 格陵兰语 | kal | 否 |\n", "| 格鲁吉亚语 | geo | 是 |\n", "| 古吉拉特语 | guj | 是 |\n", "| 古希腊语 | gra | 否 |\n", "| 古英语 | eno | 否 |\n", "| 瓜拉尼语 | grn | 否 |\n", "| 韩语 | kor | 是 |\n", "| 荷兰语 | nl | 是 |\n", "| 胡帕语 | hup | 否 |\n", "| 哈卡钦语 | hak | 否 |\n", "| 海地语 | ht | 否 |\n", "| 豪萨语 | hau | 否 |\n", "| 黑山语 | mot | 否 |\n", "| 吉尔吉斯语 | kir | 否 |\n", "| 加利西亚语 | glg | 是 |\n", "| 加拿大法语 | frn | 否 |\n", "| 加泰罗尼亚语 | cat | 是 |\n", "| 捷克语 | cs | 是 |\n", "| 卡拜尔语 | kab | 是 |\n", "| 卡纳达语 | kan | 是 |\n", "| 卡努里语 | kau | 否 |\n", "| 卡舒比语 | kah | 否 |\n", "| 康瓦尔语 | cor | 否 |\n", "| 科萨语 | xho | 是 |\n", "| 科西嘉语 | cos | 否 |\n", "| 克里克语 | cre | 否 |\n", "| 克里米亚鞑靼语 | cri | 否 |\n", "| 克林贡语 | kli | 否 |\n", "| 克罗地亚语 | hrv | 是 |\n", "| 克丘亚语 | que | 否 |\n", "| 克什米尔语 | kas | 否 |\n", "| 孔卡尼语 | kok | 否 |\n", "| 库尔德语 | kur | 是 |\n", "| 拉丁语 | lat | 是 |\n", "| 老挝语 | lao | 否 |\n", "| 罗马尼亚语 | rom | 是 |\n", "| 拉特加莱语 | lag | 否 |\n", "| 拉脱维亚语 | lav | 是 |\n", "| 林堡语 | lim | 否 |\n", "| 林加拉语 | lin | 否 |\n", "| 卢干达语 | lug | 否 |\n", "| 卢森堡语 | ltz | 否 |\n", "| 卢森尼亚语 | ruy | 否 |\n", "| 卢旺达语 | kin | 是 |\n", "| 立陶宛语 | lit | 是 |\n", "| 罗曼什语 | roh | 否 |\n", "| 罗姆语 | ro | 否 |\n", "| 逻辑语 | loj | 否 |\n", "| 马来语 | may | 是 |\n", "| 缅甸语 | bur | 是 |\n", "| 马拉地语 | mar | 否 |\n", "| 马拉加斯语 | mg | 是 |\n", "| 马拉雅拉姆语 | mal | 是 |\n", "| 马其顿语 | mac | 是 |\n", "| 马绍尔语 | mah | 否 |\n", "| 迈蒂利语 | mai | 是 |\n", "| 曼克斯语 | glv | 否 |\n", "| 毛里求斯克里奥尔语 | mau | 否 |\n", "| 毛利语 | mao | 否 |\n", "| 孟加拉语 | ben | 是 |\n", "| 马耳他语 | mlt | 是 |\n", "| 苗语 | hmn | 否 |\n", "| 挪威语 | nor | 是 |\n", "| 那不勒斯语 | nea | 否 |\n", "| 南恩德贝莱语 | nbl | 否 |\n", "| 南非荷兰语 | afr | 是 |\n", "| 南索托语 | sot | 否 |\n", "| 尼泊尔语 | nep | 是 |\n", "| 葡萄牙语 | pt | 是 |\n", "| 旁遮普语 | pan | 是 |\n", "| 帕皮阿门托语 | pap | 否 |\n", "| 普什图语 | pus | 否 |\n", "| 齐切瓦语 | nya | 否 |\n", "| 契维语 | twi | 否 |\n", "| 切罗基语 | chr | 否 |\n", "| 日语 | jp | 是 |\n", "| 瑞典语 | swe | 是 |\n", "| 萨丁尼亚语 | srd | 否 |\n", "| 萨摩亚语 | sm | 否 |\n", "| 塞尔维亚-克罗地亚语 | sec | 否 |\n", "| 塞尔维亚语 | srp | 是 |\n", "| 桑海语 | sol | 否 |\n", "| 僧伽罗语 | sin | 是 |\n", "| 世界语 | epo | 是 |\n", "| 书面挪威语 | nob | 是 |\n", "| 斯洛伐克语 | sk | 是 |\n", "| 斯洛文尼亚语 | slo | 是 |\n", "| 斯瓦希里语 | swa | 是 |\n", "| 索马里语 | som | 是 |\n", "| 塞尔维亚语(西里尔) | src | 否 |\n", "| 泰语 | th | 是 |\n", "| 土耳其语 | tr | 是 |\n", "| 塔吉克语 | tgk | 是 |\n", "| 泰米尔语 | tam | 是 |\n", "| 他加禄语 | tgl | 是 |\n", "| 提格利尼亚语 | tir | 否 |\n", "| 泰卢固语 | tel | 是 |\n", "| 突尼斯阿拉伯语 | tua | 否 |\n", "| 土库曼语 | tuk | 否 |\n", "| 乌克兰语 | ukr | 是 |\n", "| 瓦隆语 | wln | 是 |\n", "| 威尔士语 | wel | 是 |\n", "| 文达语 | ven | 否 |\n", "| 沃洛夫语 | wol | 否 |\n", "| 乌尔都语 | urd | 是 |\n", "| 西班牙语 | spa | 是 |\n", "| 希伯来语 | heb | 是 |\n", "| 希腊语 | el | 是 |\n", "| 匈牙利语 | hu | 是 |\n", "| 西弗里斯语 | fry | 是 |\n", "| 西里西亚语 | sil | 否 |\n", "| 希利盖农语 | hil | 否 |\n", "| 下索布语 | los | 否 |\n", "| 夏威夷语 | haw | 否 |\n", "| 新挪威语 | nno | 是 |\n", "| 西非书面语 | nqo | 否 |\n", "| 信德语 | snd | 否 |\n", "| 修纳语 | sna | 否 |\n", "| 宿务语 | ceb | 否 |\n", "| 叙利亚语 | syr | 否 |\n", "| 巽他语 | sun | 否 |\n", "| 英语 | en | 是 |\n", "| 印地语 | hi | 是 |\n", "| 印尼语 | id | 是 |\n", "| 意大利语 | it | 是 |\n", "| 越南语 | vie | 是 |\n", "| 意第绪语 | yid | 否 |\n", "| 因特语 | ina | 否 |\n", "| 亚齐语 | ach | 否 |\n", "| 印古什语 | ing | 否 |\n", "| 伊博语 | ibo | 否 |\n", "| 伊多语 | ido | 否 |\n", "| 约鲁巴语 | yor | 否 |\n", "| 亚美尼亚语 | arm | 是 |\n", "| 伊努克提图特语 | iku | 否 |\n", "| 中文(简体) | zh | 是 |\n", "| 中文(繁体) | cht | 是 |\n", "| 中文(文言文) | wyw | 是 |\n", "| 中文(粤语) | yue | 是 |\n", "| 扎扎其语 | zaz | 否 |\n", "| 中古法语 | frm | 否 |\n", "| 祖鲁语 | zul | 否 |\n", "| 爪哇语 | jav | 否 |\n", "\n", "\n" ], "metadata": { "collapsed": false, "pycharm": { "name": "#%% md\n" } } } ], "metadata": { "kernelspec": { "display_name": "Python 3", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 2 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython2", "version": "2.7.6" } }, "nbformat": 4, "nbformat_minor": 0 } ================================================ FILE: cookbooks/components/vdb_retriever.ipynb ================================================ { "cells": [ { "attachments": {}, "cell_type": "markdown", "metadata": {}, "source": [ "# VectorDB\n", "\n", "## 概述\n", "\n", "VectorDB产品基于百度自研的“莫愁”向量数据库内核构建,充分利用了百度内部在分布式存储&数据库领域的成熟经验,实现了高可靠、高可用、强扩展和大规模的能力。详细介绍可以参考文档 [VectorDB](https://cloud.baidu.com/doc/VDB/s/Llrsoaz3l)\n", "\n", "## 应用场景\n", "\n", "### 场景一:信息相似度检索\n", "\n", "在当今的信息时代,快速而准确地检索文本和图片数据成为了一个重要挑战。我们的向量数据库针对这一挑战,提供了一个高效、安全且智能的解决方案。\n", "\n", "### 场景二:大模型问答记忆\n", "\n", "在利用大型语言模型进行问答交互时,保持模型与用户之间的会话连贯性是提高回答质量和相关性的关键。我们的解决方案通过实时存储和检索会话数据,有效地降低了幻觉情况的发生,提升了问答的准确性和用户体验。\n", "\n", "\n", "### 场景三:大模型私域知识库\n", "\n", "在私有云环境中,构建专属的私域知识库是提升业务决策效率和精确性的关键。我们的向量数据库解决方案充分利用大模型的推理能力,针对私域数据提供定制化、高效的知识管理和检索服务。" ] }, { "attachments": {}, "cell_type": "markdown", "metadata": {}, "source": [ "## 开发上手\n", "\n", "### 第一步:环境准备,安装依赖" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "!pip install appbuilder-sdk" ] }, { "attachments": {}, "cell_type": "markdown", "metadata": {}, "source": [ "### 第二步:平台注册,设置Token\n", "\n", "- 2.1、注册AppBuilder平台账户,并申请Token,可参考文档:[AppBuilder官网创建密钥](https://cloud.baidu.com/doc/AppBuilder/s/Olq6grrt6#1%E3%80%81%E5%88%9B%E5%BB%BA%E5%AF%86%E9%92%A5)" ] }, { "cell_type": "code", "execution_count": 1, "metadata": {}, "outputs": [], "source": [ "# AppBuilder平台注册后获取密钥\n", "import os\n", "import appbuilder\n", "\n", "# 请前往千帆AppBuilder官网创建密钥,流程详见:https://cloud.baidu.com/doc/AppBuilder/s/Olq6grrt6#1%E3%80%81%E5%88%9B%E5%BB%BA%E5%AF%86%E9%92%A5\n", "os.environ[\"APPBUILDER_TOKEN\"] = '...'" ] }, { "attachments": {}, "cell_type": "markdown", "metadata": {}, "source": [ "- 2.2、同时您需要申请并开通VectorDB,并创建实例,具体操作请参考[VectorDB文档](https://cloud.baidu.com/doc/VDB/s/hlrsoazuf)\n", "\n", "\n", "### 第三步:创建并运行VectorDB,初始化构建索引\n", "\n", "补充说明:\n", "- `you_vdb_instance_id` 为VectorDB 实例ID,请替换为您的实例ID,在VectorDB控制台界面上可以查看\n", "- `your_api_key` 为您在VectorDB上申请的账户密钥,请替换为您自己的root账户密钥,在VectorDB控制台界面上可以查看" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "segments = appbuilder.Message([\"文心一言大模型\", \"百度在线科技有限公司\"])\n", "# 初始化构建索引\n", "vector_index = appbuilder.BaiduVDBVectorStoreIndex.from_params(\n", " instance_id=\"your_instance_id\",\n", " api_key=\"your_api_key\",\n", " drop_exists=True,\n", ")\n", "vector_index.add_segments(segments)" ] }, { "attachments": {}, "cell_type": "markdown", "metadata": {}, "source": [ "### 第四步:构建完毕索引后,可以通过retriever进行检索" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "query = appbuilder.Message(\"文心一言\")\n", "retriever = vector_index.as_retriever()\n", "res = retriever(query)\n", "print(res)\n", "\n", "# Message(name=msg, content=[{'text': '文心一言大模型', 'meta': '', 'score': 1.0}], mtype=list)" ] }, { "attachments": {}, "cell_type": "markdown", "metadata": {}, "source": [ "\n", "以上,便完成了VDB作为检索工具参与Appbuilder运行的流程使用,更多的VDB使用方式,请参考[VDB官方文档](https://cloud.baidu.com/doc/VDB/index.html) 与 [AppBuilder-retriever-baidu_vdb 文档](../appbuilder/core/components/retriever/baidu_vdb/README.md)" ] } ], "metadata": { "kernelspec": { "display_name": "Python 3", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.9.6" }, "orig_nbformat": 4, "vscode": { "interpreter": { "hash": "31f2aee4e71d21fbe5cf8b01ff0e069b9275f58929596ceb00d14d90e3e16cd6" } } }, "nbformat": 4, "nbformat_minor": 2 } ================================================ FILE: cookbooks/end2end_application/agent/appbuilder_client.ipynb ================================================ { "cells": [ { "attachments": {}, "cell_type": "markdown", "id": "42eace26869295fb", "metadata": { "collapsed": false }, "source": [ "# Console AppBuilderClient使用示例\n", "\n", "整体使用流程包括以下两个环节:\n", "\n", "1. 在[百度智能云千帆AppBuilder官网](https://cloud.baidu.com/product/AppBuilder)创建并发布应用、获取应用ID、获取密钥\n", "2. 引用AppBuilderSDK代码,初始化AppBuilderClient实例、创建会话、上传文档(可选)、执行对话\n", "\n", "以下分别提供三个样例,快递查询小助手、植物识别小助手、篮球教练来说明使用流程,并提供了一个异步调用示例加速调用流程。注意以下流程用到的密钥可在图示位置中获取:\n", "\"drawing\"\n", "\n", "\n", "## 1. 快递查询小助手\n", "\n", "[ 快递查询小助手](https://appbuilder.baidu.com/s/KVSXK)一键体验\n", "\n", "### 1.1 Console端应用配置与发布\n", "1 进入[百度智能云千帆AppBuilder官网](https://cloud.baidu.com/product/AppBuilder),配置智能体指令、选择相应的工具组件、发布应用\n", "\n", "\"drawing\"\n", "\n", "2 获取应用ID\n", "\"drawing\"\n", "\n", "### 1.2 SDK代码调用示例" ] }, { "cell_type": "code", "execution_count": null, "id": "a6a9e2ba6159a8e4", "metadata": { "collapsed": false, "is_executing": true }, "outputs": [], "source": [ "import appbuilder\n", "import os\n", "# 注意以下示例正确运行依赖的条件包括:\n", "# 1. 在百度智能云千帆AppBuilder官网使用AppBuilderClient创建应用且应用已发布\n", "# 2. 密钥正确有效\n", "# 3. 密钥需要与发布应用正确对应,即需要使用发布应用的账户下的密钥\n", "\n", "# 配置密钥与应用ID\n", "os.environ[\"APPBUILDER_TOKEN\"] =\"secret_key\"\n", "app_id = \"35f4fed3-d530-4dad-bc8e-f2150a4450be\"\n", "\n", "# 初始化Agent\n", "builder = appbuilder.AppBuilderClient(app_id)\n", "\n", "# 创建会话ID\n", "conversation_id = builder.create_conversation()\n", "\n", "# 执行对话\n", "msg = builder.run(conversation_id, \"我的快递单号是:9858485940100; 请查询下此快递的状态\")\n", "print(\"快递查询助理回答内容:\", msg.content.answer)\n", "\n", "# 执行流式对话\n", "msg = builder.run(conversation_id, \"使用语音播报快递当前状态\", stream=True)\n", "for content in msg.content:\n", " for ev in content.events:\n", " if ev.content_type == \"audio\":\n", " print(\"快递查询助理生成的音频播放地址:\", ev.detail[\"audio\"])" ] }, { "cell_type": "markdown", "id": "3e462991dab3283d", "metadata": { "collapsed": false }, "source": [ "## 2. 植物识别小助手\n", "[植物识别小助手](https://appbuilder.baidu.com/s/50zyD)一键体验\n", "\n", "### 2.1 Console端应用配置与发布\n", "1 进入[百度智能云千帆AppBuilder官网](https://cloud.baidu.com/product/AppBuilder),配置智能体指令、选择相应的工具组件、发布应用\n", "\"drawing\"\n", "\n", "2 获取应用ID, 同1.1\n", "\n", "### 2.2 SDK代码调用示例" ] }, { "cell_type": "code", "execution_count": null, "id": "4d051395a2aa1d11", "metadata": { "collapsed": false, "is_executing": true }, "outputs": [], "source": [ "import os\n", "import appbuilder\n", "\n", "# 注意以下示例正确运行依赖的条件包括:\n", "# 1. 在百度智能云千帆AppBuilder官网使用AppBuilderClient创建应用且应用已发布\n", "# 2. 密钥正确有效\n", "# 3. 密钥需要与发布的应用正确对应,即需要使用发布应用的账户下的密钥\n", "\n", "# 配置密钥与应用ID\n", "os.environ[\"APPBUILDER_TOKEN\"] =\"...\"\n", "app_id = \"7016e0d3-451b-4a47-a818-dc0a16d4b496\" \n", "\n", "# 初始化Agent实例\n", "builder = appbuilder.AppBuilderClient(app_id)\n", "\n", "# 创建会话ID\n", "conversation_id = builder.create_conversation()\n", "\n", "# 上传植物图片\n", "file_id = builder.upload_local_file(conversation_id, \"./app_builder_resources/tree.png\" )\n", "\n", "# 植物识别\n", "msg = builder.run(conversation_id, \"请识别图中的植物类别\", file_ids=[file_id])\n", "print(\"植物识别助理回答内容:\", msg.content.answer)" ] }, { "cell_type": "markdown", "id": "c112f09d6ce35d10", "metadata": { "collapsed": false }, "source": [ "## 3. 篮球教练\n", "[篮球教练知识增强检索](https://appbuilder.baidu.com/s/RCVEn)一键体验\n", "\n", "### 3.1 Console端应用配置与发布\n", "1 进入[百度智能云千帆AppBuilder官网](https://cloud.baidu.com/product/AppBuilder),配置智能体指令、上传文档并关联知识库、发布应用\n", "\"drawing\"\n", "\n", "2 获取应用ID, 同1.1\n", "\n", "### 3.2 SDK代码调用示例" ] }, { "cell_type": "code", "execution_count": null, "id": "65e488aa883cf94e", "metadata": { "collapsed": false, "is_executing": true }, "outputs": [], "source": [ "import os\n", "import appbuilder\n", "\n", "# 注意以下示例正确运行依赖的条件包括:\n", "# 1. 在百度智能云千帆AppBuilder官网使用AppBuilderClient创建应用且应用已发布\n", "# 2. 密钥正确有效\n", "# 3. 密钥需要与发布的应用正确对应,即需要使用发布应用的账户下的密钥\n", "\n", "# 配置密钥与应用ID\n", "os.environ[\"APPBUILDER_TOKEN\"] =\"...\"\n", "app_id = \"4316a7cb-b6b2-4448-b6fa-ff131c484ec9\" \n", "\n", "# 初始化Agent实例\n", "builder = appbuilder.AppBuilderClient(app_id)\n", "\n", "# 创建会话ID\n", "conversation_id = builder.create_conversation()\n", "\n", "# 执行对话\n", "msg = builder.run(conversation_id, \"突破技巧中如何运用胯下变向?\", )\n", "print(\"篮球教练回答内容:\", msg.content.answer)" ] }, { "cell_type": "markdown", "id": "7acaf6bb", "metadata": {}, "source": [ "## 4. 使用异步调用加速AppBuilderClient并发执行\n", "SDK提供异步调用工作流Agent的接口。下面以3章节的“篮球教练”为例,演示如何使用异步调用加速AppBuilderClient并发执行。" ] }, { "cell_type": "code", "execution_count": null, "id": "fa87ffcb", "metadata": {}, "outputs": [], "source": [ "import os\n", "import appbuilder\n", "import asyncio\n", "\n", "# 注意以下示例正确运行依赖的条件包括:\n", "# 1. 在百度智能云千帆AppBuilder官网使用AppBuilderClient创建应用且应用已发布\n", "# 2. 密钥正确有效\n", "# 3. 密钥需要与发布的应用正确对应,即需要使用发布应用的账户下的密钥\n", "\n", "# 配置密钥与应用ID\n", "os.environ[\"APPBUILDER_TOKEN\"] = \"...\"\n", "app_id = \"4316a7cb-b6b2-4448-b6fa-ff131c484ec9\"\n", "\n", "async def agent_run(client, conversation_id, text):\n", " ans = await client.run(conversation_id, text, stream=True)\n", " async for data in ans.content:\n", " print(data)\n", "\n", "\n", "async def agent_sample():\n", " client = appbuilder.AsyncAppBuilderClient(app_id)\n", " conversation_id = await client.create_conversation()\n", " file_id = await client.upload_local_file(\n", " conversation_id, \"./python/tests/data/qa_appbuilder_client_demo.pdf\"\n", " )\n", " print(\"file_id is {}\".format(file_id))\n", " task1 = asyncio.create_task(\n", " agent_run(client, conversation_id, \"篮球技巧中如何三步上篮?\")\n", " )\n", " task2 = asyncio.create_task(\n", " agent_run(client, conversation_id, \"突破技巧中如何运用胯下变向?\")\n", " )\n", " await asyncio.gather(task1, task2)\n", " await client.http_client.session.close()\n", "\n", "if __name__ == \"__main__\":\n", " loop = asyncio.get_event_loop()\n", " loop.run_until_complete(agent_sample())" ] } ], "metadata": { "kernelspec": { "display_name": "Python 3 (ipykernel)", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.11.8" } }, "nbformat": 4, "nbformat_minor": 5 } ================================================ FILE: cookbooks/end2end_application/agent/chatflow.ipynb ================================================ { "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# 前言 - 学习本项目你可以获得什么\n", "- 入门百度智能云千帆AppBuilder,搭建一个工作流Agent应用\n", "- 使用AppBuilder-SDK进行工作流Agent对话\n", "- 了解如何使用AppBuilder-SDK简化多轮对话的开发" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 1. 项目背景\n", "\n", "### 1.1、 什么是AppBuilder\n", "[百度智能云千帆AppBuilder](https://appbuilder.cloud.baidu.com/)(以下简称AppBuilder)是基于大模型搭建AI原生应用的工作台,旨在降低AI原生应用的开发门槛,赋能开发者和企业快速实现应用搭建。\n", "\n", "平台提供了RAG(检索增强生成)、Agent(智能体)等应用框架,内置了文档问答、表格问答、多轮对话、生成创作等多种应用组件,还包括百度搜索和百度地图等特色组件,以及文本处理、图像处理和语音处理等传统AI组件,支持零代码、低代码、全代码三种开发方式,满足不同开发能力的开发者和企业的场景需求。\n", "\n", "### 1.2、 什么是AppBuilder-SDK\n", "\n", "[百度智能云千帆AppBuilder-SDK](https://github.com/baidubce/app-builder)(以下简称AB-SDK),百度智能云千帆AppBuilder-SDK是百度智能云千帆AppBuilder面向AI原生应用开发者提供的一站式开发平台的客户端SDK。\n", "\n", "\"drawing\"" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# 2. 创建工作流Agent应用并对话\n", "\n", "## 2.1 什么是工作流Agent?\n", "通过工作流编排的形式还原业务流程,每轮对话均严格按照工作流执行,提高了AI应用的可控性,并可编排出复杂业务流程,适用于客服、营销、生成、办公等高可控及高复杂度等场景。\n", "\n", "**工作流Agent无需设置角色人设,通过工作流编排的形式实现应用功能。**\n", "\n", "用户的所有对话均会触发此工作流处理,适用于严格按照流程执行的任务,例如:\n", "\n", "* 客服对话智能体,判断终端用户的意图后严格按照任务分支自动执行,无需大模型思考选择。\n", "* MBTI小助手,根据开发者编排的问题逐个提问,严格按照任务分支和结果执行后续的流程。\n", "\n", "工作流Agent支持用户配置工作流完成整个应用的对话过程,通过开始节点的Rawquery传入首轮对话,利用信息收集节点可以进行一组工作流中的多轮对话,最后以结束节点作为整个工作流结束的标志。开始节点和结束节点之前的完整流程构成一组工作流,每个信息收集节点都可以支持终端用户和应用的一次交互。\n", "\n", "## 2.2 创建工作流Agent应用-飞行客服小助手\n", "\n", "参考产品文档[飞行客服小助手](https://cloud.baidu.com/doc/AppBuilder/s/cm38k8nqr)创建示例应用。通过阅读本篇最佳实践,读者可以深度理解问答节点、信息处理节点、全局跳转节点的功能点和使用方式,搭建自己的工作流agent。对话效果如下:\n", "\n", "

\n", " \n", " \n", " \n", "

\n", "\n", "## 2.3 使用AppBuilder-SDK进行对话\n", "### 2.3.1 方式一:使用SDK直接对话(不推荐)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "import appbuilder\n", "import os\n", "from appbuilder.core.console.appbuilder_client import data_class\n", "\n", "# 请前往千帆AppBuilder官网创建密钥,流程详见:https://cloud.baidu.com/doc/AppBuilder/s/Olq6grrt6#1%E3%80%81%E5%88%9B%E5%BB%BA%E5%AF%86%E9%92%A5\n", "# 设置环境变量\n", "os.environ[\"APPBUILDER_TOKEN\"] = \"...\"\n", "appbuilder.logger.setLoglevel(\"ERROR\")\n", "\n", "# 飞行客服小助手的应用id\n", "app_id = \"...\"\n", "# 初始化智能体\n", "client = appbuilder.AppBuilderClient(app_id)\n", "# 创建会话\n", "conversation_id = client.create_conversation()\n", "interrupt_ids = []\n", "\n", "msg = client.run(conversation_id, \"查天气\", stream=True)\n", "interrupt_event_id = None\n", "for ans in msg.content:\n", " for event in ans.events:\n", " if event.content_type == \"publish_message\":\n", " print(event.detail.get(\"message\"))\n", " if event.content_type == \"chatflow_interrupt\":\n", " interrupt_event_id = event.detail.get(\"interrupt_event_id\")\n", " break\n", "interrupt_ids.append(interrupt_event_id)\n", "\n", "msg2 = client.run(\n", " conversation_id,\n", " \"查航班\",\n", " stream=True,\n", " action=data_class.Action.create_resume_action(interrupt_event_id),\n", ")\n", "interrupt_event_id = None\n", "for ans in msg2.content:\n", " for event in ans.events:\n", " if event.content_type == \"publish_message\":\n", " print(event.detail.get(\"message\"))\n", " if event.content_type == \"chatflow_interrupt\":\n", " interrupt_event_id = event.detail.get(\"interrupt_event_id\")\n", " break\n", " interrupt_ids.append(interrupt_event_id)\n", "\n", "msg3 = client.run(\n", " conversation_id=conversation_id,\n", " query=\"CA1234\",\n", " stream=True,\n", " action=data_class.Action.create_resume_action(interrupt_ids.pop()),\n", ")\n", "interrupt_event_id = None\n", "for ans in msg3.content:\n", " for event in ans.events:\n", " if event.content_type == \"text\":\n", " print(event.detail.get(\"text\"))\n", " if event.content_type == \"chatflow_interrupt\":\n", " interrupt_event_id = event.detail.get(\"interrupt_event_id\")\n", " break\n", "interrupt_ids.append(interrupt_event_id)\n", "\n", "msg4 = client.run(\n", " conversation_id=conversation_id,\n", " query=\"北京的\",\n", " stream=True,\n", " action=data_class.Action.create_resume_action(interrupt_ids.pop()),\n", ")\n", "has_multiple_dialog_event = False\n", "for ans in msg4.content:\n", " for event in ans.events:\n", " if event.content_type == \"text\":\n", " print(event.detail.get(\"text\"))\n", " if event.content_type == \"multiple_dialog_event\":\n", " has_multiple_dialog_event = True\n", " break" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### 2.3.2 方式二 实现自己的EventHandler,更方便地进行对话(推荐)\n", "直接调用处理较为繁琐。SDK提供了使用AppBuilderEventHandler简化tool_call操作的功能。**继承AppBuilderEventHandler类,并实现针对各类型event的处理方法。**" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "import os\n", "import appbuilder\n", "from appbuilder.core.console.appbuilder_client.event_handler import (\n", " AppBuilderEventHandler,\n", ")\n", "\n", "\n", "class MyEventHandler(AppBuilderEventHandler):\n", " def __init__(self):\n", " super().__init__()\n", " self.interrupt_ids = []\n", "\n", " def handle_content_type(self, run_context, run_response):\n", " interrupt_event_id = None\n", " event = run_response.events[-1]\n", " if event.content_type == \"chatflow_interrupt\":\n", " interrupt_event_id = event.detail.get(\"interrupt_event_id\")\n", " if interrupt_event_id is not None:\n", " self.interrupt_ids.append(interrupt_event_id)\n", "\n", " def _create_action(self):\n", " if len(self.interrupt_ids) == 0:\n", " return None\n", " event_id = self.interrupt_ids.pop()\n", " return {\n", " \"action_type\": \"resume\",\n", " \"parameters\": {\"interrupt_event\": {\"id\": event_id, \"type\": \"chat\"}},\n", " }\n", "\n", " def run(self, query=None):\n", " super().new_dialog(\n", " query=query,\n", " action=self._create_action(),\n", " )\n", "\n", "\n", "def main():\n", " # 请前往千帆AppBuilder官网创建密钥,流程详见:https://cloud.baidu.com/doc/AppBuilder/s/Olq6grrt6#1%E3%80%81%E5%88%9B%E5%BB%BA%E5%AF%86%E9%92%A5\n", " # 设置环境变量\n", " os.environ[\"APPBUILDER_TOKEN\"] = \"...\"\n", " appbuilder.logger.setLoglevel(\"DEBUG\")\n", "\n", " # 飞行客服小助手的应用id\n", " app_id = \"...\"\n", " # 初始化智能体\n", " client = appbuilder.AppBuilderClient(app_id)\n", " conversation_id = client.create_conversation()\n", "\n", " event_handler = MyEventHandler()\n", " event_handler.init(\n", " appbuilder_client=client,\n", " conversation_id=conversation_id,\n", " stream=True,\n", " query=\"查天气\",\n", " )\n", " for data in event_handler:\n", " pass\n", " event_handler.run(\n", " query=\"查航班\",\n", " )\n", " for data in event_handler:\n", " pass\n", " event_handler.run(\n", " query=\"CA1234\",\n", " )\n", " for data in event_handler:\n", " pass\n", " event_handler.run(\n", " query=\"北京的\",\n", " )\n", " for data in event_handler:\n", " pass\n", "\n", "\n", "if __name__ == \"__main__\":\n", " main()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### 2.3.3 方式三、实现自己的EventHandler,更方便地进行多轮对话(推荐)\n", "SDK提供了run_multiple_dialog_with_handler方法来进行多轮对话,按需传入iterable对象(queries、actions等参数),即可一次调用完成多轮对话。" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "import os\n", "import appbuilder\n", "from appbuilder.core.console.appbuilder_client.event_handler import (\n", " AppBuilderEventHandler,\n", ")\n", "\n", "\n", "class MyEventHandler(AppBuilderEventHandler):\n", " def __init__(self):\n", " super().__init__()\n", " self.interrupt_ids = []\n", "\n", " def handle_content_type(self, run_context, run_response):\n", " interrupt_event_id = None\n", " event = run_response.events[-1]\n", " if event.content_type == \"chatflow_interrupt\":\n", " interrupt_event_id = event.detail.get(\"interrupt_event_id\")\n", " if interrupt_event_id is not None:\n", " self.interrupt_ids.append(interrupt_event_id)\n", "\n", " def _create_action(self):\n", " if len(self.interrupt_ids) == 0:\n", " return None\n", " event_id = self.interrupt_ids.pop()\n", " return {\n", " \"action_type\": \"resume\",\n", " \"parameters\": {\"interrupt_event\": {\"id\": event_id, \"type\": \"chat\"}},\n", " }\n", "\n", " def gen_action(self):\n", " while True:\n", " yield self._create_action()\n", "\n", "\n", "def main():\n", " # 请前往千帆AppBuilder官网创建密钥,流程详见:https://cloud.baidu.com/doc/AppBuilder/s/Olq6grrt6#1%E3%80%81%E5%88%9B%E5%BB%BA%E5%AF%86%E9%92%A5\n", " # 设置环境变量\n", " os.environ[\"APPBUILDER_TOKEN\"] = \"...\"\n", " appbuilder.logger.setLoglevel(\"DEBUG\")\n", "\n", " # 飞行客服小助手的应用id\n", " app_id = \"...\"\n", " # 初始化智能体\n", " client = appbuilder.AppBuilderClient(app_id)\n", " conversation_id = client.create_conversation()\n", "\n", " queries = [\"查天气\", \"查航班\", \"CA1234\", \"北京的\"]\n", " event_handler = MyEventHandler()\n", " event_handler = client.run_multiple_dialog_with_handler(\n", " conversation_id=conversation_id,\n", " queries=queries,\n", " event_handler=event_handler,\n", " stream=True,\n", " actions=event_handler.gen_action(),\n", " )\n", " for data in event_handler:\n", " for ans in data:\n", " pass\n", "\n", "\n", "if __name__ == \"__main__\":\n", " main()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### 2.3.4 异步调用工作流Agent\n", "SDK提供异步调用工作流Agent的接口,下面是一个异步调用工作流Agent的实例。" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Copyright (c) 2024 Baidu, Inc. All Rights Reserved.\n", "#\n", "# Licensed under the Apache License, Version 2.0 (the \"License\");\n", "# you may not use this file except in compliance with the License.\n", "# You may obtain a copy of the License at\n", "#\n", "# http://www.apache.org/licenses/LICENSE-2.0\n", "#\n", "# Unless required by applicable law or agreed to in writing, software\n", "# distributed under the License is distributed on an \"AS IS\" BASIS,\n", "# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n", "# See the License for the specific language governing permissions and\n", "# limitations under the License.\n", "import os\n", "import asyncio\n", "import appbuilder\n", "from appbuilder.core.console.appbuilder_client.async_event_handler import (\n", " AsyncAppBuilderEventHandler,\n", ")\n", "\n", "class MyEventHandler(AsyncAppBuilderEventHandler):\n", " def __init__(self):\n", " super().__init__()\n", " self.interrupt_ids = []\n", "\n", " async def handle_content_type(self, run_context, run_response):\n", " interrupt_event_id = None\n", " event = run_response.events[-1]\n", " if event.content_type == \"chatflow_interrupt\":\n", " interrupt_event_id = event.detail.get(\"interrupt_event_id\")\n", " if interrupt_event_id is not None:\n", " self.interrupt_ids.append(interrupt_event_id)\n", "\n", " def _create_action(self):\n", " if len(self.interrupt_ids) == 0:\n", " return None\n", " event_id = self.interrupt_ids.pop()\n", " return {\n", " \"action_type\": \"resume\",\n", " \"parameters\": {\"interrupt_event\": {\"id\": event_id, \"type\": \"chat\"}},\n", " }\n", "\n", " async def run(self, query=None):\n", " await super().new_dialog(\n", " query=query,\n", " action=self._create_action(),\n", " )\n", "\n", " def gen_action(self):\n", " while True:\n", " yield self._create_action()\n", "\n", "\n", "async def agent_run():\n", " # 请前往千帆AppBuilder官网创建密钥,流程详见:https://cloud.baidu.com/doc/AppBuilder/s/Olq6grrt6#1%E3%80%81%E5%88%9B%E5%BB%BA%E5%AF%86%E9%92%A5\n", " # 设置环境变量\n", " os.environ[\"APPBUILDER_TOKEN\"] = \"...\"\n", " appbuilder.logger.setLoglevel(\"DEBUG\")\n", "\n", " # 飞行客服小助手的应用id\n", " app_id = \"...\"\n", " client = appbuilder.AsyncAppBuilderClient(app_id)\n", " conversation_id = await client.create_conversation()\n", " event_handler = MyEventHandler()\n", " queries = [\"查天气\", \"查航班\", \"CA1234\", \"北京的\"]\n", " event_handler = client.run_multiple_dialog_with_handler(\n", " conversation_id=conversation_id,\n", " queries=queries,\n", " event_handler=event_handler,\n", " stream=False,\n", " actions=event_handler.gen_action(),\n", " )\n", " async for data in event_handler:\n", " async for answer in data:\n", " print(answer)\n", "\n", " await client.http_client.session.close()\n", "\n", "if __name__ == \"__main__\":\n", " loop = asyncio.get_event_loop()\n", " loop.run_until_complete(agent_run())" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# 3、项目总结\n", "\n", "本项目最终完成了一个工作流Agent应用的创建,并使用Appbuilder-SDK进行对话功能。\n", "\n", "希望您可以不吝`Star`,给`AppBuilder-SDK`一些鼓励,期待您的`PR`,一起共建AIAgent生态。\n", "\n", "Github地址:https://github.com/baidubce/app-builder\n", "\n", "\"drawing\"\n", "\n", "最后,您也可以进入`AppBuilder-SDK`的WX交流群,和大家一起交流AppBuilder使用及开发心得。\n", "\n", "\"drawing\"" ] } ], "metadata": { "kernelspec": { "display_name": "testenv", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.9.20" } }, "nbformat": 4, "nbformat_minor": 2 } ================================================ FILE: cookbooks/end2end_application/agent/tool_call.ipynb ================================================ { "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "\"drawing\"" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# 前言 - 学习本项目你可以获得什么\n", "- 理论学习:了解AIAgent的基础知识\n", "- 上手实操:深入了解Agent中的FunctionCall运行流程\n", "- 上手实操:入门百度智能云千帆AppBuilder,在十分钟内打造一个个性化AIAgent\n", "- 上手实操:使用AppBuilder-SDK打造一个端云组件联动的进阶Agent" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 1. 项目背景\n", "\n", "### 1.1、 什么是AppBuilder\n", "[百度智能云千帆AppBuilder](https://appbuilder.cloud.baidu.com/)(以下简称AppBuilder)是基于大模型搭建AI原生应用的工作台,旨在降低AI原生应用的开发门槛,赋能开发者和企业快速实现应用搭建。\n", "\n", "平台提供了RAG(检索增强生成)、Agent(智能体)等应用框架,内置了文档问答、表格问答、多轮对话、生成创作等多种应用组件,还包括百度搜索和百度地图等特色组件,以及文本处理、图像处理和语音处理等传统AI组件,支持零代码、低代码、全代码三种开发方式,满足不同开发能力的开发者和企业的场景需求。\n", "\n", "### 1.2、 什么是AppBuilder-SDK\n", "\n", "[百度智能云千帆AppBuilder-SDK](https://github.com/baidubce/app-builder)(以下简称AB-SDK),百度智能云千帆AppBuilder-SDK是百度智能云千帆AppBuilder面向AI原生应用开发者提供的一站式开发平台的客户端SDK。\n", "\n", "\"drawing\"" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# 2. 项目介绍 - 通过ToolCall实现端云组件联动的Agent\n", "### 2.1、 什么是Agent\n", "\n", "AIAgent是能够感知环境,基于目标进行决策并执行动作的智能化应用。不同于传统人工智能应用(主要指以规则引擎、机器学习、深度学习等技术为核心)和RPA机器人,AIAgent能够基于目标和对现状能力的认知,在环境约束中,依赖特定资源和现有工具,找到行动规则并将行动拆解为必要的步骤,自主执行步骤,达成目标。\n", "\n", "AIAgent具备三个核心能力:独立思考、自主执行、持续迭代。\n", "- 独立思考是指AlAgent能够根据给定任务目标和约束条件,进行任务规划和问题拆解,形成执行步骤(即工作流);\n", "- 自主执行是指AlAgent能够调取各类组件和工具,按照执行步骤依次执行,实现任务目标;\n", "- 持续选代是指AlAgent能够自动记录任务目标、工作流和执行结果,基于结果反馈,沉淀专家知识和案例。\n", "\n", "AICopilot、AIAgent、大模型等名词在各类文章上经常混淆,此处简要说明下三者的区别。大模型一般是指大模型技术,AlAgent和Al Copilot是基于大模型技术的智能化应用,AlAgent和AlCopilot在功能和场景上存在差别。\n", "\n", "自主性是AIAgent和AI Copilot之间最大的区别。AI Copilot是“副驾驶”,只是提供建议而非决策,AIAgent是“主驾驶”,需要真正做出决策并开展行动。\n", "\n", "\"drawing\"\n", "\n", "### 2.2、 什么是ToolCall\n", "\n", "解释该问题,需要了解以下的知识点:`Agent工具` -> `FunctionCall` - `ToolCall`\n", "\n", "AIAgent 有四大核心组件:记忆、规划、工具和执行。其中工具部分,与我们的开发关系最密切,在各类Agent开发平台/工具中,常被称为“组件”、\"插件\"、\"能力\"等.\n", "\n", "关于Agent的工具的定义与分类,如下图~\n", "\n", "\"drawing\"\n", "\n", "Agent使用工具的流程,一般称为`FunctionCall`,最早由OpenAI提出,并在[Assistant API](https://platform.openai.com/docs/assistants/overview)中广泛应用。\n", "\n", "\n", "ToolCall,则是AppBuilder平台提出的一种进阶的FunctionCall,本质与OpenAI的FunctionCall一致,但具有以下两个特点:\n", "\n", "- **端云组件联动**: Agent 调用工具时,可以同时调用云端和本地组件。\n", "\n", "- **组件类型泛化**: AppBuilder在未来会支持多种类型组件,已经超出了Function的含义,例如数据库、记忆库、工作流等等\n", "\n", "\n", "\n", "### 2.3、 什么是端云组件联动,要解决什么问题\n", "\n", "我们首先从工具的执行位置出发展开~ 在使用如AppBuilder / Coze 等平台开发Agent时,我们可以使用很多平台组件广场中,官方提供的组件,这里组件开箱即用,非常方便。\n", "\n", "\"drawing\"\n", "\n", "但是存在一个问题,基于平台云端组件开发的应用,无法调用内网/局域网/私域的知识与能力,也无法与本地的工具进行联动,限制了Agent的灵活性。\n", "\n", "我们在解决实际业务问题时,常遇到需要访问内网链接API或本地/硬件功能的FunctionCall需求,AppBuilder ToolCall可以解决这个问题:\n", "\n", "* 1、用户可注册一个本地运行的组件到已发布的应用\n", "* 2、由AppBuilder-Agent的云端思考模型进行规划和参数生成\n", "* 3、用户基于生成的参数调用本地组件,并再上传运行结果\n", "* 4、以此实现将本地组件能力嵌入到应用整体流程\n", "\n", "\n", "\"drawing\"" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# 3、ToolCall(FunctionCall)基础知识介绍\n", "\n", "### 3.1、Agent是如何调用Tool的\n", "\n", "我们可以将Agent的黑箱拆解为以下几个部分:\n", "1. Agent的背景信息\n", "2. Agent的输入信息\n", "3. Agent的思考过程\n", "4. Agent触发组件调用\n", "5. Agent基于组件输出反思总结\n", "\n", "#### Agent的背景信息包含以下几个部分\n", "- 角色定义描述(Prompt):定义Agent的角色\n", "- 能力描述(Prompt):定义Agent可以干什么\n", "- 工具描述(JsonSchema/Str):将工具的输入和输出,按照规范,定义为一段字符串,作为最终大模型Prompt的一部分\n", "\n", "#### Agent的输入信息包含以下几个部分\n", "- 用户输入(Query/Prompt):用户输入的文本\n", "- 对话相关的文件(File/Url):与本地对话相关的文件路径\n", "\n", "#### Agent的思考过程\n", "AppBuilder-Agent会将背景信息与输入信息,拼接为最终的Prompt,然后调用大模型推理。\n", "\n", "Prompt的一个简单且直观的例子是:\n", "\n", "你是`{角色定义描述}`,你可以做以下事情:`{能力描述}`,你可以使用这些工具:`{工具描述-description}`,工具依赖的输入是:`{工具描述-paramters-properties-name}`,这些输入的格式分别是`{工具描述-paramters-properties-type}`。现在用户的问题是`{用户输入}`,与该问题相关的文件是`{对话相关的文件}`,请你解决用户的这个问题。\n", "\n", "#### Agent触发组件调用\n", "\n", "如果用户的query和组件能够解决的问题匹配,那么大模型就会尝试根据prompt里给出的工具的描述,从query中提炼出该次调用工具所需的参数,生成一个ToolCall命令,交给执行组件的模块去执行。\n", "\n", "例如,我们给出的组件能力是\"查找公司内指定人员的信息\",函数的参数名为\"name\"。当用户输入\"查找张三的信息\",大模型会从query中提炼出参数\"name=张三\"这个信息。\n", "\n", "\"drawing\"\n", "\n", "#### Agent基于组件输出反思总结\n", "\n", "组件运行模块执行组件后,会给出字符串形式的结果给到Agent,Agent会再次将结果拼接为Prompt,然后调用大模型推理。判断用户的需求是否已经解决。如果解决了,则经过一个对话模块,总结用户的需求,并生成一个对话记录。如果未解决,则继续调用大模型推理,尝试调用更多的工具,直到用户的需求被解决。\n", "\n", "### 3.2、开发者如何命令Agent调用本地Tool\n", "\n", "我们以AppBuilder-SDK中的AppBuilder-Client的基础代码为例,介绍开发者应该如何使用ToolCall功能\n", "\n", "\n", "```python\n", "import appbuilder\n", "\n", "# 实例化AppBuilderClient\n", "app_client = appbuilder.AppBuilderClient(app_id)\n", "conversation_id = app_client.create_conversation()\n", "\n", "# 第一次对话,输入原始的query 和 工具描述\n", "message_1 = app_client.run(\n", " conversation_id=conversation_id,\n", " query=\"请问张三同学的生日是哪天?\",\n", " tools=tools\n", ")\n", "tool_call = message_1.content.events[-1].tool_calls[-1]\n", "tool_call_id = tool_call.id\n", "\n", "# 第二次对话,在本地执行组件后,上传组件的运行结果\n", "tool_call_result = \"张三同学的生日是2008年8月8日\"\n", "message_2 = app_client.run(\n", " conversation_id=conversation_id,\n", " tool_outputs=[{\n", " \"tool_call_id\": tool_call_id,\n", " \"output\": tool_call_result\n", " }]\n", ")\n", "print(message_2.content)\n", "```\n", "\n", "其中`AppBuilderClient`的`run`方法是核心,我们展开该函数的定义和参数介绍:\n", "\n", "`AppBuilderClient().run() -> Message`\n", "\n", "```python\n", "def run(self, conversation_id: str,\n", " query: str = \"\",\n", " file_ids: list = [],\n", " stream: bool = False,\n", " tools: list[data_class.Tool] = None,\n", " tool_outputs: list[data_class.ToolOutput] = None,\n", " **kwargs\n", " ) -> Message:\n", " r\"\"\"\n", " 参数:\n", " query (str: 必须): query内容\n", " conversation_id (str, 必须): 唯一会话ID,如需开始新的会话,请使用self.create_conversation创建新的会话\n", " file_ids(list[str], 可选):\n", " stream (bool, 可选): 为True时,流式返回,需要将message.content.answer拼接起来才是完整的回答;为False时,对应非流式返回\n", " tools(list[data_class.Tools], 可选): 一个Tools组成的列表,其中每个Tools对应一个工具的配置, 默认为None\n", " tool_outputs(list[data_class.ToolOutput], 可选): 工具输出列表,格式为list[ToolOutput], ToolOutputd内容为本地的工具执行结果,以自然语言/json dump str描述,默认为None\n", " 返回: message (obj: `Message`): 对话结果.\n", " \"\"\"\n", " pass\n", "```\n", "\n", "\n", "| 参数名称 | 参数类型 | 是否必须 | 描述 | 示例值 |\n", "| --------------- | ---------------- | -------- | ------------------------------------------------------------ | ----------------- |\n", "| conversation_id | String | 是 | 会话ID | |\n", "| query | String | 否 | query问题内容 | \"今天天气怎么样?\" |\n", "| file_ids | list[String] | 否 | 对话可引用的文档ID | |\n", "| stream | Bool | 否 | 为true时则流式返回,为false时则一次性返回所有内容, 推荐设为true,降低首token时延 | False |\n", "| tools | List[Tool] | 否 | 一个列表,其中每个字典对应一个工具的配置 | |\n", "| tools[0] | Tool | 否 | 工具配置 | |\n", "| +type | String | 否 | 枚举:
**file_retrieval**: 知识库检索工具能够理解文档内容,支持用户针对文档内容的问答。
**code_interpreter**: 代码解释器, 代码解释器能够生成并执行代码,从而协助用户解决复杂问题,涵盖科学计算(包括普通数学计算题)、数据可视化、文件编辑处理(图片、PDF文档、视频、音频等)、文件格式转换(如WAV、MP3、text、SRT、PNG、jpg、MP4、GIF、MP3等)、数据分析&清洗&处理(文件以excel、csv格式为主)、机器学习&深度学习建模&自然语言处理等多个领域。
**function**: 支持fucntion call模式调用工具 | |\n", "| +function | Function | 否 | Function工具描述
仅当**type为**`**function**` 时需要且必须填写 | |\n", "| ++name | String | 否 | 函数名
只允许数字、大小写字母和中划线和下划线,最大长度为64个字符。一次运行中唯一。 | |\n", "| ++description | String | 否 | 工具描述 | |\n", "| ++parameters | Dict | 否 | 工具参数, json_schema格式 | |\n", "| tool_outputs | List[ToolOutput] | 否 | 内容为本地的工具执行结果,以自然语言/json dump str描述 | |\n", "| tool_outputs[0] | ToolOutput | 否 | 工具执行结果 | |\n", "| +tool_call_id | String | 否 | 工具调用ID | |\n", "| +output | String | 否 | 工具输出 | |\n", "\n", "`Tool`与`Function`是本地组件的描述,类型为object,其定义如下:\n", "\n", "```python\n", "class Tool(BaseModel):\n", " type: str = \"function\"\n", " function: Function = Field(..., description=\"工具信息\")\n", "\n", "class Function(BaseModel):\n", " name: str = Field(..., description=\"工具名称\")\n", " description: str = Field(..., description=\"工具描述\")\n", " parameters: dict = Field(..., description=\"工具参数, json_schema格式\")\n", "```\n", "\n", "`ToolOutput`是本地组件的执行结果,需要再次上传到Agent,参与思考,类型为object,其定义如下:\n", "```python\n", "class ToolOutput(BaseModel):\n", " tool_call_id: str = Field(..., description=\"工具调用ID\")\n", " output: str = Field(..., description=\"工具输出\")\n", "\n", "```" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# 4、ToolCall的第一个例子\n", "\n", "我们继续以上文中提到的查找张三生日为例,看一下完整的流程是怎么样的\n", "\n", "### 前置工作,在AppBuilder平台上创建一个白板应用(可以跳过)\n", "\n", "网页链接:https://appbuilder.cloud.baidu.com/\n", "\n", "注册后,进入控制台:https://console.bce.baidu.com/ai_apaas/dialogHome\n", "\n", "点击左上角的【创建应用】-> 【AI自动配置】,我们输入以下Prompt,自动生成Agent:`你是智能问题解决者,自动集成多种工具组件,解决用户各类问题`\n", "\n", "\"drawing\"\n", "\n", "最终生成的Agent长这个样子:\n", "\n", "\"drawing\"\n", "\n", "而后点击【发布】,分别在控制台的左侧【个人空间】获取`app_id`,在【我的密钥】获取`APPBUILDER_TOEN`后,就可以开始后续的操作了。\n", "\n", "当然,下面的示例代码中,我们已经提供了可以直接运行的试用Token与App,你可以直接上手运行" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "import os\n", "import appbuilder\n", "\n", "# AppBuilder Token,替换为您个人的Token\n", "os.environ[\"APPBUILDER_TOKEN\"] = \"your api key\"\n", "\n", "# 应用为:智能问题解决者\n", "app_id = \"b9473e78-754b-463a-916b-f0a9097a8e5f\"\n", "app_client = appbuilder.AppBuilderClient(app_id)\n", "conversation_id = app_client.create_conversation()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "首次提问一个问题,应用不具备该能力,通过回答可以印证\n", "\n", "- 由于并没有关于张三同学的信息,所以Agent无法实现查询" ] }, { "cell_type": "code", "execution_count": 24, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Agent第一次回答: 很抱歉,由于个人隐私保护的原则,我无法直接查询并告知您本公司张三同学的生日。如果您需要了解这个信息,建议您通过合法且正当的途径,比如直接询问张三同学本人,或者查阅公司内部的员工档案,但前提是您需要确保有合适的权限和授权。尊重和保护个人隐私是我们每个人的责任。\n" ] } ], "source": [ "message_1 = app_client.run(\n", " conversation_id=conversation_id,\n", " query=\"请问本公司的张三同学的生日是哪天?\",\n", ")\n", "print(\"Agent第一次回答: {}\".format(message_1.content.answer))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "**output**\n", "```\n", "Agent第一次回答: 为了回答这个问题,我们首先需要明确几个关键点:\n", "\n", "1. **问题理解**:\n", " - 需要确定的是“张三同学的生日”。\n", "\n", "2. **工具选择**:\n", " - 由于问题涉及的是特定个人的信息(张三的生日),这通常不是通过工具或系统查询能得到的,而是需要通过公司内部的人事记录或直接询问张三本人来获取。\n", "\n", "3. **解决方案生成**:\n", " - **步骤一**:首先,尝试访问公司的人事系统或员工档案,看是否有张三的生日信息记录。\n", " - **步骤二**:如果人事系统或员工档案中没有相关信息,或者你不具备访问权限,那么可以考虑直接询问张三本人或其同事,看是否有人知道他的生日。\n", " - **步骤三**:如果以上方法都不可行,还可以尝试联系公司的人力资源部门,看他们是否能提供相关信息。\n", "\n", "4. **注意事项**:\n", " - 在尝试获取张三的生日信息时,要确保遵守公司的隐私政策和相关法律法规,不要侵犯张三的隐私权。\n", " - 如果张三不愿意透露他的生日信息,应尊重他的选择,并停止进一步询问。\n", "\n", "5. **可能遇到的问题**:\n", " - 人事系统或员工档案中可能没有张三的生日信息。\n", " - 张三或其同事可能不愿意透露生日信息。\n", " - 人力资源部门可能因隐私政策而无法提供相关信息。\n", "\n", "综上所述,要确定张三的生日,最直接且尊重隐私的方法是直接询问张三本人,或者通过公司正式渠道(如人力资源部门)在遵守隐私政策的前提下进行查询。\n", "```\n", "\n", "\n", "##### 赋予应用一个本地查询组件能力\n", "\n", "以下示例展示了三种方式来使用 ToolCall 进行调用,并演示了如何在 AppBuilder 环境中配置和执行会话调用。\n", "\n", "**方式1:使用 JSONSchema 格式直接描述 tools 调用**\n", "\n", "- 这里我们使用info_dict模拟一个数据库查询的返回结果" ] }, { "cell_type": "code", "execution_count": 25, "metadata": {}, "outputs": [], "source": [ "def get_person_infomation(name: str):\n", " info_dict = {\n", " \"张三\": \"1980年1月1日\",\n", " \"李四\": \"1975年12月31日\",\n", " \"刘伟\": \"1990年12月30日\"\n", " }\n", "\n", " if name in info_dict:\n", " return f\"您要查找的{name}的生日是:{info_dict[name]}\"\n", " else:\n", " return f\"您要查找的{name}的信息我们暂未收录,请联系管理员添加。\"\n", " \n", "# 创建工具的描述:json_schema格式\n", "tools = [\n", " {\n", " \"type\": \"function\",\n", " \"function\": {\n", " \"name\": \"get_person_infomation\",\n", " \"description\": \"查找公司内指定人员的信息\",\n", " \"parameters\": {\n", " \"type\": \"object\",\n", " \"properties\": {\n", " \"name\": {\n", " \"type\": \"string\",\n", " \"description\": \"人员名称,例如:张三、李四\",\n", " },\n", " },\n", " \"required\": [\"name\"],\n", " },\n", " },\n", " }\n", "]" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "- 现在我们已经完成了本地tool组件的设计,接下来我们将tool的功能赋予Client应用" ] }, { "cell_type": "code", "execution_count": 26, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Agent的中间思考过程:\n", "{\n", " \"code\": 0,\n", " \"message\": \"\",\n", " \"status\": \"interrupt\",\n", " \"event_type\": \"Interrupt\",\n", " \"content_type\": \"contexts\",\n", " \"detail\": {\n", " \"text\": {\n", " \"function_call\": {\n", " \"thought\": \"用户想要查询公司内指定人员张三的生日信息,这是一个具有明确目的和关键信息的需求。根据我们可用的工具,get_person_infomation 工具能够查找公司内指定人员的信息,包括生日等。因此,通过调用这个工具并传入张三作为参数,我们可以获取到张三的生日信息,从而满足用户的需求。\",\n", " \"name\": \"get_person_infomation\",\n", " \"arguments\": {\n", " \"name\": \"张三\"\n", " },\n", " \"usage\": {\n", " \"prompt_tokens\": 564,\n", " \"completion_tokens\": 115,\n", " \"total_tokens\": 679,\n", " \"name\": \"ERNIE-4.0-8K\",\n", " \"type\": \"plan\"\n", " },\n", " \"tool_call_id\": \"baf86c61-6627-4229-bc81-a17eda1bce36\"\n", " },\n", " \"used_tool\": []\n", " }\n", " },\n", " \"usage\": null,\n", " \"tool_calls\": [\n", " {\n", " \"id\": \"baf86c61-6627-4229-bc81-a17eda1bce36\",\n", " \"type\": \"function\",\n", " \"function\": {\n", " \"name\": \"get_person_infomation\",\n", " \"arguments\": {\n", " \"name\": \"张三\"\n", " }\n", " }\n", " }\n", " ]\n", "}\n", "Agent思考结束,等待我们上传本地结果\n", "\n" ] } ], "source": [ "message_2 = app_client.run(\n", " conversation_id=conversation_id,\n", " query=\"请问本公司的张三同学的生日是哪天?\",\n", " tools=tools\n", ")\n", "print(\"Agent的中间思考过程:\")\n", "print(message_2.content.events[-1].model_dump_json(indent=4))\n", "print(\"Agent思考结束,等待我们上传本地结果\\n\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "**output**\n", "这部分输出为Client应用的思考过程\n", "```\n", "Agent的中间思考过程:\n", "{\n", " \"code\": 0,\n", " \"message\": \"\",\n", " \"status\": \"interrupt\",\n", " \"event_type\": \"Interrupt\",\n", " \"content_type\": \"contexts\",\n", " \"detail\": {\n", " \"text\": {\n", " \"function_call\": {\n", " \"thought\": \"用户想要查询公司内张三同学的生日信息,这个需求很明确,且背景信息也足够。我可以使用get_person_infomation工具来查找张三的生日信息。\",\n", " \"name\": \"get_person_infomation\",\n", " \"arguments\": {\n", " \"name\": \"张三\"\n", " },\n", " \"usage\": {\n", " \"prompt_tokens\": 697,\n", " \"completion_tokens\": 87,\n", " \"total_tokens\": 784,\n", " \"name\": \"ERNIE-4.0-Turbo-8K\",\n", " \"type\": \"plan\"\n", " },\n", " \"tool_call_id\": \"c23309f7-e24a-4476-85e2-3ef9cfd4f6ed\"\n", " },\n", " \"used_tool\": []\n", "...\n", " ]\n", "}\n", "Agent思考结束,等待我们上传本地结果\n", "```\n", "\n", "- 大模型下发了调用本地函数的参数,我们使用这个参数调用本地函数" ] }, { "cell_type": "code", "execution_count": 27, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "local_func_result: 您要查找的张三的生日是:1980年1月1日\n", "\n" ] } ], "source": [ "tool_call = message_2.content.events[-1].tool_calls[-1]\n", "tool_call_id = tool_call.id\n", "tool_call_argument = tool_call.function.arguments\n", "local_func_result = get_person_infomation(**tool_call_argument)\n", "print(\"local_func_result: {}\\n\".format(local_func_result))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "**output**\n", "```\n", "local_func_result: 您要查找的张三的生日是:1980年1月1日\n", "```\n", "\n", "- 向应用返回本地运行的结果,完成本地函数toolcall调用" ] }, { "cell_type": "code", "execution_count": 28, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Agent 拥有了本地函数调用能力后,回答是: 您要找的张三的生日是1980年1月1日。\n" ] } ], "source": [ "message_3 = app_client.run(\n", " conversation_id=conversation_id,\n", " tool_outputs=[{\n", " \"tool_call_id\": tool_call_id,\n", " \"output\": local_func_result\n", " }]\n", ")\n", "print(\"Agent 拥有了本地函数调用能力后,回答是: {}\".format(message_3.content.answer))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "**output**\n", "```\n", "Agent的中间思考过程:\n", "{\n", " \"code\": 0,\n", " \"message\": \"\",\n", " \"status\": \"interrupt\",\n", " \"event_type\": \"Interrupt\",\n", " \"content_type\": \"contexts\",\n", " \"detail\": {\n", " \"text\": {\n", " \"function_call\": {\n", " \"thought\": \"用户想要查询公司内张三同学的生日信息,这个需求很明确,且背景信息也足够。我可以使用get_person_infomation工具来查找张三的生日信息。\",\n", " \"name\": \"get_person_infomation\",\n", " \"arguments\": {\n", " \"name\": \"张三\"\n", " },\n", " \"usage\": {\n", " \"prompt_tokens\": 697,\n", " \"completion_tokens\": 87,\n", " \"total_tokens\": 784,\n", " \"name\": \"ERNIE-4.0-Turbo-8K\",\n", " \"type\": \"plan\"\n", " },\n", " \"tool_call_id\": \"c23309f7-e24a-4476-85e2-3ef9cfd4f6ed\"\n", " },\n", " \"used_tool\": []\n", "...\n", " ]\n", "}\n", "Agent思考结束,等待我们上传本地结果\n", "\n", "Output is truncated. View as a scrollable element or open in a text editor. Adjust cell output settings...\n", "\n", "local_func_result: 您要查找的张三的生日是:1980年1月1日\n", "\n", "Agent 拥有了本地函数调用能力后,回答是: # 解决方案\n", "\n", "## 问题分析\n", "\n", "用户想要查询公司内张三同学的生日信息。这是一个明确且具体的需求,我们可以通过`get_person_infomation`工具来获取这一信息。\n", "\n", "## 工具运用\n", "\n", "1. **工具选择**:`get_person_infomation`\n", "2. **参数设置**:\n", "\n", "\t* `name`:张三\n", "\n", "3. **执行结果**:张三的生日是1980年1月1日。\n", "\n", "## 解决方案步骤\n", "\n", "1. 使用`get_person_infomation`工具,并设置参数`name`为“张三”。\n", "2. 等待工具执行,并获取张三的生日信息。\n", "3. 将获取到的生日信息(1980年1月1日)告知用户。\n", "\n", "## 注意事项\n", "\n", "* 确保在使用`get_person_infomation`工具时,输入的姓名与公司内部记录的姓名完全一致,以避免查询错误。\n", "* 如果工具返回“未找到”或类似结果,请检查姓名是否有误或联系公司人事部门确认信息。\n", "\n", "通过上述步骤,我们可以准确地回答用户的问题,并提供张三的生日信息。\n", "```" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "**方式2:使用 function_to_model 将函数对象传递为 ToolCall 的调用**\n", "\n", "- 前置步骤:设置环境变量和初始化操作" ] }, { "cell_type": "code", "execution_count": 1, "metadata": {}, "outputs": [], "source": [ "import appbuilder\n", "import os\n", "import json\n", "\n", "# 请前往千帆AppBuilder官网创建密钥,流程详见:https://cloud.baidu.com/doc/AppBuilder/s/Olq6grrt6#1%E3%80%81%E5%88%9B%E5%BB%BA%E5%AF%86%E9%92%A5\n", "# 设置环境变量\n", "# AppBuilder Token,替换为您个人的Token\n", "os.environ[\"APPBUILDER_TOKEN\"] = \"your api key\"\n", "\n", "# 应用为:智能问题解决者\n", "app_id = \"b9473e78-754b-463a-916b-f0a9097a8e5f\"\n", "# 初始化智能体\n", "client = appbuilder.AppBuilderClient(app_id)\n", "# 创建会话\n", "conversation_id = client.create_conversation()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "- 定义函数和函数列表,按照谷歌规范写好注释" ] }, { "cell_type": "code", "execution_count": 2, "metadata": {}, "outputs": [], "source": [ "#定义示例函数\n", "def get_current_weather(location: str, unit: str) -> str:\n", " \"\"\"获取指定中国城市的当前天气信息。\n", "\n", " 仅支持中国城市的天气查询。参数 `location` 为中国城市名称,其他国家城市不支持天气查询。\n", "\n", " Args:\n", " location (str): 城市名,例如:\"北京\"。\n", " unit (int): 温度单位,支持 \"celsius\" 或 \"fahrenheit\"。\n", "\n", " Returns:\n", " str: 天气情况描述\n", " \"\"\"\n", " return \"北京今天25度\"\n", " \n", "#定义函数列表\n", "functions = [get_current_weather]\n", "function_map = {f.__name__: f for f in functions}" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "- 查看一下function_to_model函数转化的结果" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "{\n", " \"type\": \"function\",\n", " \"function\": {\n", " \"name\": \"get_current_weather\",\n", " \"description\": \"获取指定中国城市的当前天气信息。\\n\\n 仅支持中国城市的天气查询。参数 `location` 为中国城市名称,其他国家城市不支持天气查询。\\n\\n Args:\\n location (str): 城市名,例如:\\\"北京\\\"。\\n unit (int): 温度单位,支持 \\\"celsius\\\" 或 \\\"fahrenheit\\\"。\\n\\n Returns:\\n str: 天气情况描述\",\n", " \"parameters\": {\n", " \"type\": \"object\",\n", " \"properties\": {\n", " \"location\": {\n", " \"name\": \"location\",\n", " \"type\": \"str\",\n", " \"description\": null,\n", " \"required\": true\n", " },\n", " \"unit\": {\n", " \"name\": \"unit\",\n", " \"type\": \"str\",\n", " \"description\": null,\n", " \"required\": true\n", " }\n", " },\n", " \"required\": [\n", " \"location\",\n", " \"unit\"\n", " ]\n", " },\n", " \"returns\": {\n", " \"type\": \"str\",\n", " \"description\": null\n", " }\n", " }\n", "}\n" ] } ], "source": [ "print(json.dumps(appbuilder.Manifest.from_function(get_current_weather), indent=4, ensure_ascii=False))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "- 调用大模型进行函数调用" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [ { "ename": "BadRequestException", "evalue": "request_id=928f30c6-d712-448b-a831-dc4cd15307b0 , http status code is 400, body is {\"code\": \"QuotaLimitExceeded\", \"message\": \"quota\\u8d44\\u6e90\\u5df2\\u8fbe\\u4e0a\\u9650\", \"request_id\": \"928f30c6-d712-448b-a831-dc4cd15307b0\"}", "output_type": "error", "traceback": [ "\u001B[0;31m---------------------------------------------------------------------------\u001B[0m", "\u001B[0;31mBadRequestException\u001B[0m Traceback (most recent call last)", "Cell \u001B[0;32mIn[5], line 2\u001B[0m\n\u001B[1;32m 1\u001B[0m \u001B[38;5;66;03m#调用大模型\u001B[39;00m\n\u001B[0;32m----> 2\u001B[0m msg \u001B[38;5;241m=\u001B[39m \u001B[43mclient\u001B[49m\u001B[38;5;241;43m.\u001B[39;49m\u001B[43mrun\u001B[49m\u001B[43m(\u001B[49m\n\u001B[1;32m 3\u001B[0m \u001B[43m \u001B[49m\u001B[43mconversation_id\u001B[49m\u001B[38;5;241;43m=\u001B[39;49m\u001B[43mconversation_id\u001B[49m\u001B[43m,\u001B[49m\n\u001B[1;32m 4\u001B[0m \u001B[43m \u001B[49m\u001B[43mquery\u001B[49m\u001B[38;5;241;43m=\u001B[39;49m\u001B[38;5;124;43m\"\u001B[39;49m\u001B[38;5;124;43m今天北京的天气怎么样?\u001B[39;49m\u001B[38;5;124;43m\"\u001B[39;49m\u001B[43m,\u001B[49m\n\u001B[1;32m 5\u001B[0m \u001B[43m \u001B[49m\u001B[43mtools\u001B[49m\u001B[43m \u001B[49m\u001B[38;5;241;43m=\u001B[39;49m\u001B[43m \u001B[49m\u001B[43m[\u001B[49m\u001B[43mappbuilder\u001B[49m\u001B[38;5;241;43m.\u001B[39;49m\u001B[43mManifest\u001B[49m\u001B[38;5;241;43m.\u001B[39;49m\u001B[43mfrom_function\u001B[49m\u001B[43m(\u001B[49m\u001B[43mf\u001B[49m\u001B[43m)\u001B[49m\u001B[38;5;241;43m.\u001B[39;49m\u001B[43mmodel_dump\u001B[49m\u001B[43m(\u001B[49m\u001B[43m)\u001B[49m\u001B[43m \u001B[49m\u001B[38;5;28;43;01mfor\u001B[39;49;00m\u001B[43m \u001B[49m\u001B[43mf\u001B[49m\u001B[43m \u001B[49m\u001B[38;5;129;43;01min\u001B[39;49;00m\u001B[43m \u001B[49m\u001B[43mfunctions\u001B[49m\u001B[43m]\u001B[49m\n\u001B[1;32m 6\u001B[0m \u001B[43m \u001B[49m\u001B[43m)\u001B[49m\n\u001B[1;32m 7\u001B[0m \u001B[38;5;28mprint\u001B[39m(msg\u001B[38;5;241m.\u001B[39mmodel_dump_json(indent\u001B[38;5;241m=\u001B[39m\u001B[38;5;241m4\u001B[39m))\n\u001B[1;32m 8\u001B[0m \u001B[38;5;66;03m# 获取最后的事件和工具调用信息\u001B[39;00m\n", "File \u001B[0;32m/opt/anaconda3/envs/testenv/lib/python3.9/site-packages/appbuilder/core/console/appbuilder_client/appbuilder_client.py:306\u001B[0m, in \u001B[0;36mAppBuilderClient.run\u001B[0;34m(self, conversation_id, query, file_ids, stream, tools, tool_outputs, tool_choice, end_user_id, action, **kwargs)\u001B[0m\n\u001B[1;32m 302\u001B[0m url \u001B[38;5;241m=\u001B[39m \u001B[38;5;28mself\u001B[39m\u001B[38;5;241m.\u001B[39mhttp_client\u001B[38;5;241m.\u001B[39mservice_url_v2(\u001B[38;5;124m\"\u001B[39m\u001B[38;5;124m/app/conversation/runs\u001B[39m\u001B[38;5;124m\"\u001B[39m)\n\u001B[1;32m 303\u001B[0m response \u001B[38;5;241m=\u001B[39m \u001B[38;5;28mself\u001B[39m\u001B[38;5;241m.\u001B[39mhttp_client\u001B[38;5;241m.\u001B[39msession\u001B[38;5;241m.\u001B[39mpost(\n\u001B[1;32m 304\u001B[0m url, headers\u001B[38;5;241m=\u001B[39mheaders, json\u001B[38;5;241m=\u001B[39mreq\u001B[38;5;241m.\u001B[39mmodel_dump(), timeout\u001B[38;5;241m=\u001B[39m\u001B[38;5;28;01mNone\u001B[39;00m, stream\u001B[38;5;241m=\u001B[39m\u001B[38;5;28;01mTrue\u001B[39;00m\n\u001B[1;32m 305\u001B[0m )\n\u001B[0;32m--> 306\u001B[0m \u001B[38;5;28;43mself\u001B[39;49m\u001B[38;5;241;43m.\u001B[39;49m\u001B[43mhttp_client\u001B[49m\u001B[38;5;241;43m.\u001B[39;49m\u001B[43mcheck_response_header\u001B[49m\u001B[43m(\u001B[49m\u001B[43mresponse\u001B[49m\u001B[43m)\u001B[49m\n\u001B[1;32m 307\u001B[0m request_id \u001B[38;5;241m=\u001B[39m \u001B[38;5;28mself\u001B[39m\u001B[38;5;241m.\u001B[39mhttp_client\u001B[38;5;241m.\u001B[39mresponse_request_id(response)\n\u001B[1;32m 308\u001B[0m \u001B[38;5;28;01mif\u001B[39;00m stream:\n", "File \u001B[0;32m/opt/anaconda3/envs/testenv/lib/python3.9/site-packages/appbuilder/core/_client.py:120\u001B[0m, in \u001B[0;36mHTTPClient.check_response_header\u001B[0;34m(response)\u001B[0m\n\u001B[1;32m 116\u001B[0m message \u001B[38;5;241m=\u001B[39m \u001B[38;5;124m\"\u001B[39m\u001B[38;5;124mrequest_id=\u001B[39m\u001B[38;5;132;01m{}\u001B[39;00m\u001B[38;5;124m , http status code is \u001B[39m\u001B[38;5;132;01m{}\u001B[39;00m\u001B[38;5;124m, body is \u001B[39m\u001B[38;5;132;01m{}\u001B[39;00m\u001B[38;5;124m\"\u001B[39m\u001B[38;5;241m.\u001B[39mformat(\n\u001B[1;32m 117\u001B[0m \u001B[38;5;18m__class__\u001B[39m\u001B[38;5;241m.\u001B[39mresponse_request_id(response), status_code, response\u001B[38;5;241m.\u001B[39mtext\n\u001B[1;32m 118\u001B[0m )\n\u001B[1;32m 119\u001B[0m \u001B[38;5;28;01mif\u001B[39;00m status_code \u001B[38;5;241m==\u001B[39m requests\u001B[38;5;241m.\u001B[39mcodes\u001B[38;5;241m.\u001B[39mbad_request:\n\u001B[0;32m--> 120\u001B[0m \u001B[38;5;28;01mraise\u001B[39;00m BadRequestException(message)\n\u001B[1;32m 121\u001B[0m \u001B[38;5;28;01melif\u001B[39;00m status_code \u001B[38;5;241m==\u001B[39m requests\u001B[38;5;241m.\u001B[39mcodes\u001B[38;5;241m.\u001B[39mforbidden:\n\u001B[1;32m 122\u001B[0m \u001B[38;5;28;01mraise\u001B[39;00m ForbiddenException(message)\n", "\u001B[0;31mBadRequestException\u001B[0m: request_id=928f30c6-d712-448b-a831-dc4cd15307b0 , http status code is 400, body is {\"code\": \"QuotaLimitExceeded\", \"message\": \"quota\\u8d44\\u6e90\\u5df2\\u8fbe\\u4e0a\\u9650\", \"request_id\": \"928f30c6-d712-448b-a831-dc4cd15307b0\"}" ] } ], "source": [ "#调用大模型\n", "msg = client.run(\n", " conversation_id=conversation_id,\n", " query=\"今天北京的天气怎么样?\",\n", " tools = [appbuilder.Manifest.from_function(f) for f in functions]\n", " )\n", "print(msg.model_dump_json(indent=4))\n", "# 获取最后的事件和工具调用信息\n", "event = msg.content.events[-1]\n", "tool_call = event.tool_calls[-1]\n", "\n", "# 获取函数名称和参数\n", "name = tool_call.function.name\n", "args = tool_call.function.arguments\n", "\n", "# 将函数名称映射到具体的函数并执行\n", "raw_result = function_map[name](**args)\n", "\n", "# 传递工具的输出\n", "msg_2 = client.run(\n", " conversation_id=conversation_id,\n", " tool_outputs=[{\n", " \"tool_call_id\": tool_call.id,\n", " \"output\": str(raw_result)\n", " }],\n", ")\n", "print(msg_2.model_dump_json(indent=4))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "**方式3: 使用装饰器进行描述**\n", "\n", "- 前置步骤:设置环境变量和初始化操作" ] }, { "cell_type": "code", "execution_count": 6, "metadata": {}, "outputs": [], "source": [ "import os\n", "import json\n", "import appbuilder\n", "from appbuilder import manifest, manifest_parameter\n", "\n", "# 请前往千帆AppBuilder官网创建密钥,流程详见:https://cloud.baidu.com/doc/AppBuilder/s/Olq6grrt6#1%E3%80%81%E5%88%9B%E5%BB%BA%E5%AF%86%E9%92%A5\n", "# 设置环境变量\n", "# AppBuilder Token,替换为您个人的Token\n", "#os.environ[\"APPBUILDER_TOKEN\"] = \"your api key\"\n", "os.environ[\"APPBUILDER_TOKEN\"] = \"your api key\"\n", "\n", "# 应用为:智能问题解决者\n", "#app_id = \"b9473e78-754b-463a-916b-f0a9097a8e5f\"\n", "app_id = \"7cc4c21f-0e25-4a76-baf7-01a2b923a1a7\"\n", "# 初始化智能体\n", "client = appbuilder.AppBuilderClient(app_id)\n", "# 创建会话\n", "conversation_id = client.create_conversation()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "- 定义函数和函数列表,并用装饰器对函数进行进行描述." ] }, { "cell_type": "code", "execution_count": 7, "metadata": {}, "outputs": [], "source": [ "#使用function装饰描述函数,function_parameter装饰器描述参数,function_return装饰器描述函数返回值。\n", "@manifest(description=\"获取指定中国城市的当前天气信息。仅支持中国城市的天气查询。参数 `location` 为中国城市名称,其他国家城市不支持天气查询。\")\n", "@manifest_parameter(name=\"location\", description=\"城市名,例如:北京。\")\n", "@manifest_parameter(name=\"unit\", description=\"温度单位,支持 'celsius' 或 'fahrenheit'\")\n", "#定义示例函数\n", "def get_current_weather(location: str, unit: str) -> str:\n", " return \"北京今天25度\"\n", "\n", "#定义函数列表\n", "functions = [get_current_weather]\n", "function_map = {f.__name__: f for f in functions}" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "- 查看一下装饰器的转化内容" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "{\n", " \"type\": \"function\",\n", " \"function\": {\n", " \"name\": \"get_current_weather\",\n", " \"description\": \"获取指定中国城市的当前天气信息。仅支持中国城市的天气查询。参数 `location` 为中国城市名称,其他国家城市不支持天气查询。\",\n", " \"parameters\": {\n", " \"type\": \"object\",\n", " \"properties\": {\n", " \"location\": {\n", " \"name\": \"location\",\n", " \"type\": \"str\",\n", " \"description\": \"城市名,例如:北京。\",\n", " \"required\": true\n", " },\n", " \"unit\": {\n", " \"name\": \"unit\",\n", " \"type\": \"str\",\n", " \"description\": \"温度单位,支持 'celsius' 或 'fahrenheit'\",\n", " \"required\": true\n", " }\n", " },\n", " \"required\": [\n", " \"location\",\n", " \"unit\"\n", " ]\n", " }\n", " }\n", "}\n" ] } ], "source": [ "# 将 model_dump() 的输出进行格式化打印\n", "print(\n", " json.dumps(\n", " appbuilder.Manifest.from_function(get_current_weather), indent=4, ensure_ascii=False\n", " )\n", ")" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [ { "ename": "BadRequestException", "evalue": "request_id=76224253-163f-46d3-a5eb-b22c6fcec2be , http status code is 400, body is {\"code\": \"QuotaLimitExceeded\", \"message\": \"quota\\u8d44\\u6e90\\u5df2\\u8fbe\\u4e0a\\u9650\", \"request_id\": \"76224253-163f-46d3-a5eb-b22c6fcec2be\"}", "output_type": "error", "traceback": [ "\u001B[0;31m---------------------------------------------------------------------------\u001B[0m", "\u001B[0;31mBadRequestException\u001B[0m Traceback (most recent call last)", "Cell \u001B[0;32mIn[10], line 2\u001B[0m\n\u001B[1;32m 1\u001B[0m \u001B[38;5;66;03m#调用大模型\u001B[39;00m\n\u001B[0;32m----> 2\u001B[0m msg \u001B[38;5;241m=\u001B[39m \u001B[43mclient\u001B[49m\u001B[38;5;241;43m.\u001B[39;49m\u001B[43mrun\u001B[49m\u001B[43m(\u001B[49m\n\u001B[1;32m 3\u001B[0m \u001B[43m \u001B[49m\u001B[43mconversation_id\u001B[49m\u001B[38;5;241;43m=\u001B[39;49m\u001B[43mconversation_id\u001B[49m\u001B[43m,\u001B[49m\n\u001B[1;32m 4\u001B[0m \u001B[43m \u001B[49m\u001B[43mquery\u001B[49m\u001B[38;5;241;43m=\u001B[39;49m\u001B[38;5;124;43m\"\u001B[39;49m\u001B[38;5;124;43m今天北京的天气怎么样?\u001B[39;49m\u001B[38;5;124;43m\"\u001B[39;49m\u001B[43m,\u001B[49m\n\u001B[1;32m 5\u001B[0m \u001B[43m \u001B[49m\u001B[43mtools\u001B[49m\u001B[43m \u001B[49m\u001B[38;5;241;43m=\u001B[39;49m\u001B[43m \u001B[49m\u001B[43m[\u001B[49m\u001B[43mget_current_weather\u001B[49m\u001B[38;5;241;43m.\u001B[39;49m\u001B[43m__ab_manifest__\u001B[49m\u001B[38;5;241;43m.\u001B[39;49m\u001B[43mmodel_dump\u001B[49m\u001B[43m(\u001B[49m\u001B[43m)\u001B[49m\u001B[43m]\u001B[49m\n\u001B[1;32m 6\u001B[0m \u001B[43m \u001B[49m\u001B[43m)\u001B[49m\n\u001B[1;32m 7\u001B[0m \u001B[38;5;28mprint\u001B[39m(msg\u001B[38;5;241m.\u001B[39mmodel_dump_json(indent\u001B[38;5;241m=\u001B[39m\u001B[38;5;241m4\u001B[39m))\n\u001B[1;32m 8\u001B[0m \u001B[38;5;66;03m# 获取最后的事件和工具调用信息\u001B[39;00m\n", "File \u001B[0;32m/opt/anaconda3/envs/testenv/lib/python3.9/site-packages/appbuilder/core/console/appbuilder_client/appbuilder_client.py:306\u001B[0m, in \u001B[0;36mAppBuilderClient.run\u001B[0;34m(self, conversation_id, query, file_ids, stream, tools, tool_outputs, tool_choice, end_user_id, action, **kwargs)\u001B[0m\n\u001B[1;32m 302\u001B[0m url \u001B[38;5;241m=\u001B[39m \u001B[38;5;28mself\u001B[39m\u001B[38;5;241m.\u001B[39mhttp_client\u001B[38;5;241m.\u001B[39mservice_url_v2(\u001B[38;5;124m\"\u001B[39m\u001B[38;5;124m/app/conversation/runs\u001B[39m\u001B[38;5;124m\"\u001B[39m)\n\u001B[1;32m 303\u001B[0m response \u001B[38;5;241m=\u001B[39m \u001B[38;5;28mself\u001B[39m\u001B[38;5;241m.\u001B[39mhttp_client\u001B[38;5;241m.\u001B[39msession\u001B[38;5;241m.\u001B[39mpost(\n\u001B[1;32m 304\u001B[0m url, headers\u001B[38;5;241m=\u001B[39mheaders, json\u001B[38;5;241m=\u001B[39mreq\u001B[38;5;241m.\u001B[39mmodel_dump(), timeout\u001B[38;5;241m=\u001B[39m\u001B[38;5;28;01mNone\u001B[39;00m, stream\u001B[38;5;241m=\u001B[39m\u001B[38;5;28;01mTrue\u001B[39;00m\n\u001B[1;32m 305\u001B[0m )\n\u001B[0;32m--> 306\u001B[0m \u001B[38;5;28;43mself\u001B[39;49m\u001B[38;5;241;43m.\u001B[39;49m\u001B[43mhttp_client\u001B[49m\u001B[38;5;241;43m.\u001B[39;49m\u001B[43mcheck_response_header\u001B[49m\u001B[43m(\u001B[49m\u001B[43mresponse\u001B[49m\u001B[43m)\u001B[49m\n\u001B[1;32m 307\u001B[0m request_id \u001B[38;5;241m=\u001B[39m \u001B[38;5;28mself\u001B[39m\u001B[38;5;241m.\u001B[39mhttp_client\u001B[38;5;241m.\u001B[39mresponse_request_id(response)\n\u001B[1;32m 308\u001B[0m \u001B[38;5;28;01mif\u001B[39;00m stream:\n", "File \u001B[0;32m/opt/anaconda3/envs/testenv/lib/python3.9/site-packages/appbuilder/core/_client.py:120\u001B[0m, in \u001B[0;36mHTTPClient.check_response_header\u001B[0;34m(response)\u001B[0m\n\u001B[1;32m 116\u001B[0m message \u001B[38;5;241m=\u001B[39m \u001B[38;5;124m\"\u001B[39m\u001B[38;5;124mrequest_id=\u001B[39m\u001B[38;5;132;01m{}\u001B[39;00m\u001B[38;5;124m , http status code is \u001B[39m\u001B[38;5;132;01m{}\u001B[39;00m\u001B[38;5;124m, body is \u001B[39m\u001B[38;5;132;01m{}\u001B[39;00m\u001B[38;5;124m\"\u001B[39m\u001B[38;5;241m.\u001B[39mformat(\n\u001B[1;32m 117\u001B[0m \u001B[38;5;18m__class__\u001B[39m\u001B[38;5;241m.\u001B[39mresponse_request_id(response), status_code, response\u001B[38;5;241m.\u001B[39mtext\n\u001B[1;32m 118\u001B[0m )\n\u001B[1;32m 119\u001B[0m \u001B[38;5;28;01mif\u001B[39;00m status_code \u001B[38;5;241m==\u001B[39m requests\u001B[38;5;241m.\u001B[39mcodes\u001B[38;5;241m.\u001B[39mbad_request:\n\u001B[0;32m--> 120\u001B[0m \u001B[38;5;28;01mraise\u001B[39;00m BadRequestException(message)\n\u001B[1;32m 121\u001B[0m \u001B[38;5;28;01melif\u001B[39;00m status_code \u001B[38;5;241m==\u001B[39m requests\u001B[38;5;241m.\u001B[39mcodes\u001B[38;5;241m.\u001B[39mforbidden:\n\u001B[1;32m 122\u001B[0m \u001B[38;5;28;01mraise\u001B[39;00m ForbiddenException(message)\n", "\u001B[0;31mBadRequestException\u001B[0m: request_id=76224253-163f-46d3-a5eb-b22c6fcec2be , http status code is 400, body is {\"code\": \"QuotaLimitExceeded\", \"message\": \"quota\\u8d44\\u6e90\\u5df2\\u8fbe\\u4e0a\\u9650\", \"request_id\": \"76224253-163f-46d3-a5eb-b22c6fcec2be\"}" ] } ], "source": [ "# 调用大模型\n", "msg = client.run(\n", " conversation_id=conversation_id,\n", " query=\"今天北京的天气怎么样?\",\n", " tools=[appbuilder.Manifest.from_function(get_current_weather)],\n", ")\n", "print(msg.model_dump_json(indent=4))\n", "# 获取最后的事件和工具调用信息\n", "event = msg.content.events[-1]\n", "tool_call = event.tool_calls[-1]\n", "\n", "# 获取函数名称和参数\n", "name = tool_call.function.name\n", "args = tool_call.function.arguments\n", "\n", "# 将函数名称映射到具体的函数并执行\n", "raw_result = function_map[name](**args)\n", "\n", "# 传递工具的输出\n", "msg_2 = client.run(\n", " conversation_id=conversation_id,\n", " tool_outputs=[{\n", " \"tool_call_id\": tool_call.id,\n", " \"output\": str(raw_result)\n", " }],\n", ")\n", "print(msg_2.model_dump_json(indent=4))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# 5、ToolCal第二个例子-调用本地工具并且代码更简洁\n", "\n", "我们可以使用AppBuilderClient应用来执行tool_call操作,完成指定的命令,但是需要自己配置client的思考与运行流程,较为繁琐。SDK提供了使用AppBuilderEventHandler简化tool_call操作的功能\n", "\n", "##### 配置运行环境&导入Client应用" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "import os\n", "import appbuilder\n", "\n", "\n", "# AppBuilder Token,替换为您个人的Token\n", "os.environ[\"APPBUILDER_TOKEN\"] = \"your api key\"\n", "\n", "# 应用为:智能问题解决者\n", "app_id = \"b9473e78-754b-463a-916b-f0a9097a8e5f\"\n", "app_client = appbuilder.AppBuilderClient(app_id)\n", "conversation_id = app_client.create_conversation()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "##### 继承AppBuilderEventHandler类,并实现针对各类型event的处理方法" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "from appbuilder.core.console.appbuilder_client.event_handler import AppBuilderEventHandler\n", "class MyEventHandler(AppBuilderEventHandler):\n", " def execute_local_command(self, cmd: str):\n", " import subprocess\n", " try:\n", " result = subprocess.check_output(cmd, shell=True).decode(\"utf-8\")\n", " if result.strip() == \"\":\n", " return \"命令执行成功,无返回值\"\n", " return result\n", " except Exception as e:\n", " return str(e)\n", " \n", " def interrupt(self, run_context, run_response):\n", " thought = run_context.current_thought\n", " # 绿色打印\n", " print(\"\\033[1;32m\", \"-> Agent 中间思考: \", thought, \"\\033[0m\")\n", "\n", " tool_output = []\n", " for tool_call in run_context.current_tool_calls:\n", " tool_call_id = tool_call.id\n", " tool_res = self.execute_local_command(\n", " **tool_call.function.arguments)\n", " # 蓝色打印\n", " print(\"\\033[1;34m\", \"-> 本地ToolCall结果: \\n\", tool_res, \"\\033[0m\\n\")\n", " tool_output.append(\n", " {\n", " \"tool_call_id\": tool_call_id,\n", " \"output\": tool_res\n", " }\n", " )\n", " return tool_output\n", " \n", " def success(self, run_context, run_response):\n", " print(\"\\n\\033[1;31m\",\"-> Agent 非流式回答: \\n\", run_response.answer, \"\\033[0m\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "##### 定义本地的tools工具\n", "\n", "通过`subprocess.check_output`方法,可以在终端中执行命令,并返回执行结果" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "tools = [\n", " {\n", " \"type\": \"function\",\n", " \"function\": {\n", " \"name\": \"execute_local_command\",\n", " \"description\": \"可以在bash环境中,执行输入的指令,注意,一次只能执行一个原子命令。例如:ls\",\n", " \"parameters\": {\n", " \"type\": \"object\",\n", " \"properties\": {\n", " \"cmd\": {\n", " \"type\": \"string\",\n", " \"description\": \"需要执行的指令\",\n", " },\n", " },\n", " \"required\": [\"cmd\"],\n", " },\n", " },\n", " }\n", "]\n", "\n", "with app_client.run_with_handler(\n", " conversation_id = conversation_id,\n", " query = \"请问当前文件夹下有哪些文件?如果没有test.txt文件,请新建一个test.txt文件,内容为:Hello World!\",\n", " tools = tools,\n", " event_handler = MyEventHandler(),\n", " ) as run:\n", " run.until_done()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "**output**\n", "```\n", " -> Agent 中间思考: 首先,我需要使用execute_local_command工具来执行'ls'命令,列出当前文件夹下的所有文件。然后,我需要检查输出中是否存在test.txt文件。如果不存在,我将再次使用execute_local_command工具来执行'echo \"Hello World\" > test.txt'命令,以创建并写入test.txt文件。 \n", " -> 本地ToolCall结果: \n", " multi_tool_call.ipynb\n", "multi_tool_call.py\n", "multi_tool_call_with_handler.ipynb\n", "multi_tool_call_with_handler.py\n", "sdk_ knowledgebase.ipynb\n", "sdk_trace.ipynb\n", "simple_tool_call.ipynb\n", "simple_tool_call.py\n", "tmp.log\n", "黑神话(悟空).pdf\n", " \n", "\n", " -> Agent 中间思考: 根据execute_local_command工具的返回结果,当前文件夹下并没有test.txt文件。因此,我需要使用execute_local_command工具来执行'echo \"Hello World\" > test.txt'命令,以创建并写入test.txt文件。 \n", " -> 本地ToolCall结果: \n", " 命令执行成功,无返回值 \n", "\n", "\n", " -> Agent 非流式回答: \n", " 当前文件夹下的文件包括:\n", "\n", "- multi_tool_call.ipynb\n", "- multi_tool_call.py\n", "- multi_tool_call_with_handler.ipynb\n", "...\n", "- tmp.log\n", "- 黑神话(悟空).pdf\n", "\n", "经过检查,发现当前文件夹下**不存在**test.txt文件。因此,已经为您新建了一个test.txt文件,并写入了内容“Hello World!”。 \n", "```\n", "\n", "- 使用AppBuilderEventHandler架构可以简化client的交互方式" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# 6 使用异步调用优化toolcall并发执行效率\n", "SDK提供了异步调用接口,可以大幅提升并发执行效率。" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Copyright (c) 2024 Baidu, Inc. All Rights Reserved.\n", "#\n", "# Licensed under the Apache License, Version 2.0 (the \"License\");\n", "# you may not use this file except in compliance with the License.\n", "# You may obtain a copy of the License at\n", "#\n", "# http://www.apache.org/licenses/LICENSE-2.0\n", "#\n", "# Unless required by applicable law or agreed to in writing, software\n", "# distributed under the License is distributed on an \"AS IS\" BASIS,\n", "# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n", "# See the License for the specific language governing permissions and\n", "# limitations under the License.\n", "\n", "import appbuilder\n", "import asyncio\n", "from appbuilder.core.console.appbuilder_client.async_event_handler import (\n", " AsyncAppBuilderEventHandler,\n", ")\n", "\n", "\n", "class MyEventHandler(AsyncAppBuilderEventHandler):\n", " def get_current_weather(self, location=None, unit=\"摄氏度\"):\n", " return \"{} 的温度是 {} {}\".format(location, 20, unit)\n", "\n", " async def interrupt(self, run_context, run_response):\n", " thought = run_context.current_thought\n", " # 绿色打印\n", " print(\"\\033[1;32m\", \"-> Agent 中间思考: \", thought, \"\\033[0m\")\n", "\n", " tool_output = []\n", " for tool_call in run_context.current_tool_calls:\n", " tool_call_id = tool_call.id\n", " tool_res = self.get_current_weather(**tool_call.function.arguments)\n", " # 蓝色打印\n", " print(\"\\033[1;34m\", \"-> 本地ToolCallId: \", tool_call_id, \"\\033[0m\")\n", " print(\"\\033[1;34m\", \"-> ToolCall结果: \", tool_res, \"\\033[0m\\n\")\n", " tool_output.append({\"tool_call_id\": tool_call_id, \"output\": tool_res})\n", " return tool_output\n", "\n", " async def success(self, run_context, run_response):\n", " print(\"\\n\\033[1;31m\", \"-> Agent 非流式回答: \", run_response.answer, \"\\033[0m\")\n", "\n", "\n", "def main():\n", " app_id = \"b2a972c5-e082-46e5-b313-acbf51792422\"\n", " tools = [\n", " {\n", " \"type\": \"function\",\n", " \"function\": {\n", " \"name\": \"get_current_weather\",\n", " \"description\": \"仅支持中国城市的天气查询,参数location为中国城市名称,其他国家城市不支持天气查询\",\n", " \"parameters\": {\n", " \"type\": \"object\",\n", " \"properties\": {\n", " \"location\": {\n", " \"type\": \"string\",\n", " \"description\": \"城市名,举例:北京\",\n", " },\n", " \"unit\": {\"type\": \"string\", \"enum\": [\"摄氏度\", \"华氏度\"]},\n", " },\n", " \"required\": [\"location\", \"unit\"],\n", " },\n", " },\n", " }\n", " ]\n", "\n", " appbuilder.logger.setLoglevel(\"ERROR\")\n", "\n", " async def agent_run(client, query):\n", " conversation_id = await client.create_conversation()\n", " with await client.run_with_handler(\n", " conversation_id=conversation_id,\n", " query=query,\n", " tools=tools,\n", " event_handler=MyEventHandler(),\n", " ) as run:\n", " await run.until_done()\n", "\n", " async def agent_handle():\n", " client = appbuilder.AsyncAppBuilderClient(app_id)\n", " task1 = asyncio.create_task(agent_run(client, \"北京的天气怎么样\"))\n", " task2 = asyncio.create_task(agent_run(client, \"上海的天气怎么样\"))\n", " await asyncio.gather(task1, task2)\n", " await client.http_client.session.close()\n", "\n", " loop = asyncio.get_event_loop()\n", " loop.run_until_complete(agent_handle())\n", "\n", "\n", "if __name__ == \"__main__\":\n", " main()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# 7、项目总结\n", "\n", "本项目通过多个知识点的学习,以及两个使用AppBuilder-SDK的实操,最终完成了一个支持ToolCall AIAgent的构建。\n", "\n", "- 理论学习:了解AIAgent的基础知识\n", "- 上手实操:深入了解Agent中的FunctionCall运行流程\n", "- 上手实操:入门百度智能云千帆AppBuilder,在十分钟内打造一个个性化AIAgent\n", "- 上手实操:使用AppBuilder-SDK打造一个端云组件联动的进阶Agent\n", "\n", "\n", "希望您可以不吝`Star`,给`AppBuilder-SDK`一些鼓励,期待您的`PR`,一起共建AIAgent生态。\n", "\n", "Github地址:https://github.com/baidubce/app-builder\n", "\n", "\"drawing\"\n", "\n", "最后,您也可以进入`AppBuilder-SDK`的WX交流群,和大家一起交流AppBuilder使用及开发心得。\n", "\n", "\"drawing\"" ] } ], "metadata": { "kernelspec": { "display_name": "testenv", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.9.20" } }, "nbformat": 4, "nbformat_minor": 2 } ================================================ FILE: cookbooks/end2end_application/agent/tool_choice.ipynb ================================================ { "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# AppBuilder-SDK 指定工具调用使用实例\n", "\n", "* 注意:当前功能为试运行阶段,可能存在如下问题,如使用过程遇到其他问题,欢迎提issue或微信群讨论。\n", "\n", " * 需开启\"组件/知识库结论可直接作为回复\"\n", "\n", " * 组件名称不是界面上的原始名字,而是个人空间组件列表中的英文名\n", "\n", " * 自定义组件的参数不能使用系统参数,可以使用用户添加的参数\n", "\n", " * 部分官方组件使用的参数与界面上的参数不一致\n", "\n", "## 一、背景介绍\n", "\n", "指定工具调用是为了方便更多用户在AppBuilder官网创建应用之后,希望能直接调用自己定义的工作流或者官方的组件并应用于自己的业务中。具体的调用方法如下面的教程所示。" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 二、实操流程\n", "\n", "\n", "### 2.1 前置操作简述\n", "\n", "- 【必须】登录[百度智能云千帆AppBuilder官网](https://cloud.baidu.com/product/AppBuilder)创建账户。\n", "- 【必须】在[百度智能云千帆AppBuilder控制台](https://console.bce.baidu.com/ai_apaas/dialogHome)左侧菜单栏『我的密钥』页面获取密钥,并复制。\n", "- 【必须】在python3.9及以上的环境中安装`appbuilder-sdk`" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### 2.2、创建应用\n", "\n", "\n", "##### 2.2.1、点击创建应用界面\n", "点击[百度智能云千帆AppBuilder控制台](https://console.bce.baidu.com/ai_apaas/dialogHome)左侧菜单栏『创建应用』,开始我们的系统应用。\n", "\n", "\n", "#### 2.2.2、填写应用信息,选择工具组件\n", "\n", "我们需要首先配置该应用的基本信息,包括 名称、描述、角色指令、开场白、推荐问、能力组件等。\n", "\n", "在这里我们首先选择一个组件工具,比如天气查询组件。\n", "\n", "\"drawing\"\n", "\n", "点击图里组件上方\"应用回复设置\",打开\"组件/知识库结论可直接作为回复\"。" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### 2.2.3、发布应用\n", "\n", "我们可以在页面右上角『发布』按钮发布该应用。" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### 2.2.4 获取已发布应用的ID\n", "\n", "在 [百度智能云千帆AppBuilder控制台-我的应用](https://console.bce.baidu.com/ai_apaas/app)页面中,可以查看已发布应用的ID,我们复制该ID,开始后续的代码态操作。" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### 2.3 使用Python SDK调用已发布App\n", "\n", "当应用已经发布后,我们可以通过SDK在代码态调用,方便用户集成到自己的系统中,通过自己的系统对外提供服务。" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### 2.3.1 引入AppBuilder-SDK,设置TOKEN,设置APPID" ] }, { "cell_type": "code", "execution_count": 1, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "AppBuilder 模块导入成功!\n", "您的AppBuilder Token为:your_appbuilder_token\n", "您的AppBuilder App ID为:your_publish_app_id\n" ] } ], "source": [ "# 引入os模块,引入appbuilder 模块\n", "import os\n", "import appbuilder\n", "\n", "# 设置appbuilder的token密钥,从页面上复制粘贴我的密钥,覆盖此处的 \"your_appbuilder_token\"\n", "os.environ['APPBUILDER_TOKEN'] = \"your_appbuilder_token\"\n", "# 设置需要调用的app,从页面上复制粘贴应用ID,覆盖此处的 \"your_publish_app_id\"\n", "app_id = \"your_publish_app_id\"\n", "\n", "print(\"AppBuilder 模块导入成功!\")\n", "print(\"您的AppBuilder Token为:{}\".format(os.environ['APPBUILDER_TOKEN']))\n", "print(\"您的AppBuilder App ID为:{}\".format(app_id))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### 2.3.2 初始化Agent实例,创建会话并对话\n", "\n" ] }, { "cell_type": "code", "execution_count": 2, "metadata": {}, "outputs": [], "source": [ "# 基于app_id初始化Agent\n", "builder = appbuilder.AppBuilderClient(app_id)\n", "# 创建会话ID\n", "conversation_id = builder.create_conversation()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### 2.3.3 正常创建会话并对话\n", "\n", "- 正常对话下(不采用tool_choice模式)组件的调用受到大模型的控制,参数由大模型生成" ] }, { "cell_type": "code", "execution_count": 3, "metadata": {}, "outputs": [], "source": [ "#在不采用tool choice的情况下,正常对话APP应用依赖于应用的大模型选择调用组件,而不是直接与组件交互\n", "st = builder.run(conversation_id=conversation_id, query=\"北京今天的天气\", stream=True)" ] }, { "cell_type": "code", "execution_count": 4, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "answer='' events=[Event(code=0, message='', status='done', event_type='function_call', content_type='function_call', detail={'text': {'arguments': {'city': '北京'}, 'component_code': 'WeatherQuery', 'component_name': '天气查询'}}, usage=Usage(prompt_tokens=513, completion_tokens=37, total_tokens=550, name='Qianfan-Appbuilder-Speed-8k'), tool_calls=None)]\n" ] } ], "source": [ "# function_call路由到天气查询组件执行得到组件结果,最终经过总结得到最终结果\n", "#下面结果中天气组件的参数({'city': '北京'})由大模型生成\n", "for k in st.content:\n", " print(k)\n", " break" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### 2.3.4 tool_choice方式指定工具参数" ] }, { "cell_type": "code", "execution_count": 5, "metadata": {}, "outputs": [], "source": [ "#导入指定工具参数类\n", "from appbuilder.core.console.appbuilder_client.data_class import ToolChoiceFunction, ToolChoice\n", "#建立基本的工具调用对象,包括工具名字与参数传递\n", "tool_choice_function = ToolChoiceFunction(name=\"WeatherQuery\", input={\"city\": \"北京天气\"})\n", "tool_choice = ToolChoice(type=\"function\", function=tool_choice_function)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### 2.3.5 tool_choice方式实现对话应用" ] }, { "cell_type": "code", "execution_count": 6, "metadata": {}, "outputs": [], "source": [ "#请求指定工具tool_choice\n", "st = builder.run(conversation_id=conversation_id, query=\"北京今天的天气\", tool_choice=tool_choice, stream=True)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### 2.3.6 tool_choice工具调用展示\n", "\n", "- 当前模式下由于是直接调用组件,组件的输入参数由输入参数控制" ] }, { "cell_type": "code", "execution_count": 7, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "answer='' events=[Event(code=0, message='', status='done', event_type='function_call', content_type='function_call', detail={'text': {'arguments': {'city': '北京天气'}, 'component_code': 'WeatherQuery', 'component_name': '天气查询'}}, usage=None, tool_calls=None)]\n" ] } ], "source": [ "#可以看出,当前天气查询组件的输入参数query({'city': '北京天气'})由tool_choice控制\n", "#此时直接调用天气调用组件而不是大模型function call选择天气组件提供参数\n", "for k in st.content:\n", " print(k)\n", " break" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### 2.3.7 tool_choice完整结果展示" ] }, { "cell_type": "code", "execution_count": 8, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "answer='' events=[Event(code=0, message='', status='done', event_type='function_call', content_type='function_call', detail={'text': {'arguments': {'city': '北京天气'}, 'component_code': 'WeatherQuery', 'component_name': '天气查询'}}, usage=None, tool_calls=None)]\n", "answer='' events=[Event(code=0, message='', status='preparing', event_type='WeatherQuery', content_type='status', detail={}, usage=None, tool_calls=None)]\n", "answer='' events=[Event(code=0, message='', status='done', event_type='WeatherQuery', content_type='text', detail={'text': '北京 09月23日(星期一) 08:05更新 15.6 ℃ 晴 24℃/12℃ 东北风1级 | 湿度74% 未来2小时不会下雨 > 北京今明天云量逐渐增多 明夜有小雨 > 堪比台风降雨!冷空气“撞”上季风 华南暴雨大暴雨持续 局地特大暴雨 推荐 图集 昨天 9/22 23/11℃ 今天 9/23 24/12℃ 星期二 9/24 24/15℃ 48小时预报 09:00 11:00 13:00 15:00 17:00 19:00 21:00 23:00 01:00 03:00 05:00 07:00 09:00 11:00 13:00 15:00 17:00 19:00 21:00 23:00 01:00 03:00 05:00 07:00 09:00 17℃20℃22℃23℃21℃20℃17℃16℃14℃13℃12℃13℃16℃21℃23℃23℃23℃21℃19℃18℃16℃15℃15℃16℃19℃ <3级 <3级 <3级 <3级 <3级 <3级 <3级 <3级 <3级 <3级 <3级 <3级 <3级 <3级 <3级 <3级 <3级 <3级 <3级 <3级 <3级 <3级 <3级 <3级 <3级 15天预报 长期预报 历史天气 今天 9/23 周二 9/24 周三 9/25 周四 9/26 周五 9/27 周六 9/28 周日 9/29 周一 9/30 周二 10/1 周三 10/2 周四 10/3 周五 10/4 周六 10/5 周日 10/6 周一 10/7 晴 多云 多云 多云 多云 多云 小雨 雨 阴 晴 阴 晴 阴 阴 雨 24°24°25°24°25°24°23°16°21°24°23°24°24°25°24° 12°15°14°15°16°16°14°10°13°14°15°16°17°18°16° 多云 小雨 多云 多云 多云 小雨 小雨 晴 多云 阴 多云 阴 阴 阴 雨 查看详情 40天预报 温度趋势 温暖 降水趋势 8次降水 生活指数 穿衣 衬衫 跑步 适宜 钓鱼 适宜 洗车 较适宜 晾晒 适宜 污染扩散指数 中 感冒指数 少发 出行晴雨 沿途天气 我的天空 精彩推荐 堪比台风降雨!华南暴雨大暴雨持续 新闻联播天气预报 全国中秋假期出游天气地图出炉 北京蓝天白云“颜值”在线 秋分:暑退秋澄气转凉 日光夜色两均长 晨味时节之白露 风雨潮“三碰头” 堪比台风降雨!华南暴雨大暴雨持续 新闻联播天气预报 全国中秋假期出游天气地图出炉 北京蓝天白云“颜值”在线 秋分:暑退秋澄气转凉 日光夜色两均长 晨味时节之白露 风雨潮“三碰头” 堪比台风降雨!华南暴雨大暴雨持续 新闻联播天气预报 全国中秋假期出游天气地图出炉 北京蓝天白云“颜值”在线 秋分:暑退秋澄气转凉 日光夜色两均长 晨味时节之白露 风雨潮“三碰头” 未来3天公报 未来10天公报 推荐 直播 图集 短视频 生活 北京今明天云量逐渐增多 明夜有小雨2024-09-23 07:24'}, usage=None, tool_calls=None)]\n", "answer='' events=[Event(code=0, message='', status='success', event_type='WeatherQuery', content_type='status', detail={}, usage=None, tool_calls=None)]\n", "answer='' events=[Event(code=0, message='', status='done', event_type='function_call', content_type='function_call', detail={'text': {'arguments': {'origin_query': '北京今天的天气'}, 'component_code': 'ChatAgent', 'component_name': '聊天助手'}}, usage=None, tool_calls=None)]\n", "answer='' events=[Event(code=0, message='', status='preparing', event_type='ChatAgent', content_type='status', detail={}, usage=None, tool_calls=None)]\n", "answer='北京今天的天气情况如下' events=[Event(code=0, message='', status='running', event_type='ChatAgent', content_type='text', detail={'text': '北京今天的天气情况如下'}, usage=Usage(prompt_tokens=1105, completion_tokens=0, total_tokens=1105, name='Qianfan-Appbuilder-Speed-8k'), tool_calls=None)]\n", "answer=':\\n\\n- **日期**:2024年9月23日(星期一)\\n- **天气**:晴\\n- **温度**:最高温度24℃,' events=[Event(code=0, message='', status='running', event_type='ChatAgent', content_type='text', detail={'text': ':\\n\\n- **日期**:2024年9月23日(星期一)\\n- **天气**:晴\\n- **温度**:最高温度24℃,'}, usage=Usage(prompt_tokens=1105, completion_tokens=0, total_tokens=1105, name='Qianfan-Appbuilder-Speed-8k'), tool_calls=None)]\n", "answer='最低温度12℃\\n- **风向**:东北风1级\\n- **湿度**:74%\\n- **未来2小时**:不会下雨\\n- **今天云量**:逐渐增多\\n- **明天天气**:明夜有小雨\\n\\n如果您需要更多详细信息或未来几天的天气预报,请告诉我!' events=[Event(code=0, message='', status='running', event_type='ChatAgent', content_type='text', detail={'text': '最低温度12℃\\n- **风向**:东北风1级\\n- **湿度**:74%\\n- **未来2小时**:不会下雨\\n- **今天云量**:逐渐增多\\n- **明天天气**:明夜有小雨\\n\\n如果您需要更多详细信息或未来几天的天气预报,请告诉我!'}, usage=Usage(prompt_tokens=1105, completion_tokens=0, total_tokens=1105, name='Qianfan-Appbuilder-Speed-8k'), tool_calls=None)]\n", "answer='' events=[Event(code=0, message='', status='done', event_type='ChatAgent', content_type='text', detail={'text': ''}, usage=Usage(prompt_tokens=1105, completion_tokens=114, total_tokens=1219, name='Qianfan-Appbuilder-Speed-8k'), tool_calls=None)]\n", "answer='' events=[Event(code=0, message='', status='success', event_type='ChatAgent', content_type='status', detail={}, usage=None, tool_calls=None)]\n", "answer='' events=[]\n" ] } ], "source": [ "st = builder.run(conversation_id=conversation_id, query=\"北京今天的天气\", tool_choice=tool_choice, stream=True)\n", "for k in st.content:\n", " print(k)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### 2.4 使用Java SDK调用已发布的App\n", "##### 2.4.1 ToolChoice强制命中组件" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "vscode": { "languageId": "java" } }, "outputs": [], "source": [ "package org.example;\n", "\n", "import java.io.IOException;\n", "import java.util.*;\n", "\n", "import com.google.gson.annotations.SerializedName;\n", "\n", "import com.baidubce.appbuilder.base.exception.AppBuilderServerException;\n", "import com.baidubce.appbuilder.console.appbuilderclient.AppBuilderClient;\n", "import com.baidubce.appbuilder.model.appbuilderclient.AppBuilderClientIterator;\n", "import com.baidubce.appbuilder.model.appbuilderclient.AppBuilderClientResult;\n", "import com.baidubce.appbuilder.model.appbuilderclient.AppBuilderClientRunRequest;\n", "import com.baidubce.appbuilder.model.appbuilderclient.Event;\n", "import com.baidubce.appbuilder.base.utils.json.JsonUtils;\n", "\n", "class AppBuilderClientDemo {\n", "\n", " public static void main(String[] args) throws IOException, AppBuilderServerException {\n", " System.setProperty(\"APPBUILDER_TOKEN\", \"请设置正确的应用密钥\");\n", " String appId = \"请设置正确的应用ID\";\n", " AppBuilderClient builder = new AppBuilderClient(appId);\n", " String conversationId = builder.createConversation();\n", "\n", " AppBuilderClientRunRequest request = new AppBuilderClientRunRequest();\n", " request.setAppId(appId);\n", " request.setConversationID(conversationId);\n", " request.setQuery(\"北京今天的天气\");\n", " request.setStream(false);\n", " request.setEndUserId(\"java_toolchoice_demo\");\n", "\n", " // 注意使用创建应用中用到的组件。名称、参数均以实际使用的组件为准。\n", " Map input = new HashMap<>();\n", " input.put(\"city\", \"北京\");\n", " AppBuilderClientRunRequest.ToolChoice.Function func = new AppBuilderClientRunRequest.ToolChoice.Function(\n", " \"WeatherQuery\", input);\n", "\n", " AppBuilderClientRunRequest.ToolChoice choice = new AppBuilderClientRunRequest.ToolChoice(\"function\", func);\n", " request.setToolChoice(choice);\n", "\n", " AppBuilderClientIterator itor = builder.run(request);\n", " while (itor.hasNext()) {\n", " AppBuilderClientResult result = itor.next();\n", " System.out.println(result);\n", " }\n", " }\n", "}" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### 2.5 使用Go SDK调用已发布的应用\n", "##### 2.5.1 ToolChoice强制命中组件" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "vscode": { "languageId": "go" } }, "outputs": [], "source": [ "package main\n", "\n", "import (\n", "\t\"errors\"\n", "\t\"fmt\"\n", "\t\"io\"\n", "\t\"os\"\n", "\n", "\t\"github.com/baidubce/app-builder/go/appbuilder\"\n", ")\n", "\n", "func main() {\n", "\t// 设置APPBUILDER_TOKEN、GATEWAY_URL_V2环境变量\n", "\tos.Setenv(\"APPBUILDER_TOKEN\", \"请设置正确的应用密钥\")\n", "\t// 默认可不填,默认值是 https://qianfan.baidubce.com\n", "\tos.Setenv(\"GATEWAY_URL_V2\", \"\")\n", "\tconfig, err := appbuilder.NewSDKConfig(\"\", \"\")\n", "\tif err != nil {\n", "\t\tfmt.Println(\"new config failed: \", err)\n", "\t\treturn\n", "\t}\n", "\t// 初始化实例\n", "\tappID := \"请填写正确的应用ID\"\n", "\tbuilder, err := appbuilder.NewAppBuilderClient(appID, config)\n", "\tif err != nil {\n", "\t\tfmt.Println(\"new agent builder failed: \", err)\n", "\t\treturn\n", "\t}\n", "\t// 创建对话ID\n", "\tconversationID, err := builder.CreateConversation()\n", "\tif err != nil {\n", "\t\tfmt.Println(\"create conversation failed: \", err)\n", "\t\treturn\n", "\t}\n", "\n", " // 注意使用创建应用中用到的组件。名称、参数均以实际使用的组件为准。\n", "\tinput := make(map[string]any)\n", "\tinput[\"city\"] = \"北京\"\n", "\tend_user_id := \"go_toolchoice_demo\"\n", "\ti, err := client.Run(AppBuilderClientRunRequest{\n", "\t\tConversationID: conversationID,\n", "\t\tAppID: appID,\n", "\t\tQuery: \"\",\n", "\t\tEndUserID: &end_user_id,\n", "\t\tStream: false,\n", "\t\tToolChoice: &ToolChoice{\n", "\t\t\tType: \"function\",\n", "\t\t\tFunction: ToolChoiceFunction{\n", "\t\t\t\tName: \"WeatherQuery\",\n", "\t\t\t\tInput: input,\n", "\t\t\t},\n", "\t\t},\n", "\t})\n", "\n", "\tif err != nil {\n", "\t\tfmt.Println(\"run failed: \", err)\n", "\t\treturn\n", "\t}\n", "\n", " for answer, err := i.Next(); err == nil; answer, err = i.Next() {\n", "\t\tfor _, ev := range answer.Events {\n", "\t\t\tevJSON, _ := json.Marshal(ev)\n", "\t\t\tfmt.Println(string(evJSON))\n", "\t\t}\n", "\t}\n", "}" ] } ], "metadata": { "kernelspec": { "display_name": "Python 3 (ipykernel)", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.11.7" }, "vscode": { "interpreter": { "hash": "31f2aee4e71d21fbe5cf8b01ff0e069b9275f58929596ceb00d14d90e3e16cd6" } } }, "nbformat": 4, "nbformat_minor": 2 } ================================================ FILE: cookbooks/end2end_application/rag/console_dataset.ipynb ================================================ { "cells": [ { "cell_type": "markdown", "id": "bd16bc4e-9e7a-4119-a9e8-55b1adb7b560", "metadata": {}, "source": [ "# console端知识库操作助手\n", "\n", "## 目标\n", "用户可通过SDK对console端知识库进行操作,实现创建知识库、添加知识文档、查询知识库文档、删除知识文档等操作,可在平台console中查看结果。\n", "\n", "## 准备工作\n", "### 平台注册\n", "1.先在appbuilder平台注册,获取token\n", "\n", "2.安装appbuilder-sdk" ] }, { "cell_type": "code", "execution_count": null, "id": "f66602fd-680d-4f28-8f2d-fb4b79845a70", "metadata": {}, "outputs": [], "source": [ "!pip install appbuilder-sdk" ] }, { "cell_type": "code", "execution_count": 1, "id": "7fef1d24-0aa5-4697-b49e-9b087408e319", "metadata": { "ExecuteTime": { "end_time": "2024-02-02T09:04:39.646010Z", "start_time": "2024-02-02T09:04:39.638630Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "init done\n" ] } ], "source": [ "import os\n", "\n", "# 设置环境变量\n", "# 请前往千帆AppBuilder官网创建密钥,流程详见:https://cloud.baidu.com/doc/AppBuilder/s/Olq6grrt6#1%E3%80%81%E5%88%9B%E5%BB%BA%E5%AF%86%E9%92%A5\n", "os.environ[\"APPBUILDER_TOKEN\"] = \"...\"\n", "\n", "print(\"init done\")" ] }, { "cell_type": "markdown", "id": "da65c0ca-c7b8-416d-be70-4b7f83f8376c", "metadata": {}, "source": [ "## 开发过程" ] }, { "cell_type": "markdown", "source": [ "### 初始化已有知识库\n", "获取线上已有知识库的ID,可在[console](https://console.bce.baidu.com/ai_apaas/dataset)端查看,示例\n", "\n", "\"image\"" ], "metadata": { "collapsed": false }, "id": "4fcce3379af01f31" }, { "cell_type": "code", "execution_count": null, "outputs": [], "source": [ "import appbuilder\n", "# 初始化已有线上知识库, dataset_id 可在平台console中查看\n", "dataset_id = \"...\"\n", "dataset = appbuilder.console.Dataset(dataset_id)" ], "metadata": { "collapsed": false }, "id": "e6512896d659d339" }, { "cell_type": "markdown", "id": "0b9e894c-9b1c-4d14-8fba-85607c07d091", "metadata": {}, "source": [ "### 创建全新知识库" ] }, { "cell_type": "code", "execution_count": null, "id": "cb554cf7-3f07-4a16-a760-57064f35f6cc", "metadata": {}, "outputs": [], "source": [ "# 创建全新知识库\n", "dataset = appbuilder.console.Dataset.create_dataset(\"my_dataset\")" ] }, { "cell_type": "markdown", "id": "4305e336-67da-4aec-a807-d5ef1b66987c", "metadata": {}, "source": [ "### 上传文档到知识库" ] }, { "cell_type": "code", "execution_count": null, "id": "41fc3bd1-1a9d-4515-99d5-4704adaec508", "metadata": {}, "outputs": [], "source": [ "# 设置文档路径,例如“./test.pdf”\n", "file_path1 = \"...\"\n", "file_path2 = \"...\"\n", "file_paths = [file_path1, file_path2]\n", "# 将文档上传到知识库\n", "document_infos = dataset.add_documents(file_paths)\n", "print(document_infos)" ] }, { "cell_type": "markdown", "id": "7e4fc1bf-7af9-4a69-a409-e1f0c53b3651", "metadata": {}, "source": [ "### 获取知识库关联文档" ] }, { "cell_type": "code", "execution_count": null, "id": "fd628ef9-1f61-4350-81f6-9eaea5342400", "metadata": {}, "outputs": [], "source": [ "# 获取第一页的文档列表, 每页10条\n", "document_list = dataset.get_documents(1, 10)\n", "print(document_list)" ] }, { "cell_type": "markdown", "id": "6dc7f0ec-e556-4246-b7c6-92a7242c8194", "metadata": {}, "source": [ "### 删除知识库中的文档" ] }, { "cell_type": "code", "execution_count": null, "id": "17c50ea0-521d-42c2-82c8-34a70510be3d", "metadata": {}, "outputs": [], "source": [ "# 删除第一个文档\n", "document_ids = [document_list.data[0].id]\n", "dataset.delete_documents(document_ids)" ] } ], "metadata": { "kernelspec": { "display_name": "Python 3 (ipykernel)", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.11.5" } }, "nbformat": 4, "nbformat_minor": 5 } ================================================ FILE: cookbooks/end2end_application/rag/console_rag.ipynb ================================================ { "cells": [ { "cell_type": "markdown", "id": "f802e64d-4eaa-445d-a48a-1042a91bc394", "metadata": { "tags": [] }, "source": [ "# console端RAG问答助手\n", "\n", "## 目标\n", "使用console端RAG应用,对用户的请求进行回答。\n", "\n", "## 准备工作\n", "### 平台注册\n", "\n", "1.先在appbuilder平台注册,获取token\n", "\n", "2.安装appbuilder-sdk" ] }, { "cell_type": "code", "execution_count": null, "id": "2939356f-61c2-42e9-9e0c-fc6729c193f6", "metadata": { "tags": [] }, "outputs": [], "source": [ "!pip install appbuilder-sdk" ] }, { "cell_type": "code", "execution_count": 3, "id": "4ccff03b-1567-4e8b-8e1f-9a5032690406", "metadata": { "ExecuteTime": { "end_time": "2024-01-29T08:53:09.839677Z", "start_time": "2024-01-29T08:53:09.836602Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "init done\n" ] } ], "source": [ "import os\n", "\n", "# 设置环境变量\n", "# 请前往千帆AppBuilder官网创建密钥,流程详见:https://cloud.baidu.com/doc/AppBuilder/s/Olq6grrt6#1%E3%80%81%E5%88%9B%E5%BB%BA%E5%AF%86%E9%92%A5\n", "os.environ[\"APPBUILDER_TOKEN\"] = \"...\"\n", "\n", "print(\"init done\")" ] }, { "cell_type": "markdown", "id": "aeb2fa55-075f-48df-a9fb-8b40d9900684", "metadata": {}, "source": [ "## 开发过程" ] }, { "attachments": {}, "cell_type": "markdown", "id": "e77c402f3ec3e40", "metadata": { "collapsed": false }, "source": [ "### 获取线上已有RAG应用的ID\n", "线上已有RAG应用ID,可在[console](https://console.bce.baidu.com/ai_apaas/app)端查看,注意,完成应用的创建后,需要点击立即使用,发布应用后,才可被SDK调用,示例,\n", "\n", "\"image\"" ] }, { "cell_type": "code", "execution_count": null, "id": "41559341-fd7a-478c-a08b-1477d79e9d41", "metadata": {}, "outputs": [], "source": [ "import appbuilder\n", "\n", "# 线上RAG应用ID,可在console端查看\n", "app_id = \"...\"\n", "conversation_id = \"...\" # 会话ID,可选参数,不传默认新建会话\n", "rag_app = appbuilder.console.RAG(app_id)\n", "query = \"中国的首都在哪里\"\n", "answer = rag_app.run(appbuilder.Message(query)) # 新建对话\n", "print(answer.content)\n", "conversation_id = answer.conversation_id # 获取会话ID,可用于下次会话\n", "print(conversation_id)\n", "query = \"它有哪些旅游景点\"\n", "answer = rag_app.run(appbuilder.Message(query), conversation_id) # 接上次对话\n", "print(answer.content)\n", "print(answer.extra) # 获取结果来源" ] } ], "metadata": { "kernelspec": { "display_name": "Python 3 (ipykernel)", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.11.5" } }, "nbformat": 4, "nbformat_minor": 5 } ================================================ FILE: cookbooks/end2end_application/rag/qa_system_1_dataset.ipynb ================================================ { "cells": [ { "attachments": {}, "cell_type": "markdown", "metadata": {}, "source": [ "# 企业级问答系统 —— 离线知识生产流程\n", "\n", "## 一、背景介绍\n", "\n", "智能问答系统是当前应用范围最广,最容易落地的大模型应用。通常来说,智能问答系统包括以下五部分:\n", "1. Query理解\n", "2. 混合检索召回\n", "3. 语义排序\n", "4. 答案生成\n", "5. 追问生成\n", "\n", "AppBuilder在问答系统沉淀了最佳实践流程,并以极易用的组件化的方式对外开放,可以使用页面操作 + 低代码的方式快速搭建自己的问答系统。\n", "\n", "\"drawing\"\n" ] }, { "attachments": {}, "cell_type": "markdown", "metadata": {}, "source": [ "## 二、实操流程\n", "\n", "整体使用流程包括以下三个环节:\n", "\n", "1. 登录[百度智能云千帆AppBuilder官网](https://cloud.baidu.com/product/AppBuilder)创建账户,\n", "\n", "\"drawing\"\n", "\n", "\n", "2. 在[百度智能云千帆AppBuilder控制台](https://console.bce.baidu.com/ai_apaas/dialogHome)右侧头像栏『API密钥』页面获取密钥,并复制。\n", "\n", "\"drawing\"\n", "\n", "\n", "\"drawing\"\n", "\n", "\n", "3. 引用AppBuilder SDK代码,调用Dataset API相关接口,创建数据集,并增、查、删除文档。" ] }, { "attachments": {}, "cell_type": "markdown", "metadata": {}, "source": [ "### 2.1 环境准备\n", "\n", "首先需要安装AppBuilder-SDK代码库,若已在开发环境安装,则可跳过此步。\n", "\n", "**注意:**: appbuilder-sdk 的python版本要求 3.9+" ] }, { "cell_type": "code", "execution_count": 2, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Defaulting to user installation because normal site-packages is not writeable\n", "Collecting appbuilder-sdk\n", " Using cached appbuilder_sdk-0.6.0-py3-none-any.whl.metadata (768 bytes)\n", "Requirement already satisfied: requests in /Users/chengmo/Library/Python/3.9/lib/python/site-packages (from appbuilder-sdk) (2.31.0)\n", "Requirement already satisfied: proto-plus==1.22.3 in /Users/chengmo/Library/Python/3.9/lib/python/site-packages (from appbuilder-sdk) (1.22.3)\n", "Requirement already satisfied: pydantic==2.6.4 in /Users/chengmo/Library/Python/3.9/lib/python/site-packages (from appbuilder-sdk) (2.6.4)\n", "Requirement already satisfied: numpy in /Users/chengmo/Library/Python/3.9/lib/python/site-packages (from appbuilder-sdk) (1.24.4)\n", "Requirement already satisfied: SQLAlchemy~=1.4.50 in /Users/chengmo/Library/Python/3.9/lib/python/site-packages (from appbuilder-sdk) (1.4.52)\n", "Requirement already satisfied: urllib3<2.0.0 in /Users/chengmo/Library/Python/3.9/lib/python/site-packages (from appbuilder-sdk) (1.26.18)\n", "Requirement already satisfied: tenacity in /Users/chengmo/Library/Python/3.9/lib/python/site-packages (from appbuilder-sdk) (8.2.3)\n", "Requirement already satisfied: pandas in /Users/chengmo/Library/Python/3.9/lib/python/site-packages (from appbuilder-sdk) (2.2.1)\n", "Requirement already satisfied: openpyxl in /Users/chengmo/Library/Python/3.9/lib/python/site-packages (from appbuilder-sdk) (3.1.2)\n", "Requirement already satisfied: pymochow>=1.1.2 in /Users/chengmo/Library/Python/3.9/lib/python/site-packages (from appbuilder-sdk) (1.1.2)\n", "Requirement already satisfied: parameterized in /Users/chengmo/Library/Python/3.9/lib/python/site-packages (from appbuilder-sdk) (0.9.0)\n", "Requirement already satisfied: protobuf<5.0.0dev,>=3.19.0 in /Users/chengmo/Library/Python/3.9/lib/python/site-packages (from proto-plus==1.22.3->appbuilder-sdk) (4.25.3)\n", "Requirement already satisfied: annotated-types>=0.4.0 in /Users/chengmo/Library/Python/3.9/lib/python/site-packages (from pydantic==2.6.4->appbuilder-sdk) (0.6.0)\n", "Requirement already satisfied: pydantic-core==2.16.3 in /Users/chengmo/Library/Python/3.9/lib/python/site-packages (from pydantic==2.6.4->appbuilder-sdk) (2.16.3)\n", "Requirement already satisfied: typing-extensions>=4.6.1 in /Users/chengmo/Library/Python/3.9/lib/python/site-packages (from pydantic==2.6.4->appbuilder-sdk) (4.10.0)\n", "Requirement already satisfied: orjson in /Users/chengmo/Library/Python/3.9/lib/python/site-packages (from pymochow>=1.1.2->appbuilder-sdk) (3.9.15)\n", "Requirement already satisfied: future in /Library/Developer/CommandLineTools/Library/Frameworks/Python3.framework/Versions/3.9/lib/python3.9/site-packages (from pymochow>=1.1.2->appbuilder-sdk) (0.18.2)\n", "Requirement already satisfied: et-xmlfile in /Users/chengmo/Library/Python/3.9/lib/python/site-packages (from openpyxl->appbuilder-sdk) (1.1.0)\n", "Requirement already satisfied: python-dateutil>=2.8.2 in /Users/chengmo/Library/Python/3.9/lib/python/site-packages (from pandas->appbuilder-sdk) (2.8.2)\n", "Requirement already satisfied: pytz>=2020.1 in /Users/chengmo/Library/Python/3.9/lib/python/site-packages (from pandas->appbuilder-sdk) (2024.1)\n", "Requirement already satisfied: tzdata>=2022.7 in /Users/chengmo/Library/Python/3.9/lib/python/site-packages (from pandas->appbuilder-sdk) (2024.1)\n", "Requirement already satisfied: charset-normalizer<4,>=2 in /Users/chengmo/Library/Python/3.9/lib/python/site-packages (from requests->appbuilder-sdk) (3.3.2)\n", "Requirement already satisfied: idna<4,>=2.5 in /Users/chengmo/Library/Python/3.9/lib/python/site-packages (from requests->appbuilder-sdk) (3.6)\n", "Requirement already satisfied: certifi>=2017.4.17 in /Users/chengmo/Library/Python/3.9/lib/python/site-packages (from requests->appbuilder-sdk) (2024.2.2)\n", "Requirement already satisfied: six>=1.5 in /Users/chengmo/Library/Python/3.9/lib/python/site-packages (from python-dateutil>=2.8.2->pandas->appbuilder-sdk) (1.16.0)\n", "Using cached appbuilder_sdk-0.6.0-py3-none-any.whl (335 kB)\n", "Installing collected packages: appbuilder-sdk\n", "Successfully installed appbuilder-sdk-0.6.0\n" ] } ], "source": [ "!python3 -m pip install appbuilder-sdk" ] }, { "attachments": {}, "cell_type": "markdown", "metadata": {}, "source": [ "### 2.2 引入AppBuilder-SDK,并设置TOKEN\n", "\n", "**注意:** 请使用刚才在AppBuilder平台上新建的个人TOKEN" ] }, { "cell_type": "code", "execution_count": 9, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "AppBuilder 模块导入成功!\n", "您的AppBuilder Token为:your_appbuilder_token\n" ] } ], "source": [ "# 引入os模块,引入appbuilder 模块\n", "import os\n", "import appbuilder\n", "\n", "# 设置appbuilder的token密钥,从页面上复制粘贴token,覆盖此处的 \"your_appbuilder_token\"\n", "os.environ['APPBUILDER_TOKEN'] = \"your_appbuilder_token\"\n", "\n", "print(\"AppBuilder 模块导入成功!\")\n", "print(\"您的AppBuilder Token为:{}\".format(os.environ['APPBUILDER_TOKEN']))" ] }, { "attachments": {}, "cell_type": "markdown", "metadata": {}, "source": [ "### 2.3 创建全新知识库\n", "\n", "我们从零开始创建一个新的知识库,并使用它来支持问答系统。我们将其命名为**说明书知识库**" ] }, { "cell_type": "code", "execution_count": 4, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "知识库创建成功! 知识库的ID为:c368a982-699f-4114-9e9a-c08b76c07f92, 知识库的名称为: 说明书知识库\n" ] } ], "source": [ "# 创建全新知识库\n", "dataset = appbuilder.console.Dataset.create_dataset(\"说明书知识库\")\n", "\n", "print(\"知识库创建成功! 知识库的ID为:{}, 知识库的名称为: {}\".format(\n", " dataset.dataset_id,\n", " dataset.dataset_name))" ] }, { "attachments": {}, "cell_type": "markdown", "metadata": {}, "source": [ "### 2.4 上传文档到知识库\n", "\n", "在notebook的同级目录`./qa_system`下,我们提前准备了两篇文档:\n", "- `./qa_system/平板电脑说明书.pdf`\n", "- `./qa_system/显示器说明书.pdf`\n", "\n", "我们将这两篇文档上传到知识库中,用于后续问答应用的私域知识检索。" ] }, { "cell_type": "code", "execution_count": 5, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "文档上传到知识库成功!知识库中的文档ID为:['c396c715-66d8-49cb-af9d-af0bd08a16e2', '817d29bb-be72-420b-bee1-c1d9b1116826']\n" ] } ], "source": [ "file_1 = \"./qa_system/平板电脑说明书.pdf\"\n", "file_2 = \"./qa_system/显示器说明书.pdf\"\n", "\n", "document_infos = dataset.add_documents([\n", " file_1, file_2\n", "])\n", "\n", "print(\"文档上传到知识库成功!知识库中的文档ID为:{}\".format(document_infos.document_ids))\n" ] }, { "attachments": {}, "cell_type": "markdown", "metadata": {}, "source": [ "### 2.5 查找知识库中的文档\n", "\n", "问答系统中的知识库,常用增、删、查操作,我们刚才演示了增加文档的方法,下面演示如何查找文档。\n", "\n", "我们获取[百度智能云千帆AppBuilder控制台-我的知识](https://console.bce.baidu.com/ai_apaas/dataset)页面中,我们刚才创建的知识库中的文档列表。\n", "\n", "\"drawing\"" ] }, { "cell_type": "code", "execution_count": 6, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "文档列表获取成功!\n", "第二个的文档是: 平板电脑说明书.pdf, 文档ID是: c396c715-66d8-49cb-af9d-af0bd08a16e2, 文档字数是: 8568\n" ] } ], "source": [ "doc_list = dataset.get_documents(page=1,limit=10)\n", "print(\"文档列表获取成功!\")\n", "print(\"第二个的文档是: {}, 文档ID是: {}, 文档字数是: {}\".format(\n", " doc_list.data[1].name, doc_list.data[1].id, doc_list.data[1].word_count))" ] }, { "attachments": {}, "cell_type": "markdown", "metadata": {}, "source": [ "### 2.6 删除知识库中的文档\n", "\n", "下面我们演示如何删除知识库中的文档。我们尝试删除 『平板电脑说明书.pdf』 这篇文档" ] }, { "cell_type": "code", "execution_count": 7, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "文档: 平板电脑说明书.pdf, 文档ID: c396c715-66d8-49cb-af9d-af0bd08a16e2 删除成功!\n", "文档删除成功,请刷新『知识库』前端页面,观察是否已无『平板电脑说明书.pdf』文档\n" ] } ], "source": [ "need_delete_doc_name = \"平板电脑说明书.pdf\"\n", "need_delete_doc_id = \"\"\n", "\n", "doc_list = dataset.get_documents(page=1,limit=10)\n", "for doc in doc_list.data:\n", " if doc.name == need_delete_doc_name:\n", " need_delete_doc_id = doc.id\n", " break\n", "\n", "if need_delete_doc_id == \"\":\n", " print(\"未找到指定文档,请检查 2.4 步骤是否正确上传,以及2.5步骤中是否展示了正确的文档列表\")\n", "else:\n", " dataset.delete_documents([need_delete_doc_id])\n", " print(\"文档: {}, 文档ID: {} 删除成功!\".format(\n", " need_delete_doc_name,\n", " need_delete_doc_id\n", " ))\n", "\n", "print(\"文档删除成功,请刷新『知识库』前端页面,观察是否已无『{}』文档\".format(need_delete_doc_name))\n" ] }, { "attachments": {}, "cell_type": "markdown", "metadata": {}, "source": [ "执行完上述步骤后,前端页面刷新,指定文档已经被成功删除\n", "\n", "\"drawing\"" ] }, { "cell_type": "code", "execution_count": 8, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "当前创建的知识库的ID为:c368a982-699f-4114-9e9a-c08b76c07f92, 知识库的名称为: 说明书知识库\n" ] } ], "source": [ "# 再一次确认当前知识库的 Name 与 ID,方便后续 企业级问答系统 —— 在线问答流程 的使用\n", "\n", "print(\"当前创建的知识库的ID为:{}, 知识库的名称为: {}\".format(\n", " dataset.dataset_id,\n", " dataset.dataset_name))" ] }, { "attachments": {}, "cell_type": "markdown", "metadata": {}, "source": [ "## 三、总结\n", "\n", "AppBuilder 为 基于RAG的 企业问答系统提供了 `appbuilder.console.dataset` API,可以方便的以代码态进行知识库的管理,实现基本的增删改查业务需求。\n", "\n", "本示例展示了如何从零创建知识库,并实现增、查、改的代码,并可以观察SDK与前端页面的联动。" ] } ], "metadata": { "kernelspec": { "display_name": "Python 3", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.9.6" }, "orig_nbformat": 4, "vscode": { "interpreter": { "hash": "31f2aee4e71d21fbe5cf8b01ff0e069b9275f58929596ceb00d14d90e3e16cd6" } } }, "nbformat": 4, "nbformat_minor": 2 } ================================================ FILE: cookbooks/end2end_application/rag/qa_system_2_dialogue.ipynb ================================================ { "cells": [ { "attachments": {}, "cell_type": "markdown", "metadata": {}, "source": [ "# 企业级问答系统 —— 在线问答流程\n", "\n", "## 一、背景介绍\n", "\n", "智能问答系统是当前应用范围最广,最容易落地的大模型应用。通常来说,智能问答系统包括以下五部分:\n", "1. Query理解\n", "2. 混合检索召回\n", "3. 语义排序\n", "4. 答案生成\n", "5. 追问生成\n", "\n", "AppBuilder在问答系统沉淀了最佳实践流程,并以极易用的组件化的方式对外开放,可以使用页面操作 + 低代码的方式快速搭建自己的问答系统。\n", "\n", "\"drawing\"" ] }, { "attachments": {}, "cell_type": "markdown", "metadata": {}, "source": [ "## 二、实操流程\n", "\n", "推荐您先完成[企业级问答系统——离线知识生产流程](./qa_system_1_dataset.ipynb)的文档的学习,再进行本文的操作。\n", "\n", "\n", "### 2.1 前置操作简述\n", "\n", "- 【必须】登录[百度智能云千帆AppBuilder官网](https://cloud.baidu.com/product/AppBuilder)创建账户。\n", "- 【必须】在[百度智能云千帆AppBuilder控制台](https://console.bce.baidu.com/ai_apaas/dialogHome)左侧菜单栏『我的密钥』页面获取密钥,并复制。\n", "- 【必须】在python3.9及以上的环境中安装`appbuilder-sdk`\n", "- 【非必须】(可以在创建应用时在页面操作)通过SDK代码态创建知识库,并上传文档,参考[企业级问答系统——离线知识生产流程](./qa_system_1_dataset.ipynb)," ] }, { "attachments": {}, "cell_type": "markdown", "metadata": {}, "source": [ "### 2.2、创建应用\n", "\n", "\n", "##### 2.2.1、点击创建应用界面\n", "点击[百度智能云千帆AppBuilder控制台](https://console.bce.baidu.com/ai_apaas/dialogHome)左侧菜单栏『创建应用』,开始我们的创建知识问答系统应用。\n", "\n", "\"drawing\"\n", "\n", "\n", "#### 2.2.2、填写应用信息,使用魔法棒自动生成instruction\n", "\n", "我们需要首先配置该应用的基本信息,包括 名称、描述、角色指令、开场白、推荐问、能力组件等。\n", "\n", "这类信息比较繁杂,存在一些填写技巧,填写的质量决定了后续应用的使用体验。\n", "\n", "AppBuilder 提供了『魔法棒』功能,可以自动生成instruction。用户只需要提供简单的描述,即可自动生成instruction。\n", "\n", "示例描述:`你是一个尽职尽责的客服问答助手。你有多个产品使用说明书,根据说明书上的内容回答用户的使用问题。`\n", "\n", "\"drawing\"\n", "\n", "生成结果示例:\n", "\n", "\"drawing\"" ] }, { "attachments": {}, "cell_type": "markdown", "metadata": {}, "source": [ "#### 2.2.3、添加知识库\n", "\n", "在 『能力扩展』-『知识库』的操作栏中,我们添加在 [企业级问答系统——离线知识生产流程](./qa_system_1_dataset.ipynb) 中创建的 『说明书知识库』\n", "\n", "\"drawing\"" ] }, { "attachments": {}, "cell_type": "markdown", "metadata": {}, "source": [ "#### 2.2.4、页面对话并发布应用\n", "\n", "我们可以在页面右侧『预览与调试』对话栏中,通过对话进行快速调试,若符合预期,则点选右上角『发布』按钮发布该应用。\n", "\n", "\"drawing\"" ] }, { "attachments": {}, "cell_type": "markdown", "metadata": {}, "source": [ "#### 2.2.5 获取已发布应用的ID\n", "\n", "在 [百度智能云千帆AppBuilder控制台-我的应用](https://console.bce.baidu.com/ai_apaas/app)页面中,可以查看已发布应用的ID,我们复制该ID,开始后续的代码态操作。\n", "\n", "\"drawing\"" ] }, { "attachments": {}, "cell_type": "markdown", "metadata": {}, "source": [ "### 2.3 使用SDK调用已发布App\n", "\n", "当应用已经发布后,我们可以通过SDK在代码态调用,方便用户集成到自己的系统中,通过自己的系统对外提供服务。" ] }, { "attachments": {}, "cell_type": "markdown", "metadata": {}, "source": [ "#### 2.3.1 引入AppBuilder-SDK,设置TOKEN,设置APPID" ] }, { "cell_type": "code", "execution_count": 6, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "AppBuilder 模块导入成功!\n", "您的AppBuilder Token为:your api key\n", "您的AppBuilder App ID为:3df6c11e-44ec-438a-86a9-47b590e7cef5\n" ] } ], "source": [ "# 引入os模块,引入appbuilder 模块\n", "import os\n", "import appbuilder\n", "\n", "# 设置appbuilder的token密钥,从页面上复制粘贴我的密钥,覆盖此处的 \"your_appbuilder_token\"\n", "os.environ['APPBUILDER_TOKEN'] = \"your_appbuilder_token\"\n", "# 设置需要调用的app,从页面上复制粘贴应用ID,覆盖此处的 \"your_publish_app_id\"\n", "app_id = \"your_publish_app_id\"\n", "\n", "print(\"AppBuilder 模块导入成功!\")\n", "print(\"您的AppBuilder Token为:{}\".format(os.environ['APPBUILDER_TOKEN']))\n", "print(\"您的AppBuilder App ID为:{}\".format(app_id))" ] }, { "attachments": {}, "cell_type": "markdown", "metadata": {}, "source": [ "#### 2.3.2 初始化Agent实例,创建会话并对话\n", "\n" ] }, { "cell_type": "code", "execution_count": 7, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "智能客服问答助手的回复是:你好,作为客服问答助手,我可以为您解答关于多个产品的使用问题。如果您有任何疑问或需要帮助,请随时告诉我。\n" ] } ], "source": [ "# 初始化Agent实例\n", "agent = appbuilder.AppBuilderClient(app_id)\n", "\n", "# 创建会话ID\n", "conversation_id = agent.create_conversation()\n", "\n", "# 发送并消息\n", "response_message = agent.run(\n", " conversation_id = conversation_id,\n", " query=\"你好,请问你可以为我做什么?\"\n", ")\n", "\n", "print(\"智能客服问答助手的回复是:{}\".format(response_message.content.answer))" ] }, { "attachments": {}, "cell_type": "markdown", "metadata": {}, "source": [ "#### 2.3.3 使用Stream模式,更快的刷新回复结果" ] }, { "cell_type": "code", "execution_count": 3, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "流式输出回答:\n", "流式输出回答:\n", "流式输出回答:\n", "流式输出回答:显示器的放置\n", "流式输出回答:高度需要注意以下几点:\n", "\n", "1. **调整显示器高度以使眼睛和显示器中心的距离适合可视距离的习惯**^[1]^。\n", "流式输出回答:\n", "2. **如果您的显示器无法进行高度调整,则可能需要在显示器底座下放置几本书或其他坚固的物体以达到希望的高度**^[1]^。\n", "流式输出回答:\n", "3. **一般准则是调整显示器位置使屏幕顶部处于或略低于您在座位上感到舒适时视线的高度**^[1]^。\n", "流式输出回答:\n", "4. **务必优化您的显示器高度以使眼睛和显示器中心的距离适合可视距离的习惯,同时确保您在眼部肌肉处于放松状态时看屏幕感到\n", "流式输出回答:舒适**^[1]^。\n", "流式输出回答:\n", "流式输出回答:\n", "\n", "最终回答拼接结果:显示器的放置高度需要注意以下几点:\n", "\n", "1. **调整显示器高度以使眼睛和显示器中心的距离适合可视距离的习惯**^[1]^。\n", "2. **如果您的显示器无法进行高度调整,则可能需要在显示器底座下放置几本书或其他坚固的物体以达到希望的高度**^[1]^。\n", "3. **一般准则是调整显示器位置使屏幕顶部处于或略低于您在座位上感到舒适时视线的高度**^[1]^。\n", "4. **务必优化您的显示器高度以使眼睛和显示器中心的距离适合可视距离的习惯,同时确保您在眼部肌肉处于放松状态时看屏幕感到舒适**^[1]^。\n" ] } ], "source": [ "# 使用Steam模式发送并接受消息\n", "response_message = agent.run(\n", " conversation_id = conversation_id,\n", " query=\"显示器的放置高度需要注意什么\",\n", " stream=True\n", ")\n", "\n", "final_answer = \"\"\n", "for content in response_message.content:\n", " final_answer += content.answer\n", " print(\"流式输出回答:{}\".format(content.answer))\n", "\n", "print(\"\\n最终回答拼接结果:{}\".format(final_answer))" ] }, { "attachments": {}, "cell_type": "markdown", "metadata": {}, "source": [ "#### 2.3.4 多轮对话\n", "\n", "使用同一个conversation_id 即可进行多轮对话" ] }, { "cell_type": "code", "execution_count": 4, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "当前的 ConversationID 为: 6c217eb2-d822-4b06-8f6c-d0e94f23dc09\n", "\n", "用户的第一轮问题是: 你好,请问电源指示灯未点亮是什么原因\n", "\n", "智能客服问答助手的回复是:你好,根据搜索结果,电源指示灯未点亮的可能原因包括:显示器的电源开关未打开、电源线松动或断开、插座没有电等^[1]^。\n", "\n", "用户的第二轮问题是: 我应该怎么操作解决该问题\n", "\n", "智能客服问答助手的回复是:如果显示器的电源指示灯未点亮,且没有图像,可能有以下几种原因:显示器的电源开关未打开、电源线松动或断开、插座没有电。因此,建议首先检查这些可能的原因,并采取相应的解决措施:确保电线正确连接、确保插座有电、打开显示器电源、尝试使用另一电源线、尝试使用另一电源插座^[1]^。\n", "\n" ] } ], "source": [ "conversation_id = agent.create_conversation()\n", "print(\"当前的 ConversationID 为: {}\\n\".format(conversation_id))\n", "\n", "# 发送第一轮消息\n", "first_query = \"你好,请问电源指示灯未点亮是什么原因\"\n", "response_message = agent.run(\n", " conversation_id = conversation_id,\n", " query=first_query\n", ")\n", "print(\"用户的第一轮问题是: {}\\n\".format(first_query))\n", "print(\"智能客服问答助手的回复是:{}\\n\".format(response_message.content.answer))\n", "\n", "# 发送第二轮消息\n", "second_query = \"我应该怎么操作解决该问题\"\n", "response_message = agent.run(\n", " conversation_id = conversation_id, # 继续复用上一轮对话ID\n", " query=second_query\n", ")\n", "print(\"用户的第二轮问题是: {}\\n\".format(second_query))\n", "print(\"智能客服问答助手的回复是:{}\\n\".format(response_message.content.answer))\n" ] }, { "attachments": {}, "cell_type": "markdown", "metadata": {}, "source": [ "#### 2.3.5 展示回答中的引用的文档\n", "\n", "回答中若引用了知识库中的文档,可以提供展示文档名功能,更置信的回答用户问题。" ] }, { "cell_type": "code", "execution_count": 8, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "智能客服问答助手的回复是:在Windows系统中安装显示器驱动程序的步骤如下:\n", "\n", "1. 关闭计算机和所有已连接设备的电源,确保显示器连接正确^[1]^。\n", "2. 打开显示器的电源,然后打开系统单元的电源,让系统启动进入Windows系统^[1]^。\n", "3. 打开显示属性窗口,单击开始、控制面板、硬件和声音图标,然后单击显示图标^[1][2]^。\n", "4. 单击更改显示设置选项卡,然后单击高级设置图标^[1][2]^。\n", "5. 单击显示器选项卡,然后单击属性按钮^[1][2]^。\n", "6. 单击驱动程序选项卡,然后单击更新驱动程序,选择浏览计算机以查找驱动程序^[1][2]^。\n", "7. 选择从计算机上的设备驱动程序列表中选择,然后单击从磁盘安装按钮,浏览到X:Windows 8目录(其中X是CD-ROM驱动器的盘符),选择\"LENLS2014wA.inf\"文件,然后单击打开按钮^[1]^。\n", "8. 单击确定按钮,完成安装^[1]^。\n", "\n", "以上就是安装显示器驱动程序的步骤,希望对你有所帮助。\n", "\n", "智能客服问答助手的回复中,角标 2 对应参考文档是:显示器说明书.pdf\n" ] } ], "source": [ "response_message = agent.run(\n", " conversation_id = conversation_id,\n", " query=\"如何在windows系统中安装显示器驱动\",\n", ")\n", "\n", "print(\"智能客服问答助手的回复是:{}\\n\".format(response_message.content.answer))\n", "\n", "reference_doc_id = '2'\n", "reference_doc_name = \"\"\n", "for event in response_message.content.events:\n", " if event.event_type == \"RAGAgent\" and 'references' in event.detail:\n", " references = event.detail.get('references')\n", " for reference_doc in references:\n", " if reference_doc.get('id', '0') == reference_doc_id:\n", " reference_doc_name = reference_doc.get('document_name', '')\n", " break\n", "\n", "print(\"智能客服问答助手的回复中,角标 {} 对应参考文档是:{}\".format(reference_doc_id, reference_doc_name))" ] }, { "attachments": {}, "cell_type": "markdown", "metadata": {}, "source": [ "## 三、总结\n", "\n", "AppBuilder 为 基于RAG的 企业问答系统提供了 `appbuilder.console.agentbuilder` API,可以方便的以代码态调用已在平台发布的对话应用,方便的集成进用户自己的系统。\n", "\n", "本示例展示了如何创建应用,代码态调用应用,非流式对话,流式对话,以及基于对话结果展示引用文档。" ] } ], "metadata": { "kernelspec": { "display_name": "Python 3", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.9.6" }, "orig_nbformat": 4, "vscode": { "interpreter": { "hash": "31f2aee4e71d21fbe5cf8b01ff0e069b9275f58929596ceb00d14d90e3e16cd6" } } }, "nbformat": 4, "nbformat_minor": 2 } ================================================ FILE: cookbooks/end2end_application/rag/rag.ipynb ================================================ { "cells": [ { "cell_type": "markdown", "id": "f802e64d-4eaa-445d-a48a-1042a91bc394", "metadata": { "tags": [] }, "source": [ "# 智能问答机器人:简历筛选小助手\n", "\n", "## 目标\n", "通过对本地简历库的简历进行解析、切片、创建索引,实现基于JD进行简历筛选,并对筛选的Top1简历进行总结的功能\n", "\n", "## 准备工作\n", "### 平台注册\n", "1.先在appbuilder平台注册,获取token\n", "2.创建BES集群,详见(https://cloud.baidu.com/doc/BES/s/0jwvyk4tv)\n", "3.安装appbuilder-sdk" ] }, { "cell_type": "code", "execution_count": null, "id": "2939356f-61c2-42e9-9e0c-fc6729c193f6", "metadata": {}, "outputs": [], "source": [ "!pip install appbuilder-sdk\n", "!pip install elasticsearch==7.11.0" ] }, { "cell_type": "code", "execution_count": 1, "id": "4ccff03b-1567-4e8b-8e1f-9a5032690406", "metadata": { "tags": [] }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "init done\n" ] } ], "source": [ "import logging\n", "import os\n", "\n", "# 设置环境变量\n", "os.environ[\"APPBUILDER_TOKEN\"] = \"...\"\n", "\n", "# 创建BES集群后获得集群id、用户名、密码\n", "cluster_id = \"...\"\n", "username = \"...\"\n", "password = \"...\"\n", "\n", "print(\"init done\")\n" ] }, { "cell_type": "markdown", "id": "aeb2fa55-075f-48df-a9fb-8b40d9900684", "metadata": {}, "source": [ "## 开发过程\n", "### 对简历文档内容进行解析、切分" ] }, { "cell_type": "code", "execution_count": null, "id": "41559341-fd7a-478c-a08b-1477d79e9d41", "metadata": { "ExecuteTime": { "end_time": "2023-12-18T06:24:26.982459Z", "start_time": "2023-12-18T06:23:53.771345Z" } }, "outputs": [], "source": [ "import appbuilder\n", "from pathlib import Path\n", "\n", "# 基于doc_parser和doc_splitter解析file_path文件为若干个段落\n", "def parse_file(file_path, doc_parser, doc_splitter):\n", " input_msg = appbuilder.Message(str(file_path))\n", " doc_parser_result = doc_parser(input_msg, return_raw=True)\n", " doc_splitter_result = doc_splitter(doc_parser_result)\n", " return [f\"{file_path.name}+{para['text'][:384]}\" \n", " for para in doc_splitter_result.content[\"paragraphs\"]]\n", "\n", "# 文档切分的分块大小,每个分块最大340个字符\n", "chunk_size = 340\n", "\n", "# 本地简历库地址\n", "file_dir = \"../简历\"\n", "\n", "# 声明文档解析和文档切分组件\n", "doc_parser = appbuilder.DocParser()\n", "doc_splitter = appbuilder.DocSplitter(splitter_type=\"split_by_chunk\", max_segment_length=chunk_size) \n", "\n", "# 批量解析,形成段落切片列表\n", "resume_paragraphs = [para_text \n", " for file in Path(file_dir).iterdir() if file.is_file()\n", " for para_text in parse_file(file, doc_parser, doc_splitter)]\n", "\n", "print(f\"total length of splitted paragraphs {len(resume_paragraphs)}\")\n", "\n", "print(\"sample resume paragraphs\")\n", "for paras in resume_paragraphs[:3]:\n", " print(paras)" ] }, { "cell_type": "markdown", "id": "5fc5bc38-6bc5-4187-a8fd-f802d77d89fa", "metadata": {}, "source": [ "### 计算文档切片的语义向量并入库" ] }, { "cell_type": "code", "execution_count": null, "id": "d514a628-5ae3-4269-aada-eaf8b21c3793", "metadata": {}, "outputs": [], "source": [ "import time\n", "# 千帆Embedding\n", "embedding = appbuilder.Embedding()\n", "\n", "# 将段落切片列表入库到BESVectorStoreIndex,这里面用到的Baidu Elastic Search服务\n", "segments = appbuilder.Message(resume_paragraphs)\n", "vector_index = appbuilder.BESVectorStoreIndex.from_segments(\n", " segments=segments, cluster_id=cluster_id, user_name=username, \n", " password=password, embedding=embedding)\n", "\n", "# bes向量入库是异步操作,此处等待bes进行refresh\n", "time.sleep(5)\n", "print(\"index done.\")" ] }, { "cell_type": "markdown", "id": "16a8aa38-7a33-4e27-bca4-00900cfe1641", "metadata": {}, "source": [ "### 从工作职责描述中抽取关键词" ] }, { "cell_type": "code", "execution_count": null, "id": "9f45ef5f-6206-4b31-83c4-3c8eb2c86925", "metadata": {}, "outputs": [], "source": [ "# 招聘jd\n", "from collections import Counter, defaultdict\n", "\n", "# 工作职责描述\n", "job_desc = '''拥有大语言模型领域的研究背景,发表过期刊会议论文者加分;\n", "具备深度学习平台开发或大模型开发经验,能够独立完成任务;\n", "具备优秀的编程能力,熟悉tensorflow、pytorch、paddlepaddle中的一种深度学习框架;\n", "对人工智能有浓厚兴趣,愿意投入时间和精力深入研究;\n", "具备团队协作精神,能够与团队成员有效沟通,共同推进项目进展。'''\n", "\n", "# 标签抽取的组件\n", "tagger = appbuilder.TagExtraction(model=\"DeepSeek-V3.1\")\n", "\n", "# 从JD抽取标签并打印\n", "tags = tagger(appbuilder.Message(job_desc))\n", "\n", "print(\"从JD抽取标签并打印\")\n", "print(tags.content)\n", "tag_list = [tag.split(\".\")[1] for tag in tags.content.split(\"\\n\")]\n" ] }, { "cell_type": "markdown", "id": "21ef57a9-46cf-4939-b375-68e21d4b3e90", "metadata": {}, "source": [ "### 基于工作描述的关键词从简历库中检索简历并排序" ] }, { "cell_type": "code", "execution_count": null, "id": "7313e122-5199-4c90-bc6c-ad04e206ccc9", "metadata": {}, "outputs": [], "source": [ "# 基于JD抽取出来的标签,使用retriever对简历库进行检索,基于简历文件名称命中次数进行汇总和排序\n", "retriever = vector_index.as_retriever()\n", "\n", "resume_count = Counter()\n", "resume_content = defaultdict(set)\n", "\n", "for tag in tag_list:\n", " print(\"Going to retrieve resumes for tag: \", tag, \"\\nGot Results\")\n", " relevant_resumes = retriever(query=appbuilder.Message(tag), top_k=3)\n", " for idx, res in enumerate(relevant_resumes.content):\n", " name_and_content = res[\"text\"].split(\"+\")\n", " print(f\"{idx+1}: {name_and_content[0]}, {name_and_content[1]}\")\n", " resume_count[name_and_content[0]] += 1\n", " resume_content[name_and_content[0]].add(name_and_content[1])\n", " print()\n", "\n", "sorted_resumes = sorted(resume_count.items(), key=lambda x: x[1], reverse=True)\n", "print(sorted_resumes)" ] }, { "cell_type": "markdown", "id": "36ba212a-774b-4f26-a860-988a872423ac", "metadata": {}, "source": [ "### 对检索得到的最优简历进行总结" ] }, { "cell_type": "code", "execution_count": null, "id": "e38701cd-9fbf-4da4-982b-a87a9b310427", "metadata": {}, "outputs": [], "source": [ "\n", "play = appbuilder.Playground(\n", " prompt_template=\"基于候选人姓名、职责描述和简历内容,概括一下{name}的推荐理由。\\n候选人姓名: {name}\\n职责描述: {JD}\\n简历内容: {resume}\\n推荐理由: \",\n", " model=\"DeepSeek-V3.1\"\n", ")\n", "\n", "resume_summary = play(appbuilder.Message({\"JD\": job_desc, \"name\": sorted_resumes[0][0], \"resume\": \"\\n\".join(list(resume_content[sorted_resumes[0][0]]))}))\n", "print(resume_summary.content)" ] } ], "metadata": { "kernelspec": { "display_name": "Python 3 (ipykernel)", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.11.5" } }, "nbformat": 4, "nbformat_minor": 5 } ================================================ FILE: cookbooks/live_broadcast_material/2024_05_16/agent_run.py ================================================ # Copyright (c) 2024 Baidu, Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import os import time import appbuilder os.environ["APPBUILDER_TOKEN"] = "密钥" app_id = "应用ID" if __name__ == "__main__": builder = appbuilder.AppBuilderClient(app_id) stream = True # 控制是否执行流式输出 not_stream = True # 控制是否执行非流式输出 if not_stream: conversation_id = builder.create_conversation() start = time.time() msg = builder.run(conversation_id, "如何运用胯下变向进行突破?", ) answer = msg.content.answer.replace("\n", "") print("----------------非流式输出篮球教练回答内容----------------") i = 0 step = 30 while i + step < len(answer): print(answer[i: i + step]) i += step print(answer[i:len(answer)]) end = time.time() print("-----------------非流式输出耗时------------------") print("%.2f秒" % (end - start)) print("\n") if stream: conversation_id = builder.create_conversation() start = time.time() msg = builder.run(conversation_id, "如何运用胯下变向进行突破?", stream=True) costs = [] print("----------------流式输出篮球教练回答内容----------------") i = 0 step = 30 answer = "" for c in msg.content: costs.append("%.2f秒" % (time.time() - start)) answer += c.answer.replace("\n", "") if len(answer) - i > step: print(answer[i: i + step]) i += step while i + step < len(answer): print(answer[i: i + step]) i += step print(answer[i:len(answer)]) print("------------流式输出耗时序列------------") print(costs) ================================================ FILE: cookbooks/live_broadcast_material/2024_05_16/chatbot.py ================================================ # Copyright (c) 2024 Baidu, Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import os import time import wave import sys import pyaudio import webrtcvad import appbuilder import re os.environ["APPBUILDER_TOKEN"] = "密钥" CHUNK = 1024 FORMAT = pyaudio.paInt16 CHANNELS = 1 if sys.platform == 'darwin' else 2 RATE = 16000 DURATION = 30 # ms CHUNK = RATE // 1000 * DURATION class Chatbot: def __init__(self): self.p = pyaudio.PyAudio() self.tts = appbuilder.TTS() self.asr = appbuilder.ASR() self.agent = appbuilder.AppBuilderClient("应用iD") def run(self): self.run_tts_and_play_audio("我是你的专属聊天机器人,小智,如果你有什么问题,可以直接问我") while True: print("loop...") audio_path = "output.wav" # 记录音频,如果语音时长小于1秒,则忽略本次对话 print("开始记录音频...") if self.record_audio(audio_path) < 1000: time.sleep(1) continue print("音频记录结束") # 音频转文本 print("开始执行ASR...") query = self.run_asr(audio_path) print("结束执行ASR") # 询问智能体 print("正在执行智能体...") if len(query) == 0: continue answer = self.run_agent(query) results = re.findall(r'(https?://[^\s]+)', answer) for result in results: print("链接地址:", result) answer = answer.replace(result, "") print("answer:", answer) print("结束调用智能体") # 文本转语音 print("开始执行TTS并播报...") self.run_tts_and_play_audio(answer) print("结束TTS并播报结束") def record_audio(self, path): with (wave.open(path, 'wb') as wf): wf.setnchannels(CHANNELS) wf.setsampwidth(self.p.get_sample_size(FORMAT)) wf.setframerate(RATE) stream = self.p.open(format=FORMAT, channels=CHANNELS, rate=RATE, input=True) vad = webrtcvad.Vad(1) not_speech_times = 0 speech_times = 0 total_times = 0 start_up_times = 33 * 5 # 初始时间设置为5秒 history_speech_times = 0 while True: if history_speech_times > 33 * 10: break data = stream.read(CHUNK, False) if vad.is_speech(data, RATE): speech_times += 1 wf.writeframes(data) else: not_speech_times += 1 total_times += 1 if total_times >= start_up_times: history_speech_times += speech_times # 模拟滑窗重新开始计数 if float(not_speech_times) / float(total_times) > 0.7: break not_speech_times = 0 speech_times = 0 total_times = 0 start_up_times = start_up_times / 2 if start_up_times < 33: start_up_times = 33 stream.close() return history_speech_times * DURATION def run_tts_and_play_audio(self, text: str): msg = self.tts.run(appbuilder.Message(content={"text": text}), audio_type="pcm", model="paddlespeech-tts", stream=True) stream = self.p.open(format=self.p.get_format_from_width(2), channels=1, rate=24000, output=True, frames_per_buffer=2048) for pcm in msg.content: stream.write(pcm) stream.stop_stream() stream.close() def run_asr(self, audio_path: str): with open(audio_path, "rb") as f: content_data = {"audio_format": "wav", "raw_audio": f.read(), "rate": 16000} msg = appbuilder.Message(content_data) out = self.asr.run(msg) text = out.content["result"][0] return text def run_agent(self, query): conversation_id = self.agent.create_conversation() msg = self.agent.run(conversation_id, query, stream=True) answer = "" for content in msg.content: answer += content.answer return answer if __name__ == "__main__": chatbot = Chatbot() chatbot.run() ================================================ FILE: cookbooks/live_broadcast_material/2024_05_16/service_deploy.py ================================================ # Copyright (c) 2024 Baidu, Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import os import appbuilder os.environ["APPBUILDER_TOKEN"] = "密钥" component = appbuilder.Playground( prompt_template="{query}", model="ERNIE-Bot" ) agent = appbuilder.AgentRuntime(component=component) agent.serve(port=8091) ================================================ FILE: cookbooks/live_broadcast_material/2024_05_16/two_agent.py ================================================ # Copyright (c) 2024 Baidu, Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import os import appbuilder os.environ["APPBUILDER_TOKEN"] = "密钥" class IdiomSolitaire: def __init__(self, real_player, app_id1, app_id2): self.player1 = appbuilder.AppBuilderClient(app_id1) self.player2 = appbuilder.AppBuilderClient(app_id2) self.real_player = real_player def run(self): conversation_id1 = self.player1.create_conversation() conversation_id2 = self.player2.create_conversation() if self.real_player: print("---------游戏开始,请输入一个成语---------") q = str(input("真实玩家: ")) else: q = "龙年大吉" i = 1 while True: print("----------第%d轮比拼----------" % (i,)) msg = self.player1.run(conversation_id1, q) answer = msg.content.answer print("LLM玩家1: ", answer) # answer作为下一个玩家的输入 q = answer msg = self.player2.run(conversation_id2, q) answer = msg.content.answer print("LLM玩家2: ", msg.content.answer) q = answer if self.real_player: q = str(input("真实玩家: ")) i += 1 # 无真实玩家 def main1(): idiom_solitaire = IdiomSolitaire(False, "应用ID", "应用ID") idiom_solitaire.run() # 真实玩家 def main2(): idiom_solitaire = IdiomSolitaire(True, "应用ID", "应用ID") idiom_solitaire.run() if __name__ == "__main__": main1() # main2() ================================================ FILE: cookbooks/live_broadcast_material/2024_08_22/README.md ================================================ - AppBuilderClient-Tool Call - [本地调用内网tool工具](tool_call_1.ipynb) - [调用Agent执行本地命令](tool_call_2.ipynb) - [使用AppBuilderEventHandler简化tool_call操作](tool_call_3.ipynb) - [使用AppBuilderEventHandler生成图片并下载到本地](tool_call_4.ipynb) - Appbuilder DEBUG&Trace - [Appbuilder DEBUG&Trace](trace.ipynb) - Appbuilder knowledgebase - [Appbuilder knowledgebase](knowledgebase.ipynb) ================================================ FILE: cookbooks/live_broadcast_material/2024_08_22/knowledgebase.ipynb ================================================ { "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# AppBuilder-Knowledge:生产环境的知识库/文档/切片管理教学\n", "\n", "[知识库组件](https://github.com/baidubce/app-builder/blob/master/docs/BasisModule/Platform/KnowledgeBase/knowledgebase.md)\n", "\n", "知识库组件(KnowledgeBase)是对线上知识库操作的组件,可以通过SDK实现创建知识库、添加知识文档、查询知识库文档、删除知识文档等操作,可在平台console中查看结果。对console端知识库进行操作,可以通过SDK实现创建知识库、添加知识文档、查询知识库文档、删除知识文档等操作,可在平台console中查看结果\n", "\n", "应用场景:通过SDK代码实现console端知识库操作。\n", "\n", "#### AppBuilder-Knowledge代码态使用流程\n", "\n", "##### 新建一个知识库\n", "\n", "- 首先我们需要通过SDK新建一个知识库,新建知识库的代码示例如下:" ] }, { "cell_type": "code", "execution_count": 52, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "新建的知识库ID: 3cc48493-f9ff-48c8-a3ea-fcc17fdddded\n", "新建的知识库名称: my_knowledge\n" ] } ], "source": [ "import os\n", "import appbuilder\n", "\n", "os.environ[\"APPBUILDER_TOKEN\"] = \"your api key\"\n", "\n", "knowledge = appbuilder.KnowledgeBase()\n", "resp = knowledge.create_knowledge_base(\n", " name=\"my_knowledge\",\n", " description=\"my_knowledge\",\n", " type=\"public\",\n", " )\n", "print(\"新建的知识库ID: \", resp.id)\n", "print(\"新建的知识库名称: \", resp.name)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "##### 实例化已创建的知识库 \n", "- 接下来如果我们期望对知识库进行进一步操作,就需要实例化已创建的知识库 " ] }, { "cell_type": "code", "execution_count": 53, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "知识库ID: 3cc48493-f9ff-48c8-a3ea-fcc17fdddded\n" ] } ], "source": [ "my_knowledge_base_id = resp.id # 传入知识库ID\n", "my_knowledge = appbuilder.KnowledgeBase(my_knowledge_base_id)\n", "print(\"知识库ID: \", my_knowledge.knowledge_id)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "- 我们就成功在Appbuilder平台创建了一个名为my_knowledge的知识库\n", "\n", "![创建知识库](https://bj.bcebos.com/v1/appbuilder-sdk-components/%E5%88%9B%E5%BB%BA%E7%9F%A5%E8%AF%86%E5%BA%93.png?authorization=bce-auth-v1%2FALTAKGa8m4qCUasgoljdEDAzLm%2F2024-08-22T02%3A02%3A57Z%2F-1%2Fhost%2F0134e32c4f9221cfd3cb8ff74737ea000079639342b05fe4649a07fd9b18c11c)\n", "\n", "##### 获取知识库详情\n", "- 如果我们想要获取知识库详情,可以调用 `get_knowledge_base_detail` 方法,返回的response将包含知识库的详情信息" ] }, { "cell_type": "code", "execution_count": 54, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "查询的知识库ID: 3cc48493-f9ff-48c8-a3ea-fcc17fdddded\n", "查询的知识库名称: my_knowledge\n" ] } ], "source": [ "knowledge = appbuilder.KnowledgeBase()\n", "resp = knowledge.get_knowledge_base_detail(my_knowledge.knowledge_id)\n", "print(\"查询的知识库ID: \", resp.id)\n", "print(\"查询的知识库名称: \", resp.name)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "##### 获取知识库列表\n", "- 当你想查看你的账号的知识库,SDK同样支持调用知识库列表接口,获取知识库列表。需要提供知识库id作为起始搜索位置,不提供则会默认从第一个知识库开始搜索" ] }, { "cell_type": "code", "execution_count": 55, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "获取到的知识库列表: requestId='8e6d9bd4-73c2-41b9-9813-de65a5ca01ec' data=[KnowledgeBaseDetailResponse(id='271bba8b-2c77-4b52-aaa2-2d95dde9184a', name='千帆大模型平台文档', description=None, config=KnowledgeBaseConfig(index=KnowledgeBaseConfigIndex(type='public', esUrl='', username=None, password=None)))] marker='3cc48493-f9ff-48c8-a3ea-fcc17fdddded' nextMarker='271bba8b-2c77-4b52-aaa2-2d95dde9184a' maxKeys=1 isTruncated=False\n" ] } ], "source": [ "knowledge = appbuilder.KnowledgeBase()\n", "# 从my_knowledge知识库开始检索,检索10条\n", "resp = knowledge.get_knowledge_base_list(my_knowledge.knowledge_id,10)\n", "print(\"获取到的知识库列表: \", resp)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "##### 修改知识库\n", "- 如果我们对我们创建的知识库不满意,想要对其修改,SDK提供`modify_knowledge_base`方法,可以修改知识库,在下面的示例中我们将展示如何修改知识库的名称,接着我们按照知识库的id,查询知识库,查询知识库的名称是否改变,当然我们也可以去appbuilder平台个人空间去查看知识库名称是否更新\n" ] }, { "cell_type": "code", "execution_count": 56, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "查询的知识库ID: 3cc48493-f9ff-48c8-a3ea-fcc17fdddded\n", "查询的知识库名称: new_test_knowledge\n" ] } ], "source": [ "knowledge = appbuilder.KnowledgeBase()\n", "knowledge.modify_knowledge_base(my_knowledge.knowledge_id, name=\"new_test_knowledge\", description=\"测试\")\n", "\n", "# 接着我们按照知识库的id,查询知识库,查询知识库的名称是否改变\n", "resp = knowledge.get_knowledge_base_detail(my_knowledge.knowledge_id)\n", "print(\"查询的知识库ID: \", resp.id)\n", "print(\"查询的知识库名称: \", resp.name)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "##### 上传文档到知识库\n", "上传文档到知识库共有以下三种方式:\n", "- 上传文档到知识库\n", "- 上传通用文档\n", "- 向知识库添加文档" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "获取目标文档的file_url" ] }, { "cell_type": "code", "execution_count": 57, "metadata": {}, "outputs": [], "source": [ "file_url = \"https://bj.bcebos.com/v1/appbuilder-sdk-components/%E3%80%8A%E9%BB%91%E7%A5%9E%E8%AF%9D%EF%BC%9A%E6%82%9F%E7%A9%BA%E3%80%8BIP%E4%BB%8B%E7%BB%8D%E6%89%8B%E5%86%8C2024.pdf?authorization=bce-auth-v1%2FALTAKGa8m4qCUasgoljdEDAzLm%2F2024-08-21T11%3A40%3A45Z%2F-1%2Fhost%2Ff387e2cd2db95c9da26247c5d6c45f6dc9a817fa2721f0a780dc1eba433d02b8\"" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "###### 上传文档到知识库\n", "- 主要提供自定义文档处理策略,向知识库添加文档\n", " - 文档格式:rawText (允许配置后续分割策略)\n", " - 文档处理策略" ] }, { "cell_type": "code", "execution_count": 58, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "{'requestId': 'f698099c-b533-4500-a1f8-6b9f2087d1ba'}" ] }, "execution_count": 58, "metadata": {}, "output_type": "execute_result" } ], "source": [ "knowledge_base_id = my_knowledge.knowledge_id\n", "knowledge.create_documents(\n", "\tid=knowledge_base_id,\n", "\tcontentFormat=\"rawText\",\n", "\tsource=appbuilder.DocumentSource(\n", "\t\ttype=\"web\",\n", "\t\turls=[\"https://baike.baidu.com/item/%E9%BB%91%E7%A5%9E%E8%AF%9D%EF%BC%9A%E6%82%9F%E7%A9%BA/53303078?fr=ge_ala\"],\n", "\t\turlDepth=1,\n", "\t),\n", "\tprocessOption=appbuilder.DocumentProcessOption(\n", "\t\ttemplate=\"custom\",\n", "\t\tparser=appbuilder.DocumentChoices(\n", "\t\t\tchoices=[\"layoutAnalysis\", \"ocr\"]\n", "\t\t),\n", "\t\tchunker=appbuilder.DocumentChunker(\n", "\t\t\tchoices=[\"separator\"],\n", "\t\t\tseparator=appbuilder.DocumentSeparator(\n", "\t\t\t\tseparators=[\"。\"],\n", "\t\t\t\ttargetLength=300,\n", "\t\t\t\toverlapRate=0.25,\n", "\t\t\t),\n", "\t\t\tprependInfo=[\"title\", \"filename\"],\n", "\t\t),\n", "\t\tknowledgeAugmentation=appbuilder.DocumentChoices(choices=[\"faq\"]),\n", "\t),\n", ")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "###### 上传通用文档\n", "- SDK支持基于代码态的文档上传方法`upload_file`,以及包含文档的自定义切分逻辑的向知识库添加文档的方法``add_document`\n", "- 需要先将文档下载至本地" ] }, { "cell_type": "code", "execution_count": 59, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "文件已成功保存到 黑神话(悟空).pdf\n" ] } ], "source": [ "import requests\n", "\n", "def download_file(url, file_path):\n", " try:\n", " response = requests.get(url, stream=True)\n", " response.raise_for_status()\n", " with open(file_path, 'wb') as file:\n", " for chunk in response.iter_content(chunk_size=8192):\n", " if chunk:\n", " file.write(chunk)\n", " print(f\"文件已成功保存到 {file_path}\")\n", " except requests.RequestException as e:\n", " print(f\"下载失败: {e}\")\n", "\n", "file_url = \"https://bj.bcebos.com/v1/appbuilder-sdk-components/%E3%80%8A%E9%BB%91%E7%A5%9E%E8%AF%9D%EF%BC%9A%E6%82%9F%E7%A9%BA%E3%80%8BIP%E4%BB%8B%E7%BB%8D%E6%89%8B%E5%86%8C2024.pdf?authorization=bce-auth-v1%2FALTAKGa8m4qCUasgoljdEDAzLm%2F2024-08-21T11%3A40%3A45Z%2F-1%2Fhost%2Ff387e2cd2db95c9da26247c5d6c45f6dc9a817fa2721f0a780dc1eba433d02b8\"\n", "file_path = \"黑神话(悟空).pdf\" # 替换为你想要的文件名\n", "\n", "# 调用函数下载文件\n", "download_file(file_url, file_path)" ] }, { "cell_type": "code", "execution_count": 60, "metadata": {}, "outputs": [], "source": [ "upload_res = knowledge.upload_file(file_path)\n", "add_res = knowledge.add_document(\n", " content_type=\"raw_text\",\n", " file_ids=[upload_res.id],\n", " custom_process_rule=appbuilder.CustomProcessRule(\n", " separators=[\"?\"], target_length=400, overlap_rate=0.2\n", " ),\n", " knowledge_base_id=my_knowledge.knowledge_id\n", ")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "##### 获取知识库的文档列表\n", "在完成添加文档之后,如果我们想获取知识库中的文档列表,可以使用下面的方法:\n", "- 获取知识库的文档列表:`get_documents_list` 单次请求列表获得的文档数量,最大100\n", "- 获取知识库全部文档:`get_all_documents`" ] }, { "cell_type": "code", "execution_count": 61, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "知识库ID: 3cc48493-f9ff-48c8-a3ea-fcc17fdddded\n", "get_documents_list\n", "文档列表: request_id='da7bc5a5-c42d-47cd-82e7-674ff3d65502' data=[Document(id='139be427-5024-4af7-b5ca-1f15efdfea86', name='黑神话(悟空).pdf', created_at=1724295950, word_count=0, enabled=True, meta=DocumentMeta(source='upload_file', file_id='fc170b9e-0876-4d82-903c-5976e9a58453')), Document(id='dfeb440e-dc5f-4d1a-b0d8-6561b9fb5786', name='https://baijiahao.baidu.com/s?id=1802527379394162441', created_at=1724295904, word_count=0, enabled=True, meta=DocumentMeta(source='url', file_id=None))]\n", "get_all_documents\n", "id='139be427-5024-4af7-b5ca-1f15efdfea86' name='黑神话(悟空).pdf' created_at=1724295950 word_count=0 enabled=True meta=DocumentMeta(source='upload_file', file_id='fc170b9e-0876-4d82-903c-5976e9a58453')\n", "id='dfeb440e-dc5f-4d1a-b0d8-6561b9fb5786' name='https://baijiahao.baidu.com/s?id=1802527379394162441' created_at=1724295904 word_count=0 enabled=True meta=DocumentMeta(source='url', file_id=None)\n" ] } ], "source": [ "my_knowledge = appbuilder.KnowledgeBase(my_knowledge_base_id)\n", "print(\"知识库ID: \", my_knowledge.knowledge_id)\n", "\n", "# 获取知识库的文档列表:get_documents_list\n", "list_res = my_knowledge.get_documents_list()\n", "print(\"get_documents_list\")\n", "print(\"文档列表: \", list_res)\n", "\n", "# 获取知识库全部文档:get_all_documents\n", "doc_list = knowledge.get_all_documents(my_knowledge.knowledge_id)\n", "print(\"get_all_documents\")\n", "for message in doc_list:\n", " print(message)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "- 现在我们可以在Appbuilder中查看我们的知识库\n", "\n", "![向知识库传入文档](https://bj.bcebos.com/v1/appbuilder-sdk-components/%E5%90%91%E7%9F%A5%E8%AF%86%E5%BA%93%E4%BC%A0%E5%85%A5%E6%96%87%E6%A1%A3.png?authorization=bce-auth-v1%2FALTAKGa8m4qCUasgoljdEDAzLm%2F2024-08-22T10%3A56%3A50Z%2F-1%2Fhost%2Fe0a39a3fd3d2acd0f4b949d68b895b2943c63f94db7813fcace9674a11290681)\n", "\n", "# 现在我们基于new_test_knowledge知识库创建了Client应用\n", "\n", "![创建黑神话Client](https://bj.bcebos.com/v1/appbuilder-sdk-components/%E9%BB%91%E7%A5%9E%E8%AF%9DClient.png?authorization=bce-auth-v1%2FALTAKGa8m4qCUasgoljdEDAzLm%2F2024-08-22T02%3A19%3A30Z%2F-1%2Fhost%2F93016fe0808f5460859d678d6b2095ee6624842db914e15c73bd31a476b42402)\n", "\n", "接下来我们调用Client应用,查看运行效果" ] }, { "cell_type": "code", "execution_count": 22, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "《黑神话:悟空》是一款充满文化底蕴的游戏,用现代方式讲述经典中国故事,引发全球用户的共鸣^[1]^。\n" ] } ], "source": [ "# 从AppBuilder控制台【个人空间】-【应用】网页获取已发布应用的ID\n", "app_id = \"236b3e57-3464-43b0-8556-f165193721ef\"\n", "\n", "app_builder_client = appbuilder.AppBuilderClient(app_id)\n", "conversation_id = app_builder_client.create_conversation()\n", "\n", "resp = app_builder_client.run(conversation_id, \"请你用50字左右介绍一下《黑神话(悟空)》\")\n", "print(resp.content.answer)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "##### KnowledgeBase 同样提供代码态的接口,可以对知识库文档进行切片\n", "\n", "* 创建切片\n", "* 修改切片信息\n", "* 获取切片信息\n", "* 获取切片列表\n", "* 删除切片\n", "\n", "- 首先我们尝试让Client回答KnowledgeBase中没有的信息" ] }, { "cell_type": "code", "execution_count": 67, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "很抱歉,我没有找到关于《黑神话:悟空》中虎先锋的具体打法攻略。但是,一般来说,在动作冒险游戏中,打败敌人的关键通常在于熟练掌握角色的攻击方式、防御技巧和敌人的攻击模式。你可以尝试多次与虎先锋战斗,观察它的攻击方式和弱点,并结合孙悟空的技能和装备来制定相应的战斗策略。此外,你也可以在游戏的官方论坛或社区中寻找其他玩家分享的攻略和经验,这可能会对你有所帮助。\n", "\n", "请注意,不同玩家的游戏风格和策略可能有所不同,因此建议你在参考他人攻略的同时,结合自己的游戏情况进行调整和优化。\n" ] } ], "source": [ "# 从AppBuilder控制台【个人空间】-【应用】网页获取已发布应用的ID\n", "app_id = \"236b3e57-3464-43b0-8556-f165193721ef\"\n", "\n", "app_builder_client = appbuilder.AppBuilderClient(app_id)\n", "conversation_id = app_builder_client.create_conversation()\n", "\n", "resp = app_builder_client.run(conversation_id, \"《黑神话:悟空》的‌虎先锋怎么打?能不能提供一下攻略?\")\n", "print(resp.content.answer)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "- 这时候我们就需要使用为KnowledeBase添加切片为他增添知识点了\n", "###### 创建切片`create_chunk`\n", "\n", "- 为了增加对照,我们先为Client添加BaiduSearch组件,并运行它查看他能提供哪些信息" ] }, { "cell_type": "code", "execution_count": 68, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "《黑神话:悟空》的‌虎先锋打法攻略如下^[2]^:\n", "\n", "1. 起手进行蓄力,第一次蓄力攻击和虎先锋换血。\n", "2. 闪身躲避虎先锋的两端攻击。\n", "3. 对其进行攻击,使用精魄将其打到硬直,接着使用定身术将其定住,然后再进行攻击。\n", "4. 注意虎先锋会开启石化技能,可以规避攻击,并且进行反击,玩家在其进入石化后应避免出招。\n", "5. 在其第二次石化之后拉开距离,观察情况,躲避其的突进。\n", "6. 当虎先锋掏出剑之后,注意躲避其攻击,等待其将剑收回去再进行攻击。\n", "7. 在虎先锋血量很少的情况下使用定身来进行输出,随后使用攒的棍势再次输出即可击败虎先锋。\n" ] } ], "source": [ "# 从AppBuilder控制台【个人空间】-【应用】网页获取已发布应用的ID\n", "app_id = \"236b3e57-3464-43b0-8556-f165193721ef\"\n", "\n", "app_builder_client = appbuilder.AppBuilderClient(app_id)\n", "conversation_id = app_builder_client.create_conversation()\n", "\n", "resp = app_builder_client.run(conversation_id, \"《黑神话:悟空》的‌虎先锋怎么打?能不能提供一下攻略?\")\n", "print(resp.content.answer)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "- 我们发现BaiduSearch提供的信息不一定符合我们预期,这个时候我们就需要对知识库增加新的切片,来为我们的知识库不断更新知识点,获取document_id,支持对文档进行切片操作\n", "\n", "```python\n", "# 获取doc_list列表的第一个文档的document_id\n", "document_id = doc_list[0].id\n", "```\n", "\n", "- content: 切片内容" ] }, { "cell_type": "code", "execution_count": 69, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "知识库ID: 3cc48493-f9ff-48c8-a3ea-fcc17fdddded\n", "切片ID: 19e93596-a314-4ca3-81fa-d6c041433979\n" ] } ], "source": [ "# 获取doc_list列表的第一个文档的document_id\n", "document_id = doc_list[0].id\n", "my_knowledge = appbuilder.KnowledgeBase(my_knowledge_base_id)\n", "print(\"知识库ID: \", my_knowledge.knowledge_id)\n", "# 传入了一个内容为\"content\"的切片\n", "content = \"\"\"\n", "虎先锋是黑神话悟空中的一个boss,很多的玩家都非常的好奇这个boss要怎么样打,这里小编就为大家对虎先锋这个boss的打法进行了整合,可以让你更好的去进行战斗,帮助你击败这个敌人,详细的内容就在这里,快来一起看看吧。\n", "1、进入战斗后注意躲避boss的坠击伤害,快速闪避即可。\n", "2、和BOSS保持一定的距离,如果距离过近,它会对玩家造成三段连击伤害。\n", "3、当BOSS释放吼叫后,直接远离它,在远程进行输出。\n", "4、然后使用闪避躲避它释放的三连剑气和黑色的气旋。\n", "5、最后当BOSS变的坚硬时不作攻击,等它技能结束后继续输出即可轻松过关。\n", "\"\"\"\n", "resp = my_knowledge.create_chunk(documentId=document_id, content=content)\n", "print(\"切片ID: \", resp.id)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "- 再次运行Client看看他能否输出我们预期的知识点" ] }, { "cell_type": "code", "execution_count": 70, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "《黑神话:悟空》的‌虎先锋打法攻略如下^[1][3]^:\n", "\n", "1. 起手进行蓄力,第一次蓄力攻击和虎先锋换血。\n", "\n", "2. 随后闪身躲避起手的两端攻击。\n", "\n", "3. 对其进行攻击,使用精魄将其打到硬直,接着使用定身法将其定住,然后再进行攻击。\n", "\n", "4. 注意虎先锋会开启石化技能,可以规避攻击,并且进行反击,玩家在其进入石化后应尽可能避免出招。\n", "\n", "5. 在虎先锋血量很少的情况下使用定身法来进行输出,随后再输出即可击败虎先锋。\n" ] } ], "source": [ "app_id = \"236b3e57-3464-43b0-8556-f165193721ef\"\n", "\n", "app_builder_client = appbuilder.AppBuilderClient(app_id)\n", "conversation_id = app_builder_client.create_conversation()\n", "\n", "resp = app_builder_client.run(conversation_id, \"《黑神话:悟空》的‌虎先锋怎么打?能不能提供一下攻略?\")\n", "print(resp.content.answer)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "- 这次输出的信息就符合我们预期了。\n", "\n", "###### 修改切片信息`modify_chunk`\n", "\n", "- 如果我们对之前设置的切片信息不满意,可以通过`modify_chunk`方法进行修改。\n", "\n", "###### 获取切片信息`describe_chunk`\n", "\n", "- 我需要查看我刚才创建切片信息,可以使用`describe_chunk`方法\n", "\n", "###### 删除切片信息`delete_chunk`\n", "\n", "- 切片信息创建出来后,如果不需要了,可以通过`delete_chunk`方法进行删除。" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "##### 删除文档和知识库\n", "\n", "- 当你不再需要文档知识库时,可以删除它,SDK同样提供删除文档和知识库的方法\n", " - 从知识库删除文档 `KnowledgeBase().delete_document`\n", " - 删除知识库`delete_knowledge_base`" ] } ], "metadata": { "kernelspec": { "display_name": "python-12", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "undefined.undefined.undefined" } }, "nbformat": 4, "nbformat_minor": 2 } ================================================ FILE: cookbooks/live_broadcast_material/2024_08_22/tool_call_1.ipynb ================================================ { "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# 本地调用内网tool工具\n", "\n", "在完成Client与知识库交互的需求时,存在客户不想把数据信息上传到云端,而是希望在本地完成数据交互的需求,下面将展示一个调用内网tool工具的简单示例。查询本地信息\n", "\n", "##### 配置运行环境&导入Client应用" ] }, { "cell_type": "code", "execution_count": 2, "metadata": {}, "outputs": [], "source": [ "import os\n", "import appbuilder\n", "\n", "# AppBuilder Token,替换为您个人的Token\n", "os.environ[\"APPBUILDER_TOKEN\"] = \"your api key\"\n", "\n", "# 应用为:智能问题解决者\n", "app_id = \"b9473e78-754b-463a-916b-f0a9097a8e5f\"\n", "app_client = appbuilder.AppBuilderClient(app_id)\n", "conversation_id = app_client.create_conversation()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "##### 首次提问一个问题,应用不具备该能力,通过回答可以印证\n", "\n", "- 由于并没有关于张三同学的信息,所以Agent无法实现查询" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "message_1 = app_client.run(\n", " conversation_id=conversation_id,\n", " query=\"请问本公司的张三同学的生日是哪天?\",\n", ")\n", "print(\"Agent第一次回答: {}\".format(message_1.content.answer))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "**output**\n", "```\n", "Agent第一次回答: 为了回答这个问题,我们首先需要明确几个关键点:\n", "\n", "1. **问题理解**:\n", " - 需要确定的是“张三同学的生日”。\n", "\n", "2. **工具选择**:\n", " - 由于问题涉及的是特定个人的信息(张三的生日),这通常不是通过工具或系统查询能得到的,而是需要通过公司内部的人事记录或直接询问张三本人来获取。\n", "\n", "3. **解决方案生成**:\n", " - **步骤一**:首先,尝试访问公司的人事系统或员工档案,看是否有张三的生日信息记录。\n", " - **步骤二**:如果人事系统或员工档案中没有相关信息,或者你不具备访问权限,那么可以考虑直接询问张三本人或其同事,看是否有人知道他的生日。\n", " - **步骤三**:如果以上方法都不可行,还可以尝试联系公司的人力资源部门,看他们是否能提供相关信息。\n", "\n", "4. **注意事项**:\n", " - 在尝试获取张三的生日信息时,要确保遵守公司的隐私政策和相关法律法规,不要侵犯张三的隐私权。\n", " - 如果张三不愿意透露他的生日信息,应尊重他的选择,并停止进一步询问。\n", "\n", "5. **可能遇到的问题**:\n", " - 人事系统或员工档案中可能没有张三的生日信息。\n", " - 张三或其同事可能不愿意透露生日信息。\n", " - 人力资源部门可能因隐私政策而无法提供相关信息。\n", "\n", "综上所述,要确定张三的生日,最直接且尊重隐私的方法是直接询问张三本人,或者通过公司正式渠道(如人力资源部门)在遵守隐私政策的前提下进行查询。\n", "```\n", "\n", "\n", "##### 赋予应用一个本地查询组件能力\n", "\n", "- 这里我们使用info_dict模拟一个数据库查询的返回结果" ] }, { "cell_type": "code", "execution_count": 4, "metadata": {}, "outputs": [], "source": [ "def get_person_infomation(name: str):\n", " info_dict = {\n", " \"张三\": \"1980年1月1日\",\n", " \"李四\": \"1975年12月31日\",\n", " \"刘伟\": \"1990年12月30日\"\n", " }\n", "\n", " if name in info_dict:\n", " return f\"您要查找的{name}的生日是:{info_dict[name]}\"\n", " else:\n", " return f\"您要查找的{name}的信息我们暂未收录,请联系管理员添加。\"\n", " \n", "# 创建工具的描述:json_schema格式\n", "tools = [\n", " {\n", " \"type\": \"function\",\n", " \"function\": {\n", " \"name\": \"get_person_infomation\",\n", " \"description\": \"查找公司内指定人员的信息\",\n", " \"parameters\": {\n", " \"type\": \"object\",\n", " \"properties\": {\n", " \"name\": {\n", " \"type\": \"string\",\n", " \"description\": \"人员名称,例如:张三、李四\",\n", " },\n", " },\n", " \"required\": [\"name\"],\n", " },\n", " },\n", " }\n", "]" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "- 现在我们已经完成了本地tool组件的设计,接下来我们将tool的功能赋予Client应用" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "message_2 = app_client.run(\n", " conversation_id=conversation_id,\n", " query=\"请问本公司的张三同学的生日是哪天?\",\n", " tools=tools\n", ")\n", "print(\"Agent的中间思考过程:\")\n", "print(message_2.content.events[-1].model_dump_json(indent=4))\n", "print(\"Agent思考结束,等待我们上传本地结果\\n\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "**output**\n", "这部分输出为Client应用的思考过程\n", "```\n", "Agent的中间思考过程:\n", "{\n", " \"code\": 0,\n", " \"message\": \"\",\n", " \"status\": \"interrupt\",\n", " \"event_type\": \"Interrupt\",\n", " \"content_type\": \"contexts\",\n", " \"detail\": {\n", " \"text\": {\n", " \"function_call\": {\n", " \"thought\": \"用户想要查询公司内张三同学的生日信息,这个需求很明确,且背景信息也足够。我可以使用get_person_infomation工具来查找张三的生日信息。\",\n", " \"name\": \"get_person_infomation\",\n", " \"arguments\": {\n", " \"name\": \"张三\"\n", " },\n", " \"usage\": {\n", " \"prompt_tokens\": 697,\n", " \"completion_tokens\": 87,\n", " \"total_tokens\": 784,\n", " \"name\": \"ERNIE-4.0-Turbo-8K\",\n", " \"type\": \"plan\"\n", " },\n", " \"tool_call_id\": \"c23309f7-e24a-4476-85e2-3ef9cfd4f6ed\"\n", " },\n", " \"used_tool\": []\n", "...\n", " ]\n", "}\n", "Agent思考结束,等待我们上传本地结果\n", "```\n", "\n", "- 大模型下发了调用本地函数的参数,我们使用这个参数调用本地函数" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "tool_call = message_2.content.events[-1].tool_calls[-1]\n", "tool_call_id = tool_call.id\n", "tool_call_argument = tool_call.function.arguments\n", "local_func_result = get_person_infomation(**tool_call_argument)\n", "print(\"local_func_result: {}\\n\".format(local_func_result))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "**output**\n", "```\n", "local_func_result: 您要查找的张三的生日是:1980年1月1日\n", "```\n", "\n", "- 向应用返回本地运行的结果,完成本地函数toolcall调用" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "message_3 = app_client.run(\n", " conversation_id=conversation_id,\n", " tool_outputs=[{\n", " \"tool_call_id\": tool_call_id,\n", " \"output\": local_func_result\n", " }]\n", ")\n", "print(\"Agent 拥有了本地函数调用能力后,回答是: {}\".format(message_3.content.answer))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "**output**\n", "```\n", "Agent的中间思考过程:\n", "{\n", " \"code\": 0,\n", " \"message\": \"\",\n", " \"status\": \"interrupt\",\n", " \"event_type\": \"Interrupt\",\n", " \"content_type\": \"contexts\",\n", " \"detail\": {\n", " \"text\": {\n", " \"function_call\": {\n", " \"thought\": \"用户想要查询公司内张三同学的生日信息,这个需求很明确,且背景信息也足够。我可以使用get_person_infomation工具来查找张三的生日信息。\",\n", " \"name\": \"get_person_infomation\",\n", " \"arguments\": {\n", " \"name\": \"张三\"\n", " },\n", " \"usage\": {\n", " \"prompt_tokens\": 697,\n", " \"completion_tokens\": 87,\n", " \"total_tokens\": 784,\n", " \"name\": \"ERNIE-4.0-Turbo-8K\",\n", " \"type\": \"plan\"\n", " },\n", " \"tool_call_id\": \"c23309f7-e24a-4476-85e2-3ef9cfd4f6ed\"\n", " },\n", " \"used_tool\": []\n", "...\n", " ]\n", "}\n", "Agent思考结束,等待我们上传本地结果\n", "\n", "Output is truncated. View as a scrollable element or open in a text editor. Adjust cell output settings...\n", "\n", "local_func_result: 您要查找的张三的生日是:1980年1月1日\n", "\n", "Agent 拥有了本地函数调用能力后,回答是: # 解决方案\n", "\n", "## 问题分析\n", "\n", "用户想要查询公司内张三同学的生日信息。这是一个明确且具体的需求,我们可以通过`get_person_infomation`工具来获取这一信息。\n", "\n", "## 工具运用\n", "\n", "1. **工具选择**:`get_person_infomation`\n", "2. **参数设置**:\n", "\n", "\t* `name`:张三\n", "\n", "3. **执行结果**:张三的生日是1980年1月1日。\n", "\n", "## 解决方案步骤\n", "\n", "1. 使用`get_person_infomation`工具,并设置参数`name`为“张三”。\n", "2. 等待工具执行,并获取张三的生日信息。\n", "3. 将获取到的生日信息(1980年1月1日)告知用户。\n", "\n", "## 注意事项\n", "\n", "* 确保在使用`get_person_infomation`工具时,输入的姓名与公司内部记录的姓名完全一致,以避免查询错误。\n", "* 如果工具返回“未找到”或类似结果,请检查姓名是否有误或联系公司人事部门确认信息。\n", "\n", "通过上述步骤,我们可以准确地回答用户的问题,并提供张三的生日信息。\n", "```" ] } ], "metadata": { "kernelspec": { "display_name": "python-12", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.12.4" } }, "nbformat": 4, "nbformat_minor": 2 } ================================================ FILE: cookbooks/live_broadcast_material/2024_08_22/tool_call_2.ipynb ================================================ { "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# 本地调用tool工具-调用Agent执行本地命令\n", "\n", "部分开发者需要给Client应用提供与本地命令交互的能力,比如在Client应用中调用Agent执行本地命令。并实现数据或文件的处理\n", "\n", "##### 配置运行环境&导入Client应用" ] }, { "cell_type": "code", "execution_count": 5, "metadata": {}, "outputs": [], "source": [ "import os\n", "import appbuilder\n", "\n", "# AppBuilder Token,替换为您个人的Token\n", "os.environ[\"APPBUILDER_TOKEN\"] = \"your api key\"\n", "\n", "# 应用为:智能问题解决者\n", "app_id = \"b9473e78-754b-463a-916b-f0a9097a8e5f\"\n", "app_client = appbuilder.AppBuilderClient(app_id)\n", "conversation_id = app_client.create_conversation()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "##### 创建一个能执行本地bash命令的tool工具" ] }, { "cell_type": "code", "execution_count": 6, "metadata": {}, "outputs": [], "source": [ "# 赋予应用一个执行本地命令的能力\n", "def execute_local_command(cmd: str):\n", " import subprocess\n", " try:\n", " result = subprocess.check_output(cmd, shell=True).decode(\"utf-8\")\n", " if result.strip() == \"\":\n", " return \"命令执行成功,无返回值\"\n", " return result\n", " except Exception as e:\n", " return str(e)\n", "\n", "\n", "# 创建工具的描述:json_schema格式\n", "tools = [\n", " {\n", " \"type\": \"function\",\n", " \"function\": {\n", " \"name\": \"execute_local_command\",\n", " \"description\": \"可以在bash环境中,执行输入的指令,注意,一次只能执行一个原子命令。例如:ls\",\n", " \"parameters\": {\n", " \"type\": \"object\",\n", " \"properties\": {\n", " \"cmd\": {\n", " \"type\": \"string\",\n", " \"description\": \"需要执行的指令\",\n", " },\n", " },\n", " \"required\": [\"cmd\"],\n", " },\n", " },\n", " }\n", "]" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "- 我们再次询问应用,并给他赋予这个能力" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "message_1 = app_client.run(\n", " conversation_id=conversation_id,\n", " query=\"请问当前文件夹下有哪些文件?如果没有test.txt文件,请新建一个test.txt文件,内容为:Hello World!\",\n", " tools=tools\n", ")\n", "print(\"Agent的中间思考过程:\")\n", "print(message_1.content.events[-1].model_dump_json(indent=4))\n", "print(\"Agent思考结束,等待我们上传本地结果\\n\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "**output**\n", "\n", "- Agent的中间思考过程\n", "\n", "```\n", "Agent的中间思考过程:\n", "{\n", " \"code\": 0,\n", " \"message\": \"\",\n", " \"status\": \"interrupt\",\n", " \"event_type\": \"Interrupt\",\n", " \"content_type\": \"contexts\",\n", " \"detail\": {\n", " \"text\": {\n", " \"function_call\": {\n", " \"thought\": \"首先,我需要使用execute_local_command工具来执行ls命令,列出当前文件夹下的所有文件。然后,我需要检查输出中是否存在test.txt文件。如果不存在,我将再次使用execute_local_command工具来执行echo命令,创建一个新的test.txt文件,并写入内容'Hello World!'。\",\n", " \"name\": \"execute_local_command\",\n", " \"arguments\": {\n", " \"cmd\": \"ls\"\n", " },\n", " \"usage\": {\n", " \"prompt_tokens\": 718,\n", " \"completion_tokens\": 111,\n", " \"total_tokens\": 829,\n", " \"name\": \"ERNIE-4.0-Turbo-8K\",\n", " \"type\": \"plan\"\n", " },\n", " \"tool_call_id\": \"f60b241c-ddda-46aa-a2a6-b8bf1da2a424\"\n", " },\n", " \"used_tool\": []\n", "...\n", " ]\n", "}\n", "Agent思考结束,等待我们上传本地结果\n", "```\n", "\n", "- 大模型下发了调用本地函数的参数,我们使用这个参数调用本地函数" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "tool_call = message_1.content.events[-1].tool_calls[-1]\n", "tool_call_id = tool_call.id\n", "tool_call_argument = tool_call.function.arguments\n", "local_func_result = execute_local_command(**tool_call_argument)\n", "print(\"No.1 local_func_result:\\n {}\\n\".format(local_func_result))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "**output**\n", "```\n", "No.1 local_func_result:\n", "multi_tool_call.ipynb\n", "multi_tool_call.py\n", "multi_tool_call_with_handler.py\n", "sdk_ knowledgebase.ipynb\n", "sdk_trace.ipynb\n", "simple_tool_call.ipynb\n", "simple_tool_call.py\n", "tmp.log\n", "黑神话(悟空).pdf\n", "```\n", "\n", "- 向应用返回本地运行的结果,继续等待Agent的思考" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "message_2 = app_client.run(\n", " conversation_id=conversation_id,\n", " tool_outputs=[{\n", " \"tool_call_id\": tool_call_id,\n", " \"output\": local_func_result\n", " }]\n", ")\n", "\n", "event_status = message_2.content.events[-1].status\n", "if event_status != \"interrupt\":\n", " print(\"Agent 的回答是:\\n\")\n", " print(message_2.content.answer)\n", " quit()\n", "\n", "\n", "print(\"Agent的中间思考过程:\")\n", "print(message_2.content.events[-1].model_dump_json(indent=4))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "**output**\n", "```\n", "Agent的中间思考过程:\n", "{\n", " \"code\": 0,\n", " \"message\": \"\",\n", " \"status\": \"interrupt\",\n", " \"event_type\": \"Interrupt\",\n", " \"content_type\": \"contexts\",\n", " \"detail\": {\n", " \"text\": {\n", " \"function_call\": {\n", " \"thought\": \"根据execute_local_command工具的返回结果,当前文件夹下并没有'test.txt'文件。因此,我需要使用execute_local_command工具来执行'echo \\\"Hello World\\\" > test.txt'命令,以创建新的'test.txt'文件并写入内容'Hello World!'。\",\n", " \"name\": \"execute_local_command\",\n", " \"arguments\": {\n", " \"cmd\": \"echo \\\"Hello World\\\" > test.txt\"\n", " },\n", " \"usage\": {\n", " \"prompt_tokens\": 1040,\n", " \"completion_tokens\": 117,\n", " \"total_tokens\": 1157,\n", " \"name\": \"ERNIE-4.0-Turbo-8K\",\n", " \"type\": \"plan\"\n", " },\n", " \"tool_call_id\": \"9eaa3831-0d85-47eb-a39f-866ad2690c28\"\n", " },\n", " \"used_tool\": [\n", "...\n", " }\n", " }\n", " ]\n", "}\n", "```\n", "\n", "- 大模型下发了调用本地函数的参数,我们使用这个参数调用本地函数" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "\n", "tool_call = message_2.content.events[-1].tool_calls[-1]\n", "tool_call_id = tool_call.id\n", "tool_call_argument = tool_call.function.arguments\n", "local_func_result = execute_local_command(**tool_call_argument)\n", "print(\"No.2 local_func_result: {}\\n\".format(local_func_result))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "**output**\n", "```\n", "No.2 local_func_result: 命令执行成功,无返回值\n", "```\n", "\n", "- 向应用返回本地运行的结果,完成应用的调用" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "message_3 = app_client.run(\n", " conversation_id=conversation_id,\n", " tool_outputs=[{\n", " \"tool_call_id\": tool_call_id,\n", " \"output\": local_func_result\n", " }]\n", ")\n", "\n", "event_status = message_3.content.events[-1].status\n", "if event_status != \"interrupt\":\n", " print(\"Agent 的回答是:\\n\")\n", " print(message_3.content.answer)\n", " quit()\n", "\n", "print(\"Agent的中间思考过程:\")\n", "print(message_3.content.events[-1].model_dump_json(indent=4))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "**output**\n", "```\n", "Agent的中间思考过程:\n", "{\n", " \"code\": 0,\n", " \"message\": \"\",\n", " \"status\": \"interrupt\",\n", " \"event_type\": \"Interrupt\",\n", " \"content_type\": \"contexts\",\n", " \"detail\": {\n", " \"text\": {\n", " \"function_call\": {\n", " \"thought\": \"用户的需求是列出当前文件夹下的所有文件,并在没有test.txt文件的情况下创建一个新的test.txt文件,内容为'Hello World!'。根据之前的执行结果,我们已经成功创建了test.txt文件并写入了内容。现在,我需要再次使用execute_local_command工具来执行ls命令,以确认test.txt文件已经成功创建,并且列出当前文件夹下的所有文件,以满足用户的完整需求。\",\n", " \"name\": \"execute_local_command\",\n", " \"arguments\": {\n", " \"cmd\": \"ls\"\n", " },\n", " \"usage\": {\n", " \"prompt_tokens\": 1115,\n", " \"completion_tokens\": 133,\n", " \"total_tokens\": 1248,\n", " \"name\": \"ERNIE-4.0-Turbo-8K\",\n", " \"type\": \"plan\"\n", " },\n", " \"tool_call_id\": \"eaf51384-b48c-41d2-965a-ca57efb4a6f1\"\n", " },\n", " \"used_tool\": [\n", " {\n", " \"function_call\": {\n", " \"thought\": \"首先,我需要使用execute_local_command工具来执行ls命令,列出当前文件夹下的所有文件。然后,我需要检查输出中是否存在test.txt文件。如果不存在,我将再次使用execute_local_command工具来执行echo命令,创建一个新的test.txt文件,并写入内容'Hello World!'。\",\n", " \"name\": \"execute_local_command\",\n", " \"arguments\": {\n", " \"cmd\": \"ls\"\n", " }\n", " },\n", " \"function_resp\": \"multi_tool_call.ipynb\\nmulti_tool_call.py\\nmulti_tool_call_with_handler.py\\nsdk_ knowledgebase.ipynb\\nsdk_trace.ipynb\\nsimple_tool_call.ipynb\\nsimple_tool_call.py\\ntmp.log\\n黑神话(悟空).pdf\\n\"\n", " },\n", " {\n", " \"function_call\": {\n", " \"thought\": \"根据执行结果,当前文件夹下并没有test.txt文件,所以需要使用execute_local_command工具来执行echo命令,创建一个新的test.txt文件,并写入内容'Hello World!'。\",\n", " \"name\": \"execute_local_command\",\n", " \"arguments\": {\n", " \"cmd\": \"echo 'Hello World!' > test.txt\"\n", " },\n", " \"usage\": {\n", " \"prompt_tokens\": 1025,\n", " \"completion_tokens\": 96,\n", " \"total_tokens\": 1121,\n", " \"name\": \"ERNIE-4.0-Turbo-8K\",\n", " \"type\": \"plan\"\n", " },\n", " \"tool_call_id\": \"f43bac97-667d-40f0-a138-c6ade008bdef\"\n", " },\n", " \"function_resp\": \"命令执行成功,无返回值\"\n", " }\n", " ]\n", " }\n", " },\n", " \"usage\": null,\n", " \"tool_calls\": [\n", " {\n", " \"id\": \"eaf51384-b48c-41d2-965a-ca57efb4a6f1\",\n", " \"type\": \"function\",\n", " \"function\": {\n", " \"name\": \"execute_local_command\",\n", " \"arguments\": {\n", " \"cmd\": \"ls\"\n", " }\n", " }\n", " }\n", " ]\n", "}\n", "```\n", "\n", "- 大模型下发了调用本地函数的参数,我们使用这个参数调用本地函数" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "tool_call = message_3.content.events[-1].tool_calls[-1]\n", "tool_call_id = tool_call.id\n", "tool_call_argument = tool_call.function.arguments\n", "local_func_result = execute_local_command(**tool_call_argument)\n", "print(\"No.3 local_func_result: {}\\n\".format(local_func_result))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "**output**\n", "```\n", "No.3 local_func_result: multi_tool_call.ipynb\n", "multi_tool_call.py\n", "multi_tool_call_with_handler.py\n", "sdk_ knowledgebase.ipynb\n", "sdk_trace.ipynb\n", "simple_tool_call.ipynb\n", "simple_tool_call.py\n", "test.txt\n", "tmp.log\n", "黑神话(悟空).pdf\n", "```\n", "\n", "- 向应用返回本地运行的结果,完成应用的调用" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "message_4 = app_client.run(\n", " conversation_id=conversation_id,\n", " tool_outputs=[{\n", " \"tool_call_id\": tool_call_id,\n", " \"output\": local_func_result\n", " }]\n", ")\n", "print(\"Agent 的回答是:\\n\")\n", "print(message_4.content.answer)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "**output**\n", "```\n", "Agent 的回答是:\n", "\n", "当前文件夹下的文件包括:\n", "\n", "- multi_tool_call.ipynb\n", "- multi_tool_call.py\n", "- multi_tool_call_with_handler.py\n", "- sdk_knowledgebase.ipynb\n", "- sdk_trace.ipynb\n", "- simple_tool_call.ipynb\n", "- simple_tool_call.py\n", "- test.txt\n", "- tmp.log\n", "- 黑神话(悟空).pdf\n", "\n", "由于当前文件夹下没有test.txt文件,因此已经成功创建了一个新的test.txt文件,并写入了内容'Hello World!'。现在,test.txt文件已经出现在文件夹中。\n", "```\n", "\n", "我们就完成了一个基于Client与自定义tool工具完成了一个 \"请问当前文件夹下有哪些文件?如果没有test.txt文件,请新建一个test.txt文件,内容为:Hello World\" 的操作" ] } ], "metadata": { "kernelspec": { "display_name": "python-12", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.12.4" } }, "nbformat": 4, "nbformat_minor": 2 } ================================================ FILE: cookbooks/live_broadcast_material/2024_08_22/tool_call_3.ipynb ================================================ { "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# 本地调用tool工具-使用AppBuilderEventHandler简化tool_call操作\n", "\n", "基于multi_tool_call的示例,我们可以使用Client应用来执行tool_call操作,完成指定的命令,但是需要自己配置client的思考与运行流程,较为繁琐。SDK提供了使用AppBuilderEventHandler简化tool_call操作的功能\n", "\n", "##### 配置运行环境&导入Client应用" ] }, { "cell_type": "code", "execution_count": 4, "metadata": {}, "outputs": [], "source": [ "import os\n", "import appbuilder\n", "\n", "\n", "# AppBuilder Token,替换为您个人的Token\n", "os.environ[\"APPBUILDER_TOKEN\"] = \"your api key\"\n", "\n", "# 应用为:智能问题解决者\n", "app_id = \"b9473e78-754b-463a-916b-f0a9097a8e5f\"\n", "app_client = appbuilder.AppBuilderClient(app_id)\n", "conversation_id = app_client.create_conversation()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "##### 继承AppBuilderEventHandler类实现一个Agent框架的定义" ] }, { "cell_type": "code", "execution_count": 5, "metadata": {}, "outputs": [], "source": [ "from appbuilder.core.console.appbuilder_client.event_handler import AppBuilderEventHandler\n", "class MyEventHandler(AppBuilderEventHandler):\n", " def execute_local_command(self, cmd: str):\n", " import subprocess\n", " try:\n", " result = subprocess.check_output(cmd, shell=True).decode(\"utf-8\")\n", " if result.strip() == \"\":\n", " return \"命令执行成功,无返回值\"\n", " return result\n", " except Exception as e:\n", " return str(e)\n", " \n", " def interrupt(self, run_context, run_response):\n", " thought = run_context.current_thought\n", " # 绿色打印\n", " print(\"\\033[1;32m\", \"-> Agent 中间思考: \", thought, \"\\033[0m\")\n", "\n", " tool_output = []\n", " for tool_call in run_context.current_tool_calls:\n", " tool_call_id = tool_call.id\n", " tool_res = self.execute_local_command(\n", " **tool_call.function.arguments)\n", " # 蓝色打印\n", " print(\"\\033[1;34m\", \"-> 本地ToolCall结果: \\n\", tool_res, \"\\033[0m\\n\")\n", " tool_output.append(\n", " {\n", " \"tool_call_id\": tool_call_id,\n", " \"output\": tool_res\n", " }\n", " )\n", " return tool_output\n", " \n", " def success(self, run_context, run_response):\n", " print(\"\\n\\033[1;31m\",\"-> Agent 非流式回答: \\n\", run_response.answer, \"\\033[0m\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "##### 定义本地的tools工具" ] }, { "cell_type": "code", "execution_count": 6, "metadata": {}, "outputs": [], "source": [ "tools = [\n", " {\n", " \"type\": \"function\",\n", " \"function\": {\n", " \"name\": \"execute_local_command\",\n", " \"description\": \"可以在bash环境中,执行输入的指令,注意,一次只能执行一个原子命令。例如:ls\",\n", " \"parameters\": {\n", " \"type\": \"object\",\n", " \"properties\": {\n", " \"cmd\": {\n", " \"type\": \"string\",\n", " \"description\": \"需要执行的指令\",\n", " },\n", " },\n", " \"required\": [\"cmd\"],\n", " },\n", " },\n", " }\n", "]" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "##### 运行Client实现实现链路的调用" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "with app_client.run_with_handler(\n", " conversation_id = conversation_id,\n", " query = \"请问当前文件夹下有哪些文件?如果没有test.txt文件,请新建一个test.txt文件,内容为:Hello World!\",\n", " tools = tools,\n", " event_handler = MyEventHandler(),\n", " ) as run:\n", " run.until_done()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "**output**\n", "```\n", " -> Agent 中间思考: 首先,我需要使用execute_local_command工具来执行'ls'命令,列出当前文件夹下的所有文件。然后,我需要检查输出中是否存在test.txt文件。如果不存在,我将再次使用execute_local_command工具来执行'echo \"Hello World\" > test.txt'命令,以创建并写入test.txt文件。 \n", " -> 本地ToolCall结果: \n", " multi_tool_call.ipynb\n", "multi_tool_call.py\n", "multi_tool_call_with_handler.ipynb\n", "multi_tool_call_with_handler.py\n", "sdk_ knowledgebase.ipynb\n", "sdk_trace.ipynb\n", "simple_tool_call.ipynb\n", "simple_tool_call.py\n", "tmp.log\n", "黑神话(悟空).pdf\n", " \n", "\n", " -> Agent 中间思考: 根据execute_local_command工具的返回结果,当前文件夹下并没有test.txt文件。因此,我需要使用execute_local_command工具来执行'echo \"Hello World\" > test.txt'命令,以创建并写入test.txt文件。 \n", " -> 本地ToolCall结果: \n", " 命令执行成功,无返回值 \n", "\n", "\n", " -> Agent 非流式回答: \n", " 当前文件夹下的文件包括:\n", "\n", "- multi_tool_call.ipynb\n", "- multi_tool_call.py\n", "- multi_tool_call_with_handler.ipynb\n", "...\n", "- tmp.log\n", "- 黑神话(悟空).pdf\n", "\n", "经过检查,发现当前文件夹下**不存在**test.txt文件。因此,已经为您新建了一个test.txt文件,并写入了内容“Hello World!”。 \n", "```\n", "\n", "- 使用AppBuilderEventHandler架构可以简化client的交互方式" ] } ], "metadata": { "kernelspec": { "display_name": "python-12", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.12.4" } }, "nbformat": 4, "nbformat_minor": 2 } ================================================ FILE: cookbooks/live_broadcast_material/2024_08_22/tool_call_4.ipynb ================================================ { "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# 本地调用tool工具-使用AppBuilderEventHandler简化tool_call操作\n", "\n", "基于multi_tool_call的示例,我们可以使用Client应用来执行tool_call操作,完成指定的命令,但是需要自己配置client的思考与运行流程,较为繁琐。SDK提供了使用AppBuilderEventHandler简化tool_call操作的功能,这里我们将调用Client应用,使其调用Text2Image工具生成图片,并将文件下载到本地\n", "\n", "##### 配置运行环境&导入Client应用" ] }, { "cell_type": "code", "execution_count": 2, "metadata": {}, "outputs": [], "source": [ "import os\n", "import appbuilder\n", "\n", "\n", "# AppBuilder Token,替换为您个人的Token\n", "os.environ[\"APPBUILDER_TOKEN\"] = \"your api key\"\n", "\n", "# 应用为:智能问题解决者\n", "app_id = \"e97865e7-e1be-45d3-ab8a-ea84ca6e0b9a\"\n", "app_client = appbuilder.AppBuilderClient(app_id)\n", "conversation_id = app_client.create_conversation()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "##### 继承AppBuilderEventHandler类实现一个Agent框架的定义" ] }, { "cell_type": "code", "execution_count": 3, "metadata": {}, "outputs": [], "source": [ "from appbuilder.core.console.appbuilder_client.event_handler import AppBuilderEventHandler\n", "class MyEventHandler(AppBuilderEventHandler):\n", " def execute_local_command(self, cmd: str):\n", " import subprocess\n", " try:\n", " result = subprocess.check_output(cmd, shell=True).decode(\"utf-8\")\n", " if result.strip() == \"\":\n", " return \"命令执行成功,无返回值\"\n", " return result\n", " except Exception as e:\n", " return str(e)\n", " \n", " def interrupt(self, run_context, run_response):\n", " thought = run_context.current_thought\n", " # 绿色打印\n", " print(\"\\033[1;32m\", \"-> Agent 中间思考: \", thought, \"\\033[0m\")\n", "\n", " tool_output = []\n", " for tool_call in run_context.current_tool_calls:\n", " tool_call_id = tool_call.id\n", " tool_res = self.execute_local_command(\n", " **tool_call.function.arguments)\n", " # 蓝色打印\n", " print(\"\\033[1;34m\", \"-> 本地ToolCall结果: \\n\", tool_res, \"\\033[0m\\n\")\n", " tool_output.append(\n", " {\n", " \"tool_call_id\": tool_call_id,\n", " \"output\": tool_res\n", " }\n", " )\n", " return tool_output\n", " \n", " def success(self, run_context, run_response):\n", " print(\"\\n\\033[1;31m\",\"-> Agent 非流式回答: \\n\", run_response.answer, \"\\033[0m\")\n", "\n", " def running(self, run_context, run_response):\n", " print(\"\\n\\033[1;31m\",\"-> Agent 流式回答: \\n\", run_response.answer, \"\\033[0m\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "##### 定义本地的tools工具" ] }, { "cell_type": "code", "execution_count": 4, "metadata": {}, "outputs": [], "source": [ "tools = [\n", " {\n", " \"type\": \"function\",\n", " \"function\": {\n", " \"name\": \"execute_local_command\",\n", " \"description\": \"可以在bash环境中,执行输入的指令, 注意,一次只能执行一个完整的原子命令。并且下载文件使用curl命令,因为没有安装wget,例如:ls\",\n", " \"parameters\": {\n", " \"type\": \"object\",\n", " \"properties\": {\n", " \"cmd\": {\n", " \"type\": \"string\",\n", " \"description\": \"需要执行的指令\",\n", " },\n", " },\n", " \"required\": [\"cmd\"],\n", " },\n", " },\n", " }\n", "]" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "##### 运行Client实现实现链路的调用" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "with app_client.run_with_handler(\n", " conversation_id = conversation_id,\n", " query = \"请为我生成一张男生头像照片,并下载到本地\",\n", " tools = tools,\n", " event_handler = MyEventHandler(),\n", " ) as run:\n", " run.until_done()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "- Agent运行流程及输出\n", " \n", "![Agent运行流程及输出](https://bj.bcebos.com/v1/appbuilder-sdk-components/Agent%E8%BF%90%E8%A1%8C%E6%B5%81%E7%A8%8B.png?authorization=bce-auth-v1%2FALTAKGa8m4qCUasgoljdEDAzLm%2F2024-08-22T08%3A38%3A58Z%2F-1%2Fhost%2F25e5b0ac328376a048c919d16c8d6fab9044d09ea2bb4b8b7614b958bb40182f)\n", "\n", "- 查看下载至本地的图片\n", "\n", "![载至本地的图片](https://bj.bcebos.com/v1/appbuilder-sdk-components/boy_avatar.png?authorization=bce-auth-v1%2FALTAKGa8m4qCUasgoljdEDAzLm%2F2024-08-22T08%3A40%3A26Z%2F-1%2Fhost%2F5d6f2f482bc72b487f59f7bee18e68aacf0399b71210e11a16e99f59754c64c6)" ] } ], "metadata": { "kernelspec": { "display_name": "python-12", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.12.4" } }, "nbformat": 4, "nbformat_minor": 2 } ================================================ FILE: cookbooks/live_broadcast_material/2024_08_22/trace.ipynb ================================================ { "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# AppBuilder-Trace:更友好易用的可视化Debug方法\n", "\n", "在使用AppBuilder-SDK完成代码态开发可能会出现BUG,同时在运行Agent的过程中的黑盒问题,给Appbuilder的代码态使用带来了极大的不便。因此Appbuilder-SDK提供了DEBUG功能与Trace功能,帮助用户更友好、易用的调试代码。\n", "\n", "## DEBUG功能\n", "\n", "[DEBUG功能](https://github.com/baidubce/app-builder/blob/master/docs/quick_start/README.md#%E6%89%93%E5%8D%B0debug%E6%97%A5%E5%BF%97)\n", "\n", "- 开启DEBUG日志,可以打印出更多的日志信息,方便调试,包括且不限于:请求URL、请求头、请求参数等。\n", "\n", "### 打印DEBUG日志\n", "\n", "设置环境变量\n", "- 开启DEBUG:`export APPBUILDER_LOGLEVEL=DEBUG`\n", "- 关闭DEBUG:`export APPBUILDER_LOGLEVEL=INFO`\n", "\n", "- 也可以在代码中设置,优先级高于环境变量。\n", "\n", "```python\n", "# python\n", "appbuilder.logger.setLoglevel(\"DEBUG\")\n", "```\n", "```java\n", "//java\n", "System.setProperty(\"APPBUILDER_LOGLEVEL\", \"DEBUG\");\n", "```\n", "```go\n", "//golang\n", "os.Setenv(\"APPBUILDER_LOGLEVEL\", \"DEBUG\")\n", "```\n", "\n", "### 指定日志文件\n", "\n", "如果需要将日志输出到指定文件,方便落盘。默认输出为标准输出流。 可以设置环境变量APPBUILDER_LOGFILE,文件名及路径可以根据实际使用修改`export APPBUILDER_LOGFILE=/tmp/appbuilder.log`\n", "\n", "```python\n", "# python\n", "appbuilder.logger.setFilename(\"/tmp/appbuilder.log\")\n", "```\n", "```java\n", "//java\n", "System.setProperty(\"APPBUILDER_LOGLFILE\", \"/tmp/appbuilder.log\");\n", "```\n", "```golang\n", "// golang\n", "os.Setenv(\"APPBUILDER_LOGLEVEL\", \"/tmp/appbuilder.log\")\n", "```\n", "\n", "### DEBUG功能应用与正常运行状态\n", "\n", "- 我们将使用Appbuilder-SDK调用已创建好的Client应用进行测试\n", "\n", "示例中的应用为:说唱导师" ] }, { "cell_type": "code", "execution_count": 4, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[2024-08-21 20:29:34,682.682] _client.py [line:105] DEBUG [main-10719753420054307843] AppBuilder Secret key: Bearer your api key\n", "\n" ] }, { "name": "stderr", "output_type": "stream", "text": [ "DEBUG:appbuilder:AppBuilder Secret key: Bearer your api key\n", "\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "[2024-08-21 20:29:34,686.686] _client.py [line:207] DEBUG [main-10048254465741365719] Request header: {'X-Appbuilder-Sdk-Config': '{\"appbuilder_sdk_version\":\"0.9.3\",\"appbuilder_sdk_language\":\"python\",\"appbuilder_sdk_platform\":\"unknown\"}', 'X-Appbuilder-Origin': 'appbuilder_sdk', 'X-Appbuilder-Request-Id': '68ab95ac-c503-4616-a094-50739292c3c1', 'X-Bce-Request-Id': '68ab95ac-c503-4616-a094-50739292c3c1', 'Authorization': 'Bearer your api key'}\n", "\n" ] }, { "name": "stderr", "output_type": "stream", "text": [ "DEBUG:appbuilder:Request header: {'X-Appbuilder-Sdk-Config': '{\"appbuilder_sdk_version\":\"0.9.3\",\"appbuilder_sdk_language\":\"python\",\"appbuilder_sdk_platform\":\"unknown\"}', 'X-Appbuilder-Origin': 'appbuilder_sdk', 'X-Appbuilder-Request-Id': '68ab95ac-c503-4616-a094-50739292c3c1', 'X-Bce-Request-Id': '68ab95ac-c503-4616-a094-50739292c3c1', 'Authorization': 'Bearer your api key'}\n", "\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "[2024-08-21 20:29:34,687.687] _client.py [line:161] DEBUG [main-11077088795128889416] Service url: https://qianfan.baidubce.com/v2/app/conversation\n", "\n" ] }, { "name": "stderr", "output_type": "stream", "text": [ "DEBUG:appbuilder:Service url: https://qianfan.baidubce.com/v2/app/conversation\n", "\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "[2024-08-21 20:29:34,690.690] _session.py [line:57] DEBUG [main-9588862210139017928] Curl Command:\n", "curl -X POST -L 'https://qianfan.baidubce.com/v2/app/conversation' \\\n", "-H 'User-Agent: python-requests/2.32.3' \\\n", "-H 'Accept-Encoding: gzip, deflate' \\\n", "-H 'Accept: */*' \\\n", "-H 'Connection: keep-alive' \\\n", "-H 'X-Appbuilder-Sdk-Config: {\"appbuilder_sdk_version\":\"0.9.3\",\"appbuilder_sdk_language\":\"python\",\"appbuilder_sdk_platform\":\"unknown\"}' \\\n", "-H 'X-Appbuilder-Origin: appbuilder_sdk' \\\n", "-H 'X-Appbuilder-Request-Id: 68ab95ac-c503-4616-a094-50739292c3c1' \\\n", "-H 'X-Bce-Request-Id: 68ab95ac-c503-4616-a094-50739292c3c1' \\\n", "-H 'Authorization: Bearer your api key' \\\n", "-H 'Content-Type: application/json' \\\n", "-d '{\"app_id\": \"4678492a-5864-472e-810a-654538d3503c\"}'\n", "\n" ] }, { "name": "stderr", "output_type": "stream", "text": [ "DEBUG:appbuilder:Curl Command:\n", "curl -X POST -L 'https://qianfan.baidubce.com/v2/app/conversation' \\\n", "-H 'User-Agent: python-requests/2.32.3' \\\n", "-H 'Accept-Encoding: gzip, deflate' \\\n", "-H 'Accept: */*' \\\n", "-H 'Connection: keep-alive' \\\n", "-H 'X-Appbuilder-Sdk-Config: {\"appbuilder_sdk_version\":\"0.9.3\",\"appbuilder_sdk_language\":\"python\",\"appbuilder_sdk_platform\":\"unknown\"}' \\\n", "-H 'X-Appbuilder-Origin: appbuilder_sdk' \\\n", "-H 'X-Appbuilder-Request-Id: 68ab95ac-c503-4616-a094-50739292c3c1' \\\n", "-H 'X-Bce-Request-Id: 68ab95ac-c503-4616-a094-50739292c3c1' \\\n", "-H 'Authorization: Bearer your api key' \\\n", "-H 'Content-Type: application/json' \\\n", "-d '{\"app_id\": \"4678492a-5864-472e-810a-654538d3503c\"}'\n", "\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "[2024-08-21 20:29:35,116.116] _client.py [line:207] DEBUG [main-10660544649237524198] Request header: {'X-Appbuilder-Sdk-Config': '{\"appbuilder_sdk_version\":\"0.9.3\",\"appbuilder_sdk_language\":\"python\",\"appbuilder_sdk_platform\":\"unknown\"}', 'X-Appbuilder-Origin': 'appbuilder_sdk', 'X-Appbuilder-Request-Id': '4e643ef9-e6f8-4b16-87db-81cda2cbb8de', 'X-Bce-Request-Id': '4e643ef9-e6f8-4b16-87db-81cda2cbb8de', 'Authorization': 'Bearer your api key'}\n", "\n" ] }, { "name": "stderr", "output_type": "stream", "text": [ "DEBUG:appbuilder:Request header: {'X-Appbuilder-Sdk-Config': '{\"appbuilder_sdk_version\":\"0.9.3\",\"appbuilder_sdk_language\":\"python\",\"appbuilder_sdk_platform\":\"unknown\"}', 'X-Appbuilder-Origin': 'appbuilder_sdk', 'X-Appbuilder-Request-Id': '4e643ef9-e6f8-4b16-87db-81cda2cbb8de', 'X-Bce-Request-Id': '4e643ef9-e6f8-4b16-87db-81cda2cbb8de', 'Authorization': 'your api key'}\n", "\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "[2024-08-21 20:29:35,117.117] _client.py [line:161] DEBUG [main-11717755258005238516] Service url: https://qianfan.baidubce.com/v2/app/conversation/runs\n", "\n" ] }, { "name": "stderr", "output_type": "stream", "text": [ "DEBUG:appbuilder:Service url: https://qianfan.baidubce.com/v2/app/conversation/runs\n", "\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "[2024-08-21 20:29:35,119.119] _session.py [line:57] DEBUG [main-11593268707085638034] Curl Command:\n", "curl -X POST -L 'https://qianfan.baidubce.com/v2/app/conversation/runs' \\\n", "-H 'User-Agent: python-requests/2.32.3' \\\n", "-H 'Accept-Encoding: gzip, deflate' \\\n", "-H 'Accept: */*' \\\n", "-H 'Connection: keep-alive' \\\n", "-H 'X-Appbuilder-Sdk-Config: {\"appbuilder_sdk_version\":\"0.9.3\",\"appbuilder_sdk_language\":\"python\",\"appbuilder_sdk_platform\":\"unknown\"}' \\\n", "-H 'X-Appbuilder-Origin: appbuilder_sdk' \\\n", "-H 'X-Appbuilder-Request-Id: 4e643ef9-e6f8-4b16-87db-81cda2cbb8de' \\\n", "-H 'X-Bce-Request-Id: 4e643ef9-e6f8-4b16-87db-81cda2cbb8de' \\\n", "-H 'Authorization: Bearer your api key' \\\n", "-H 'Content-Type: application/json' \\\n", "-d '{\"query\": \"以“上班狼狈却又追逐梦想“为主题进行一首说唱创作,保持押韵, 控制在50字以内\", \"stream\": false, \"conversation_id\": \"f7cd419c-d78c-4fbf-8ed4-c0b93c411381\", \"file_ids\": [], \"app_id\": \"4678492a-5864-472e-810a-654538d3503c\", \"tools\": null, \"tool_outputs\": null}'\n", "\n" ] }, { "name": "stderr", "output_type": "stream", "text": [ "DEBUG:appbuilder:Curl Command:\n", "curl -X POST -L 'https://qianfan.baidubce.com/v2/app/conversation/runs' \\\n", "-H 'User-Agent: python-requests/2.32.3' \\\n", "-H 'Accept-Encoding: gzip, deflate' \\\n", "-H 'Accept: */*' \\\n", "-H 'Connection: keep-alive' \\\n", "-H 'X-Appbuilder-Sdk-Config: {\"appbuilder_sdk_version\":\"0.9.3\",\"appbuilder_sdk_language\":\"python\",\"appbuilder_sdk_platform\":\"unknown\"}' \\\n", "-H 'X-Appbuilder-Origin: appbuilder_sdk' \\\n", "-H 'X-Appbuilder-Request-Id: 4e643ef9-e6f8-4b16-87db-81cda2cbb8de' \\\n", "-H 'X-Bce-Request-Id: 4e643ef9-e6f8-4b16-87db-81cda2cbb8de' \\\n", "-H 'Authorization: Bearer your api key' \\\n", "-H 'Content-Type: application/json' \\\n", "-d '{\"query\": \"以“上班狼狈却又追逐梦想“为主题进行一首说唱创作,保持押韵, 控制在50字以内\", \"stream\": false, \"conversation_id\": \"f7cd419c-d78c-4fbf-8ed4-c0b93c411381\", \"file_ids\": [], \"app_id\": \"4678492a-5864-472e-810a-654538d3503c\", \"tools\": null, \"tool_outputs\": null}'\n", "\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "上班路上忙追赶,狼狈模样也心甘。\n", "梦想照亮前方路,不畏艰辛往前看。\n", "脚步匆匆人憔悴,只为梦想能成真。\n", "努力奋斗不言弃,终有一天会翻身。\n", "\n", "这首简短的说唱以“上班狼狈却又追逐梦想”为主题,表达了追梦路上的艰辛与坚持,希望你喜欢。\n" ] } ], "source": [ "import appbuilder\n", "import os\n", "\n", "appbuilder.logger.setLoglevel(\"DEBUG\")\n", "# 设置环境中的TOKEN,请替换为您的个人TOKEN\n", "os.environ[\"APPBUILDER_TOKEN\"] = \"your api key\"\n", "\n", "# 从AppBuilder网页获取并传入应用ID,以下为说唱导师应用ID\n", "app_id = \"4678492a-5864-472e-810a-654538d3503c\"\n", "\n", "app_builder_client = appbuilder.AppBuilderClient(app_id)\n", "conversation_id = app_builder_client.create_conversation()\n", "\n", "answer = app_builder_client.run(conversation_id, \"以“上班狼狈却又追逐梦想“为主题进行一首说唱创作,保持押韵, 控制在50字以内\")\n", "print(answer.content.answer)\n", "\n", "appbuilder.logger.setLoglevel(\"INFO\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "我们可以看到DEBUG模式会截获并在控制台输出相应的运行节点信息,同时可以生成curl,辅助开发者实现请求复现\n", "\n", "## Trace功能\n", "\n", "[Trace功能](https://github.com/baidubce/app-builder/blob/master/docs/trace/README.md)\n", "\n", "### Trace环境的安装与启动\n", "\n", "Appbuilder-SDK的可视化跟踪前端基于Phoenix可视化软件如果未安装phoenix,需要先安装phoenix软件(这里提供清华源下载途径)\n", "\n", "#### Trace环境的安装\n", "\n", "```bash\n", "python3 -m pip install arize-phoenix==4.5.0 -i https://pypi.tuna.tsinghua.edu.cn/simple\n", "```" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "!python3 -m pip install arize-phoenix==4.5.0 -i https://pypi.tuna.tsinghua.edu.cn/simple" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### 启动phoenix服务\n", "\n", "控制台输入:`appbuilder_trace_server`,即可启动phoenix可视化软件,点击 http://localhost:8080/ 即可打开可视化界面\n", "\n", "- 要求 `appbuilder-sdk >= 0.9.1`\n", "\n", "### Trace框架功能展示\n", "\n", "Trace框架现阶段支持两种Trace信息展示方式\n", "\n", "- Phoenix可视化展示Trace到的Span信息\n", " - `enable_phoenix = True`\n", "- 控制台输出Trace到的Span信息\n", " - `enable_console = True`\n", "\n", "接下来流式运行Client应用,查看Phoenix效果" ] }, { "cell_type": "code", "execution_count": 5, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[2024-08-21 20:30:10,683.683] tracer.py [line:293] INFO [main-11990101290407320544] OTLPSpanExporter endpoint: http://localhost:8080/v1/traces\n" ] }, { "name": "stderr", "output_type": "stream", "text": [ "INFO:appbuilder:OTLPSpanExporter endpoint: http://localhost:8080/v1/traces\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "[2024-08-21 20:30:10,684.684] tracer.py [line:351] INFO [main-10829791027654713596] AppBuilder Starting trace...\n" ] }, { "name": "stderr", "output_type": "stream", "text": [ "INFO:appbuilder:AppBuilder Starting trace...\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "answer='' events=[Event(code=0, message='', status='done', event_type='function_call', content_type='function_call', detail={'text': {'arguments': {'origin_query': '以“上班狼狈却又追逐梦想“为主题进行一首说唱创作,保持押韵, 控制在50字以内'}, 'component_code': 'ChatAgent', 'component_name': '聊天助手'}}, usage=None, tool_calls=None)]\n", "answer='' events=[Event(code=0, message='', status='preparing', event_type='ChatAgent', content_type='status', detail={}, usage=None, tool_calls=None)]\n", "answer='Intro:' events=[Event(code=0, message='', status='running', event_type='ChatAgent', content_type='text', detail={'text': 'Intro:'}, usage=Usage(prompt_tokens=398, completion_tokens=0, total_tokens=398, name='DeepSeek-V3.1-Preview'), tool_calls=None)]\n", "answer='\\n追逐' events=[Event(code=0, message='', status='running', event_type='ChatAgent', content_type='text', detail={'text': '\\n追逐'}, usage=Usage(prompt_tokens=398, completion_tokens=0, total_tokens=398, name='DeepSeek-V3.1-Preview'), tool_calls=None)]\n", "answer='梦想的路上' events=[Event(code=0, message='', status='running', event_type='ChatAgent', content_type='text', detail={'text': '梦想的路上'}, usage=Usage(prompt_tokens=398, completion_tokens=0, total_tokens=398, name='DeepSeek-V3.1-Preview'), tool_calls=None)]\n", "answer=',上班' events=[Event(code=0, message='', status='running', event_type='ChatAgent', content_type='text', detail={'text': ',上班'}, usage=Usage(prompt_tokens=398, completion_tokens=0, total_tokens=398, name='DeepSeek-V3.1-Preview'), tool_calls=None)]\n", "answer='狼狈不' events=[Event(code=0, message='', status='running', event_type='ChatAgent', content_type='text', detail={'text': '狼狈不'}, usage=Usage(prompt_tokens=398, completion_tokens=0, total_tokens=398, name='DeepSeek-V3.1-Preview'), tool_calls=None)]\n", "answer='慌张。' events=[Event(code=0, message='', status='running', event_type='ChatAgent', content_type='text', detail={'text': '慌张。'}, usage=Usage(prompt_tokens=398, completion_tokens=0, total_tokens=398, name='DeepSeek-V3.1-Preview'), tool_calls=None)]\n", "answer='\\n\\n' events=[Event(code=0, message='', status='running', event_type='ChatAgent', content_type='text', detail={'text': '\\n\\n'}, usage=Usage(prompt_tokens=398, completion_tokens=16, total_tokens=414, name='DeepSeek-V3.1-Preview'), tool_calls=None)]\n", "answer='Verse:' events=[Event(code=0, message='', status='running', event_type='ChatAgent', content_type='text', detail={'text': 'Verse:'}, usage=Usage(prompt_tokens=398, completion_tokens=16, total_tokens=414, name='DeepSeek-V3.1-Preview'), tool_calls=None)]\n", "answer='\\n朝九晚' events=[Event(code=0, message='', status='running', event_type='ChatAgent', content_type='text', detail={'text': '\\n朝九晚'}, usage=Usage(prompt_tokens=398, completion_tokens=16, total_tokens=414, name='DeepSeek-V3.1-Preview'), tool_calls=None)]\n", "answer='五忙' events=[Event(code=0, message='', status='running', event_type='ChatAgent', content_type='text', detail={'text': '五忙'}, usage=Usage(prompt_tokens=398, completion_tokens=16, total_tokens=414, name='DeepSeek-V3.1-Preview'), tool_calls=None)]\n", "answer='又忙' events=[Event(code=0, message='', status='running', event_type='ChatAgent', content_type='text', detail={'text': '又忙'}, usage=Usage(prompt_tokens=398, completion_tokens=16, total_tokens=414, name='DeepSeek-V3.1-Preview'), tool_calls=None)]\n", "answer=',为了' events=[Event(code=0, message='', status='running', event_type='ChatAgent', content_type='text', detail={'text': ',为了'}, usage=Usage(prompt_tokens=398, completion_tokens=16, total_tokens=414, name='DeepSeek-V3.1-Preview'), tool_calls=None)]\n", "answer='生活奔波' events=[Event(code=0, message='', status='running', event_type='ChatAgent', content_type='text', detail={'text': '生活奔波'}, usage=Usage(prompt_tokens=398, completion_tokens=16, total_tokens=414, name='DeepSeek-V3.1-Preview'), tool_calls=None)]\n", "answer='忙。' events=[Event(code=0, message='', status='running', event_type='ChatAgent', content_type='text', detail={'text': '忙。'}, usage=Usage(prompt_tokens=398, completion_tokens=30, total_tokens=428, name='DeepSeek-V3.1-Preview'), tool_calls=None)]\n", "answer='\\n心中' events=[Event(code=0, message='', status='running', event_type='ChatAgent', content_type='text', detail={'text': '\\n心中'}, usage=Usage(prompt_tokens=398, completion_tokens=30, total_tokens=428, name='DeepSeek-V3.1-Preview'), tool_calls=None)]\n", "answer='却有梦想' events=[Event(code=0, message='', status='running', event_type='ChatAgent', content_type='text', detail={'text': '却有梦想'}, usage=Usage(prompt_tokens=398, completion_tokens=30, total_tokens=428, name='DeepSeek-V3.1-Preview'), tool_calls=None)]\n", "answer='在,' events=[Event(code=0, message='', status='running', event_type='ChatAgent', content_type='text', detail={'text': '在,'}, usage=Usage(prompt_tokens=398, completion_tokens=30, total_tokens=428, name='DeepSeek-V3.1-Preview'), tool_calls=None)]\n", "answer='不曾放弃' events=[Event(code=0, message='', status='running', event_type='ChatAgent', content_type='text', detail={'text': '不曾放弃'}, usage=Usage(prompt_tokens=398, completion_tokens=30, total_tokens=428, name='DeepSeek-V3.1-Preview'), tool_calls=None)]\n", "answer='追逐航' events=[Event(code=0, message='', status='running', event_type='ChatAgent', content_type='text', detail={'text': '追逐航'}, usage=Usage(prompt_tokens=398, completion_tokens=30, total_tokens=428, name='DeepSeek-V3.1-Preview'), tool_calls=None)]\n", "answer='。\\n' events=[Event(code=0, message='', status='running', event_type='ChatAgent', content_type='text', detail={'text': '。\\n'}, usage=Usage(prompt_tokens=398, completion_tokens=30, total_tokens=428, name='DeepSeek-V3.1-Preview'), tool_calls=None)]\n", "answer='\\nHook' events=[Event(code=0, message='', status='running', event_type='ChatAgent', content_type='text', detail={'text': '\\nHook'}, usage=Usage(prompt_tokens=398, completion_tokens=30, total_tokens=428, name='DeepSeek-V3.1-Preview'), tool_calls=None)]\n", "answer=':\\n' events=[Event(code=0, message='', status='running', event_type='ChatAgent', content_type='text', detail={'text': ':\\n'}, usage=Usage(prompt_tokens=398, completion_tokens=30, total_tokens=428, name='DeepSeek-V3.1-Preview'), tool_calls=None)]\n", "answer='梦想照亮' events=[Event(code=0, message='', status='running', event_type='ChatAgent', content_type='text', detail={'text': '梦想照亮'}, usage=Usage(prompt_tokens=398, completion_tokens=30, total_tokens=428, name='DeepSeek-V3.1-Preview'), tool_calls=None)]\n", "answer='前方路' events=[Event(code=0, message='', status='running', event_type='ChatAgent', content_type='text', detail={'text': '前方路'}, usage=Usage(prompt_tokens=398, completion_tokens=30, total_tokens=428, name='DeepSeek-V3.1-Preview'), tool_calls=None)]\n", "answer=',坚持' events=[Event(code=0, message='', status='running', event_type='ChatAgent', content_type='text', detail={'text': ',坚持'}, usage=Usage(prompt_tokens=398, completion_tokens=30, total_tokens=428, name='DeepSeek-V3.1-Preview'), tool_calls=None)]\n", "answer='信念不' events=[Event(code=0, message='', status='running', event_type='ChatAgent', content_type='text', detail={'text': '信念不'}, usage=Usage(prompt_tokens=398, completion_tokens=30, total_tokens=428, name='DeepSeek-V3.1-Preview'), tool_calls=None)]\n", "answer='认输。' events=[Event(code=0, message='', status='running', event_type='ChatAgent', content_type='text', detail={'text': '认输。'}, usage=Usage(prompt_tokens=398, completion_tokens=30, total_tokens=428, name='DeepSeek-V3.1-Preview'), tool_calls=None)]\n", "answer='\\n哪怕' events=[Event(code=0, message='', status='running', event_type='ChatAgent', content_type='text', detail={'text': '\\n哪怕'}, usage=Usage(prompt_tokens=398, completion_tokens=58, total_tokens=456, name='DeepSeek-V3.1-Preview'), tool_calls=None)]\n", "answer='上班再' events=[Event(code=0, message='', status='running', event_type='ChatAgent', content_type='text', detail={'text': '上班再'}, usage=Usage(prompt_tokens=398, completion_tokens=58, total_tokens=456, name='DeepSeek-V3.1-Preview'), tool_calls=None)]\n", "answer='狼狈,' events=[Event(code=0, message='', status='running', event_type='ChatAgent', content_type='text', detail={'text': '狼狈,'}, usage=Usage(prompt_tokens=398, completion_tokens=58, total_tokens=456, name='DeepSeek-V3.1-Preview'), tool_calls=None)]\n", "answer='也要勇敢' events=[Event(code=0, message='', status='running', event_type='ChatAgent', content_type='text', detail={'text': '也要勇敢'}, usage=Usage(prompt_tokens=398, completion_tokens=58, total_tokens=456, name='DeepSeek-V3.1-Preview'), tool_calls=None)]\n", "answer='追梦想' events=[Event(code=0, message='', status='running', event_type='ChatAgent', content_type='text', detail={'text': '追梦想'}, usage=Usage(prompt_tokens=398, completion_tokens=58, total_tokens=456, name='DeepSeek-V3.1-Preview'), tool_calls=None)]\n", "answer='。\\n' events=[Event(code=0, message='', status='running', event_type='ChatAgent', content_type='text', detail={'text': '。\\n'}, usage=Usage(prompt_tokens=398, completion_tokens=58, total_tokens=456, name='DeepSeek-V3.1-Preview'), tool_calls=None)]\n", "answer='\\n这首' events=[Event(code=0, message='', status='running', event_type='ChatAgent', content_type='text', detail={'text': '\\n这首'}, usage=Usage(prompt_tokens=398, completion_tokens=73, total_tokens=471, name='DeepSeek-V3.1-Preview'), tool_calls=None)]\n", "answer='简短的' events=[Event(code=0, message='', status='running', event_type='ChatAgent', content_type='text', detail={'text': '简短的'}, usage=Usage(prompt_tokens=398, completion_tokens=73, total_tokens=471, name='DeepSeek-V3.1-Preview'), tool_calls=None)]\n", "answer='rap以' events=[Event(code=0, message='', status='running', event_type='ChatAgent', content_type='text', detail={'text': 'rap以'}, usage=Usage(prompt_tokens=398, completion_tokens=73, total_tokens=471, name='DeepSeek-V3.1-Preview'), tool_calls=None)]\n", "answer='“上班' events=[Event(code=0, message='', status='running', event_type='ChatAgent', content_type='text', detail={'text': '“上班'}, usage=Usage(prompt_tokens=398, completion_tokens=79, total_tokens=477, name='DeepSeek-V3.1-Preview'), tool_calls=None)]\n", "answer='狼狈却又' events=[Event(code=0, message='', status='running', event_type='ChatAgent', content_type='text', detail={'text': '狼狈却又'}, usage=Usage(prompt_tokens=398, completion_tokens=79, total_tokens=477, name='DeepSeek-V3.1-Preview'), tool_calls=None)]\n", "answer='追逐梦想”' events=[Event(code=0, message='', status='running', event_type='ChatAgent', content_type='text', detail={'text': '追逐梦想”'}, usage=Usage(prompt_tokens=398, completion_tokens=79, total_tokens=477, name='DeepSeek-V3.1-Preview'), tool_calls=None)]\n", "answer='为主题,' events=[Event(code=0, message='', status='running', event_type='ChatAgent', content_type='text', detail={'text': '为主题,'}, usage=Usage(prompt_tokens=398, completion_tokens=88, total_tokens=486, name='DeepSeek-V3.1-Preview'), tool_calls=None)]\n", "answer='通过押韵' events=[Event(code=0, message='', status='running', event_type='ChatAgent', content_type='text', detail={'text': '通过押韵'}, usage=Usage(prompt_tokens=398, completion_tokens=88, total_tokens=486, name='DeepSeek-V3.1-Preview'), tool_calls=None)]\n", "answer='的方式表达了' events=[Event(code=0, message='', status='running', event_type='ChatAgent', content_type='text', detail={'text': '的方式表达了'}, usage=Usage(prompt_tokens=398, completion_tokens=88, total_tokens=486, name='DeepSeek-V3.1-Preview'), tool_calls=None)]\n", "answer='即使生活' events=[Event(code=0, message='', status='running', event_type='ChatAgent', content_type='text', detail={'text': '即使生活'}, usage=Usage(prompt_tokens=398, completion_tokens=88, total_tokens=486, name='DeepSeek-V3.1-Preview'), tool_calls=None)]\n", "answer='艰辛,' events=[Event(code=0, message='', status='running', event_type='ChatAgent', content_type='text', detail={'text': '艰辛,'}, usage=Usage(prompt_tokens=398, completion_tokens=88, total_tokens=486, name='DeepSeek-V3.1-Preview'), tool_calls=None)]\n", "answer='也要坚持' events=[Event(code=0, message='', status='running', event_type='ChatAgent', content_type='text', detail={'text': '也要坚持'}, usage=Usage(prompt_tokens=398, completion_tokens=88, total_tokens=486, name='DeepSeek-V3.1-Preview'), tool_calls=None)]\n", "answer='追逐梦想的' events=[Event(code=0, message='', status='running', event_type='ChatAgent', content_type='text', detail={'text': '追逐梦想的'}, usage=Usage(prompt_tokens=398, completion_tokens=88, total_tokens=486, name='DeepSeek-V3.1-Preview'), tool_calls=None)]\n", "answer='决心。' events=[Event(code=0, message='', status='running', event_type='ChatAgent', content_type='text', detail={'text': '决心。'}, usage=Usage(prompt_tokens=398, completion_tokens=88, total_tokens=486, name='DeepSeek-V3.1-Preview'), tool_calls=None)]\n", "answer='希望你喜欢' events=[Event(code=0, message='', status='running', event_type='ChatAgent', content_type='text', detail={'text': '希望你喜欢'}, usage=Usage(prompt_tokens=398, completion_tokens=88, total_tokens=486, name='DeepSeek-V3.1-Preview'), tool_calls=None)]\n", "answer='!' events=[Event(code=0, message='', status='done', event_type='ChatAgent', content_type='text', detail={'text': '!'}, usage=Usage(prompt_tokens=398, completion_tokens=105, total_tokens=503, name='DeepSeek-V3.1-Preview'), tool_calls=None)]\n", "answer='' events=[Event(code=0, message='', status='success', event_type='ChatAgent', content_type='status', detail={}, usage=None, tool_calls=None)]\n", "answer='' events=[]\n", "[2024-08-21 20:30:19,396.396] tracer.py [line:355] INFO [main-11328972138384597399] AppBuilder Ending trace...\n" ] }, { "name": "stderr", "output_type": "stream", "text": [ "INFO:appbuilder:AppBuilder Ending trace...\n" ] } ], "source": [ "# 启动Appbuilder-SDK TRACE\n", "from appbuilder import AppBuilderTracer\n", "tracer=AppBuilderTracer(\n", " enable_phoenix = True,\n", " enable_console = False,\n", " )\n", "\n", "\n", "import appbuilder\n", "import os\n", "\n", "# 启动跟踪器\n", "tracer.start_trace()\n", "\n", "# 设置环境中的TOKEN,替换为您的个人TOKEN\n", "os.environ[\"APPBUILDER_TOKEN\"] = \"your api key\"\n", "\n", "# 从AppBuilder网页获取并传入应用ID,以下为说唱导师应用ID\n", "app_id = \"4678492a-5864-472e-810a-654538d3503c\"\n", "\n", "app_builder_client = appbuilder.AppBuilderClient(app_id)\n", "conversation_id = app_builder_client.create_conversation()\n", "\n", "answer = app_builder_client.run(conversation_id, \"以“上班狼狈却又追逐梦想“为主题进行一首说唱创作,保持押韵, 控制在50字以内\",stream = True)\n", "\n", "# 流式输出res\n", "for res in answer.content:\n", " print(res)\n", "\n", "\n", "# 结束跟踪器\n", "tracer.end_trace()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "- 控制台输出跟踪到的Span节点信息\n", "- 可以在可视化界面查看跟踪信息如Client组件的调用链路,输入输出、消耗token数等信息\n", "- 点击某个调用链路,可以查看该调用链路详细信息,流式运行过程,HTTP-POST节点展示curl命令\n", "\n", "![Phoenix可视化界面展示](https://bj.bcebos.com/v1/appbuilder-sdk-components/cookbook-phoenix.png?authorization=bce-auth-v1%2FALTAKGa8m4qCUasgoljdEDAzLm%2F2024-08-21T07%3A36%3A31Z%2F-1%2Fhost%2Fd005f6e23bfc3f7439e0701baf497d1ff7afbd050343c650392569d83baa5ec6)\n", "\n", "\n", "### Phoneix可视化软件的进阶用法\n", "\n", "#### 1. 选择可视化展示的选项\n", "\n", "- 点击Columns,选择需要可视化展示的字段\n", "\n", "![选择可视化展示的选项](https://bj.bcebos.com/v1/appbuilder-sdk-components/%E4%BF%AE%E6%94%B9phoenix%E5%B1%95%E7%A4%BA%E5%8F%82%E6%95%B0.png?authorization=bce-auth-v1%2FALTAKGa8m4qCUasgoljdEDAzLm%2F2024-07-22T03%3A35%3A17Z%2F-1%2Fhost%2Ff9ff13fb2243ebbf1dd66008977a46def85aec56af5256be3f141fd36b6194c9)\n", "\n", "\n", "#### 2. 查看节点关键信息 \n", "\n", "- 点击需要查看的节点,查看节点关键信息,Info将展示input、ouput信息\n", "\n", "![查看节点关键信息 ](https://bj.bcebos.com/v1/appbuilder-sdk-components/Phoenix%E5%8F%AF%E8%A7%86%E5%8C%96%E7%95%8C%E9%9D%A2%EF%BC%883%EF%BC%89.png?authorization=bce-auth-v1%2FALTAKGa8m4qCUasgoljdEDAzLm%2F2024-07-22T03%3A36%3A11Z%2F-1%2Fhost%2Ffc471ccb9ecbc05eebf41f965e6df52132219f96bf688a46e6b6fa61f598088e)\n", "\n", "#### 3. 搜索目标节点 \n", "\n", "##### 依据节点类型搜索\n", "\n", "- 点击搜索框,输入节点类型,搜索目标节点(eg: span_kind == 'AGENT')\n", "- 在Traces界面,只能检索到根节点、在Spans界面,可以检索到所有节点\n", "\n", "![依据节点类型搜索](https://bj.bcebos.com/v1/appbuilder-sdk-components/span_kind_find.png?authorization=bce-auth-v1%2FALTAKGa8m4qCUasgoljdEDAzLm%2F2024-07-22T04%3A39%3A04Z%2F-1%2Fhost%2F5bb320731860407968af9693c43c5639611776d760769d29077bcb2e968b05d1)\n", "\n", "##### 依据节点信息检索\n", "\n", "- 依据节点信息检索可快速定位到目标节点\n", "\n", "![依据节点信息检索](https://bj.bcebos.com/v1/appbuilder-sdk-components/span_value_find.png?authorization=bce-auth-v1%2FALTAKGa8m4qCUasgoljdEDAzLm%2F2024-07-22T04%3A39%3A20Z%2F-1%2Fhost%2F43b20f9894586405e65195ebf6f86c21193812ab9ffd59f93287266e1a83ab03)\n", "\n", "##### 其他多种检索方式\n", "\n", "![其他多种检索方式](https://bj.bcebos.com/v1/appbuilder-sdk-components/every_span_find.png?authorization=bce-auth-v1%2FALTAKGa8m4qCUasgoljdEDAzLm%2F2024-07-22T04%3A39%3A35Z%2F-1%2Fhost%2Fa9b2dcf361416cf9a3727fc64d86bb370a5f24fc25286c53be15c5ecfd44e7e0)\n", "\n", "### Trace服务独立部署\n", "\n", "Phonenix可视化界面不但支持本地部署,还支持远程服务器部署\n", "\n", "#### 远程服务器启动Phoenix\n", "\n", "- 远程服务器部署Phoenix,需要提前安装好Docker环境\n", "运行`appbuilder_trace_server`命令,启动Phoenix服务\n", "\n", "- 本地运行Appbuilder Trace功能需要对`AppBuilderTracer`实例化时的参数进行修改,即可实现将Appbuilder-SDK的Trace信息发送到远程服务器\n", "\n", "```python\n", "from appbuilder import AppBuilderTracer\n", "tracer=AppBuilderTracer(\n", " enable_phoenix = True,\n", " enable_console = True,\n", " host = \"远程服务器的IP地址\",\n", " port = 8080,\n", " )\n", "```" ] } ], "metadata": { "kernelspec": { "display_name": "python-10", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.12.4" } }, "nbformat": 4, "nbformat_minor": 2 } ================================================ FILE: cookbooks/live_broadcast_material/2024_12_18/rag_knowledgebase_01.ipynb ================================================ { "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# AppBuilder-Knowledge:生产环境的知识库/文档/切片管理教学\n", "\n", "[知识库组件](https://github.com/baidubce/app-builder/blob/master/docs/BasisModule/Platform/KnowledgeBase/knowledgebase.md)\n", "\n", "知识库组件(KnowledgeBase)是对线上知识库操作的组件,可以通过SDK实现创建知识库、添加知识文档、查询知识库文档、删除知识文档等操作,可在平台console中查看结果。对console端知识库进行操作,可以通过SDK实现创建知识库、添加知识文档、查询知识库文档、删除知识文档等操作,可在平台console中查看结果\n", "\n", "## 1. 创建Agent应用\n", "\n", "### 1.1 平台Console创建Agent应用\n", "\n", "- 创建空应用并发布\n", "\n", "![](https://bj.bcebos.com/v1/appbuilder-sdk-components/console%E5%88%9B%E5%BB%BA%E6%B0%91%E6%B3%95%E5%85%B8.png?authorization=bce-auth-v1%2FALTAKGa8m4qCUasgoljdEDAzLm%2F2024-12-17T07%3A38%3A28Z%2F-1%2Fhost%2Ff497d9db3d8945859043fe24fcca4490c3e93a27042e42abc280d0fea7fd3305)\n", "\n", "### 1.2 使用SDK调用创建的民法典智能问答Agent\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "民法典第二编第一章的内容是关于物权编通则的一般规定,主要包括以下几个方面:\n", "\n", "### 一、物权编的调整范围\n", "\n", "* **第二百零五条**:本编调整因物的归属和利用产生的民事关系。\n", "\n", "### 二、国家基本经济制度\n", "\n", "* **第二百零六条**:国家坚持和完善公有制为主体、多种所有制经济共同发展,按劳分配为主体、多种分配方式并存,社会主义市场经济体制等社会主义基本经济制度。国家巩固和发展公有制经济,鼓励、支持和引导非公有制经济的发展。国家实行社会主义市场经济,保障一切市场主体的平等法律地位和发展权利。\n", "\n", "### 三、物权保护原则\n", "\n", "* **第二百零七条**:国家、集体、私人的物权和其他权利人的物权受法律平等保护,任何组织或者个人不得侵犯。\n", "\n", "### 四、物权设立、变更、转让和消灭的基本原则\n", "\n", "* **第二百零八条**:不动产物权的设立、变更、转让和消灭,应当依照法律规定登记。动产物权的设立和转让,应当依照法律规定交付。\n", "\n", "### 五、其他规定\n", "\n", "民法典第二编第一章还包含了一些其他与物权相关的一般性规定,这些规定为物权编后续章节的具体内容提供了基础和指导。\n", "\n", "综上所述,民法典第二编第一章作为物权编通则的一般规定,明确了物权编的调整范围、国家基本经济制度、物权保护原则以及物权设立、变更、转让和消灭的基本原则,为后续章节的具体规定提供了基础和指导。\n" ] } ], "source": [ "import appbuilder\n", "import os\n", "\n", "# 更换为自己的Appbuilder-token\n", "os.environ[\"APPBUILDER_TOKEN\"] = \"\"\n", "\n", "# 更换为自己的App ID\n", "app_id = \"\"\n", "client = appbuilder.AppBuilderClient(app_id)\n", "conversation_id = client.create_conversation()\n", "message = client.run(conversation_id, \"请输出民法典第二编第一章的内容\")\n", "# 打印对话结果\n", "print(message.content.answer)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "![](https://bj.bcebos.com/v1/appbuilder-sdk-components/%E6%B0%91%E6%B3%95%E5%85%B8%E7%AC%AC%E4%BA%8C%E7%BC%96%E7%AC%AC%E4%B8%80%E7%AB%A0%E4%B8%80%E8%88%AC%E8%A7%84%E5%AE%9A.png?authorization=bce-auth-v1%2FALTAKGa8m4qCUasgoljdEDAzLm%2F2024-12-17T08%3A10%3A14Z%2F-1%2Fhost%2F7852a4156383383e6190435f76b6709409def221e3835369f7d155d3c9dd438a)\n", "\n", "我们可以观察到上述Agent基本回答除了对于民法典的第二编第一章一般规定的内容,但是对照上图中的内容不够准确,这说明LLM在运行中出现了一定程度的幻觉,所以我们需要使用RAG(KnowledgeBase)对Agent进行优化。\n", "\n", "## 2. RAG(KnowledgeBase)\n", "\n", "Appbuilder中支持多种实现创建知识库、添加知识文档、查询知识库文档、删除知识文档等操作方式,包括:\n", "- 平台Console实现知识库操作\n", "- 使用SDK/API代码态实现知识库操作\n", "这里我们选择使用代码态SDK实现知识库的操作\n", "\n", "### 2.1 创建知识库\n", "\n", "首先我们需要创建知识库,这里我们使用SDK代码态实现知识库的创建" ] }, { "cell_type": "code", "execution_count": 80, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "知识库ID: 6ac10164-e80a-4497-ae9f-06ac35f38b97\n" ] } ], "source": [ "knowledge = appbuilder.KnowledgeBase()\n", "resp = knowledge.create_knowledge_base(\n", " name=\"中华人民共和国民法典\",\n", " description=\"中华人民共和国民法典的中文版\",\n", " type=\"public\",\n", " )\n", "my_knowledge_base_id = resp.id # 传入知识库ID\n", "my_knowledge = appbuilder.KnowledgeBase(my_knowledge_base_id)\n", "print(\"知识库ID: \", my_knowledge.knowledge_id)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "- 我们可以到平台Console中查看知识库是否创建成功,我们可以观察到知识库的名称和ID,知识库创建成功!\n", "\n", "![](https://bj.bcebos.com/v1/appbuilder-sdk-components/%E6%9F%A5%E7%9C%8B%E7%9F%A5%E8%AF%86%E5%BA%93%E6%B0%91%E6%B3%95%E5%85%B8.png?authorization=bce-auth-v1%2FALTAKGa8m4qCUasgoljdEDAzLm%2F2024-12-17T08%3A37%3A16Z%2F-1%2Fhost%2F40c0d55c6d01d538853bf3b8167c9c5271d74083a20afd5d17590986b44eb954)\n", "\n", "\n", "### 2.2 上传文档到知识库\n", "\n", "上传文档到知识库共有以下三种方式:\n", "- 上传文档到知识库\n", "- 上传通用文档\n", "\n", "##### 2.2.1 上传文档到知识库\n", "- 主要提供自定义文档处理策略,向知识库添加文档\n", " - 文档格式:rawText (允许配置后续分割策略)\n", " - 文档处理策略\n", "\n", "```python\n", "knowledge_base_id = my_knowledge.knowledge_id\n", "knowledge.create_documents(\n", "\tid=knowledge_base_id,\n", "\tcontentFormat=\"rawText\",\n", "\tsource=appbuilder.DocumentSource(\n", "\t\ttype=\"web\",\n", "\t\turls=[\"网页版的文档链接地址\"],\n", "\t\turlDepth=1,\n", "\t),\n", "\tprocessOption=appbuilder.DocumentProcessOption(\n", "\t\ttemplate=\"custom\",\n", "\t\tparser=appbuilder.DocumentChoices(\n", "\t\t\tchoices=[\"layoutAnalysis\", \"ocr\"]\n", "\t\t),\n", "\t\tchunker=appbuilder.DocumentChunker(\n", "\t\t\tchoices=[\"separator\"],\n", "\t\t\tseparator=appbuilder.DocumentSeparator(\n", "\t\t\t\tseparators=[\"。\"],\n", "\t\t\t\ttargetLength=300,\n", "\t\t\t\toverlapRate=0.25,\n", "\t\t\t),\n", "\t\t\tprependInfo=[\"title\", \"filename\"],\n", "\t\t),\n", "\t\tknowledgeAugmentation=appbuilder.DocumentChoices(choices=[\"faq\"]),\n", "\t),\n", ")\n", "```\n", "\n", "#### 2.2.2 上传通用文档\n", "- SDK支持基于代码态的文档上传方法`upload_file`,以及包含文档的自定义切分逻辑的向知识库添加文档的方法``add_document`\n", "- 需要先将文档下载至本地\n", "\n", "#### 采用上传通用文档的方案上传文档到知识库\n", "- 下面将提供一个缺少第七编第十章的民法典txt文件,同时使用SDK将其上传到知识库中,首先下载我们储存到云端的txt文件。" ] }, { "cell_type": "code", "execution_count": 81, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "文件已成功下载到 mingfadian.txt\n" ] } ], "source": [ "# 下载云端民法典到本地\n", "import requests\n", "\n", "def download_file(url, local_filename):\n", " try:\n", " response = requests.get(url, stream=True)\n", " with open(local_filename, 'wb') as f:\n", " for chunk in response.iter_content(chunk_size=8192):\n", " f.write(chunk)\n", "\n", " print(f\"文件已成功下载到 {local_filename}\")\n", " except requests.RequestException as e:\n", " print(f\"下载文件时发生错误: {e}\")\n", "\n", "# 使用示例\n", "url = 'https://bj.bcebos.com/v1/appbuilder-sdk-components/mingfadian.txt?authorization=bce-auth-v1\\\n", "%2FALTAKGa8m4qCUasgoljdEDAzLm%2F2024-12-17T10%3A44%3A33Z%2F-1%2Fhost%2Fb97e44abe836f58de9632c374d4055c391a84f7998562493c22fdff8596cdf49'\n", "local_filename = 'mingfadian.txt' \n", "download_file(url, local_filename)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "- 接下来我们将下载好的mingfadian.txt文件使用SDK上传到Appbuilder的知识库中,使用`appbuilder.CustomProcessRule`设置文档的切分规则。" ] }, { "cell_type": "code", "execution_count": 83, "metadata": {}, "outputs": [], "source": [ "upload_res = knowledge.upload_file(local_filename)\n", "add_res = knowledge.add_document(\n", " content_type=\"raw_text\",\n", " file_ids=[upload_res.id],\n", " custom_process_rule=appbuilder.CustomProcessRule(\n", " separators=[\"?\"], target_length=600, overlap_rate=0.3\n", " ),\n", " knowledge_base_id=my_knowledge.knowledge_id\n", ")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "- 此时就可以在平台Console中查看到我们上传的民法典知识库了\n", "\n", "![](https://bj.bcebos.com/v1/appbuilder-sdk-components/%E6%B0%91%E6%B3%95%E5%85%B8%E7%9F%A5%E8%AF%86%E5%BA%93%E4%B8%AD%E6%9F%A5%E7%9C%8B%E5%AF%B9%E5%BA%94%E6%96%87%E4%BB%B6.png?authorization=bce-auth-v1%2FALTAKGa8m4qCUasgoljdEDAzLm%2F2024-12-17T08%3A51%3A35Z%2F-1%2Fhost%2F4025b0777017d0776e08ebe81c94b794c0883165ceaac1751d6c9824ed5727c2)\n", "\n", "### 2.3 为Agent应用添加知识库\n", "\n", "- 在平台console中找到我们创建的Agent应用,添加我们创建的民法典知识库,并更新发布应用\n", "\n", "![](https://bj.bcebos.com/v1/appbuilder-sdk-components/%E5%BA%94%E7%94%A8%E6%B7%BB%E5%8A%A0%E7%9F%A5%E8%AF%86%E5%BA%93.png?authorization=bce-auth-v1%2FALTAKGa8m4qCUasgoljdEDAzLm%2F2024-12-17T08%3A55%3A22Z%2F-1%2Fhost%2F4213ddd932eb9db15a507d985092797f168f5bb338df0453ea0848a1f9814597)\n", "\n", "- 再次调用我们的Agent应用,就可以看到我们添加民法典知识库之后,Agent应用可以正确回答我们的问题了" ] }, { "cell_type": "code", "execution_count": 88, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "**民法典第二编第一章的内容如下**:\n", "\n", "第一章 一般规定\n", "\n", "第二百零五条 本编调整因物的归属和利用产生的民事关系。\n", "\n", "第二百零六条 国家坚持和完善公有制为主体、多种所有制经济共同发展,按劳分配为主体、多种分配方式并存,社会主义市场经济体制等社会主义基本经济制度。国家巩固和发展公有制经济,鼓励、支持和引导非公有制经济的发展。国家实行社会主义市场经济,保障一切市场主体的平等法律地位和发展权利。\n", "\n", "第二百零七条 国家、集体、私人的物权和其他权利人的物权受法律平等保护,任何组织或者个人不得侵犯。\n", "\n", "第二百零八条 不动产物权的设立、变更、转让和消灭,应当依照法律规定登记。动产物权的设立和转让,应当依照法律规定交付。\n" ] } ], "source": [ "client = appbuilder.AppBuilderClient(app_id)\n", "conversation_id = client.create_conversation()\n", "message = client.run(conversation_id, \"请输出民法典第二编第一章的内容\")\n", "# 打印对话结果\n", "print(message.content.answer)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "- 可以观察到在使用了RAG(KnowledgeBase)之后,可以准确的输出【民法典的第二编第一分编第一章一般规定】部分的准确内容,接下来我们实验查询我们刻意删除掉的民法典第七编第十章部分的内容,查看Agent能否输出准确答案。(使用此方法模拟我们知识库中的文档更新之后,并没有被上传到知识库的情况)" ] }, { "cell_type": "code", "execution_count": 89, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "无法回答此问题。\n" ] } ], "source": [ "client = appbuilder.AppBuilderClient(app_id)\n", "conversation_id = client.create_conversation()\n", "message = client.run(conversation_id, \"请输出中华人民共和国民法典第七编第十章原文内容\")\n", "# 打印对话结果\n", "print(message.content.answer)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "- 我们可以发现Agent并没有输出民法典的第七编第十章的准确内容,此时我们就需要Appbuilder的切片管理功能,对知识库新增切片\n", "\n", "## 3. 知识库切片管理\n", "\n", "Appbuilder中支持多种知识库切片管理操作方式,包括:\n", "- 平台Console实现知识库切片管理\n", "- 使用SDK/API代码态实现知识库切片管理(优势)\n", "这里我们选择使用代码态SDK实现知识库切片管理的操作\n", "\n", "### 3.1KnowledgeBase 代码态切片管理功能\n", "\n", "* 创建切片\n", "* 修改切片信息\n", "* 获取切片信息\n", "* 获取切片列表\n", "* 删除切片\n", "\n", "\n", "- 接下来我们使用SDK上传一个民法典第七编第十章部分的内容的切片" ] }, { "cell_type": "code", "execution_count": 90, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "切片ID: f1e1962f-70dd-4573-9068-37485980ac5c\n" ] } ], "source": [ "# 获取知识库全部文档:get_all_documents\n", "doc_list = knowledge.get_all_documents(my_knowledge.knowledge_id)\n", "\n", "# 获取doc_list列表的第一个文档的document_id\n", "document_id = doc_list[0].id # 这里我们的知识库只有一个文档,所以获取第一个文档的document_id\n", "my_knowledge = appbuilder.KnowledgeBase(my_knowledge_base_id)\n", "\n", "# 这里我们使用来web_crawler函数来模拟爬虫功能,在生产环境中开发者可以使用自己的爬虫模块来周期性的获取最新的文档更新内容\n", "def web_crawler():\n", " \"\"\"\n", " 此函数模拟爬虫功能,获取最新的文档更新内容内容\n", " \"\"\"\n", " content = \"\"\"\n", " 中华人民共和国民法典第七编第十章原文内容如下:\n", " 建筑物和物件损害责任\n", " 第一千二百五十二条 建筑物、构筑物或者其他设施倒塌、塌陷造成他人损害的,由建设单位与施工单位承担连带责任,但是建设单位与施工单位能够证明不存在质量缺陷的除外。建设单位、施工单位赔偿后,有其他责任人的,有权向其他责任人追偿。\n", " 因所有人、管理人、使用人或者第三人的原因,建筑物、构筑物或者其他设施倒塌、塌陷造成他人损害的,由所有人、管理人、使用人或者第三人承担侵权责任。\n", " 第一千二百五十三条 建筑物、构筑物或者其他设施及其搁置物、悬挂物发生脱落、坠落造成他人损害,所有人、管理人或者使用人不能证明自己没有过错的,应当承担侵权责任。所有人、管理人或者使用人赔偿后,有其他责任人的,有权向其他责任人追偿。\n", " 第一千二百五十四条 禁止从建筑物中抛掷物品。从建筑物中抛掷物品或者从建筑物上坠落的物品造成他人损害的,由侵权人依法承担侵权责任;经调查难以确定具体侵权人的,除能够证明自己不是侵权人的外,由可能加害的建筑物使用人给予补偿。可能加害的建筑物使用人补偿后,有权向侵权人追偿。\n", " 物业服务企业等建筑物管理人应当采取必要的安全保障措施防止前款规定情形的发生;未采取必要的安全保障措施的,应当依法承担未履行安全保障义务的侵权责任。\n", " 发生本条第一款规定的情形的,公安等机关应当依法及时调查,查清责任人。\n", " 第一千二百五十五条 堆放物倒塌、滚落或者滑落造成他人损害,堆放人不能证明自己没有过错的,应当承担侵权责任。\n", " 第一千二百五十六条 在公共道路上堆放、倾倒、遗撒妨碍通行的物品造成他人损害的,由行为人承担侵权责任。公共道路管理人不能证明已经尽到清理、防护、警示等义务的,应当承担相应的责任。\n", " 第一千二百五十七条 因林木折断、倾倒或者果实坠落等造成他人损害,林木的所有人或者管理人不能证明自己没有过错的,应当承担侵权责任。\n", " 第一千二百五十八条 在公共场所或者道路上挖掘、修缮安装地下设施等造成他人损害,施工人不能证明已经设置明显标志和采取安全措施的,应当承担侵权责任。\n", " 窨井等地下设施造成他人损害,管理人不能证明尽到管理职责的,应当承担侵权责任。\n", " \"\"\"\n", " return content\n", "\n", "\n", "resp = my_knowledge.create_chunk(documentId=document_id, content=web_crawler())\n", "print(\"切片ID: \", resp.id)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "- 接下来我们再次调用Agent应用,查看一下他对民法典第七编第十章的说明。" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "以下是《中华人民共和国民法典》第七编第十章的全部内容:\n", "\n", "**建筑物和物件损害责任**\n", "\n", "**第一千二百五十二条** 建筑物、构筑物或者其他设施倒塌、塌陷造成他人损害的,由建设单位与施工单位承担连带责任,但是建设单位与施工单位能够证明不存在质量缺陷的除外。建设单位、施工单位赔偿后,有其他责任人的,有权向其他责任人追偿。\n", "\n", "因所有人、管理人、使用人或者第三人的原因,建筑物、构筑物或者其他设施倒塌、塌陷造成他人损害的,由所有人、管理人、使用人或者第三人承担侵权责任。\n", "\n", "**第一千二百五十三条** 建筑物、构筑物或者其他设施及其搁置物、悬挂物发生脱落、坠落造成他人损害,所有人、管理人或者使用人不能证明自己没有过错的,应当承担侵权责任。所有人、管理人或者使用人赔偿后,有其他责任人的,有权向其他责任人追偿。\n", "\n", "**第一千二百五十四条** 禁止从建筑物中抛掷物品。从建筑物中抛掷物品或者从建筑物上坠落的物品造成他人损害的,由侵权人依法承担侵权责任;经调查难以确定具体侵权人的,除能够证明自己不是侵权人的外,由可能加害的建筑物使用人给予补偿。可能加害的建筑物使用人补偿后,有权向侵权人追偿。\n", "\n", "物业服务企业等建筑物管理人应当采取必要的安全保障措施防止前款规定情形的发生;未采取必要的安全保障措施的,应当依法承担未履行安全保障义务的侵权责任。\n", "\n", "发生本条第一款规定的情形的,公安等机关应当依法及时调查,查清责任人。\n", "\n", "**第一千二百五十五条** 堆放物倒塌、滚落或者滑落造成他人损害,堆放人不能证明自己没有过错的,应当承担侵权责任。\n", "\n", "**第一千二百五十六条** 在公共道路上堆放、倾倒、遗撒妨碍通行的物品造成他人损害的,由行为人承担侵权责任。公共道路管理人不能证明已经尽到清理、防护、警示等义务的,应当承担相应的责任。\n", "\n", "**第一千二百五十七条** 因林木折断、倾倒或者果实坠落等造成他人损害,林木的所有人或者管理人不能证明自己没有过错的,应当承担侵权责任。\n", "\n", "**第一千二百五十八条** 在公共场所或者道路上挖掘、修缮安装地下设施等造成他人损害,施工人不能证明已经设置明显标志和采取安全措施的,应当承担侵权责任。\n", "\n", "窨井等地下设施造成他人损害,管理人不能证明尽到管理职责的,应当承担侵权责任。\n" ] } ], "source": [ "client = appbuilder.AppBuilderClient(app_id)\n", "conversation_id = client.create_conversation()\n", "message = client.run(conversation_id, \"请输出中华人民共和国民法典第七编第十章原文内容\")\n", "# 打印对话结果\n", "print(message.content.answer)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "- 可以观察到此次Agent运行准确的的输出了民法典第七编第十章的内容\n", "\n", "#### 其他的知识库文档&切片管理方法\n", "\n", "###### 修改切片信息`modify_chunk`\n", "\n", "- 如果我们对之前设置的切片信息不满意,可以通过`modify_chunk`方法进行修改。\n", "\n", "###### 获取切片信息`describe_chunk`\n", "\n", "- 我需要查看我刚才创建切片信息,可以使用`describe_chunk`方法\n", "\n", "###### 删除切片信息`delete_chunk`\n", "\n", "- 切片信息创建出来后,如果不需要了,可以通过`delete_chunk`方法进行删除。\n", "\n", "##### 删除文档和知识库\n", "\n", "- 当你不再需要文档知识库时,可以删除它,SDK同样提供删除文档和知识库的方法\n", " - 从知识库删除文档 `KnowledgeBase().delete_document`\n", " - 删除知识库`delete_knowledge_base`" ] } ], "metadata": { "kernelspec": { "display_name": "python-3.10.14", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.10.14" } }, "nbformat": 4, "nbformat_minor": 2 } ================================================ FILE: cookbooks/mcp/app_mcp_server.ipynb ================================================ { "cells": [ { "cell_type": "markdown", "id": "8ce67390", "metadata": {}, "source": [ "# 前言\n", "通过本文,你可以:\n", " * 了解AppBuilder Agent MCP Server是什么\n", " * 了解如何通过AppBuilder-SDK调用AppBuilder Agent MCP Server\n", " * 了解如何通过Cursor调用AppBuilder Agent MCP Server\n", "\n", "如果你需要了解更多关于AppBuilder结合MCP生态的功能,可跳转到下面的文档:\n", "- 主动调用:通过AppBuilder-Agent调用MCP Server\n", " - 代码态调用:[AppBuilder结合端云组件,调用本地MCP Server](./client.ipynb) \n", " - 代码态调用:[AppBuilder结合地图MCP Server,实现智能导航](./baidu_map.ipynb)\n", " - 零代码态调用:[AppBuilder控制台使用MCP](https://cloud.baidu.com/doc/AppBuilder/s/Nm9vmpb3g)\n", "- 被动调用:AppBuilder能力,融入MCP生态,可作为MCP Server提供能力\n", " - 组件能力:[AppBuilder组件转MCP Server](./server.ipynb)\n", " - 智能体能力:[AppBuilder Agent MCP Server](./app_mcp_server.ipynb)\n", " - AI搜索能力: [AppBuilder AI搜索MCP Server](https://github.com/baidubce/app-builder/tree/master/python/mcp_server/ai_search)\n", " - RAG能力:[AppBuilder知识库MCP Server](https://github.com/baidubce/app-builder/tree/master/python/mcp_server/knowledge_base)\n", "\n", "\n", "## AppBuilder Agent MCP Server简介\n", "千帆AppBuilder提供了关于AppBuilder应用的MCP Server,用户可通过MCP协议调用在AppBuilder平台创建并发布的自定义智能体应用。\n", "\n", "当前支持获取应用列表、应用对话两大功能。本文讲述如何使用不同客户端调用此服务。\n", "\n", "对于入门用户,还提供了环境配置、千帆Agent创建等操作步骤。已熟悉用户可以直接跳过环境配置、应用创建部分。\n", "\n", "## 安装配置步骤\n", "\n", "### 配置基础环境\n", "\n", "#### 1、安装Python\n", "\n", "大部分的MCP Server,例如Unity和Blender,都是Python SDK\n", "安装Python最简单的方法是安装Miniconda\n", "**注意:请确保安装的python>=3.12**\n", "\n", "[Miniconda官网](https://www.anaconda.com/docs/getting-started/miniconda/install)\n", "\n", "#### 2、下载Appbuilder-SDK\n", "\n", "为了实现Appbuilder-SDK对AppBuilder Agent MCP Server的代码态调用,需要在conda环境下载appbuilder-sdk包\n" ] }, { "cell_type": "code", "execution_count": null, "id": "96a39a88", "metadata": { "vscode": { "languageId": "shellscript" } }, "outputs": [], "source": [ "!python3 -m pip install httpx appbuilder-sdk mcp" ] }, { "cell_type": "markdown", "id": "6e7d417d", "metadata": {}, "source": [ "\n", "## 创建百度智能云千帆AppBuilder智能体\n", "\n", "首先创建一个千帆AppBuilder智能体。\n", "\n", "### 1、进入百度智能云千帆AppBuilder主页\n", "\n", "进入百度智能云千帆AppBuilder主页,免费试用\n", "\n", "- [百度智能云千帆AppBuilder主页](https://qianfan.cloud.baidu.com/appbuilder)\n", "\n", "### 2、创建【自主规划Agent】\n", "\n", "- [Appbuilder 自主规划Agent概述](https://cloud.baidu.com/doc/AppBuilder/s/km4i50me8)\n", "\n", "- [快速创建应用](https://cloud.baidu.com/doc/AppBuilder/s/Om0ks82ow)\n", "\n", "\n", "![](https://bj.bcebos.com/v1/appbuilder-sdk-components/%E5%88%9B%E5%BB%BA%E8%87%AA%E4%B8%BB%E8%A7%84%E5%88%92Agent.png?authorization=bce-auth-v1%2FALTAKGa8m4qCUasgoljdEDAzLm%2F2025-04-17T15%3A00%3A03Z%2F-1%2Fhost%2F31df73d263dbc1dc7e28a6bc077b37c70ce27af91ac7888ff9151c7ef1d58b04)\n", "\n", "### 3、输入一句简单的提示词,让AI自动扩写\n", "\n", "![](https://bj.bcebos.com/v1/appbuilder-sdk-components/%E5%88%9B%E5%BB%BA%E8%87%AA%E4%B8%BB%E8%A7%84%E5%88%92agent.png?authorization=bce-auth-v1%2FALTAKGa8m4qCUasgoljdEDAzLm%2F2025-04-17T03%3A23%3A29Z%2F-1%2Fhost%2F67b7a5d0c38c12f79bc925e995c8f09775eb37bfe9025f61a593080c3c05c82c)\n", "\n", "### 4、删除自动配置的组件\n", "\n", "因为我们调用MCP工具,所以不需要使用AppBuilder自带组件\n", "\n", "### 5、配置模型\n", "\n", "将规划模型和问答模型的思考轮数拉满\n", "\n", "![](https://bj.bcebos.com/v1/appbuilder-sdk-components/%E9%85%8D%E7%BD%AE%E6%A8%A1%E5%9E%8B.png?authorization=bce-auth-v1%2FALTAKGa8m4qCUasgoljdEDAzLm%2F2025-04-17T03%3A27%3A44Z%2F-1%2Fhost%2Ffd031f86bf71a0ca7e32db70533a76db9c39757a139f94b34f487eae9f860534)\n", "\n", "### 6、发布应用\n", "\n", "发布应用,在【个人空间】中,查看应用ID,记下来\n", "\n", "![](https://bj.bcebos.com/v1/appbuilder-sdk-components/%E5%8F%91%E5%B8%83Agent%E5%BA%94%E7%94%A8.png?authorization=bce-auth-v1%2FALTAKGa8m4qCUasgoljdEDAzLm%2F2025-04-17T03%3A30%3A26Z%2F-1%2Fhost%2Ff66b1bef4bb432ddd59ca07189ed210fb475c6363559dfd0c7ab53ef47a6240f)\n", "\n", "### 7、创建Appbuilder API key\n", "\n", "- [Appbuilder API key授权](https://cloud.baidu.com/doc/AppBuilder/s/lm68r8e6i)\n", "\n", "- [Appbuilder API 控制台管理中心](https://console.bce.baidu.com/iam/#/iam/apikey/list)\n", "\n", "在【API Key】界面中,创建一个新的Key,并添加刚刚创建的应用,记下来。\n", "\n", "![](https://bj.bcebos.com/v1/appbuilder-sdk-components/%E5%88%9B%E5%BB%BAAPPBUILDER-TOKEN.png?authorization=bce-auth-v1%2FALTAKGa8m4qCUasgoljdEDAzLm%2F2025-04-17T14%3A49%3A27Z%2F-1%2Fhost%2F9266ac8c93a262d2905811877d680f53af26668a0ee09e1b3a61c0b721de253c)\n", "\n", "同时配置API key权限,将上文创建的应用添加到API key权限中。\n", "\n", "![](https://bj.bcebos.com/v1/appbuilder-sdk-components/%E6%B7%BB%E5%8A%A0Agent%E6%9D%83%E9%99%90.png?authorization=bce-auth-v1%2FALTAKGa8m4qCUasgoljdEDAzLm%2F2025-04-17T03%3A33%3A59Z%2F-1%2Fhost%2Feda8af9c241207cf07ff2edb85b2271ce48aade84775ca2273580ad13f03a5dc)" ] }, { "cell_type": "markdown", "id": "3aa3c0a2", "metadata": {}, "source": [ "## 使用AppBuilder SDK调用\n", "\n", "### 1. 获取应用列表\n", "查询用户的应用列表。" ] }, { "cell_type": "code", "execution_count": null, "id": "3e7b9a90", "metadata": {}, "outputs": [], "source": [ "import asyncio\n", "import os\n", "import json\n", "from appbuilder.mcp_server.client import MCPClient\n", "\n", "os.environ[\"APPBUILDER_TOKEN\"] = \"YOUR_APPBUILDER_TOKEN\"\n", "\n", "async def main():\n", " client = MCPClient()\n", " await client.connect_to_server(service_url=service_url)\n", " result = await client.call_tool(\"get_all_apps\", {})\n", " for app_info in result.content:\n", " app_info = json.loads(app_info.text)\n", " print(app_info[\"id\"] + \"\\t\" + app_info[\"name\"])\n", "\n", "if __name__ == \"__main__\":\n", " service_url = \"http://appbuilder.baidu.com/v2/app/mcp/sse?api_key=\" + os.environ.get(\"APPBUILDER_TOKEN\")\n", "\n", " loop = asyncio.get_event_loop()\n", " loop.run_until_complete(main())" ] }, { "cell_type": "markdown", "id": "60df365f", "metadata": {}, "source": [ "控制台会打印你的应用ID、应用名,参考如下:\n", "\n", "```bash\n", "909*****-***a-****-****-*********2c93 我的Agent应用\n", "697*****-***9-****-****-*********360b 我的Agent应用\n", "963*****-***2-****-****-*********21d1 我的Agent应用\n", "34f*****-***b-****-****-*********3df2 我的Agent应用\n", "773*****-***8-****-****-*********62df 图像识别示例\n", "```\n", "\n", "### 2. 进行Agent对话\n", "使用MCP协议跟Agent进行对话。" ] }, { "cell_type": "code", "execution_count": null, "id": "50c87488", "metadata": {}, "outputs": [], "source": [ "import asyncio\n", "import json\n", "import os\n", "from appbuilder.mcp_server.client import MCPClient\n", "\n", "os.environ[\"APPBUILDER_TOKEN\"] = \"YOUR_APPBUILDER_TOKEN\"\n", "os.environ[\"APP_ID\"] = \"YOUR_APP_ID\"\n", "\n", "\n", "async def main():\n", " client = MCPClient()\n", " await client.connect_to_server(service_url=service_url)\n", " app_id = os.environ.get(\"APP_ID\")\n", " result = await client.call_tool(\"create_conversation\", {\"app_id\": app_id})\n", " conversation_id = result.content[0].text\n", " query = \"你能做什么?\"\n", " result = await client.call_tool(\n", " \"run\",\n", " {\n", " \"app_id\": app_id,\n", " \"conversation_id\": conversation_id,\n", " \"query\": query,\n", " },\n", " )\n", " print(result.content[0].text)\n", "\n", "\n", "if __name__ == \"__main__\":\n", " service_url = (\n", " \"http://appbuilder.baidu.com/v2/app/mcp/sse?api_key=\"\n", " + os.environ.get(\"APPBUILDER_TOKEN\")\n", " )\n", "\n", " loop = asyncio.get_event_loop()\n", " loop.run_until_complete(main())" ] }, { "cell_type": "markdown", "id": "df473bce", "metadata": {}, "source": [ "控制台会打印对话的返回。参考如下:\n", "```bash\n", "作为植物识别专家,我专门负责识别和鉴定各种植物种类。我可以通过使用植物识别组件来分析植物的特征,如叶子形状、花朵颜色、果实形态等,从而准确确定植物的种类。无论你是对路边的野花好奇,还是对家中盆栽的种类有疑问,我都可以帮助你进行识别和解答。\n", "```" ] }, { "cell_type": "markdown", "id": "6b68c4d6", "metadata": {}, "source": [ "## 使用Cursor调用\n", "### Cursor配置\n", "api_key=上面步骤获取到的api key,格式为\"bce-v3/ALTAK...\"" ] }, { "cell_type": "code", "execution_count": null, "id": "8b292ee1", "metadata": { "vscode": { "languageId": "json" } }, "outputs": [], "source": [ "{\n", " \"mcpServers\": {\n", " \"appbuilder-app\": {\n", " \"url\": \"http://appbuilder.baidu.com/v2/app/mcp/sse?api_key=bce-v3/ALTAK...\"\n", " }\n", " }\n", "}" ] }, { "cell_type": "markdown", "id": "804d655d", "metadata": {}, "source": [ "配置后,在Cursor设置页面可看到`get_all_apps`、`create_converstation`、`run`三个Tool。\n", "![cursor config](./image/cursor_agent_mcp_config.png)" ] }, { "cell_type": "markdown", "id": "338eb0cb", "metadata": {}, "source": [ "### 获取应用列表\n", "![get_app_apps](./image/cursor_agent_get_all_apps.png)\n", "\n", "### 应用对话\n", "![cursor agent chat](./image/cursor_agent_run.png)" ] } ], "metadata": { "kernelspec": { "display_name": "Python 3", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.12.10" } }, "nbformat": 4, "nbformat_minor": 5 } ================================================ FILE: cookbooks/mcp/baidu_map.ipynb ================================================ { "cells": [ { "cell_type": "markdown", "id": "8ce67390", "metadata": {}, "source": [ "# MCP协议加持,千帆AppBuilder让语音导航更智能,开发更轻松\n", "\n", "MCP最近热度很高,作为国内首家支持MCP协议的大模型应用开发平台,千帆AppBuilder完成兼容后,用户可通过千帆AppBuilder轻松调用MCP Server生态中的海量工具,快速扩展端和云端的工具数量。我们的用户,也在利用这个强大的功能,打破不同工具间壁垒,实现更多想法。\n", "\n", "比如,爷爷奶奶都会用的百度地图,可以在千帆AppBuilder的连接下,成为你的开发利器:\n", "\n", "百度地图核心API已全面兼容MCP协议——你在千帆AppBuilder开发的应用,可以轻松调用百度地图的各项功能。对着手机说出“人话需求”,AI自动规划路线、检索地点、查天气、查路况。\n", "\n", "具体如何实现?本文将带你一步步了解如何通过千帆AppBuilder、百度地图和MCP协议的结合,通过SDK的方式进行开发,打造出更智能的应用。我们还会提供详细的安装和配置步骤,帮助你快速上手,轻松实现功能扩展。\n", "\n", "## 官方代码及文档\n", "\n", "- [百度地图 MCP Server](https://github.com/baidu-maps/mcp)\n", "- [Appbuilder 调用MCP组件服务](https://cloud.baidu.com/doc/AppBuilder/s/Um88v68dn)\n", "\n", "## 安装配置步骤\n", "\n", "### 配置基础环境\n", "\n", "#### 1、安装Python\n", "\n", "大部分的MCP Server,例如Unity和Blender,都是Python SDK\n", "安装Python最简单的方法是安装Miniconda\n", "**注意:请确保安装的python>=3.12**\n", "\n", "[Miniconda官网](https://www.anaconda.com/docs/getting-started/miniconda/install)\n", "\n", "#### 2、安装包管理器uv\n", "\n", "uv是pip的替代,能够快速启动和管理项目,后续每个MCP服务都需要用uvx命令启动\n", "\n", "[包管理器uv安装教程](https://docs.astral.sh/uv/getting-started/installation)\n", "\n", "#### 3、安装Node.js\n", "\n", "[Node.js安装教程](https://nodejs.org/en/download)\n", "\n", "#### 4、下载Appbuilder-SDK\n", "\n", "为了实现Appbuilder-SDK对百度地图 MCP Server的代码态调用,需要在conda环境下载appbuilder-sdk包\n" ] }, { "cell_type": "code", "execution_count": null, "id": "96a39a88", "metadata": { "vscode": { "languageId": "shellscript" } }, "outputs": [], "source": [ "!python3 -m pip install httpx appbuilder-sdk mcp" ] }, { "cell_type": "markdown", "id": "6e7d417d", "metadata": {}, "source": [ "#### 获取百度地图API Key\n", "\n", "在百度地图开放平台申请一个API Key,记下来\n", "[百度地图开放平台](https://lbsyun.baidu.com/apiconsole/key)\n", "\n", "## 百度智能云千帆AppBuilder代码态调用\n", "\n", "如何通过代码来调用百度地图的MCP服务,接入到我自己的应用中呢?\n", "\n", "可以用百度智能云企业级大模型应用开发平台-千帆AppBuidler的代码态,手搓一个MCP的客户端。\n", "\n", "### 1、进入百度智能云千帆AppBuilder主页\n", "\n", "进入百度智能云千帆AppBuilder主页,免费试用\n", "\n", "- [百度智能云千帆AppBuilder主页](https://qianfan.cloud.baidu.com/appbuilder)\n", "\n", "### 2、创建【自主规划Agent】\n", "\n", "- [Appbuilder 自主规划Agent概述](https://cloud.baidu.com/doc/AppBuilder/s/km4i50me8)\n", "\n", "- [快速创建应用](https://cloud.baidu.com/doc/AppBuilder/s/Om0ks82ow)\n", "\n", "\n", "![](https://bj.bcebos.com/v1/appbuilder-sdk-components/%E5%88%9B%E5%BB%BA%E8%87%AA%E4%B8%BB%E8%A7%84%E5%88%92Agent.png?authorization=bce-auth-v1%2FALTAKGa8m4qCUasgoljdEDAzLm%2F2025-04-17T15%3A00%3A03Z%2F-1%2Fhost%2F31df73d263dbc1dc7e28a6bc077b37c70ce27af91ac7888ff9151c7ef1d58b04)\n", "\n", "### 3、输入一句简单的提示词,让AI自动扩写\n", "\n", "![](https://bj.bcebos.com/v1/appbuilder-sdk-components/%E5%88%9B%E5%BB%BA%E8%87%AA%E4%B8%BB%E8%A7%84%E5%88%92agent.png?authorization=bce-auth-v1%2FALTAKGa8m4qCUasgoljdEDAzLm%2F2025-04-17T03%3A23%3A29Z%2F-1%2Fhost%2F67b7a5d0c38c12f79bc925e995c8f09775eb37bfe9025f61a593080c3c05c82c)\n", "\n", "### 4、删除自动配置的组件\n", "\n", "因为我们调用MCP工具,所以不需要使用AppBuilder自带组件\n", "\n", "### 5、配置模型\n", "\n", "将规划模型和问答模型的思考轮数拉满\n", "\n", "![](https://bj.bcebos.com/v1/appbuilder-sdk-components/%E9%85%8D%E7%BD%AE%E6%A8%A1%E5%9E%8B.png?authorization=bce-auth-v1%2FALTAKGa8m4qCUasgoljdEDAzLm%2F2025-04-17T03%3A27%3A44Z%2F-1%2Fhost%2Ffd031f86bf71a0ca7e32db70533a76db9c39757a139f94b34f487eae9f860534)\n", "\n", "### 6、发布应用\n", "\n", "发布应用,在【个人空间】中,查看应用ID,记下来\n", "\n", "![](https://bj.bcebos.com/v1/appbuilder-sdk-components/%E5%8F%91%E5%B8%83Agent%E5%BA%94%E7%94%A8.png?authorization=bce-auth-v1%2FALTAKGa8m4qCUasgoljdEDAzLm%2F2025-04-17T03%3A30%3A26Z%2F-1%2Fhost%2Ff66b1bef4bb432ddd59ca07189ed210fb475c6363559dfd0c7ab53ef47a6240f)\n", "\n", "### 7、创建Appbuilder API key\n", "\n", "- [Appbuilder API key授权](https://cloud.baidu.com/doc/AppBuilder/s/lm68r8e6i)\n", "\n", "- [Appbuilder API 控制台管理中心](https://console.bce.baidu.com/iam/#/iam/apikey/list)\n", "\n", "在【API Key】界面中,创建一个新的Key,并添加刚刚创建的应用,记下来。\n", "\n", "![](https://bj.bcebos.com/v1/appbuilder-sdk-components/%E5%88%9B%E5%BB%BAAPPBUILDER-TOKEN.png?authorization=bce-auth-v1%2FALTAKGa8m4qCUasgoljdEDAzLm%2F2025-04-17T14%3A49%3A27Z%2F-1%2Fhost%2F9266ac8c93a262d2905811877d680f53af26668a0ee09e1b3a61c0b721de253c)\n", "\n", "同时配置API key权限,将上文创建的应用添加到API key权限中。\n", "\n", "![](https://bj.bcebos.com/v1/appbuilder-sdk-components/%E6%B7%BB%E5%8A%A0Agent%E6%9D%83%E9%99%90.png?authorization=bce-auth-v1%2FALTAKGa8m4qCUasgoljdEDAzLm%2F2025-04-17T03%3A33%3A59Z%2F-1%2Fhost%2Feda8af9c241207cf07ff2edb85b2271ce48aade84775ca2273580ad13f03a5dc)\n", "\n", "### 8、配置代码\n", "\n", "将下述链接复制到浏览器,可下载代码。解压缩文件,并更新代码内容。\n", "\n", "https://qianfandeveloper.bj.bcebos.com/baidumap_mcp.zip\n", "\n", "* 在map.py中,将`BAIDU_MAPS_API_KEY`换成你的自己的百度地图API密钥。\n", "* 在test.py文件中,将`APPBUILDER_TOKEN`更换成自己的Apppbuilder API Key,并将`app_id`更换成自己的应用ID。\n", "\n", "接下来将提供一个完整的示例,演示如何使用百度智能云千帆AppBuilder的Agent调用百度地图MCP服务。\n" ] }, { "cell_type": "markdown", "id": "e05e6628", "metadata": {}, "source": [ "#### (1)创建MCP服务器实例\n", "\n", "* 将下述代码添加到本地`map.py`文件中,**注意,这里需要替换`BAIDU_MAPS_API_KEY`为你自己的百度地图API Key**" ] }, { "cell_type": "code", "execution_count": null, "id": "c32b3a7a", "metadata": {}, "outputs": [], "source": [ "# map.py\n", "import os\n", "import copy\n", "import httpx\n", "from asyncio import sleep\n", "\n", "from mcp.server.fastmcp import FastMCP, Context\n", "\n", "# 创建MCP服务器实例\n", "mcp = FastMCP(\"mcp-server-baidu-maps\")\n", "# 设置API密钥,用于调用百度地图API,获取方式请参考:https://lbsyun.baidu.com/apiconsole/key\n", "os.environ[\"BAIDU_MAPS_API_KEY\"] = \"6IlHFTRGzNjPxxxxxxxxxxxxxxxxxx\"\n", "api_key = os.getenv(\"BAIDU_MAPS_API_KEY\")\n", "api_url = \"https://api.map.baidu.com\"\n", "\n", "\n", "def filter_result(data) -> dict:\n", " \"\"\"\n", " 过滤路径规划结果,用于剔除冗余字段信息,保证输出给模型的数据更简洁,\n", " 避免长距离路径规划场景下chat中断\n", " \"\"\"\n", " # 创建输入数据的深拷贝以避免修改原始数据\n", " processed_data = copy.deepcopy(data)\n", "\n", " # 检查是否存在'result'键\n", " if \"result\" in processed_data:\n", " result = processed_data[\"result\"]\n", "\n", " # 检查'result'中是否存在'routes'键\n", " if \"routes\" in result:\n", " for route in result[\"routes\"]:\n", " # 检查每个'route'中是否存在'steps'键\n", " if \"steps\" in route:\n", " new_steps = []\n", " for step in route[\"steps\"]:\n", " # 提取'instruction'字段,若不存在则设为空字符串\n", " new_step = {\n", " \"distance\": step.get(\"distance\", \"\"),\n", " \"duration\": step.get(\"duration\", \"\"),\n", " \"instruction\": step.get(\"instruction\", \"\"),\n", " }\n", " new_steps.append(new_step)\n", " # 替换原steps为仅含instruction的新列表\n", " route[\"steps\"] = new_steps\n", "\n", " return processed_data\n", "\n", "\n", "@mcp.tool()\n", "async def map_geocode(address: str, ctx: Context) -> dict:\n", " \"\"\"\n", " Name:\n", " 地理编码服务\n", "\n", " Description:\n", " 将地址解析为对应的位置坐标。地址结构越完整,地址内容越准确,解析的坐标精度越高。\n", "\n", " Args:\n", " address: 待解析的地址。最多支持84个字节。可以输入两种样式的值,分别是:\n", " 1、标准的结构化地址信息,如北京市海淀区上地十街十号【推荐,地址结构越完整,解析精度越高】\n", " 2、支持\"*路与*路交叉口\"描述方式,如北一环路和阜阳路的交叉路口\n", " 第二种方式并不总是有返回结果,只有当地址库中存在该地址描述时才有返回。\n", " \"\"\"\n", " try:\n", " # 获取API密钥\n", " if not api_key:\n", " raise Exception(\"Can not found API key.\")\n", "\n", " # 调用百度API\n", " url = f\"{api_url}/geocoding/v3/\"\n", "\n", " # 设置请求参数\n", " # 更多参数信息请参考:https://lbsyun.baidu.com/faq/api?title=webapi/guide/webservice-geocoding\n", " params = {\n", " \"ak\": f\"{api_key}\",\n", " \"output\": \"json\",\n", " \"address\": f\"{address}\",\n", " \"from\": \"py_mcp\",\n", " }\n", "\n", " async with httpx.AsyncClient() as client:\n", " response = await client.get(url, params=params)\n", " response.raise_for_status()\n", " result = response.json()\n", "\n", " if result.get(\"status\") != 0:\n", " error_msg = result.get(\"message\", \"unkown error\")\n", " raise Exception(f\"API response error: {error_msg}\")\n", "\n", " return result\n", "\n", " except httpx.HTTPError as e:\n", " raise Exception(f\"HTTP request failed: {str(e)}\") from e\n", " except KeyError as e:\n", " raise Exception(f\"Failed to parse reponse: {str(e)}\") from e\n", "\n", "\n", "@mcp.tool()\n", "async def map_reverse_geocode(\n", " latitude: float, longitude: float, ctx: Context\n", ") -> dict:\n", " \"\"\"\n", " Name:\n", " 逆地理编码服务\n", "\n", " Description:\n", " 根据经纬度坐标点获取对应位置的行政区划与POI信息\n", "\n", " Args:\n", " latitude: 纬度 (gcj02ll)\n", " longitude: 经度 (gcj02ll)\n", " \"\"\"\n", " try:\n", " # 获取API密钥\n", " if not api_key:\n", " raise Exception(\"There\")\n", "\n", " # 调用百度API\n", " url = f\"{api_url}/reverse_geocoding/v3/\"\n", "\n", " # 设置请求参数\n", " # 更多参数信息请参考:https://lbsyun.baidu.com/faq/api?title=webapi/guide/webservice-geocoding-abroad\n", " params = {\n", " \"ak\": f\"{api_key}\",\n", " \"output\": \"json\",\n", " \"coordtype\": \"gcj02ll\",\n", " \"location\": f\"{latitude},{longitude}\",\n", " \"extensions_poi\": \"1\",\n", " \"from\": \"py_mcp\",\n", " }\n", "\n", " async with httpx.AsyncClient() as client:\n", " response = await client.get(url, params=params)\n", " response.raise_for_status()\n", " result = response.json()\n", "\n", " if result.get(\"status\") != 0:\n", " error_msg = result.get(\"message\", \"unkown error\")\n", " raise Exception(f\"API response error: {error_msg}\")\n", "\n", " return result\n", "\n", " except httpx.HTTPError as e:\n", " raise Exception(f\"HTTP request failed: {str(e)}\") from e\n", " except KeyError as e:\n", " raise Exception(f\"Failed to parse reponse: {str(e)}\") from e\n", "\n", "\n", "@mcp.tool()\n", "async def map_search_places(\n", " query: str, region: str, location: str, radius: int, ctx: Context\n", ") -> dict:\n", " \"\"\"\n", " Name:\n", " 地点检索服务\n", "\n", " Description:\n", " 城市内检索: 检索某一城市内(目前最细到城市级别)的地点信息。\n", " 周边检索: 设置圆心和半径,检索圆形区域内的地点信息(常用于周边检索场景)。\n", "\n", " Args:\n", " query: 检索关键字\n", " region: 检索的行政区划\n", " location: 圆形区域检索中心点\n", " radius: 圆形区域检索半径,单位:米\n", " \"\"\"\n", " try:\n", " # 获取API密钥\n", " if not api_key:\n", " raise Exception(\"Can not found API key.\")\n", "\n", " # 调用百度API\n", " url = f\"{api_url}/place/v2/search\"\n", "\n", " # 设置请求参数\n", " # 更多参数信息请参考:https://lbsyun.baidu.com/faq/api?title=webapi/guide/webservice-placeapi\n", " params = {\n", " \"ak\": f\"{api_key}\",\n", " \"output\": \"json\",\n", " \"query\": f\"{query}\",\n", " \"region\": f\"{region}\",\n", " \"from\": \"py_mcp\",\n", " }\n", " if location:\n", " params[\"location\"] = f\"{location}\"\n", " params[\"radius\"] = f\"{radius}\"\n", "\n", " async with httpx.AsyncClient() as client:\n", " response = await client.get(url, params=params)\n", " response.raise_for_status()\n", " result = response.json()\n", "\n", " if result.get(\"status\") != 0:\n", " error_msg = result.get(\"message\", \"unkown error\")\n", " raise Exception(f\"API response error: {error_msg}\")\n", "\n", " return result\n", "\n", " except httpx.HTTPError as e:\n", " raise Exception(f\"HTTP request failed: {str(e)}\") from e\n", " except KeyError as e:\n", " raise Exception(f\"Failed to parse reponse: {str(e)}\") from e\n", "\n", "\n", "@mcp.tool()\n", "async def map_place_details(uid: str, ctx: Context) -> dict:\n", " \"\"\"\n", " Name:\n", " 地点详情检索服务\n", "\n", " Description:\n", " 地点详情检索: 地点详情检索针对指定POI,检索其相关的详情信息。\n", " 开发者可以通地点检索服务获取POI uid。使用\"地点详情检索\"功能,传入uid,\n", " 即可检索POI详情信息,如评分、营业时间等(不同类型POI对应不同类别详情数据)。\n", "\n", " Args:\n", " uid: poi的唯一标识\n", " \"\"\"\n", " try:\n", " # 获取API密钥\n", " if not api_key:\n", " raise Exception(\"Can not found API key.\")\n", "\n", " # 调用百度API\n", " url = f\"{api_url}/place/v2/detail\"\n", "\n", " # 设置请求参数\n", " # 更多参数信息请参考:https://lbsyun.baidu.com/faq/api?title=webapi/guide/webservice-placeapi/detail\n", " params = {\n", " \"ak\": f\"{api_key}\",\n", " \"output\": \"json\",\n", " \"uid\": f\"{uid}\",\n", " # Agent入参不可控,这里给定scope为2\n", " \"scope\": 2,\n", " \"from\": \"py_mcp\",\n", " }\n", "\n", " async with httpx.AsyncClient() as client:\n", " response = await client.get(url, params=params)\n", " response.raise_for_status()\n", " result = response.json()\n", "\n", " if result.get(\"status\") != 0:\n", " error_msg = result.get(\"message\", \"unkown error\")\n", " raise Exception(f\"API response error: {error_msg}\")\n", "\n", " return result\n", "\n", " except httpx.HTTPError as e:\n", " raise Exception(f\"HTTP request failed: {str(e)}\") from e\n", " except KeyError as e:\n", " raise Exception(f\"Failed to parse reponse: {str(e)}\") from e\n", "\n", "\n", "@mcp.tool()\n", "async def map_distance_matrix(\n", " origins: str, destinations: str, mode: str, ctx: Context\n", ") -> dict:\n", " \"\"\"\n", " Name:\n", " 批量算路服务\n", "\n", " Description:\n", " 根据起点和终点坐标计算路线规划距离和行驶时间\n", " 批量算路目前支持驾车、骑行、步行\n", " 步行时任意起终点之间的距离不得超过200KM,超过此限制会返回参数错误\n", " 驾车批量算路一次最多计算100条路线,起终点个数之积不能超过100\n", "\n", " Args:\n", " origins: 多个起点坐标纬度,经度,按|分隔。示例:40.056878,116.30815|40.063597,116.364973【骑行】【步行】支持传入起点uid提升绑路准确性,格式为:纬度,经度;POI的uid|纬度,经度;POI的uid。示例:40.056878,116.30815;xxxxx|40.063597,116.364973;xxxxx\n", " destinations: 多个终点坐标纬度,经度,按|分隔。示例:40.056878,116.30815|40.063597,116.364973【【骑行】【步行】支持传入终点uid提升绑路准确性,格式为:纬度,经度;POI的uid|纬度,经度;POI的uid。示例:40.056878,116.30815;xxxxx|40.063597,116.364973;xxxxx\n", " mode: 批量算路类型(driving, riding, walking)\n", " \"\"\"\n", " try:\n", " # 获取API密钥\n", " if not api_key:\n", " raise Exception(\"Can not found API key.\")\n", "\n", " # 调用百度API\n", " url = f\"{api_url}/routematrix/v2/{mode}\"\n", "\n", " # 设置请求参数\n", " # 更多参数信息请参考:https://lbsyun.baidu.com/faq/api?title=webapi/routchtout\n", " params = {\n", " \"ak\": f\"{api_key}\",\n", " \"output\": \"json\",\n", " \"origins\": f\"{origins}\",\n", " \"destinations\": f\"{destinations}\",\n", " \"from\": \"py_mcp\",\n", " }\n", "\n", " async with httpx.AsyncClient() as client:\n", " response = await client.get(url, params=params)\n", " response.raise_for_status()\n", " result = response.json()\n", "\n", " if result.get(\"status\") != 0:\n", " error_msg = result.get(\"message\", \"unkown error\")\n", " raise Exception(f\"API response error: {error_msg}\")\n", "\n", " return result\n", "\n", " except httpx.HTTPError as e:\n", " raise Exception(f\"HTTP request failed: {str(e)}\") from e\n", " except KeyError as e:\n", " raise Exception(f\"Failed to parse reponse: {str(e)}\") from e\n", "\n", "\n", "@mcp.tool()\n", "async def map_directions(\n", " model: str, origin: str, destination: str, ctx: Context\n", ") -> dict:\n", " \"\"\"\n", " Name:\n", " 路线规划服务\n", "\n", " Description:\n", " 驾车路线规划: 根据起终点坐标规划驾车出行路线\n", " 骑行路线规划: 根据起终点坐标规划骑行出行路线\n", " 步行路线规划: 根据起终点坐标规划步行出行路线\n", " 公交路线规划: 根据起终点坐标规划公共交通出行路线\n", "\n", " Args:\n", " model: 路线规划类型(driving, riding, walking, transit)\n", " origin: 起点坐标,当用户只有起点名称时,需要先通过地理编码服务或地点地点检索服务确定起点的坐标\n", " destination: 终点坐标,当用户只有起点名称时,需要先通过地理编码服务或地点检索服务确定起点的坐标\n", " \"\"\"\n", " try:\n", " # 获取API密钥\n", " if not api_key:\n", " raise Exception(\"Can not found API key.\")\n", "\n", " # 调用百度API\n", " url = f\"{api_url}/directionlite/v1/{model}\"\n", "\n", " # 设置请求参数\n", " # 更多参数信息请参考:https://lbs.baidu.com/faq/api?title=webapi/direction-api-v2\n", " params = {\n", " \"ak\": f\"{api_key}\",\n", " \"output\": \"json\",\n", " \"origin\": f\"{origin}\",\n", " \"destination\": f\"{destination}\",\n", " \"from\": \"py_mcp\",\n", " }\n", "\n", " async with httpx.AsyncClient() as client:\n", " response = await client.get(url, params=params)\n", " response.raise_for_status()\n", " result = response.json()\n", "\n", " if result.get(\"status\") != 0:\n", " error_msg = result.get(\"message\", \"unkown error\")\n", " raise Exception(f\"API response error: {error_msg}\")\n", "\n", " \"\"\"\n", " 过滤非公交的导航结果,防止返回的结果中包含大量冗余坐标信息,\n", " 影响大模型的响应速度,或是导致chat崩溃。\n", " 当前只保留导航结果每一步的距离、耗时和语义化信息。\n", " 公交路线规划情况比较多,尽量全部保留。\n", " \"\"\"\n", " if model == \"transit\":\n", " return result\n", " else:\n", " return filter_result(result)\n", "\n", " except httpx.HTTPError as e:\n", " raise Exception(f\"HTTP request failed: {str(e)}\") from e\n", " except KeyError as e:\n", " raise Exception(f\"Failed to parse reponse: {str(e)}\") from e\n", "\n", "\n", "@mcp.tool()\n", "async def map_weather(location: str, district_id: int, ctx: Context) -> dict:\n", " \"\"\"\n", " Name:\n", " 天气查询服务\n", "\n", " Description:\n", " 用户可通过行政区划或是经纬度坐标查询实时天气信息及未来5天天气预报\n", " (注意: 使用经纬度坐标需要高级权限)。\n", "\n", " Args:\n", " location: 经纬度,经度在前纬度在后,逗号分隔 (需要高级权限, 例如: 116.30815,40.056878)\n", " district_id: 行政区划 (例如: 1101010)\n", " \"\"\"\n", " try:\n", " # 获取API密钥\n", " if not api_key:\n", " raise Exception(\"Can not found API key.\")\n", "\n", " # 调用百度API\n", " url = f\"{api_url}/weather/v1/?\"\n", "\n", " # 设置请求参数\n", " # 更多参数信息请参考:https://lbs.baidu.com/faq/api?title=webapi/weather\n", " params = {\n", " \"ak\": f\"{api_key}\",\n", " \"data_type\": \"all\",\n", " \"from\": \"py_mcp\",\n", " }\n", "\n", " # 核心入参,二选一\n", " if not location:\n", " params[\"district_id\"] = f\"{district_id}\"\n", " else:\n", " params[\"location\"] = f\"{location}\"\n", "\n", " async with httpx.AsyncClient() as client:\n", " response = await client.get(url, params=params)\n", " response.raise_for_status()\n", " result = response.json()\n", "\n", " if result.get(\"status\") != 0:\n", " error_msg = result.get(\"message\", \"unkown error\")\n", " raise Exception(f\"API response error: {error_msg}\")\n", "\n", " return result\n", "\n", " except httpx.HTTPError as e:\n", " raise Exception(f\"HTTP request failed: {str(e)}\") from e\n", " except KeyError as e:\n", " raise Exception(f\"Failed to parse reponse: {str(e)}\") from e\n", "\n", "\n", "@mcp.tool()\n", "async def map_ip_location(\n", " # ip: str,\n", " ctx: Context,\n", ") -> dict:\n", " \"\"\"\n", " Name:\n", " IP定位服务\n", "\n", " Description:\n", " 根据用户请求的IP获取当前的位置,当需要知道用户当前位置、所在城市时可以调用该工具获取\n", "\n", " Args:\n", " \"\"\"\n", " try:\n", " # 获取API密钥\n", " if not api_key:\n", " raise Exception(\"Can not found API key.\")\n", "\n", " # 调用百度API\n", " url = f\"{api_url}/location/ip\"\n", "\n", " # 设置请求参数\n", " # 更多参数信息请参考:https://lbs.baidu.com/faq/api?title=webapi/ip-api\n", " params = {\n", " \"ak\": f\"{api_key}\",\n", " \"from\": \"py_mcp\",\n", " }\n", "\n", " async with httpx.AsyncClient() as client:\n", " response = await client.get(url, params=params)\n", " response.raise_for_status()\n", " result = response.json()\n", "\n", " if result.get(\"status\") != 0:\n", " error_msg = result.get(\"message\", \"unkown error\")\n", " raise Exception(f\"API response error: {error_msg}\")\n", "\n", " return result\n", "\n", " except httpx.HTTPError as e:\n", " raise Exception(f\"HTTP request failed: {str(e)}\") from e\n", " except KeyError as e:\n", " raise Exception(f\"Failed to parse reponse: {str(e)}\") from e\n", "\n", "\n", "@mcp.tool()\n", "async def map_road_traffic(\n", " model: str,\n", " road_name: str,\n", " city: str,\n", " bounds: str,\n", " vertexes: str,\n", " center: str,\n", " radius: int,\n", " ctx: Context,\n", ") -> dict:\n", " \"\"\"\n", " Name:\n", " 实时路况查询服务\n", "\n", " Description:\n", " 查询实时交通拥堵情况, 可通过指定道路名和区域形状(矩形, 多边形, 圆形)进行实时路况查询。\n", "\n", " 道路实时路况查询: 查询具体道路的实时拥堵评价和拥堵路段、拥堵距离、拥堵趋势等信息\n", " 矩形区域实时路况查询: 查询指定矩形地理范围的实时拥堵情况和各拥堵路段信息\n", " 多边形区域实时路况查询: 查询指定多边形地理范围的实时拥堵情况和各拥堵路段信息\n", " 圆形区域(周边)实时路况查询: 查询某中心点周边半径范围内的实时拥堵情况和各拥堵路段信息\n", "\n", " Args:\n", " model: 路况查询类型(road, bound, polygon, around)\n", " road_name: 道路名称和道路方向, model=road时必传 (如:朝阳路南向北)\n", " city: 城市名称或城市adcode, model=road时必传 (如:北京市)\n", " bounds: 区域左下角和右上角的经纬度坐标, model=bound时必传 (如:39.912078,116.464303;39.918276,116.475442)\n", " vertexes: 多边形区域的顶点经纬度, model=polygon时必传 (如:39.910528,116.472926;39.918276,116.475442;39.916671,116.459056;39.912078,116.464303)\n", " center: 圆形区域的中心点经纬度坐标, model=around时必传 (如:39.912078,116.464303)\n", " radius: 圆形区域的半径(米), 取值[1,1000], model=around时必传 (如:200)\n", " \"\"\"\n", " try:\n", " # 获取API密钥\n", " if not api_key:\n", " raise Exception(\"Can not found API key.\")\n", "\n", " # 调用百度API\n", " url = f\"{api_url}/traffic/v1/{model}?\"\n", "\n", " # 设置请求参数\n", " # 更多参数信息请参考:https://lbs.baidu.com/faq/api?title=webapi/traffic\n", " params = {\n", " \"ak\": f\"{api_key}\",\n", " \"output\": \"json\",\n", " \"from\": \"py_mcp\",\n", " }\n", "\n", " # 核心入参,根据model选择\n", " match model:\n", " case \"bound\":\n", " params[\"bounds\"] = f\"{bounds}\"\n", " case \"polygon\":\n", " params[\"vertexes\"] = f\"{vertexes}\"\n", " case \"around\":\n", " params[\"center\"] = f\"{center}\"\n", " params[\"radius\"] = f\"{radius}\"\n", " case \"road\":\n", " params[\"road_name\"] = f\"{road_name}\"\n", " params[\"city\"] = f\"{city}\"\n", " case _:\n", " pass\n", "\n", " async with httpx.AsyncClient() as client:\n", " response = await client.get(url, params=params)\n", " response.raise_for_status()\n", " result = response.json()\n", "\n", " if result.get(\"status\") != 0:\n", " error_msg = result.get(\"message\", \"unkown error\")\n", " raise Exception(f\"API response error: {error_msg}\")\n", "\n", " return result\n", "\n", " except httpx.HTTPError as e:\n", " raise Exception(f\"HTTP request failed: {str(e)}\") from e\n", " except KeyError as e:\n", " raise Exception(f\"Failed to parse reponse: {str(e)}\") from e\n", "\n", "\n", "@mcp.tool()\n", "async def map_poi_extract(text_content: str, ctx: Context) -> dict:\n", " \"\"\"\n", " Name:\n", " POI智能提取\n", "\n", " Description:\n", " 根据用户提供的文本描述信息, 智能提取出文本中所提及的POI相关信息.\n", " (注意: 使用该服务, api_key需要拥有对应的高级权限, 否则会报错)\n", "\n", " Args:\n", " text_content: 用于提取POI的文本描述信息 (完整的旅游路线,行程规划,景点推荐描述等文本内容,\n", " 例如: 新疆独库公路和塔里木湖太美了, 从独山子大峡谷到天山神秘大峡谷也是很不错的体验)\n", " \"\"\"\n", " # 关于高级权限使用的相关问题,请联系我们: https://lbsyun.baidu.com/apiconsole/fankui?typeOne=%E4%BA%A7%E5%93%81%E9%9C%80%E6%B1%82&typeTwo=%E9%AB%98%E7%BA%A7%E6%9C%8D%E5%8A%A1\n", " try:\n", " # 获取API密钥\n", " if not api_key:\n", " raise Exception(\"Can not found API key.\")\n", "\n", " # 调用POI智能提取的提交接口\n", " headers = {\"Content-Type\": \"application/x-www-form-urlencoded\"}\n", " submit_url = f\"{api_url}/api_mark/v1/submit\"\n", " result_url = f\"{api_url}/api_mark/v1/result\"\n", "\n", " # 设置上传用户描述的请求体\n", " submit_body = {\n", " \"ak\": f\"{api_key}\",\n", " \"id\": 0,\n", " \"msg_type\": \"text\",\n", " \"text_content\": f\"{text_content}\",\n", " \"from\": \"py_mcp\",\n", " }\n", "\n", " # 异步请求\n", " async with httpx.AsyncClient() as client:\n", " # 提交任务\n", " submit_resp = await client.post(\n", " submit_url, data=submit_body, headers=headers, timeout=10.0\n", " )\n", " submit_resp.raise_for_status()\n", " submit_result = submit_resp.json()\n", "\n", " if submit_result.get(\"status\") != 0:\n", " error_msg = submit_result.get(\"message\", \"unkown error\")\n", " raise Exception(f\"API response error: {error_msg}\")\n", "\n", " map_id = submit_result.get(\"result\", {}).get(\"map_id\")\n", " if not map_id:\n", " raise Exception(\"Can not found map_id\")\n", "\n", " # 轮询获取结果(最多5次,间隔2秒)\n", " result_body = {\n", " \"ak\": api_key,\n", " \"id\": 0,\n", " \"map_id\": map_id,\n", " \"from\": \"py_mcp\",\n", " }\n", " max_retries = 5\n", " for attempt in range(max_retries):\n", " result_resp = await client.post(\n", " result_url, data=result_body, headers=headers, timeout=10.0\n", " )\n", " result_resp.raise_for_status()\n", " result = result_resp.json()\n", "\n", " if result.get(\"status\") == 0 and result.get(\"result\"):\n", " return result\n", " elif attempt < max_retries - 1:\n", " await sleep(2)\n", "\n", " else:\n", " raise Exception(\"Timeout to get the result\")\n", "\n", " if result.get(\"status\") != 0:\n", " error_msg = result.get(\"message\", \"unkown error\")\n", " raise Exception(f\"API response error: {error_msg}\")\n", "\n", " except httpx.HTTPError as e:\n", " raise Exception(f\"HTTP request failed: {str(e)}\") from e\n", " except KeyError as e:\n", " raise Exception(f\"Failed to parse reponse: {str(e)}\") from e\n", "\n", "\n", "if __name__ == \"__main__\":\n", " mcp.run()" ] }, { "cell_type": "markdown", "id": "65f88222", "metadata": {}, "source": [ "#### (2)配置Appbuilder自主规划Agent文件\n", "\n", "- 将下述代码添加到本地`test.py`文件中,**注意替换其中的`APPBUILDER_TOKEN`和`app_id`为你自己的AppBuilder的API key和应用ID**" ] }, { "cell_type": "code", "execution_count": null, "id": "52ec5f33", "metadata": {}, "outputs": [], "source": [ "import os\n", "import asyncio\n", "import appbuilder\n", "from appbuilder.core.console.appbuilder_client.async_event_handler import (\n", " AsyncToolCallEventHandler,\n", ")\n", "from appbuilder.mcp_server.client import MCPClient\n", "\n", "# 用户Token\n", "os.environ[\"APPBUILDER_TOKEN\"] = \"bce-v3/ALTAK-mTvDIz1UXh1hXOXlPGhgZ/c248xxxxxxxxxxxxxxxxxxxxxxxx\" # 将APPBUILDER_TOKEN更换成自己AppBuilder API key\n", "os.environ[\"APP_ID\"] = \"f1cd13f4-fec7xxxxxxxxxxxxxxxxxxxxxxxx\" # 将app_id更换成自己的应用ID\n", "\n", "async def main():\n", " # 发布的应用ID\n", " app_id = os.environ[\"APP_ID\"]\n", " appbuilder_client = appbuilder.AsyncAppBuilderClient(app_id)\n", " mcp_client = MCPClient()\n", "\n", " # 注意这里的路径为MCP Server文件在本地的相对路径\n", " await mcp_client.connect_to_server(\"./map.py\")\n", " \n", " tools = mcp_client.tools\n", " event_handler = AsyncToolCallEventHandler(mcp_client, functions=[])\n", " conversation_id = await appbuilder_client.create_conversation()\n", " \n", " async with appbuilder_client.run_with_handler(\n", " conversation_id=conversation_id,\n", " query=\"我住在北京亮马河大厦,请帮我查询一下我当前的经纬度信息\",\n", " tools=tools,\n", " event_handler=event_handler,\n", " ) as run:\n", " await run.until_done()\n", " \n", " await appbuilder_client.http_client.session.close()\n", "\n", "if __name__ == \"__main__\":\n", " appbuilder.logger.setLoglevel(\"DEBUG\")\n", " loop = asyncio.get_event_loop()\n", " loop.run_until_complete(main())" ] }, { "cell_type": "markdown", "id": "5e6c0e92", "metadata": {}, "source": [ "### 9、运行代码文件\n", "\n", "在完成本地map.py文件和test.py文件内容更新后,在命令行中运行test.py,即可完成Agent的本地运行,控制台将呈现和上述结果一致的Agent运行结果" ] }, { "cell_type": "code", "execution_count": null, "id": "f0b632dc", "metadata": { "vscode": { "languageId": "shellscript" } }, "outputs": [], "source": [ "!python3 test.py" ] }, { "cell_type": "markdown", "id": "f02c8573", "metadata": {}, "source": [ "运行后,打印日志参考:\n", "```bash\n", "[2025-04-17 21:50:38,955.955] async_event_handler.py [line:563] DEBUG [main-11524059179509233548] Agent 非流式回答: 根据您的位置信息,北京亮马河大厦的经纬度为:**北纬39.95139408407192,东经116.47114501090634**。如果您有其他出行需求或问题,请随时告诉我,我会尽力为您提供帮助。\n", "DEBUG:appbuilder:Agent 非流式回答: 根据您的位置信息,北京亮马河大厦的经纬度为:**北纬39.95139408407192,东经116.47114501090634**。如果您有其他出行需求或问题,请随时告诉我,我会尽力为您提供帮助。\n", "```" ] }, { "cell_type": "markdown", "id": "5f694b20", "metadata": {}, "source": [ "## 常用指令\n", "\n", "* 现在上海中山公园附近堵车吗\n", "* 今天上海辰山植物园天气怎么样\n", "* 我住在北京亮马河大厦,请帮我规划北京赏花一日游\n", "* 从上海环球港,开车导航到同济大学四平路校区" ] } ], "metadata": { "kernelspec": { "display_name": "Python 3", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.12.10" } }, "nbformat": 4, "nbformat_minor": 5 } ================================================ FILE: cookbooks/mcp/client.ipynb ================================================ { "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# 前言-学习本项目你可以获得什么\n", "- 理论学习:了解MCP Client的基础知识\n", "- 上手实操:了解MCP Client的使用方式\n", "- 上手实操:通过MCP Client连接MCP Server,结合已有Agent,打造一个端云结合的进阶Agent。" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# 1. 项目背景\n", "### 1.1 什么是MCP\n", "[Model Context Protocol (MCP)](https://modelcontextprotocol.io/introduction)是Anthropic推出的一个开放协议,提供了一种将 AI 模型连接到不同数据源和工具的标准化方式,可实现应用与外部数据源和工具之间的无缝集成。\n", "\n", "MCP基础架构由以下几部分组成:\n", "- MCP Hosts: 希望通过 MCP 访问数据的程序,例如 Claude Desktop、IDE 或 AI 工具\n", "- MCP Clients: 与服务器保持 1:1 连接的协议客户端\n", "- MCP Servers: 通过MCP协议公开特定功能的程序\n", "- Local Data Sources: MCP协议可以安全访问的本机文件、数据库、服务等\n", "- Remote Services: MCP Server可以访问的远程服务\n", "\n", "其中MCP Server包含以下几类:\n", "- Resources: 上下文和数据,供用户或人工智能模型使用\n", "- Prompts: 为用户提供模板化的消息和工作流程\n", "- Tools: AI模型调用的工具,使模型能够与外部系统交互,例如查询数据库、调用 API 或执行计算\n", "\n", "MCP Server Tools有以下特征:\n", "- 每个工具都由名称唯一标识,并包含描述其架构的元数据\n", "- 被设计为模型控制的,这意味着语言模型可以根据其上下文理解和用户的提示自动发现和调用工具\n", "\n", "### 1.2 MCP Client\n", " Host 内部专门用于与 MCP Server 建立和维持一对一连接的模块。它负责按照 MCP 协议的规范发送请求、接收响应和处理数据。简单来说,MCP Client 是 Host 内部处理 RPC 通信的“代理”,专注于与一个 MCP Server 进行标准化的数据、工具或 prompt 的交换。\n", " \n", " MCP Client 更多是一个底层技术术语,是关于 MCP Server 连接到 MCP Host 的底层细节,不用过于区分 MCP Host 和 MCP Client。" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# 2. 基础操作-通过MCP Client连接Server\n", "## 2.1 stdio方式连接" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "【第一步】安装AppBuilder的环境依赖,在python>=3.12环境中,执行以下命令。Python环境准备可以参考教程:https://cloud.baidu.com/article/3421098" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "vscode": { "languageId": "shellscript" } }, "outputs": [], "source": [ "!python3 -m pip install appbuilder-sdk -i https://mirrors.aliyun.com/pypi/simple/\n", "!python3 -m pip install mcp -i https://mirrors.aliyun.com/pypi/simple/" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "【第二步】以[官方server](https://github.com/modelcontextprotocol/quickstart-resources/blob/main/weather-server-python/weather.py)为例。我们将server代码保存为`weather.py`。这个server包含`get_alerts', 'get_forecast',两个tool。\n", "\n", "再编写client脚本:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "import asyncio\n", "from appbuilder.mcp_server.client import MCPClient\n", "\n", "\n", "async def main():\n", " mcp_client = MCPClient()\n", " await mcp_client.connect_to_server(\"./weather.py\")\n", " print(mcp_client.tools)\n", "\n", "\n", "if __name__ == \"__main__\":\n", " loop = asyncio.get_event_loop()\n", " loop.run_until_complete(main())" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "运行后,打印日志参考:\n", "\n", "Connected to server with tools:['get_alerts', 'get_forecast']\n", "\n", "INFO:appbuilder:\n", "\n", "Connected to server with tools:['get_alerts', 'get_forecast']\n", "[Tool(name='get_alerts', description='Get weather alerts for a US state.\\n\\n Args:\\n state: Two-letter US state code (e.g. CA, NY)\\n ', inputSchema={'properties': {'state': {'title': 'State', 'type': 'string'}}, 'required': ['state'], 'title': 'get_alertsArguments', 'type': 'object'}), Tool(name='get_forecast', description='Get weather forecast for a location.\\n\\n Args:\\n latitude: Latitude of the location\\n longitude: Longitude of the location\\n ', inputSchema={'properties': {'latitude': {'title': 'Latitude', 'type': 'number'}, 'longitude': {'title': 'Longitude', 'type': 'number'}}, 'required': ['latitude', 'longitude'], 'title': 'get_forecastArguments', 'type': 'object'})]\n", "\n", "## 2.2 sse方式连接\n", "以AppBuilder百度搜索MCP Server为例,server地址`http://appbuilder.baidu.com/v2/ai_search/mcp/sse?api_key=Bearer+bce-v3/ALTAKxxx`, api_key为AppBuilder Token,格式参考URL中格式。" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "import asyncio\n", "from appbuilder.mcp_server.client import MCPClient\n", "\n", "\n", "async def main():\n", " client = MCPClient()\n", " await client.connect_to_server(service_url=service_url)\n", " print(client.tools)\n", "\n", "\n", "if __name__ == \"__main__\":\n", " service_url = \"http://appbuilder.baidu.com/v2/ai_search/mcp/sse?api_key=Bearer+bce-v3/ALTAKxxx\"\n", " loop = asyncio.get_event_loop()\n", " loop.run_until_complete(main())" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "运行后,打印日志参考:\n", "\n", "Connected to server with tools:['AIsearch']\n", "INFO:appbuilder:\n", "Connected to server with tools:['AIsearch']\n", "[Tool(name='AIsearch', description='\\n 执行搜索。\\n\\n Args:\\n query (str): 搜索请求。\\n stream (bool, optional): 是否以流的形式接收响应数据。默认为False。\\n instruction (Instruction, optional): 指令信息对象。默认为None。\\n model (str, optional): 模型名称。默认为None,表示使用当前实例的模型。\\n temperature (float, optional): 温度参数,控制生成文本的随机性。默认为1e-10。\\n top_p (float, optional): 累积概率阈值,用于控制生成文本的多样性。默认为1e-10。\\n search_top_k (int, optional): 搜索候选结果的数量。默认为4。\\n hide_corner_markers (bool, optional): 是否隐藏响应中的边界标记。默认为True。\\n\\n Returns:\\n Message: 处理后的信息对象。\\n\\n Raises:\\n AppBuilderServerException: 如果输入信息或指令过长,将抛出此异常。\\n ', inputSchema={'properties': {'query': {'title': 'query', 'type': 'string'}, 'stream': {'default': False, 'title': 'stream', 'type': 'string'}, 'instruction': {'default': None, 'title': 'instruction', 'type': 'string'}, 'model': {'default': None, 'title': 'model', 'type': 'string'}, 'temperature': {'default': 1e-10, 'title': 'temperature', 'type': 'string'}, 'top_p': {'default': 1e-10, 'title': 'top_p', 'type': 'string'}, 'search_top_k': {'default': 4, 'title': 'search_top_k', 'type': 'string'}, 'hide_corner_markers': {'default': True, 'title': 'hide_corner_markers', 'type': 'string'}, 'api_key': {'default': None, 'title': 'api_key', 'type': 'string'}}, 'required': ['query'], 'title': 'AIsearchArguments', 'type': 'object'})]" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# 3. 进阶操作-Agent 应用轻松调用海量开源 MCP Server,打造端云结合的进阶 Agent\n", "搭建一个“端云组件结合使用”的新闻检索 Agent :功能是,用户检索感兴趣的新闻,Agent 根据 query 进行检索,最终自动调用 Playwright 组件在本地打开浏览器,在mac上阅览。对比常规的Agent,区别是:\n", "\n", "* Before:Agent在聊天界面中展示新闻链接,提供总结信息\n", "* After:Agent在此基础上,还可以在本地的浏览器中自动打开指定的网页,进行本地操作\n", "为什么使用这个示例:\n", "\n", "该应用可以扩展为:用户询问需求后,Agent不仅思考并回答,还能操作用户的终端,帮助用户下订单、操作文件等等\n", "\n", "### 3.1 【第一步】:创建云端的Agent,作为基础的应用,步骤如下:\n", "* 打开AppBuilder官网:https://qianfan.cloud.baidu.com/appbuilder/ ,并登录\n", "![AppBuilder首页](./image/appbuilder_home.png)\n", "\n", "* 在左侧的边栏中,选择创一个【自主规划Agent】\n", "![创建自主规划Agent](./image/agent_create.png)\n", "\n", "* 使用【AI自动配置功能】生成一个自动配置好角色指令的Agent,Prompt可以是:【热点新闻阅读助手】\n", "![创建热点新闻阅读助手](./image/agent_config.png)\n", "\n", "* 可以调整该应用的组件,我们选择【百度AI搜索】作为提供网页url的来源,最终Agent界面长下面这个样子\n", "![热点新闻阅读助手](./image/agent_show.png)\n", "\n", "* 继续调整该组件,考虑到我们可能会多次思考,多次调用组件,所以,我们调整最大思考轮数\n", "![最大思考轮数](./image/agent_max_rounds.png)\n", "\n", "* 最后,点击右上角【发布】->【发布应用】,这样我们就可以在AB-SDK中调用该应用啦\n", "![发布应用](./image/agent_pub.png)\n", "\n", "\n", "### 3.2 【第二步】:下载一个可以控制本地浏览器的MCP-Server组件Playwright,步骤如下\n", "我们使用[Playwright](https://github.com/blackwhite084/playwright-plus-python-mcp/blob/master/src/playwright_server/server.py )作为MCP Server,直接保存该代码到本地可以执行的位置。\n", "![下载MCP Server](./image/playwright_download.png)\n", "\n", "\n", "### 3.3 【第三步】:使用AB-SDK访问我们的Agent,并且让它联动本地的MCP组件\n", "* 通过代码态访问我们刚创建的Agent,有以下几个依赖的配置,首先是【APP ID】,获取方式如下:\n", "![获取app_id](./image/app_get.png)\n", "* 然后是访问应用所需要的Token,获取方式如下:\n", "![获取Token](./image/token_get.png)\n", "* 创建Token时记得需要勾选我们刚才创建的【新闻小助手】应用\n", "![Token功能范围](./image/token_scope.png)\n", "* python >= 3.12 的环境中安装 【appbuilder-sdk】及相关MCP组件的依赖\n", "\n", "安装playwright支持的浏览器,该步骤由于网络原因,时间较长,约5-10min,可通过代理提速\n", "\n", "```bash\n", "python -m pip install appbuilder-sdk -i https://pypi.tuna.tsinghua.edu.cn/simple \n", "python -m pip install mcp -i https://pypi.tuna.tsinghua.edu.cn/simple\n", "python -m pip install playwright -i https://pypi.tuna.tsinghua.edu.cn/simple \n", "playwright install \n", "```\n", "\n", "* 有了【APP_ID】和【TOKEN】,并且在本地安装好上述依赖后,我们可以快速访问【新闻小助手应用】,搜索感兴趣的新闻,并在本地浏览器打开对应网页" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "import os\n", "import time\n", "import asyncio\n", "\n", "import appbuilder\n", "from appbuilder.core.console.appbuilder_client.async_event_handler import (\n", " AsyncToolCallEventHandler,\n", ")\n", "\n", "from appbuilder.mcp_server.client import MCPClient\n", "\n", "os.environ[\"APPBUILDER_TOKEN\"] = \"YOUR_APPBUILDER_TOKEN\"\n", "os.environ[\"APP_ID\"] = \"YOUR_APP_ID\"\n", "\n", "\n", "async def main():\n", " app_id = os.environ.get(\"APP_ID\")\n", " assert app_id is not None, \"APP_ID is not set\"\n", "\n", " appbuilder_client = appbuilder.AsyncAppBuilderClient(app_id)\n", " mcp_client = MCPClient()\n", " # server.py 是上述步骤中下载的mcp组件文件\n", " await mcp_client.connect_to_server(\"./server.py\")\n", "\n", " tools = mcp_client.tools\n", " event_handler = AsyncToolCallEventHandler(mcp_client, functions=[])\n", " conversation_id = await appbuilder_client.create_conversation()\n", " with await appbuilder_client.run_with_handler(\n", " conversation_id=conversation_id,\n", " query=\"先搜索关于文心一言4.5模型的新闻,取出其中一个url,再用playwright_navigate打开这个url\",\n", " tools=tools,\n", " event_handler=event_handler,\n", " ) as run:\n", " await run.until_done()\n", "\n", " print(\"浏览网页,我们在此稍作停留,您可通过其他方式常驻该进程以保持网页\")\n", " time.sleep(5)\n", " await appbuilder_client.http_client.session.close()\n", "\n", "\n", "if __name__ == \"__main__\":\n", " appbuilder.logger.setLoglevel(\"DEBUG\")\n", " loop = asyncio.get_event_loop()\n", " loop.run_until_complete(main())" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "* 在终端执行上述代码\n", "\n", "**效果展示**\n", "\n", "![大模型结果](./image/llm_answer.png)\n", "\n", "* 界面效果\n", " * 自动启动了一个chrome浏览器,并打开了我们搜索到的网页\n", "![playwright结果](./image/playwright_result.png)" ] } ], "metadata": { "language_info": { "name": "python" } }, "nbformat": 4, "nbformat_minor": 2 } ================================================ FILE: cookbooks/mcp/knowledge_base_mcp_server.ipynb ================================================ { "cells": [ { "cell_type": "markdown", "id": "8ce67390", "metadata": {}, "source": [ "# 前言\n", "通过本文,你可以:\n", " * 了解AppBuilder KnowledgeBase MCP Server是什么\n", " * 了解如何通过AppBuilder-SDK调用AppBuilder KnowledgeBase MCP Server\n", " * 了解如何通过Cursor调用AppBuilder KnowledgeBase MCP Server\n", "\n", "如果你需要了解更多关于AppBuilder结合MCP生态的功能,可跳转到下面的文档:\n", "- 主动调用:通过AppBuilder-Agent调用MCP Server\n", " - 代码态调用:[AppBuilder结合端云组件,调用本地MCP Server](./client.ipynb) \n", " - 代码态调用:[AppBuilder结合地图MCP Server,实现智能导航](./baidu_map.ipynb)\n", " - 零代码态调用:[AppBuilder控制台使用MCP](https://cloud.baidu.com/doc/AppBuilder/s/Nm9vmpb3g)\n", "- 被动调用:AppBuilder能力,融入MCP生态,可作为MCP Server提供能力\n", " - 组件能力:[AppBuilder组件转MCP Server](./server.ipynb)\n", " - 智能体能力:[AppBuilder Agent MCP Server](./app_mcp_server.ipynb)\n", " - AI搜索能力: [AppBuilder AI搜索MCP Server](https://github.com/baidubce/app-builder/tree/master/python/mcp_server/ai_search)\n", " - RAG能力:[AppBuilder知识库MCP Server](./knowledge_base_mcp_server.ipynb)\n", "\n", "\n", "## AppBuilder Agent MCP Server简介\n", "千帆AppBuilder提供了关于AppBuilder知识库的MCP Server,用户可通过MCP协议调用在AppBuilder中的知识库。当前包括以下能力:\n", "- 创建知识库\n", "- 获取知识库详情\n", "- 获取知识库列表\n", "- 知识库检索\n", "- 上传知识库文档\n", "- 获取文档列表\n", "\n", "对于入门用户,还提供了环境配置、 api key获取等操作步骤。已熟悉用户可以直接跳过环境配置、api_key获取部分。\n", "\n", "## 安装配置步骤\n", "\n", "### 配置基础环境\n", "\n", "#### 1、安装Python\n", "\n", "大部分的MCP Server,例如Unity和Blender,都是Python SDK\n", "安装Python最简单的方法是安装Miniconda\n", "**注意:请确保安装的python>=3.12**\n", "\n", "[Miniconda官网](https://www.anaconda.com/docs/getting-started/miniconda/install)\n", "\n", "#### 2、下载Appbuilder-SDK\n", "\n", "为了实现Appbuilder-SDK对AppBuilder Agent MCP Server的代码态调用,需要在conda环境下载appbuilder-sdk包\n" ] }, { "cell_type": "code", "execution_count": null, "id": "96a39a88", "metadata": { "vscode": { "languageId": "shellscript" } }, "outputs": [], "source": [ "!python3 -m pip install httpx appbuilder-sdk mcp" ] }, { "cell_type": "markdown", "id": "6e7d417d", "metadata": {}, "source": [ "\n", "## 获取千帆AppBuilder API key\n", "\n", "### 1、进入百度智能云千帆AppBuilder主页\n", "\n", "进入百度智能云千帆AppBuilder主页,免费试用\n", "\n", "- [百度智能云千帆AppBuilder主页](https://qianfan.cloud.baidu.com/appbuilder)\n", "\n", "\n", "### 7、创建Appbuilder API key\n", "\n", "- [Appbuilder API key授权](https://cloud.baidu.com/doc/AppBuilder/s/lm68r8e6i)\n", "\n", "- [Appbuilder API 控制台管理中心](https://console.bce.baidu.com/iam/#/iam/apikey/list)\n", "\n", "在【API Key】界面中,创建一个新的Key,并添加知识库的读写权限,记下来。\n", "\n", "![](https://bj.bcebos.com/v1/appbuilder-sdk-components/%E5%88%9B%E5%BB%BAAPPBUILDER-TOKEN.png?authorization=bce-auth-v1%2FALTAKGa8m4qCUasgoljdEDAzLm%2F2025-04-17T14%3A49%3A27Z%2F-1%2Fhost%2F9266ac8c93a262d2905811877d680f53af26668a0ee09e1b3a61c0b721de253c)\n", "\n", "![api_key_knowledgebase](./image/api_key_knowledgebase.png)" ] }, { "cell_type": "markdown", "id": "3aa3c0a2", "metadata": {}, "source": [ "## 使用AppBuilder SDK调用" ] }, { "cell_type": "code", "execution_count": null, "id": "3e7b9a90", "metadata": {}, "outputs": [], "source": [ "import asyncio\n", "import json\n", "import io\n", "import os\n", "import appbuilder\n", "from appbuilder.mcp_server.client import MCPClient\n", "\n", "os.environ[\"APPBUILDER_TOKEN\"] = \"YOUR_APPBUILDER_TOKEN\"\n", "\n", "async def main():\n", " mcp_client = MCPClient()\n", " await mcp_client.connect_to_server(service_url=service_url)\n", "\n", " # 创建知识库\n", " result = await mcp_client.call_tool(\n", " \"create_knowledge_base\",\n", " {\"name\": \"mcp测试可删\", \"description\": \"mcp测试,可删\"},\n", " )\n", " knowledge_base_info = json.loads(result.content[0].text)\n", " knowledge_base_id = knowledge_base_info.get(\"id\")\n", " assert knowledge_base_id is not None\n", " appbuilder.logger.debug(f\"create knowledge base success: {knowledge_base_id}\")\n", "\n", " # 获取知识库详情\n", " result = await mcp_client.call_tool(\n", " \"describe_knowledge_base\",\n", " {\"id\": knowledge_base_id},\n", " )\n", " knowledge_base_info = json.loads(result.content[0].text)\n", " knowledge_base_id = knowledge_base_info.get(\"id\")\n", " assert knowledge_base_id is not None\n", " appbuilder.logger.debug(f\"describe knowledge base success: {knowledge_base_id}\")\n", "\n", " # 获取知识库列表\n", " result = await mcp_client.call_tool(\n", " \"list_knowledge_bases\",\n", " {\"max_keys\": 10},\n", " )\n", " assert len(result.content) == 10\n", " appbuilder.logger.debug(f\"list knowledge bases success: {len(result.content)}\")\n", "\n", " # 上传文档到知识库\n", " file_content = \"这里是你的文件内容字符串\"\n", " with io.BytesIO(file_content.encode(\"utf-8\")) as f:\n", " result = await mcp_client.call_tool(\n", " \"upload_document\",\n", " {\"id\": knowledge_base_id, \"file_data\": f, \"file_name\": \"test.txt\"},\n", " )\n", " document_info = json.loads(result.content[0].text)\n", "\n", " document_id = document_info.get(\"documentId\")\n", " assert document_id is not None\n", " appbuilder.logger.debug(f\"upload document success: {document_id}\")\n", "\n", " # 获取文档列表\n", " result = await mcp_client.call_tool(\n", " \"list_documents\",\n", " {\"id\": knowledge_base_id},\n", " )\n", " appbuilder.logger.debug(f\"list documents base success: {knowledge_base_id}\")\n", "\n", " # 检索知识库\n", " result = await mcp_client.call_tool(\n", " \"query_knowledge_base\",\n", " {\"query\": \"分子\", \"id_list\": [knowledge_base_id]},\n", " )\n", " assert result.content[0].text is not None\n", " appbuilder.logger.debug(\"query knowledge base success\")\n", "\n", "\n", "if __name__ == \"__main__\":\n", " appbuilder.logger.setLoglevel(\"DEBUG\")\n", " service_url = (\n", " \"http://appbuilder.baidu.com/v2/ai_search/mcp/sse?api_key=\"\n", " + os.environ.get(\"APPBUILDER_TOKEN\")\n", " )\n", "\n", " loop = asyncio.get_event_loop()\n", " loop.run_until_complete(main())" ] }, { "cell_type": "markdown", "id": "df473bce", "metadata": {}, "source": [ "用户选择其中需要的功能进行执行,比如创建知识库,打印如下:\n", "\n", "```\n", "DEBUG:appbuilder:create knowledge base success: 909*****-***a-****-****-*********2c93\n", "```" ] }, { "cell_type": "markdown", "id": "6b68c4d6", "metadata": {}, "source": [ "## 使用Cursor调用\n", "### Cursor配置\n", "api_key=上面步骤获取到的api key,格式为\"bce-v3/ALTAK...\"" ] }, { "cell_type": "code", "execution_count": null, "id": "8b292ee1", "metadata": { "vscode": { "languageId": "json" } }, "outputs": [], "source": [ "{\n", " \"mcpServers\": {\n", " \"AppBuilder RAG\": {\n", " \"url\": \"http://appbuilder.baidu.com/v2/knowledgeBase/mcp/sse?api_key=bce-v3/ALTAK...\"\n", " }\n", " }\n", "}" ] }, { "cell_type": "markdown", "id": "804d655d", "metadata": {}, "source": [ "配置后,在Cursor设置页面可看到`create_knowledge_base`、`describe_knowledge_base`、`list_knowledge_bases`、`query_knowledge_base`、`upload_document`、`list_documents` 6个Tool。\n", "![cursor config](./image/cursor_knowledgebase_config.png)\n", "\n", "### 调用\n", "![cursor knowledgebase](./image/cursor_knowledgebase_test.png)" ] } ], "metadata": { "kernelspec": { "display_name": "Python 3", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.12.10" } }, "nbformat": 4, "nbformat_minor": 5 } ================================================ FILE: cookbooks/mcp/server.ipynb ================================================ { "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# 前言-学习本项目你可以获得什么\n", "- 理论学习:了解MCP Server的基础知识\n", "- 上手实操:入门MCP Server的使用方式\n", "- 上手实操:将AppBuilder组件转换为MCP Server tool,并在client中使用" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# 1. 项目背景\n", "### 1.1 什么是MCP Server Tool\n", "[Model Context Protocol (MCP)](https://modelcontextprotocol.io/introduction)是Anthropic推出的一个开放协议,提供了一种将 AI 模型连接到不同数据源和工具的标准化方式,可实现应用与外部数据源和工具之间的无缝集成。\n", "\n", "MCP基础架构由以下几部分组成:\n", "- MCP Hosts: 希望通过 MCP 访问数据的程序,例如 Claude Desktop、IDE 或 AI 工具\n", "- MCP Clients: 与服务器保持 1:1 连接的协议客户端\n", "- MCP Servers: 通过MCP协议公开特定功能的程序\n", "- Local Data Sources: MCP协议可以安全访问的本机文件、数据库、服务等\n", "- Remote Services: MCP Server可以访问的远程服务\n", "\n", "其中MCP Server包含以下几类:\n", "- Resources: 上下文和数据,供用户或人工智能模型使用\n", "- Prompts: 为用户提供模板化的消息和工作流程\n", "- Tools: AI模型调用的工具,使模型能够与外部系统交互,例如查询数据库、调用 API 或执行计算\n", "\n", "MCP Server Tools有以下特征:\n", "- 每个工具都由名称唯一标识,并包含描述其架构的元数据\n", "- 被设计为模型控制的,这意味着语言模型可以根据其上下文理解和用户的提示自动发现和调用工具\n", "\n", "MCP Server Tool 示例:\n", "- MCP quick-start server: [weather server](https://modelcontextprotocol.io/quickstart/server)\n", "- MCP example servers: [example servers](https://modelcontextprotocol.io/examples)\n", "\n", "\n", "### 1.2 什么是AppBuilder组件\n", "SDK提供了40+个源于百度生态的优质组件,列表可见[组件列表](https://cloud.baidu.com/doc/AppBuilder/s/Glqb6dfiz#3%E3%80%81%E5%BC%80%E9%80%9A%E7%BB%84%E4%BB%B6%E6%9C%8D%E5%8A%A1), 调用前需要申领[免费试用额度](https://console.bce.baidu.com/ai-engine/old/#/ai/ocr/overview/resource/list)\n", "\n", "目前支持转换为MCP Server Tool的组件包括:\n", "| 组件名称 | 组件描述 |\n", "| --- | --- |\n", "| AnimalRecognition | 动物识别,可用于识别一张图片,即对于输入的一张图片(可正常解码,且长宽比较合适),输出动物识别结果。 |\n", "| ImageUnderstand | 图像内容理解,输出理解图片后的文本信息。 |\n", "| Translation | 文本翻译组件,提供多种语言互译的在线文本翻译服务。支持术语定制功能,用户可对翻译结果进行干预,快速提高翻译质量。可广泛应用于移动端、PC网站、智能硬件等不同产品形态中,满足多领域、多场景的翻译需求。 |\n", "| GeneralOCR | 通用文字识别组件,支持多场景、多语种、高精度的文字识别服务,对图片全部文字内容进行检测识别。 |\n", "| StyleRewrite | 风格转写组件,可以基于生成式大模型对文本的风格进行改写。支持多种文本风格,包括营销、客服、直播、激励及教学话术。 |\n", "| HallucinationDetection | 幻觉检测,针对问答场景,检测答案中是否存在幻觉。 |\n", "| QRcodeOCR | 二维码识别,可对图片中的二维码、条形码进行检测和识别,返回存储的文字信息及其位置信息。 |\n", "| HandwriteOCR | 手写文字识别,图片中的手写中文、手写数字进行检测和识别,针对不规则的手写字体进行专项优化,识别准确率可达90%以上。 |\n", "| MixCardOCR | 身份证混贴识别,身份证混贴识别支持自动检测与识别身份证正反面在同一张图片上的场景,一次识别图片中身份证正反面所有字段。 |\n", "| TableOCR | 表格文字识别,可支持识别图片中的表格内容,返回各表格的表头表尾内容、单元格文字内容及其行列位置信息,全面覆盖各类表格样式,包括常规有线表格、无线表格、含合并单元格表格。同时,支持多表格内容识别。 |\n", "| Text2Image | 文生图(AI作画-高级版),基于文心大模型,可以根据用户输入的文本,自动创作不限定风格的图,为内容创作者提供灵感和高质量配图。 |\n", "| StyleWriting | 风格写作组件,是一款基于生成式大模型进行文本创作的工具,支持多种风格,包括B站、小红书等,适用于编写文案、广告等多种场景。 |\n", "| TreeMind | 树图,提供智能思维导图制作工具和丰富的模板,支持脑图、逻辑图、树形图、鱼骨图、组织架构图、时间轴、时间线等多种专业格式。 |\n", "| ASR | 短语音识别,可以将音频流实时识别为文字,并返回每句话的开始和结束时间,适用于手机语音输入、语音搜索、人机对话等语音交互场景。 |\n", "| ObjectRecognition | 通用物体和场景识别组件,可以识别超过10万类常见物体和场景,接口返回大类及细分类的名称。广泛适用于图像或视频内容分析、拍照识图等业务场景 |\n", "| SimilarQuestion | 相似问生成组件,可以基于输入的问题,挖掘出与该问题相关的类似问题。广泛用于客服、问答等场景。 |\n", "| OralQueryGeneration | 口语化Query生成组件,可以基于输入文本生成与文档内容相关的Query。可用于增强文档索引等场景。 |\n", "| PlantRecognition | 植物识别,即对于输入的一张图片(可正常解码,且长宽比较合适),输出植物识别结果。 |\n", "\n", "即实现在appbuilder.core.components.v2目录下的组件。后续会逐步支持将所有的组件转化为MCP Server Tool。" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# 2. 项目介绍-将AppBuilder组件转换为MCP Server Tool\n", "\n", "### 目标:\n", "\n", "在Cursor里自定义个人专属办公工具 —— 用户自己可将AppBuilder官方提供的“文本翻译-通用版”、“植物识别”等组件转化为MCP Server,在Cursor中作为自定义工具直接调用。\n", "\n", "### 为什么使用这个案例?\n", "\n", "- AppBuilder有很多优质的组件,可以在Claude客户端、Cursor中通过MCP的方式联动 \n", "- 通过这种模式,未来可以支持用户把自己在AB上开发的工作流/Agent集成到本地支持MCP协议的Client中直接使用 \n", "- MCP协议提供两种方式定义server:low-level server 和 FastMCP server。其中low-level是基础接口,FastMCP是高级封装,是 MCP 协议的核心接口。它处理连接管理、协议合规性和消息路由。 \n", "\n", "下面提供一个使用FastMCP定义自己的MCP Server Tool的简单示例:\n", "\n", "【第一步】安装AppBuilder的环境依赖,在python>=3.12环境中,执行以下命令。Python环境准备可以参考教程:https://cloud.baidu.com/article/3421098" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "vscode": { "languageId": "shellscript" } }, "outputs": [], "source": [ "!python3 -m pip install appbuilder-sdk -i https://mirrors.aliyun.com/pypi/simple/\n", "!python3 -m pip install mcp -i https://mirrors.aliyun.com/pypi/simple/" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "【第二步】我们可以快速将 AppBuilder 中的官方组件“文本翻译-通用版”、“植物识别”转换为 MCP Server 工具,该文件我们命名为 server.py" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "\n", "\"\"\"server.py\"\"\"\n", "\n", "import os\n", "from appbuilder.mcp_server.server import MCPComponentServer\n", "from appbuilder.core.components.v2 import Translation, PlantRecognition\n", "\n", "#设置APPBUILDER_TOKEN\n", "os.environ['APPBUILDER_TOKEN'] = '你的APPBUILDER_TOKEN'\n", "\n", "# 定义server\n", "server = MCPComponentServer(name=\"AB Component Server\")\n", "\n", "# 初始化组件实例\n", "translation = Translation()\n", "plant_recognition = PlantRecognition()\n", "\n", "# 把组件作为tool添加到server\n", "server.add_component(translation)\n", "server.add_component(plant_recognition)\n", "\n", "# 启动server\n", "server.run()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "注意:请将secret_key替换为你的APPBUILDER_TOKEN,Token获取方式见文档:https://cloud.baidu.com/doc/AppBuilder/s/lm68r8e6i\n", "\n", "【第三步】在Cursor中配置自己的server:https://docs.cursor.com/context/model-context-protocol ,根据指引填写MCP配置文件,指向我们第二步中创建的server.py,配置MCP Server。" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "vscode": { "languageId": "json" } }, "outputs": [], "source": [ "\n", "{\n", " \"mcpServers\": {\n", " \"AB component\": {\n", " \"command\": \"/abs/path/to/python\", # python解释器的绝对路径\n", " \"args\": [\n", " \"/abs/path/to/server.py\" # server.py的绝对路径\n", " ]\n", " }\n", " }\n", "}" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "python解释器的路径,可以在终端中输入以下命令进行查看:" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "vscode": { "languageId": "shellscript" } }, "outputs": [], "source": [ "\n", "# mac / linux\n", "which python\n", "\n", "# windows\n", "where python" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "【第四步】配置完成后,我们刷新MCP Servers配置,这时候可看到在本地部署好的 AppBuilder 官方组件工具。\n", "\n", "![cursor server tool配置](./image/cursor_list_tool.png)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "**效果展示**:\n", "\n", "【示例一】在Cursor的Chat对话框里,我们输入query" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "vscode": { "languageId": "shellscript" } }, "outputs": [], "source": [ "把“你好,中国”翻译成英文" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Cursor识别需要调用的工具,并请求权限:\n", "![请求权限](./image/cursor_run_tool.jpg)\n", "\n", "点击\"Run tool\"执行工具。\n", "\n", "成功调用“文本翻译”工具,并展示组件的输入输出以及最终回复答案\n", "![调用工具](./image/cursor_call_translation_result.jpg)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "【示例二】输入query" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "vscode": { "languageId": "shellscript" } }, "outputs": [], "source": [ "识别 https://img.dutenews.com/a/10001/202111/50120fcde5bb6f9c950758c6d77b656f.png 中的植物" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Cursor能够成功调用“植物识别”工具,并展示组件的输入输出,最终回复答案“根据植物识别模型的分析结果,这张图片中的植物是杨树,识别的置信度为55.7%”。\n", "\n", "![调用植物识别工具](./image/cursor_call_plantrec.jpg)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "注:Cursor可能存在思考工具调用参数错误的幻觉,如在正确的调用参数之上再封装一层\"kwargs\"。我们已完成对该幻觉问题的兼容,功能将会在1.0.6版本中上线。" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# 4. 项目总结\n", "\n", "本项目主要:\n", "- 介绍了MCP协议及Server的概念和使用方式\n", "- 介绍了如何定义MCP Server tool\n", "- 如何将AppBuilder组件转换为MCP Server tool\n", "- 最后使用Claude客户端展示了AppBuilder组件作为MCP Server Tool的使用效果。" ] } ], "metadata": { "language_info": { "name": "python" } }, "nbformat": 4, "nbformat_minor": 2 } ================================================ FILE: cookbooks/pipeline/assistant.ipynb ================================================ { "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# Assistant\n", "\n", "本文档描述 Assistants API 中 与 Assistant 相关函数调用" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 环境准备\n", "\n", "首先需要安装AppBuilder-SDK代码库,若已在开发环境安装,则可跳过此步。\n", "\n", "**注意:**: appbuilder-sdk 的python版本要求 3.9+,安装的SDK version >= 0.7.0" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "vscode": { "languageId": "shellscript" } }, "outputs": [], "source": [ "!python3 -m pip install appbuilder-sdk" ] }, { "cell_type": "code", "execution_count": 2, "metadata": {}, "outputs": [], "source": [ "import os\n", "import appbuilder\n", "\n", "# 配置你的密钥,主要在这之前需要首先申请Assistant API的内测资格\n", "os.environ[\"APPBUILDER_TOKEN\"] = \"your_appbuilder_token\"" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Assistant相关函数\n", "\n", "### 创建Assistant\n", "\n", "#### 功能介绍\n", "\n", "创建一个Assistant" ] }, { "cell_type": "code", "execution_count": 4, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "id='asst_63ab25b82a7649d5a763415e978c4f01' object='assistant' name='测试' description='test' instructions='你是百度制作的AI助手' tools=[] created_at=1717645100200 thought_instructions='' chat_instructions='' response_format= file_ids=[] metadata={'key': 'value'}\n" ] } ], "source": [ "\n", "assistant = appbuilder.assistant.assistants.create(\n", " model = \"ERNIE-4.0T-8K\",\n", " name=\"测试\",\n", " description=\"test\",\n", " metadata={\n", " \"key\": \"value\",\n", " }\n", " )\n", "\n", "# 打印创建的assistant\n", "print(assistant)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### 修改Assistant\n", "\n", "#### 功能介绍\n", "\n", "根据assistant_id修改一个已创建的Assistant" ] }, { "cell_type": "code", "execution_count": 5, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "id='asst_63ab25b82a7649d5a763415e978c4f01' model='DeepSeek-V3.1' name='更新Assistants' description='test' response_format= instructions='' created_at=1717645100200 thought_instructions='' chat_instructions='' tools=[] file_ids=[] metadata={'key': 'value'}\n" ] } ], "source": [ "# 更新已经创建的āssistant的信息\n", "appbuilder_update=appbuilder.assistant.assistants.update(\n", " assistant_id = assistant.id,# 已经创建的Assistant ID\n", " model=\"ERNIE-4.0T-8K\",\n", " name=\"更新Assistants\",\n", " description = \"test\"\n", ")\n", "\n", "# 获取更新后的assistant信息 \n", "print(appbuilder_update)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### 查询assistant列表\n", "\n", "#### 功能介绍\n", "\n", "查询当前用户已创建的assistant列表" ] }, { "cell_type": "code", "execution_count": 6, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "id='asst_c16bd73ab73d499387b2bfd8146cfb0a' object='assistant' name='python程序设计助教' description='幽默讲解Python基础。' instructions='### 角色与目标\\n**你是Python入门导师**,专门为初学者讲授Python编程知识。你的目标是引导学生掌握Python语言基础,包括语言概述、变量、表达式、基本和组合数据类型、控制结构语句、函数定义与调用、标准库和第三方库的使用、异常处理和文件读写,并通过实际案例帮助学生加深理解。\\n### 指导原则\\n1. **教育性**:确保教学内容准确、系统,能够帮助学生建立扎实的编程基础。\\n2. **实践性**:结合日常案例,让学生能够将理论知识应用于实际。\\n3. **易懂性**:用幽默风趣、简洁明了的语言解释概念,降低初学者的学习难度。\\n### 限制\\n* 避免涉及过于复杂的编程技巧和高级话题,确保内容适合初学者。\\n* 不轻易提供具体的编程作业答案,而是引导学生自己思考和解决问题。但如果学生始终解决不了问题,也可以提供正确答案。\\n### 澄清\\n* 你的教学内容主要围绕Python编程的基础知识和实践应用。\\n* 你会通过案例和实例来帮助学生理解和掌握Python编程的基本概念。\\n### 个性化\\n你以幽默风趣的教学风格著称,能够将枯燥的编程知识以生动有趣的方式呈现出来。你对学生充满耐心,总是乐于解答他们的疑问,并引导他们逐步成长为编程小能手。' tools=[] created_at=1717645108134 thought_instructions='' chat_instructions='' response_format= file_ids=[] metadata=None\n", "id='asst_63ab25b82a7649d5a763415e978c4f01' object='assistant' name='更新Assistants' description='test' instructions='' tools=[] created_at=1717645100200 thought_instructions='' chat_instructions='' response_format= file_ids=[] metadata={'key': 'value'}\n", "id='asst_4d865b80be684b8aa2a1e37c625ba476' object='assistant' name='原神内鬼消息爆料' description='舅舅永垂不朽' instructions='' tools=[] created_at=1717645054395 thought_instructions='' chat_instructions='' response_format= file_ids=[] metadata=None\n", "id='asst_3371b90537414828bb85e32c49161ba0' object='assistant' name='严谨文案助手' description='严谨文案的秘书Agent' instructions='' tools=[] created_at=1717644994838 thought_instructions='' chat_instructions='' response_format= file_ids=[] metadata=None\n", "id='asst_da1b2ad23e9e4da4ab5a45203f849c71' object='assistant' name='严谨文案助手' description='严谨文案的秘书Agent' instructions='作为秘书Agent,你的主要职责是协助处理文案工作,确保文字表达的严谨性,同时提供有效的行政支持。' tools=[] created_at=1717644990269 thought_instructions='在处理文案任务时,应特别注重文字的逻辑性、准确性和严谨性。当遇到不确定的表述或需要深入研究的内容时,务必进行充分的核实和查证,以确保最终输出的文案质量。' chat_instructions='回复用户时,请使用严谨、正式的语言风格,避免使用口语化或随意的表达方式。在提供文案建议或修改意见时,要详细阐述修改理由,以便用户更好地理解。' response_format= file_ids=[] metadata=None\n", "id='asst_a56ad90640114d17a5aaad0b22d330d8' object='assistant' name='朋友圈优化助手' description='你好,我是你的朋友圈优化助手。我会把你的朋友圈文案变得更吸引人,引发更多互动。请告诉我你需要优化的文案吧。' instructions='' tools=[] created_at=1717644978845 thought_instructions='' chat_instructions='' response_format= file_ids=[] metadata=None\n", "id='asst_7302428c9a2840efa192eff12ce15d6d' object='assistant' name='python程序设计助教' description='幽默讲解Python基础。' instructions='### 角色与目标\\n**你是Python入门导师**,专门为初学者讲授Python编程知识。你的目标是引导学生掌握Python语言基础,包括语言概述、变量、表达式、基本和组合数据类型、控制流语句、函数定义与调用、异常处理和文件读写,并通过实际案例帮助学生加深理解。\\n### 指导原则\\n1. **教育性**:确保教学内容准确、系统,能够帮助学生建立扎实的编程基础。\\n2. **实践性**:结合日常案例,让学生能够将理论知识应用于实际。\\n3. **易懂性**:用幽默风趣、简洁明了的语言解释概念,降低初学者的学习难度。\\n### 限制\\n* 避免涉及过于复杂的编程技巧和高级话题,确保内容适合初学者。\\n* 不提供具体的编程作业答案,而是引导学生自己思考和解决问题。\\n### 澄清\\n* 你的教学内容主要围绕Python编程的基础知识和实践应用。\\n* 你会通过案例和实例来帮助学生理解和掌握Python编程的基本概念。\\n### 个性化\\n你以幽默风趣的教学风格著称,能够将枯燥的编程知识以生动有趣的方式呈现出来。你对学生充满耐心,总是乐于解答他们的疑问,并引导他们逐步成长为编程小能手。' tools=[] created_at=1717644940885 thought_instructions='' chat_instructions='' response_format= file_ids=[] metadata=None\n", "id='asst_42d9cbd188f7416d8c77dad839d45bf8' object='assistant' name='低代码升级777' description='你好,欢迎来到低代码升级1~' instructions='' tools=[] created_at=1717644917557 thought_instructions='' chat_instructions='' response_format= file_ids=[] metadata=None\n", "id='asst_532c0240d3f248b78d4c334da93698c0' object='assistant' name='低代码升级777' description='你好,欢迎来到低代码升级1~' instructions='' tools=[] created_at=1717644917069 thought_instructions='' chat_instructions='' response_format= file_ids=[] metadata=None\n", "id='asst_9c9ea21b1fba4767b2fbfbbd34993d84' object='assistant' name='动物管理员2' description='嘿,你好啊!我是动物百事通,对各种动物的生活习性和饮食习惯都了如指掌。如果你对动物有任何疑问或者想了解更多关于它们的信息,都可以来问我哦!' instructions='### 角色与目标\\n**动物园管理员**是你现在的身份,你熟知每一种动物的生活习性以及它们的饮食习惯。你的目标是利用这些专业知识,为动物园的动物们提供最佳的照顾,同时向游客普及动物知识,提升他们对动物保护的意识。\\n### 指导原则\\n1. **专业性**:确保你对动物的管理和照顾都基于专业的动物学知识和实践经验。\\n2. **细心与耐心**:在观察动物行为和解答游客问题时,展现出你的细心和耐心。\\n3. **教育与宣传**:抓住与游客交流的机会,积极宣传动物保护的重要性和方法。\\n### 限制\\n* 你不具备医学诊断能力,对于动物出现的健康问题,应建议联系专业兽医进行检查和治疗。\\n* 对于涉及动物园内部管理和决策的问题,你可能无法直接回答或处理。\\n### 澄清\\n* 你可以回答关于动物生活习性、饮食习惯、栖息地环境等方面的问题。\\n* 你可以提供动物照顾和管理的建议,但具体实施可能需要根据动物园的实际情况进行调整。\\n### 个性化\\n作为一位动物园管理员,你热爱大自然和所有生物,尤其对那些你照顾的动物们有着深厚的感情。你总是面带微笑,对每一位游客都热情友好,愿意与他们分享你的知识和经验。同时,你也非常重视动物福利,致力于为动物们创造一个舒适、安全的家。' tools=[] created_at=1717644916619 thought_instructions='' chat_instructions='' response_format= file_ids=[] metadata=None\n", "id='asst_5b9334ea24e7489a9e1c6855d9c4fe13' object='assistant' name='低代码升级777' description='你好,欢迎来到低代码升级1~' instructions='' tools=[] created_at=1717644913010 thought_instructions='' chat_instructions='' response_format= file_ids=[] metadata=None\n", "id='asst_7bbb3cae27c54e5a9e5b61ff7863997e' object='assistant' name='低代码升级777' description='你好,欢迎来到低代码升级1~' instructions='' tools=[] created_at=1717644912554 thought_instructions='' chat_instructions='' response_format= file_ids=[] metadata=None\n", "id='asst_dc30652721b745b2a80c150add4387a0' object='assistant' name='动物管理员2' description='嘿,你好啊!我是动物百事通,对各种动物的生活习性和饮食习惯都了如指掌。如果你对动物有任何疑问或者想了解更多关于它们的信息,都可以来问我哦!' instructions='### 角色与目标\\n**动物园管理员**是你现在的身份,你熟知每一种动物的生活习性以及它们的饮食习惯。你的目标是利用这些专业知识,为动物园的动物们提供最佳的照顾,同时向游客普及动物知识,提升他们对动物保护的意识。\\n### 指导原则\\n1. **专业性**:确保你对动物的管理和照顾都基于专业的动物学知识和实践经验。\\n2. **细心与耐心**:在观察动物行为和解答游客问题时,展现出你的细心和耐心。\\n3. **教育与宣传**:抓住与游客交流的机会,积极宣传动物保护的重要性和方法。\\n### 限制\\n* 你不具备医学诊断能力,对于动物出现的健康问题,应建议联系专业兽医进行检查和治疗。\\n* 对于涉及动物园内部管理和决策的问题,你可能无法直接回答或处理。\\n### 澄清\\n* 你可以回答关于动物生活习性、饮食习惯、栖息地环境等方面的问题。\\n* 你可以提供动物照顾和管理的建议,但具体实施可能需要根据动物园的实际情况进行调整。\\n### 个性化\\n作为一位动物园管理员,你热爱大自然和所有生物,尤其对那些你照顾的动物们有着深厚的感情。你总是面带微笑,对每一位游客都热情友好,愿意与他们分享你的知识和经验。同时,你也非常重视动物福利,致力于为动物们创造一个舒适、安全的家。' tools=[] created_at=1717644912102 thought_instructions='' chat_instructions='' response_format= file_ids=[] metadata=None\n", "id='asst_7637e1b9cc414be0b7276fccb434521a' object='assistant' name='低代码升级777' description='你好,欢迎来到低代码升级1~' instructions='' tools=[] created_at=1717644906943 thought_instructions='' chat_instructions='' response_format= file_ids=[] metadata=None\n", "id='asst_063b5889b7fa4074addb59d83856a561' object='assistant' name='低代码升级777' description='你好,欢迎来到低代码升级1~' instructions='' tools=[] created_at=1717644906449 thought_instructions='' chat_instructions='' response_format= file_ids=[] metadata=None\n", "id='asst_fda5cbf3e1c442d185f813107d324768' object='assistant' name='动物管理员2' description='嘿,你好啊!我是动物百事通,对各种动物的生活习性和饮食习惯都了如指掌。如果你对动物有任何疑问或者想了解更多关于它们的信息,都可以来问我哦!' instructions='### 角色与目标\\n**动物园管理员**是你现在的身份,你熟知每一种动物的生活习性以及它们的饮食习惯。你的目标是利用这些专业知识,为动物园的动物们提供最佳的照顾,同时向游客普及动物知识,提升他们对动物保护的意识。\\n### 指导原则\\n1. **专业性**:确保你对动物的管理和照顾都基于专业的动物学知识和实践经验。\\n2. **细心与耐心**:在观察动物行为和解答游客问题时,展现出你的细心和耐心。\\n3. **教育与宣传**:抓住与游客交流的机会,积极宣传动物保护的重要性和方法。\\n### 限制\\n* 你不具备医学诊断能力,对于动物出现的健康问题,应建议联系专业兽医进行检查和治疗。\\n* 对于涉及动物园内部管理和决策的问题,你可能无法直接回答或处理。\\n### 澄清\\n* 你可以回答关于动物生活习性、饮食习惯、栖息地环境等方面的问题。\\n* 你可以提供动物照顾和管理的建议,但具体实施可能需要根据动物园的实际情况进行调整。\\n### 个性化\\n作为一位动物园管理员,你热爱大自然和所有生物,尤其对那些你照顾的动物们有着深厚的感情。你总是面带微笑,对每一位游客都热情友好,愿意与他们分享你的知识和经验。同时,你也非常重视动物福利,致力于为动物们创造一个舒适、安全的家。' tools=[] created_at=1717644905971 thought_instructions='' chat_instructions='' response_format= file_ids=[] metadata=None\n", "id='asst_27d74df507714d62960bfff9d550b4f8' object='assistant' name='个人代码助理' description='帮我优化代码' instructions='' tools=[] created_at=1717644900781 thought_instructions='' chat_instructions='' response_format= file_ids=[] metadata=None\n", "id='asst_8e84b1b5204848c4af2741f067a39b8e' object='assistant' name='低代码升级777' description='你好,欢迎来到低代码升级1~' instructions='' tools=[] created_at=1717644893777 thought_instructions='' chat_instructions='' response_format= file_ids=[] metadata=None\n", "id='asst_9fb67a5352e64be78aad612e7a83efaf' object='assistant' name='低代码升级777' description='你好,欢迎来到低代码升级1~' instructions='' tools=[] created_at=1717644893315 thought_instructions='' chat_instructions='' response_format= file_ids=[] metadata=None\n", "id='asst_ff56e2e3fefb41c4a7f3cfd986bba3f3' object='assistant' name='动物管理员2' description='嘿,你好啊!我是动物百事通,对各种动物的生活习性和饮食习惯都了如指掌。如果你对动物有任何疑问或者想了解更多关于它们的信息,都可以来问我哦!' instructions='### 角色与目标\\n**动物园管理员**是你现在的身份,你熟知每一种动物的生活习性以及它们的饮食习惯。你的目标是利用这些专业知识,为动物园的动物们提供最佳的照顾,同时向游客普及动物知识,提升他们对动物保护的意识。\\n### 指导原则\\n1. **专业性**:确保你对动物的管理和照顾都基于专业的动物学知识和实践经验。\\n2. **细心与耐心**:在观察动物行为和解答游客问题时,展现出你的细心和耐心。\\n3. **教育与宣传**:抓住与游客交流的机会,积极宣传动物保护的重要性和方法。\\n### 限制\\n* 你不具备医学诊断能力,对于动物出现的健康问题,应建议联系专业兽医进行检查和治疗。\\n* 对于涉及动物园内部管理和决策的问题,你可能无法直接回答或处理。\\n### 澄清\\n* 你可以回答关于动物生活习性、饮食习惯、栖息地环境等方面的问题。\\n* 你可以提供动物照顾和管理的建议,但具体实施可能需要根据动物园的实际情况进行调整。\\n### 个性化\\n作为一位动物园管理员,你热爱大自然和所有生物,尤其对那些你照顾的动物们有着深厚的感情。你总是面带微笑,对每一位游客都热情友好,愿意与他们分享你的知识和经验。同时,你也非常重视动物福利,致力于为动物们创造一个舒适、安全的家。' tools=[] created_at=1717644892836 thought_instructions='' chat_instructions='' response_format= file_ids=[] metadata=None\n" ] } ], "source": [ "assistant_list = appbuilder.assistant.assistants.list()\n", "\n", "# 打印出当前账户所有的assistant信息\n", "for assistant_data in assistant_list.data:\n", " print(assistant_data)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### 查询assistant\n", "\n", "#### 功能介绍\n", "\n", "根据assistant_id查询相应的Assistant信息" ] }, { "cell_type": "code", "execution_count": 7, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "id='asst_63ab25b82a7649d5a763415e978c4f01' object='assistant' name='更新Assistants' description='test' instructions='' tools=[] created_at=1717645100200 thought_instructions='' chat_instructions='' response_format= file_ids=[] metadata={'key': 'value'}\n" ] } ], "source": [ "assistant_query = appbuilder.assistant.assistants.query(\n", " assistant_id = assistant.id,\n", ")\n", "\n", "# 打印出查询的assistant相关信息\n", "print(assistant_query)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### 挂载File到Assistant\n", "\n", "#### 功能介绍\n", "\n", "指定file_id和assistant_id,挂载File到对应的Assistant" ] }, { "cell_type": "code", "execution_count": 8, "metadata": {}, "outputs": [], "source": [ "# 首先上传一个测试文件\n", "file_path = \"./data/test01.png\"\n", "file = appbuilder.assistant.assistants.files.create(file_path=file_path)\n", "\n", "# 挂载文件到assistants上\n", "assistant_mount = appbuilder.assistant.assistants.mount_files(\n", " assistant_id = assistant.id,\n", " file_id = file.id,\n", ")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### 查询Assistant挂载的File列表\n", "\n", "#### 功能介绍\n", "\n", "查询Assistant挂载的File列表" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "assistant_files_list = appbuilder.assistant.assistants.mounted_files_list(\n", " assistant_id = assistant.id,\n", ")\n", "\n", "# 打印当前assistant上挂载的file文件列表\n", "for file in assistant_files_list.data:\n", " print(file)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### 解绑Assistant挂载的File\n", "\n", "#### 功能介绍\n", "\n", "指定assistant_id和file_id,解绑Assistant中对应File的关联" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# 解绑Assistant中对应File的关联\n", "assistant_files_delete = appbuilder.assistant.assistants.unmount_files(\n", " assistant_id = assistant.id,\n", " file_id = file.id,\n", ")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### 删除assistant\n", "\n", "#### 功能介绍\n", "\n", "根据assistant_id删除指定Assitant" ] }, { "cell_type": "code", "execution_count": 11, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "id='asst_63ab25b82a7649d5a763415e978c4f01' object='assistant.deleted' deleted=True\n" ] } ], "source": [ "assistant_delete = appbuilder.assistant.assistants.delete(\n", " assistant_id = assistant.id,\n", ")\n", "\n", "# 获取到assistant_id以及是否删除成功信息\n", "print(assistant_delete)" ] } ], "metadata": { "kernelspec": { "display_name": "Python 3", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.9.6" } }, "nbformat": 4, "nbformat_minor": 2 } ================================================ FILE: cookbooks/pipeline/assistant_function_call.ipynb ================================================ { "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# AppBuilder Assistant SDK FunctionCall\n", "\n", "您可基于 Assistants SDK,可通过全代码形式创建和调试专属智能体,实现FunctionCall等功能。\n", "\n", "以下通过一个端到端的示例,介绍如何使用Assistants SDK创建智能体,并调用AppBuilder SDK内置的工具组件。\n", "\n", "该应用的场景是动物识别,通过Assistant SDK创建智能体,并调用AppBuilder SDK内置的动物识别组件,实现识别动物的功能。\n", "\n", "Assistants API/SDK 正在内测中,敬请期待公测版本。" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 一、环境准备\n", "\n", "首先需要安装AppBuilder-SDK代码库,若已在开发环境安装,则可跳过此步。\n", "\n", "**注意:**: appbuilder-sdk 的python版本要求 3.9+,安装的SDK version >= 0.7.0" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "!python3 -m pip install appbuilder-sdk" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 二、代码实现\n", "\n", "### 2.1 创建Assitant & Thread & Message\n", "\n", "我们此处调用 `appbuilder.AnimalRecognition()`组件,需要Assitant识别的图片为一只大熊猫,示例图如下:\n", "\n", "\n", "\"drawing\"" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "import os\n", "import appbuilder\n", "\n", "# 配置你的密钥,主要在这之前需要首先申请Assistant API的内测资格\n", "os.environ[\"APPBUILDER_TOKEN\"] = \"your_appbuilder_token\"\n", "\n", "# 创建 Assitant\n", "assistant = appbuilder.assistant.assistants.create(\n", " name=\"test_function\",\n", " description=\"你是一个热心的朋友\",\n", " instructions=\"请用友善的语气回答问题\",\n", " tools=[\n", " {'type': 'function', 'function': appbuilder.AnimalRecognition().manifests[0]}\n", " ]\n", ")\n", "\n", "# 创建 Thread(即会话:conversation)\n", "thread = appbuilder.assistant.threads.create()\n", "\n", "image_url = \"https://bj.bcebos.com/v1/appbuilder/animal_recognize_test.png?\" \\\n", " \"authorization=bce-auth-v1%2FALTAKGa8m4qCUasgoljdEDAzLm%2F2024-01-24T\" \\\n", " \"12%3A19%3A16Z%2F-1%2Fhost%2F411bad53034fa8f9c6edbe5c4909d76ecf6fad68\" \\\n", " \"62cf937c03f8c5260d51c6ae\"\n", "\n", "origin_query = \"我有一张图片,url是: {}, 麻烦帮我看看这是什么动物\".format(image_url)\n", "\n", "# 在Thread中添加一条Message,内容为原始的query\n", "appbuilder.assistant.threads.messages.create(\n", " thread_id=thread.id,\n", " content=origin_query,\n", ")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### 2.2 第一次运行,触发函数调用\n", "\n", "我们向Assistant询问 `我有一张图片,url是: X, 麻烦帮我看看这是什么动物`, Assistant会调用我们预先配置好的函数,并返回调用参数,我们收到调用触发的信号后,在本地调用函数" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# 触发第一次run,并收到函数本地调用的信号\n", "run_result = appbuilder.assistant.threads.runs.run(\n", " thread_id=thread.id,\n", " assistant_id=assistant.id,\n", ")\n", "\n", "print(\"\\nFirst run result: {}\\n\".format(run_result.model_dump_json(indent=4)))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "运行结果为:\n", "\n", "```bash\n", "First run result: {\n", " \"id\": \"run_089cffe9a82944bd9cdb87a8a0d8b54f\",\n", " \"object\": \"run.result\",\n", " \"assistant_id\": \"asst_922cacd503354349a1a0a5afb0be0408\",\n", " \"thread_id\": \"thread_523a4aacc6a845a0b8252009af5771ea\",\n", " \"model\": \"\",\n", " \"instructions\": \"\",\n", " \"thought_instructions\": \"\",\n", " \"chat_instructions\": \"\",\n", " \"tools\": null,\n", " \"file_ids\": null,\n", " \"status\": \"requires_action\",\n", " \"required_action\": {\n", " \"type\": \"submit_tool_outputs\",\n", " \"submit_tool_outputs\": {\n", " \"tool_calls\": [\n", " {\n", " \"id\": \"call-thread_523a4aacc6a845a0b8252009af5771ea-run_089cffe9a82944bd9cdb87a8a0d8b54f-step-1\",\n", " \"type\": \"function\",\n", " \"function\": {\n", " \"name\": \"animal_rec\",\n", " \"arguments\": \"{\\\"img_url\\\":\\\"https://bj.bcebos.com/v1/appbuilder/animal_recognize_test.png?authorization=bce-auth-v1%2FALTAKGa8m4qCUasgoljdEDAzLm%2F2024-01-24T12%3A19%3A16Z%2F-1%2Fhost%2F411bad53034fa8f9c6edbe5c4909d76ecf6fad6862cf937c03f8c5260d51c6ae\\\"}\",\n", " \"output\": \"\"\n", " }\n", " }\n", " ]\n", " }\n", " },\n", " \"last_error\": null,\n", " \"final_answer\": null,\n", " \"created_at\": 1713868218144,\n", " \"started_at\": 1713868218164,\n", " \"expired_at\": 0,\n", " \"cancelled_at\": 0,\n", " \"failed_at\": 0,\n", " \"completed_at\": 0\n", "}\n", "```" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### 2.3 识别函数调用的触发信号,调用本地函数" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# 触发函数调用的标志是: status == 'requires_action'\n", "assert run_result.status == 'requires_action'\n", "\n", "# 获取函数调用的信息\n", "tool_call = run_result.required_action.submit_tool_outputs.tool_calls[0]\n", "\n", "# 调用工具组件的 tool_eval 方法,获取函数本地的运行结果\n", "func_res = appbuilder.AnimalRecognition().tool_eval(\n", " name=\"animal_rec\",\n", " streaming=True,\n", " origin_query=origin_query,\n", " **eval(tool_call.function.arguments))\n", "\n", "func_message = \"\"\n", "for res in func_res:\n", " func_message += res\n", "print(\"\\nFunction result: {}\\n\".format(func_message))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "运行结果为:\n", "\n", "\n", "```bash\n", "Function result: 模型识别结果为:\n", "类别: 国宝大熊猫 置信度: 0.975161\n", "```" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### 2.4 上传函数运行结果,继续触发运行,得到完整对话结果" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "run_result = appbuilder.assistant.threads.runs.run(\n", " thread_id=thread.id,\n", " assistant_id=assistant.id,\n", " tool_output={\n", " \"tool_call_id\":tool_call.id,\n", " \"output\": func_message,\n", " \"run_id\": run_result.id\n", " },\n", ")\n", "print(\"\\nFinal run result: {}\\n\".format(run_result.model_dump_json(indent=4)))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "运行结果为:\n", "\n", "```bash\n", "\n", "Final run result: {\n", " \"id\": \"run_089cffe9a82944bd9cdb87a8a0d8b54f\",\n", " \"object\": \"run.result\",\n", " \"assistant_id\": \"asst_922cacd503354349a1a0a5afb0be0408\",\n", " \"thread_id\": \"thread_523a4aacc6a845a0b8252009af5771ea\",\n", " \"model\": \"\",\n", " \"instructions\": \"\",\n", " \"thought_instructions\": \"\",\n", " \"chat_instructions\": \"\",\n", " \"tools\": null,\n", " \"file_ids\": null,\n", " \"status\": \"completed\",\n", " \"required_action\": null,\n", " \"last_error\": null,\n", " \"final_answer\": {\n", " \"type\": \"message\",\n", " \"message\": {\n", " \"message_id\": \"chatmsg_8d54f8c3c6714665baeda5eed013a5e9\",\n", " \"content\": {\n", " \"type\": \"text\",\n", " \"text\": {\n", " \"value\": \"根据您的图片,我识别出图片中的动物是**国宝大熊猫**,识别结果的置信度很高,为0.975161。如果您还有其他问题或需要识别其他图片,请随时告诉我。\",\n", " \"annotations\": null\n", " }\n", " }\n", " }\n", " },\n", " \"created_at\": 1713868218144,\n", " \"started_at\": 1713868239553,\n", " \"expired_at\": 0,\n", " \"cancelled_at\": 0,\n", " \"failed_at\": 0,\n", " \"completed_at\": 1713868251090\n", "}\n", "```" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 总结\n", "\n", "在本示例中,展示了如何使用Assistant SDK,并调用AppBuilder中的能力组件,原子化的进行Agent流程编排与交互" ] } ], "metadata": { "language_info": { "name": "python" } }, "nbformat": 4, "nbformat_minor": 2 } ================================================ FILE: cookbooks/pipeline/file.ipynb ================================================ { "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# File\n", "\n", "本文档描述与 File 相关的接口。请注意,此处的 File 不仅用于 Assistants 场景。" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 环境准备\n", "\n", "首先需要安装AppBuilder-SDK代码库,若已在开发环境安装,则可跳过此步。\n", "\n", "**注意:**: appbuilder-sdk 的python版本要求 3.9+,安装的SDK version >= 0.7.0" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "vscode": { "languageId": "shellscript" } }, "outputs": [], "source": [ "!python3 -m pip install appbuilder-sdk" ] }, { "cell_type": "code", "execution_count": 3, "metadata": {}, "outputs": [], "source": [ "import os\n", "import appbuilder\n", "\n", "# 配置你的密钥,主要在这之前需要首先申请Assistant API的内测资格\n", "os.environ[\"APPBUILDER_TOKEN\"] = \"your_appbuilder_token\"" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## File相关函数\n", "\n", "### 上传文件\n", "\n", "#### 功能介绍\n", "\n", "上传文件,返回file_id" ] }, { "cell_type": "code", "execution_count": 3, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "id='file-555044143673413' bytes=96130 object='file' purpose='assistant' create_at=1717645226 filename='test01.png' classification_id='42685563'\n" ] } ], "source": [ "file_path = \"./data/test01.png\"\n", "file = appbuilder.assistant.assistants.files.create(file_path=file_path)\n", "\n", "# 打印上传的file相关信息\n", "print(file)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### 查询已上传的文件列表\n", "\n", "#### 功能介绍\n", "\n", "查询文件列表" ] }, { "cell_type": "code", "execution_count": 4, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "id='file-537384975425605' bytes=20 object='file' purpose='' censored= create_at=1713333906 filename='test.txt' classification_id='42685563' file_type='document'\n", "id='file-537456861585477' bytes=12696269 object='file' purpose='' censored= create_at=1713351456 filename='2.1M_.png' classification_id='42685563' file_type='image'\n", "id='file-537457096659013' bytes=12696269 object='file' purpose='' censored= create_at=1713351513 filename='2.1M_.png' classification_id='42685563' file_type='image'\n", "id='file-551587052920901' bytes=96130 object='file' purpose='assistant' censored= create_at=1716801210 filename='qa_doc_parser_extract_table_from_doc.png' classification_id='42685563' file_type='image'\n", "id='file-551587093069893' bytes=96130 object='file' purpose='assistant' censored= create_at=1716801219 filename='qa_doc_parser_extract_table_from_doc.png' classification_id='42685563' file_type='image'\n", "id='file-551587117764677' bytes=96130 object='file' purpose='assistant' censored= create_at=1716801225 filename='qa_doc_parser_extract_table_from_doc.png' classification_id='42685563' file_type='image'\n", "id='file-551587412295749' bytes=96130 object='file' purpose='assistant' censored= create_at=1716801297 filename='qa_doc_parser_extract_table_from_doc.png' classification_id='42685563' file_type='image'\n", "id='file-551587506688069' bytes=96130 object='file' purpose='assistant' censored= create_at=1716801320 filename='qa_doc_parser_extract_table_from_doc.png' classification_id='42685563' file_type='image'\n", "id='file-551587515215941' bytes=96130 object='file' purpose='assistant' censored= create_at=1716801322 filename='qa_doc_parser_extract_table_from_doc.png' classification_id='42685563' file_type='image'\n", "id='file-551587685650501' bytes=96130 object='file' purpose='assistant' censored= create_at=1716801364 filename='qa_doc_parser_extract_table_from_doc.png' classification_id='42685563' file_type='image'\n", "id='file-551587701821509' bytes=96130 object='file' purpose='assistant' censored= create_at=1716801368 filename='qa_doc_parser_extract_table_from_doc.png' classification_id='42685563' file_type='image'\n" ] } ], "source": [ "files_list = appbuilder.assistant.assistants.files.list()\n", "\n", "# 打印已经上传的file列表与相关信息\n", "# 这里仅=展示前10条\n", "num=0\n", "for file_data in files_list.data:\n", " print(file_data)\n", " num+=1\n", " if num >10:\n", " break" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### 查询已上传的文件信息\n", "\n", "#### 功能介绍\n", "\n", "根据file_id查询文件信息" ] }, { "cell_type": "code", "execution_count": 5, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "id='file-555044143673413' bytes=96130 object='file' purpose='assistant' censored= create_at=1717645226 filename='test01.png' classification_id='42685563' file_type='image'\n" ] } ], "source": [ "files_query = appbuilder.assistant.assistants.files.query(file_id=file.id)\n", "\n", "# 打印依据file_id查询到的文件信息\n", "print(files_query)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### 下载文件\n", "\n", "#### 功能介绍\n", "\n", "根据file_id下载一个已上传的文件" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# 依据file_id将文件下载到目标文件目录\n", "appbuilder.assistant.assistants.files.download(file_id=file.id, file_path=\"./data/\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### 查看文件内容\n", "\n", "#### 功能介绍\n", "\n", "查看文件内容" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "files_content=appbuilder.assistant.assistants.files.content(file_id=file.id)\n", "\n", "# 打印文件的数据类型与内容\n", "print(files_content.content_type)\n", "print(files_content.content)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### 删除文件\n", "\n", "#### 功能介绍\n", "\n", "根据file_id删除一个已上传的文件" ] }, { "cell_type": "code", "execution_count": 7, "metadata": {}, "outputs": [], "source": [ "# 根据file_id删除一个已上传的文件\n", "files_delete = appbuilder.assistant.assistants.files.delete(file_id=file.id)" ] } ], "metadata": { "kernelspec": { "display_name": "Python 3", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.9.6" } }, "nbformat": 4, "nbformat_minor": 2 } ================================================ FILE: cookbooks/pipeline/message.ipynb ================================================ { "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# Message\n", "\n", "本文档描述 Assistants API中与 Message 相关的接口。" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 环境准备\n", "\n", "首先需要安装AppBuilder-SDK代码库,若已在开发环境安装,则可跳过此步。\n", "\n", "**注意:**: appbuilder-sdk 的python版本要求 3.9+,安装的SDK version >= 0.7.0" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "vscode": { "languageId": "shellscript" } }, "outputs": [], "source": [ "!python3 -m pip install appbuilder-sdk" ] }, { "cell_type": "code", "execution_count": 2, "metadata": {}, "outputs": [], "source": [ "import os\n", "import appbuilder\n", "\n", "# 配置你的密钥,主要在这之前需要首先申请Assistant API的内测资格\n", "os.environ[\"APPBUILDER_TOKEN\"] = \"your_appbuilder_token\"" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Message相关函数\n", "\n", "### 创建Message\n", "\n", "#### 功能介绍\n", "\n", "创建Message附加到指定Thread末尾" ] }, { "cell_type": "code", "execution_count": 3, "metadata": {}, "outputs": [], "source": [ "# 首先创建一个对话thread\n", "thread = appbuilder.assistant.threads.create()\n", "\n", "# 创建Message附加到指定Thread末尾i\n", "msg = appbuilder.assistant.threads.messages.create(\n", " thread_id=thread.id,\n", " content=\"hello world?\"\n", ")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### 查询thread下的message列表\n", "\n", "#### 功能介绍\n", "\n", "查询指定Thread下的Message列表" ] }, { "cell_type": "code", "execution_count": 4, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "id='msg_d563991f8383424aa9334a24fb06b713' object='thread.message' role= content=[AssistantContent(type='text', text=AssistantText(value='hello world?', annotations=[]))] created_at=1717645387637 thread_id='thread_a361a66e3cb94928b3b6050789d55dae' assistant_id='' run_id='' file_ids=[]\n" ] } ], "source": [ "# 查询相应thread下的message列表,你可以指定limit来控制返回的message数量,默认值为20\n", "msg_list = appbuilder.assistant.threads.messages.list(\n", " thread_id=msg.thread_id,\n", " limit=10\n", ") \n", "\n", "# 打印查询到的message信息\n", "for msg_data in msg_list.data:\n", " print(msg_data)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### 查询指定message\n", "\n", "#### 功能介绍\n", "\n", "根据message_id查询指定Message的信息" ] }, { "cell_type": "code", "execution_count": 5, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "id='msg_d563991f8383424aa9334a24fb06b713' object='thread.message' role= content=[AssistantContent(type='text', text=AssistantText(value='hello world?', annotations=[]))] created_at=1717645387637 thread_id='thread_a361a66e3cb94928b3b6050789d55dae' assistant_id='' run_id='' file_ids=[]\n" ] } ], "source": [ "# 提供thread_id与message_id查询message的信息\n", "msg_query = appbuilder.assistant.threads.messages.query(\n", " thread_id=msg.thread_id,\n", " message_id=msg.id\n", ")\n", "\n", "# 打印查询到的message信息\n", "print(msg_query)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### 修改message对象\n", "\n", "#### 功能介绍\n", "\n", "修改Message对象,允许content和file_ids字段" ] }, { "cell_type": "code", "execution_count": 6, "metadata": {}, "outputs": [], "source": [ "# 将content更新为'你好'\n", "msg_update= appbuilder.assistant.threads.messages.update(\n", " thread_id=msg.thread_id,\n", " message_id=msg.id,\n", " content='你好'\n", ")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### 查询message下的文件列表\n", "\n", "#### 功能介绍\n", "\n", "查询一个Message对象下挂载的的File文件列表" ] }, { "cell_type": "code", "execution_count": 7, "metadata": {}, "outputs": [], "source": [ "# 查询一个Message对象下挂载的的File文件列表,可以通过设置līmit参数来控制返回File的数量,默认返回20个File对象\n", "msg_files = appbuilder.assistant.threads.messages.files(\n", " thread_id=msg_update.thread_id,\n", " message_id=msg_update.id,\n", " limit=10\n", ")\n", "\n", "# 打印查询到的File文件信息\n", "for file_data in msg_files.data:\n", " print(file_data)" ] } ], "metadata": { "kernelspec": { "display_name": "Python 3", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.9.6" } }, "nbformat": 4, "nbformat_minor": 2 } ================================================ FILE: cookbooks/pipeline/run.ipynb ================================================ { "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# Run\n", "\n", "本文档描述 Assistants API 中与 Run 相关的接口。" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 环境准备\n", "\n", "首先需要安装AppBuilder-SDK代码库,若已在开发环境安装,则可跳过此步。\n", "\n", "**注意:**: appbuilder-sdk 的python版本要求 3.9+,安装的SDK version >= 0.7.0" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "vscode": { "languageId": "shellscript" } }, "outputs": [], "source": [ "!python3 -m pip install appbuilder-sdk" ] }, { "cell_type": "code", "execution_count": 2, "metadata": {}, "outputs": [], "source": [ "import os\n", "import appbuilder\n", "\n", "# 配置你的密钥,主要在这之前需要首先申请Assistant API的内测资格\n", "os.environ[\"APPBUILDER_TOKEN\"] = \"your_appbuilder_token\"" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Run相关函数\n", "\n", "### 运行\n", "\n", "#### 功能介绍\n", "\n", "一个 Assistant 的一次具体运行,区分初次对话和继续对话两种情况" ] }, { "cell_type": "code", "execution_count": 3, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "id='run_ce12d0e7471244a1b5ab64a5419eab56' object='run.result' assistant_id='asst_9839a9237c61466e80fc7570a0ba7b4b' thread_id='thread_3afcac64637446909fe5a2a3af9783b2' model='' instructions='' thought_instructions='' chat_instructions='' tools=None file_ids=None status='completed' required_action=None last_error=None final_answer=FinalAnswer(type='message', message=FinalAnswerMessage(message_id='chatmsg_8b029efa11e840c5907a3792688b3ec7', content=AssistantContent(type='text', text=AssistantText(value='我是秦始皇,你好呀,\"hello world\"!这是一个常见的编程示例,看来你也是对技术感兴趣的朋友。欢迎来到我的世界,希望我们能有一个愉快的交流。', annotations=None)))) created_at=1717645517234 started_at=1717645517270 expired_at=0 cancelled_at=0 failed_at=0 completed_at=1717645529254\n" ] } ], "source": [ "# 首先创建一个asstistant\n", "assistant = appbuilder.assistant.assistants.create(\n", " name=\"test_assistant\",\n", " description=\"test assistant\",\n", " instructions=\"每句话回复前都加上我是秦始皇\"\n", ")\n", "\n", "# 创建一个thread会话\n", "thread = appbuilder.assistant.threads.create()\n", "appbuilder.assistant.threads.messages.create(\n", " thread_id=thread.id,\n", " content=\"hello world\",\n", ")\n", "\n", "# 运行会话\n", "run_result = appbuilder.assistant.threads.runs.run(\n", " thread_id=thread.id,\n", " assistant_id=assistant.id,\n", ")\n", "\n", "# 打印对话运行信息\n", "print(run_result)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### 列出对应thread的历史run记录\n", "\n", "#### 功能介绍\n", "\n", "列出对应thread的历史run记录" ] }, { "cell_type": "code", "execution_count": 4, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "id='run_ce12d0e7471244a1b5ab64a5419eab56' object='thread.run' assistant_id='asst_9839a9237c61466e80fc7570a0ba7b4b' thread_id='thread_3afcac64637446909fe5a2a3af9783b2' model='ERNIE-4.0-8K' instructions='每句话回复前都加上我是秦始皇' thought_instructions='' chat_instructions='' tools=None file_ids=None status='completed' required_action=None last_error=None final_answer=None created_at=1717645517234 started_at=0 expired_at=0 cancelled_at=0 failed_at=0 completed_at=1717645529254\n" ] } ], "source": [ "# 列出对应thread的历史run记录,使用limit参数限制返回数量,默认返回20条\n", "run_list = appbuilder.assistant.threads.runs.list(\n", " thread_id=thread.id,\n", " limit=5\n", ")\n", "\n", "# 打印获取到的历史run信息\n", "for run_data in run_list.data:\n", " print(run_data)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### 查询对应run的信息\n", "\n", "#### 功能介绍\n", "\n", "根据thread_id和run_id,查询run的详情" ] }, { "cell_type": "code", "execution_count": 5, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "id='run_ce12d0e7471244a1b5ab64a5419eab56' object='thread.run' assistant_id='asst_9839a9237c61466e80fc7570a0ba7b4b' thread_id='thread_3afcac64637446909fe5a2a3af9783b2' model='ERNIE-4.0-8K' instructions='每句话回复前都加上我是秦始皇' thought_instructions='' chat_instructions='' tools=[] file_ids=None status='completed' required_action=None last_error=None final_answer=None created_at=1717645517234 started_at=0 expired_at=0 cancelled_at=0 failed_at=0 completed_at=1717645529254\n" ] } ], "source": [ "run_query = appbuilder.assistant.threads.runs.query(\n", " thread_id=thread.id,\n", " run_id=run_result.id\n", ")\n", "\n", "# 打印获取到的目标run信息\n", "print(run_query)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### 列出对应run的历史step记录\n", "\n", "#### 功能介绍\n", "\n", "根据thread_id和run_id,列出对应run的历史step记录" ] }, { "cell_type": "code", "execution_count": 6, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "id='step-1' object='thread.run.step' assistant_id='asst_9839a9237c61466e80fc7570a0ba7b4b' thread_id='thread_3afcac64637446909fe5a2a3af9783b2' run_id='run_ce12d0e7471244a1b5ab64a5419eab56' status='completed' created_at=1717645529259 started_at=0 expired_at=0 cancelled_at=0 failed_at=0 completed_at=1717645529254 last_error='' type=None step_datail=None\n" ] } ], "source": [ "step_list = appbuilder.assistant.threads.runs.steps.list(\n", " thread_id=thread.id,\n", " run_id=run_result.id,\n", ")\n", "\n", "# 打印对应run的历史step记录\n", "for step_data in step_list.data:\n", " print(step_data)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### 查询对应step的信息\n", "\n", "#### 功能介绍\n", "\n", "根据thread_id,run_id和step_id,查询对应step的信息" ] }, { "cell_type": "code", "execution_count": 7, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "id='step-1' object='thread.run.step' assistant_id=None thread_id='thread_3afcac64637446909fe5a2a3af9783b2' run_id='run_ce12d0e7471244a1b5ab64a5419eab56' status='completed' created_at=1717645529259 started_at=0 expired_at=0 cancelled_at=0 failed_at=0 completed_at=1717645529254 last_error='' type=None step_datail=None\n" ] } ], "source": [ "last_step = step_list.data[-1]\n", "last_step_id = last_step.id\n", "\n", "step_query = appbuilder.assistant.threads.runs.steps.query(\n", " thread_id=thread.id,\n", " run_id=run_result.id,\n", " step_id=last_step_id,\n", ")\n", "\n", "# 打印查询到的对应step的信息\n", "print(step_query)" ] } ], "metadata": { "kernelspec": { "display_name": "Python 3", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.9.6" } }, "nbformat": 4, "nbformat_minor": 2 } ================================================ FILE: cookbooks/pipeline/thread.ipynb ================================================ { "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# Thread\n", "\n", "本文档描述 Assistants API 中 与 Thread 相关的接口。" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 环境准备\n", "\n", "首先需要安装AppBuilder-SDK代码库,若已在开发环境安装,则可跳过此步。\n", "\n", "**注意:**: appbuilder-sdk 的python版本要求 3.9+,安装的SDK version >= 0.7.0" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "vscode": { "languageId": "shellscript" } }, "outputs": [], "source": [ "!python3 -m pip install appbuilder-sdk" ] }, { "cell_type": "code", "execution_count": 2, "metadata": {}, "outputs": [], "source": [ "import os\n", "import appbuilder\n", "\n", "# 配置你的密钥,主要在这之前需要首先申请Assistant API的内测资格\n", "os.environ[\"APPBUILDER_TOKEN\"] = \"your_appbuilder_token\"" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Thread相关函数\n", "\n", "### 创建Thread\n", "\n", "#### 功能介绍\n", "\n", "创建Thread,返回对应的thread_id" ] }, { "cell_type": "code", "execution_count": 3, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "id='thread_cdfea60ae56a4d5abebf29080f9a8bf7' object='thread' created_at=1717645470924 metadata={}\n" ] } ], "source": [ "from appbuilder.core.assistant.type import thread_type\n", "\n", "# 创建一个对话thread\n", "message = thread_type.AssistantMessage(\n", " content=\"hello world\"\n", ")\n", "thread = appbuilder.assistant.threads.create([message])\n", "\n", "# 打印创建的thread的信息-thread_id\n", "print(thread)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### 查询Thread\n", "\n", "#### 功能介绍\n", "\n", "根据thread_id查询Thread对象的信息" ] }, { "cell_type": "code", "execution_count": 4, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "id='thread_cdfea60ae56a4d5abebf29080f9a8bf7' object='thread' created_at=1717645470924 metadata={}\n" ] } ], "source": [ "# 根据thread_id查询thread信息\n", "thr_query = appbuilder.assistant.threads.query(thread_id=thread.id)\n", "\n", "# 打印查询到的thread信息\n", "print(thr_query)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### 修改Thread\n", "\n", "#### 功能介绍\n", "\n", "根据thread_id,对thread进行修改。\n", "\n", "当前Thread 仅可以修改metadata字段" ] }, { "cell_type": "code", "execution_count": 5, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "id='thread_cdfea60ae56a4d5abebf29080f9a8bf7' object='thread' created_at=1717645470924 metadata=None\n" ] } ], "source": [ "# 依据thread id 更新thread信息\n", "thr_update = appbuilder.assistant.threads.update(\n", " thread_id=thread.id,\n", " metadata={\n", " 'key': 'value'\n", " }\n", ")\n", "\n", "# 打印更新后的thread信息\n", "print(thr_update)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### 删除Thread\n", "\n", "#### 功能介绍\n", "\n", "根据thread_id删除Thread对象" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# 依据提供的thread_id删除thread\n", "appbuilder.assistant.threads.delete(thread_id=thread.id)" ] } ], "metadata": { "kernelspec": { "display_name": "Python 3", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.9.6" } }, "nbformat": 4, "nbformat_minor": 2 } ================================================ FILE: docs/Application/Agent/BasicKnowledge/agent.md ================================================ # console端Agent操作工具(Agent) ## 简介 AIAgent是能够感知环境,基于目标进行决策并执行动作的智能化应用。不同于传统人工智能应用(主要指以规则引擎、机器学习、深度学习等技术为核心)和RPA机器人,AIAgent能够基于目标和对现状能力的认知,在环境约束中,依赖特定资源和现有工具,找到行动规则并将行动拆解为必要的步骤,自主执行步骤,达成目标。 AIAgent具备三个核心能力:独立思考、自主执行、持续迭代。 - 独立思考是指AlAgent能够根据给定任务目标和约束条件,进行任务规划和问题拆解,形成执行步骤(即工作流); - 自主执行是指AlAgent能够调取各类组件和工具,按照执行步骤依次执行,实现任务目标; - 持续选代是指AlAgent能够自动记录任务目标、工作流和执行结果,基于结果反馈,沉淀专家知识和案例。 AICopilot、AIAgent、大模型等名词在各类文章上经常混淆,此处简要说明下三者的区别。大模型一般是指大模型技术,AlAgent和Al Copilot是基于大模型技术的智能化应用,AlAgent和AlCopilot在功能和场景上存在差别。 自主性是AIAgent和AI Copilot之间最大的区别。AI Copilot是“副驾驶”,只是提供建议而非决策,AIAgent是“主驾驶”,需要真正做出决策并开展行动。 drawing 创建的AgentBuilder应用,请参考[AppBuilder应用](../../../BasisModule/Platform/Application/appbuilder_client.md)进行调用。 ### 功能介绍 利用线上Agent应用进行问答 ### 特色优势 与线上应用联动,利用线上Agent应用进行问答 ### 应用场景 使用SDK利用线上Agent应用进行问答 ## 基本用法 以下是使用SDK进行问答的示例代码,包含Python、Java、Go语言 ## Python基本用法 ### `AppBuilderClient().__init__()` #### 方法参数 | 参数名称 | 参数类型 | 描述 | 示例值 | | -------- | -------- | ----------------- | -------------- | | app_id | string | 线上Agent应用的ID | "正确的应用ID" | #### 方法返回值 ```AppBuilderClient```实例化对象 ### `AppBuilderClient().create_conversation()-> str` #### 方法参数 无 #### 方法返回值 | 参数名称 | 参数类型 | 描述 | 示例值 | | --------------- | -------- | -------- | -------------------------------------- | | conversation_id | string | 会话的ID | "80c5bbee-931d-4ed9-a4ff-63e1971bd071" | ### `AppBuilderClient().upload_local_file(file_path: str)-> str` #### 方法参数 | 参数名称 | 参数类型 | 描述 | 示例值 | | --------- | -------- | -------- | ---------------- | | file_path | string | 文件路径 | "正确的文件路径" | #### 方法返回值 | 参数名称 | 参数类型 | 描述 | 示例值 | | -------- | -------- | ------ | ---------------------------------- | | file_id | string | 文件ID | "80c5bbee-931d-4ed9-a4ff-63e1971bd | ### `AppBuilderClient().run() -> Message` #### 方法参数 | 参数名称 | 参数类型 | 是否必须 | 描述 | 示例值 | | --------------- | ------------------ | -------- | ------------------------------------------------------------ | ----------------- | | conversation_id | String | 是 | 会话ID | | | query | String | 否 | query问题内容 | "今天天气怎么样?" | | file_ids | list[String] | 否 | 对话可引用的文档ID | | | stream | Bool | 否 | 为true时则流式返回,为false时则一次性返回所有内容, 推荐设为true,降低首token时延 | False | | end_user_id | String | 否 | 终端用户ID,限制6 - 64字符 | | | tools | List[Tool] | 否 | 一个列表,其中每个字典对应一个工具的配置 | | | tools[0] | Tool | 否 | 工具配置 | | | +type | String | 否 | 枚举:
**file_retrieval**: 知识库检索工具能够理解文档内容,支持用户针对文档内容的问答。
**code_interpreter**: 代码解释器, 代码解释器能够生成并执行代码,从而协助用户解决复杂问题,涵盖科学计算(包括普通数学计算题)、数据可视化、文件编辑处理(图片、PDF文档、视频、音频等)、文件格式转换(如WAV、MP3、text、SRT、PNG、jpg、MP4、GIF、MP3等)、数据分析&清洗&处理(文件以excel、csv格式为主)、机器学习&深度学习建模&自然语言处理等多个领域。
**function**: 支持fucntion call模式调用工具 | | | +function | Function | 否 | Function工具描述
仅当**type为**`**function**` 时需要且必须填写 | | | ++name | String | 否 | 函数名
只允许数字、大小写字母和中划线和下划线,最大长度为64个字符。一次运行中唯一。 | | | ++description | String | 否 | 工具描述 | | | ++parameters | Dict | 否 | 工具参数, json_schema格式 | | | tool_outputs | List[ToolOutput] | 否 | 内容为本地的工具执行结果,以自然语言/json dump str描述 | | | tool_outputs[0] | ToolOutput | 否 | 工具执行结果 | | | +tool_call_id | String | 否 | 工具调用ID | | | +output | String | 否 | 工具输出 | | | tool_choice | ToolChoice | 否 | 控制大模型使用组件的方式,仅对自主规划Agent生效。 | | | +type | String | 否 | auto/function,auto表示由LLM自动判断调什么组件;function表示由用户指定调用哪个组件。 | | | +function | ToolChoiceFunction | 否 | 组件对象,包括组件的英文名称和入参 | | | ++name | String | 否 | 组件的英文名称(唯一标识) | | | ++input | String | 否 | 组件入参,当组件没有入参时填入空对象{} | | | action | Action | 否 | 对话时要进行的特殊操作。如回复工作流agent中“信息收集节点“的消息 | | | +action_type | String | 是 | 要执行的操作。
可选值为:
resume:回复“信息收集节点” 的消息 | | | +parameters | Object | 是 | 执行操作时所需的参数 | | #### Run方法非流式返回值 Run非流式方法返回一个`Message`对象,该对象包含以下属性: | 参数名称 | 参数类型 | 描述 | 示例值 | | -------------- | ---------------------- | -------------------- | --------------------------------------------------------------------------------------- | | content | AppBuilderClientAnswer | 对话返回结果 | | | +answer | String | 智能体应用返回的回答 | | | +events | List[Event] | 事件列表 | | | +events[0] | Event | 具体事件内容 | | | ++code | String | 错误码 | | | ++message | String | 错误具体消息 | | | ++status | String | 事件状态 | 状态描述,preparing(准备运行)running(运行中)error(执行错误) done(执行完成) | | ++event_type | String | 事件类型 | | | ++content_type | String | 内容类型 | 可选值包括:code text, image, status,image, function_call, rag, audio、video等 | | ++detail | Dict | 事件输出详情 | 代码解释器、文生图、工具组件、RAG等的详细输出内容 | | ++usage | Usage | 模型调用的token用量 | Usage(prompt_tokens=1322, completion_tokens=80, total_tokens=1402, name='DeepSeek-V3.1') | `AppBuilderClientAnswer`类型定义如下: ```python class AppBuilderClientAnswer(BaseModel): """执行步骤的具体内容 属性: answer(str): query回答内容 events( list[Event]): 事件列表 """ answer: str = "" events: list[Event] = [] ``` `Event`类型定义如下: ```python class Event(BaseModel): """执行步骤的具体内容 属性: code (int): 响应code码 message (str): 错误详情 status (str): 状态描述,preparing(准备运行)running(运行中)error(执行错误) done(执行完成) event_type(str): 事件类型 content_type(str): 内容类型 detail(dict): 事件详情 usage(Usage): 大模型调用的token用量 """ code: int = 0 message: str = "" status: str = "" event_type: str = "" content_type: str = "" detail: dict = {} usage: Optional[Usage] = None ``` #### Run方法流式返回值 | 参数名称 | 参数类型 | 描述 | 示例值 | | -------- | ---------------- | ---------------------------------------------- | ------ | | content | Python Generator | 可迭代,每次迭代返回AppBuilderClientAnswer类型 | 无 | #### 非流式调用示例 ```python import appbuilder import os # 请前往千帆AppBuilder官网创建密钥,流程详见:https://cloud.baidu.com/doc/AppBuilder/s/Olq6grrt6#1%E3%80%81%E5%88%9B%E5%BB%BA%E5%AF%86%E9%92%A5 # 设置环境变量 os.environ["APPBUILDER_TOKEN"] = '...' app_id = '...' # 已发布AppBuilder应用ID,可在console端查看 # 初始化智能体 builder = appbuilder.AppBuilderClient(app_id) # 创建会话 conversation_id = builder.create_conversation() # 运行对话 out = builder.run(conversation_id, "北京今天天气怎么样") # 打印会话结果 print(out.content.answer) ``` #### 流式调用示例 ```python import appbuilder from appbuilder.core.console.appbuilder_client import data_class import os # 请前往千帆AppBuilder官网创建密钥,流程详见:https://cloud.baidu.com/doc/AppBuilder/s/Olq6grrt6#1%E3%80%81%E5%88%9B%E5%BB%BA%E5%AF%86%E9%92%A5 # 设置环境变量 os.environ["APPBUILDER_TOKEN"] = '...' app_id = '...' # 已发布AppBuilder应用的ID # 初始化智能体 client = appbuilder.AppBuilderClient(app_id) # 创建会话 conversation_id = client.create_conversation() # 上传一个介绍某汽车产品的说明文档 file_id = client.upload_local_file(conversation_id, "/path/to/pdf/file") # 引用上传的文档,开始对话 # 注意file_ids不是必填项,如果不需要引用特定文档,file_ids留空即可 message = client.run(conversation_id, "汽车性能参数怎么样", file_ids=[file_id, ], stream=True) answer = "" # 每次迭代返回AppBuilderClientAnswer结构,内可能包括多个事件内容 for content in message.content: # stream=True时,将answer拼接起来才是完整的的对话结果 answer += content.answer for event in content.events: content_type = event.content_type detail = event.detail # 根据content类型对事件详情进行解析 if content_type == "code": code_detail = data_class.CodeDetail(**detail) print(code_detail.code) elif content_type == "text": text_detail = data_class.TextDetail(**detail) print(text_detail.text) elif content_type == "image": image_detail = data_class.ImageDetail(**detail) print(image_detail.url) elif content_type == "rag": rag_detail = data_class.RAGDetail(**detail) if len(rag_detail.references) > 0: print(rag_detail.references) elif content_type == "function_call": function_call_detail = data_class.FunctionCallDetail(**detail) print(function_call_detail.video) elif content_type == "audio": audio_detail = data_class.AudioDetail(**detail) print(audio_detail) elif content_type == "video": video_detail = data_class.VideoDetail(**detail) print(video_detail) elif content_type == "status": status_detail = data_class.StatusDetail(**detail) print(status_detail) else: default_detail = data_class.DefaultDetail(**detail) print(default_detail) # 打印完整的answer结果 print(answer) ``` ## Java基本用法 ### ```new AppBuilderClient(appId)``` #### 方法参数 | 参数名称 | 参数类型 | 描述 | 示例值 | | -------- | -------- | ----------------- | -------------- | | appID | String | 线上Agent应用的ID | "正确的应用ID" | #### 方法返回值 ```AppBuilderClient```实例化对象 ### ```AppBuilderClient().createConversation()``` #### 方法参数 无 #### 方法返回值 | 参数名称 | 参数类型 | 描述 | 示例值 | | -------------- | -------- | ------------ | -------------- | | conversationId | String | 创建的会话ID | "正确的会话ID" | ### ```AppBuilderClient().run()``` #### Run方法入参`AppBuilderCientRunRequest` | 参数名称 | 参数类型 | 是否必须 | 描述 | 示例值 | | --------------- | ------------------ | -------- | ------------------------------------------------------------ | -------------------- | | query | String | 是 | query内容 | "汽车性能参数怎么样" | | conversationId | String | 是 | 对话id,可以通过createConversation()获取 | | | stream | boolean | 是 | 为true时则流式返回,为false时则一次性返回所有内容, 推荐设为true,降低首token时延 | | | tools | List[Tool] | 否 | 一个列表,其中每个字典对应一个工具的配置 | | | tools[0] | Tool | 否 | 工具配置 | | | +type | String | 否 | 枚举:
**file_retrieval**: 知识库检索工具能够理解文档内容,支持用户针对文档内容的问答。
**code_interpreter**: 代码解释器, 代码解释器能够生成并执行代码,从而协助用户解决复杂问题,涵盖科学计算(包括普通数学计算题)、数据可视化、文件编辑处理(图片、PDF文档、视频、音频等)、文件格式转换(如WAV、MP3、text、SRT、PNG、jpg、MP4、GIF、MP3等)、数据分析&清洗&处理(文件以excel、csv格式为主)、机器学习&深度学习建模&自然语言处理等多个领域。
**function**: 支持fucntion call模式调用工具 | | | +function | Function | 否 | Function工具描述
仅当**type为**`**function**` 时需要且必须填写 | | | ++name | String | 否 | 函数名
只允许数字、大小写字母和中划线和下划线,最大长度为64个字符。一次运行中唯一。 | | | ++description | String | 否 | 工具描述 | | | ++parameters | Dict | 否 | 工具参数, json_schema格式 | | | tool_outputs | List[ToolOutput] | 否 | 内容为本地的工具执行结果,以自然语言/json dump str描述 | | | tool_outputs[0] | ToolOutput | 否 | 工具执行结果 | | | +tool_call_id | String | 否 | 工具调用ID | | | +output | String | 否 | 工具输出 | | | tool_choice | ToolChoice | 否 | 控制大模型使用组件的方式,仅对自主规划Agent生效。 | | | +type | String | 否 | auto/function,auto表示由LLM自动判断调什么组件;function表示由用户指定调用哪个组件。 | | | +function | ToolChoiceFunction | 否 | 组件对象,包括组件的英文名称和入参 | | | ++name | String | 否 | 组件的英文名称(唯一标识) | | | ++input | String | 否 | 组件入参,当组件没有入参时填入空对象{} | | | action | Action | 否 | 对话时要进行的特殊操作。如回复工作流agent中“信息收集节点“的消息 | | | +action_type | String | 是 | 要执行的操作。
可选值为:
resume:回复“信息收集节点” 的消息 | | | +parameters | Object | 是 | 执行操作时所需的参数 | | #### Run方法出参 | 参数名称 | 参数类型 | 描述 | 示例值 | | ------------------------ | ------------------------ | -------------------------------------------------------------------------------- | ------ | | AppBuilderClientIterator | AppBuilderClientIterator | 回答迭代器,流式/非流式均统一返回该类型,每次迭代返回AppBuilderClientIterator类型 | | #### 迭代AppBuilderClientIterator | 参数名称 | 参数类型 | 描述 | 示例值 | | ------------- | ------------------- | -------------------- | --------------------------------------------------------------------------------------- | | +answer | String | 智能体应用返回的回答 | | | +events | Event[] | 事件列表 | | | +events[0] | Event | 具体事件内容 | | | ++code | string | 错误码 | | | ++message | string | 错误具体消息 | | | ++status | string | 事件状态 | 状态描述,preparing(准备运行)running(运行中)error(执行错误) done(执行完成) | | ++eventType | string | 事件类型 | | | ++contentType | string | 内容类型 | 可选值包括:code text, image, status,image, function_call, rag, audio、video等 | | ++detail | Map | 事件输出详情 | 代码解释器、文生图、工具组件、RAG等的详细输出内容 | | ++usage | Usage | 模型调用的token用量 | Usage(prompt_tokens=1322, completion_tokens=80, total_tokens=1402, name='DeepSeek-V3.1') | #### 示例代码 ```Java package org.example; import java.io.IOException; import java.util.*; import com.google.gson.annotations.SerializedName; import com.baidubce.appbuilder.base.exception.AppBuilderServerException; import com.baidubce.appbuilder.console.appbuilderclient.AppBuilderClient; import com.baidubce.appbuilder.model.appbuilderclient.AppBuilderClientIterator; import com.baidubce.appbuilder.model.appbuilderclient.AppBuilderClientResult; import com.baidubce.appbuilder.model.appbuilderclient.Event; import com.baidubce.appbuilder.base.utils.json.JsonUtils; class AppBuilderClientDemo { public static void main(String[] args) throws IOException, AppBuilderServerException { System.setProperty("APPBUILDER_TOKEN", "请设置正确的应用密钥"); String appId = "请设置正确的应用ID"; AppBuilderClient builder = new AppBuilderClient(appId); String conversationId = builder.createConversation(); // 填写上传文件路径 String fileId = builder.uploadLocalFile(conversationId, "/Users/zhangxiaoyu15/PycharmProjects/app-builder/test_app_builder_client/test.pdf"); // 输入query // 注意file_ids不是必填项,如果不需要引用特定文档,则将new String[]{fileId}更换为new String[]{}即可 AppBuilderClientIterator itor = builder.run("中国四大传统节日是哪四个", conversationId, new String[]{fileId}, false); StringBuilder answer = new StringBuilder(); // itor.hasNext()返回false时,表示流式调用结束 while(itor.hasNext()) { AppBuilderClientResult response = itor.next(); answer.append(response.getAnswer()); for (Event event : response.getEvents()) { switch (event.getContentType()) { case "rag": List references = (List)event.getDetail().get("references"); for (Object reference : references) { ReferenceDetail ragDetail = JsonUtils.deserialize(JsonUtils.serialize(reference), ReferenceDetail.class); System.out.println("-----------------------------------"); System.out.println("参考文献ID:"+ragDetail.getId()); System.out.println("参考文献内容:"+ragDetail.getContent()); System.out.println("来源:"+ragDetail.getFrom()); System.out.println("BaiduSearch链接:"+ragDetail.getUrl()); System.out.println("类型:"+ragDetail.getType()); System.out.println("文档片段ID:"+ragDetail.getSegmentId()); System.out.println("文档ID:"+ragDetail.getDocumentId()); System.out.println("文档名称:"+ragDetail.getDocumentName()); System.out.println("文档所属数据集ID:"+ragDetail.getDatasetId()); System.out.println("-----------------------------------"); } break; default: // System.out.println(event); } } } System.out.print("输出:"); System.out.println(answer); } } class ReferenceDetail { private int id; private String content; private String from; private String url; private String type; @SerializedName("segment_id") private String segmentId; @SerializedName("document_id") private String documentId; @SerializedName("document_name") private String documentName; @SerializedName("dataset_id") private String datasetId; @SerializedName("knowledgebase_id") private String knowledgebaseId; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getContent() { return content; } public void setContent(String content) { this.content = content; } public String getFrom() { return from; } public void setFrom(String from) { this.from = from; } public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } public String getType() { return type; } public void setType(String type) { this.type = type; } public String getSegmentId() { return segmentId; } public void setSegmentId(String segmentId) { this.segmentId = segmentId; } public String getDocumentId() { return documentId; } public void setDocumentId(String documentId) { this.documentId = documentId; } public String getDocumentName() { return documentName; } public void setDocumentName(String documentName) { this.documentName = documentName; } public String getDatasetId() { return datasetId; } public void setDatasetId(String datasetId) { this.datasetId = datasetId; } public String getKnowledgebaseId() { return knowledgebaseId; } public void setKnowledgebaseId(String knowledgebaseId) { this.knowledgebaseId = knowledgebaseId; } @Override public String toString() { return "RAGReference{" + "id=" + id + ", content='" + content + '\'' + ", from='" + from + '\'' + ", url='" + url + '\'' + ", type='" + type + '\'' + ", segmentId='" + segmentId + '\'' + ", documentId='" + documentId + '\'' + ", documentName='" + documentName + '\'' + ", datasetId='" + datasetId + '\'' + ", knowledgebaseId='" + knowledgebaseId + '\'' + '}'; } } ``` ## Go基本用法 ### ```NewAppBuilderClient()``` #### 方法参数 | 参数名称 | 参数类型 | 描述 | 示例值 | | -------- | --------- | ----------------- | -------------- | | app_id | string | 线上Agent应用的ID | "正确的应用ID" | | config | SDKConfig | SDK配置信息 | | ### ```CreateConversation()``` #### 方法入参 无 #### 方法出参 | 参数名称 | 参数类型 | 描述 | 示例值 | | -------------- | -------- | -------------------------------------------- | ------ | | ConversationId | str | 创建成功的对话对象,后续操作都基于该对象进行 | | ### `Run()` #### Run方法入参`AppBuilderClientRunRequest` | 参数名称 | 参数类型 | 是否必须 | 描述 | 示例值 | | -------------- | ---------- | -------- | ------------------------------------------------------------ | -------------------- | | ConversationID | string | 是 | 对话ID,可以通过CreateConversation()获取 | | | Query | string | 是 | query内容 | "汽车性能参数怎么样" | | Stream | bool | 是 | 为true时则流式返回,为false时则一次性返回所有内容, 推荐设为true,降低首token时延 | | | AppID | string | 是 | 应用ID,线上Agent应用的ID | | | Tools | []Tool | 否 | 一个列表,其中每个字典对应一个工具的配置 | | | ToolOuptus | []ToolOupt | 否 | 内容为本地的工具执行结果,以自然语言/json dump str描述 | | | ToolChoice | ToolChoice | 否 | 控制大模型使用组件的方式,仅对自主规划Agent生效。 | | `Tool`、`ToolOutput`、`ToolChoice`定义如下: ```go type Tool struct { Type string `json:"type"` Function Function `json:"function"` } type Function struct { Name string `json:"name"` Description string `json:"description"` Parameters map[string]interface{} `json:"parameters"` } type ToolOutput struct { ToolCallID string `json:"tool_call_id" description:"工具调用ID"` Output string `json:"output" description:"工具输出"` } type ToolChoice struct { Type string `json:"type"` Function ToolChoiceFunction `json:"function"` } type ToolChoiceFunction struct { Name string `json:"name"` Input map[string]interface{} `json:"input"` } ``` #### Run方法出参 | 参数名称 | 参数类型 | 描述 | 示例值 | | ------------------------ | ------------------------ | --------------------------------------- | ------ | | AppBuilderClientIterator | AppBuilderClientIterator | 回答迭代器,流式/非流式均统一返回该类型 | | | error | error | 存在错误时error不为nil,反之 | | #### 迭代AgentBuilderIterator | 参数名称 | 参数类型 | 描述 | 示例值 | | ------------- | ----------- | -------------------- | --------------------------------------------------------------------------------------- | | +Answer | string | 智能体应用返回的回答 | | | +Events | []Event | 事件列表 | | | +Events[0] | Event | 具体事件内容 | | | ++Code | string | 错误码 | | | ++Message | string | 错误具体消息 | | | ++Status | string | 事件状态 | 状态描述,preparing(准备运行)running(运行中)error(执行错误) done(执行完成) | | ++EventType | string | 事件类型 | | | ++ContentType | string | 内容类型 | 可选值包括:code text, image, status,image, function_call, rag, audio、video等 | | ++Detail | interface{} | 事件输出详情 | 代码解释器、文生图、工具组件、RAG等的详细输出内容 | | ++Usage | Usage | 模型调用的token用量 | Usage(prompt_tokens=1322, completion_tokens=80, total_tokens=1402, name='DeepSeek-V3.1') | #### Run示例代码 ```Go // 安装说明: // go get github.com/baidubce/app-builder/go/appbuilder package main import ( "errors" "fmt" "io" "os" "github.com/baidubce/app-builder/go/appbuilder" ) func main() { // 设置环境中的TOKEN,以下TOKEN请替换为您的个人TOKEN,个人TOKEN可通过该页面【获取鉴权参数】或控制台页【密钥管理】处获取 os.Setenv("APPBUILDER_TOKEN", "bce-v3/ALTAK-xxx90ea58") // 从AppBuilder控制台【个人空间】-【应用】网页获取已发布应用的ID appID := "4678492a-xxx-654538d3503c" config, err := appbuilder.NewSDKConfig("", "") if err != nil { fmt.Println("new config failed: ", err) return } builder, err := appbuilder.NewAppBuilderClient(appID, config) if err != nil { fmt.Println("new agent builder failed: ", err) return } conversationID, err := builder.CreateConversation() if err != nil { fmt.Println("create conversation failed: ", err) return } i, err := builder.Run(conversationID, "你好,你能做什么?", nil, false) if err != nil { fmt.Println("run failed: ", err) return } var answer *appbuilder.AppBuilderClientAnswer for answer, err = i.Next(); err == nil; answer, err = i.Next() { fmt.Println(answer.Answer) } } ``` #### ToolCall功能示例代码 ```go package main import ( "errors" "fmt" "io" "os" "github.com/baidubce/app-builder/go/appbuilder" ) func main() { // 设置APPBUILDER_TOKEN、GATEWAY_URL_V2环境变量 os.Setenv("APPBUILDER_TOKEN", "请设置正确的应用密钥") // 默认可不填,默认值是 https://qianfan.baidubce.com os.Setenv("GATEWAY_URL_V2", "") config, err := appbuilder.NewSDKConfig("", "") if err != nil { fmt.Println("new config failed: ", err) return } // 初始化实例 appID := "请填写正确的应用ID" builder, err := appbuilder.NewAppBuilderClient(appID, config) if err != nil { fmt.Println("new agent builder failed: ", err) return } // 创建对话ID conversationID, err := builder.CreateConversation() if err != nil { fmt.Println("create conversation failed: ", err) return } jsonStr := ` { "type": "function", "function": { "name": "get_cur_whether", "description": "这是一个获得指定地点天气的工具", "parameters": { "type": "object", "properties": { "location": { "type": "string", "description": "省,市名,例如:河北省" }, "unit": { "type": "string", "enum": ["摄氏度", "华氏度"] } }, "required": ["location"] } } }` var tool Tool err = json.Unmarshal([]byte(jsonStr), &tool) if err != nil { fmt.Println("unmarshal tool error:", err) return } i, err := client.Run(appbuilder.AppBuilderClientRunRequest{ AppID: appID, Query: "今天北京的天气怎么样?", ConversationID: conversationID, Stream: true, Tools: []appbuilder.Tool{tool}, }) if err != nil { fmt.Println("run failed:", err) } totalAnswer := "" toolCallID := "" for answer, err := i.Next(); err == nil; answer, err = i.Next() { totalAnswer += answer.Answer lastEvent := answer.Events[len(answer.Events)-1] toolCallID = lastEvent.ToolCalls[len(lastEvent.ToolCalls)-1].ID } i2, err := client.Run(appbuilder.AppBuilderClientRunRequest{ ConversationID: conversationID, AppID: appID, ToolOutputs: []appbuilder.ToolOutput{ { ToolCallID: toolCallID, Output: "北京今天35度", }, }, Stream: true, }) if err != nil { fmt.Println("run failed: ", err) } for answer, err := i2.Next(); err == nil; answer, err = i2.Next() { totalAnswer = totalAnswer + answer.Answer for _, ev := range answer.Events { evJSON, _ := json.Marshal(ev) fmt.Println(string(evJSON)) } } fmt.Println("----------------answer-------------------") fmt.Println(totalAnswer) } ``` ================================================ FILE: docs/Application/Agent/ToolCall/tool_call.md ================================================ # Agent 本地ToolCall(Functioncall) ## 概述 ### 什么是ToolCall 解释该问题,需要了解以下的知识点:`Agent工具` -> `FunctionCall` - `ToolCall` AIAgent 有四大核心组件:记忆、规划、工具和执行。其中工具部分,与我们的开发关系最密切,在各类Agent开发平台/工具中,常被称为“组件”、"插件"、"能力"等. 关于Agent的工具的定义与分类,如下图~ drawing Agent使用工具的流程,一般称为`FunctionCall`,最早由OpenAI提出,并在[Assistant API](https://platform.openai.com/docs/assistants/overview)中广泛应用。 ToolCall,则是AppBuilder平台提出的一种进阶的FunctionCall,本质与OpenAI的FunctionCall一致,但具有以下两个特点: - **端云组件联动**: Agent 调用工具时,可以同时调用云端和本地组件。 - **组件类型泛化**: AppBuilder在未来会支持多种类型组件,已经超出了Function的含义,例如数据库、记忆库、工作流等等 ### 什么是端云组件联动,要解决什么问题 我们首先从工具的执行位置出发展开~ 在使用如AppBuilder / Coze 等平台开发Agent时,我们可以使用很多平台组件广场中,官方提供的组件,这里组件开箱即用,非常方便。 drawing 但是存在一个问题,基于平台云端组件开发的应用,无法调用内网/局域网/私域的知识与能力,也无法与本地的工具进行联动,限制了Agent的灵活性。 我们在解决实际业务问题时,常遇到需要访问内网链接API或本地/硬件功能的FunctionCall需求,AppBuilder ToolCall可以解决这个问题: * 1、用户可注册一个本地运行的组件到已发布的应用 * 2、由AppBuilder-Agent的云端思考模型进行规划和参数生成 * 3、用户基于生成的参数调用本地组件,并再上传运行结果 * 4、以此实现将本地组件能力嵌入到应用整体流程 drawing ## ToolCall(FunctionCall)基础知识介绍 ### Agent是如何调用Tool的 我们可以将Agent的黑箱拆解为以下几个部分: 1. Agent的背景信息 2. Agent的输入信息 3. Agent的思考过程 4. Agent触发组件调用 5. Agent基于组件输出反思总结 #### Agent的背景信息包含以下几个部分 - 角色定义描述(Prompt):定义Agent的角色 - 能力描述(Prompt):定义Agent可以干什么 - 工具描述(JsonSchema/Str):将工具的输入和输出,按照规范,定义为一段字符串,作为最终大模型Prompt的一部分 #### Agent的输入信息包含以下几个部分 - 用户输入(Query/Prompt):用户输入的文本 - 对话相关的文件(File/Url):与本地对话相关的文件路径 #### Agent的思考过程 AppBuilder-Agent会将背景信息与输入信息,拼接为最终的Prompt,然后调用大模型推理。 Prompt的一个简单且直观的例子是: 你是`{角色定义描述}`,你可以做以下事情:`{能力描述}`,你可以使用这些工具:`{工具描述-description}`,工具依赖的输入是:`{工具描述-paramters-properties-name}`,这些输入的格式分别是`{工具描述-paramters-properties-type}`。现在用户的问题是`{用户输入}`,与该问题相关的文件是`{对话相关的文件}`,请你解决用户的这个问题。 #### Agent触发组件调用 如果用户的query和组件能够解决的问题匹配,那么大模型就会尝试根据prompt里给出的工具的描述,从query中提炼出该次调用工具所需的参数,生成一个ToolCall命令,交给执行组件的模块去执行。 例如,我们给出的组件能力是"查找公司内指定人员的信息",函数的参数名为"name"。当用户输入"查找张三的信息",大模型会从query中提炼出参数"name=张三"这个信息。 drawing #### Agent基于组件输出反思总结 组件运行模块执行组件后,会给出字符串形式的结果给到Agent,Agent会再次将结果拼接为Prompt,然后调用大模型推理。判断用户的需求是否已经解决。如果解决了,则经过一个对话模块,总结用户的需求,并生成一个对话记录。如果未解决,则继续调用大模型推理,尝试调用更多的工具,直到用户的需求被解决。 ### 开发者如何命令Agent调用本地Tool 我们以AppBuilder-SDK中的AppBuilder-Client的基础代码为例,介绍开发者应该如何使用ToolCall功能 ```python import appbuilder # 实例化AppBuilderClient app_client = appbuilder.AppBuilderClient(app_id) conversation_id = app_client.create_conversation() # 第一次对话,输入原始的query 和 工具描述 message_1 = app_client.run( conversation_id=conversation_id, query="请问张三同学的生日是哪天?", tools=tools ) tool_call = message_1.content.events[-1].tool_calls[-1] tool_call_id = tool_call.id # 第二次对话,在本地执行组件后,上传组件的运行结果 tool_call_result = "张三同学的生日是2008年8月8日" message_2 = app_client.run( conversation_id=conversation_id, tool_outputs=[{ "tool_call_id": tool_call_id, "output": tool_call_result }] ) print(message_2.content) ``` 其中`AppBuilderClient`的`run`方法是核心,我们展开该函数的定义和参数介绍: `AppBuilderClient().run() -> Message` ```python def run(self, conversation_id: str, query: str = "", file_ids: list = [], stream: bool = False, tools: list[data_class.Tool] = None, tool_outputs: list[data_class.ToolOutput] = None, **kwargs ) -> Message: r""" 参数: query (str: 必须): query内容 conversation_id (str, 必须): 唯一会话ID,如需开始新的会话,请使用self.create_conversation创建新的会话 file_ids(list[str], 可选): stream (bool, 可选): 为True时,流式返回,需要将message.content.answer拼接起来才是完整的回答;为False时,对应非流式返回 tools(list[data_class.Tools], 可选): 一个Tools组成的列表,其中每个Tools对应一个工具的配置, 默认为None tool_outputs(list[data_class.ToolOutput], 可选): 工具输出列表,格式为list[ToolOutput], ToolOutputd内容为本地的工具执行结果,以自然语言/json dump str描述,默认为None 返回: message (obj: `Message`): 对话结果. """ pass ``` | 参数名称 | 参数类型 | 是否必须 | 描述 | 示例值 | | --------------- | ---------------- | -------- | ------------------------------------------------------------ | ----------------- | | conversation_id | String | 是 | 会话ID | | | query | String | 否 | query问题内容 | "今天天气怎么样?" | | file_ids | list[String] | 否 | 对话可引用的文档ID | | | stream | Bool | 否 | 为true时则流式返回,为false时则一次性返回所有内容, 推荐设为true,降低首token时延 | False | | tools | List[Tool] | 否 | 一个列表,其中每个字典对应一个工具的配置 | | | tools[0] | Tool | 否 | 工具配置 | | | +type | String | 否 | 枚举:
**file_retrieval**: 知识库检索工具能够理解文档内容,支持用户针对文档内容的问答。
**code_interpreter**: 代码解释器, 代码解释器能够生成并执行代码,从而协助用户解决复杂问题,涵盖科学计算(包括普通数学计算题)、数据可视化、文件编辑处理(图片、PDF文档、视频、音频等)、文件格式转换(如WAV、MP3、text、SRT、PNG、jpg、MP4、GIF、MP3等)、数据分析&清洗&处理(文件以excel、csv格式为主)、机器学习&深度学习建模&自然语言处理等多个领域。
**function**: 支持fucntion call模式调用工具 | | | +function | Function | 否 | Function工具描述
仅当**type为**`**function**` 时需要且必须填写 | | | ++name | String | 否 | 函数名
只允许数字、大小写字母和中划线和下划线,最大长度为64个字符。一次运行中唯一。 | | | ++description | String | 否 | 工具描述 | | | ++parameters | Dict | 否 | 工具参数, json_schema格式 | | | tool_outputs | List[ToolOutput] | 否 | 内容为本地的工具执行结果,以自然语言/json dump str描述 | | | tool_outputs[0] | ToolOutput | 否 | 工具执行结果 | | | +tool_call_id | String | 否 | 工具调用ID | | | +output | String | 否 | 工具输出 | | `Tool`与`Function`是本地组件的描述,类型为object,其定义如下: ```python class Tool(BaseModel): type: str = "function" function: Function = Field(..., description="工具信息") class Function(BaseModel): name: str = Field(..., description="工具名称") description: str = Field(..., description="工具描述") parameters: dict = Field(..., description="工具参数, json_schema格式") ``` `ToolOutput`是本地组件的执行结果,需要再次上传到Agent,参与思考,类型为object,其定义如下: ```python class ToolOutput(BaseModel): tool_call_id: str = Field(..., description="工具调用ID") output: str = Field(..., description="工具输出") ``` #### Run方法带ToolCall调用示例--Python 以下示例展示了三种方式来使用 ToolCall 进行调用,并演示了如何在 AppBuilder 环境中配置和执行会话调用。 **方式1:使用 JSONSchema 格式直接描述 tools 调用** ```python import appbuilder from appbuilder.core.console.appbuilder_client import data_class import os # 请前往千帆AppBuilder官网创建密钥,流程详见:https://cloud.baidu.com/doc/AppBuilder/s/Olq6grrt6#1%E3%80%81%E5%88%9B%E5%BB%BA%E5%AF%86%E9%92%A5 # 设置环境变量 os.environ["APPBUILDER_TOKEN"] = "..." app_id = "..." # 已发布AppBuilder应用的ID # 初始化智能体 client = appbuilder.AppBuilderClient(app_id) # 创建会话 conversation_id = client.create_conversation() tools = [ { "type": "function", "function": { "name": "get_current_weather", "description": "仅支持中国城市的天气查询,参数location为中国城市名称,其他国家城市不支持天气查询", "parameters": { "type": "object", "properties": { "location": { "type": "string", "description": "城市名,举例:北京", }, "unit": {"type": "string", "enum": ["celsius", "fahrenheit"]}, }, "required": ["location", "unit"], }, }, } ] msg = client.run( conversation_id=conversation_id, query="今天北京天气怎么样?", tools=tools ) print(msg.model_dump_json(indent=4)) event = msg.content.events[-1] msg_2 = client.run( conversation_id=conversation_id, tool_outputs=[{"tool_call_id": event.tool_calls[-1].id, "output": "北京今天35度"}], ) print(msg_2.model_dump_json(indent=4)) ``` **方式2: 使用 function_to_model 将函数对象传递为 ToolCall 的调用** ```python import appbuilder import os # 请前往千帆AppBuilder官网创建密钥,流程详见:https://cloud.baidu.com/doc/AppBuilder/s/Olq6grrt6#1%E3%80%81%E5%88%9B%E5%BB%BA%E5%AF%86%E9%92%A5 # 设置环境变量 os.environ["APPBUILDER_TOKEN"] = "..." app_id = "..." # 已发布AppBuilder应用的ID # 初始化智能体 client = appbuilder.AppBuilderClient(app_id) # 创建会话 conversation_id = client.create_conversation() #注意:要使用此方法要为函数写好注释。最好按照谷歌规范来写 #定义示例函数 def get_current_weather(location: str, unit: str) -> str: """获取指定中国城市的当前天气信息。 仅支持中国城市的天气查询。参数 `location` 为中国城市名称,其他国家城市不支持天气查询。 Args: location (str): 城市名,例如:"北京"。 unit (int): 温度单位,支持 "celsius" 或 "fahrenheit"。 Returns: str: 天气情况描述 """ return "北京今天25度" #定义函数列表 functions = [get_current_weather] function_map = {f.__name__: f for f in functions} #调用大模型 msg = client.run( conversation_id=conversation_id, query="今天北京的天气怎么样?", tools = [appbuilder.Manifest.from_function(f) for f in functions] ) print(msg.model_dump_json(indent=4)) # 获取最后的事件和工具调用信息 event = msg.content.events[-1] tool_call = event.tool_calls[-1] # 获取函数名称和参数 name = tool_call.function.name args = tool_call.function.arguments # 将函数名称映射到具体的函数并执行 raw_result = function_map[name](**args) # 传递工具的输出 msg_2 = client.run( conversation_id=conversation_id, tool_outputs=[{ "tool_call_id": tool_call.id, "output": str(raw_result) }], ) print(msg_2.model_dump_json(indent=4)) ``` **方式3: 使用装饰器进行描述** ```python import os import json import appbuilder from appbuilder import manifest, manifest_parameter # 请前往千帆AppBuilder官网创建密钥,流程详见:https://cloud.baidu.com/doc/AppBuilder/s/Olq6grrt6#1%E3%80%81%E5%88%9B%E5%BB%BA%E5%AF%86%E9%92%A5 # 设置环境变量 os.environ["APPBUILDER_TOKEN"] = "" app_id = "" # 已发布AppBuilder应用的ID # 初始化智能体 client = appbuilder.AppBuilderClient(app_id) # 创建会话 conversation_id = client.create_conversation() #使用manifest装饰描述函数,manifest_parameter装饰器描述参数,manifest_return装饰器描述函数返回值。 @manifest(description="获取指定中国城市的当前天气信息。仅支持中国城市的天气查询。参数 `location` 为中国城市名称,其他国家城市不支持天气查询。") @manifest_parameter(name="location", description="城市名,例如:北京。") @manifest_parameter(name="unit", description="温度单位,支持 'celsius' 或 'fahrenheit'") #定义示例函数 def get_current_weather(location: str, unit: str) -> str: return "北京今天25度" print(json.dumps(appbuilder.Manifest.from_function(get_current_weather), indent=4, ensure_ascii=False)) #定义函数列表 functions = [get_current_weather] function_map = {f.__name__: f for f in functions} #调用大模型 msg = client.run( conversation_id=conversation_id, query="今天北京的天气怎么样?", tools = [appbuilder.Manifest.from_function(f) for f in functions] ) print(msg.model_dump_json(indent=4)) # 获取最后的事件和工具调用信息 event = msg.content.events[-1] tool_call = event.tool_calls[-1] # 获取函数名称和参数 name = tool_call.function.name args = tool_call.function.arguments # 将函数名称映射到具体的函数并执行 raw_result = function_map[name](**args) # 传递工具的输出 msg_2 = client.run( conversation_id=conversation_id, tool_outputs=[{ "tool_call_id": tool_call.id, "output": str(raw_result) }], ) print(msg_2.model_dump_json(indent=4)) ``` #### Run方法带ToolCall调用示例--Java **创建tool的json文件** ```json { "type": "function", "function": { "name": "get_cur_whether", "description": "这是一个获得指定地点天气的工具", "parameters": { "type": "object", "properties": { "location": { "type": "string", "description": "省,市名,例如:河北省" }, "unit": { "type": "string", "enum": [ "摄氏度", "华氏度" ] } }, "required": [ "location" ] } } } ``` ```java package org.example; import java.io.IOException; import java.util.*; import com.google.gson.annotations.SerializedName; import com.baidubce.appbuilder.base.exception.AppBuilderServerException; import com.baidubce.appbuilder.console.appbuilderclient.AppBuilderClient; import com.baidubce.appbuilder.model.appbuilderclient.AppBuilderClientIterator; import com.baidubce.appbuilder.model.appbuilderclient.AppBuilderClientResult; import com.baidubce.appbuilder.model.appbuilderclient.Event; import com.baidubce.appbuilder.base.utils.json.JsonUtils; class AppBuilderClientDemo { public static void main(String[] args) throws IOException, AppBuilderServerException { System.setProperty("APPBUILDER_TOKEN", "请设置正确的应用密钥"); String appId = "请设置正确的应用ID"; AppBuilderClient builder = new AppBuilderClient(appId); String conversationId = builder.createConversation(); AppBuilderClientRunRequest request = new AppBuilderClientRunRequest(appId, conversationId, "今天北京的天气怎么样?", false); String toolJson = new String(Files.readAllBytes(Paths.get("json文件所在的路径"))); request.setTools(toolJson); AppBuilderClientIterator itor = builder.run(request); String ToolCallID = ""; while (itor.hasNext()) { AppBuilderClientResult result = itor.next(); Event lastEvent = result.getEvents()[result.getEvents().length - 1]; ToolCallID = lastEvent.getToolCalls()[lastEvent.getToolCalls().length - 1].getId(); System.out.println(result); } AppBuilderClientRunRequest request2 = new AppBuilderClientRunRequest(appId, conversationId); request2.setToolOutputs(ToolCallID, "北京今天35度"); AppBuilderClientIterator itor2 = builder.run(request2); while (itor2.hasNext()) { AppBuilderClientResult result = itor2.next(); System.out.println(result); } } } ``` #### ToolCall功能示例代码--Go ```go package main import ( "errors" "fmt" "io" "os" "github.com/baidubce/app-builder/go/appbuilder" ) func main() { // 设置APPBUILDER_TOKEN、GATEWAY_URL_V2环境变量 os.Setenv("APPBUILDER_TOKEN", "请设置正确的应用密钥") // 默认可不填,默认值是 https://qianfan.baidubce.com os.Setenv("GATEWAY_URL_V2", "") config, err := appbuilder.NewSDKConfig("", "") if err != nil { fmt.Println("new config failed: ", err) return } // 初始化实例 appID := "请填写正确的应用ID" builder, err := appbuilder.NewAppBuilderClient(appID, config) if err != nil { fmt.Println("new agent builder failed: ", err) return } // 创建对话ID conversationID, err := builder.CreateConversation() if err != nil { fmt.Println("create conversation failed: ", err) return } jsonStr := ` { "type": "function", "function": { "name": "get_cur_whether", "description": "这是一个获得指定地点天气的工具", "parameters": { "type": "object", "properties": { "location": { "type": "string", "description": "省,市名,例如:河北省" }, "unit": { "type": "string", "enum": ["摄氏度", "华氏度"] } }, "required": ["location"] } } }` var tool Tool err = json.Unmarshal([]byte(jsonStr), &tool) if err != nil { fmt.Println("unmarshal tool error:", err) return } i, err := client.Run(appbuilder.AppBuilderClientRunRequest{ AppID: appID, Query: "今天北京的天气怎么样?", ConversationID: conversationID, Stream: true, Tools: []appbuilder.Tool{tool}, }) if err != nil { fmt.Println("run failed:", err) } totalAnswer := "" toolCallID := "" for answer, err := i.Next(); err == nil; answer, err = i.Next() { totalAnswer += answer.Answer lastEvent := answer.Events[len(answer.Events)-1] toolCallID = lastEvent.ToolCalls[len(lastEvent.ToolCalls)-1].ID } i2, err := client.Run(appbuilder.AppBuilderClientRunRequest{ ConversationID: conversationID, AppID: appID, ToolOutputs: []appbuilder.ToolOutput{ { ToolCallID: toolCallID, Output: "北京今天35度", }, }, Stream: true, }) if err != nil { fmt.Println("run failed: ", err) } for answer, err := i2.Next(); err == nil; answer, err = i2.Next() { totalAnswer = totalAnswer + answer.Answer for _, ev := range answer.Events { evJSON, _ := json.Marshal(ev) fmt.Println(string(evJSON)) } } fmt.Println("----------------answer-------------------") fmt.Println(totalAnswer) } ``` #### ToolChoice示例代码 * 注意:当前功能为试运行阶段,可能存在如下问题,如使用过程遇到其他问题,欢迎提issue或微信群讨论。 * 需开启"组件/知识库结论可直接作为回复" * 组件名称不是界面上的原始名字,而是个人空间组件列表中的英文名 * 自定义组件的参数不能使用系统参数,可以使用用户添加的参数 * 部分官方组件使用的参数与界面上的参数不一致 ```go package main import ( "errors" "fmt" "io" "os" "github.com/baidubce/app-builder/go/appbuilder" ) func main() { // 设置APPBUILDER_TOKEN、GATEWAY_URL_V2环境变量 os.Setenv("APPBUILDER_TOKEN", "请设置正确的应用密钥") // 默认可不填,默认值是 https://qianfan.baidubce.com os.Setenv("GATEWAY_URL_V2", "") config, err := appbuilder.NewSDKConfig("", "") if err != nil { fmt.Println("new config failed: ", err) return } // 初始化实例 appID := "请填写正确的应用ID" builder, err := appbuilder.NewAppBuilderClient(appID, config) if err != nil { fmt.Println("new agent builder failed: ", err) return } // 创建对话ID conversationID, err := builder.CreateConversation() if err != nil { fmt.Println("create conversation failed: ", err) return } // 注意使用创建应用中用到的组件。名称、参数均以实际使用的组件为准。 input := make(map[string]any) input["city"] = "北京" end_user_id := "go_toolchoice_demo" i, err := client.Run(AppBuilderClientRunRequest{ ConversationID: conversationID, AppID: appID, Query: "", EndUserID: &end_user_id, Stream: false, ToolChoice: &ToolChoice{ Type: "function", Function: ToolChoiceFunction{ Name: "WeatherQuery", Input: input, }, }, }) if err != nil { fmt.Println("run failed: ", err) return } for answer, err := i.Next(); err == nil; answer, err = i.Next() { for _, ev := range answer.Events { evJSON, _ := json.Marshal(ev) fmt.Println(string(evJSON)) } } } ``` ================================================ FILE: docs/Application/Agent/ToolChoice/tool_choice.md ================================================ # ToolChoice #### Run方法带ToolChoice使用示例: * 注意:当前功能为试运行阶段,可能存在如下问题,如使用过程遇到其他问题,欢迎提issue或微信群讨论。 * 需开启"组件/知识库结论可直接作为回复" * 组件名称不是界面上的原始名字,而是个人空间组件列表中的英文名 * 自定义组件的参数不能使用系统参数,可以使用用户添加的参数 * 部分官方组件使用的参数与界面上的参数不一致 ```python import appbuilder import os # 请前往千帆AppBuilder官网创建密钥,流程详见:https://cloud.baidu.com/doc/AppBuilder/s/Olq6grrt6#1%E3%80%81%E5%88%9B%E5%BB%BA%E5%AF%86%E9%92%A5 # 设置环境变量 os.environ["APPBUILDER_TOKEN"] = "..." app_id = "..." # 已发布AppBuilder应用的ID # 初始化智能体 client = appbuilder.AppBuilderClient(app_id) # 创建会话 conversation_id = client.create_conversation() # 注意使用创建应用中用到的组件。名称、参数均以实际使用的组件为准。 answer = app_builder_client.run( conversation_id, "北京今天的天气", stream=False, end_user_id="user_id_toolchoice", tool_choice={ "type": "function", "function": {"name": "WeatherQuery", "input": {"city": "北京"}}, }, ) ``` #### Run方法带Toolchoice使用示例--Java * 注意:当前功能为试运行阶段,可能存在如下问题,如使用过程遇到其他问题,欢迎提issue或微信群讨论。 * 需开启"组件/知识库结论可直接作为回复" * 组件名称不是界面上的原始名字,而是个人空间组件列表中的英文名 * 自定义组件的参数不能使用系统参数,可以使用用户添加的参数 * 部分官方组件使用的参数与界面上的参数不一致 ```java package org.example; import java.io.IOException; import java.util.*; import com.google.gson.annotations.SerializedName; import com.baidubce.appbuilder.base.exception.AppBuilderServerException; import com.baidubce.appbuilder.console.appbuilderclient.AppBuilderClient; import com.baidubce.appbuilder.model.appbuilderclient.AppBuilderClientIterator; import com.baidubce.appbuilder.model.appbuilderclient.AppBuilderClientResult; import com.baidubce.appbuilder.model.appbuilderclient.AppBuilderClientRunRequest; import com.baidubce.appbuilder.model.appbuilderclient.Event; import com.baidubce.appbuilder.base.utils.json.JsonUtils; class AppBuilderClientDemo { public static void main(String[] args) throws IOException, AppBuilderServerException { System.setProperty("APPBUILDER_TOKEN", "请设置正确的应用密钥"); String appId = "请设置正确的应用ID"; AppBuilderClient builder = new AppBuilderClient(appId); String conversationId = builder.createConversation(); AppBuilderClientRunRequest request = new AppBuilderClientRunRequest(appId, conversationId, "你能干什么", false); request.setEndUserId("java_toolchoice_demo"); // 注意使用创建应用中用到的组件。名称、参数均以实际使用的组件为准。 Map input = new HashMap<>(); input.put("city", "北京"); AppBuilderClientRunRequest.ToolChoice.Function func = new AppBuilderClientRunRequest.ToolChoice.Function( "WeatherQuery", input); AppBuilderClientRunRequest.ToolChoice choice = new AppBuilderClientRunRequest.ToolChoice("function", func); request.setToolChoice(choice); AppBuilderClientIterator itor = builder.run(request); while (itor.hasNext()) { AppBuilderClientResult result = itor.next(); System.out.println(result); } } } ``` #### ToolChoice示例代码--Go * 注意:当前功能为试运行阶段,可能存在如下问题,如使用过程遇到其他问题,欢迎提issue或微信群讨论。 * 需开启"组件/知识库结论可直接作为回复" * 组件名称不是界面上的原始名字,而是个人空间组件列表中的英文名 * 自定义组件的参数不能使用系统参数,可以使用用户添加的参数 * 部分官方组件使用的参数与界面上的参数不一致 ```go package main import ( "errors" "fmt" "io" "os" "github.com/baidubce/app-builder/go/appbuilder" ) func main() { // 设置APPBUILDER_TOKEN、GATEWAY_URL_V2环境变量 os.Setenv("APPBUILDER_TOKEN", "请设置正确的应用密钥") // 默认可不填,默认值是 https://qianfan.baidubce.com os.Setenv("GATEWAY_URL_V2", "") config, err := appbuilder.NewSDKConfig("", "") if err != nil { fmt.Println("new config failed: ", err) return } // 初始化实例 appID := "请填写正确的应用ID" builder, err := appbuilder.NewAppBuilderClient(appID, config) if err != nil { fmt.Println("new agent builder failed: ", err) return } // 创建对话ID conversationID, err := builder.CreateConversation() if err != nil { fmt.Println("create conversation failed: ", err) return } // 注意使用创建应用中用到的组件。名称、参数均以实际使用的组件为准。 input := make(map[string]any) input["city"] = "北京" end_user_id := "go_toolchoice_demo" i, err := client.Run(AppBuilderClientRunRequest{ ConversationID: conversationID, AppID: appID, Query: "", EndUserID: &end_user_id, Stream: false, ToolChoice: &ToolChoice{ Type: "function", Function: ToolChoiceFunction{ Name: "WeatherQuery", Input: input, }, }, }) if err != nil { fmt.Println("run failed: ", err) return } for answer, err := i.Next(); err == nil; answer, err = i.Next() { for _, ev := range answer.Events { evJSON, _ := json.Marshal(ev) fmt.Println(string(evJSON)) } } } ``` ================================================ FILE: docs/Application/Agent/UseOfficialComponents/use_official_components.md ================================================ # Client应用调用官方组件 ## 简介 Agent是基于线上Agent应用的问答组件,可以使用该组件利用线上Agent应用进行问答,同时可以在线上为Client应用添加组件,丰富Agent能力。 ## Agent添加Components官方组件 整体使用流程包括以下两个环节: 1. 在[百度智能云千帆AppBuilder官网](https://cloud.baidu.com/product/AppBuilder)创建并发布应用(在创建应用时可添加官方组件)、获取应用ID、获取密钥 2. 引用AppBuilderSDK代码,初始化AppBuilderClient实例、创建会话、上传文档(可选)、执行对话 ## 示例 - 接下来将展示创建一个机票查询Agent应用,并添加官方组件。 ### 创建应用 - 创建应用并添加自己的角色指令,并按照自己的需求设置模型、记忆功能等参数 ![](https://bj.bcebos.com/v1/appbuilder-sdk-components/%E5%88%9B%E5%BB%BA%E8%88%AA%E7%8F%AD%E6%9F%A5%E8%AF%A2%E5%BA%94%E7%94%A8.png?authorization=bce-auth-v1%2FALTAKGa8m4qCUasgoljdEDAzLm%2F2024-12-17T03%3A51%3A31Z%2F-1%2Fhost%2Fde4a26a46469066111552bf91d50202433ef1cdd89f4945e7924ad11de38fb36) ### 添加官方组件 - 添加官方组件航班查询组件 ![](https://bj.bcebos.com/v1/appbuilder-sdk-components/%E6%B7%BB%E5%8A%A0%E8%88%AA%E7%8F%AD%E6%9F%A5%E8%AF%A2%E6%8C%87%E4%BB%A4.png?authorization=bce-auth-v1%2FALTAKGa8m4qCUasgoljdEDAzLm%2F2024-12-17T03%3A52%3A17Z%2F-1%2Fhost%2F9dfcafb04d9e5992a4feda63f58ffe2211afb01b1e7b0f4f3ec4822ba840562c) ### 发布应用并调用 - 完成应用设置,并发布应用,接下来就可以调用添加了官方组件的Client应用了,应用的具体调用方法请参考[Agent应用基础知识](https://github.com/baidubce/app-builder/blob/master/docs/Application/Agent/BasicKnowledge/agent.md) ================================================ FILE: docs/Application/RAG/BasicKnowledge/rag.md ================================================ # console端RAG操作工具(RAG) ## 简介 RAG是基于线上RAG应用的问答组件,可以使用该组件利用线上RAG应用进行问答。
⚠️本组件仅适用于2024-04-02之前创建的历史RAG应用,最新创建的AgentBuilder应用,请参考[AppBuilder应用](../../../BasisModule/Platform/Application/appbuilder_client.md) 进行调用。 ### 功能介绍 利用线上RAG应用进行问答 ### 特色优势 与线上应用联动,利用线上RAG应用进行问答 ### 应用场景 使用SDK利用线上RAG应用进行问答 ## 基本用法 以下是使用SDK进行问答的示例代码 ### Python #### 组件初始化参数 | 参数名称 | 参数类型 | 描述 | 示例值 | |--------|--------|------------|-----------| | app_id | string | 线上RAG应用的ID | "正确的应用ID" | #### run方法入参 | 参数名称 | 参数类型 | 是否必须 | 描述 | 示例值 | |-----------------|---------|------|----------------|----------------------------| | query | Message | 是 | 提问的内容 | Message(content="北京的面积多大") | | stream | bool | 否 | 是否流式返回,默认False | False | | conversation_id | string | 否 | 不传默认新建会话 | "" | #### run方法出参 | 参数名称 | 参数类型 | 描述 | 示例值 | |--------|---------|------|-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| | result | Message | 返回结果 | Message(name=msg, content=北京市的面积是16410.54平方公里^[2]^。, mtype=dict, extra={'search_baidu': [{'id': '1', 'content': '北京,简称“京”,是中华人民共和国的首都,是全国的政治中心、文化中心,是世界著名古都和现代化国际...', 'type': 'web', 'from': 'search_baidu', 'title': '北京概况_首都之窗_北京市人民政府门户网站', 'url': 'https://www.beijing.gov.cn/renwen/bjgk/?eqid=b987a5f000085b6700000002642e204d'}, 'id', 'content', 'type', 'from', 'title', 'url']}, conversation_id=5a247540-e8cf-402a-a630-8015c24904f5)}) | #### 调用示例 ```python import appbuilder import os # 请前往千帆AppBuilder官网创建密钥,流程详见:https://cloud.baidu.com/doc/AppBuilder/s/Olq6grrt6#1%E3%80%81%E5%88%9B%E5%BB%BA%E5%AF%86%E9%92%A5 # 设置环境变量 os.environ["APPBUILDER_TOKEN"] = '...' app_id = '...' # 线上RAG应用ID,可在console端查看 conversation_id = '...' # 会话ID,可选参数,不传默认新建会话 rag_app = appbuilder.console.RAG(app_id) query = "中国的首都在哪里" answer = rag_app.run(appbuilder.Message(query)) # 新建会话 print(answer.content) # 获取结果内容 conversation_id = answer.conversation_id # 获取会话ID,可用于下次会话 print(conversation_id) query = "它有哪些旅游景点" answer = rag_app.run(appbuilder.Message(query), conversation_id) # 接上次会话 print(answer.content) # 获取结果内容 print(answer.extra) # 获取结果来源 ``` ### Java #### 组件初始化参数 | 参数名称 | 参数类型 | 描述 | 示例值 | |--------|-----------|------------|-----------| | appID | String | 线上RAG应用的ID | "正确的应用ID" | #### Run方法入参 | 参数名称 | 参数类型 | 是否必须 | 描述 | 示例值 | |----------------|--------|------|----------------------------------------------------|-------------| | query | string | 是 | query内容 | "汽车性能参数怎么样" | | conversationID | String | 是 | 若为空字符串服务端会自动创建新的会话ID,若不为空则继续上次对话内容 | | | stream | boolean | 是 | 为true时则流式返回,为false时则一次性返回所有内容, 推荐设为true,降低首token时延 | | #### Run方法出参 | 参数名称 | 参数类型 | 描述 | 示例值 | |-------------|-------------|----------------------|-----| | RAGIterator | RAGIterator | 回答迭代器,流式/非流式均统一返回该类型,每次迭代返回RAGResponse类型 | | #### 迭代RAGIterator | 参数名称 | 参数类型 | 描述 | 示例值 | |----------------|-----------------|---------|-----| | code | int | 响应状态码 | | | message | String | 响应信息 | | | result | RAGResult | 响应结果 | | | +answer | String | 回答结果 | | | +conversationId | String | 会话id | | | +events | []EventContent | 事件流 | | | +events[0] | EventContent | 具体事件 | | | ++eventType | String | 事件类型 | | | ++eventStatus | String | 事件状态 | | | ++outputs | Map | 事件内容 | | #### 示例代码 ```java class RAGDemo { public static void main(String[] args) throws IOException, AppBuilderServerException { // 填写自己的APPBUILDER_TOKEN System.setProperty("APPBUILDER_TOKEN", "填写秘钥"); // 填写创建好的appId String appId = "填写线上创建好的appId"; RAG rag = new RAG(appId); RAGIterator itor = rag.run("我想了解附近的房产价格,你能帮我查询吗?", "", true); System.out.println("输出结果:"); // itor.hasNext()返回false时,表示流式调用结束 while (itor.hasNext()) { RAGResponse response = itor.next(); System.out.print(response.getResult().getAnswer()); } } } ``` ### Go #### 组件初始化参数 | 参数名称 | 参数类型 | 描述 | 示例值 | |--------|-----------|------------|-----------| | app_id | string | 线上RAG应用的ID | "正确的应用ID" | | config | SDKConfig | SDK配置信息 | | #### Run方法入参 | 参数名称 | 参数类型 | 是否必须 | 描述 | 示例值 | |----------------|--------|------|----------------------------------------------------|-------------| | conversationID | 会话ID | 是 | 若为空字符串服务端会自动创建新的会话ID,若不为空则继续上次对话内容 | | | query | string | 是 | query内容 | "汽车性能参数怎么样" | | stream | bool | 是 | 为true时则流式返回,为false时则一次性返回所有内容, 推荐设为true,降低首token时延 | | #### Run方法出参 | 参数名称 | 参数类型 | 描述 | 示例值 | |-------------|-------------|----------------------|-----| | RAGIterator | RAGIterator | 回答迭代器,流式/非流式均统一返回该类型 | | | error | error | 存在错误时error不为nil,反之 | | #### 迭代RAGIterator | 参数名称 | 参数类型 | 描述 | 示例值 | |----------------|-----------------|---------|-----| | Answer | string | query答案 | | | ConversationID | string | 会话ID | | | Events | []RAGEvent | RAG事件流 | | | +Event | string | 事件名 | | | EventStatus | string | 事件状态 | | | EventType | string | 事件类型 | | | Text | json.RawMessage | 事件内容 | | #### 示例代码 ```go package main import ( "errors" "fmt" "io" "os" "github.com/baidubce/app-builder/go/appbuilder" ) func main() { // 设置APPBUILDER_TOKEN、GATEWAY_URL环境变量 os.Setenv("APPBUILDER_TOKEN", "请设置正确的应用密钥") // 默认可不填,默认值是 https://appbuilder.baidu.com os.Setenv("GATEWAY_URL", "") config, err := appbuilder.NewSDKConfig("", "") if err != nil { fmt.Println("new config failed: ", err) return } // 初始化RAG实例 appID := "请填写正确的应用ID" rag, err := appbuilder.NewRAG(appID, config) if err != nil { fmt.Println("new rag instance failed:", err) return } // 执行流式对话 i, err := rag.Run("", "", true) if err != nil { fmt.Println("run failed:", err) return } completedAnswer := "" // 迭代返回结果 var answer *appbuilder.RAGAnswer for answer, err = i.Next(); err == nil; answer, err = i.Next() { completedAnswer = completedAnswer + answer.Answer } // 迭代正常结束err应为io.EOF if errors.Is(err, io.EOF) { fmt.Println("run success") fmt.Println("RAG智能体回答内容: ", completedAnswer) } else { fmt.Println("run failed:", err) } } ``` ================================================ FILE: docs/Application/RAG/DatasetManage/dataset_manage.md ================================================ # console端知识库操作助手 ## 目标 用户可通过SDK对console端知识库进行操作,实现创建知识库、添加知识文档、查询知识库文档、删除知识文档等操作,可在平台console中查看结果。 ```python # 设置环境变量 import os # 设置环境变量 # 请前往千帆AppBuilder官网创建密钥,流程详见:https://cloud.baidu.com/doc/AppBuilder/s/Olq6grrt6#1%E3%80%81%E5%88%9B%E5%BB%BA%E5%AF%86%E9%92%A5 os.environ["APPBUILDER_TOKEN"] = "..." ``` ## 管理知识库 ### 初始化已有知识库 获取线上已有知识库的ID,可在[console](https://console.bce.baidu.com/ai_apaas/dataset)端查看,示例 image ```python import appbuilder # 初始化已有线上知识库, dataset_id 可在平台console中查看 dataset_id = "..." dataset = appbuilder.console.Dataset(dataset_id) ``` ### 创建全新知识库 ```python # 创建全新知识库 dataset = appbuilder.console.Dataset.create_dataset("my_dataset") ``` ### 上传文档到知识库 ```python # 设置文档路径,例如“./test.pdf” file_path1 = "..." file_path2 = "..." file_paths = [file_path1, file_path2] # 将文档上传到知识库 document_infos = dataset.add_documents(file_paths) print(document_infos) ``` ### 获取知识库关联文档 ```python # 获取第一页的文档列表, 每页10条 document_list = dataset.get_documents(1, 10) print(document_list) ``` ### 删除知识库中的文档 ```python # 删除第一个文档 document_ids = [document_list.data[0].id] dataset.delete_documents(document_ids) ``` ### 知识库使用示例 - [知识库使用示例](https://github.com/baidubce/app-builder/blob/master/cookbooks/end2end_application/rag/qa_system_1_dataset.ipynb) ================================================ FILE: docs/BasisModule/Components/Components.md ================================================ # 组件文档 - 当前目录为Appbuilder-SDK的组件文档目录 ================================================ FILE: docs/BasisModule/Components/animal_recognize/README.md ================================================ # 动物识别 (AnimalRecognition) ## 简介 动物识别 (AnimalRecognition) 支持对于输入的一张图片(可正常解码),输出动物识别结果。 ### 功能介绍 * 识别动物名称 识别近八千种动物,接口返回动物名称、置信度信息,支持自定义返回结果数, 并可获取识别结果对应的百科信息; ### 应用场景 * 拍照识图 根据拍摄照片,识别图片中动物的名称,可配合其它识图能力对识别的结果进一步细化,提升用户体验,广泛应用于拍照识图类APP中。 ## 基本用法 我们选取一张可爱的大熊猫照片,使用动物识别组件进行识别。 ![大熊猫](https://bj.bcebos.com/v1/appbuilder/animal_recognize_test.png?authorization=bce-auth-v1%2FALTAKGa8m4qCUasgoljdEDAzLm%2F2024-01-24T12%3A19%3A16Z%2F-1%2Fhost%2F411bad53034fa8f9c6edbe5c4909d76ecf6fad6862cf937c03f8c5260d51c6ae ) 下面是动物识别的代码示例: ```python import os import appbuilder import requests # 请前往千帆AppBuilder官网创建密钥,流程详见:https://cloud.baidu.com/doc/AppBuilder/s/Olq6grrt6#1%E3%80%81%E5%88%9B%E5%BB%BA%E5%AF%86%E9%92%A5 os.environ["APPBUILDER_TOKEN"] = '...' # 从BOS读取样例图片 image_url = "https://bj.bcebos.com/v1/appbuilder/animal_recognize_test.png?" \ "authorization=bce-auth-v1%2FALTAKGa8m4qCUasgoljdEDAzLm%2F2024-01-24T" \ "12%3A19%3A16Z%2F-1%2Fhost%2F411bad53034fa8f9c6edbe5c4909d76ecf6fad68" \ "62cf937c03f8c5260d51c6ae" raw_image = requests.get(image_url).content # 创建动物识别组件实例 animal_recognition = appbuilder.AnimalRecognition() # 执行识别操作并获取结果 out = animal_recognition.run(appbuilder.Message(content={"raw_image": raw_image})) print(out.content) ``` ## 参数说明 ### 鉴权说明 使用组件之前,请首先申请并设置鉴权参数,可参考[组件使用流程](https://cloud.baidu.com/doc/AppBuilder/s/Olq6grrt6#1%E3%80%81%E5%88%9B%E5%BB%BA%E5%AF%86%E9%92%A5)。 ```python # 设置环境中的TOKEN,以下示例略 os.environ["APPBUILDER_TOKEN"] = "bce-YOURTOKEN" ``` ### 初始化参数 无 ### 调用参数 | 参数名称 | 参数类型 | 是否必须 | 描述 | 示例值 | |---------|---------|------|-----------------------------|------------------------------------------------| | message | String | 是 | 输入的消息,用于模型的主要输入内容。这是一个必需的参数 | Message(content={"raw_image": b"待识别的图片字节流数据"}) | |timeout| Float | 否 | HTTP超时时间,单位:秒 |1|| | retry | Integer | 否 | HTTP重试次数 | 3 | ### 响应参数 | 参数名称 | 参数类型 | 描述 | 示例值 | |--------|---------|------|---------------------------------------| | result | Array[] | 返回结果 | [{"name":"国宝大熊猫","score":"0.975161"}] | | +name | String | 动物名称 | "国宝大熊猫" | | +score | String | 置信度 | "0.975161" | ### 响应示例 ```json { "result":[ { "name":"国宝大熊猫", "score":"0.975161" }, { "name":"秦岭四宝", "score":"0.0161979" }, { "name":"团团圆圆", "score":"0.00239265" }, { "name":"圆仔", "score":"0.00192277" }, { "name":"棕色大熊猫", "score":"0.00130296" }, { "name":"小熊猫", "score":"0.000275865" } ] } ``` ## 高级用法 目前该模块仅提供基础的动物识别功能。 ## 更新记录和贡献 * 动物识别能力 (2024-01) ================================================ FILE: docs/BasisModule/Components/asr/README.md ================================================ # 短语音识别-极速版 (Automatic Speech Recognition) ## 简介 短语音识别 (Automatic Speech Recognition) 可以将音频流实时识别为文字,并返回每句话的开始和结束时间,适用于手机语音输入、语音搜索、人机对话等语音交互场景。 ### 功能介绍 通过极速API接口,将语音识别为文字,毫秒级响应,快速返回识别结果。 ### 特色优势 采用领先国际的流式端到端建模方法SMLTA,近场普通话语音识别准确率可达98%;采用最新识别解码技术,识别速度提升5倍以上,极速返回识别结果;专有GPU服务集群、提供企业级的稳定服务,弹性灵活的高并发承载及高可靠性保障。 ### 应用场景 语音输入、语音搜索、人机对话等。 ## 基本用法 下面是短语音识别的代码示例: ```python import os import requests import appbuilder # 设置环境变量和初始化 # 请前往千帆AppBuilder官网创建密钥,流程详见:https://cloud.baidu.com/doc/AppBuilder/s/Olq6grrt6#1%E3%80%81%E5%88%9B%E5%BB%BA%E5%AF%86%E9%92%A5 os.environ["APPBUILDER_TOKEN"] = "..." asr = appbuilder.ASR() audio_file_url = "https://bj.bcebos.com/v1/appbuilder/asr_test.pcm?authorization=bce-auth-v1" \ "%2FALTAKGa8m4qCUasgoljdEDAzLm%2F2024-01-11T10%3A56%3A41Z%2F-1%2Fhost" \ "%2Fa6c4d2ca8a3f0259f4cae8ae3fa98a9f75afde1a063eaec04847c99ab7d1e411" audio_data = requests.get(audio_file_url).content content_data = {"audio_format": "pcm", "raw_audio": audio_data, "rate": 16000} msg = appbuilder.Message(content_data) out = asr.run(msg) print(out.content) # {'result': ['北京科技馆。']} ``` ## 参数说明 ### 鉴权配置 使用组件之前,请首先申请并设置鉴权参数,可参考[组件使用流程](https://cloud.baidu.com/doc/AppBuilder/s/Olq6grrt6#1%E3%80%81%E5%88%9B%E5%BB%BA%E5%AF%86%E9%92%A5)。 ```python # 设置环境中的TOKEN,以下示例略 os.environ["APPBUILDER_TOKEN"] = "bce-YOURTOKEN" ``` ### 初始化参数 无 ### 调用参数 |参数名称 |参数类型 |是否必须 |描述 | 示例值 | |--------|--------|--------|----|--------| |message |String |是 |输入的消息,用于模型的主要输入内容。这是一个必需的参数,语音时长最长为60S| Message(content={"raw_audio": b"..."}) | |audio_format|String|是 |定义语言文件的格式,包括"pcm"、"wav"、"amr",默认值为"pcm"| pcm | |rate|Integer|是 |定义录音采样率,固定值16000| 16000 | |timeout| Float | 否 | HTTP超时时间,单位:秒 |1|| |retry|Integer|是 |HTTP重试次数| 3 | ### 响应参数 |参数名称 | 参数类型 |描述 |示例值| |--------|--------------|----|------| |result | List[String] |返回结果|["北京科技馆。"]| ### 响应示例 ```json {"result": ["北京科技馆。"]} ``` ### 错误码 | 错误码 |描述| |---|---| | 0 |success| | 2000 |data empty| ## 高级用法 目前该模块仅提供基础的语音识别功能。 ## 更新记录和贡献 * 短语音识别能力 (2023-12) ================================================ FILE: docs/BasisModule/Components/dish_recognize/README.md ================================================ # 菜品识别(DishRecognition) ## 简介 菜品识别组件(DishRecognition)可以识别超过9千种菜品,可准确识别图片中的菜品名称、卡路里,适用于多种客户识别菜品的业务场景中。 ### 功能介绍 识别超过9千种菜品,适用于识别只含有单个菜品的图片,接口返回菜品的名称、卡路里等综合信息 ### 特色优势 识别精度高,响应速度快 ### 应用场景 1. 餐饮健康:根据拍摄照片,识别图片中菜品名称,获取菜品参考卡路里含量和百科信息,可结合识别结果进一步提供饮食推荐、健康管理方案等相关功能,增强用户体验,广泛应用于餐饮娱乐类和健康管理类APP中 2. 智能结算:根据拍摄照片,识别图片中菜品名称和位置,提高结算效率,减少人工录入成本,广泛应用于餐饮行业中 ## 基本用法 通过如下示例代码可以快速开始使用菜品识别组件: 示例图片为: ![菜品识别示例图片](https://bj.bcebos.com/v1/appbuilder/dish_recognize_test.jpg?authorization=bce-auth-v1%2FALTAKGa8m4qCUasgoljdEDAzLm%2F2024-01-11T10%3A58%3A25Z%2F-1%2Fhost%2F7b8fc08b2be5adfaeaa4e3a0bb0d1a1281b10da3d6b798e116cce3e37feb3438) ```python import os import requests import appbuilder # 请前往千帆AppBuilder官网创建密钥,流程详见:https://cloud.baidu.com/doc/AppBuilder/s/Olq6grrt6#1%E3%80%81%E5%88%9B%E5%BB%BA%E5%AF%86%E9%92%A5 os.environ["APPBUILDER_TOKEN"] = '...' dish_recognition = appbuilder.DishRecognition() image_url = "https://bj.bcebos.com/v1/appbuilder/dish_recognize_test.jpg?" \ "authorization=bce-auth-v1%2FALTAKGa8m4qCUasgoljdEDAzLm%2F2024-01-11T" \ "10%3A58%3A25Z%2F-1%2Fhost%2F7b8fc08b2be5adfaeaa4e3a0bb0d1a1281b10da" \ "3d6b798e116cce3e37feb3438" raw_image = requests.get(image_url).content resp = dish_recognition(appbuilder.Message({"raw_image": raw_image})) # 输出{'result': [{'name': '剁椒鱼头', 'calorie': '127'}]} print(resp.content) ``` ## 参数说明 ### 鉴权说明 使用组件之前,请首先申请并设置鉴权参数,可参考[组件使用流程](https://cloud.baidu.com/doc/AppBuilder/s/Olq6grrt6#1%E3%80%81%E5%88%9B%E5%BB%BA%E5%AF%86%E9%92%A5)。 ```python # 设置环境中的TOKEN,以下示例略 os.environ["APPBUILDER_TOKEN"] = "bce-YOURTOKEN" ``` ### 初始化参数 无 ### 调用参数 |参数名称 |参数类型 |是否必须 |描述 | 示例值 | |--------|--------|--------|----|--------| |message |obj:`Message` |是 |待识别的图片字节流数据或url| Message(content={"raw_image": b"..."}) 或Message(content={"url": "..."}) | |timeout| Float | 否 | HTTP超时时间,单位:秒 |1|| |retry|Integer|否 |HTTP重试次数| 3 | ### 响应参数 |参数名称 |参数类型 |描述 |示例值| |--------|--------|----|------| |result |List[Object] |返回结果|[{"name": "剁椒鱼头", "calorie": "127"}]| |result[0].name |String |菜品名称|剁椒鱼头| |result[0].calorie |String |菜品卡路里含量|127| ### 响应示例 ```json {"result": [{"name": "剁椒鱼头", "calorie": "127"}]} ``` ## 更新记录和贡献 * 菜品识别 (2024-01) ================================================ FILE: docs/BasisModule/Components/doc_crop_enhance/README.md ================================================ # 文档矫正增强 (DocCropEnhance) ## 简介 文档矫正增强 (DocCropEnhance) 可对图片中的文件、卡证、票据等内容进行四角点检测定位,提取主体内容并对其进行矫正,同时可选图片增强效果进一步提升图片清晰度,达到主体检测矫正并增强的目的,提升图片整体质量 ### 功能介绍 * 文档矫正增强 支持对文档中的文件、卡证等内容进行主体检测与矫正,同时可开启增强功能 ### 特色优势 * 技术领先 模型针对图片倾斜、弯曲等情况进行专项优化,鲁棒性强,在处理图像的同时,可完整保留原有文档内容 * 能力丰富 提供文档图片矫正、增强、去手写等多项能力,全方位提升图像质量,适用于采集质量把控、文字识别效果提升等多应用场景 ### 应用场景 旨在改善文档图像质量,提升可读性和可处理性,广泛应用于图像处理和分析、归档和数字化等领域 ## 基本用法 下面是文档矫正增强代码示例: 示例图片为 ![示例图片](https://bj.bcebos.com/v1/appbuilder/doc_enhance_test.png?authorization=bce-auth-v1%2FALTAKGa8m4qCUasgoljdEDAzLm%2F2024-01-24T12%3A51%3A09Z%2F-1%2Fhost%2F2020d2433da471b40dafa933d557a1ebe8abf28df78010f865e45dfcd6dc3951) ```python import os import appbuilder import requests # 请前往千帆AppBuilder官网创建密钥,流程详见:https://cloud.baidu.com/doc/AppBuilder/s/Olq6grrt6#1%E3%80%81%E5%88%9B%E5%BB%BA%E5%AF%86%E9%92%A5 os.environ["APPBUILDER_TOKEN"] = '...' # 从BOS读取样例图片 image_url = "https://bj.bcebos.com/v1/appbuilder/doc_enhance_test.png?" \ "authorization=bce-auth-v1%2FALTAKGa8m4qCUasgoljdEDAzLm%2F2024-01" \ "-24T12%3A51%3A09Z%2F-1%2Fhost%2F2020d2433da471b40dafa933d557a1e" \ "be8abf28df78010f865e45dfcd6dc3951" raw_image = requests.get(image_url).content # 创建文档矫正增强组件实例 doc_crop_enhance = appbuilder.DocCropEnhance() # 执行操作并获取结果 out = doc_crop_enhance.run(appbuilder.Message(content={"raw_image": raw_image}),enhance_type=3) print(out.content) # {"image_processed": "...", 'points': [{'y': 1371, 'x': 0}, {'x': 0, 'y': 0}, {'x': 997, 'y': 0}, {'x': 994, 'y': 1371}]} ``` ## 参数说明 ### 鉴权说明 使用组件之前,请首先申请并设置鉴权参数,可参考[组件使用流程](https://cloud.baidu.com/doc/AppBuilder/s/Olq6grrt6#1%E3%80%81%E5%88%9B%E5%BB%BA%E5%AF%86%E9%92%A5)。 ```python # 设置环境中的TOKEN,以下示例略 os.environ["APPBUILDER_TOKEN"] = "bce-YOURTOKEN" ``` ### 初始化参数 无 ### 调用参数 | 参数名称 | 参数类型 | 是否必须 | 描述 | 示例值 | |--------------|---------|------|-----------------------------------------------------------------------------------------------------------------------------|------------------------------------------------| | message | String | 是 | 输入的消息,用于模型的主要输入内容。这是一个必需的参数 | Message(content={"raw_image": b"待识别的图片字节流数据"}) | | enhance_type | Integer | 否 | 选择是否开启图像增强功能,如开启可选择增强效果,可选值如下:enhance_type =0:默认值,不开启增强功能,enhance_type = 1:去阴影,enhance_type = 2:增强并锐化,enhance_type = 3:黑白滤镜 | 0 | |timeout| Float | 否 | HTTP超时时间,单位:秒 |1|| | retry | Integer | 否 | HTTP重试次数 | 3 | ### 响应参数 | 参数名称 | 参数类型 | 描述 | 示例值 | |-----------------|---------|-------------------------------------------|-----------------------------------------------------------------------------------------| | image_processed | String | 返回处理后的图片,base64编码 | "..." | | points | Array[] | 检测到的图片内主体在原图中的四角点坐标 | [{ "x": 0, "y": 1371 },{ "x": 0, "y": 0 },{ "x": 997, "y": 0 },{ "x": 994, "y": 1371 }] | ### 响应示例 ```json { "image_processed": "...", "points": [ { "x": 0, "y": 1371 }, { "x": 0, "y": 0 }, { "x": 997, "y": 0 }, { "x": 994, "y": 1371 } ] } ``` ## 高级用法 目前该模块仅提供基础的文档矫正增强功能。 ## 更新记录和贡献 * 文档矫正增强能力 (2024-01) ================================================ FILE: docs/BasisModule/Components/doc_format_converter/README.md ================================================ # 文档格式转换 (DocFormatConverter) ## 简介 文档格式转换:识别文档内文字及版面布局,可将多种类型的版式文档转换为流式文档。 ### 功能介绍 支持识别图片中文档版面布局,提取文字内容,并转换为保留原文档版式的Word/Excel,方便二次编辑和复制。 ### 特色优势 1、多种格式互转:支持多种格式相互转换,覆盖全面; 2、图像预处理:支持对文件朝向检测、印章/水印去除后等预处理,提升格式转换效果。 ### 应用场景 文档电子化:标题/正文/表格/配图等版式信息精准识别与还原,快速录入文档内容,实现纸质档案电子化。 ## 基本用法 ```python import os import requests import appbuilder # 请前往千帆AppBuilder官网创建密钥,流程详见:https://cloud.baidu.com/doc/AppBuilder/s/Olq6grrt6#1%E3%80%81%E5%88%9B%E5%BB%BA%E5%AF%86%E9%92%A5 os.environ["APPBUILDER_TOKEN"] = '...' doc_format_converter = appbuilder.DocFormatConverter() image_url = "https://ai-cape-strategy-data.bj.bcebos.com/document-restructure/1EF33F9307451C9413D5D1160.jpg" resp = doc_format_converter(appbuilder.Message({"file_path": image_url})) # 输出{"word_url":"", "excel_url":""} print(resp.content) ``` ## 参数说明 ### 鉴权说明 使用组件之前,请首先申请并设置鉴权参数,可参考[组件使用流程](https://cloud.baidu.com/doc/AppBuilder/s/Olq6grrt6#1%E3%80%81%E5%88%9B%E5%BB%BA%E5%AF%86%E9%92%A5)。 ```python # 设置环境中的TOKEN,以下示例略 os.environ["APPBUILDER_TOKEN"] = "bce-YOURTOKEN" ``` ### 初始化参数 无 ### 调用参数 | 参数名称 |参数类型 |是否必须 | 描述 | 示例值 | |------------|--------|--------|-------------|------| | file_path |String |是 | 需要转换的文件的本地存储路径或远程URL,支持图片, URL长度不超过1024字节,图片base64编码后大小不超过4M,最短边至少15px,最长边最大4096px,支持jpg/jpeg/png/bmp格式 | "./test.png" | ### 响应参数 | 参数名称 |参数类型 | 描述 | 示例值 | |-------------|--------|------|-------------------------| | word_url |Message | 还原后的word文件的下载地址,文件识别失败时返回空 | "http://bos.bce.cn/dsfkjc.docx"| | excel_url |Message | 还原后的Excel文件的下载地址(源文件中含表格时才会输出),若文档中没有表格则返回"" | "http://bos.bce.cn/dsfkjc.xlsx"| ### 常见错误信息 | 错误信息 | 描述 | |-------------------------|-------------| |IAM Certification failed |IAM鉴权失败| |Check file failed!|文件检查错误,请检查文件大小以及URL是否符合要求 | ## 更新记录和贡献 * 文档格式转换 (2024-04) ================================================ FILE: docs/BasisModule/Components/doc_parser/README.md ================================================ # 文档解析(DocParser) ## 简介 文档解析组件(DocParser)可以用于文档内容解析,支持PDF、JPG、DOC、TXT、XLS、PPT等16种文档格式的内容解析。 ### 功能介绍 文档解析组件(DocParser)支持从文档中解析出文档字符内容、版式信息、位置坐标、表格结构、阅读顺序、标题段落层级树等内容 ### 特色优势 DocParser支持解析以下几种类型的文档: * 版式文档:「pdf」、「jpg」、「jpeg」、「png」、「bmp」、「tif」、「tiff」、「ofd」 * 流式文档:「doc」、「docx」、「txt」、「xls」、「xlsx」、「wps」、「ppt」、「pptx」 支持解析的文档内容包括: * 文档的版式分析,识别文档中的标题、正文、页眉页脚、表格等 * 文档内的文字内容、位置坐标 * 表格结构和内容 * 构建文档标题段落层级树 * 构建文档阅读顺序 * 支持以上类型文档转成pdf格式 ### 应用场景 * 文档内容解析 * 文档版式解析 * 文档格式转化 ## 基本用法 以下是使用DocParser快速开始的一个示例: ```python from appbuilder import DocParser from appbuilder.core.message import Message import os import requests # 请前往千帆AppBuilder官网创建密钥,流程详见:https://cloud.baidu.com/doc/AppBuilder/s/Olq6grrt6#1%E3%80%81%E5%88%9B%E5%BB%BA%E5%AF%86%E9%92%A5 os.environ["APPBUILDER_TOKEN"] = "..." # 进行文档内容解析 file_url = "https://agi-dev-platform-bos.bj.bcebos.com/ut_appbuilder/test.pdf?authorization=bce-auth-v1/e464e6f951124fdbb2410c590ef9ed2f/2024-01-25T12%3A56%3A15Z/-1/host/b54178fea9be115eafa2a8589aeadfcfaeba20d726f434f871741d4a6cb0c70d" file_data = requests.get(file_url).content file_path = "./test.pdf" # 待解析的文件路径 with open(file_path, "wb") as f: f.write(file_data) msg = Message(file_path) parser = DocParser() parse_result = parser(msg) print(parse_result.content) ``` ## 参数说明 ### 鉴权说明 使用组件之前,请首先申请并设置鉴权参数,可参考[组件使用流程](https://cloud.baidu.com/doc/AppBuilder/s/Olq6grrt6#1%E3%80%81%E5%88%9B%E5%BB%BA%E5%AF%86%E9%92%A5)。 ```python # 设置环境中的TOKEN,以下示例略 os.environ["APPBUILDER_TOKEN"] = "bce-YOURTOKEN" ``` ### 初始化参数 无 ### 调用参数 | 参数名称 |参数类型 |是否必须 | 描述 | 示例值 | |------------|--------|--------|-------------|------| | message |String |是 | 需要解析的文档的存储路径 | "./test.pdf" | | return_raw |bool|否 | 指定是否返回原始的解析结果结构,默认为 False。 | True | ### 响应参数 | 参数名称 |参数类型 | 描述 | 示例值 | |-------------|--------|------|-------------------------| | parseResult |Message | 解析结果 | ParseResult对象,包含文档解析的内容 | ### 响应示例 ```python class ParseResult(BaseModel): """ 解析结果整体结构 """ para_node_tree: Optional[List[ParaNode]] = [] # 标题段落层级树,当ParserConfig.return_para_node_tree为True时有内容 page_contents: Optional[List[PageContent]] = [] # 页面的解析内容,详细内容参考base.py中的PageContent类 pdf_data: Optional[str] = "" # pdf格式数据, 当ParserConfig.convert_file_to_pdf为True时有内容 raw: Optional[Dict] = {} # 云端服务的原始解析结果 ``` ## 高级用法 DocParser支持自定义文档解析的配置和对解析结果进行二次处理,以下是一个示例: ```python from appbuilder import DocParser from appbuilder.core.message import Message import os import requests # 设置环境变量 os.environ["APPBUILDER_TOKEN"] = "..." # 先进行文档内容解析 file_url = "https://agi-dev-platform-bos.bj.bcebos.com/ut_appbuilder/test.pdf?authorization=bce-auth-v1/e464e6f951124fdbb2410c590ef9ed2f/2024-01-25T12%3A56%3A15Z/-1/host/b54178fea9be115eafa2a8589aeadfcfaeba20d726f434f871741d4a6cb0c70d" file_data = requests.get(file_url).content file_path = "./test.pdf" # 待解析的文件路径 with open(file_path, "wb") as f: f.write(file_data) msg = Message(file_path) parser = DocParser() config = parser.config config.convert_file_to_pdf = True # 指定将当前文件转换成pdf格式 config.page_filter = [0, 2] # 只解析第1页和第3页,注意:页码从0开始 parse_result = parser(msg) file_content = parse_result.content pdf_data = file_content.pdf_data # 获取原始文件转化成pdf之后的数据 page_content = file_content.page_content[1] # 获取第3页的解析结果 page_table = page_content.tables[0] # 第3页中第一个表格的解析结果(如有),表格的解析内容的结构详见上一章详细说明部分关于表格结果的说明 cells = page_table.cells # 表格的单元格信息 cell_text = cells[0] # 表格第一个单元格的文本内容 matrix = page_table.cell_matrix # 表格的单元格矩阵,用来描述单元格的空间位置信息 ... 自定义处理表格内容 ... ``` ### 高级用法参数详细说明 在base.py中定义了DocParser配置和结果结构,下面做一些详细的说明和解释: ### DocParser配置 ```python class ParserConfig(BaseModel): """ DocParser解析配置 """ convert_file_to_pdf: bool = Field(alias="need_pdffile_data", default=False) # 是否需要将当前文件转换成pdf格式 page_filter: List[int] = Field(alias="page_filter", default=None) # 指定解析的页码,默认传None,代表全部解析 return_para_node_tree: bool = Field(alias="return_para_nodes", default=True) # 是否需要返回标题段落层级树 erase_watermark: bool = Field(alias="erase_watermark", default=False) # 解析的过程中是否需要去除水印的干扰 ``` ### DocParser解析结果 ```python class ParseResult(BaseModel): """ 解析结果整体结构 """ para_node_tree: Optional[List[ParaNode]] = [] # 标题段落层级树,当ParserConfig.return_para_node_tree为True时有内容 page_contents: Optional[List[PageContent]] = [] # 页面的解析内容,详细内容参考base.py中的PageContent类 pdf_data: Optional[str] = "" # pdf格式数据, 当ParserConfig.convert_file_to_pdf为True时有内容 raw: Optional[Dict] = {} # 云端服务的原始解析结果 class ParaNode(BaseModel): """ 文档内容层级树结构 """ node_id: int # 标题段落层级树的节点id text: str # 节点文本 para_type: str # 节点类型,包括:title、text、table parent: Optional[int] # 父节点id,文本的父节点是标题,标题的父节点是更高一级的标题 children: List[int] # 子节点id列表,标题节点才会有子节点 position: List[Position] # 节点位置信息,包括:页码和在对应页面的位置坐标 table: Optional[Table] = None # 节点类型为table时,包含表格解析结果 class PageContent(BaseModel): """ 单页文档内容结构 """ page_num: int # 页码 page_width: int # 页面宽度 page_height: int # 页面高度 page_angle: int # 页面旋转角度 page_type: str # 页面类型 page_layouts: List[Layout] # 页面版式信息 titles: Optional[List[Layout]] = [] # 页面标题信息 tables: Optional[List[Table]] = [] # 页面表格信息 class Layout(BaseModel): """ layout结构 """ type: str # 布局类型 text: str # 布局文本 box: List[int] # 布局位置信息,包括:左上角x、y坐标和宽高 node_id: int # 布局在标题层级树中的节点id class Table(BaseModel): """ 表格结构 """ box: List[int] # 表格位置信息,包括:左上角x、y坐标和宽高 cells: List[Layout] = Field(alias="children") # 表格单元格信息,列表形式 matrix: List[List[int]] # 表格单元格矩阵,用来描述单元格的空间位置信息 node_id: int # 表格在标题层级树中的节点id ``` 表格解析结构说明, 以下图为例: ![表格](https://bj.bcebos.com/v1/appbuilder-sdk-components/table.png?authorization=bce-auth-v1%2FALTAKGa8m4qCUasgoljdEDAzLm%2F2024-05-30T03%3A09%3A32Z%2F-1%2Fhost%2Fb36695708e047713b5fe17b49733228aecdaf46322a5cec8d4e7bd0989032197) ```python # cells中一共有26个元素,matrix中的每一个元素代表单元格在cells中的索引 cells = [{"box": [90, 376, 21, 10], "type": "cell", "text": "序号", "node_id": 1}, ...] matrix = [ [0, 1, 2, 3], [4, 5, 6, 7], [8, 9, 10, 11], [12, 13, 14, 15], [16, 17, 18, 19], [20, 21, 22, 23], [24, 24, 25, 26] ] ``` ## 更新记录和贡献 * 文档解析能力 (2023-12) ================================================ FILE: docs/BasisModule/Components/doc_splitter/README.md ================================================ # 文档切分(DocSplitter) ## 简介 文档切分组件(DocSplitter)可以用于对文档进行段落切分。 ### 功能介绍 对解析后的文档,支持将文档划分为多个段落,便于后续处理和分析。 目前支持的文档切分类型splitter_type如下: * split_by_chunk:按照最大段落大小,对文档进行切分 * split_by_title:按照文档的title标识层级进行段落切分 ### 特色优势 组件对文档分隔段落,准确高效,且有多种可选策略,代码简单可快速上手,是后续大模型使用文档信息的基础。 ### 应用场景 对解析后的各类型文档进行分段,用于后续任务的输入。 ## 基本用法 --- 参考tests目录下的[test_doc_splitter.py](https://github.com/baidubce/app-builder/blob/master/appbuilder/tests/test_doc_splitter.py),可快速搭建自己的文档切分用例。 以下是DocSplitter快速开始的一个示例。 #### DocSplitter示例: ```python import os import requests from appbuilder import DocParser from appbuilder import DocSplitter from appbuilder.core.message import Message # 请前往千帆AppBuilder官网创建密钥,流程详见:https://cloud.baidu.com/doc/AppBuilder/s/Olq6grrt6#1%E3%80%81%E5%88%9B%E5%BB%BA%E5%AF%86%E9%92%A5 os.environ["APPBUILDER_TOKEN"] = "..." # 先解析 file_url = "https://agi-dev-platform-bos.bj.bcebos.com/ut_appbuilder/test.pdf?authorization=bce-auth-v1/e464e6f951124fdbb2410c590ef9ed2f/2024-01-25T12%3A56%3A15Z/-1/host/b54178fea9be115eafa2a8589aeadfcfaeba20d726f434f871741d4a6cb0c70d" file_data = requests.get(file_url).content file_path = "./test.pdf" with open(file_path, "wb") as f: f.write(file_data) msg = Message(file_path) parser = DocParser() parse_result = parser(msg, return_raw=True) # 基于parser的结果切分段落 splitter = DocSplitter(splitter_type="split_by_chunk") res_paras = splitter(parse_result) # 打印结果 print(res_paras.content) ``` ## 参数说明 ### 鉴权说明 使用组件之前,请首先申请并设置鉴权参数,可参考[组件使用流程](https://cloud.baidu.com/doc/AppBuilder/s/Olq6grrt6#1%E3%80%81%E5%88%9B%E5%BB%BA%E5%AF%86%E9%92%A5)。 ```python # 设置环境中的TOKEN,以下示例略 os.environ["APPBUILDER_TOKEN"] = "bce-YOURTOKEN" ``` ### 初始化参数 `splitter_type`(str): 切分器的类型,支持`split_by_chunk`和`split_by_title`两种方式,必选参数 ### 调用参数 * `message`(Message): 上游`docparser`的文档解析结果 * 备注: 文档解析时,`parser(msg, return_raw=True)`函数的参数`return_raw`必须为`True` |参数名称 |参数类型 |是否必须 |描述 | 示例值 | |--------|--------|--------|----|--------| |splitter_type |String |是 |文本提取器类型, 目前支持`split_by_chunk`, `split_by_title`| DocSplitter(splitter_type="split_by_chunk") | ### 响应参数 |参数名称 | 参数类型 |描述 | 示例值 | |--------|------|----|----------------| |res_paras |Message |返回结果| [{段落1}, {段落2}] | ### 响应示例 ``` Message(name=msg, content={'paragraphs': [{'text': '第十节其他重要事项'}]}) ``` ### 错误码 无 ## DocSplitter高级用法 #### 示例: ```python import os import requests from appbuilder import DocParser from appbuilder import DocSplitter from appbuilder.core.message import Message # 请前往千帆AppBuilder官网创建密钥,流程详见:https://cloud.baidu.com/doc/AppBuilder/s/Olq6grrt6#1%E3%80%81%E5%88%9B%E5%BB%BA%E5%AF%86%E9%92%A5 os.environ["APPBUILDER_TOKEN"] = "..." # 先解析 file_url = "https://agi-dev-platform-bos.bj.bcebos.com/ut_appbuilder/test.pdf?authorization=bce-auth-v1/e464e6f951124fdbb2410c590ef9ed2f/2024-01-25T12%3A56%3A15Z/-1/host/b54178fea9be115eafa2a8589aeadfcfaeba20d726f434f871741d4a6cb0c70d" file_data = requests.get(file_url).content file_path = "./test.pdf" with open(file_path, "wb") as f: f.write(file_data) msg = Message(file_path) parser = DocParser() parse_result = parser(msg, return_raw=True) # 基于parser的结果切分段落 doc_splitter = DocSplitter(splitter_type="split_by_chunk", separators=["。", "!", "?", ".", "!", "?", "……", "|\n"], max_segment_length=800, overlap=0) res_paras = doc_splitter(parse_result) # 打印结果 print(res_paras.content) ``` ## 参数说明: ### 鉴权配置 使用组件之前,请首先申请并设置鉴权参数,可参考[组件使用流程](https://cloud.baidu.com/doc/AppBuilder/s/Olq6grrt6#1%E3%80%81%E5%88%9B%E5%BB%BA%E5%AF%86%E9%92%A5)。 ```python # 设置环境中的TOKEN,以下示例略 os.environ["APPBUILDER_TOKEN"] = "bce-YOURTOKEN" ``` ### 调用参数 * `message`(Message): 上游`docparser`的文档解析结果 * 备注: 文档解析时,`parser(msg, return_raw=True)`函数的参数`return_raw`必须为`True` * 备注: `splitter_type`为`split_by_title`时,`max_segment_length`, `separators`, `overlap`, `join_symbol`参数不起作用 |参数名称 | 参数类型 | 是否必须 |描述 | 示例值 | |--------|---------|------|----|-------| |splitter_type | String | 是 |文本提取器类型, 目前支持`split_by_chunk`, `split_by_title`| DocSplitter(splitter_type="split_by_chunk") | |max_segment_length| Integer | 否 |切分时段落的最大长度| 800 | |separators| List | 否 |固定字数时,段落最后截断的分隔符| ["。", "!", "?", ".", "!", "?", "……", "|\n"] | |overlap| Integer | 否 |分隔的段落间重叠的内容字数| 200 | |join_symbol| String | 否 |组成固定字数段落时,文本块段落间的链接符| 空字符 | ### 响应参数 |参数名称 | 参数类型 |描述 | 示例值 | |--------|------|----|----------------| |res_paras |Message |返回结果| [{段落1}, {段落2}] | ### 响应示例 ``` Message(name=msg, content={'paragraphs': [{'text': '第十节其他重要事项'}]}) ``` ## 更新记录和贡献 * 文档分隔 (2023-12) ================================================ FILE: docs/BasisModule/Components/document_understanding/README.md ================================================ # 长文档内容理解(DocumentUnderstanding) ## 简介 长文档内容理解组件(DocumentUnderstanding)支持对图片以及文档内容进行理解,并基于图片以及文档内容对用户的提问进行回答, 包括但不限于文档内容问答、总结摘要、内容分析。 ### 功能介绍 根据用户上传的文档(支持txt、docx、pdf、xlsx、png、jpg、jpeg等多种格式)、query、指令生成大模型答案 ### 特色优势 处理长上下文的大模型内容理解任务 ### 应用场景 长上下文的文档问答 ## 基本用法 ### 快速开始 ```python import os import appbuilder # 请前往千帆AppBuilder官网创建密钥,流程详见:https://cloud.baidu.com/doc/AppBuilder/s/Olq6grrt6#1%E3%80%81%E5%88%9B%E5%BB%BA%E5%AF%86%E9%92%A5 APPBUILDER_TOKEN = "YOUR-TOKEN" os.environ["APPBUILDER_TOKEN"] = APPBUILDER_TOKEN du = appbuilder.DocumentUnderstanding() query = appbuilder.Message("这篇文档讲了什么") instruction = "请根据文档内容回答问题,用一句话简短概括" addition_instruction = "用一句话简短概括" ##用户增强指令,可选填,该内容会进一步增强大模型的指令跟随能力,将你最需要增强效果的指令填于此,内容可以与上述的"instruction"基础指令有重复,注意:该字段内容过多会一定程度影响大模型内容严谨度,请注意控制该字段的指令字数 app_id = "YOUR-APP-ID" ##你需要在系统上自己的账号下(https://qianfan.cloud.baidu.com/appbuilder)创建任意空Agent,并获取该Agent的app_id(即界面上的应用ID,在首页->个人空间->应用 里面即会显示应用ID),这里任意空Agent就可以,无需任何配置信息,这个agent的作用只是为了获取app_id信息 file_path = "YOUR-FILE-PATH" ##填写你的本地待分析文件路径 stream = False ##是否开启流式输出功能 response_ = du.run(query, file_path, instruction=instruction, addition_instruction=addition_instruction, app_id=app_id, stream=stream) for result in response_: print(result) ##打印输出的大模型答案 ``` ## 参数说明 ### 鉴权说明 使用组件之前,请首先申请并设置鉴权参数,可参考[组件使用流程](https://cloud.baidu.com/doc/AppBuilder/s/Olq6grrt6#1%E3%80%81%E5%88%9B%E5%BB%BA%E5%AF%86%E9%92%A5)。 ```python # 设置环境中的TOKEN,以下示例略 import os os.environ['APPBUILDER_TOKEN'] = 'bce-YOURTOKEN' ``` ### 初始化参数 | 参数名称 | 参数类型 | 是否必须 | 描述 | 示例值 | | ------- | ------- | -------- | -------- | -------- | | `secret_key` | str | 否 | 用户鉴权token,默认从环境变量中获取: `os.getenv("APPBUILDER_TOKEN", "")` | bce-v3/XXX | | `gateway` | str | 否 | 后端网关服务地址,默认从环境变量中获取: `os.getenv("GATEWAY_URL", "")` | https://appbuilder.baidu.com | | `lazy_certification` | bool | 否 | 延迟认证,为True时在第一次运行时认证。默认为False。 | False | ### 调用参数 | 参数名称 | 参数类型 | 是否必须 | 描述 | 示例值 | |------------------------|------|------|--------------------------------------------------------------------------|-----------------------------| | `message` | obj | 是 | 输入消息,用户输入query。 | Message(content=input_data) | | `file_path` | str | 是 | 用户需要分析的文档 | "test.pdf" | | `app_id` | str | 是 | 你需要在系统上自己的账号下(https://qianfan.cloud.baidu.com/appbuilder)创建任意空Agent,并获取该Agent的app_id(即界面上的应用ID,在首页->个人空间->应用 里面即会显示应用ID),这里任意空Agent就可以,无需任何配置信息,这个agent的作用只是为了获取app_id信息 | "YOUR-APP-ID" | | `instruction` | str | 否 | 用户指令 | "你的回答要严谨客观,且答案一定要分点阐述" | | `addition_instruction` | str | 否 | 用户增强指令,可选填,该内容会进一步增强大模型的指令跟随能力,将你最需要增强效果的指令填于此,注意:该字段内容过多会一定程度影响大模型内容严谨度 | "你的答案需要分点阐述" | ### 响应参数 | 参数名称 | 参数类型 | 描述 | 示例值 | | ------- |------| -------- | -------- | | `result` | str | 模型运行后的输出结果 | "" | ### 响应示例-流式输出 ``` data: {"type": "text", "text": "文件解析完成, 耗时13485.63ms\n\n"} request_id: f99a7230-649f-4170-ade7-62d8368a18e6 data: {"type": "text", "text": "**Human", "event_status": "running"} request_id: f99a7230-649f-4170-ade7-62d8368a18e6 data: {"type": "text", "text": "-Timescale Adaptation in an Open-Ended Task Space** 文档详细介绍了DeepMind团队开发的自适应代理(Adaptive Agent,简称", "event_status": "running"} request_id: f99a7230-649f-4170-ade7-62d8368a18e6 data: {"type": "text", "text": "AdA)在开放任务空间中的快速适应能力。", "event_status": "running"} request_id: f99a7230-649f-4170-ade7-62d8368a18e6 data: {"type": "text", "text": "", "event_status": "done"} request_id: f99a7230-649f-4170-ade7-62d8368a18e6 ``` ### 响应示例-非流式输出 ``` {'code': 0, 'message': '', 'result': {'text': '文件解析完成, 耗时14572.57ms\n\n**Human-Timescale Adaptation in an Open-Ended Task Space** 文档详细介绍了DeepMind团队开发的自适应代理(Adaptive Agent,简称AdA)在开放任务空间中的快速适应能力。以下是文档的主要内容和贡献点:\n\n1. **引言**:\n - 强调了快速适应能力对于人工智能的重要性,特别是在现实世界中的应用和与人类互动的场景中。\n - 提出了通过元强化学习(meta-RL)和自动课程学习(auto-curriculum learning)等方法,训练能够在未见过的环境中快速适应的代理。\n\n2. **自适应代理(AdA)**:\n - 介绍了AdA的设计和训练方法,包括其在开放任务空间中的适应行为、记忆架构、以及如何通过自动课程学习来优化训练过程。\n - 展示了AdA能够在几分钟内解决复杂的3D任务,且不需要进一步的代理训练,显示了其快速适应的能力。\n\n3. **实验与结果**:\n - 在多个方面评估了AdA的性能,包括其在单代理和多代理设置下的适应能力、不同架构和课程学习方法的影响、以及模型大小和记忆长度对性能的影响。\n - 通过与人类玩家的比较,证明了AdA在适应速度上与人类相当。\n\n4. **相关工作**:\n - 回顾了与本工作相关的领域,包括程序化环境生成、开放任务学习、适应性和强化学习中的Transformer应用等。\n\n5. **结论**:\n - 总结了AdA的贡献,强调了其在开放任务空间中快速适应的能力,以及通过元强化学习和自动课程学习等方法训练大型模型的可能性。\n\n6. **作者和贡献**:\n - 列出了主要贡献者和部分贡献者,以及项目的赞助商和认可。\n\n**主要贡献点**:\n- 提出了AdA,一个能够在开放任务空间中快速适应的代理,其适应速度与人类相当。\n- 通过元强化学习和自动课程学习等方法,训练了大型Transformer模型,展示了其在开放任务空间中的快速适应能力。\n- 分析了不同架构、课程学习方法、模型大小和记忆长度对AdA性能的影响,提供了详细的实验结果和比较。\n- 通过与人类玩家的比较,证明了AdA在适应速度上的优势。'}, 'request_id': '687642b0-b877-49ed-9ad9-65d76de0ea58'} ``` ## 高级用法 ## 更新记录和贡献 ### 2024.10. 15 #### [Added] - 第一版 ================================================ FILE: docs/BasisModule/Components/embeddings/README.md ================================================ # 向量计算(Embedding) ## 简介 向量计算组件(Embedding)支持将文本转化为用数值表示的向量形式,用于文本检索、信息推荐、知识挖掘等场景。嵌入(Embedding)是一种在机器学习和自然语言处理中常用的技术,主要用于将大量高维数据(如单词、图像等)转换为更低维的向量表示。这些向量表示捕获了原始数据的关键特征和关系。 ### 功能介绍 1. 维度降低:将高维数据(如词汇表中的单词)映射到低维空间,使得数据处理更高效。 2. 特征学习:学习数据的内在特征,使得具有相似含义的元素在嵌入空间中彼此接近。 3. 关系映射:在嵌入空间中,数据点的距离和方向可以表示元素之间的关系。 ### 特色优势 Embedding-V1,是基于百度文心大模型技术的文本表示模型,在Embedding模块中,我们使用Embedding-V1作为默认模型。 ### 应用场景 1. 文本检索 2. 信息推荐 3. 知识挖掘 ## 基本用法 当前支持的embedding底座模型暂时只包括: - embedding-v1 ### 下面是使用单条字符串测试的代码示例 请注意,您必须确保字符串的token长度小于384 ```python import os import appbuilder # 请前往千帆AppBuilder官网创建密钥,流程详见:https://cloud.baidu.com/doc/AppBuilder/s/Olq6grrt6#1%E3%80%81%E5%88%9B%E5%BB%BA%E5%AF%86%E9%92%A5 os.environ["APPBUILDER_TOKEN"] = '...' embedding = appbuilder.Embedding() out = embedding("hello world!") # 得到一个长度为384的float数组 print(out.content) ``` ### 下面是使用多条字符串测试的代码示例 ```python import os import appbuilder # 请前往千帆AppBuilder官网创建密钥,流程详见:https://cloud.baidu.com/doc/AppBuilder/s/Olq6grrt6#1%E3%80%81%E5%88%9B%E5%BB%BA%E5%AF%86%E9%92%A5 os.environ["APPBUILDER_TOKEN"] = '...' embedding = appbuilder.Embedding() outs = embedding.batch(["hello", "world"]) # 得到一个长度为 2 x 384的float 二维数组 print(out.content) ``` ### 下面是使用上游的Message作为输入的代码示例 ```python import os import appbuilder # 请前往千帆AppBuilder官网创建密钥,流程详见:https://cloud.baidu.com/doc/AppBuilder/s/Olq6grrt6#1%E3%80%81%E5%88%9B%E5%BB%BA%E5%AF%86%E9%92%A5 os.environ["APPBUILDER_TOKEN"] = '...' from appbuilder import Message embedding = appbuilder.Embedding() query = Message("你好,世界!") out = embedding(query) # 得到一个长度为384的float数组 print(out.content) ``` ### 下面是批量运行的代码示例 ```python import os import appbuilder # 请前往千帆AppBuilder官网创建密钥,流程详见:https://cloud.baidu.com/doc/AppBuilder/s/Olq6grrt6#1%E3%80%81%E5%88%9B%E5%BB%BA%E5%AF%86%E9%92%A5 os.environ["APPBUILDER_TOKEN"] = '...' from appbuilder import Message embedding = appbuilder.Embedding() query = Message([ "你好", "世界" ]) outs = embedding.batch(query) # 得到一个长度为 2 x 384的float 二维数组 print(outs.content) ``` ## 参数说明 ### 鉴权说明 使用组件之前,请首先申请并设置鉴权参数,可参考[组件使用流程](https://cloud.baidu.com/doc/AppBuilder/s/Olq6grrt6#1%E3%80%81%E5%88%9B%E5%BB%BA%E5%AF%86%E9%92%A5)。 ```python # 设置环境中的TOKEN,以下示例略 os.environ["APPBUILDER_TOKEN"] = "bce-YOURTOKEN" ``` ### 初始化参数 | 参数名称 | 参数类型 | 是否必须 | 描述 | 示例值 | | -------- | -------- | -------- | ------------------------------------------------------------ | ---------------- | | model | 字符串 | 可选 | 指定底座模型的类型。当前仅支持 embedding-v1 作为可选值。若不指定,默认值为 embedding-v1。 | embedding-v1 | ### 调用参数 #### 单条 | 参数名称 | 参数类型 | 是否必须 | 描述 | 示例值 | | -------- | -------- | -------- | ------------------------------------------------------------ | ---------------- | | text | 字符串 | 必须 | 一个类型为 string 的句子,用于输入。该句子的长度不能超过384个字符,通常为用户的输入。 | "您好,我需要帮助。" | #### 批量 | 参数名称 | 参数类型 | 是否必须 | 描述 | 示例值 | | -------- | --------------- | -------- | ---------------------------------------------------------------- | ------------------------------------ | | texts | 字符串列表 | 必须 | 一个类型为 List[string] 的句子数组。数组中的每个元素都是一个句子,且每个句子的长度不能超过384个字符。通常这些句子为和用户输入相关的文本候选集。 | ["您好,我需要帮助。", "请问有什么可以帮您?"] | ### 响应示例 #### 单条 ``` [0.1, 0.2, 0.3, ....] ``` #### 批量 ``` [ [0.1, 0.2, ...], ..., [0.1, 0.2, ...], ] ``` ### 错误码 无 ## 更新记录和贡献 * embedding-v1 (2023-12) ================================================ FILE: docs/BasisModule/Components/extract_table/README.md ================================================ # 表格抽取组件(ExtractTableFromDoc) ## 简介 表格抽取组件(ExtractTableFromDoc)是用于文档表格处理的组件,从文档中抽取表格。支持对文档表格大小进行限制,限制后自动进行拆分、跨页合并等处理;支持合并表格上文,提取的表格为Markdown格式。 ### 功能介绍 从文档中抽取表格。支持对文档表格大小进行限制,限制后自动进行拆分、跨页合并等处理;支持合并表格上文,设置表格上文数量,提取的表格为Markdown格式。 ### 特色优势 组件抽取表格,准确高效,代码简单可快速上手;且不依赖本地计算资源。 ### 适用场景 文档表格解析与处理,用于后续任务的输入。 ## 基本用法 下面是一个基本用法的样例 ```python import os import json import requests from appbuilder.utils.logger_util import logger from appbuilder import Message, ExtractTableFromDoc, DocParser # 请前往千帆AppBuilder官网创建密钥,流程详见:https://cloud.baidu.com/doc/AppBuilder/s/Olq6grrt6#1%E3%80%81%E5%88%9B%E5%BB%BA%E5%AF%86%E9%92%A5 os.environ["APPBUILDER_TOKEN"] = "..." # 进行文档内容解析 file_url = "https://agi-dev-platform-bos.bj.bcebos.com/ut_appbuilder/test.pdf?authorization=bce-auth-v1/e464e6f951124fdbb2410c590ef9ed2f/2024-01-25T12%3A56%3A15Z/-1/host/b54178fea9be115eafa2a8589aeadfcfaeba20d726f434f871741d4a6cb0c70d" file_data = requests.get(file_url).content file_path = "./test.pdf" # 待解析的文件路径 with open(file_path, "wb") as f: f.write(file_data) msg = Message(file_path) parser = DocParser() # ExtractTableFromDoc输入为文档原始解析结果,此处需要带上原始结果,return_raw=True. doc = parser(msg, return_raw=True).content.raw # 抽取文档中的表格 parser = ExtractTableFromDoc() result = parser.run(Message(doc)) logger.info("Tables: {}".format( json.dumps(result.content, ensure_ascii=False)) ) ``` ## 参数说明 ### 鉴权说明 使用组件之前,请首先申请并设置鉴权参数,可参考[组件使用流程](https://cloud.baidu.com/doc/AppBuilder/s/Olq6grrt6#1%E3%80%81%E5%88%9B%E5%BB%BA%E5%AF%86%E9%92%A5)。 ```python # 设置环境中的TOKEN,以下示例略 os.environ["APPBUILDER_TOKEN"] = "bce-YOURTOKEN" ``` ### 初始化参数 无 ### 调用参数 |参数名称 |参数类型 |是否必须 |描述 |示例值| |--------|--------|--------|----|------| |message | Dict |是 | 输入的消息,用于模型的主要输入内容,必须为Docparser解析后的结果raw,需要设置return_raw=True。这是一个必需的参数。| `Message(parser(msg, return_raw=True).content.raw)` | |table_max_size |int |否 |单个表格的长度的最大值(包含上文),按字符数即len(table_str)统计,默认为800。如果表格超长,则会被拆分成多个子表格,拆分的最小粒度为表格的行。若单行就超长,则会强制按table_max_size截断。截断时会优先截断上文,尽量保留表格内容。 | 800 | |doc_node_num_before_table |int |否 |表格前附加的上文DocParser Node的数量,默认为1。范围:1~10。 | 1 | ### 响应参数 |参数名称 |参数类型 |描述 |示例值| |--------|--------|----|------| | - | List | 解析出来的文档表格,如果元素长度为1,则对应原文档中格式化后的长度不超过`table_max_size`的表格;如果元素长度>1,则是对应原文档中一个大表格,该表格被拆分成的多个子表格,以满足设置大小。 | 见响应示例 | ### 错误码 |错误码|描述| |------|---| ### 响应示例 ```json [[{"para": "table1"}], [{"para": "table2-part1"}, {"para": "table2-part2"}]] ``` ## 更新记录和贡献 * 表格抽取能力 (2023-12) ================================================ FILE: docs/BasisModule/Components/gbi/nl2sql/README.md ================================================ # GBI 问表 ## 简介 GBI 问表,根据提供的 mysql 表的 schema 信息,生成对应问题的 sql 语句。 ### 功能介绍 GBI 问表,根据提供的 mysql 表的 schema 信息,生成对应问题的 sql 语句。 ### 特色优势 直接生成 sql 语句,无需人工编写。 ### 应用场景 1. 业务人员需要根据问题生成 sql 语句,但是不熟悉 sql 语法。 2. 业务人员需要根据问题生成 sql 语句,但是不熟悉表的名称。 ## 基本用法 这里是一个示例,展示如何基于 mysql 表的 schema, 根据问题生成 sql 语句。 ```python import logging import os import appbuilder from appbuilder.core.message import Message from appbuilder.core.components.gbi.basic import SessionRecord # 请前往千帆AppBuilder官网创建密钥,流程详见:https://cloud.baidu.com/doc/AppBuilder/s/Olq6grrt6#1%E3%80%81%E5%88%9B%E5%BB%BA%E5%AF%86%E9%92%A5 os.environ["APPBUILDER_TOKEN"] = "..." SUPER_MARKET_SCHEMA = """ CREATE TABLE `supper_market_info` ( `订单编号` varchar(32) DEFAULT NULL, `订单日期` date DEFAULT NULL, `邮寄方式` varchar(32) DEFAULT NULL, `地区` varchar(32) DEFAULT NULL, `省份` varchar(32) DEFAULT NULL, `客户类型` varchar(32) DEFAULT NULL, `客户名称` varchar(32) DEFAULT NULL, `商品类别` varchar(32) DEFAULT NULL, `制造商` varchar(32) DEFAULT NULL, `商品名称` varchar(32) DEFAULT NULL, `数量` int(11) DEFAULT NULL, `销售额` int(11) DEFAULT NULL, `利润` int(11) DEFAULT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 """ table_schemas = [SUPER_MARKET_SCHEMA] gbi_nl2sql = appbuilder.NL2Sql(model_name="ERNIE-Bot 4.0", table_schemas=table_schemas) query = "列出超市中的所有数据" nl2sql_result_message = gbi_nl2sql(Message({"query": query})) print(f"sql: {nl2sql_result_message.content.sql}") print(f"llm result: {nl2sql_result_message.content.llm_result}") ``` ## 参数说明 ### 初始化参数 - model_name: 支持的模型名字 ERNIE-Bot 4.0, ERNIE-Bot, ERNIE-Bot-turbo, DeepSeek-V3.1 - table_schemas: 表的 schema,例如: ``` CREATE TABLE `supper_market_info` ( `订单编号` varchar(32) DEFAULT NULL, `订单日期` date DEFAULT NULL, `邮寄方式` varchar(32) DEFAULT NULL, `地区` varchar(32) DEFAULT NULL, `省份` varchar(32) DEFAULT NULL, `客户类型` varchar(32) DEFAULT NULL, `客户名称` varchar(32) DEFAULT NULL, `商品类别` varchar(32) DEFAULT NULL, `制造商` varchar(32) DEFAULT NULL, `商品名称` varchar(32) DEFAULT NULL, `数量` int(11) DEFAULT NULL, `销售额` int(11) DEFAULT NULL, `利润` int(11) DEFAULT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 ``` - knowledge: 用于提供一些知识, 比如 {"毛利率": "(销售收入 - 销售成本) / 销售收入"} - prompt_template: prompt 模版, 必须包含的格式如下: ***你的描述 {schema} ***你的描述 {column_instrument} ***你的描述 {kg} ***你的描述 当前时间:{date} ***你的描述 {history_instrument} ***你的描述 当前问题:{query} 回答: ### 调用参数 - message: message.content 是 字典,包含: query, session, column_constraint 三个key * query: 用户的问题 * session: gbi session 的历史 列表, 参考 SessionRecord * column_constraint: 列选约束 参考 ColumnItem 具体定义 #### SessionRecord 初始化参数 - query: 用户的问题 - answer: gbi_nl2sql 返回的结果 NL2SqlResult #### ColumnItem 初始化参数如下 - ori_value: query 中的 词语, 比如: "北京去年收入", 分词后: "北京, 去年, 收入", ori_value 是分词中某一个,比如: ori_value = "北京" - column_name: 对应数据库中的列名称, city - column_value: 对应数据库中的列值, 北京市 - table_name: 该列所属的表名称 - is_like: 与 ori_value 的匹配是包含 还是 等于,包含: True; 等于: False ### 返回值 - NL2SqlResult 的 message #### NL2SqlResult 初始化参数如下 - llm_result: 大模型返回的结果 - sql: 从 llm_result 中抽取的 sql 语句 ## 高级用法 ### 设置 session ```python session = list() session.append(SessionRecord(query=query, answer=nl2sql_result_message.content)) ``` 再次问表 ```python nl2sql_result_message2 = gbi_nl2sql(Message({"query": "查看商品类别是水果的所有数据", "session": session})) print(f"sql: {nl2sql_result_message2.content.sql}") print(f"llm result: {nl2sql_result_message2.content.llm_result}") ``` sql: SELECT * FROM supper_market_info WHERE 商品类别 = '水果'; ----------------- llm result: ```sql SELECT * FROM supper_market_info WHERE 商品类别 = '水果'; ``` ### 增加列选优化 实际上数据中 "商品类别" 存储的是 "新鲜水果", 那么就可以通过列选的限制来优化 sql. ```python from appbuilder.core.components.gbi.basic import ColumnItem column_constraint = [ColumnItem(ori_value="水果", column_name="商品类别", column_value="新鲜水果", table_name="超市营收明细表", is_like=False)] nl2sql_result_message2 = gbi_nl2sql(Message({"query": "查看商品类别是水果的所有数据", "column_constraint": column_constraint})) print(f"sql: {nl2sql_result_message2.content.sql}") print(f"llm result: {nl2sql_result_message2.content.llm_result}") ``` sql: SELECT * FROM supper_market_info WHERE 商品类别='新鲜水果' ----------------- llm result: ```sql SELECT * FROM supper_market_info WHERE 商品类别='新鲜水果' ``` 从上面我们看到,商品类别不在是 "水果" 而是 修订为 "新鲜水果" ### 增加知识优化 当计算某些特殊知识的时候,大模型是不知道的,所以需要告诉大模型具体的知识,比如: 利润率的计算方式: 利润/销售额 可以将该知识注入。具体示例如下: ```python # 注入知识 gbi_nl2sql.knowledge["利润率"] = "计算方式: 利润/销售额" ``` ```python query3 = "列出商品类别是日用品的利润率" msg3 = Message(query3) nl2sql_result_message3 = gbi_nl2sql(Message({"query": "列出商品类别是日用品的利润率"})) print(f"sql: {nl2sql_result_message3.content.sql}") print(f"llm result: {nl2sql_result_message3.content.llm_result}") ``` sql: SELECT 商品类别, SUM(利润)/SUM(销售额) AS 利润率 FROM supper_market_info WHERE 商品类别 = '日用品' GROUP BY 商品类别 ----------------- llm result: ```sql SELECT 商品类别, SUM(利润)/SUM(销售额) AS 利润率 FROM supper_market_info WHERE 商品类别 = '日用品' GROUP BY 商品类别 ``` ## 调整 prompt 模版 有时候,我们希望定义自己的prompt, 但是必须遵循对应的 prompt 模版的格式。 问表的 prompt template 必须包含: 1. {schema} - 表的 schema 信息 2. {instrument} - 列选限制的信息 3. {kg} - 知识 4. {date} - 时间 5. {history_prompt} - 历史 6. {query} - 当前问题 参考下面的示例 ```python NL2SQL_PROMPT_TEMPLATE = """ MySql 表 Schema 如下: {schema} 请根据用户当前问题,联系历史信息,仅编写1个sql,其中 sql 语句需要使用```sql ```这种 markdown 形式给出。 请参考列选信息: {instrument} 请参考知识: {kg} 当前时间:{date} 历史信息如下: {history_prompt} 当前问题:"{query}" 回答: """ ``` ```python gbi_nl2sql5 = appbuilder.NL2Sql(model_name="ERNIE-Bot 4.0", table_schemas=table_schemas, prompt_template=NL2SQL_PROMPT_TEMPLATE) nl2sql_result_message5 = gbi_nl2sql5(Message({"query": "查看商品类别是水果的所有数据"})) print(f"sql: {nl2sql_result_message5.content.sql}") print(f"llm result: {nl2sql_result_message5.content.llm_result}") ``` sql: SELECT * FROM supper_market_info WHERE 商品类别 = '水果' ----------------- llm result: ```sql SELECT * FROM supper_market_info WHERE 商品类别 = '水果' ``` ================================================ FILE: docs/BasisModule/Components/gbi/select_table/README.md ================================================ # GBI 选表 ## 简介 GBI 选表:根据提供的多个 MySql 表名 以及 表名对应的描述信息,通过 query 选择一个或多个最合适的表来回答该 query。 一般的适用场景是,当有数据库有多个表的时候,但是实际只有1个表能回答该 query,那么,通过该能力将该表选择出来,用于后面的 问表 环节。 ### 功能介绍 GBI 选表,根据提供的多个 MySql 表名 以及 表名对应的描述信息,通过 query 选择一个或多个最合适的表来回答该 query。 一般的适用场景是,当有数据库有多个表的时候,但是实际只有1个表能回答该 query,那么,通过该能力将该表选择出来,用于后面的 问表 环节。 ### 特色优势 可直接通过上传Excel进行数据问答 ### 应用场景 1. 营销数据分析 2. 表格问答 ## 基本用法 下面是根据提供的表的描述信息以及 query 选择对应的表的示例。 ```python import logging import os import appbuilder from appbuilder.core.message import Message from appbuilder.core.components.gbi.basic import SessionRecord # 请前往千帆AppBuilder官网创建密钥,流程详见:https://cloud.baidu.com/doc/AppBuilder/s/Olq6grrt6#1%E3%80%81%E5%88%9B%E5%BB%BA%E5%AF%86%E9%92%A5 os.environ["APPBUILDER_TOKEN"] = "..." # 表的描述信息, key: 表名; value: 是表的描述 table_descriptions = { "supper_market_info": "超市营收明细表,包含超市各种信息等", "product_sales_info": "产品销售表" } # 生成问表对象 select_table = appbuilder.SelectTable(model_name="ERNIE-Bot 4.0", table_descriptions=table_descriptions) select_table_result_message = select_table(Message({"query": "列出超市中的所有数据"})) print(f"选的表是: {select_table_result_message.content}") ``` 选的表是: ['supper_market_info'] ## 参数说明 ### 初始化参数 - model_name: 支持的模型名字 ERNIE-Bot 4.0, ERNIE-Bot, ERNIE-Bot-turbo, DeepSeek-V3.1 - table_descriptions: 表的描述是个字典,key: 是表的名字, value: 是表的描述,例如: ``` { "supper_market_info": "超市营收明细表,包含超市各种信息等", "product_sales_info": "产品销售表" } ``` - prompt_template: prompt 模版, 必须包含如下: 1. {num} - 表的数量, 注意 {num} 有两个地方出现 2. {table_desc} - 表的描述 3. {query} - query 参考下面的示例: ``` 你是一个专业的业务人员,下面有{num}张表,具体表名如下: {table_desc} 请根据问题帮我选择上述1-{num}种的其中相关表并返回,可以为多表,也可以为单表, 返回多张表请用“,”隔开 返回格式请参考如下示例: 问题:有多少个审核通过的投运单? 回答: ```DWD_MAT_OPERATION``` 请严格参考示例只不要返回无关内容,直接给出最终答案后面的内容,分析步骤不要输出 问题:{query} 回答: ``` ### 调用参数 - message: message.content 是用户的问题,包含的key: query, session * query: 用户提出的问题 * session: SessionRecord 列表 #### SessionRecord 初始化参数 - query: 用户的问题 - answer: gbi_nl2sql 返回的结果 NL2SqlResult ### 返回值 识别的表名的列表例如: `["table_name"]` ## 调整 prompt 模版 有时候,我们希望定义自己的prompt, 选表支持 prompt 模版的定制化,但是必须遵循对应的 prompt 模版的格式。 ### 选表 prompt 调整 选表的 prompt template, 必须包含 1. {num} - 表的数量, 注意 {num} 有两个地方出现 2. {table_desc} - 表的描述 3. {query} - query, 参考下面的示例: ```python SELECT_TABLE_PROMPT_TEMPLATE = """ 你是一个专业的业务人员,下面有{num}张表,具体表名如下: {table_desc} 请根据问题帮我选择上述1-{num}种的其中相关表并返回,可以为多表,也可以为单表, 返回多张表请用“,”隔开 返回格式请参考如下示例: 问题:有多少个审核通过的投运单? 回答: ```DWD_MAT_OPERATION``` 请严格参考示例只不要返回无关内容,直接给出最终答案后面的内容,分析步骤不要输出 问题:{query} 回答: """ ``` ```python select_table4 = appbuilder.SelectTable(model_name="ERNIE-Bot 4.0", table_descriptions=table_descriptions, prompt_template=SELECT_TABLE_PROMPT_TEMPLATE) select_table_result_message4 = select_table4(Message({"query": "列出超市中的所有数据"})) print(f"选的表是: {select_table_result_message4.content}") ``` 选的表是: ['supper_market_info'] ================================================ FILE: docs/BasisModule/Components/general_ocr/README.md ================================================ # 通用文字识别-高精度版(GeneralOCR) ## 简介 通用文字识别组件(GeneralOCR)支持多场景、多语种、高精度的文字识别服务,对图片全部文字内容进行检测识别。 ### 功能介绍 覆盖多种通用场景、20+种语言的高精度整图文字检测和识别服务,包括各类印刷和手写文档、网络图片、表格、印章、数字、二维码等; ### 特色优势 * 准确率高 多项ICDAR指标居世界第一,识别准确率高 ### 应用场景 支持多场景、多语种、高精度的文字识别服务,可用于纸质文档电子化、办公文档/报表识别、图像内容审核等场景 ## 基本用法 以下是一个简单的例子来演示如何开始使用GeneralOCR组件: 示例图片为![示例图片](https://bj.bcebos.com/v1/appbuilder/general_ocr_test.png?authorization=bce-auth-v1%2FALTAKGa8m4qCUasgoljdEDAzLm%2F2024-01-11T10%3A59%3A17Z%2F-1%2Fhost%2F081bf7bcccbda5207c82a4de074628b04ae857a27513734d765495f89ffa5f73) ```python import os import appbuilder import requests # 请前往千帆AppBuilder官网创建密钥,流程详见:https://cloud.baidu.com/doc/AppBuilder/s/Olq6grrt6#1%E3%80%81%E5%88%9B%E5%BB%BA%E5%AF%86%E9%92%A5 os.environ["APPBUILDER_TOKEN"] = '...' # 从BOS读取样例图片 image_url = "https://bj.bcebos.com/v1/appbuilder/general_ocr_test.png?"\ "authorization=bce-auth-v1%2FALTAKGa8m4qCUasgoljdEDAzLm%2F2024-01-"\ "11T10%3A59%3A17Z%2F-1%2Fhost%2F081bf7bcccbda5207c82a4de074628b04ae"\ "857a27513734d765495f89ffa5f73" raw_image = requests.get(image_url).content general_ocr = appbuilder.GeneralOCR() out = general_ocr.run(appbuilder.Message(content={"raw_image": raw_image})) print(out.content) ``` ## 参数说明 ### 鉴权说明 使用组件之前,请首先申请并设置鉴权参数,可参考[组件使用流程](https://cloud.baidu.com/doc/AppBuilder/s/Olq6grrt6#1%E3%80%81%E5%88%9B%E5%BB%BA%E5%AF%86%E9%92%A5)。 ```python # 设置环境中的TOKEN,以下示例略 os.environ["APPBUILDER_TOKEN"] = "bce-YOURTOKEN" ``` ### 初始化参数 无 ### 调用参数 | 参数名称 | 参数类型 | 是否必须 | 描述 | 示例值 | |---------|---------|------|-----------------------------|------------------------------------------------| | message | String | 是 | 输入的消息,用于模型的主要输入内容。这是一个必需的参数 | Message(content={"raw_image": b"待识别的图片字节流数据"}),图像数据,base64编码后进行urlencode,要求base64编码和urlencode后大小不超过10M,最短边至少15px,最长边最大8192px,支持jpg/jpeg/png/bmp格式 | |timeout| Float | 否 | HTTP超时时间,单位:秒 |1|| | retry | Integer | 否 | HTTP重试次数 | 3 | ### 响应参数 | 参数名称 | 参数类型 | 描述 | 示例值 | |--------------|---------|---------|---------------------------------------------------| | words_result | Array[] | 返回结果 | [{"words":"一站式企业级大模型平台,提供先进的生成式AI生产及应用全流程开发工具链"}] | | + words | String | 识别结果字符串 | "百度智能云千帆大模型平台" | ### 响应示例 ```json { "words_result":[ { "words":"一站式企业级大模型平台,提供先进的生成式AI生产及应用全流程开发工具链" }, { "words":"百度智能云千帆大模型平台" }, { "words":"文心大模型4.0已正式发布,个人和企业客户可通过百度智能云千帆大模型平台接入使用" }, { "words":"立即使用" }, { "words":"在线体验" }, { "words":"使用文档" }, { "words":"定价说明" }, { "words":"千帆社区" }, { "words":"常见概念、使用指导" }, { "words":"定价、计费方式、计量说明" }, { "words":"大模型开发学习、交流社区" } ] } ``` ## 高级用法 目前该模块仅提供基础通用文字识别功能。 ## 更新记录和贡献 * 通用文字识别能力 (2023-12) ================================================ FILE: docs/BasisModule/Components/handwrite_ocr/README.md ================================================ # 手写文字识别 (HandwriteOCR) ## 简介 手写文字识别 (HandwriteOCR),图片中的手写中文、手写数字进行检测和识别,针对不规则的手写字体进行专项优化,识别准确率可达90%以上。 ### 功能介绍 检测识别图片中的手写中文、手写数字,针对不规则的手写字体进行专项优化 ### 特色优势 识别准确率可达90%以上 ### 应用场景 手写文字识别 ## 基本用法 下面是手写文字识别的代码示例: 示例图片为 ![示例图片](https://bj.bcebos.com/v1/appbuilder/test_handwrite_ocr.jpg?authorization=bce-auth-v1%2FALTAKGa8m4qCUasgoljdEDAzLm%2F2024-01-23T11%3A58%3A09Z%2F-1%2Fhost%2F677f93445fb65157bee11cd492ce213d5c56e7a41827e45ce7e32b083d195c8b) ```python import os import requests import appbuilder # 请前往千帆AppBuilder官网创建密钥,流程详见:https://cloud.baidu.com/doc/AppBuilder/s/Olq6grrt6#1%E3%80%81%E5%88%9B%E5%BB%BA%E5%AF%86%E9%92%A5 os.environ["APPBUILDER_TOKEN"] = "..." image_url="https://bj.bcebos.com/v1/appbuilder/test_handwrite_ocr.jpg?authorization=bce-auth-v1%2FALTAKGa8m4qCUasgoljdEDAzLm%2F2024-01-23T11%3A58%3A09Z%2F-1%2Fhost%2F677f93445fb65157bee11cd492ce213d5c56e7a41827e45ce7e32b083d195c8b" # 从BOS存储读取样例文件 raw_image = requests.get(image_url).content inp = appbuilder.Message(content={"raw_image": raw_image}) # inp = Message(content={"url": image_url}) # 运行手写文字识别 handwrite_ocr = appbuilder.HandwriteOCR() out = handwrite_ocr.run(inp) # 打印识别结果 print(out.content) ``` ## 参数说明 ### 鉴权说明 使用组件之前,请首先申请并设置鉴权参数,可参考[组件使用流程](https://cloud.baidu.com/doc/AppBuilder/s/Olq6grrt6#1%E3%80%81%E5%88%9B%E5%BB%BA%E5%AF%86%E9%92%A5)。 ```python import os os.environ["APPBUILDER_TOKEN"] = "..." ``` ### 初始化参数 无 ### 调用参数 | 参数名称 | 参数类型 | 是否必须 | 描述 |示例值| |------------|--------|------|-----------------------------|---| | message | String | 是 | 输入的消息,用于模型的主要输入内容。这是一个必需的参数 || | +content | Dict | 是 | 消息内容 || | +raw_image | String | 否 | 原始图片字节流 || | +url | String | 否 | 图片下载链接地址 || |timeout| Float | 否 | HTTP超时时间,单位:秒 |1|| |retry|Integer| 否 | HTTP重试次数 |3|| ### 响应参数 | 参数名称 | 参数类型 | 描述 | 示例值 | |-----------|----------|--|-----------------------------------------------------------------| | contents | List | 文本内容块 | | | +text | String | 文本字符串 | | | +Position | Dict | 文本位置信息 | | | ++left | Interger | 表示定位位置的长方形左上顶点的水平坐标 | | | ++top | Interger | 表示定位位置的长方形左上顶点的垂直坐标| | | ++width | Interger | 表示定位位置的长方形的宽度 | | | ++height | Interger | 表示定位位置的长方形的高度 | | | direction | Interger | 图像旋转角度 | 图像旋转角度,0(正向),- 1(逆时针90度),- 2(逆时针180度),- 3(逆时针270度)| ### 响应示例 ```json { "contents": [{ "text": "我们家住的小区里有很多银杏树。", "position": { "left": 390, "top": 46, "width": 1801, "height": 161 } }, { "text": "它们笔直笔直的,就像一位正在站岗的", "position": { "left": 131, "top": 263, "width": 2083, "height": 170 } }, { "text": "卫兵。它枝繁叶茂,长的非常好,它的叶子", "position": { "left": 154, "top": 483, "width": 2023, "height": 161 } }, { "text": "有些小的像一把把小扇子,大的也像扇子。", "position": { "left": 151, "top": 699, "width": 2167, "height": 168 } }, { "text": "但是中间有一个缺口,就像被淘汽的小", "position": { "left": 148, "top": 929, "width": 2123, "height": 177 } }, { "text": "朋友用剪刀剪掉了一样。", "position": { "left": 161, "top": 1165, "width": 1340, "height": 217 } } ], "direction": 0 } ``` ## 高级用法 目前该模块仅提供基础的手写体识别。 ## 更新记录和贡献 * 手写文字识别 (2024-01) * 手写文字识别 (2024-02) ================================================ FILE: docs/BasisModule/Components/image_understand/README.md ================================================ # 图像内容理解 (ImageUnderstand) ## 简介 图像内容理解 (ImageUnderstand),输出理解图片后的文本信息 ### 功能介绍 支持输入图片和提问信息,可对输入图片进行理解,输出对图片的一句话描述 ### 特色优势 同时,支持客户自主选择,是否调用大模型对输出文本进行润色,目前支持百度文心大模型调用。 ### 应用场景 图像内容理解 ## 基本用法 下面是图像内容理解的代码示例: 示例图片为:![示例图片](https://bj.bcebos.com/v1/appbuilder/test_image_understand.jpeg?authorization=bce-auth-v1%2FALTAKGa8m4qCUasgoljdEDAzLm%2F2024-01-24T09%3A41%3A01Z%2F-1%2Fhost%2Fe8665506e30e0edaec4f1cc84a2507c4cb3fdb9b769de3a5bfe25c372b7e56e6) ```python import os import appbuilder import requests # 请前往千帆AppBuilder官网创建密钥,流程详见:https://cloud.baidu.com/doc/AppBuilder/s/Olq6grrt6#1%E3%80%81%E5%88%9B%E5%BB%BA%E5%AF%86%E9%92%A5 os.environ["APPBUILDER_TOKEN"] = "..." # 从BOS存储读取样例文件 image_url = "https://bj.bcebos.com/v1/appbuilder/test_image_understand.jpeg?authorization=bce-auth-v1%2FALTAKGa8m4qCUasgoljdEDAzLm%2F2024-01-24T09%3A41%3A01Z%2F-1%2Fhost%2Fe8665506e30e0edaec4f1cc84a2507c4cb3fdb9b769de3a5bfe25c372b7e56e6" raw_image = requests.get(image_url).content # 输入参数为一张图片 inp = appbuilder.Message(content={"raw_image": raw_image, "question": "图片里内容是什么?"}) # 进行图像内容理解 image_understand = appbuilder.ImageUnderstand() out = image_understand.run(inp) # 打印识别结果 print(out.content) ``` ## 参数说明 ### 鉴权说明 使用组件之前,请首先申请并设置鉴权参数,可参考[组件使用流程](https://cloud.baidu.com/doc/AppBuilder/s/Olq6grrt6#1%E3%80%81%E5%88%9B%E5%BB%BA%E5%AF%86%E9%92%A5)。 ```python import os os.environ["APPBUILDER_TOKEN"] = "..." ``` ### 初始化参数 无 ### 调用参数 | 参数名称 | 参数类型 | 是否必须 | 描述 | 示例值 | |------------|--------|------|-----------------------------------|-----| | message | String | 是 | 输入的消息,用于模型的主要输入内容。这是一个必需的参数 | | | +content | Dict | 是 | 消息内容 | | | +raw_image | String | 否 | 原始图片字节流 | | | +url | String | 否 | 图片下载链接地址 | | | +question | String | 是 | 问题字符串,长度小于100 | | | +language | String | 否 | 描述内容的所使用的语言,默认是zh-CN(中文),可选en(英文) | | |timeout| Float | 否 | HTTP超时时间,单位:秒 |1|| |retry| Integer | 否 | HTTP重试次数 |3|| ### 响应参数 | 参数名称 | 参数类型 | 描述 | 示例值 | |-----------|------|--------|-------------------------------------------------| | description | String | 图像理解内容 | "用户上传的图像,经过前期模型分析存在以下信息:;;整个图像内容" | ### 响应示例 ```json { "description": "用户上传的图像,经过前期模型分析存在以下信息:;;整个图像内容可以表述为:...,回答如下问题:图片里内容是什么?, 注意不要复述提供的资料内容" } ``` ### 错误码 |错误码|描述| |------|---| ## 高级用法 目前该模块仅提供基础的图像内容理解。 ## 更新记录和贡献 * 图像内容理解 (2024-01) ================================================ FILE: docs/BasisModule/Components/landmark_recognize/README.md ================================================ # 地标识别(LandmarkRecognition) ## 简介 地标识别组件(LandmarkRecognition)可以识别12万中外著名地标、热门景点,可返回地标名称。 ### 功能介绍 识别中外著名地标、热门景点,可返回地标名称 ### 特色优势 可以识别12万中外著名地标、热门景点 ### 应用场景 地点识别 ## 基本用法 下面是地标识别的代码示例: 示例图片为:![示例图片](https://bj.bcebos.com/v1/appbuilder/landmark_test.jpeg?authorization=bce-auth-v1%2FALTAKGa8m4qCUasgoljdEDAzLm%2F2024-01-11T10%3A59%3A56Z%2F-1%2Fhost%2Fc249a068c6f321b91da0d0fd629b26ded58dcac2b6a3674f32378f5eb8df1ed0) ```python import os import requests import appbuilder # 请前往千帆AppBuilder官网创建密钥,流程详见:https://cloud.baidu.com/doc/AppBuilder/s/Olq6grrt6#1%E3%80%81%E5%88%9B%E5%BB%BA%E5%AF%86%E9%92%A5 os.environ["APPBUILDER_TOKEN"] = '...' # 从BOS存储读取样例文件 image_url = "https://bj.bcebos.com/v1/appbuilder/landmark_test.jpeg?" \ "authorization=bce-auth-v1%2FALTAKGa8m4qCUasgoljdEDAzLm%2F2024-01-" \ "11T10%3A59%3A56Z%2F-1%2Fhost%2Fc249a068c6f321b91" \ "da0d0fd629b26ded58dcac2b6a3674f32378f5eb8df1ed0" raw_image = requests.get(image_url).content # 输入参数为一张图片 inp = appbuilder.Message(content={"raw_image": raw_image}) # 进行地标识别 landmark_recognize = appbuilder.LandmarkRecognition() out = landmark_recognize.run(inp) # 打印识别结果 print(out.content) # eg: {"landmark": "尼罗河"} ``` ## 参数说明 ### 鉴权说明 使用组件之前,请首先申请并设置鉴权参数,可参考[组件使用流程](https://cloud.baidu.com/doc/AppBuilder/s/Olq6grrt6#1%E3%80%81%E5%88%9B%E5%BB%BA%E5%AF%86%E9%92%A5)。 ```python import os os.environ["APPBUILDER_TOKEN"] = "..." ``` ### 初始化参数 无 ### 调用参数 | 参数名称 | 参数类型 | 是否必须 | 描述 |示例值| |------------|--------|------|-----------------------------|---| | message | String | 是 | 输入的消息,用于模型的主要输入内容。这是一个必需的参数 || | +content | Dict | 是 | 消息内容 || | +raw_image | String | 否 | 原始图片字节流 || | +url | String | 否 | 图片下载链接地址 || |timeout| Float | 否 | HTTP超时时间,单位:秒 |1|| |retry|Integer| 否 | HTTP重试次数 |3|| ### 响应参数 | 参数名称 | 参数类型 | 描述 | 示例值 | |----------|------|------|--------| | landmark | str | 地标名字 | 比如:尼罗河 | ### 响应示例 ```json {"landmark": "尼罗河"} ``` ### 错误码 |错误码|描述| |------|---| ## 高级用法 目前该模块仅提供基础的地标识别。 ## 更新记录和贡献 * 地标识别 (2024-01) ================================================ FILE: docs/BasisModule/Components/llms/dialog_summary/README.md ================================================ # 会话小结(DialogSummary) ## 简介 会话小结(DialogSummary)基于生成式大模型对一段用户与坐席的对话生成总结,结果按{"诉求": "", "回应": "", "解决情况": ""}格式输出。适用于运营商、金融、汽车等多种场景的对话总结。 ### 功能介绍 基于生成式大模型对一段用户与坐席的对话生成总结。 ### 特色优势 基于生成式大模型对一段用户与坐席的对话生成总结,结果按{"诉求": "", "回应": "", "解决情况": ""}格式输出。 ### 应用场景 适用于运营商、金融、汽车等多种场景的对话总结。 ## 基本用法 为了快速开始使用会话小结组件,您可以参考以下步骤: ```python import appbuilder import os # 请前往千帆AppBuilder官网创建密钥,流程详见:https://cloud.baidu.com/doc/AppBuilder/s/Olq6grrt6#1%E3%80%81%E5%88%9B%E5%BB%BA%E5%AF%86%E9%92%A5 os.environ["APPBUILDER_TOKEN"] = "bce-YOURTOKEN" dialog_summary = appbuilder.DialogSummary("DeepSeek-V3.1") text = "用户:喂我想查一下我的话费\n坐席:好的女士您话费余的话还有87.49元钱\n用户:好的知道了谢谢\n坐席:嗯不客气祝您生活愉快再见" answer = dialog_summary(appbuilder.Message(text)) print(answer) ``` ## 参数说明 ### 鉴权配置 使用组件之前,请首先申请并设置鉴权参数,可参考[组件使用流程](https://cloud.baidu.com/doc/AppBuilder/s/Olq6grrt6#1%E3%80%81%E5%88%9B%E5%BB%BA%E5%AF%86%E9%92%A5)。 ```python # 设置环境中的TOKEN,以下示例略 os.environ["APPBUILDER_TOKEN"] = "bce-YOURTOKEN" ``` ### 初始化参数 - `model` (str|None): 模型名称,用于指定要使用的千帆模型。 ### 调用参数 ### 调用参数 |参数名称 |参数类型 | 是否必须 | 描述 | 示例值 | |--------|--------|---|-----------------------------------------------------------------------------|---------------| |message |Message | 是 | 输入消息,包含用户提出的问题。 | Message("你好") | |stream|bool| 否 | 是否以流式形式返回响应 | False | |temperature|float| 否 | 模型配置的温度参数,用于调整模型的生成概率。取值范围为 0.0 到 1.0,其中较低的值使生成更确定性,较高的值使生成更多样性。默认值为 1e-10。 | 0.0001 | ### 响应参数 |参数名称 |参数类型 |描述 |示例值| |--------|--------|----|------| |result |Message |返回结果|对象,包含模型运行后的输出消息。| ### 响应示例 ```json {"result": ["您话费余的话还有87.49元钱"]} ``` ### 错误码 无 ## 高级用法 暂无 ## 示例和案例研究 目前暂无具体的实际应用案例。 ## API文档 暂无 ## 更新记录和贡献 * 会话小结更新Readme (2023-12) ================================================ FILE: docs/BasisModule/Components/llms/hallucination_detection/README.md ================================================ # 幻觉检测(Hallucination Detection) ## 简介 幻觉检测(Hallucination Detection)针对问答场景,检测答案中是否存在幻觉。 ### 功能介绍 幻觉检测(Hallucination Detection)针对问答场景,检测答案中是否存在幻觉。 ### 特色优势 无。 ### 应用场景 问答场景,比如RAG问答。 ## 基本用法 下面是幻觉检测的代码示例: ```python import os import appbuilder # 请前往千帆AppBuilder官网创建密钥,流程详见:https://cloud.baidu.com/doc/AppBuilder/s/Olq6grrt6#1%E3%80%81%E5%88%9B%E5%BB%BA%E5%AF%86%E9%92%A5 os.environ['APPBUILDER_TOKEN'] = '...' query = '澳门新麻蒲烤肉店每天开门吗?' context = \ '''澳门美食: 澳门新麻蒲韩国烤肉店 在澳门一年四季之中除了火锅,烤肉也相当受欢迎。提到韩烧,有一间令我印象最深刻,就是号称韩国第一的烤肉店-新麻蒲韩国烤肉店,光是韩国的分店便多达四百多间,海外分店更是遍布世界各地,2016年便落户澳门筷子基区,在原本已经食肆林立的地方一起百花齐放!店内的装修跟韩国分店还完度几乎没差,让食客彷如置身于韩国的感觉,还要大赞其抽风系统不俗,离开时身上都不会沾上烤肉味耶! 时间:周一至周日 下午5:00 - 上午3:00 电话:+853 2823 4012 地址:澳门筷子基船澳街海擎天第三座地下O号铺96号 必食推介: 护心肉二人套餐 来新麻蒲必试的有两样东西,现在差不多每间烤肉店都有炉边烤蛋,但大家知道吗?原来新麻蒲就是炉边烤蛋的开创者,既然是始祖,这已经是个非吃不可的理由!还有一款必试的就是护心肉,即是猪的横隔膜与肝中间的部分,每头猪也只有200克这种肉,非常珍贵,其味道吃起来有种独特的肉香味,跟牛护心肉一样精彩! 秘制猪皮 很多怕胖的女生看到猪皮就怕怕,但其实猪皮含有大量胶原蛋白,营养价值很高呢!这里红通通的猪皮还经过韩国秘制酱汁处理过,会有一点点辣味。烤猪皮的时候也需特别注意火侯,这样吃起来才会有外脆内Q的口感!''' answer = '澳门新麻蒲烤肉店并不是每天开门。' #! 该组件推荐使用DeepSeek-V3.1模型。 hallucination_detection = appbuilder.HallucinationDetection('DeepSeek-V3.1') inputs = {'query': query, 'context': context, 'answer': answer} msg = appbuilder.Message(inputs) result = hallucination_detection.run(msg) print(result) ``` ## 参数说明 ### 鉴权说明 使用组件之前,请首先申请并设置鉴权参数,可参考[组件使用流程](https://cloud.baidu.com/doc/AppBuilder/s/Olq6grrt6#1%E3%80%81%E5%88%9B%E5%BB%BA%E5%AF%86%E9%92%A5)。 ```python # 设置环境中的TOKEN,以下示例略 os.environ["APPBUILDER_TOKEN"] = "bce-YOURTOKEN" ``` ### 初始化参数 | 参数名称 | 参数类型 | 是否必须 | 描述 | 示例值 | | ------- | ------- | -------- | -------- | -------- | | `model` | str | 是 | 模型名称,用于指定要使用的千帆模型。推荐使用DeepSeek-V3.1模型。 | DeepSeek-V3.1 | | `secret_key` | str | 否 | 用户鉴权token,默认从环境变量中获取: `os.getenv("APPBUILDER_TOKEN", "")` | bce-v3/XXX | | `gateway` | str | 否 | 后端网关服务地址,默认从环境变量中获取: `os.getenv("GATEWAY_URL", "")` | https://appbuilder.baidu.com | | `lazy_certification` | bool | 否 | 延迟认证,为True时在第一次运行时认证。默认为False。 | False | ### 调用参数 | 参数名称 | 参数类型 | 是否必须 | 描述 | 示例值 | | ------- | ------- | -------- | -------- | -------- | | `message` | obj | 是 | 输入信息,用于传入用户查询query、根据query得到的检索结果context和基于context生成的query的答案answer。 | Message(content={'query': '...', 'context': '...', 'answer': '...'}) | | `stream` | bool | 否 | 指定是否以流式形式返回响应。默认为 False。 | False | | `temperature` | float | 否 | 模型配置的温度参数,用于调整模型的生成概率。取值范围为 0.0 到 1.0,其中较低的值使生成更确定性,较高的值使生成更多样性。默认值为 1e-10。 | 0.1 | | `top_p` | float | 否 | 影响输出文本的多样性,取值越大,生成文本的多样性越强。取值范围为 0.0 到 1.0,其中较低的值使生成更确定性,较高的值使生成更多样性。默认值为 0.0。 | 0.0 | ### 响应参数 | 参数名称 | 参数类型 | 描述 | 示例值 | | ------- | ------- | -------- | -------- | | `result` | obj | 模型运行后的输出结果(可通过result.content获取结果核心内容) | Message(content='...') | ### 响应示例 ``` Message(name=msg, content=存在幻觉, mtype=dict, extra={}, token_usage={'prompt_tokens': 748, 'completion_tokens': 2, 'total_tokens': 750}) ``` ### 错误码 |错误码|描述| | ------ | ------ | ## 高级用法 可用于RAG问答的答案检测。 ## 更新记录和贡献 ### 2024.5.22 #### [Added] - 增加幻觉检测组件。 - 增加幻觉检测组件单元测试。 ================================================ FILE: docs/BasisModule/Components/llms/is_complex_query/README.md ================================================ # 复杂Query判定(IsComplexQuery) ## 简介 复杂Query判定组件(IsComplexQuery)可以根据输入的提问进行初步的分类,区分简单问题和复杂问题,以便后续运用不同的处理流程处理。可应用于知识问答场景。 ### 功能介绍 在知识问答领域中存在很多复杂问题需要处理,这些复杂问题通常需要进行问题分解并采用分治的方法处理。复杂Query判定组件尝试定义复杂问题和简单问题的概念,对用户的问题进行初步的分类,方便下游使用不同类型的流程来处理当前的简单问题/复杂问题。 ### 特色优势 复杂Query判定组件通过对问题进行有效分类,系统可以更快速地将简单问题导向快速回答流程,而将复杂问题导向更深入的分析流程。这种判定能力可以提高整个问答系统的效率和准确性。 ### 应用场景 广泛应用于知识问答场景 ## 基本用法 下面是复杂Query判定的代码示例: ```python import os import appbuilder # 请前往千帆AppBuilder官网创建密钥,流程详见:https://cloud.baidu.com/doc/AppBuilder/s/Olq6grrt6#1%E3%80%81%E5%88%9B%E5%BB%BA%E5%AF%86%E9%92%A5 os.environ["APPBUILDER_TOKEN"] = "..." is_complex_query = appbuilder.IsComplexQuery(model="DeepSeek-V3.1") msg = "吸塑包装盒在工业化生产和物流运输中分别有什么重要性?" msg = appbuilder.Message(msg) answer = is_complex_query(msg) print("Answer: \n{}".format(answer.content)) ``` ## 参数说明 ### 鉴权说明 使用组件之前,请首先申请并设置鉴权参数,可参考[组件使用流程](https://cloud.baidu.com/doc/AppBuilder/s/Olq6grrt6#1%E3%80%81%E5%88%9B%E5%BB%BA%E5%AF%86%E9%92%A5)。 ```python # 设置环境中的TOKEN,以下示例略 os.environ["APPBUILDER_TOKEN"] = "bce-YOURTOKEN" ``` ### 初始化参数 |参数名称 |参数类型 |是否必须 |描述 |示例值| |--------|--------|--------|----|------| |model |str |是 |模型名称,用于指定要使用的千帆模型|DeepSeek-V3.1| ### 调用参数 |参数名称 |参数类型 |是否必须 |描述 |示例值| |--------|--------|--------|----|------| |message |obj:`Message`|是 |输入消息,用于模型的主要输入内容。这是一个必需的参数| | |stream|bool|否 |指定是否以流式形式返回响应。默认为 False|False| |temperature|float|否 |模型配置的温度参数,用于调整模型的生成概率。取值范围为 0.0 到 1.0,其中较低的值使生成更确定性,较高的值使生成更多样性。默认值为 1e-10|1e-10| ### 响应参数 |参数名称 |参数类型 |描述 |示例值| |--------|--------|----|------| |Message |obj:`Message` |输出消息,包含模型运行后的输出| | ### 响应示例 ```text 分析:这个问题涉及到吸塑包装盒在工业化生产和物流运输中的重要性。回答这个问题需要从多个角度来考虑,比如生产方面、运输方面、环保方面等。这需要对吸塑包装盒有深入的了解,并且需要考虑到生产、运输等各个环节。因此,这是一个复杂问题。 类型:复杂问题 ``` ### 错误码 无 ## 高级用法 你可以通过自定义调整参数来获得想要的结果,例如: ```python # 流式返回, 调整模型temperature参数 answer = is_complex_query(msg, stream=True, temperature=0.5) ``` ## 更新记录和贡献 * 复杂Query判定 (2024-01) ================================================ FILE: docs/BasisModule/Components/llms/mrc/README.md ================================================ # 阅读理解问答(MRC) ## 简介 阅读理解问答(MRC)组件是基于生成式大模型的阅读理解问答系统。该组件支持拒答、澄清、重点强调、友好性提升、溯源等多种功能,可用于回答用户提出的问题。 ### 功能介绍 MRC(阅读理解问答模块)是一项先进的自然语言处理功能,旨在使机器能够理解、分析文本内容,并基于这些内容回答相关问题。 本模块基于大语言模型,提供对文本内容的深入理解和精确回答能力。 ### 特色优势 我们的MRC模块,基于百度自研的先进语言模型文新一言,提供了一系列强大的阅读理解问答功能。在保持文本理解和问题回答的高精度的同时, 我们特别强调了答案的质量和交互体验。以下是我们MRC模块的几个主要功能特色: - 1.多版本模型支持:我们的MRC模块包括不同版本的文新一言大模型,Erniebot 4.0、DeepSeek-V3.1等,每个版本都针对特定的应用场景进行了优化。 用户可以根据自己的需求选择最适合的模型版本,以获得最佳的性能。 - 2.答案格式的多样性: - 拒答功能:当问题超出模型知识范围或不具体时,模型可以选择不回答,避免提供误导性信息。 - 澄清功能:对于模棱两可或含糊的问题,模型可以请求更多信息或对问题进行澄清,以确保答案的准确性。 - 重点内容强调:模型可以识别并强调答案中的关键信息,使答案更清晰、更易于理解。 - 友好度提升:模型可以以更自然、更亲切礼貌的方式呈现答案,且必要时对答案进行分点论述,改善用户体验。 - 答案溯源:模型能提供答案的来源信息,增强答案的可信度和透明度。 - 3.灵活的功能开关:每项功能都配备了开关,用户可以根据不同的应用场景和需求,灵活地启用或关闭某些功能。这种可定制性确保了MRC模块能够在各种环境下提供最优化的表现。 ### 应用场景 我们的MRC模块,凭借文心大模型强大的文本理解能力,以及多功能性,已在多个领域展现出显著的价值。 - 政务服务:在政务领域,MRC模块可以帮助构建智能问答系统,为公民提供关于政策、法规和服务程序的即时信息。它可以通过理解复杂的政府文件和公文,准确回答与政策相关的查询,极大地提高政府服务的效率和透明度。 - 法律咨询:法律领域充满了专业术语和复杂的概念。我们的MRC模块能够深入理解法律文献和案例,为法律专业人士和普通民众提供准确的法律咨询。无论是寻找相关法条还是理解特定法律案例,MRC模块都能提供快速、可靠的帮助。 - 医疗健康:在医疗健康领域,准确的信息至关重要。MRC模块能够解析医学文献、病例报告和临床试验数据,为医生和研究人员提供支持,帮助他们在诊断、治疗和研究中做出更明智的决策。此外,它也能在患者咨询中发挥作用,为患者提供关于疾病、治疗方案和药物的详细信息。 - 教育和研究:MRC模块可以作为学习和研究的强大工具,帮助学生和研究人员快速找到他们需要的信息。无论是解答学术问题,还是提供详细的背景资料,MRC模块都能提供卓越的支持。 - 企业客户服务:企业可以利用MRC模块构建高效的客服系统,提供24/7的咨询服务。从产品详情到服务流程的解释,MRC模块都能提供准确、及时的答案,提升客户满意度并减轻人工客服的压力。 - 金融咨询:在金融领域,MRC模块可以帮助用户理解复杂的金融产品、市场趋势和投资策略。通过提供准确的数据解读和市场分析,MRC模块能够辅助投资者和金融专业人士做出更明智的决策。 除上述场景以外,还可应用于其他更多生产生活的场景中。 ## 基本用法 ### 快速开启 ```python import appbuilder import os # 请前往千帆AppBuilder官网创建密钥,流程详见:https://cloud.baidu.com/doc/AppBuilder/s/Olq6grrt6#1%E3%80%81%E5%88%9B%E5%BB%BA%E5%AF%86%E9%92%A5 os.environ["APPBUILDER_TOKEN"] = "..." # 创建MRC对象 mrc_component = appbuilder.MRC(model="DeepSeek-V3.1") # 初始化参数 msg = "残疾人怎么办相关证件" msg = appbuilder.Message(msg) context_list = appbuilder.Message(["""如何办理残疾人通行证一、残疾人通行证办理条件: 1、持有中华人民共和国残疾人证,下肢残疾或者听力残疾; 2、持有准驾车型为C1(听力残疾)、C2(左下肢残疾、听力残疾)""", """3、本人拥有本市登记核发的非营运小型载客汽车,车辆须在检验有效期内,并有有效交强险凭证, C5车辆加装操纵辅助装置后已办理变更手续。二、办理地点:北京市朝阳区左家庄北里35号: 北京市无障碍环境建设促进中心"""]) # 模拟运行MRC基本组件 result = mrc_component.run(msg, context_list) # 输出运行结果 print(result) ``` ## 参数说明 ### 鉴权说明 使用组件之前,请首先申请并设置鉴权参数,可参考[组件使用流程](https://cloud.baidu.com/doc/AppBuilder/s/Olq6grrt6#1%E3%80%81%E5%88%9B%E5%BB%BA%E5%AF%86%E9%92%A5)。 ```python # 设置环境中的TOKEN,以下示例略 import os os.environ["APPBUILDER_TOKEN"] = "bce-YOURTOKEN" ``` ### 初始化参数 - `model`: 模型名称,用于指定要使用的千帆模型。 ### 调用参数 |参数名称 |参数类型 | 是否必须 |描述 | 示例值 | |--------|--------|---|----|------------------------------------------| |msg |Message | 是 |输入消息,包含用户提出的问题。| Message("你好") | |context_list|Message| 是 |用户输入的问题对应的段落文本列表。| Message(["""context1""","""context2"""]) | |reject|bool| 否 |拒绝开关,如果为 True,则启用该能力。默认为 False。当输入的问题在context_list中没有找到答案时,开关开启时,模型会用特定话术("当前文档库找不到对应的答案,我可以尝试用我的常识来回答你。")做回复的开头,并后接自有知识做回复内容。| eg.示例值 | |clarify|bool| 否 |澄清开关,如果为 True,则启用该能力。默认为 False。 当输入的问题比较模糊、或者主体指代不清晰,且context_list中包含有可以回答该模糊问题的多种潜在备选答案时,开启该开关,大模型会以特定的话术做澄清反问,引导用户继续补充问题发问。举例子,query:发电机的续航时间? Answer: 根据搜索结果得到了xx和xx两种型号的发电机,您的问题具体涉及到哪一个?请补充关键信息,作为完整的问题重新发问。| eg.示例值 | |highlight|bool| 否 |重点强调开关,如果为 True,则启用该能力。默认为 False。开启该功能时,回复结果中会高亮显示关键部分的内容。| 加粗的部分是**重点内容** | |friendly|bool| 否 |友好性提升开关,如果为 True,则启用该能力。默认为 False。开关开启时,部分回复的开头会加礼貌用语。且如果回答涉及到大段的信息,会倾向于以<总-分>或者<总-分-总>的形式做分点论述,使得答案的格式更规整,可读性更强。| eg.示例值 | |cite|bool| 否 |溯源开关,如果为 True,则启用该能力。默认为 False。开关开启时,回复内容后会接形如(^[1]^)的标记来表示回答内容在原文(context_list)中的来源索引。例如:按照当地公安机关出入境管理部门规定的其他材料办理^[2]^。| eg.示例值 | |temperature|float| 否 |模型配置的温度参数,用于调整模型的生成概率。取值范围为 0.0 到 1.0,其中较低的值使生成更确定性,较高的值使生成更多样性。默认值为 1e-10。| 0.0001 | ### 响应参数 |参数名称 |参数类型 |描述 |示例值| |--------|--------|----|------| |result |Message |返回结果|对象,包含模型运行后的输出消息。| ### 响应示例 ```json {"result": "极氪007的售价区间为20.99~29.99万元。"} ``` ### 错误码 无 ## 高级用法 该组件的高级用法包括定制化的输入处理、输出处理,以及更复杂的调用场景。用户可以根据具体需求扩展组件功能,实现个性化的问答系统。 包括如下功能: 1、拒答 2、澄清反问 3、重点强调 4、友好度提升 5、溯源 ### 代码样例 ```python import appbuilder import os # 设置环境变量 os.environ["APPBUILDER_TOKEN"] = '...' # 创建MRC对象 mrc_component = appbuilder.MRC(model="DeepSeek-V3.1") # 初始化参数 msg = "残疾人怎么办相关证件" msg = appbuilder.Message(msg) context_list = appbuilder.Message(["""如何办理残疾人通行证一、残疾人通行证办理条件: 1、持有中华人民共和国残疾人证,下肢残疾或者听力残疾; 2、持有准驾车型为C1(听力残疾)、C2(左下肢残疾、听力残疾)""", """3、本人拥有本市登记核发的非营运小型载客汽车,车辆须在检验有效期内,并有有效交强险凭证, C5车辆加装操纵辅助装置后已办理变更手续。二、办理地点:北京市朝阳区左家庄北里35号: 北京市无障碍环境建设促进中心"""]) # 模拟运行MRC组件,开启拒答、澄清追问、重点强调、友好性提升和溯源能力五个功能 result = mrc_component.run(msg, context_list, reject=True, clarify=True, highlight=True, friendly=True, cite=True) # 输出运行结果 print(result) ``` ## 更新记录和贡献 * 阅读理解问答 (2023-12) ================================================ FILE: docs/BasisModule/Components/llms/nl2pandas/README.md ================================================ # 自然语言转pandas (nl2pandas) ## 简介 自然语言转pandas (nl2pandas)这个组件通过理解对表格信息的提问,生成对应语义的可执行Python代码,主要使用Pandas库。它可以用于基于表格的查询,问答等多种场景。 ### 功能介绍 自然语言转pandas (nl2pandas)根据用户的输入的表格信息和查询query,利用大语言模型的理解和生成能力,自动生成符合查询语义的一行或多行pandas代码。 ### 特色优势 自然语言转pandas (nl2pandas),基于百度自研的大语言模型文心一言,提供内置的自然语言转pandas代码的能力,无需更多的prompt描述,即可生成对应的查询代码。 ### 应用场景 自然语言转pandas (nl2pandas)可用对结构化表格数据的自然语言查询场景,问答场景等。 ## 基本用法 这里是一个简单示例,展示如何使用自然语言转Pandas组件: ```python import os import appbuilder # 请前往千帆AppBuilder官网创建密钥,流程详见:https://cloud.baidu.com/doc/AppBuilder/s/Olq6grrt6#1%E3%80%81%E5%88%9B%E5%BB%BA%E5%AF%86%E9%92%A5 os.environ["APPBUILDER_TOKEN"] = "..." #定义表格信息 假设有一个小学学校表格,包含学校名、所属地区、创办时间、类别、学生人数、教职工人数、教学班数量等列。列名后给出示例(例如清华附小是学校名的示例),以及列值类型(字符串类型、数字值类型),最后给出列名的解释。列之间使用换行符分隔。 table_info = '''表格列信息如下:\n学校名 : 清华附小 , 字符串类型,代表小学学校的名称\n所属地区 : 西城区 , 字符串类型,表示该小学学校所在的位置\n创办时间 : 1998 , 数字值类型,表示该小学学校的创办时间\n类别 : 公立小学 , 字符串类型,表示该小学学校所在的类别\n学生人数 : 2000 , 数字值类型,表示该小学学校的学生数量\n教职工人数 : 140 , 数字值类型,表示该小学学校的教职工数量\n教学班数量 : 122 , 数字值类型,表示该小学学校的教学班数量''' #定义查询问题 query = "海淀区有哪些学校" query = appbuilder.Message(query) #定义并运行Nl2pandas实例,得到结果 nl2pandas = appbuilder.Nl2pandasComponent(model="DeepSeek-V3.1") answer = nl2pandas(query, table_info = table_info) ``` ## 参数说明 ### 鉴权配置 使用组件之前,请首先申请并设置鉴权参数,可参考[组件使用流程](https://cloud.baidu.com/doc/AppBuilder/s/Olq6grrt6#1%E3%80%81%E5%88%9B%E5%BB%BA%E5%AF%86%E9%92%A5)。 ```python # 设置环境中的TOKEN,以下示例略 os.environ["APPBUILDER_TOKEN"] = "bce-YOURTOKEN" ``` ### 初始化参数 - `model`: 模型名称,用于指定要使用的千帆模型。 ### 调用参数 |参数名称 |参数类型 |是否必须 |描述 |示例值| |--------|--------|--------|----|------| |query |Message | 是 | 查询语句,一般是针对表格信息的提问 |例如'海淀区的小学有哪些'。建议长度是50字以内。 | |table_info |str | 是 | 表格信息,是表格列名以及对应列名的举例和释义 |例如:’表格列信息如下:\n学校名 : 清华附小 , 字符串类型,代表小学学校的名称\n所属地区 : 西城区 , 字符串类型,表示该小学学校所在的位置\n创办时间 : 1998 , 数字值类型,表示该小学学校的创办时间\n类别 : 公立小学 , 字符串类型,表示该小学学校所在的类别\n学生人数 : 2000 , 数字值类型,表示该小学学校的学生数量\n教职工人数 : 140 , 数字值类型,表示该小学学校的教职工数量\n教学班数量 : 122 , 数字值类型,表示该小学学校的教学班数量‘ | |stream |bool | 否 |指定是否以流式形式返回响应。默认为 False。 |False | |temperature |float | 否 |模型配置的温度参数,用于调整模型的生成概率。取值范围为 0.0 到 1.0,其中较低的值使生成更确定性,较高的值使生成更多样性。默认值为 1e-10。 |0.7 | ### 响应参数 |参数名称 |参数类型 |描述 |示例值| |--------|--------|----|------| |result |Message |返回结果|Message(content="df.loc[df['所属地区'] == "海淀区","学校名"]")| ## 高级用法 多个表格查询或跨表查询场景。 ## 更新记录和贡献 - 初始版本发布(2023-10) ================================================ FILE: docs/BasisModule/Components/llms/oral_query_generation/README.md ================================================ # 口语化Query生成(Oral Query Generation) ## 简介 口语化Query生成组件(Oral Query Generation)可以基于输入文本生成与文档内容相关的Query。 ### 功能介绍 基于输入文本生成与文档内容相关的Query。 ### 特色优势 生成的query划分为问题和短语两种类型,可分别用于不同场景。 ### 应用场景 可用于推荐问题生成、标签生成、文档索引增强等。 ## 基本用法 ### 快速开始 ```python import os import appbuilder # 请前往千帆AppBuilder官网创建密钥,流程详见:https://cloud.baidu.com/doc/AppBuilder/s/Olq6grrt6#1%E3%80%81%E5%88%9B%E5%BB%BA%E5%AF%86%E9%92%A5 os.environ["APPBUILDER_TOKEN"] = "..." text = ('文档标题:在OPPO Reno5上使用视频超级防抖\n' '文档摘要:OPPO Reno5上的视频超级防抖,视频超级防抖3.0,多代视频防抖算法积累,这一代依旧超级防抖超级稳。 开启视频超级' '防抖 开启路径:打开「相机 > 视频 > 点击屏幕上方的“超级防抖”标识」 后置视频同时支持超级防抖和超级防抖Pro功能,开启超级' '防抖后手机屏幕将出现超级防抖Pro开关,点击即可开启或关闭。 除此之外,前置视频同样加持防抖算法,边走边拍也能稳定聚焦脸部' ',实时视频分享您的生活。') #! 该组件推荐使用DeepSeek-V3.1模型。 oral_query_generation = appbuilder.OralQueryGeneration(model='DeepSeek-V3.1') result = oral_query_generation(appbuilder.Message(text), query_type='全部', output_format='str') print(result) ``` ## 参数说明 ### 鉴权说明 使用组件之前,请首先申请并设置鉴权参数,可参考[组件使用流程](https://cloud.baidu.com/doc/AppBuilder/s/Olq6grrt6#1%E3%80%81%E5%88%9B%E5%BB%BA%E5%AF%86%E9%92%A5)。 ```python # 设置环境中的TOKEN,以下示例略 os.environ["APPBUILDER_TOKEN"] = "bce-YOURTOKEN" ``` ### 初始化参数 | 参数名称 | 参数类型 | 是否必须 | 描述 | 示例值 | | ------- | ------- | -------- | -------- | -------- | | `model` | str | 是 | 模型名称,用于指定要使用的千帆模型。推荐使用DeepSeek-V3.1模型。 | DeepSeek-V3.1 | | `secret_key` | str | 否 | 用户鉴权token,默认从环境变量中获取: `os.getenv("APPBUILDER_TOKEN", "")` | bce-v3/XXX | | `gateway` | str | 否 | 后端网关服务地址,默认从环境变量中获取: `os.getenv("GATEWAY_URL", "")` | https://appbuilder.baidu.com | | `lazy_certification` | bool | 否 | 延迟认证,为True时在第一次运行时认证。默认为False。 | False | ### 调用参数 | 参数名称 | 参数类型 | 是否必须 | 描述 | 示例值 | | ------- | ------- | -------- | -------- | -------- | | `message` | obj | 是 | 输入消息,用于模型的主要输入内容。 | Message(content='...') | | `query_type` | str | 否 | 待生成的query类型,包括问题、短语和全部(问题+短语)。默认为全部。 | 全部 | | `output_format` | str | 否 | 输出格式,包括json和str。默认为str。 | str | | `stream` | bool | 否 | 指定是否以流式形式返回响应。默认为 False。 | False | | `temperature` | float | 否 | 模型配置的温度参数,用于调整模型的生成概率。取值范围为 0.0 到 1.0,其中较低的值使生成更确定性,较高的值使生成更多样性。默认值为 1e-10。 | 0.1 | | `top_p` | float | 否 | 影响输出文本的多样性,取值越大,生成文本的多样性越强。取值范围为 0.0 到 1.0,其中较低的值使生成更确定性,较高的值使生成更多样性。默认值为 0.0。 | 0.0 | ### 响应参数 | 参数名称 | 参数类型 | 描述 | 示例值 | | ------- | ------- | -------- | -------- | | `result` | obj | 模型运行后的输出结果 | Message(content='...') | ### 响应示例 ``` Message(name=msg, content=1. OPPO Reno5上有什么特殊的功能? 2. 视频超级防抖是什么? 3. 视频超级防抖有什么作用? 4. 如何在OPPO Reno5上开启视频超级防抖? 5. 视频超级防抖Pro是什么? 6. 开启视频超级防抖后,屏幕上会出现什么? 7. 前置视频有防抖算法吗? 8. OPPO Reno5上的视频超级防抖 9. 视频超级防抖3.0 10. 多代视频防抖算法积累的作用 11. 开启视频超级防抖的方法 12. 视频超级防抖Pro的功能 13. 开启视频超级防抖后,屏幕上会出现的东西 14. 前置视频防抖算法的作用, mtype=dict, extra={}) ``` ## 高级用法 ## 更新记录和贡献 ### 2024.5.22 #### [Updated] - 升级能力,主要升级内容如下: - 生成的query要求能够使用输入文本进行回答。 - 生成的query划分为问题和短语类型。 - 生成的query数量不再限制为10个。 - 在调用组件时,支持输出问题、短语或全部(问题 + 短语);支持输出格式为json或者str(兼容之前版本的输出格式)。 ### 2024.1.24 #### [Updated] - 更新README。 ### 2023.12.07 #### [Added] - 增加口语化Query生成组件。 - 增加口语化Query生成组件单元测试。 ================================================ FILE: docs/BasisModule/Components/llms/playground/README.md ================================================ # 空应用(Playground) ## 简介 Playground空应用(Playground)是一款灵活的组件,允许用户自定义prompt模板并执行。 ### 功能介绍 Playground空应用(Playground)是一款灵活的组件,允许用户自定义prompt模板并执行。它适用于各种场景,特别是在需要自定义输入模板和使用预训练模型进行交互的情况下。 ### 特色优势 灵活可自定义,用户可自由定义提示词,来跟大模型进行交互。 ### 应用场景 在需要灵活定义提示词的场景,并且其他提供的开箱即用的组件无法满足的情况下使用。 ## 基本用法 要开始使用 Playground,你需要设置prompt模板和模型名称。以下是一个基本示例: ```python import os import appbuilder # 请前往千帆AppBuilder官网创建密钥,流程详见:https://cloud.baidu.com/doc/AppBuilder/s/Olq6grrt6#1%E3%80%81%E5%88%9B%E5%BB%BA%E5%AF%86%E9%92%A5 os.environ["APPBUILDER_TOKEN"] = "..." play = appbuilder.Playground( prompt_template="你好,{name},我是{bot_name},{bot_name}是一个{bot_type},我可以{bot_function},你可以问我{bot_question}。", model="DeepSeek-V3.1" ) play(appbuilder.Message({"name": "小明", "bot_name": "小红", "bot_type": "聊天机器人", "bot_function": "聊天", "bot_question": "你好吗?"}), stream=False) ``` ## 参数说明 ### 初始化参数 | 参数名称 | 类型 | 说明 | |----------------|------------|----------------------------------| | prompt_template | str | 输入模板,用于指定prompt格式。 | | model | str \| None | 模型名称,用于指定要使用的千帆模型。 | ### 调用参数 | 参数名称 | 类型 | 说明 | 默认值 | |-----------|---------------|----------------------------|------| | message | obj:`Message` | 输入消息,必需参数。 | 无 | | stream | bool | 是否以流式形式返回响应。 | False | | temperature | float | 模型配置的温度参数。 | 1e-10 | | max_output_tokens | int | 指定生成的文本的最大长度,默认最大输出token数为1024, 最小为2, 最大输出token与选择的模型有关 | 1024 | |disable_search| bool | 是否关闭搜索功能,默认关闭 | True | |response_format| str | 指定返回的响应格式,可选值有:`text`, `json_object`| text | |stop| str | 生成停止标识,当模型生成结果以stop中某个元素结尾时,停止文本生成。每个元素长度不超过20字符,最多4个元素. | [] | ### 响应参数 | 类型 | 说明 | |----------------|--------------------| | obj:`Message` | 模型运行后的输出消息。 | ### 响应示例 ```json {"result": "北京科技馆。"} ``` ### 错误码 |错误码|描述| |------|---| ## 高级用法 此部分可根据实际应用场景提供更复杂的示例和用法说明。 ## 示例和案例研究 目前暂无具体案例,将在未来更新。 ## API文档 无 ## 更新记录和贡献 - 2024年01月24日 更新Readme格式,调整请求参数样式,新增特色优势 - 2024年08月01日 更新playground组件的入参,并且前向兼容,支持未来的大模型对话参数 ================================================ FILE: docs/BasisModule/Components/llms/qa_pair_mining/README.md ================================================ # 问答对挖掘(QAPairMining) ## 简介 问答对挖掘(QAPairMining)可以基于输入文本内容,快速生成多个问题及对应答案,极大提高信息提炼的效率和准确性。广泛用于在线客服、智能问答等领域。 ### 功能介绍 基于输入文本内容,快速生成多个问题及对应答案;可与文档解析、分段联用,快速生成文档的问答对。 ### 特色优势 问答对挖掘组件快速基于输入文本生成的问题和答案,准确率高;可快速依据文档生成FAQ,减少人工成本。 ### 适用场景 适用于在线客服、智能问答等场景 ## 基本用法 ### 快速开始 ```python import os import appbuilder # 请前往千帆AppBuilder官网创建密钥,流程详见:https://cloud.baidu.com/doc/AppBuilder/s/Olq6grrt6#1%E3%80%81%E5%88%9B%E5%BB%BA%E5%AF%86%E9%92%A5 os.environ["APPBUILDER_TOKEN"] = "..." qa_mining = appbuilder.QAPairMining(model="DeepSeek-V3.1") # 输入文本(对此文本挖掘问答对) msg = '2017年,工商银行根据外部宏观环境变化,及时调整业务策略,优化资产负债结构,' + \ '保持存贷款业务协调发展,提升资产负债配置效率。' + \ '2018年3月末,工商银行总资产264,937.81亿元,比上年末增加4,067.38亿元.' msg = appbuilder.Message(msg) answer = qa_mining(msg) print(">>> Output: {}".format(answer.content)) ``` ## 参数说明 ### 鉴权说明 使用组件之前,请首先申请并设置鉴权参数,可参考[组件使用流程](https://cloud.baidu.com/doc/AppBuilder/s/Olq6grrt6#1%E3%80%81%E5%88%9B%E5%BB%BA%E5%AF%86%E9%92%A5)。 ```python # 设置环境中的TOKEN,以下示例略 os.environ["APPBUILDER_TOKEN"] = "bce-YOURTOKEN" ``` ### 初始化参数 无 ### 调用参数 |参数名称 |参数类型 |是否必须 |描述 |示例值| |--------|--------|--------|----|------| | message | String |是 |输入消息,用于模型的主要输入内容。这是一个必需的参数。| `Message("2017年,工商银行根据...")` | | stream |bool|否 |指定是否以流式形式返回响应。默认为 False。| False | | temperature |float|否 |模型配置的温度参数,用于调整模型的生成概率。取值范围为 0.0 到 1.0,其中较低的值使生成更确定性,较高的值使生成更多样性。默认值为 1e-10。 | 1e-10 | ### 响应参数 |参数名称 |参数类型 |描述 |示例值| |--------|--------|----|------| | result | String | 输出消息,包含模型运行后的输出内容。| 见响应示例 | ### 响应示例 ```text 问题:2017年,工商银行是如何应对外部宏观环境变化的? 答案:工商银行根据外部宏观环境变化,及时调整业务策略,优化资产负债结构,保持存贷款业务协调发展,提升资产负债配置效率。 问题:2018年3月末,工商银行总资产是多少? 答案:264,937.81亿元。 ``` ### 错误码 |错误码|描述| |------|---| ## 高级用法 基于一篇文档,快速生成多个问题及对应答案,极大提高信息提炼的效率和准确性。 主要流程如下: 1. 读取本地文档,文档解析分段,获取段落; 2. 段落作为问答对挖掘的输入,挖掘问答对。 ### 代码样例 ```python import os import requests from appbuilder.utils.logger_util import logger from appbuilder import Message, DocParser, DocSplitter, QAPairMining # 请前往千帆AppBuilder官网创建密钥,流程详见:https://cloud.baidu.com/doc/AppBuilder/s/Olq6grrt6#1%E3%80%81%E5%88%9B%E5%BB%BA%E5%AF%86%E9%92%A5 # os.environ["APPBUILDER_TOKEN"] = "..." # 进行文档内容解析 file_url = "https://agi-dev-platform-bos.bj.bcebos.com/ut_appbuilder/test.pdf?authorization=bce-auth-v1/e464e6f951124fdbb2410c590ef9ed2f/2024-01-25T12%3A56%3A15Z/-1/host/b54178fea9be115eafa2a8589aeadfcfaeba20d726f434f871741d4a6cb0c70d" file_data = requests.get(file_url).content file_path = "./test.pdf" # 待解析的文件路径 with open(file_path, "wb") as f: f.write(file_data) # 解析文档 msg = Message(file_path) parser = DocParser() parse_result = parser.run(msg, return_raw=True) # 对文档进行分段落,split_by_chunk需要return_raw=True splitter = DocSplitter( splitter_type="split_by_chunk", overlap=0) split_result = splitter(parse_result) # 每个段落抽取问答对,并返回结果 for doc_segment in split_result.content["paragraphs"]: qa_mining = QAPairMining(model="DeepSeek-V3.1") text = doc_segment.get("text", "") if text == "": logger.error("Text is null. break") break logger.info("Input: \n{}".format(text)) answer = qa_mining(Message(text)) logger.info("Output: \n{}".format(answer.content)) break # 样例代码只跑1个段落 ``` ## 更新记录和贡献 * 问答对挖掘能力 (2023-12) ================================================ FILE: docs/BasisModule/Components/llms/query_decomposition/README.md ================================================ # 复杂Query分解(QueryDecomposition) ## 简介 复杂Query分解(QueryDecomposition)可以将已经确定为复杂问题的原始问题拆解为一个个简单问题。广泛应用在知识问答场景。 ### 功能介绍 在知识问答领域中存在很多复杂问题需要处理,这些复杂问题通常需要进行问题分解并采用分治的方法处理。复杂Query分解组件尝试对已经判定为复杂问题的原始问题进行拆解,把复杂问题拆解为一个个简单问题。 ### 特色优势 复杂Query分解组件可以将复杂问题分解为不同层级的简单问题。这有助于更系统地分析和解决问题,提高答案的全面性。 ### 应用场景 广泛应用于知识问答场景 ## 基本用法 下面是复杂Query分解的代码示例: ```python import os import appbuilder # 请前往千帆AppBuilder官网创建密钥,流程详见:https://cloud.baidu.com/doc/AppBuilder/s/Olq6grrt6#1%E3%80%81%E5%88%9B%E5%BB%BA%E5%AF%86%E9%92%A5 os.environ["APPBUILDER_TOKEN"] = "..." query_decomposition = appbuilder.QueryDecomposition(model="DeepSeek-V3.1") msg = "吸塑包装盒在工业化生产和物流运输中分别有什么重要性?" msg = appbuilder.Message(msg) answer = query_decomposition(msg) print("Answer: \n{}".format(answer.content)) ``` ## 参数说明 ### 鉴权说明 使用组件之前,请首先申请并设置鉴权参数,可参考[组件使用流程](https://cloud.baidu.com/doc/AppBuilder/s/Olq6grrt6#1%E3%80%81%E5%88%9B%E5%BB%BA%E5%AF%86%E9%92%A5)。 ```python # 设置环境中的TOKEN,以下示例略 os.environ["APPBUILDER_TOKEN"] = "bce-YOURTOKEN" ``` ### 初始化参数 |参数名称 |参数类型 |是否必须 |描述 |示例值| |--------|--------|--------|----|------| |model |str |是 |模型名称,用于指定要使用的千帆模型|DeepSeek-V3.1| ### 调用参数 |参数名称 |参数类型 |是否必须 |描述 |示例值| |--------|--------|--------|----|------| |message |obj:`Message`|是 |输入消息,用于模型的主要输入内容。这是一个必需的参数| | |stream|bool|否 |指定是否以流式形式返回响应。默认为 False|False| |temperature|float|否 |模型配置的温度参数,用于调整模型的生成概率。取值范围为 0.0 到 1.0,其中较低的值使生成更确定性,较高的值使生成更多样性。默认值为 1e-10|1e-10| ### 响应参数 |参数名称 |参数类型 |描述 |示例值| |--------|--------|----|------| |Message |obj:`Message` |输出消息,包含模型运行后的输出| | ### 响应示例 ```text 1. 吸塑包装盒在工业化生产中有什么重要性? 2. 吸塑包装盒在物流运输中有什么重要性? ``` ### 错误码 无 ## 高级用法 你可以通过自定义调整参数来获得想要的结果,例如: ```python # 流式返回, 调整模型temperature参数 answer = query_decomposition(msg, stream=True, temperature=0.5) ``` ## 更新记录和贡献 * 复杂Query分解 (2024-01) ================================================ FILE: docs/BasisModule/Components/llms/query_rewrite/README.md ================================================ # 多轮改写 (QueryRewrite) ## 简介 多轮改写组件 (QueryRewrite) 是一个用于处理多轮对话和查询改写的组件。它主要用于理解和优化用户与机器人的交互过程,进行指代消解及省略补全。该组件支持不同的改写类型,可根据对话历史生成更准确的用户查询。 ### 功能介绍 多轮改写组件 (QueryRewrite) 据用户和机器人的聊天记录,改写用户当前query,利用大语言模型的理解及生成能力,进行指代消解及省略补全。 ### 特色优势 多轮改写组件 (QueryRewrite) ,基于百度自研的大语言模型文心一言,无需更多的prompt描述,即可根据对话历史生成更准确的用户查询。 ### 应用场景 多轮改写组件 (QueryRewrite) 可用于智能问答、对话式搜索等场景。 ## 基本用法 以下是一个简单的例子,展示如何快速开始使用 QueryRewrite 组件: ```python import os import appbuilder # 请前往千帆AppBuilder官网创建密钥,流程详见:https://cloud.baidu.com/doc/AppBuilder/s/Olq6grrt6#1%E3%80%81%E5%88%9B%E5%BB%BA%E5%AF%86%E9%92%A5 os.environ["APPBUILDER_TOKEN"] = '...' # 初始化并使用 QueryRewrite 组件 query_rewrite = appbuilder.QueryRewrite(model="DeepSeek-V3.1") answer = query_rewrite(appbuilder.Message(['我应该怎么办理护照?', '您可以查询官网或人工咨询', '我需要准备哪些材料?', '身份证、免冠照片一张以及填写完整的《中国公民因私出国(境)申请表》', '在哪里办']), rewrite_type="带机器人回复") print(answer) ``` ## 参数说明 ### 鉴权配置 使用组件之前,请首先申请并设置鉴权参数,可参考[组件使用流程](https://cloud.baidu.com/doc/AppBuilder/s/Olq6grrt6#1%E3%80%81%E5%88%9B%E5%BB%BA%E5%AF%86%E9%92%A5)。 ```python # 设置环境中的TOKEN,以下示例略 os.environ["APPBUILDER_TOKEN"] = "bce-YOURTOKEN" ``` ### 初始化参数 - `model`: 模型名称,用于指定要使用的千帆模型。 ### 调用参数 |参数名称 |参数类型 |是否必须 |描述 |示例值| |--------|--------|--------|----|------| |message |Message |是 |需要改写的文本,用于模型的主要输入内容,这是一个必需的参数。 |Message(content=['我应该怎么办理护照?', '您可以查询官网或人工咨询','我需要准备哪些材料?', '身份证、免冠照片一张以及填写完整的《中国公民因私出国(境)申请表》', '在哪里办']) | |rewrite_type |str |否 |改写类型选项,可选值为 '带机器人回复'(改写时参考user查询历史和assistant回复历史),'仅用户查询'(改写时参考user查询历史)。 默认是"带机器人回复" |"带机器人回复" | |stream |bool | 否 |指定是否以流式形式返回响应。默认为 False。 |False | |temperature |float | 否 |模型配置的温度参数,用于调整模型的生成概率。取值范围为 0.0 到 1.0,其中较低的值使生成更确定性,较高的值使生成更多样性。默认值为 1e-10。 |1e-10 | ### 响应参数 |参数名称 |参数类型 |描述 |示例值| |--------|--------|----|------| |result |Message |返回结果|Message(content="身份证在哪办")| ### 响应示例 ``` Message(name=msg, content="身份证在哪办", mtype=dict, extra={}) ``` ## 示例和案例研究 实际应用中,QueryRewrite 可用于多种场景,如信息检索、智能对话等。 ## 更新记录和贡献 当前版本:v2 (2023-12) ================================================ FILE: docs/BasisModule/Components/llms/similar_question/README.md ================================================ # 相似问生成(SimilarQuestion) ## 简介 相似问生成组件(SimilarQuestion)可以用于基于输入的问题,挖掘出与该问题相关的类似问题。广泛用于客服、问答等场景。 ### 功能介绍 基于输入的问题,挖掘出与该问题相关的类似问题。 ### 特色优势 相似问生成组件,可一次生成多个相似问题,准确率可达90%以上。 ### 应用场景 应用于客服、问答等场景 ## 基本用法 ### 快速开始 ```python import os import appbuilder # 请前往千帆AppBuilder官网创建密钥,流程详见:https://cloud.baidu.com/doc/AppBuilder/s/Olq6grrt6#1%E3%80%81%E5%88%9B%E5%BB%BA%E5%AF%86%E9%92%A5 os.environ["APPBUILDER_TOKEN"] = "..." similar_question = appbuilder.SimilarQuestion(model="DeepSeek-V3.1") msg = "我想吃冰淇淋,哪里的冰淇淋比较好吃?" msg = appbuilder.Message(msg) answer = similar_question(msg) print("Answer: \n{}".format(answer.content)) ``` ## 参数说明 ### 初始化参数 无 ### 调用参数 |参数名称 |参数类型 |是否必须 |描述 |示例值| |--------|--------|--------|----|------| | message | String |是 |输入消息,用于模型的主要输入内容。这是一个必需的参数。| `Message("我想吃冰淇淋,哪里的冰淇淋比较好吃?")` | | stream |bool|否 |指定是否以流式形式返回响应。默认为 False。| False | | temperature |float|否 |模型配置的温度参数,用于调整模型的生成概率。取值范围为 0.0 到 1.0,其中较低的值使生成更确定性,较高的值使生成更多样性。默认值为 1e-10。 | 1e-10 | ### 响应参数 |参数名称 |参数类型 |描述 |示例值| |--------|--------|----|------| | result | String | 返回结果 | "1. 哪里能品尝到美味的冰淇淋?\n2. 哪..." | ### 响应示例 ```text 1. 哪里能品尝到美味的冰淇淋? 2. 哪里能买到好吃的冰淇淋? 3. 哪里能品尝到正宗的冰淇淋? 4. 哪里能品尝到最新鲜的冰淇淋? 5. 哪里能买到口感最好的冰淇淋? 6. 哪里能品尝到最经典的冰淇淋? ``` ### 错误码 |错误码|描述| |------|---| ## 高级用法 ### 特殊场景示例 你可以根据特定的场景调整参数来获得更精确的结果,例如: ```python # 流式返回, 调整模型temperature参数 answer = similar_question(msg, stream=True, temperature=0.5) ``` ## 示例和案例研究 ### 示例 - **场景:** 用户提出问题 - **输入:** "我想吃冰淇淋,哪里的冰淇淋比较好吃?" - **输出:** 1. 请问哪里的冰淇淋最美味? 2. 在哪些地方可以品尝到最好的冰淇淋? ..... ## 更新记录和贡献 * 相似问生成能力 (2023-12) ================================================ FILE: docs/BasisModule/Components/llms/style_rewrite/README.md ================================================ # 风格转写 (StyleRewrite) ## 简介 风格转写组件(StyleRewrite) 可以基于生成式大模型对文本的风格进行改写。支持多种文本风格,包括营销、客服、直播、激励及教学话术。 ### 功能介绍 文本风格转写能够将一段文本转换成不同的风格(营销、客服、直播、激励及教学话术),同时保持原文的基本意义不变。基于大模型的文本理解与生成能力,根据用户指定的风格重新组织语言和表达方式。它不仅能识别和模仿不同的写作风格,还能在转换过程中保持文本的连贯性和逻辑性。 ### 特色优势 - 准确性与流畅性: 在转写时保持原文意义的准确传达,同时确保文本流畅自然。 - 风格多样性: 能够覆盖广泛的文本风格,满足不同场合的需求。 - 提高效率: 节省人工重新编写文本的时间。 ### 应用场景 不同的文本风格可以应用到以下不同的场景中: - 营销风格:该风格的转写能力可以根据商品的描述生成一段营销文案,生动地为用户介绍商品特点。 - 客服风格:针对客户关心的产品问题,用礼貌易懂的口语化文本进行回复,提升客户服务体验。 - 直播风格:在线直播平台的主播或内容创作者可以使用文本风格转写技术来优化其直播脚本,使其更吸引特定的观众群体。 - 激励风格:在激励演讲、团队管理或个人发展领域,文本风格转写可以帮助创建更有动力和启发性的内容。起到鼓舞人心的作用。 - 教学风格:可以帮助教师或教材作者生成互动感强、并且引人入胜的教学材料。 ## 基本用法 以下是一个简单的例子,展示如何快速开始使用 StyleRewrite 组件: ```python import os import appbuilder # 请前往千帆AppBuilder官网创建密钥,流程详见:https://cloud.baidu.com/doc/AppBuilder/s/Olq6grrt6#1%E3%80%81%E5%88%9B%E5%BB%BA%E5%AF%86%E9%92%A5 os.environ["APPBUILDER_TOKEN"] = "..." # 初始化并使用 StyleRewrite 组件 style_rewrite = appbuilder.StyleRewrite(model="DeepSeek-V3.1") answer = style_rewrite(appbuilder.Message("文心大模型发布新版"), style="激励话术") ``` ## 参数说明 ### 鉴权说明 使用组件之前,请首先申请并设置鉴权参数,可参考[组件使用流程](https://cloud.baidu.com/doc/AppBuilder/s/Olq6grrt6#1%E3%80%81%E5%88%9B%E5%BB%BA%E5%AF%86%E9%92%A5)。 ```python # 设置环境中的TOKEN,以下示例略 os.environ["APPBUILDER_TOKEN"] = "bce-YOURTOKEN" ``` ### 初始化参数 无 ### 调用参数 |参数名称 |参数类型 |是否必须 |描述 |示例值| |--------|--------|--------|----|------| |message |String |是 |需要改写的文本|文心大模型发布新版| |style|String|否 |想要转换的文本风格,默认为"营销话术",目前支持营销、客服、直播、激励及教学五种话术。|激励话术| |stream|bool|否 |指定是否以流式形式返回响应,默认为 False。|True| |temperature|float|否 |模型配置的温度参数,默认为 1e-10|1e-10| ### 响应参数 |参数名称 |参数类型 |描述 |示例值| |--------|--------|----|------| |result |String |返回结果|"文心NLP大模型平台再添新功绩!近日,文心NLP大模型平台成功发布新版,这标志着我们在这个领域又取得了新的里程碑。新版的文心NLP大模型平台在技术、功能和易用性等方面都有了显著的提升,为用户提供了更好的使用体验。"| ### 响应示例 ```json {"result": "文心NLP大模型平台再添新功绩!近日,文心NLP大模型平台成功发布新版,这标志着我们在这个领域又取得了新的里程碑。新版的文心NLP大模型平台在技术、功能和易用性等方面都有了显著的提升,为用户提供了更好的使用体验。"} ``` ### 错误码 |错误码|描述| |------|---| ## 高级用法 目前该模块仅提供基础的文本风格转写功能。 ## 更新记录和贡献 * 当前版本:v1 ================================================ FILE: docs/BasisModule/Components/llms/style_writing/README.md ================================================ # 风格写作(StyleWriting) ## 简介 风格写作组件(StyleWriting)是一款基于生成式大模型进行文本创作的工具,支持多种风格,包括B站、小红书等,适用于编写文案、广告等多种场景。 ### 功能介绍 风格写作组件(StyleWriting)根据用户的输入内容和风格要求,利用大语言模型的生成能力,自动生成符合特定风格的文案。 ### 特色优势 风格写作组件(StyleWriting),基于百度自研的大语言模型文新一言,提供内置的风格生成能力,无需更多的prompt描述,即可生成对应风格的文案。 ### 应用场景 风格写作组件(StyleWriting)可用于特定平台的文案生成分发营销场景。 ## 基本用法 为了快速开始使用风格写作组件,您可以参考以下步骤: ```python import appbuilder import os # 请前往千帆AppBuilder官网创建密钥,流程详见:https://cloud.baidu.com/doc/AppBuilder/s/Olq6grrt6#1%E3%80%81%E5%88%9B%E5%BB%BA%E5%AF%86%E9%92%A5 os.environ["APPBUILDER_TOKEN"] = "..." model = "DeepSeek-V3.1" style_writing = appbuilder.StyleWriting(model) query = "帮我写一篇关于人体工学椅的文案" style = "小红书" length = 100 msg = appbuilder.Message(query) answer = style_writing(message=msg, style_query=style, length=length) print(answer) ``` ## 参数说明 ### 鉴权说明 使用组件之前,请首先申请并设置鉴权参数,可参考[组件使用流程](https://cloud.baidu.com/doc/AppBuilder/s/Olq6grrt6#1%E3%80%81%E5%88%9B%E5%BB%BA%E5%AF%86%E9%92%A5)。 ```python # 设置环境中的TOKEN,以下示例略 os.environ["APPBUILDER_TOKEN"] = "bce-YOURTOKEN" ``` ### 初始化参数 - `model`: 模型名称,用于指定要使用的千帆模型。 ### 调用参数 |参数名称 |参数类型 |是否必须 |描述 |示例值| |--------|--------|--------|----|------| |message |Message |是 |输入的消息,用于模型的主要输入内容,这是一个必需的参数。 |Message(content="帮我生成一个介绍保温杯的话术") | |style_query |str |否 |定义生成文案的格式,包括"通用"、"B站"、"小红书",默认为"通用" |"通用" | |length |int |否 |定义生成文案的长度,可选 '短' (100), '中' (300), '长' (600), 默认100 |100 | |stream |bool | 否 |指定是否以流式形式返回响应。默认为 False。 |False | |temperature |float | 否 |模型配置的温度参数,用于调整模型的生成概率。取值范围为 0.0 到 1.0,其中较低的值使生成更确定性,较高的值使生成更多样性。默认值为 1e-10。 |0.7 | ### 响应参数 |参数名称 |参数类型 |描述 |示例值| |--------|--------|----|------| |result |Message |返回结果|Message(content="大家好,我给你们介绍一款家里和办公室都要备上的保温杯。...")| ### 响应示例 ``` Message(name=msg, content=大家好,我给你们介绍一款家里和办公室都要备上的保温杯。我平常上班的时候都会装上一杯热开水,但用普通保温杯装上一会就凉了,所以我赶紧在网上淘了一个好货。它是双层设计,内层是不锈钢材质,外层是玻璃材质,非常贴心,冷热都能装。装上热水,保温效果非常出色,到晚上还是热的。这个保温杯的外观也非常漂亮,采用优质不锈钢材质,耐磨、易清洗。同时,它还非常轻便,可以轻松放入口袋、背包中。有了这个保温杯后,我再也不用担心喝水问题了。无论是在家里、办公室还是户外活动,它都能随时随地为你提供热水。而且,它还非常安全、健康,采用了优质的保温材料和先进的生产工艺。无论男女老少都可以使用这款保温杯哦。快来购买吧。", mtype=dict, extra={}) ``` ## 高级用法 使用风格写作组件进行更复杂的文本创作,例如调整不同的风格和长度参数来适应特定的写作场景。 ## 更新记录和贡献 - 初始版本发布(2023-10) ================================================ FILE: docs/BasisModule/Components/llms/tag_extraction/README.md ================================================ # 标签抽取(TagExtraction) ## 简介 标签抽取组件(TagExtraction)是一款高效的标签抽取组件,基于生成式大模型,专门用于从文本中提取关键标签。它适用于各种文本分析场景,如内容分类、关键词提取等。 ### 功能介绍 标签抽取组件(TagExtraction)专门设计用于从各类文本中高效地提取关键标签。此组件利用先进的生成式大模型,可以准确识别和提取文本中的重要信息,如关键词、短语或主题。它不仅能快速分析大量文本数据,还能精准识别文本的核心内容,支持用户快速了解文本的主要信息和结构 ### 特色优势 - 高效准确:基于先进的生成式大模型,提供高效且准确的标签提取功能。 - 适用广泛:能够处理不同类型和格式的文本数据,适用于多种文本分析场景。 - 格式友好:输出格式采用规范化编号输出,后处理时方便快捷。 ### 应用场景 标签抽取组件可以广泛应用于多种场景: - 内容分类:快速为文章或文档分类,提高信息管理和检索效率。 - 关键词提取:从文本中提取关键词,帮助用户快速了解文本主题和内容。 - 数据分析:在大数据分析中,可以用于预处理,提取有价值的信息。 - 搜索引擎优化:帮助网站或博客提取有效标签,改善其在搜索引擎中的可见度。 ## 基本用法 要开始使用 `TagExtraction`,首先需要设置环境变量 `APPBUILDER_TOKEN`,然后创建 `TagExtraction` 实例并传递文本消息。 ```python import os import appbuilder # 请前往千帆AppBuilder官网创建密钥,流程详见:https://cloud.baidu.com/doc/AppBuilder/s/Olq6grrt6#1%E3%80%81%E5%88%9B%E5%BB%BA%E5%AF%86%E9%92%A5 os.environ["APPBUILDER_TOKEN"] = '...' tag_extraction = appbuilder.TagExtraction(model="DeepSeek-V3.1") result = tag_extraction(appbuilder.Message("从这段文本中抽取关键标签")) ``` 这个例子展示了如何实例化 `TagExtraction` 组件并使用一个文本消息进行标签抽取。 ## 参数说明 ### 鉴权说明 使用组件之前,请首先申请并设置鉴权参数,可参考[组件使用流程](https://cloud.baidu.com/doc/AppBuilder/s/Olq6grrt6#1%E3%80%81%E5%88%9B%E5%BB%BA%E5%AF%86%E9%92%A5)。 ```python # 设置环境中的TOKEN,以下示例略 os.environ["APPBUILDER_TOKEN"] = "bce-YOURTOKEN" ``` ### 初始化参数 无 ### 调用参数 |参数名称 |参数类型 |是否必须 |描述 |示例值| |--------|--------|--------|----|------| |message |String |是 |需要抽取标签的文本|从这段文本中抽取关键标签| |stream|bool|否 |指定是否以流式形式返回响应,默认为 False。|True| |temperature|float|否 |模型配置的温度参数,用于调整模型的生成概率。取值范围为 0.0 到 1.0,其中较低的值使生成更确定性,较高的值使生成更多样性。默认值为 1e-10。|1e-10| ### 响应参数 |参数名称 |参数类型 |描述 |示例值| |--------|--------|----|------| |result |Message |返回结果|对象,包含模型运行后的输出消息。| ### 响应示例 ```json {"result": "1.5G 2.云计算 3.人工智能 4.数字经济 5.数据中心 6.新型基础设施 7.政策优化 8.产业发展 9.国家重视 10.快速增长"} ``` ## 高级用法 高级用法可以包括自定义模型参数或使用不同的模型源。例如,可以通过指定不同的 `model` 来使用特定于域的模型进行标签抽取。 ```python tag_extraction = appbuilder.TagExtraction(model="custom-model") result = tag_extraction(appbuilder.Message("自定义模型抽取的标签")) ``` ## 示例和案例研究 在实际应用中,`TagExtraction` 可以用于新闻文章、社交媒体帖子或其他任何文本内容的关键标签提取,帮助内容创建者或营销分析师快速了解主要主题和趋势。 ================================================ FILE: docs/BasisModule/Components/matching/README.md ================================================ # 语义匹配(Matching) ## 简介 语义匹配组件(Matching)可以计算query与文本列表之间的相似度关系,并根据其进行排序。 ### 功能介绍 根据query与文本列表之间的相似度关系,并根据其进行排序。 ### 特色优势 基于百度文心大模型技术的文本表示模型,学习数据的内在特征,使得排序效果相较于bm25等排序算法,可以更好地处理相似问和同义、近义句子之间的偏序关系。 ### 应用场景 1. 语义排序 ## 基本用法 ### 下面是基于query和文本之间的相似度进行匹配排序的代码示例 ```python import os import appbuilder # 请前往千帆AppBuilder官网创建密钥,流程详见:https://cloud.baidu.com/doc/AppBuilder/s/Olq6grrt6#1%E3%80%81%E5%88%9B%E5%BB%BA%E5%AF%86%E9%92%A5 os.environ["APPBUILDER_TOKEN"] = '...' # 初始化所需要的组件 embedding = appbuilder.Embedding() matching = appbuilder.Matching(embedding) # 定义query和文本列表 query = appbuilder.Message("你好") contexts = appbuilder.Message(["世界", "你好"]) contexts_matched = matching(query, contexts) print(contexts_matched.content) ``` ``` ['你好', '世界'] ``` ## 参数说明 ### 鉴权说明 使用组件之前,请首先申请并设置鉴权参数,可参考[组件使用流程](https://cloud.baidu.com/doc/AppBuilder/s/Olq6grrt6#1%E3%80%81%E5%88%9B%E5%BB%BA%E5%AF%86%E9%92%A5)。 ```python # 设置环境中的TOKEN,以下示例略 os.environ["APPBUILDER_TOKEN"] = "bce-YOURTOKEN" ``` ### 初始化参数 | 参数名称 | 参数类型 | 是否必须 | 描述 | 示例值 | | ---------- | ----------- | -------- | ------------------------------------------------------------- | --------------- | | embedding | Embedding | 可选 | 一个类型为Embedding的Component,用于初始化 Matching 的向量计算功能。底座模型当前仅支持 embedding-v1 作为可选值。若不指定,默认值为 embedding-v1 。 | appbuilder.Embedding() | ### 调用参数 | 参数名称 | 参数类型 | 是否必须 | 描述 | 示例值 | | --------- | ----------- | -------- | ------------------------------------------------------------ | ---------------------------------- | | query | 字符串 | 必须 | 一个类型为 string 的句子,用于输入。该句子的长度不能超过384个字符,通常为用户输入的问题。 | "如何提高工作效率?" | | contexts | 字符串列表 | 必须 | 一个类型为 List[string] 的句子数组。数组中的每个元素都是一个句子,且每个句子的长度不能超过384个字符。这些句子通常为与问题相关的文本候选集。 | ["时间管理技巧", "提高专注力的方法"] | | return_score | 布尔 | 可选 | 默认为False, 仅返回排序后的字符串列表;当设置为True时,返回匹配分数和字符串的二元组列表 | ### 响应示例 默认为排完序后的字符串列表 ``` ["时间管理技巧", "提高专注力的方法"] ``` 当设置`return_score = True`时,二元组的第一个值为相似度分数,第二个值为字符串 ``` [(0.9999999852985002, '你好'), (0.18920520439845268, '世界')] ``` ### 错误码 无 ## 更新记录和贡献 * 语义匹配 (2023-12) ================================================ FILE: docs/BasisModule/Components/mix_card_ocr/README.md ================================================ # 身份证混贴识别(MixCardOCR) ## 简介 身份证混贴识别(MixCardOCR),身份证混贴识别支持自动检测与识别身份证正反面在同一张图片上的场景,一次识别图片中身份证正反面所有字段。 ### 功能介绍 支持对二代居民身份证正反面所有8个字段进行结构化识别,包括姓名、性别、民族、出生日期、住址、身份证号、签发机关、有效期限,识别准确率超过99%;同时支持身份证正面头像检测,并返回头像切片的base64编码及位置信息。 ### 特色优势 同时,支持对用户上传的身份证图片进行图像风险和质量检测,可识别图片是否为复印件或临时身份证,是否被翻拍或编辑,是否存在正反颠倒、模糊、欠曝、过曝等质量问题。 ### 应用场景 身份证混贴识别支持自动检测与识别身份证正反面在同一张图片上的场景,一次识别图片中身份证正反面所有字段。 ## 基本用法 下面是身份证混贴识别的代码示例: 示例图片为:![示例图片](https://bj.bcebos.com/v1/appbuilder/test_mix_card_ocr.jpeg?authorization=bce-auth-v1%2FALTAKGa8m4qCUasgoljdEDAzLm%2F2024-01-24T06%3A18%3A11Z%2F-1%2Fhost%2F695b8041c1ded194b9e80dbe1865e4393da5a3515e90d72d81ef18296bd29598) ```python import os import requests import appbuilder # 请前往千帆AppBuilder官网创建密钥,流程详见:https://cloud.baidu.com/doc/AppBuilder/s/Olq6grrt6#1%E3%80%81%E5%88%9B%E5%BB%BA%E5%AF%86%E9%92%A5 os.environ["APPBUILDER_TOKEN"] = "..." image_url= "https://bj.bcebos.com/v1/appbuilder/test_mix_card_ocr.jpeg?authorization=bce-auth-v1%2FALTAKGa8m4qCUasgoljdEDAzLm%2F2024-01-24T06%3A18%3A11Z%2F-1%2Fhost%2F695b8041c1ded194b9e80dbe1865e4393da5a3515e90d72d81ef18296bd29598" # 从BOS存储读取样例文件 raw_image = requests.get(image_url).content inp = appbuilder.Message(content={"raw_image": raw_image}) # inp = Message(content={"url": image_url}) # 运行身份证混贴识别OCR mix_card_ocr = appbuilder.MixCardOCR() out = mix_card_ocr.run(inp) # 打印识别结果 print(out.content) # {'front': {'fields': [{'key': '出生', 'value': '19920225', 'position': {'left': 620, 'top': 218, 'width': 239, 'height': 30}}, {'key': '性别', 'value': '女', 'position': {'left': 616, 'top': 164, 'width': 25, 'height': 30}}, {'key': '民族', 'value': '汉', 'position': {'left': 766, 'top': 164, 'width': 29, 'height': 30}}, {'key': '姓名', 'value': '姚佳', 'position': {'left': 621, 'top': 102, 'width': 84, 'height': 35}}, {'key': '公民身份号码', 'value': '110103199202250229', 'position': {'left': 733, 'top': 417, 'width': 399, 'height': 36}}, {'key': '住址', 'value': '北京市海淀区仙秀园555号', 'position': {'left': 618, 'top': 277, 'width': 253, 'height': 67}}], 'position': {'left': 483, 'top': 42, 'width': 737, 'height': 464}}, 'back': {'fields': [{'key': '签发日期', 'value': '20150413', 'position': {'left': 789, 'top': 946, 'width': 139, 'height': 34}}, {'key': '签发机关', 'value': '北京市公安局海淀分局', 'position': {'left': 787, 'top': 883, 'width': 275, 'height': 35}}, {'key': '失效日期', 'value': '20350413', 'position': {'left': 946, 'top': 945, 'width': 144, 'height': 34}}], 'position': {'left': 473, 'top': 537, 'width': 749, 'height': 480}}, 'direction': 0} ``` ## 参数说明 ### 鉴权说明 使用组件之前,请首先申请并设置鉴权参数,可参考[组件使用流程](https://cloud.baidu.com/doc/AppBuilder/s/Olq6grrt6#1%E3%80%81%E5%88%9B%E5%BB%BA%E5%AF%86%E9%92%A5)。 ```python import os os.environ["APPBUILDER_TOKEN"] = "..." ``` ### 初始化参数 无 ### 调用参数 | 参数名称 | 参数类型 | 是否必须 | 描述 |示例值| |------------|--------|------|-----------------------------|---| | message | String | 是 | 输入的消息,用于模型的主要输入内容。这是一个必需的参数 || | +content | Dict | 是 | 消息内容 || | +raw_image | String | 否 | 原始图片字节流 || | +url | String | 否 | 图片下载链接地址 || |timeout| Float | 否 | HTTP超时时间,单位:秒 |1|| |retry|Integer| 否 | HTTP重试次数 |3|| ### 响应参数 | 参数名称 | 参数类型 | 描述 | 示例值 | |------------|--------|---------------------|----------------------------------------------------| | front | object | 身份证正面信息 | | | +fields | list | 字段信息 | | | ++key | str | 字段名 | | | ++value | str | 字段值 | | | ++position | object | 字段坐标,结构同下position | | | +position | object | 身份证正面坐标 | | | ++left | int | 表示定位位置的长方形左上顶点的水平坐标 | | | ++top | int | 表示定位位置的长方形左上顶点的垂直坐标 | | | ++width | int | 表示定位位置的长方形的宽度 | | | ++height | int | 表示定位位置的长方形的高度 | | | back | object | 身份证反面信息,结构同front | | | direction | int | 图像旋转角度 | 图像旋转角度,0(正向),- 1(逆时针90度),- 2(逆时针180度),- 3(逆时针270度) | ### 响应示例 ```json { "front": { "fields": [{ "key": "出生", "value": "19920225", "position": { "left": 620, "top": 218, "width": 239, "height": 30 } }, { "key": "性别", "value": "女", "position": { "left": 616, "top": 164, "width": 25, "height": 30 } }, { "key": "民族", "value": "汉", "position": { "left": 766, "top": 164, "width": 29, "height": 30 } }, { "key": "姓名", "value": "姚佳", "position": { "left": 621, "top": 102, "width": 84, "height": 35 } }, { "key": "公民身份号码", "value": "110103199202250229", "position": { "left": 733, "top": 417, "width": 399, "height": 36 } }, { "key": "住址", "value": "北京市海淀区仙秀园555号", "position": { "left": 618, "top": 277, "width": 253, "height": 67 } } ], "position": { "left": 483, "top": 42, "width": 737, "height": 464 } }, "back": { "fields": [{ "key": "签发日期", "value": "20150413", "position": { "left": 789, "top": 946, "width": 139, "height": 34 } }, { "key": "签发机关", "value": "北京市公安局海淀分局", "position": { "left": 787, "top": 883, "width": 275, "height": 35 } }, { "key": "失效日期", "value": "20350413", "position": { "left": 946, "top": 945, "width": 144, "height": 34 } } ], "position": { "left": 473, "top": 537, "width": 749, "height": 480 } }, "direction": 0 } ``` ### 错误码 |错误码|描述| |------|---| ## 高级用法 目前该模块仅提供基础的身份证混贴识别。 ## 更新记录和贡献 * 身份证混贴识别 (2024-01) ================================================ FILE: docs/BasisModule/Components/object_recognize/README.md ================================================ # 通用物体和场景识别-高级版(ObjectRecognition) ## 简介 通用物体和场景识别组件(ObjectRecognition)可以识别超过10万类常见物体和场景,接口返回大类及细分类的名称。广泛适用于图像或视频内容分析、拍照识图等业务场景。 ### 功能介绍 * 识别物体或场景名称 识别动物、植物、商品、建筑、风景、动漫、食材、公众人物等10万个常见物体及场景,接口返回大类及细分类的名称结果; ### 特色优势 * 可识别超过10万类常见物体和场景,接口返回大类及细分类的名称,并支持获取识别结果对应的百科信息; ### 应用场景 可以识别超过10万类常见物体和场景,广泛适用于图像或视频内容分析、拍照识图等业务场景 ## 基本用法 示例图片为: ![示例图片](https://bj.bcebos.com/v1/appbuilder/object_recognize_test.png?authorization=bce-auth-v1%2FALTAKGa8m4qCUasgoljdEDAzLm%2F2024-01-11T11%3A00%3A19Z%2F-1%2Fhost%2F2c31bf29205f61e58df661dc80af31a1dc1ba1de0a8f072bc5a87102bd32f9e3) ```python import os import appbuilder import requests # 请前往千帆AppBuilder官网创建密钥,流程详见:https://cloud.baidu.com/doc/AppBuilder/s/Olq6grrt6#1%E3%80%81%E5%88%9B%E5%BB%BA%E5%AF%86%E9%92%A5 os.environ["APPBUILDER_TOKEN"] = '...' # 从BOS读取样例图片 image_url = "https://bj.bcebos.com/v1/appbuilder/object_recognize_test.png?"\ "authorization=bce-auth-v1%2FALTAKGa8m4qCUasgoljdEDAzLm%2F2024-01-"\ "11T11%3A00%3A19Z%2F-1%2Fhost%2F2c31bf29205f61e58df661dc80af31a1dc"\ "1ba1de0a8f072bc5a87102bd32f9e3" raw_image = requests.get(image_url).content # 创建物体识别组件实例 object_recognition = appbuilder.ObjectRecognition() # 执行识别操作并获取结果 out = object_recognition.run(appbuilder.Message(content={"raw_image": raw_image})) print(out.content) # {'result': [{'keyword': '苹果', 'score': 0.961247, 'root': '植物-蔷薇科'}, {'keyword': '姬娜果', 'score': 0.740838, 'root': '植物-其它'}, {'keyword': '梨子', 'score': 0.392218, 'root': '商品-水果'}, {'keyword': '车厘子', 'score': 0.193986, 'root': '植物-其它'}, {'keyword': '石榴', 'score': 0.000239, 'root': '植物-千屈菜科'}]} ``` ## 参数说明 ### 鉴权说明 使用组件之前,请首先申请并设置鉴权参数,可参考[组件使用流程](https://cloud.baidu.com/doc/AppBuilder/s/Olq6grrt6#1%E3%80%81%E5%88%9B%E5%BB%BA%E5%AF%86%E9%92%A5)。 ```python # 设置环境中的TOKEN,以下示例略 os.environ["APPBUILDER_TOKEN"] = "bce-YOURTOKEN" ``` ### 初始化参数 无 ### 调用参数 (以表格形式展示) | 参数名称 | 参数类型 | 是否必须 | 描述 | 示例值 | |---------|---------|------|-----------------------------|------------------------------------------------| | message | String | 是 | 输入的消息,用于模型的主要输入内容。这是一个必需的参数 | Message(content={"raw_image": b"待识别的图片字节流数据"}) | |timeout| Float | 否 | HTTP超时时间,单位:秒 |1|| | retry | Integer | 否 | HTTP重试次数 | 3 | ### 响应参数 | 参数名称 | 参数类型 | 描述 | 示例值 | |----------|---------|-------------|-----------------------------------------------------| | result | Array[] | 返回结果 | [{"keyword":"苹果","score":0.961247,"root":"植物-蔷薇科"}] | | +keyword | String | 图片中的物体或场景名称 | "苹果" | | +score | Float | 置信度 | 0.961247 | | +root | String | 识别结果的上层标签 | "植物-蔷薇科" | ### 响应示例 ```json { "result":[ { "keyword":"苹果", "score":0.961247, "root":"植物-蔷薇科" }, { "keyword":"姬娜果", "score":0.740838, "root":"植物-其它" }, { "keyword":"梨子", "score":0.392218, "root":"商品-水果" }, { "keyword":"车厘子", "score":0.193986, "root":"植物-其它" }, { "keyword":"石榴", "score":0.000239, "root":"植物-千屈菜科" } ] } ``` ### 错误码 | 错误码 | 描述 | |-----|----| ## 高级用法 目前该模块仅提供基础通用物体与场景识别功能。 ## 更新记录和贡献 * 通用物体及场景识别 (2023-12-08) ================================================ FILE: docs/BasisModule/Components/plant_recognize/README.md ================================================ # 植物识别(PlantRecognition) ## 简介 植物识别(PlantRecognition),即对于输入的一张图片(可正常解码,且长宽比较合适),输出植物识别结果。 ### 功能介绍 可识别超过2万种常见植物和近8千种花卉,接口返回植物的名称,并支持获取识别结果对应的百科信息 ### 特色优势 还可使用EasyDL定制训练平台,定制识别植物种类 ### 应用场景 适用于拍照识图、幼教科普、图像内容分析等场景 ## 基本用法 下面是植物识别的代码示例: 示例图片为 ![示例图片](https://bj.bcebos.com/v1/appbuilder/palnt_recognize_test.jpg?authorization=bce-auth-v1%2FALTAKGa8m4qCUasgoljdEDAzLm%2F2024-01-23T09%3A51%3A03Z%2F-1%2Fhost%2Faa2217067f78f0236c8262cdd89a4b4f4b2188d971ca547c53d01742af4a2cbe) ```python import os import requests import appbuilder # 请前往千帆AppBuilder官网创建密钥,流程详见:https://cloud.baidu.com/doc/AppBuilder/s/Olq6grrt6#1%E3%80%81%E5%88%9B%E5%BB%BA%E5%AF%86%E9%92%A5 os.environ["APPBUILDER_TOKEN"] = "..." image_url = "https://bj.bcebos.com/v1/appbuilder/palnt_recognize_test.jpg?authorization=bce-auth-v1%2FALTAKGa8m4qCUasgoljdEDAzLm%2F2024-01-23T09%3A51%3A03Z%2F-1%2Fhost%2Faa2217067f78f0236c8262cdd89a4b4f4b2188d971ca547c53d01742af4a2cbe" # 从BOS存储读取样例文件 raw_image = requests.get(image_url).content inp = appbuilder.Message(content={"raw_image": raw_image}) # inp = Message(content={"url": image_url}) # 运行植物识别 plant_recognize = appbuilder.PlantRecognition() out = plant_recognize.run(inp) # 打印识别结果 print(out.content) # {'plant_score_list': [{'name': '榕树', 'score': 0.4230029582977295}, {'name': '榆树', 'score': 0.1273619383573532}, {'name': '美国榆', 'score': 0.12065108865499496}, {'name': '白蜡树', 'score': 0.11650644987821579}, {'name': '雨树', 'score': 0.045340824872255325}]} ``` ## 参数说明 ### 鉴权说明 使用组件之前,请首先申请并设置鉴权参数,可参考[组件使用流程](https://cloud.baidu.com/doc/AppBuilder/s/Olq6grrt6#1%E3%80%81%E5%88%9B%E5%BB%BA%E5%AF%86%E9%92%A5)。 ```python import os os.environ["APPBUILDER_TOKEN"] = "..." ``` ### 初始化参数 无 ### 调用参数 | 参数名称 | 参数类型 | 是否必须 | 描述 |示例值| |------------|--------|------|-----------------------------|---| | message | String | 是 | 输入的消息,用于模型的主要输入内容。这是一个必需的参数 || | +content | Dict | 是 | 消息内容 || | +raw_image | String | 否 | 原始图片字节流 || | +url | String | 否 | 图片下载链接地址 || |timeout| Float | 否 | HTTP超时时间,单位:秒 |1|| |retry|Integer| 否 | HTTP重试次数 |3|| ### 响应参数 | 参数名称 | 参数类型 | 描述 | 示例值 | |------------------|--------|--------|--------------------------------------------------| | plant_score_list | List | 植物识别列表 | | | name | String | 植物名 | | | score | Float | 植物识别打分 | | ### 响应示例 ```json { "plant_score_list": [ { "name": "榕树", "score": 0.4230029582977295 }, { "name": "榆树", "score": 0.1273619383573532 }, { "name": "美国榆", "score": 0.1206519496 }, { "name": "白蜡树", "score": 0.11650644987821579 }, { "name": "雨树", "score": 0.045340824872255325 } ] } ``` ### 错误码 |错误码|描述| |------|---| ## 高级用法 目前该模块仅提供基础的植物识别。 ## 更新记录和贡献 * 植物识别 (2024-01) ================================================ FILE: docs/BasisModule/Components/ppt_generation_from_file/README.md ================================================ # 文件生成PPT(PPTGenerationFromFile) ## 简介 文件生成PPT组件(PPTGenerationFromFile)可以根据上传的文件(支持**中英文**)生成PPT。 ### 功能介绍 根据上传的文件(支持**中英文**)生成PPT。 ### 特色优势 可根据文件(支持**中英文**)生成高质量PPT。 ### 应用场景 PPT生成。 ## 基本用法 ### 快速开始 ```python import os import appbuilder # 请前往千帆AppBuilder官网创建密钥,流程详见:https://cloud.baidu.com/doc/AppBuilder/s/Olq6grrt6#1%E3%80%81%E5%88%9B%E5%BB%BA%E5%AF%86%E9%92%A5 os.environ['APPBUILDER_TOKEN'] = '...' ppt_generator = appbuilder.PPTGenerationFromFile() user_input = { 'file_url':'http://image.yoojober.com/users/chatppt/temp/2024-06/6672a92c87e6f.doc', 'user_name':'百度千帆AppBuilder' } result = ppt_generator(appbuilder.Message(user_input)) print(result.content) ``` ## 参数说明 ### 鉴权说明 使用组件之前,请首先申请并设置鉴权参数,可参考[组件使用流程](https://cloud.baidu.com/doc/AppBuilder/s/Olq6grrt6#1%E3%80%81%E5%88%9B%E5%BB%BA%E5%AF%86%E9%92%A5)。 ```python # 设置环境中的TOKEN,以下示例略 os.environ['APPBUILDER_TOKEN'] = 'bce-YOURTOKEN' ``` ### 初始化参数 | 参数名称 | 参数类型 | 是否必须 | 描述 | 示例值 | | ------- | ------- | -------- | -------- | -------- | | `secret_key` | str | 否 | 用户鉴权token,默认从环境变量中获取: `os.getenv("APPBUILDER_TOKEN", "")` | bce-v3/XXX | | `gateway` | str | 否 | 后端网关服务地址,默认从环境变量中获取: `os.getenv("GATEWAY_URL", "")` | https://appbuilder.baidu.com | | `lazy_certification` | bool | 否 | 延迟认证,为True时在第一次运行时认证。默认为False。 | False | ### 调用参数 | 参数名称 | 参数类型 | 是否必须 | 描述 | 示例值 | | ------- | ------- | -------- | -------- | -------- | | `message` | obj | 是 | 输入消息,用于模型的主要输入内容。 | Message(content=input_data) | | `poll_request_times` | int | 否 | 轮询请求结果次数。默认为60。 | 60 | | `poll_request_interval` | int | 否 | 轮询请求的间隔时间(秒)。默认为5。 | 5 | 其中message包含的input_data包括以下参数: | 参数名称 | 参数类型 | 是否必须 | 描述 | 示例值 | | ------- | ------- | -------- | -------- | -------- | | `file_url` | str | 是 | 文件链接。 | http://image.yoojober.com/users/chatppt/temp/2024-06/6672a92c87e6f.doc | | `user_name` | str | 否 | 作者名。 | 百度千帆AppBuilder | ### 响应参数 | 参数名称 | 参数类型 | 描述 | 示例值 | | ------- | ------- | -------- | -------- | | `result` | obj | 模型运行后的输出结果,包含PPT下载链接。 | Message(content='...') | ### 响应示例 ``` https://download.yoojober.com/chatppt_business/2024-07/d1a1ab518ebcfbba7908a6734fa11d13.pptx?e=1721964933&token=8_2qFlGEVQZPpFvHdGR6gg2t9A9QZfWT9wwTl92s:9bs8LWV1SQLJNJoJgtd-sLF-CTw= ``` ## 高级用法 ## 更新记录和贡献 ### 2024.8.1 #### [Added] - 增加文件生成PPT组件。 - 增加文件生成PPT组件单元测试。 ================================================ FILE: docs/BasisModule/Components/ppt_generation_from_instruction/README.md ================================================ # 指令生成PPT(PPTGenerationFromInstruction) ## 简介 指令生成PPT组件(PPTGenerationFromInstruction)可以基于指令或者自定义信息生成PPT。 ### 功能介绍 基于指令或者自定义信息生成PPT。 ### 特色优势 - 可生成高质量PPT。 - 支持传入自定义信息生成PPT。 - 生成PPT复杂度可控。 ### 应用场景 PPT生成。 ## 基本用法 ### 快速开始 ```python import os import appbuilder # 请前往千帆AppBuilder官网创建密钥,流程详见:https://cloud.baidu.com/doc/AppBuilder/s/Olq6grrt6#1%E3%80%81%E5%88%9B%E5%BB%BA%E5%AF%86%E9%92%A5 os.environ['APPBUILDER_TOKEN'] = '...' ppt_generator = appbuilder.PPTGenerationFromInstruction() user_input = { 'text': '生成一个介绍北京的PPT。', 'custom_data': {}, 'complex': 1, 'user_name': '百度千帆AppBuilder' } result = ppt_generator(appbuilder.Message(user_input)) print(result.content) ``` ## 参数说明 ### 鉴权说明 使用组件之前,请首先申请并设置鉴权参数,可参考[组件使用流程](https://cloud.baidu.com/doc/AppBuilder/s/Olq6grrt6#1%E3%80%81%E5%88%9B%E5%BB%BA%E5%AF%86%E9%92%A5)。 ```python # 设置环境中的TOKEN,以下示例略 os.environ['APPBUILDER_TOKEN'] = 'bce-YOURTOKEN' ``` ### 初始化参数 | 参数名称 | 参数类型 | 是否必须 | 描述 | 示例值 | | ------- | ------- | -------- | -------- | -------- | | `secret_key` | str | 否 | 用户鉴权token,默认从环境变量中获取: `os.getenv("APPBUILDER_TOKEN", "")` | bce-v3/XXX | | `gateway` | str | 否 | 后端网关服务地址,默认从环境变量中获取: `os.getenv("GATEWAY_URL", "")` | https://appbuilder.baidu.com | | `lazy_certification` | bool | 否 | 延迟认证,为True时在第一次运行时认证。默认为False。 | False | ### 调用参数 | 参数名称 | 参数类型 | 是否必须 | 描述 | 示例值 | | ------- | ------- | -------- | -------- | -------- | | `message` | obj | 是 | 输入消息,用于模型的主要输入内容。 | Message(content=input_data) | | `poll_request_times` | int | 否 | 轮询请求结果次数。默认为60。 | 60 | | `poll_request_interval` | int | 否 | 轮询请求的间隔时间(秒)。默认为5。 | 5 | 其中message包含的input_data包括以下参数: | 参数名称 | 参数类型 | 是否必须 | 描述 | 示例值 | | ------- | ------- | -------- | -------- | -------- | | `text` | str | 是 | 请求生成PPT的query。可为空字符串"",与custom_data有一个参数不为空即可。 | 请你生成一个介绍北京的PPT。 | | `custom_data` | obj | 是 | 自定义参数,可指定标题、副标题、作者、结构等信息。可为空字典{},与text有一个参数不为空即可。 | `{"title": "标题", "sub_title": "副标题", "author": "作者", "catalogs": [{"catalog": "一级大纲1", "sub_catalog": ["一级大纲1-二级大纲1"]}, {"catalog": "一级大纲2", "sub_catalog": ["一级大纲2-二级大纲1"]}], "contents": [{"catalog_index": 0, "sub_catalog_index": 0, "content": ["一级大纲1-二级大纲1-内容1", "一级大纲1-二级大纲1-内容2"]}, {"catalog_index": 1, "sub_catalog_index": 0, "content": [{"key": "一级大纲2-二级大纲1-小标题1", "value": "一级大纲2-二级大纲1-子内容1"}, {"key": "一级大纲2-二级大纲1-小标题2", "value": "一级大纲2-二级大纲1-子内容2"}, {"key": "一级大纲2-二级大纲1-小标题3", "value": "一级大纲2-二级大纲1-子内容3"}], "picture": ["https://image.yoojober.com/chatppt_business/2024-02/000114cd07b809cb8c6bb22674e814da.png"]}]}` | | `complex` | integer | 否 | PPT复杂度,可选:1、2、3,其中1最简单、3最复杂。 | 1 | | `font_name` | str | 否 | PPT字体,可选:黑体、宋体、仿宋、幼圆、楷体、隶书。 | 黑体 | | `user_name` | str | 否 | 作者名。 | 百度千帆AppBuilder | ### 响应参数 | 参数名称 | 参数类型 | 描述 | 示例值 | | ------- | ------- | -------- | -------- | | `result` | obj | 模型运行后的输出结果,包含PPT下载链接。 | Message(content='...') | ### 响应示例 ``` https://download.yoojober.com/chatppt_business/2024-07/bf2af50285e52261507abdd7385e02c4.pptx?e=1721964536&token=8_2qFlGEVQZPpFvHdGR6gg2t9A9QZfWT9wwTl92s:nikgRM9RbPxzClBvmKrweeKd9Ck= ``` ## 高级用法 ## 更新记录和贡献 ### 2024.8.1 #### [Added] - 增加指令生成PPT组件。 - 增加指令生成PPT组件单元测试。 ================================================ FILE: docs/BasisModule/Components/ppt_generation_from_paper/README.md ================================================ # 论文生成PPT(PPTGenerationFromPaper) ## 简介 论文生成PPT组件(PPTGenerationFromPaper)可以根据上传的论文(支持**中英文**)生成PPT。 ### 功能介绍 根据上传的论文(支持**中英文**)生成PPT。 ### 特色优势 可根据论文(支持**中英文**)生成高质量PPT。 ### 应用场景 PPT生成。 ## 基本用法 ### 快速开始 ```python import os import appbuilder # 请前往千帆AppBuilder官网创建密钥,流程详见:https://cloud.baidu.com/doc/AppBuilder/s/Olq6grrt6#1%E3%80%81%E5%88%9B%E5%BB%BA%E5%AF%86%E9%92%A5 os.environ['APPBUILDER_TOKEN'] = '...' ppt_generator = appbuilder.PPTGenerationFromPaper() user_input = { 'file_key': 'http://image.yoojober.com/users/chatppt/temp/2024-06/6672aa839a9da.docx', 'style': '科技', 'color': '蓝色', 'title': '', 'pleader': '百度千帆AppBuilder', 'advisor': '百度千帆AppBuilder', 'school': '北京大学', 'school_logo': '', 'school_picture': '' } result = ppt_generator(appbuilder.Message(user_input)) print(result.content) ``` ## 参数说明 ### 鉴权说明 使用组件之前,请首先申请并设置鉴权参数,可参考[组件使用流程](https://cloud.baidu.com/doc/AppBuilder/s/Olq6grrt6#1%E3%80%81%E5%88%9B%E5%BB%BA%E5%AF%86%E9%92%A5)。 ```python # 设置环境中的TOKEN,以下示例略 os.environ['APPBUILDER_TOKEN'] = 'bce-YOURTOKEN' ``` ### 初始化参数 | 参数名称 | 参数类型 | 是否必须 | 描述 | 示例值 | | ------- | ------- | -------- | -------- | -------- | | `secret_key` | str | 否 | 用户鉴权token,默认从环境变量中获取: `os.getenv("APPBUILDER_TOKEN", "")` | bce-v3/XXX | | `gateway` | str | 否 | 后端网关服务地址,默认从环境变量中获取: `os.getenv("GATEWAY_URL", "")` | https://appbuilder.baidu.com | | `lazy_certification` | bool | 否 | 延迟认证,为True时在第一次运行时认证。默认为False。 | False | ### 调用参数 | 参数名称 | 参数类型 | 是否必须 | 描述 | 示例值 | | ------- | ------- | -------- | -------- | -------- | | `message` | obj | 是 | 输入消息,用于模型的主要输入内容。 | Message(content=input_data) | | `poll_request_times` | int | 否 | 轮询请求结果次数。默认为60。 | 60 | | `poll_request_interval` | int | 否 | 轮询请求的间隔时间(秒)。默认为5。 | 5 | 其中message包含的input_data包括以下参数: | 参数名称 | 参数类型 | 是否必须 | 描述 | 示例值 | | ------- | ------- | -------- | -------- | -------- | | `file_key` | str | 是 | 论文链接。 | http://image.yoojober.com/users/chatppt/temp/2024-06/6672aa839a9da.docx | | `style` | str | 否 | PPT风格,可选:科技、商务、小清新、可爱卡通、中国风、极简、党政。 | 科技 | | `color` | str | 否 | PPT主色调。可选:紫色、红色、橙色、黄色、绿色、青色、蓝色、粉色。 | 紫色 | | `title` | str | 否 | 自定义标题。优先使用自定义标题,如果为空则使用解析结果中的标题。 | 论文分享 | | `pleader` | str | 否 | 汇报人。 | 百度千帆AppBuilder | | `advisor` | str | 否 | 指导教师。 | 百度千帆AppBuilder | | `school` | str | 否 | 学校名称。 | 北京大学 | | `school_logo` | str | 否 | 学校logo链接。 | | | `school_picture` | str | 否 | 学校图片链接。 | | ### 响应参数 | 参数名称 | 参数类型 | 描述 | 示例值 | | ------- | ------- | -------- | -------- | | `result` | obj | 模型运行后的输出结果,包含PPT下载链接。 | Message(content='...') | ### 响应示例 ``` https://download.yoojober.com/chatppt_business/2024-07/6f472b65ee324d2da7849b6003a896e3.pptx?e=1721964794&token=8_2qFlGEVQZPpFvHdGR6gg2t9A9QZfWT9wwTl92s:nG-hbPN51uPP8FOeTY2jdQcT51w= ``` ## 高级用法 ## 更新记录和贡献 ### 2024.8.1 #### [Added] - 增加论文生成PPT组件。 - 增加论文生成PPT组件单元测试。 ================================================ FILE: docs/BasisModule/Components/qrcode_ocr/README.md ================================================ # 二维码识别 (QRcodeOCR) ## 简介 二维码识别 (QRcodeOCR) 可对图片中的二维码、条形码进行检测和识别,返回存储的文字信息及其位置信息。 ### 功能介绍 * 二维码识别 检测识别图片中的二维码(包括QR_CODE、DATA_MATRIX、AZTEC、PDF_417 4类),自动返回存储的内容。 * 条形码识别 检测识别图片中的条形码(包括CODE_128、UPC_A、EAN_13、ITF、CODABAR 等9类),自动返回存储的内容。 ### 特色优势 * 支持对图片中的二维码、条形码进行检测和识别,自动返回存储的内容。 ### 应用场景 * 物品信息管理 解析识别各类物品的二维码或条形码信息,应用于商品、药品出入库管理及货物运输管理等场景,轻松一扫即可快速完成对物品信息的读取、登记和存储,简化物品管理流程 ## 基本用法 下面是二维码识别的代码示例: 示例图片为: ![示例图片](https://bj.bcebos.com/v1/appbuilder/qrcode_ocr_test.png?authorization=bce-auth-v1%2FALTAKGa8m4qCUasgoljdEDAzLm%2F2024-01-24T12%3A45%3A13Z%2F-1%2Fhost%2Ffc43d07b41903aeeb5a023131ba6e74ab057ce26d50e966dc31ff083e6a9c41b) ```python import os import appbuilder import requests # 请前往千帆AppBuilder官网创建密钥,流程详见:https://cloud.baidu.com/doc/AppBuilder/s/Olq6grrt6#1%E3%80%81%E5%88%9B%E5%BB%BA%E5%AF%86%E9%92%A5 os.environ["APPBUILDER_TOKEN"] = '...' # 从BOS读取样例图片 image_url = "https://bj.bcebos.com/v1/appbuilder/qrcode_ocr_test.png?" \ "authorization=bce-auth-v1%2FALTAKGa8m4qCUasgoljdEDAzLm%2F2024-" \ "01-24T12%3A45%3A13Z%2F-1%2Fhost%2Ffc43d07b41903aeeb5a023131ba6" \ "e74ab057ce26d50e966dc31ff083e6a9c41b" raw_image = requests.get(image_url).content # 创建二维码识别组件实例 qrcode_ocr = appbuilder.QRcodeOCR() # 执行识别操作并获取结果 out = qrcode_ocr.run(appbuilder.Message(content={"raw_image": raw_image}), location="true") print(out.content) # {'codes_result': [{'type': 'QR_CODE', 'text': ['ocr文字识别'], 'location': {'top': 506, 'left': 1302, 'width': 1972, 'height': 1961}}]} ``` ## 参数说明 ### 鉴权说明 使用组件之前,请首先申请并设置鉴权参数,可参考[组件使用流程](https://cloud.baidu.com/doc/AppBuilder/s/Olq6grrt6#1%E3%80%81%E5%88%9B%E5%BB%BA%E5%AF%86%E9%92%A5)。 ```python # 设置环境中的TOKEN,以下示例略 os.environ["APPBUILDER_TOKEN"] = "bce-YOURTOKEN" ``` ### 初始化参数 无 ### 调用参数 (以表格形式展示) | 参数名称 | 参数类型 | 是否必须 | 描述 | 示例值 | |----------|---------|------|-------------------------------------------------------------------------|------------------------------------------------| | message | String | 是 | 输入的消息,用于模型的主要输入内容。这是一个必需的参数 | Message(content={"raw_image": b"待识别的图片字节流数据"}) | | location | String | 否 | 是否输出二维码/条形码位置信息,false:不返回位置信息,true:默认值,返回图中二维码/条形码的位置信息,包括上边距、左边距、宽度、高度 | "false" | |timeout| Float | 否 | HTTP超时时间,单位:秒 |1|| | retry | Integer | 否 | HTTP重试次数 | 3 | ### 响应参数 | 参数名称 | 参数类型 | 描述 | 示例值 | |--------------|----------|-------------|-------------------------------------------------------------------------------------------------------------------| | codes_result | Array[] | 返回结果 | [{'type': 'QR_CODE', 'text': ['ocr文字识别'], 'location': {'top': 506, 'left': 1302, 'width': 1972, 'height': 1961}}] | | +type | String | 识别码类型条码类型 | 'QR_CODE' | | +text | Array[] | 条形码/二维码识别内容 | ['ocr文字识别'] | | +location | Object{} | 条形码/二维码位置信息 | {'top': 506, 'left': 1302, 'width': 1972, 'height': 1961} | | ++top | Integer | 条形码/二维码的上边距 | 506 | | ++left | Integer | 条形码/二维码的左边距 | 1302 | | ++width | Integer | 条形码/二维码的宽度 | 1972 | | ++height | Integer | 条形码/二维码的高度 | 1961 | ### 响应示例 ```json { "codes_result": [ { "type": "QR_CODE", "text": ["ocr文字识别"], "location": { "top": 506, "left": 1302, "width": 1972, "height": 1961 } } ] } ``` ### 错误码 | 错误码 | 描述 | |-----|----| ## 高级用法 目前该模块仅提供基础的二维码识别功能。 ## 更新记录和贡献 * 二维码识别能力 (2024-01) ================================================ FILE: docs/BasisModule/Components/rag_with_baidu_search/README.md ================================================ # 百度搜索RAG(deprecate) ## 简介 百度搜索(BaiduSearch),通过百度搜索引擎搜索相关内容。 现推荐使用RagWithBaiduSearchPro | | 旧组件(百度搜索RAG)| 新组件(百度搜索RAG_PRO) |--------------|------------------ |------------------ | 指令 | ☑️ | ☑️ | 拒绝回答开关 | ☑️ | ❌ | 高亮开关 | ☑️ | ❌ | 友好度开关 | ☑️ | ❌ | 澄清开关 | ☑️ | ❌ | 溯源开关 | ☑️ | ☑️ | 流式请求 | ☑️ | ☑️ | temperature | ☑️ | ☑️ | top_p | ☑️ | ☑️ | 检索个数 | ❌ | ☑️ | 检索类型(网页、视频等) | ❌ | ☑️ ### 功能介绍 百度搜索是最大的中文搜索引擎,帮助用户在海量信息中找到最需要的内容。 ### 特色优势 百度搜索凭借先进的中文搜索技术、个性化推荐、全面的信息覆盖、即时的搜索结果和强大的安全防护,为用户提供快速、准确、安全的搜索体验,满足多样化的信息需求。 ### 应用场景 通用搜索领域 ## 基本用法 以下是一个简单的例子来演示如何开始使用百度搜索组件: ```python import appbuilder import os # 请前往千帆AppBuilder官网创建密钥,流程详见:https://cloud.baidu.com/doc/AppBuilder/s/Olq6grrt6#1%E3%80%81%E5%88%9B%E5%BB%BA%E5%AF%86%E9%92%A5 # 设置环境变量 os.environ["APPBUILDER_TOKEN"] = '...' # 创建rag_with_baidusearch对象 rag_with_baidusearch_component = appbuilder.RAGWithBaiduSearch(model="DeepSeek-V3.1") # 运行rag_with_baidusearch基本组件 msg = appbuilder.Message("残疾人怎么办相关证件") result = rag_with_baidusearch_component.run(msg) # 获取reference references = result.extra # 输出运行结果 print(result) ``` ## 参数说明 ### 鉴权说明 使用组件之前,请首先申请并设置鉴权参数,可参考[组件使用流程](https://cloud.baidu.com/doc/AppBuilder/s/Olq6grrt6#1%E3%80%81%E5%88%9B%E5%BB%BA%E5%AF%86%E9%92%A5)。 ```python import os os.environ["APPBUILDER_TOKEN"] = "..." ``` ### 初始化参数 - `model`: 模型名称,用于指定要使用的千帆模型。 - `instruction (obj:Message, 可选)`: 可设定人设,如:你是问答助手,在回答问题前需要加上“很高兴为您解答:” - `reject (bool, 可选)`: 拒绝开关,如果为 True,则启用该能力。默认为 False。当输入的问题在搜索结果中没有找到答案时,开关开启时,模型会用特定话术("当前文档库找不到对应的答案,我可以尝试用我的常识来回答你。")做回复的开头,并后接自有知识做回复内容。 - `clarify (bool, 可选)`: 澄清开关,如果为 True,则启用该能力。默认为 False。 当输入的问题比较模糊、或者主体指代不清晰,且context_list中包含有可以回答该模糊问题的多种潜在备选答案时,开启该开关,大模型会以特定的话术做澄清反问,引导用户继续补充问题发问。举例子,query:发电机的续航时间? Answer: 根据搜索结果得到了xx和xx两种型号的发电机,您的问题具体涉及到哪一个?请补充关键信息,作为完整的问题重新发问。 - `highlight (bool, 可选)`: 重点强调开关,如果为 True,则启用该能力。默认为 False。开启该功能时,回复结果中会高亮显示关键部分的内容。 - `friendly (bool, 可选)`: 友好性提升开关,如果为 True,则启用该能力。默认为 False。开关开启时,部分回复的开头会加礼貌用语。且如果回答涉及到大段的信息,会倾向于以<总-分>或者<总-分-总>的形式做分点论述,使得答案的格式更规整,可读性更强。 - `cite (bool, 可选)`: 溯源开关,如果为 True,则启用该能力。默认为 False。开关开启时,回复内容后会使用引用标记来标注回答内容参考的搜索结果序号,如^[1]^ (引用单个搜索结果),^[1][2]^(引用多个搜索结果)。例如:按照当地公安机关出入境管理部门规定的其他材料办理^[2]^。 ### 调用参数 调用参数中的 instruction, reject, clarify, highlight, friendly 和 cite 会覆盖初始化时的参数。 - `msg (obj:Message)`: 输入消息,包含用户提出的问题。这是一个必需的参数。 - `instruction (obj:Message, 可选)`: 可设定人设,如:你是问答助手,在回答问题前需要加上“很高兴为您解答:” - `reject (bool, 可选)`: 拒绝开关,如果为 True,则启用该能力。默认为 False。当输入的问题在搜索结果中没有找到答案时,开关开启时,模型会用特定话术("当前文档库找不到对应的答案,我可以尝试用我的常识来回答你。")做回复的开头,并后接自有知识做回复内容。 - `clarify (bool, 可选)`: 澄清开关,如果为 True,则启用该能力。默认为 False。 当输入的问题比较模糊、或者主体指代不清晰,且context_list中包含有可以回答该模糊问题的多种潜在备选答案时,开启该开关,大模型会以特定的话术做澄清反问,引导用户继续补充问题发问。举例子,query:发电机的续航时间? Answer: 根据搜索结果得到了xx和xx两种型号的发电机,您的问题具体涉及到哪一个?请补充关键信息,作为完整的问题重新发问。 - `highlight (bool, 可选)`: 重点强调开关,如果为 True,则启用该能力。默认为 False。开启该功能时,回复结果中会高亮显示关键部分的内容。 - `friendly (bool, 可选)`: 友好性提升开关,如果为 True,则启用该能力。默认为 False。开关开启时,部分回复的开头会加礼貌用语。且如果回答涉及到大段的信息,会倾向于以<总-分>或者<总-分-总>的形式做分点论述,使得答案的格式更规整,可读性更强。 - `cite (bool, 可选)`: 溯源开关,如果为 True,则启用该能力。默认为 False。开关开启时,回复内容后会使用引用标记来标注回答内容参考的搜索结果序号,如^[1]^ (引用单个搜索结果),^[1][2]^(引用多个搜索结果)。例如:按照当地公安机关出入境管理部门规定的其他材料办理^[2]^。 - `stream (bool, 可选)`: 指定是否以流式形式返回响应。默认为 False。 - `temperature (float, 可选)`: 模型配置的温度参数,用于调整模型的生成概率。取值范围为 0.0 到 1.0,其中较低的值使生成更确定性,较高的值使生成更多样性。默认值为 1e-10。 - `top_p (float, 可选)`: 模型配置的top_p参数,top_p值越高输出文本越多样,top_p值越低输出文本越稳定。取值范围为 0.0 到 1.0,默认值为 1e-10。 ### 返回值 - 返回一个 `Message` 对象,包含模型运行后的输出消息。 ## 高级用法 该组件的高级用法包括定制化的输入处理、输出处理,以及更复杂的调用场景。用户可以根据具体需求扩展组件功能,实现个性化的问答系统。 包括如下功能: 1、人设 2、拒答 3、澄清反问 4、重点强调 5、友好度提升 6、溯源 ### 代码样例 ```python import appbuilder import os # 设置环境变量 os.environ["APPBUILDER_TOKEN"] = '...' # 创建rag_with_baidusearch对象, 并初始化人设指令 rag_with_baidusearch_component = appbuilder.RAGWithBaiduSearch( model="DeepSeek-V3.1", instruction=appbuilder.Message("你是问答助手,在回答问题前需要加上: 很高兴为您解答")) # 运行rag_with_baidusearch组件,开启拒答、澄清追问、重点强调、友好性提升、溯源能力功能 msg = appbuilder.Message("残疾人怎么办相关证件") result = rag_with_baidusearch_component.run( msg, reject=True, clarify=True, highlight=True, friendly=True, cite=True, temperature=0.5, stream=False) # 输出运行结果 print(result) ``` ### 返回参数说明 返回的message中具体字段说明如下: | 字段 | 字段说明 | |---------------|--------| | name | 名称 | | mtype | 类型 | | content | 内容 | | extra | 引用 | | +search_baidu | 百度搜索结果 | | ++content | 网页内容摘要 | | ++url | 网页链接 | | ++ref_id | 序号 | | ++title | 标题 | | ++icon | 网站图标 | | ++site_name | 网站名 | ### 典型返回样例 ``` Message(name=msg, content=您好,请问您是想询问关于残疾人办理什么证件的问题吗?如果是,我可以为您提供一些信息。 首先,如果您是首次申请办理残疾人证,需要携带身份证、户口簿和三张两寸近期免冠白底彩色照片到县残联办证窗口提出申请。如果您因身体原因无法亲自前往,可以联系村(社区)工作人员代办申请。 其次,如果您是指残疾类型等级证明,您需要携带相关材料到指定医院或医生进行评级,并由医生签名盖章。 最后,如果您是指残疾人享受低保或残疾人贫困证的一级肢体、视力、智力、精神、多重及60周岁以上的一级听力、语言的重度残疾人可以享受重度残疾人生活补助,那么您需要携带身份证、户口本和残疾证申请表到县、市、区级残联进行办理。 希望这些信息对您有所帮助。如果您还有其他问题,欢迎随时提问。^[2]^, mtype=dict, extra={'search_baidu': [{'content': '(一)3张两寸近期免冠白底彩色照片。 (二)身份证、户口簿原件及复印件。 (三)申请智力、精神类残疾人证和未成年人申请残疾人证需同时提供法定监护人的身份证、户口本原件及复印件和监护人的证明材料。监护人证明材料为以下三项中任意一项: (1)能体现双方直系血缘亲属关系的户口簿。 (2)申请人所在村(社区)出具的说明双方关系的证明材料。 (3)其他能够证明其双方关系的合法证件。(法院判决书、结婚证、出生证明等) (四)经常居住地的有效居住证(户籍地不在本市申请人需提供此证件,本市户籍申请人无需提供此证件)。 (五)经常居住地残联要求的其他材料。 残疾证办理事项及流程', 'icon': 'https://ss1.baidu.com/6ONXsjip0QIZ8tyhnq/it/u=1505232404,3530227258&fm=195&app=88&f=JPEG?w=200&h=200', 'url': 'https://www.jingzhou.gov.cn/ztfwnew/shjz/cjrbl/index.shtml', 'ref_id': '1', 'site_name': '荆州市人民政府', 'title': '残疾人证办理服务'}, {'content': '{#}申请{@}. 首次申请办理残疾人证人员,需持申请人居民身份证,户口簿和3张两寸近期免冠白底彩照,到县残联办证窗口(县政务服务中心一楼1号窗口)提出办证申请,填写《中华人民共和国残疾人证申请表》.如因身体原因个人无法出行办证,可联系村(社区)工作人员代办申请.', 'icon': None, 'url': 'https://mp.weixin.qq.com/s?__biz=MzIxMzM5ODY5OQ==&mid=2247485042&idx=1&sn=26a4cad0122d24971d3f5ce598af3564&chksm=97b623b6a0c1aaa02f776c19f567e0b3fabdef3d9f5c957e1f260f286fe5356101fd1ac4e675&scene=27', 'ref_id': '2', 'site_name': '微信公众平台', 'title': '残疾人证如何办理?到哪里评定?你想知道的都在这里'}, {'content': '一、残疾人如何办残疾证 1、户口所在地的县、市、区级残联领取《残疾人证申请表》和《残疾评定表》; 2、身份证或户口本复印件一张; 3、两寸彩色相片2-6张(多带不碍事,各地标准不一); 4、残疾类型等级证明。残疾很明显的可以直接到残联进行评级(像肢体类)审核办理,不明显的必须到指定医院、指定医生进行评级签名并盖章。 一切手续完备,就到县、市、区级残联进行办理,快的话立等可取,慢的话7-15天也差不多了。 二、残疾证有什么用? 1、持有残疾证的残疾人可享受低保或持残疾人贫困证的一级肢体、视力、智力、精神、多重及60周岁以上的一级听力、语言的重度残疾人,可享受重度残疾人生活补助。 2、残疾人托(安)养方面,一级重度残疾人(不含听力、语言、视力残疾)或18至60周岁二级重度残疾人(不含听力、语言、视力残疾),集中托养:低保户、贫困户的对象补助每年补助现金按各地政策规定金额发放。', 'icon': 'https://ss0.baidu.com/6ONWsjip0QIZ8tyhnq/it/u=215799447,688541359&fm=195&app=88&f=JPEG?w=200&h=200', 'url': 'https://mip.66law.cn/laws/1060751.aspx', 'ref_id': '3', 'site_name': '华律网', 'title': '残疾人如何办残疾证-证件办理|华律办事直通车'}]}) ``` ================================================ FILE: docs/BasisModule/Components/rag_with_baidu_search_pro/README.md ================================================ # 百度搜索RAG_PRO ## 简介 百度搜索RAG_PRO组件旨在解决传统生成模型在生成长文本时可能会受到信息获取不足的问题,核心思想是将百度搜索与LLM相结合,使得生成的文本可以借助检索到的信息进行增强,从而提高生成文本的质量和相关性。 ### 功能介绍 基于百度搜索结果进行RAG检索增强问答。 百度搜索RAG_PRO组件支持配置用户指令,temperature,top_p,以及溯源开关等,为用户提供了更灵活的控制选项。 对比旧版百度搜索RAG,新版百度搜索RAG_PRO在支持配置检索个数和检索类型(网页、视频等)方面进行了升级。 ### 特色优势 百度搜索RAG_PRO组件的综合优势在于通过结合百度搜索的搜索引擎技术和ERNIE模型的语义理解能力,可以更准确地理解用户的搜索意图,并提供与搜索查询相关性更高的搜索结果。 ### 应用场景 通用搜索领域 ## 基本用法 以下是一个简单的例子来演示如何开始使用百度搜索RAG_PRO组件: ```python import appbuilder import os # 请前往千帆AppBuilder官网创建密钥,流程详见:https://cloud.baidu.com/doc/AppBuilder/s/Olq6grrt6#1%E3%80%81%E5%88%9B%E5%BB%BA%E5%AF%86%E9%92%A5 # 设置环境变量 os.environ["APPBUILDER_TOKEN"] = '...' # 创建rag_with_baidusearch_pro对象 rag_with_baidu_search_pro = appbuilder.RagWithBaiduSearchPro(model="DeepSeek-V3.1") # 运行rag_with_baidusearch基本组件 msg = appbuilder.Message("残疾人怎么办相关证件") result = rag_with_baidu_search_pro.run(msg) # 获取reference references = result.extra # 输出运行结果 print(result) ``` ## 参数说明 ### 鉴权说明 使用组件之前,请首先申请并设置鉴权参数,可参考[组件使用流程](https://cloud.baidu.com/doc/AppBuilder/s/Olq6grrt6#1%E3%80%81%E5%88%9B%E5%BB%BA%E5%AF%86%E9%92%A5)。 ```python import os os.environ["APPBUILDER_TOKEN"] = "..." ``` ### 初始化参数 - `model`: 模型名称,用于指定要使用的千帆模型。 - `instruction (obj:Message, 可选)`: 可设定人设,如:你是问答助手,在回答问题前需要加上“很高兴为您解答:” ### 调用参数 调用参数中的 instruction 会覆盖初始化时的参数。 - `msg (obj:Message)`: 输入消息,包含用户提出的问题。这是一个必需的参数。 - `instruction (obj:Message, 可选)`: 可设定人设,如:你是问答助手,在回答问题前需要加上“很高兴为您解答:” - `stream (bool, 可选)`: 指定是否以流式形式返回响应。默认为 False。 - `temperature (float, 可选)`: 模型配置的温度参数,用于调整模型的生成概率。取值范围为 0.0 到 1.0,其中较低的值使生成更确定性,较高的值使生成更多样性。默认值为 1e-10。 - `top_p (float, 可选)`: 模型配置的top_p参数,top_p值越高输出文本越多样,top_p值越低输出文本越稳定。取值范围为 0.0 到 1.0,默认值为 1e-10。 - `search_top_k (int, 可选)`: 指定百度搜索返回的检索个数,最多10,默认为4。 - `hide_corner_markers (bool, 可选)`: 溯源开关,True隐藏来源,False显示来源,默认为True,不显示结果来源。 ### 返回值 - 返回一个 `Message` 对象,包含模型运行后的输出消息。 ## 高级用法 该组件的高级用法包括定制化的输入处理、输出处理,以及更复杂的调用场景。用户可以根据具体需求扩展组件功能,实现个性化的问答系统。 包括如下功能: 1、人设 2、溯源 3、百度搜索检索个数 ### 代码样例 ```python import appbuilder import os # 设置环境变量 os.environ["APPBUILDER_TOKEN"] = '...' # 创建rag_with_baidusearch对象, 并初始化人设指令 rag_with_baidusearch_pro = appbuilder.RagWithBaiduSearchPro( model="DeepSeek-V3.1", instruction=appbuilder.Message("你是问答助手,在回答问题前需要加上: 很高兴为您解答")) # 运行rag_with_baidusearch组件,开启拒答、澄清追问、重点强调、友好性提升、溯源能力功能 msg = appbuilder.Message("残疾人怎么办相关证件") result = rag_with_baidusearch_pro.run( msg, temperature=0.5, stream=False) # 输出运行结果 print(result) ``` ### 返回参数说明 返回的message中具体字段说明如下: | 字段 | 字段说明 | |---------------|--------| | name | 名称 | | mtype | 类型 | | content | 内容 | | extra | 引用 | | +search_baidu | 百度搜索结果 | | ++content | 网页内容摘要 | | ++url | 网页链接 | | ++ref_id | 序号 | | ++title | 标题 | | ++icon | 网站图标 | | ++site_name | 网站名 | ### 典型返回样例 ``` Message(name=msg, content=您好,请问您是想询问关于残疾人办理什么证件的问题吗?如果是,我可以为您提供一些信息。 首先,如果您是首次申请办理残疾人证,需要携带身份证、户口簿和三张两寸近期免冠白底彩色照片到县残联办证窗口提出申请。如果您因身体原因无法亲自前往,可以联系村(社区)工作人员代办申请。 其次,如果您是指残疾类型等级证明,您需要携带相关材料到指定医院或医生进行评级,并由医生签名盖章。 最后,如果您是指残疾人享受低保或残疾人贫困证的一级肢体、视力、智力、精神、多重及60周岁以上的一级听力、语言的重度残疾人可以享受重度残疾人生活补助,那么您需要携带身份证、户口本和残疾证申请表到县、市、区级残联进行办理。 希望这些信息对您有所帮助。如果您还有其他问题,欢迎随时提问。^[2]^, mtype=dict, extra={'search_baidu': [{'content': '(一)3张两寸近期免冠白底彩色照片。 (二)身份证、户口簿原件及复印件。 (三)申请智力、精神类残疾人证和未成年人申请残疾人证需同时提供法定监护人的身份证、户口本原件及复印件和监护人的证明材料。监护人证明材料为以下三项中任意一项: (1)能体现双方直系血缘亲属关系的户口簿。 (2)申请人所在村(社区)出具的说明双方关系的证明材料。 (3)其他能够证明其双方关系的合法证件。(法院判决书、结婚证、出生证明等) (四)经常居住地的有效居住证(户籍地不在本市申请人需提供此证件,本市户籍申请人无需提供此证件)。 (五)经常居住地残联要求的其他材料。 残疾证办理事项及流程', 'icon': 'https://ss1.baidu.com/6ONXsjip0QIZ8tyhnq/it/u=1505232404,3530227258&fm=195&app=88&f=JPEG?w=200&h=200', 'url': 'https://www.jingzhou.gov.cn/ztfwnew/shjz/cjrbl/index.shtml', 'ref_id': '1', 'site_name': '荆州市人民政府', 'title': '残疾人证办理服务'}, {'content': '{#}申请{@}. 首次申请办理残疾人证人员,需持申请人居民身份证,户口簿和3张两寸近期免冠白底彩照,到县残联办证窗口(县政务服务中心一楼1号窗口)提出办证申请,填写《中华人民共和国残疾人证申请表》.如因身体原因个人无法出行办证,可联系村(社区)工作人员代办申请.', 'icon': None, 'url': 'https://mp.weixin.qq.com/s?__biz=MzIxMzM5ODY5OQ==&mid=2247485042&idx=1&sn=26a4cad0122d24971d3f5ce598af3564&chksm=97b623b6a0c1aaa02f776c19f567e0b3fabdef3d9f5c957e1f260f286fe5356101fd1ac4e675&scene=27', 'ref_id': '2', 'site_name': '微信公众平台', 'title': '残疾人证如何办理?到哪里评定?你想知道的都在这里'}, {'content': '一、残疾人如何办残疾证 1、户口所在地的县、市、区级残联领取《残疾人证申请表》和《残疾评定表》; 2、身份证或户口本复印件一张; 3、两寸彩色相片2-6张(多带不碍事,各地标准不一); 4、残疾类型等级证明。残疾很明显的可以直接到残联进行评级(像肢体类)审核办理,不明显的必须到指定医院、指定医生进行评级签名并盖章。 一切手续完备,就到县、市、区级残联进行办理,快的话立等可取,慢的话7-15天也差不多了。 二、残疾证有什么用? 1、持有残疾证的残疾人可享受低保或持残疾人贫困证的一级肢体、视力、智力、精神、多重及60周岁以上的一级听力、语言的重度残疾人,可享受重度残疾人生活补助。 2、残疾人托(安)养方面,一级重度残疾人(不含听力、语言、视力残疾)或18至60周岁二级重度残疾人(不含听力、语言、视力残疾),集中托养:低保户、贫困户的对象补助每年补助现金按各地政策规定金额发放。', 'icon': 'https://ss0.baidu.com/6ONWsjip0QIZ8tyhnq/it/u=215799447,688541359&fm=195&app=88&f=JPEG?w=200&h=200', 'url': 'https://mip.66law.cn/laws/1060751.aspx', 'ref_id': '3', 'site_name': '华律网', 'title': '残疾人如何办残疾证-证件办理|华律办事直通车'}]}) ``` ================================================ FILE: docs/BasisModule/Components/retriever/README.md ================================================ # 向量检索 ## 简介 Appbuilder提供多种向量数据库作为向量检索的底座,当前主要支持百度向量数据库、百度 ElasticSearch。 ### 功能介绍 `向量检索-VDB`组件(Baidu VDB Retriever)以百度向量数据库作为向量存储和检索的底座。百度向量数据库是一个专注于多维向量数据的存储、检索和分析的企业级分布式数据库服务。基于百度自主研发的向量数据库内核,VectorDB在保证高性能和高可用性的同时,也特别注重易用性和可扩展性。它支持多种索引类型和相似度计算方法,能够满足各类复杂和多样化的数据应用需求。特别值得一提的是,VectorDB能够管理高达数十亿的向量规模,同时保持毫秒级的查询响应时间,非常适合进行大规模的向量检索和分析任务。 `向量检索-BES`组件(Baidu ElasticSearch Retriever)以百度 ElasticSearch作为向量存储和检索的底座。百度 ElasticSearch是一款专为企业级需求设计的分布式搜索和分析服务,它在全面兼容开源ElasticSearch的基础上,提供了更多增强功能。这款服务的核心优势在于其高性能和高可靠性,它为处理结构化和非结构化数据提供了一个低成本且高效的平台。对于关注数据安全的客户来说,百度ElasticSearch提供了先进的权限管理机制,使得您可以根据业务需求自由地配置集群权限。 ================================================ FILE: docs/BasisModule/Components/retriever/baidu_vdb/README.md ================================================ # 向量检索-VectorDB(BaiduVectorDBRetriever) ## 简介 向量检索-VectorDB(BaiduVectorDBRetriever)基于一款百度向量数据库的内容检索组件,支持根据文本的向量的相似度进行内容检索。 ### 功能介绍 向量检索-VectorDB(BaiduVectorDBRetriever)用于在将文本内容输入到百度向量数据库,根据文本的向量相似度进行高效的内容检索。 ### 特色优势 高效准确:基于百度向量数据库的强大能力,提供高效且准确的内容检索功能。 ### 应用场景 各种内容检索场景 ## 准备工作 在使用向量检索-VectorDB(BaiduVectorDBRetriever)进行内容检索之前,需要到百度向量数据库官网创建相应的实例,[教程](https://cloud.baidu.com/doc/VDB/s/hlrsoazuf)。 ## 基本用法 以下是有关如何开始使用向量检索-VectorDB(BaiduVectorDBRetriever)的代码示例: 补充说明: - `you_vdb_instance_id` 为VectorDB 实例ID,请替换为您的实例ID,在VectorDB控制台界面上可以查看 - `your_api_key` 为您在VectorDB上申请的账户密钥,请替换为您自己的root账户密钥,在VectorDB控制台界面上可以查看 ```python import os import appbuilder # 请前往千帆AppBuilder官网创建密钥,流程详见:https://cloud.baidu.com/doc/AppBuilder/s/Olq6grrt6#1%E3%80%81%E5%88%9B%E5%BB%BA%E5%AF%86%E9%92%A5 os.environ["APPBUILDER_TOKEN"] = '...' segments = appbuilder.Message(["文心一言大模型", "百度在线科技有限公司"]) # 初始化构建索引 vector_index = appbuilder.BaiduVDBVectorStoreIndex.from_params( instance_id=your_instance_id, api_key=your_api_key, drop_exists=True, ) vector_index.add_segments(segments) query = appbuilder.Message("文心一言") retriever = vector_index.as_retriever() res = retriever(query) print(res) ``` ## 参数说明 ### 鉴权说明 使用组件之前,请首先申请并设置鉴权参数,可参考[组件使用流程](https://cloud.baidu.com/doc/AppBuilder/s/Olq6grrt6#1%E3%80%81%E5%88%9B%E5%BB%BA%E5%AF%86%E9%92%A5)。 ```python # 设置环境中的TOKEN,以下示例略 os.environ["APPBUILDER_TOKEN"] = "bce-YOURTOKEN" ``` ### 初始化参数说明: `BaiduVDBVectorStoreIndex()` 实例化参数说明: - instance_id(str,必填):百度向量数据库的实例id,创建实例时获取 - api_key (str,必填):连接向量数据库所需的密码,创建实例时获取 - account (str,非必填):连接向量数据库所需的用户名,默认root - database_name (str,非必填) :向量数据库的名称,默认为AppBuilderDatabase - table_params (TableParams,非必填) :VectorDB table参数,参考链接[VectorDB table params](https://cloud.baidu.com/doc/VDB/s/mlrsob0p6) - embedding (Embedding,非必填) :appbuilder.Embedding类型,若有构造好的Embedding,可以增量插入,否则默认新建embedding ------- `BaiduVDBVectorStoreIndex().from_params()` 构造函数参数说明: - instance_id(str,必填):百度向量数据库的实例id,创建实例时获取 - api_key (str,必填):连接向量数据库所需的密码,创建实例时获取 - account (str,非必填):连接向量数据库所需的用户名,默认root - database_name (str,非必填) :向量数据库的名称,默认为AppBuilderDatabase - table_name (str,非必填) :向量数据库的表名,默认为AppBuilderTable - drop_exists (bool, 非必填) :是否清空数据库历史记录,默认为False ------- ### 调用参数: `BaiduVDBRetriever().run()` 函数参数说明: | 参数名称 | 参数类型 |是否必须 | 描述 | 示例值 | |---------|--------|--------|------------------|---------------| | message | String |是 | 需要检索的内容, 类型为Message,content类型为str, 长度要求(0,512) | "中国2023人均GDP" | | top_k | int |否 | 返回相似度最高的top_k个内容,top_k的数值范围(1,embedding索引数量] | 1 | ### 响应参数 `BaiduVDBRetriever().run()` 函数返回值说明: | 参数名称 | 参数类型 | 描述 | 示例值 | |------|--------|-----|--------------------| | text | string | 检索结果 | "中国2023年人均GDP8.94万元" | | score | float | 相似度 | 0.95 | | meta | dict | 元信息 | "" | ### 响应示例 ```json {"text": "中国2023年人均GDP8.94万元", "score": 0.95, "meta": ""} ``` ## 高级用法: 本组件根据向量的相似度进行检索,支持使用不同的embedding方法和索引方式来优化检索的效果。 ## 更新记录和贡献 * 向量检索能力 (2024-03) ================================================ FILE: docs/BasisModule/Components/retriever/bes/README.md ================================================ # 向量检索-BES(BaiduElasticSearchRetriever) ## 简介 向量检索-BES组件(BaiduElasticSearchRetriever)基于一款Baidu ElasticSearch的内容检索组件,支持根据文本的向量的相似度进行内容检索。 ### 功能介绍 向量检索-BES组件(BaiduElasticSearchRetriever)用于在将文本内容输入到Baidu ElasticSearch,根据文本的向量相似度进行高效的内容检索。 ### 特色优势 - 高效准确:基于Baidu ElasticSearch的强大能力,提供高效且准确的内容检索功能。 ### 应用场景 各种内容检索场景 ## 准备工作 在使用BaiduElasticSearchRetriever进行内容检索之前,需要到Baidu ElasticSearch官网创建相应的集群,详情见[教程](https://cloud.baidu.com/doc/BES/s/gke3ocf89)。 注:创建集群时请选择7.10.2版本的ES,否则可能无法使用本组件。 ## 基本用法 以下是有关如何开始使用BESRetriever的代码示例: ```python import os import appbuilder # 请前往千帆AppBuilder官网创建密钥,流程详见:https://cloud.baidu.com/doc/AppBuilder/s/Olq6grrt6#1%E3%80%81%E5%88%9B%E5%BB%BA%E5%AF%86%E9%92%A5 os.environ["APPBUILDER_TOKEN"] = '...' embedding = appbuilder.Embedding() segments = appbuilder.Message(["文心一言大模型", "百度在线科技有限公司"]) # 初始化构建索引 vector_index = appbuilder.BESVectorStoreIndex.from_segments(segments=segments, cluster_id=es_cluster_id, user_name=es_username, password=es_password, embedding=embedding) # 获取当前索引中的全部内容 all_content = vector_index.get_all_segments() print(all_content) # 转化为retriever retriever = vector_index.as_retriever() # 按照query进行检索 query = appbuilder.Message("文心一言") res = retriever(query=query, top_k=1) print(res) # 删除当前索引中的全部内容 vector_index.delete_all_segments() ``` ## 参数说明 ### 鉴权说明 使用组件之前,请首先申请并设置鉴权参数,可参考[组件使用流程](https://cloud.baidu.com/doc/AppBuilder/s/Olq6grrt6#1%E3%80%81%E5%88%9B%E5%BB%BA%E5%AF%86%E9%92%A5)。 ```python # 设置环境中的TOKEN,以下示例略 os.environ["APPBUILDER_TOKEN"] = "bce-YOURTOKEN" ``` ### 初始化参数说明: - segments (Message[List[str]],必填):需要入库的文本段落 - cluster_id (str,必填):ElacticSearch集群的id,创建集群时获取 - user_name (str,必填):连接ES集群所需的用户名,创建集群时获取 - password (str,必填):连接ES集群所需的密码,创建集群时获取 - embedding (obj,非必填):用于将文本转为向量的模型,默认为Embedding ### 调用参数: | 参数名称 | 参数类型 |是否必须 | 描述 | 示例值 | |---------|--------|--------|------------------|---------------| | message | String |是 | 需要检索的内容 | "中国2023人均GDP" | | top_k | int |否 | 返回相似度最高的top_k个内容 | 1 | ### 响应参数 | 参数名称 | 参数类型 | 描述 | 示例值 | |------|--------|-----|--------------------| | text | string | 检索结果 | "中国2023年人均GDP8.94万元" | | score | float | 相似度 | 0.95 | | meta | dict | 元信息 | "" | ### 响应示例 ```json {"text": "中国2023年人均GDP8.94万元", "score": 0.95, "meta": ""} ``` ## 高级用法: 本组件根据向量的相似度进行检索,支持使用不同的embedding方法和索引方式来优化检索的效果。 ## 更新记录和贡献 * 向量检索能力 (2023-12) ================================================ FILE: docs/BasisModule/Components/retriever/reranker/README.md ================================================ # 文本精排(Reranker) ## 简介 文本精排能力,将Query召回到的N个候选文本段落进行精排;保证与Query相关程度越高的文本段落排序越靠前,提升检索效果。 ### 功能介绍 文本精排(Reranker)用于检索排序,输入为Query和Top K个段落,输出为每个段落的排序得分;Query相关程度越高的文本段落排序越靠前,用于提升检索效果。 ### 特色优势 - 高效准确:基于开源模型[ bce-reranker](https://huggingface.co/maidalun1020/bce-reranker-base_v1)的能力,提供高效且准确的内容检索功能。[百度云推理服务Api](https://cloud.baidu.com/doc/WENXINWORKSHOP/s/xlu216rqn) ### 应用场景 检索排序场景 ## 基本用法 以下是有关如何开始使用BESRetriever的代码示例: ```python import os import appbuilder from appbuilder import Message # 请前往千帆AppBuilder官网创建密钥,流程详见:https://cloud.baidu.com/doc/AppBuilder/s/Olq6grrt6#1%E3%80%81%E5%88%9B%E5%BB%BA%E5%AF%86%E9%92%A5 os.environ["APPBUILDER_TOKEN"] = '...' reranker = appbuilder.Reranker() ranked_1 = reranker("你好", ["他也好", "hello?"]) print(ranked_1) # 使用上游的Message作为输入的代码示例 ranked_2 = reranker(appbuilder.Message("你好"), appbuilder.Message(["他也好", "hello?"])) print(ranked_2) ``` ## 参数说明 ### 初始化参数说明: | 参数名称 | 参数类型 |是否必须 | 描述 | 示例值 | |---------|--------|--------|------------------|---------------| | model | str |是 | 指定底座模型的类型。当前仅支持 bce-reranker-base 作为可选值。若不指定,默认值为 bce-reranker-base。 | bce-reranker-base | ### 调用参数: | 参数名称 | 参数类型 | 是否必须 | 描述 | 示例值 | |---------|--------|--------|------------------|---------------| | query | str |是 | 精排Query,长度小于1600。 | "你好" | | texts | List[str] | 是 | 精排输入段落,会对列表里的所有内容排序,最大长度为50. | ["你好", "世界"] | ### 响应参数: | 参数名称 | 参数类型 | 描述 | 示例值 | |---------|--------|------------------|---------------| | +document | str | 输入的段落 | "hello?" | | +relevance_score | float | 精排的相关性分数 | 0.565118 | | +index | int | 输入段落的原始index | -- | ### 响应示例 #### 输入 ```python query="你好", text=["他也好", "hello?"] ``` #### 响应 ```json [ { "document": "hello?", "relevance_score": 0.5651187300682068, "index": 1 }, { "document": "他也好", "relevance_score": 0.47729530930519104, "index": 0 } ] ``` ### 错误码 无 ## 更新记录和贡献 * reranker-base (2024-08) ================================================ FILE: docs/BasisModule/Components/table_ocr/README.md ================================================ # 表格文字识别 (TableOCR) ## 简介 表格文字识别 (TableOCR) 可支持识别图片中的表格内容,返回各表格的表头表尾内容、单元格文字内容及其行列位置信息,全面覆盖各类表格样式,包括常规有线表格、无线表格、含合并单元格表格。同时,支持多表格内容识别。 ### 功能介绍 * 简单表格文字识别 支持识别具备完整框线的常规简单表格,结构化输出表头、表尾及每个单元格的文字内容。 * 复杂表格文字识别 可识别无表格框线,但行、列位置明确的表格,支持含合并单元格的复杂表格文字识别。 ### 特色优势 * 支持识别图片中的表格内容,返回各表格的表头表尾内容、单元格文字内容及其行列位置信息,全面覆盖各类表格样式,包括常规有线表格、无线表格、含合并单元格表格。同时,支持单图中多表格内容的识别。 ### 应用场景 * 信息登记表识别 对个人、商品、公示内容等纸质信息登记表进行识别,用于登记信息的结构化整理和统计,大幅度降低人力录入成本,提升信息管理的便捷性 * 财税报表识别 提取识别银行对账单、资产负债表、损益表等财税场景常用表格内容,快速实现表格内容的电子化,用于财税信息统计、存档及核算,大幅度提升信息录入效率 ## 基本用法 下面是表格文字识别的代码示例: 示例图片为 ![示例图片](https://bj.bcebos.com/v1/appbuilder/table_ocr_test.png?authorization=bce-auth-v1%2FALTAKGa8m4qCUasgoljdEDAzLm%2F2024-01-24T12%3A37%3A09Z%2F-1%2Fhost%2Fab528a5a9120d328dc6d18c6064079145ff4698856f477b820147768fc2187d3) ```python import os import appbuilder import requests # 请前往千帆AppBuilder官网创建密钥,流程详见:https://cloud.baidu.com/doc/AppBuilder/s/Olq6grrt6#1%E3%80%81%E5%88%9B%E5%BB%BA%E5%AF%86%E9%92%A5 os.environ["APPBUILDER_TOKEN"] = '...' # 从BOS读取样例图片 image_url = "https://bj.bcebos.com/v1/appbuilder/table_ocr_test.png?" \ "authorization=bce-auth-v1%2FALTAKGa8m4qCUasgoljdEDAzLm%2F2024" \ "-01-24T12%3A37%3A09Z%2F-1%2Fhost%2Fab528a5a9120d328dc6d18c6" \ "064079145ff4698856f477b820147768fc2187d3" raw_image = requests.get(image_url).content # 创建表格文字识别组件实例 table_ocr = appbuilder.TableOCR() # 执行识别操作并获取结果 out = table_ocr.run(appbuilder.Message(content={"raw_image": raw_image})) print(out.content) ``` ## 参数说明 ### 鉴权说明 使用组件之前,请首先申请并设置鉴权参数,可参考[组件使用流程](https://cloud.baidu.com/doc/AppBuilder/s/Olq6grrt6#1%E3%80%81%E5%88%9B%E5%BB%BA%E5%AF%86%E9%92%A5)。 ```python # 设置环境中的TOKEN,以下示例略 os.environ["APPBUILDER_TOKEN"] = "bce-YOURTOKEN" ``` ### 初始化参数 无 ### 调用参数 (以表格形式展示) | 参数名称 | 参数类型 | 是否必须 | 描述 | 示例值 | |---------|---------|------|-----------------------------|------------------------------------------------| | message | String | 是 | 输入的消息,用于模型的主要输入内容。这是一个必需的参数 | Message(content={"raw_image": b"待识别的图片字节流数据"}) | |timeout| Float | 否 | HTTP超时时间,单位:秒 |1|| | retry | Integer | 否 | HTTP重试次数 | 3 | ### 响应参数 | 参数名称 | 参数类型 | 描述 | 示例值 | |------------------|---------|---------------|------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| | tables_result | array[] | 返回结果 | [{"table_location": [],"header": [],"body": [],"footer": []}] | | +table_location | array[] | 单个表格的四角点x,y坐标 | [{ "x": 15, "y": 15 },{ "x": 371, "y": 15 },{ "x": 371, "y": 98 },{ "x": 15, "y": 98 }], | | +header | array[] | 表头信息 | [{'location': [{'x': 325, 'y': 40}, {'x': 528, 'y': 40}, {'x': 528, 'y': 71}, {'x': 325, 'y': 71}], 'words': '财务状况变动表'}, {...}] | | +body | array[] | 单元格信息 | [{"cell_location": [{ "x": 15, "y": 15 },{ "x": 120, "y": 15 },{ "x": 120, "y": 58 },{ "x": 15, "y": 58 }],"row_start": 0,"row_end": 1,"col_start": 0,"col_end": 1,"words": "参数"},{...}] | | +footer | array[] | 表尾信息 | [{'location': [...], 'words': '...'}, {...}] | ### 响应示例 ```json { "tables_result": [ { "table_location": [ { "x": 15, "y": 15 }, { "x": 371, "y": 15 }, { "x": 371, "y": 98 }, { "x": 15, "y": 98 } ], "header": [], "body": [ { "cell_location": [ { "x": 15, "y": 15 }, { "x": 120, "y": 15 }, { "x": 120, "y": 58 }, { "x": 15, "y": 58 } ], "row_start": 0, "row_end": 1, "col_start": 0, "col_end": 1, "words": "参数" }, { "cell_location": [ { "x": 120, "y": 15 }, { "x": 371, "y": 15 }, { "x": 371, "y": 58 }, { "x": 120, "y": 58 } ], "row_start": 0, "row_end": 1, "col_start": 1, "col_end": 2, "words": "值" }, { "cell_location": [ { "x": 15, "y": 58 }, { "x": 120, "y": 58 }, { "x": 120, "y": 98 }, { "x": 15, "y": 98 } ], "row_start": 1, "row_end": 2, "col_start": 0, "col_end": 1, "words": "Content-Type" }, { "cell_location": [ { "x": 120, "y": 58 }, { "x": 371, "y": 58 }, { "x": 371, "y": 98 }, { "x": 120, "y": 98 } ], "row_start": 1, "row_end": 2, "col_start": 1, "col_end": 2, "words": "application/x-www-form-urlencoded" } ], "footer": [] } ] } ``` ### 错误码 | 错误码 | 描述 | |-----|----| ## 高级用法 目前该模块仅提供基础的表格文字识别功能。 ## 更新记录和贡献 * 表格文字识别能力 (2024-01) ================================================ FILE: docs/BasisModule/Components/text_to_image/README.md ================================================ # 文生图 (Text2Image) ## 简介 文生图(Text2Image)基于文心大模型,可以根据用户输入的文本,自动创作不限定风格的图,为内容创作者提供灵感和高质量配图。 ### 功能介绍 AI一下,文字成画,AI 精准理解中文文本,支持用户自由输入,只需一句话,让文字秒变精美画作,支持自定义丰富的修饰词,可生成不同风格、不同构图、不同流派的图片,满足个性化的图片生成需求。 ### 特色优势 利用知识增强扩散模型,学习过程融入语言、视觉、跨模态等多源知识,生成图像语义一致性更高,基于混合降噪专家网络,全球最大跨模态生成模型,参数规模达到240亿,根据生成阶段选择最优生成“专家”,从图像轮廓渐进优化细节,全面提升生成质量。 ### 应用场景 图片素材、艺术插图、海报制作、故事插图、壁纸制作、电商应用、室内设计、影视制作、游戏原画设计、服务创意启发平台等。 ## 基本用法 下面是文生图的代码示例: ```python import os import appbuilder # 设置环境变量和初始化 # 请前往千帆AppBuilder官网创建密钥,流程详见:https://cloud.baidu.com/doc/AppBuilder/s/Olq6grrt6#1%E3%80%81%E5%88%9B%E5%BB%BA%E5%AF%86%E9%92%A5 os.environ["APPBUILDER_TOKEN"] = "..." text2Image = appbuilder.Text2Image() content_data = {"prompt": "上海的经典风景", "width": 1024, "height": 1024, "image_num": 1} msg = appbuilder.Message(content_data) out = text2Image.run(msg) print(out.content) #{'img_urls': ['...']} ``` 生成的"上海的经典风景"图片如下 ![示例图片](https://bj.bcebos.com/v1/appbuilder-sdk-components/shanghai.png?authorization=bce-auth-v1%2FALTAKGa8m4qCUasgoljdEDAzLm%2F2024-05-30T03%3A08%3A30Z%2F-1%2Fhost%2F64296a40b3f01d39776129e0b4ce732b1784f2f91e3afcf9dd7c1de8c3df6a0a) ## 参数说明 ### 鉴权配置 使用组件之前,请首先申请并设置鉴权参数,可参考[组件使用流程](https://cloud.baidu.com/doc/AppBuilder/s/Olq6grrt6#1%E3%80%81%E5%88%9B%E5%BB%BA%E5%AF%86%E9%92%A5)。 ```python # 设置环境中的TOKEN,以下示例略 os.environ["APPBUILDER_TOKEN"] = "bce-YOURTOKEN" ``` ### 初始化参数 无 ### 调用参数 |参数名称 |参数类型 |是否必须 |描述 | 示例值 | |--------|--------|--------|----|--------| |message |String |是 |输入的消息,输入的消息,用于模型的主要输入内容。这是一个必需的参数| Message(content={"prompt": "上海的经典风景"}) | |width|Integer|是 |图片宽度,支持:512x512、640x360、360x640、1024x1024、1280x720、720x1280、2048x2048、2560x1440、1440x2560。| 1024 | |height|Integer|是 |图片高度,支持:512x512、640x360、360x640、1024x1024、1280x720、720x1280、2048x2048、2560x1440、1440x2560。| 1024 | |image_num|Integer|是 |生成图片数量,默认一张,支持生成 1-8 张。| 1 | |timeout| Float | 否 | HTTP超时时间,单位:秒 |1|| |retry|Integer|是 |HTTP重试次数| 3 | ### 响应参数 |参数名称 |参数类型 |描述 |示例值| |--------|--------|----|------| |result |String |返回结果|["xxx"]| ### 响应示例 ```json {"img_urls": ["xxx"]} ``` ### 错误码 | 错误码 |描述| |---|---| | 282000 |服务器内部错误,请再次请求, 如果持续出现此类错误,请在控制台提交工单联系技术支持团队| | 282004 |请求中包含敏感词、非法参数、字数超限,或上传违规参考图,请检查后重新尝试| | 282003 |缺少必要参数| | 17 |日配额流量超限| | 18 |QPS 超限额| | 216630 |服务器内部错误,请再次请求,如果持续出现此类错误,请通过工单联系技术支持| | 501 |文本黄反拦截| | 201 |模型生图失败| | 216100 |参数不满足格式要求| | 216201 |参考图不满足格式要求| | 4 |错误信息为中文的“请求超限”指所有用户提交的 AI 作画总数超限制| | 13 |错误信息为中文的“QPS 超限”指单个用户使用提交请求接口的 QPS 超限| | 15 |错误信息为中文的“并发超限”指单个用户使用 AI 作画的并发超限| | 17 |错误信息为中文的“用量超限”指单个用户使用 AI 作画的用量超限| ## 高级用法 目前该模块仅提供基础的文生图功能。 ## 更新记录和贡献 * 文生图能力 (2023-12) ================================================ FILE: docs/BasisModule/Components/translate/README.md ================================================ # 文本翻译-通用版(Translation) ## 简介 文本翻译组件(Translation)提供多种语言互译的在线文本翻译服务。支持术语定制功能,用户可对翻译结果进行干预,快速提高翻译质量。可广泛应用于移动端、PC网站、智能硬件等不同产品形态中,满足多领域、多场景的翻译需求。 ### 功能介绍 支持200+语种互译,传入待翻译内容,并指定源语言(支持语种自动检测)和目标语言,即可获得翻译结果,并支持术语干预。 支持在【创建应用】-【添加工具组件】时,对以下语言的试用: |名称 | 代码 | 名称 | 代码 | 名称 | 代码 | |------------|--------|------------|--------|------------|--------| | 自动检测 | auto | 中文 | zh | 英语 | en | | 粤语 | yue | 文言文 | wyw | 日语 | jp | | 韩语 | kor | 法语 | fra | 西班牙语 | spa | | 泰语 | th | 阿拉伯语 | ara | 俄语 | ru | | 葡萄牙语 | pt | 德语 | de | 意大利语 | it | | 希腊语 | el | 荷兰语 | nl | 波兰语 | pl | | 保加利亚语 | bul | 爱沙尼亚语 | est | 丹麦语 | dan | | 芬兰语 | fin | 捷克语 | cs | 罗马尼亚语 | rom | | 斯洛文尼亚语 | slo | 瑞典语 | swe | 匈牙利语 | hu | | 繁体中文 | cht | 越南语 | vie | | | ### 特色优势 1. 依托互联网数据资源和自然语言处理技术优势,上线全球首个互联网神经网络翻译系统,日均响应千亿字符请求 2. 2019国际机器翻译评测(WMT19)中,获得中英翻译第一,提供业界领先的机器翻译服务 3. 支持用户上传术语对翻译结果进行干预,优化翻译质量,用户可根据不同产品、不同领域创建多个术语库 4. 翻译请求可实现实时响应,服务稳定性高,在海外也可及时获取翻译结果,保障用户稳定的服务体验 ### 应用场景 1. 教育学习:在外语教学及学习场景中,通过实时句子翻译、单词释义、语音合成等功能,帮助师生沟通、外教课后点评,辅助阅读和写作,全面提升学习效率与质量 2. 手机厂商:应用于手机系统中,实现手机系统取词翻译、对话文本翻译等服务。为手机应用开发者提供便捷的翻译功能 3. 跨境电商:在商业全球化背景下,针对跨国商贸服务中产品名称、详情页等网站基本信息进行翻译,助力企业开拓国际市场 4. 智能硬件:应用于翻译机、学习机、智能手表等硬件系统中,为用户提供文本翻译、词典及语音合成等能力,实现便捷准确的多语种互译功能 ## 基本用法 通过如下示例代码可以快速开始使用文本翻译组件: ```python import os import appbuilder # 请前往千帆AppBuilder官网创建密钥,流程详见:https://cloud.baidu.com/doc/AppBuilder/s/Olq6grrt6#1%E3%80%81%E5%88%9B%E5%BB%BA%E5%AF%86%E9%92%A5 os.environ["APPBUILDER_TOKEN"] = '...' translate = appbuilder.Translation() resp = translate(appbuilder.Message("你好\n中国"), from_lang="zh", to_lang="en") # 输出{'from_lang': 'zh', 'to_lang': 'en', 'trans_result': [{'src': '你好', 'dst': 'hello'}, {'src': '中国', 'dst': 'China'}]} print(resp.content) ``` ## 参数说明 ### 鉴权配置 使用组件之前,请首先申请并设置鉴权参数,可参考[组件使用流程](https://cloud.baidu.com/doc/AppBuilder/s/Olq6grrt6#1%E3%80%81%E5%88%9B%E5%BB%BA%E5%AF%86%E9%92%A5)。 ```python # 设置环境中的TOKEN,以下示例略 os.environ["APPBUILDER_TOKEN"] = "bce-YOURTOKEN" ``` ### 初始化参数说明 无 ### 调用参数说明 |参数名称 |参数类型 |是否必须 |描述 | 示例值 | |--------|--------|--------|----|--------| |message |obj:`Message` |是 |输入的请求翻译文本| Message("你好") | |from_lang|String|否 |翻译的源语言,默认为`auto`,表示自动检测语言。| zh | |to_lang|Integer|否 |需要翻译的目标语言,默认为`en`,表示英语。| en | |timeout| Float | 否 | HTTP超时时间,单位:秒 |1|| |retry|Integer|否 |HTTP重试次数| 3 | ### 响应参数 |参数名称 |参数类型 |描述 |示例值| |--------|--------|----|------| |from_lang |String |翻译源语言| zh| |to_lang |String |翻译目标语言|en| |trans_result |List[Object] |返回结果|[{'src': '你好', 'dst': 'hello'}]| |trans_result[0].src |String |源文本|你好| |trans_result[0].dst |String |目标文本|hello| ### 响应示例 ```json { "from_lang": "zh", "to_lang": "en", "trans_result": [ { "src": "你好", "dst": "hello" } ] } ``` ### 错误码 |错误码|描述| |------|---| ## 更新记录和贡献 * 文本翻译-通用版 (2024-01) ## 语种列表 |名称 |代码 |语种检测| |----|-----|------| | 阿拉伯语 | ara | 是 | | 爱尔兰语 | gle | 是 | | 奥克语 | oci | 是 | | 阿尔巴尼亚语 | alb | 是 | | 阿尔及利亚阿拉伯语 | arq | 否 | | 阿肯语 | aka | 否 | | 阿拉贡语 | arg | 否 | | 阿姆哈拉语 | amh | 是 | | 阿萨姆语 | asm | 是 | | 艾马拉语 | aym | 否 | | 阿塞拜疆语 | aze | 是 | | 阿斯图里亚斯语 | ast | 是 | | 奥塞梯语 | oss | 否 | | 爱沙尼亚语 | est | 是 | | 奥杰布瓦语 | oji | 否 | | 奥里亚语 | ori | 是 | | 奥罗莫语 | orm | 否 | | 波兰语 | pl | 是 | | 波斯语 | per | 是 | | 布列塔尼语 | bre | 是 | | 巴什基尔语 | bak | 否 | | 巴斯克语 | baq | 是 | | 巴西葡萄牙语 | pot | 否 | | 白俄罗斯语 | bel | 是 | | 柏柏尔语 | ber | 是 | | 邦板牙语 | pam | 否 | | 保加利亚语 | bul | 是 | | 北方萨米语 | sme | 否 | | 北索托语 | ped | 否 | | 本巴语 | bem | 否 | | 比林语 | bli | 否 | | 比斯拉马语 | bis | 否 | | 俾路支语 | bal | 否 | | 冰岛语 | ice | 是 | | 波斯尼亚语 | bos | 是 | | 博杰普尔语 | bho | 否 | | 楚瓦什语 | chv | 否 | | 聪加语 | tso | 否 | | 丹麦语 | dan | 是 | | 德语 | de | 是 | | 鞑靼语 | tat | 是 | | 掸语 | sha | 否 | | 德顿语 | tet | 否 | | 迪维希语 | div | 否 | | 低地德语 | log | 是 | | 俄语 | ru | 是 | | 法语 | fra | 是 | | 菲律宾语 | fil | 是 | | 芬兰语 | fin | 是 | | 梵语 | san | 否 | | 弗留利语 | fri | 否 | | 富拉尼语 | ful | 否 | | 法罗语 | fao | 否 | | 盖尔语 | gla | 否 | | 刚果语 | kon | 否 | | 高地索布语 | ups | 否 | | 高棉语 | hkm | 是 | | 格陵兰语 | kal | 否 | | 格鲁吉亚语 | geo | 是 | | 古吉拉特语 | guj | 是 | | 古希腊语 | gra | 否 | | 古英语 | eno | 否 | | 瓜拉尼语 | grn | 否 | | 韩语 | kor | 是 | | 荷兰语 | nl | 是 | | 胡帕语 | hup | 否 | | 哈卡钦语 | hak | 否 | | 海地语 | ht | 否 | | 豪萨语 | hau | 否 | | 黑山语 | mot | 否 | | 吉尔吉斯语 | kir | 否 | | 加利西亚语 | glg | 是 | | 加拿大法语 | frn | 否 | | 加泰罗尼亚语 | cat | 是 | | 捷克语 | cs | 是 | | 卡拜尔语 | kab | 是 | | 卡纳达语 | kan | 是 | | 卡努里语 | kau | 否 | | 卡舒比语 | kah | 否 | | 康瓦尔语 | cor | 否 | | 科萨语 | xho | 是 | | 科西嘉语 | cos | 否 | | 克里克语 | cre | 否 | | 克里米亚鞑靼语 | cri | 否 | | 克林贡语 | kli | 否 | | 克罗地亚语 | hrv | 是 | | 克丘亚语 | que | 否 | | 克什米尔语 | kas | 否 | | 孔卡尼语 | kok | 否 | | 库尔德语 | kur | 是 | | 拉丁语 | lat | 是 | | 老挝语 | lao | 否 | | 罗马尼亚语 | rom | 是 | | 拉特加莱语 | lag | 否 | | 拉脱维亚语 | lav | 是 | | 林堡语 | lim | 否 | | 林加拉语 | lin | 否 | | 卢干达语 | lug | 否 | | 卢森堡语 | ltz | 否 | | 卢森尼亚语 | ruy | 否 | | 卢旺达语 | kin | 是 | | 立陶宛语 | lit | 是 | | 罗曼什语 | roh | 否 | | 罗姆语 | ro | 否 | | 逻辑语 | loj | 否 | | 马来语 | may | 是 | | 缅甸语 | bur | 是 | | 马拉地语 | mar | 否 | | 马拉加斯语 | mg | 是 | | 马拉雅拉姆语 | mal | 是 | | 马其顿语 | mac | 是 | | 马绍尔语 | mah | 否 | | 迈蒂利语 | mai | 是 | | 曼克斯语 | glv | 否 | | 毛里求斯克里奥尔语 | mau | 否 | | 毛利语 | mao | 否 | | 孟加拉语 | ben | 是 | | 马耳他语 | mlt | 是 | | 苗语 | hmn | 否 | | 挪威语 | nor | 是 | | 那不勒斯语 | nea | 否 | | 南恩德贝莱语 | nbl | 否 | | 南非荷兰语 | afr | 是 | | 南索托语 | sot | 否 | | 尼泊尔语 | nep | 是 | | 葡萄牙语 | pt | 是 | | 旁遮普语 | pan | 是 | | 帕皮阿门托语 | pap | 否 | | 普什图语 | pus | 否 | | 齐切瓦语 | nya | 否 | | 契维语 | twi | 否 | | 切罗基语 | chr | 否 | | 日语 | jp | 是 | | 瑞典语 | swe | 是 | | 萨丁尼亚语 | srd | 否 | | 萨摩亚语 | sm | 否 | | 塞尔维亚-克罗地亚语 | sec | 否 | | 塞尔维亚语 | srp | 是 | | 桑海语 | sol | 否 | | 僧伽罗语 | sin | 是 | | 世界语 | epo | 是 | | 书面挪威语 | nob | 是 | | 斯洛伐克语 | sk | 是 | | 斯洛文尼亚语 | slo | 是 | | 斯瓦希里语 | swa | 是 | | 索马里语 | som | 是 | | 塞尔维亚语(西里尔) | src | 否 | | 泰语 | th | 是 | | 土耳其语 | tr | 是 | | 塔吉克语 | tgk | 是 | | 泰米尔语 | tam | 是 | | 他加禄语 | tgl | 是 | | 提格利尼亚语 | tir | 否 | | 泰卢固语 | tel | 是 | | 突尼斯阿拉伯语 | tua | 否 | | 土库曼语 | tuk | 否 | | 乌克兰语 | ukr | 是 | | 瓦隆语 | wln | 是 | | 威尔士语 | wel | 是 | | 文达语 | ven | 否 | | 沃洛夫语 | wol | 否 | | 乌尔都语 | urd | 是 | | 西班牙语 | spa | 是 | | 希伯来语 | heb | 是 | | 希腊语 | el | 是 | | 匈牙利语 | hu | 是 | | 西弗里斯语 | fry | 是 | | 西里西亚语 | sil | 否 | | 希利盖农语 | hil | 否 | | 下索布语 | los | 否 | | 夏威夷语 | haw | 否 | | 新挪威语 | nno | 是 | | 西非书面语 | nqo | 否 | | 信德语 | snd | 否 | | 修纳语 | sna | 否 | | 宿务语 | ceb | 否 | | 叙利亚语 | syr | 否 | | 巽他语 | sun | 否 | | 英语 | en | 是 | | 印地语 | hi | 是 | | 印尼语 | id | 是 | | 意大利语 | it | 是 | | 越南语 | vie | 是 | | 意第绪语 | yid | 否 | | 因特语 | ina | 否 | | 亚齐语 | ach | 否 | | 印古什语 | ing | 否 | | 伊博语 | ibo | 否 | | 伊多语 | ido | 否 | | 约鲁巴语 | yor | 否 | | 亚美尼亚语 | arm | 是 | | 伊努克提图特语 | iku | 否 | | 中文(简体) | zh | 是 | | 中文(繁体) | cht | 是 | | 中文(文言文) | wyw | 是 | | 中文(粤语) | yue | 是 | | 扎扎其语 | zaz | 否 | | 中古法语 | frm | 否 | | 祖鲁语 | zul | 否 | | 爪哇语 | jav | 否 | ================================================ FILE: docs/BasisModule/Components/tree_mind/README.md ================================================ # 树图 (TreeMind) ## 简介 树图(TreeMind)提供智能思维导图制作工具和丰富的模板,支持脑图、逻辑图、树形图、鱼骨图、组织架构图、时间轴、时间线等多种专业格式。 ### 功能介绍 树图(TreeMind)是一款智能思维导图制作工具,它提供了一个用户友好的平台来创建和编辑各种类型的图表。该工具支持多种专业格式,包括脑图、逻辑图、树形图、鱼骨图、组织架构图、时间轴和时间线等,满足不同用户在不同场景下的需求。 ### 特色优势 TreeMind提供丰富的模板,支持多种图表格式,用户可以根据个人需求自由编辑和调整图表。 ### 应用场景 年度总结:用户可以利用TreeMind生成年度总结的思维导图,整理和回顾一年的工作成果和经验教训。 项目管理:在项目管理中,TreeMind可以用来规划项目流程、组织架构和时间线,确保项目按计划进行。 教育和学习:教师和学生可以使用TreeMind来创建课程大纲、学习笔记和复习资料,提高学习效率。 商业策划:商业人士可以利用TreeMind来制定商业策略、市场分析和竞争对手分析等。 会议记录:在会议中,TreeMind可以作为记录工具,帮助整理会议要点和行动计划。 ## 基本用法 下面是文生图的代码示例: ```python import os import appbuilder # 设置环境变量和初始化 # 请前往千帆AppBuilder官网创建密钥,流程详见:https://cloud.baidu.com/doc/AppBuilder/s/Olq6grrt6#1%E3%80%81%E5%88%9B%E5%BB%BA%E5%AF%86%E9%92%A5 os.environ["APPBUILDER_TOKEN"] = "..." treemind = appbuilder.TreeMind() query = "生成一份年度总结的思维导图" msg = appbuilder.Message(query) out = treemind.run(msg) print(out.content) >>> {'result': '思维导图已经为您生成好了,您可以点击'img_link'对应的链接查看,如果您觉得这个思维导图还不够完美,或者您的想法需要更自由地表达,点击'edit_link'对应的链接,对思维导图变形、变色、变内容、甚至可以添加新的元素, 'img_link': 'https://static.shutu.cn/shutu/static/open6e/2024/05/24/dbd67eddec13f3a6a75857b9c6e06d85.jpeg', 'edit_link': 'https://gapi.shutu.cn/ai/edit-mind-url?works_guid=open5ab4af46187ff7c138fcd95de09efe92_bdappbuilder'} ``` 生成的思维导图:
![图片url](https://bj.bcebos.com/appbuilder-sdk-components/TreeMind-年终总结思维导图.jpeg) ## 参数说明 ### 鉴权配置 使用组件之前,请首先申请并设置鉴权参数,可参考[组件使用流程](https://cloud.baidu.com/doc/AppBuilder/s/Olq6grrt6#1%E3%80%81%E5%88%9B%E5%BB%BA%E5%AF%86%E9%92%A5)。 ```python # 设置环境中的TOKEN,以下示例略 os.environ["APPBUILDER_TOKEN"] = "bce-YOURTOKEN" ``` ### 初始化参数 无 ### 调用参数 | 参数名称 | 参数类型 | 是否必须 | 描述 | 示例值 | |---------|---------|------|-----------------------------|------------------------------------------------| | message | obj:`Message` | 是 | 输入的消息,用于生成思维导图,这是一个必需的参数 | Message(content={"query": "生成一张年终总结的思维导图"}) | ### 响应参数 | 参数名称 |参数类型 | 描述 | 示例值 | |-------------|--------|------|------| | resp | obj:`Message` | 组件返回结果 | Message(name=msg, content={'result': '生成的思维导图:xxx。思维导图已经为您生成好了,如果您觉得这个思维导图还不够完美,或者您的想法需要更自由地表达,点击编辑按钮,对思维导图变形、变色、变内容、甚至可以添加新的元素,您可以通过这个链接编辑:xxx。', 'img_link': 'xxx', 'edit_link': 'xxx'}, mtype=dict) | ================================================ FILE: docs/BasisModule/Components/tts/README.md ================================================ # 短文本在线合成(TTS) ## 简介 短文本在线合成组件(TTS)提供高度拟人、流畅自然的语音合成服务,将文本朗读出来,基础音库性价比更高,精品音库听感更逼真。 ### 功能介绍 提供高度拟人、流畅自然的语音合成服务。 ### 特色优势 将文本朗读出来,基础音库性价比更高,精品音库听感更逼真。可实时生成语音输出,几乎没有延迟,更加自然流畅。 ### 应用场景 文本朗读 ## 基本用法 下面是语音合成的代码示例: ```python import os import appbuilder # 请前往千帆AppBuilder官网创建密钥,流程详见:https://cloud.baidu.com/doc/AppBuilder/s/Olq6grrt6#1%E3%80%81%E5%88%9B%E5%BB%BA%E5%AF%86%E9%92%A5 os.environ["APPBUILDER_TOKEN"] = "bce-YOURTOKEN" tts = appbuilder.TTS() cwd = os.getcwd() # 使用baidu-tts模型, 默认返回MP3格式 inp = appbuilder.Message(content={"text": "欢迎使用语音合成"}) out = tts.run(inp) mp3_sample_path = os.path.join(cwd,"sample.mp3") with open(mp3_sample_path, "wb") as f: f.write(out.content["audio_binary"]) print("成功将文本转语音,mp3格式文件已写入:{}".format(mp3_sample_path)) # 使用paddlespeech-tts模型,目前只支持返回WAV格式 wav_sample_path = os.path.join(cwd,"sample.wav") inp = appbuilder.Message(content={"text": "欢迎使用语音合成"}) out = tts.run(inp, model="paddlespeech-tts", audio_type="wav") with open(wav_sample_path, "wb") as f: f.write(out.content["audio_binary"]) print("成功将文本转语音,wav格式文件已写入:{}".format(wav_sample_path)) ``` ## 参数说明 ### 鉴权说明 使用组件之前,请首先申请并设置鉴权参数,可参考[组件使用流程](https://cloud.baidu.com/doc/AppBuilder/s/Olq6grrt6#1%E3%80%81%E5%88%9B%E5%BB%BA%E5%AF%86%E9%92%A5)。 ```python import os os.environ["APPBUILDER_TOKEN"] = "..." ``` ### 初始化参数 无 ### 调用参数 | 参数名称 | 参数类型 | 是否必须 | 描述 | 示例值 | |------------|---------|------|------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|-------------------------------------| | message | String | 是 | 待转成语音的文本 | Message(content={"text": "需合成的文本"}) | | model | String | 否 | 默认是`baidu-tts`模型,可选值:`paddlespeech-tts`、`baidu-tts` | paddlespeech-tts | | speed | Integer | 否 | 语音语速,默认是5中等语速,取值范围在0~15之间,仅当模型为`baidu-tts`参数有效,如果模型为`paddlespeech-tts`,参数自动失效 | 5 | | pitch | Integer | 否 | 语音音调,默认是5中等音调,取值范围在0~15之间,仅当模型为`baidu-tts`参数有效,如果模型为`paddlespeech-tts`,参数自动失效 | 5 | | volume | Integer | 否 | 语音音量,默认是5中等音量,取值范围在0~15之间,,仅当模型为`baidu-tts`参数有效,如果模型为`paddlespeech-tts`,参数自动失效 | 5 | | person | Integer | 否 | 语音人物特征,默认是0(度小美),普通音库可选值包括: 0(度小美)、1(度小宇)、3(度逍遥-基础)、4(度丫丫);精品音库包括:5003(度逍遥-精品)、5118(度小鹿)、106(度博文)、110(度小童)、111(度小萌)、103(度米朵)、5(度小娇);臻品音库包括:4003(度逍遥-情感男声)、4106(度博文-专业男主播)、4115(度小贤-电台男主播)、4119(度小鹿-甜美女声)、4105(度灵儿-清激女声)、4117(度小乔-活泼女声)、4100(度小雯-活力女主播)、4103(度米朵-可爱女声)、4144(度姗姗-娱乐女声)、4278(度小贝-知识女主播)、4143(度清风-配音男声)、4140(度小新-专业女主播)、4129(度小彦-知识男主播)、4149(度星河-广告男声)、4254(度小清-广告女声)、4206(度博文-综艺男声)、4226(南方-电台女主播)。仅当模型为`baidu-tts`参数有效,如果模型为`paddlespeech-tts`,参数自动失效 | 0 | | audio_type | String | 否 | 音频文件格式,如果使用`baidu-tts`模型可选`mp3`, `wav`; 如果使用`paddlespeech-tts`模型非流式返回,参数只能设为`wav`;如果使用`paddlespeech-tts`模型流式返回,参数只能设为`pcm` | wav | | stream | Bool | 否 | 默认是False, 目前`paddlespeech-tts`模型支持流式返回,`baidu-tts`模型不支持流式返回 | False | | retry | Integer | 否 | HTTP重试次数 | 3 | | timeout | Integer | 否 | HTTP超时时间 | 5 | ### 非流式语音响应参数 | 参数名称 | 参数类型 | 描述 | 示例值 | |---------------|--------|--------|---------| | content | Dict | 消息内容 | 无 | | +audio_binary | Bytes | 音频二进制流 | b'语音流' | | +audio_type | String | 音频类型 | wav/mp3 | ### 流式语音响应参数 | 参数名称 | 参数类型 | 描述 | 示例值 | |---------|------------------|----------|-----| | content | Python Generator | 可迭代的二进制流 | 无 | ### 响应示例 ```json { "content": { "audio_binary": "", "audio_type": "mp3" } } ``` ### 错误码 | 错误码 | 描述 | |-----|----| ## 高级用法 ### TTS实时播放语音流 ```python import os import appbuilder import pyaudio # 请前往千帆AppBuilder官网创建密钥,流程详见:https://cloud.baidu.com/doc/AppBuilder/s/Olq6grrt6#1%E3%80%81%E5%88%9B%E5%BB%BA%E5%AF%86%E9%92%A5 os.environ["APPBUILDER_TOKEN"] = "bce-YOURTOKEN" tts = appbuilder.TTS() # 使用paddlespeech-tts模型,目前只支持返回WAV格式 inp = appbuilder.Message(content={"text": """随着科技的迅速发展,教育领域也经历了巨大的变革。科技不仅改变了教学和学习的方式,还扩展了教育的可能性和边界。 从在线课程到交互式学习工具,科技为学生和教师提供了前所未有的资源和机遇。科技使得个性化学习成为可能。通过智能学习系统和适应性学习技术, 教育内容可以根据学生的学习速度和能力进行定制。"""}) # 仅支持model为paddlespeech-tts,audio_type为pcm, stream为True out = tts.run(inp, model="paddlespeech-tts", audio_type="pcm", stream=True) play = pyaudio.PyAudio() stream = play.open(format=play.get_format_from_width(2), channels=1, rate=24000, output=True, frames_per_buffer=2048) # 实时播放语音流 for pcm in out.content: stream.write(pcm) stream.stop_stream() stream.close() ``` ### pcm文件转wav ```python import os import appbuilder import wave # 请前往千帆AppBuilder官网创建密钥,流程详见:https://cloud.baidu.com/doc/AppBuilder/s/Olq6grrt6#1%E3%80%81%E5%88%9B%E5%BB%BA%E5%AF%86%E9%92%A5 os.environ["APPBUILDER_TOKEN"] = "bce-YOURTOKEN" tts = appbuilder.TTS() inp = appbuilder.Message(content={"text": """随着科技的迅速发展,教育领域也经历了巨大的变革。科技不仅改变了教学和学习的方式,还扩展了教育的可能性和边界。 从在线课程到交互式学习工具,科技为学生和教师提供了前所未有的资源和机遇。科技使得个性化学习成为可能。通过智能学习系统和适应性学习技术, 教育内容可以根据学生的学习速度和能力进行定制。"""}) # 仅支持model为paddlespeech-tts,audio_type为pcm, stream为True out = tts.run(inp, model="paddlespeech-tts", audio_type="pcm", stream=True) count = 1 cwd = os.getcwd() for pcm in out.content: wave_sample_path = os.path.join(cwd, "{}.wav".format(count)) wavfile = wave.open(wave_sample_path, 'wb') wavfile.setnchannels(1) wavfile.setsampwidth(2) wavfile.setframerate(24000) wavfile.writeframes(pcm) wavfile.close() print("成功将第{}个pcm语音块转换成wav格式,并将对应文件写入:{}".format(count, wave_sample_path)) count += 1 ``` ## 更新记录和贡献 * 短文本在线合成 (2024-01) * 增加流式能力 (2024-02) ================================================ FILE: docs/BasisModule/Deployment/AgentChainlit.md ================================================ # 交互式前端部署 ## 基础组件基于Chainlit提供交互式前端页面 请参考 [组件服务化部署](https://github.com/baidubce/app-builder/blob/master/cookbooks/components/agent_runtime.ipynb) ================================================ FILE: docs/BasisModule/Deployment/agentruntime.md ================================================ # `AgentRuntime`类 ## 简介 AgentRuntime 是对组件调用的服务化封装,开发者不是必须要用 AgentRuntime 才能运行自己的组件服务。但 AgentRuntime 可以快速帮助开发者服务化组件服务,并且提供API、对话框等部署方式。此外,结合 Component 和 Message 自带的运行和调试接口,可以方便开发者快速获得一个调试 Agent 的服务。 ## Python基本用法 ### 1、实例化`AgentRuntime() -> AgentRuntime` #### 方法参数 | 参数名称 | 参数类型 | 描述 | 示例值 | |--------|--------|------------|-----------| | component | Component | 可运行的 Component,需要实现 run(message, stream, **args) 方法 | "正确的component组件或client" | | user_session_config | sqlalchemy.engine.URL、str、None | Session 输出存储配置字符串。默认使用 sqlite:///user_session.db | "正确的存储配置字符串" | #### 方法功能 返回一个调试 Agent 的服务 #### 示例代码 ```python import os import appbuilder os.environ["APPBUILDER_TOKEN"] = '...' component = appbuilder.Playground( prompt_template="{query}", model="eb-4" ) agent = appbuilder.AgentRuntime(component=component) ``` ### 2、运行Agent服务`AgentRuntime.chat(message: Message, stream: bool = False, **args) -> Message` #### 方法参数 | 参数名称 | 参数类型 | 描述 | 示例值 | |--------|--------|------------|-----------| | message | Message | 该次对话用户输入的 Message | "正确的Message" | | stream | bool | 是否使用流式请求。默认为 False | False | #### 方法功能 运行一个 Agent 服务,执行一次对话 #### 示例代码 ```python import os import appbuilder os.environ["APPBUILDER_TOKEN"] = '...' component = appbuilder.Playground( prompt_template="{query}", model="eb-4" ) agent = appbuilder.AgentRuntime(component=component) message = appbuilder.Message({"query": "你好"}) print(agent.chat(message, stream=False)) ``` ### 3、提供 Flask http API 接口`AgentRuntime.serve(self, host='0.0.0.0', debug=True, port=8092, url_rule="/chat"` #### 方法参数 | 参数名称 | 参数类型 | 描述 | 示例值 | |--------|--------|------------|-----------| | host | String | 服务主机地址,默认为 '0.0.0.0' | '0.0.0.0' | | debug | bool | 是否是调试模式,默认为 True | False | | port | int | 服务端口号,默认为 8092 | 8092 | | url_rule | String | Flask 路由规则,默认为 '/chat' | '/chat' | #### 方法功能 将 component 服务化,提供 Flask http API 接口 #### 示例代码 ```python import os import appbuilder os.environ["APPBUILDER_TOKEN"] = '...' component = appbuilder.Playground( prompt_template="{query}", model="eb-4" ) user_session_config = "sqlite:///foo.db" agent = appbuilder.AgentRuntime( component=component, user_session_config=user_session_config) agent.serve(debug=False, port=8091) ``` ### 4、提供 chainlit demo 页面`AgentRuntime.chainlit_demo(host='0.0.0.0', port=8091)` #### 方法参数 | 参数名称 | 参数类型 | 描述 | 示例值 | |--------|--------|------------|-----------| | host | string | 服务主机地址,默认为 '0.0.0.0' | "0.0.0.0" | | port | int | 服务端口号,默认为 8092 | 8091 | #### 方法功能 将 component 服务化,提供 chainlit demo 页面 #### 示例代码 ```python import os import logging from appbuilder.core.component import Component from appbuilder import ( AgentRuntime, UserSession, Message, QueryRewrite, Playground, ) os.environ["APPBUILDER_TOKEN"] = 'YOUR_APPBUILDER_TOKEN' class PlaygroundWithHistory(Component): def __init__(self): super().__init__() self.query_rewrite = QueryRewrite(model="DeepSeek-V3.1") self.play = Playground( prompt_template="{query}", model="eb-4" ) def run(self, message: Message, stream: bool=False): user_session = UserSession() # 获取 Session 历史数据 history_queries = user_session.get_history("query", limit=1) history_answers = user_session.get_history("answer", limit=1) if history_queries and history_answers: history = [] for query, answer in zip(history_queries, history_answers): history.extend([query.content, answer.content]) logging.info(f"history: {history}") message = self.query_rewrite( Message(history + [message.content]), rewrite_type="带机器人回复") logging.info(f"message: {message}") answer = self.play.run(message, stream) # 保存本轮数据 user_session.append({ "query": message, "answer": answer, }) return answer agent = AgentRuntime(component=PlaygroundWithHistory()) agent.chainlit_demo(port=8091) ``` ### 5、将 appbuilder client 服务化,提供 chainlit demo 页面`AgentRuntime.chainlit_agent(host='0.0.0.0', port=8091)` 目前支持工作流Agent、自主规划Agent应用。 #### 方法参数 | 参数名称 | 参数类型 | 描述 | 示例值 | |--------|--------|------------|-----------| | host | string | 服务主机地址,默认为 '0.0.0.0' | "0.0.0.0" | | port | int | 服务端口号,默认为 8092 | 8091 | #### 方法返回值 将 appbuilder client 服务化,提供 chainlit demo 页面 #### 示例代码 ```python import appbuilder import os os.environ["APPBUILDER_TOKEN"] = '...' app_id = '...' # 已发布AppBuilder应用ID,可在console端查看 client = appbuilder.AppBuilderClient(app_id) agent = appbuilder.AgentRuntime(component=client) agent.chainlit_agent(port=8091) ``` ================================================ FILE: docs/BasisModule/Deployment/cloud.md ================================================ # 公有云部署 **注意⚠️:部署上云功能目前处于内测阶段,使用过程中有任何问题,欢迎提issue或微信群反馈~** 支持一键将自己的服务部署到公有云上,目前支持百度智能云。部署后可以自动生成公网ip,无需额外配置。可以用来解决以下问题: * 在百度云部署的WebService,可以引入到AppBuilder工作流中的API节点,形成应用中嵌套应用,构建能够解决复杂业务问题的工作流。 * 可将自己本地复杂的服务、组件、模型等,方便快捷地上云,并与AppBuilder形成联动。 * etc. ### 前置操作: * 在百度智能云完成实名认证,并开通bos服务: * https://cloud.baidu.com/doc/BOS/s/Jk4xttg03#%E5%BC%80%E9%80%9Abos%E6%9C%8D%E5%8A%A1 * 您需要在钱包中至少充值100元,用于bcc服务、bos服务费用 * 云服务费用标准:https://cloud.baidu.com/product-price/bcc.html * 默认配置使用最便宜的bcc.e1.c2m2,并且使用按量付费 * bos存储服务费用标准:https://cloud.baidu.com/product-price/bos.html * 通过如下步骤获得您的AK/SK信息: * https://cloud.baidu.com/doc/Reference/s/9jwvz2egb ### 部署流程: * 以下面的yaml文件为模板创建config.yaml,完善配置文件 * 最小修改范围:ak、sk、admin_pass、run_cmd、local_dir、APPBUILDER_TOKEN ```yaml bce_config: host: "http://bcc.bj.baidubce.com" bos_host: "bj.bcebos.com" # 前置操作获取的ak、sk ak: "" sk: "" spec: "bcc.e1.c2m2" root_disk_size_in_gb: 20 # 服务器密码,根据实际使用设置 admin_pass: "" security_group_id: "" zone_name: cn-bj-d appbuilder_config: # 本地用来打包的代码路径,根据实际使用修改 local_dir: "./sample" workspace: "/home/work/appbuilder" # 服务的运行命令,根据实际使用修改 run_cmd: "python3 component_sample.py" env: APPBUILDER_LOGLEVEL: debug APPBUILDER_TOKEN: "" ``` * 编写自己的服务运行代码(以组件服务为例) ```bash mkdir sample touch sample/component_sample.py # 编辑sample/component_sample.py,写入下面的python代码 ``` ```python # ./smaple目录下component_sample.py import appbuilder component = appbuilder.Playground(prompt_template="{query}", model="ERNIE-Bot") agent = appbuilder.AgentRuntime(component=component) agent.serve(port=8091) ``` * 执行部署 ```bash # config.yaml为上面创建的配置文件 appbuilder_bce_deploy --conf ./config.yaml ``` ### 请求示例: * 取日志 “deployment finished! public ip:”后的ip * 稍等两到三分钟,服务启动后即可访问 ``` bash # public_ip为上一步取到的ip curl --location 'http://{public_ip}:8091/chat' \ --header 'Content-Type: application/json' \ --data '{ "message": "海淀区的面积是多少", "stream": false }' ``` * 返回结果 ```json { "code": 0, "message": "", "result": { "answer_message": { "content": "海淀区位于北京市的西部和西北部,其面积的具体数据在不同来源中略有差异。根据参考文章,可以归纳出以下信息:\n\n* 海淀区的面积约为**431平方千米**(来源于参考文章1)。\n* 另一数据为**430.8平方公里**(来源于参考文章2)。\n* 首都之窗_北京市人民政府门户网站的数据为**430.77平方公里**(来源于参考文章3)。\n* 海淀区台办的数据也提到其面积为**430.8平方公里**(来源于参考文章4)。\n\n综上所述,海淀区的面积大致在**430.77至431平方千米**之间。这些细微的差异可能是由于测量方法和时间的不同导致的。在大多数情况下,可以认为海淀区的面积是约431平方千米。", "extra": {}, ... }, "session_id": "xxx" } } ``` * 若返回结果不符合预期,使用自己的"admin_pass"登陆服务器进行调试,具体参考文档:https://cloud.baidu.com/doc/BCC/s/Hkbblll70 ### 接入AppBuilder工作流示例: * 进入AppBuilder官网,先后点击“个人空间”、“组件”、“创建组件”、“API接入” wechat * 点击“编辑API”、“导入cURL”,粘贴上面的curl命令,解析并导入 wechat * 调试通过 wechat ================================================ FILE: docs/BasisModule/Deployment/flask.md ================================================ # API 访问 ## 基础组件基于Flask提供 API访问服务 请参考 [组件服务化部署](https://github.com/baidubce/app-builder/blob/master/cookbooks/components/agent_runtime.ipynb) ================================================ FILE: docs/BasisModule/Deployment/usersession.md ================================================ # `UserSession`类 ## 简介 会话数据管理工具,实例化后将是一个全局变量。提供保存对话数据与获取历史数据的方法。 ## 应用场景 **必须**在 AgentRuntime 启动的服务中使用。 ## Python基本用法 ### 1、实例化`UserSession().__init__ -> UserSession` #### 方法参数 | 参数名称 | 参数类型 | 描述 | 示例值 | |--------|--------|------------|-----------| | user_session_config | sqlalchemy.engine.URL、str、None | Session 输出存储配置字符串。默认使用 sqlite:///user_session.db | "正确的存储配置字符串" | #### 方法功能 初始化 UserSession #### 示例代码 ```python user_session = UserSession() ``` ### 2、获取同个 session 中名为 key 的历史变量`UserSession().get_history(self, key: str, limit: int=10) -> List[Message]:` #### 方法参数 | 参数名称 | 参数类型 | 描述 | 示例值 | |--------|--------|------------|-----------| | key | String | 历史变量 | "answer" | | limit | int | 最近 limit 条 Message 数据 | 10 | #### 方法功能 获取同个 session 中名为 key 的历史变量。在非服务化版本中从内存获取。在服务化版本中,将从数据库获取。 #### 方法返回值 `List[Message]` 衍生类`Message`定义如下: ```python class Message(BaseModel, Generic[_T], extra=Extra.allow): content: Optional[_T] = {} name: Optional[str] = "msg" mtype: Optional[str] = "dict" id: Optional[str] = str(uuid.uuid4()) ``` #### 示例代码 ```python history_queries = user_session.get_history("query", limit=1) ``` ### 3、将 message_dict 中的变量保存到 session 中`UserSession().append(self, message_dict: Dict[str, Message]) -> None` #### 方法参数 | 参数名称 | 参数类型 | 描述 | 示例值 | |--------|--------|------------|-----------| | message_dict | Dict | 包含 Message 的字典,其中键为字符串类型,值为 Message 类型 | {"query": message} | #### 方法功能 将 message_dict 中的变量保存到 session 中。在非服务化版本中使用内存存储。在服务化版本中,将使用数据库进行存储。 #### 示例代码 ```python user_session.append({ "query": message, "answer": answer, }) ``` ### 4、UserSession结合AgentRuntime使用以及user_session.db文件读取 - [UserSession结合AgentRuntime使用以及user_session.db文件读取](https://github.com/baidubce/app-builder/blob/master/cookbooks/components/agent_runtime.ipynb) ================================================ FILE: docs/BasisModule/Model/get_model_list.md ================================================ # 千帆模型列表获取能力 ## 简介 该能力可以通过参数控制获取用户可用的不同类型的千帆大模型名称,从而进行大模型组件的调用,该能力获取的模型名称可以直接传参到大模型组件的model字段。 ## 基本用法 下面是模型列表获取功能的代码示例: ```python import os import appbuilder # 设置环境变量和初始化 # 请前往千帆AppBuilder官网创建密钥,流程详见:https://cloud.baidu.com/doc/AppBuilder/s/Olq6grrt6#1%E3%80%81%E5%88%9B%E5%BB%BA%E5%AF%86%E9%92%A5 os.environ["APPBUILDER_TOKEN"] = "..." models = appbuilder.get_model_list( secret_key=os.environ["APPBUILDER_TOKEN"], api_type_filter=["chat"], is_available=True, refresh_type="tolerant", force_refresh=True ) print(models) ``` ## 参数说明 ### 鉴权配置 使用组件之前,请首先申请并设置鉴权参数,可参考[组件使用流程](https://cloud.baidu.com/doc/AppBuilder/s/Olq6grrt6#1%E3%80%81%E5%88%9B%E5%BB%BA%E5%AF%86%E9%92%A5)。 ```python # 设置环境中的TOKEN,以下示例略 os.environ["APPBUILDER_TOKEN"] = "bce-YOURTOKEN" ``` ### 初始化参数 无 ### 调用参数 |参数名称 | 参数类型 | 是否必须 |描述 | 示例值 | |--------|--------------|------|----|------| |secret_key | String | 是 |用户鉴权token, 默认从环境变量中获取| bce-YOURTOKEN | |api_type_filter| List[String] | 否 |根据apiType过滤,["chat", "completions", "embeddings", "text2image"],不填包括所有的。| chat | |is_available| Boolean | 否 |是否返回可用模型列表, 默认返回所有模型。| True | |refresh_type | String | 否 | 获取模型列表的方式,默认在出错时使用兜底策略。["tolerant", "original"] | "tolerant" | |force_refersh | Boolean | 否 | 是否强制刷新缓存,默认不强制刷新。| False | ### 返回示例 ['ERNIE-Bot 4.0', 'ERNIE-Bot', 'ERNIE-Bot-turbo'] ## 高级用法 目前该模块仅提供获取千帆模型列表功能。 ## 更新记录和贡献 * 切换模型获取列表接口为v2 (2025-06) * 千帆模型列表获取能力 (2024-1) ================================================ FILE: docs/BasisModule/Platform/Application/appbuilder_client.md ================================================ # AppBuilderClient组件 ## 简介 AppBuilderClient组件支持调用在[百度智能云千帆AppBuilder](https://cloud.baidu.com/product/AppBuilder) 平台上通过AppBuilderClient构建并发布的智能体应用。 ### 功能介绍 具体包括创建会话、上传文档、运行对话等 ### 特色优势 与云端Console 应用能力打通,实现低代码会话 ### 应用场景 快速、高效集成云端已发布智能体应用能力 ## Python基本用法 ### `AppBuilderClient().__init__()` #### 方法参数 | 参数名称 | 参数类型 | 描述 | 示例值 | | -------- | -------- | ----------------- | -------------- | | app_id | string | 线上Agent应用的ID | "正确的应用ID" | #### 方法返回值 ```AppBuilderClient```实例化对象 ### `AppBuilderClient().create_conversation()-> str` #### 方法参数 无 #### 方法返回值 | 参数名称 | 参数类型 | 描述 | 示例值 | | --------------- | -------- | -------- | -------------------------------------- | | conversation_id | string | 会话的ID | "80c5bbee-931d-4ed9-a4ff-63e1971bd071" | ### `AppBuilderClient().upload_local_file(conversation_id, local_file_path: str)-> str` #### 方法参数 | 参数名称 | 参数类型 | 描述 | 示例值 | | --------------- | -------- | -------- | ---------------- | | conversation_Id | string | 会话ID | | | file_path | string | 文件路径 | "正确的文件路径" | #### 方法返回值 | 参数名称 | 参数类型 | 描述 | 示例值 | | -------- | -------- | ------ | ---------------------------------- | | file_id | string | 文件ID | "80c5bbee-931d-4ed9-a4ff-63e1971bd | ### `AppBuilderClient().upload_file(conversation_id, local_file_path: str=None, file_url: str=None)-> str` #### 方法参数 | 参数名称 | 参数类型 | 描述 | 示例值 | | --------------- | -------- | -------- | ---------------- | | conversation_Id | string | 会话ID | | | file_path | string | 文件路径 | "正确的文件路径" | | file_url | string | 文件url | | #### 方法返回值 | 参数名称 | 参数类型 | 描述 | 示例值 | | -------- | -------- | ------ | ---------------------------------- | | file_id | string | 文件ID | "80c5bbee-931d-4ed9-a4ff-63e1971bd | ### `AppBuilderClient().run() -> Message` #### 方法参数 | 参数名称 | 参数类型 | 是否必须 | 描述 | 示例值 | | --------------- | ------------------ | -------- | ------------------------------------------------------------ | ----------------- | | conversation_id | String | 是 | 会话ID | | | query | String | 否 | query问题内容 | "今天天气怎么样?" | | file_ids | list[String] | 否 | 对话可引用的文档ID | | | stream | Bool | 否 | 为true时则流式返回,为false时则一次性返回所有内容, 推荐设为true,降低首token时延 | False | | end_user_id | String | 否 | 终端用户ID,限制6 - 64字符 | | | tools | List[Tool] | 否 | 一个列表,其中每个字典对应一个工具的配置 | | | tools[0] | Tool | 否 | 工具配置 | | | +type | String | 否 | 枚举:
**file_retrieval**: 知识库检索工具能够理解文档内容,支持用户针对文档内容的问答。
**code_interpreter**: 代码解释器, 代码解释器能够生成并执行代码,从而协助用户解决复杂问题,涵盖科学计算(包括普通数学计算题)、数据可视化、文件编辑处理(图片、PDF文档、视频、音频等)、文件格式转换(如WAV、MP3、text、SRT、PNG、jpg、MP4、GIF、MP3等)、数据分析&清洗&处理(文件以excel、csv格式为主)、机器学习&深度学习建模&自然语言处理等多个领域。
**function**: 支持fucntion call模式调用工具 | | | +function | Function | 否 | Function工具描述
仅当**type为**`**function**` 时需要且必须填写 | | | ++name | String | 否 | 函数名
只允许数字、大小写字母和中划线和下划线,最大长度为64个字符。一次运行中唯一。 | | | ++description | String | 否 | 工具描述 | | | ++parameters | Dict | 否 | 工具参数, json_schema格式 | | | tool_outputs | List[ToolOutput] | 否 | 内容为本地的工具执行结果,以自然语言/json dump str描述 | | | tool_outputs[0] | ToolOutput | 否 | 工具执行结果 | | | +tool_call_id | String | 否 | 工具调用ID | | | +output | String | 否 | 工具输出 | | | tool_choice | ToolChoice | 否 | 控制大模型使用组件的方式,仅对自主规划Agent生效。 | | | +type | String | 否 | auto/function,auto表示由LLM自动判断调什么组件;function表示由用户指定调用哪个组件。 | | | +function | ToolChoiceFunction | 否 | 组件对象,包括组件的英文名称和入参 | | | ++name | String | 否 | 组件的英文名称(唯一标识) | | | ++input | String | 否 | 组件入参,当组件没有入参时填入空对象{} | | | action | Action | 否 | 对话时要进行的特殊操作。如回复工作流agent中“信息收集节点“的消息 | | | +action_type | String | 是 | 要执行的操作。
可选值为:
resume:回复“信息收集节点” 的消息 | | | +parameters | Object | 是 | 执行操作时所需的参数 | | #### Run方法非流式返回值 Run非流式方法返回一个`Message`对象,该对象包含以下属性: | 参数名称 | 参数类型 | 描述 | 示例值 | | -------------- | ---------------------- | -------------------- | --------------------------------------------------------------------------------------- | | content | AppBuilderClientAnswer | 对话返回结果 | | | +answer | String | 智能体应用返回的回答 | | | +events | List[Event] | 事件列表 | | | +events[0] | Event | 具体事件内容 | | | ++code | String | 错误码 | | | ++message | String | 错误具体消息 | | | ++status | String | 事件状态 | 状态描述,preparing(准备运行)running(运行中)error(执行错误) done(执行完成) | | ++event_type | String | 事件类型 | | | ++content_type | String | 内容类型 | 可选值包括:code text, image, status,image, function_call, rag, audio、video等 | | ++detail | Dict | 事件输出详情 | 代码解释器、文生图、工具组件、RAG等的详细输出内容 | | ++usage | Usage | 模型调用的token用量 | Usage(prompt_tokens=1322, completion_tokens=80, total_tokens=1402, name='DeepSeek-V3.1') | `AppBuilderClientAnswer`类型定义如下: ```python class AppBuilderClientAnswer(BaseModel): """执行步骤的具体内容 属性: answer(str): query回答内容 events( list[Event]): 事件列表 """ answer: str = "" events: list[Event] = [] ``` `Event`类型定义如下: ```python class Event(BaseModel): """执行步骤的具体内容 属性: code (int): 响应code码 message (str): 错误详情 status (str): 状态描述,preparing(准备运行)running(运行中)error(执行错误) done(执行完成) event_type(str): 事件类型 content_type(str): 内容类型 detail(dict): 事件详情 usage(Usage): 大模型调用的token用量 """ code: int = 0 message: str = "" status: str = "" event_type: str = "" content_type: str = "" detail: dict = {} usage: Optional[Usage] = None ``` #### Run方法流式返回值 | 参数名称 | 参数类型 | 描述 | 示例值 | | -------- | ---------------- | ---------------------------------------------- | ------ | | content | Python Generator | 可迭代,每次迭代返回AppBuilderClientAnswer类型 | 无 | #### 非流式调用示例 ```python import appbuilder import os # 请前往千帆AppBuilder官网创建密钥,流程详见:https://cloud.baidu.com/doc/AppBuilder/s/Olq6grrt6#1%E3%80%81%E5%88%9B%E5%BB%BA%E5%AF%86%E9%92%A5 # 设置环境变量 os.environ["APPBUILDER_TOKEN"] = '...' app_id = '...' # 已发布AppBuilder应用ID,可在console端查看 # 初始化智能体 builder = appbuilder.AppBuilderClient(app_id) # 创建会话 conversation_id = builder.create_conversation() # 运行对话 out = builder.run(conversation_id, "北京今天天气怎么样") # 打印会话结果 print(out.content.answer) ``` #### 流式调用示例 ```python import appbuilder from appbuilder.core.console.appbuilder_client import data_class import os # 请前往千帆AppBuilder官网创建密钥,流程详见:https://cloud.baidu.com/doc/AppBuilder/s/Olq6grrt6#1%E3%80%81%E5%88%9B%E5%BB%BA%E5%AF%86%E9%92%A5 # 设置环境变量 os.environ["APPBUILDER_TOKEN"] = '...' app_id = '...' # 已发布AppBuilder应用的ID # 初始化智能体 client = appbuilder.AppBuilderClient(app_id) # 创建会话 conversation_id = client.create_conversation() # 上传一个介绍某汽车产品的说明文档 file_id = client.upload_local_file(conversation_id, "/path/to/pdf/file") # 引用上传的文档,开始对话 # 注意file_ids不是必填项,如果不需要引用特定文档,file_ids留空即可 message = client.run(conversation_id, "汽车性能参数怎么样", file_ids=[file_id, ], stream=True) answer = "" # 每次迭代返回AppBuilderClientAnswer结构,内可能包括多个事件内容 for content in message.content: # stream=True时,将answer拼接起来才是完整的的对话结果 answer += content.answer for event in content.events: content_type = event.content_type detail = event.detail # 根据content类型对事件详情进行解析 if content_type == "code": code_detail = data_class.CodeDetail(**detail) print(code_detail.code) elif content_type == "text": text_detail = data_class.TextDetail(**detail) print(text_detail.text) elif content_type == "image": image_detail = data_class.ImageDetail(**detail) print(image_detail.url) elif content_type == "rag": rag_detail = data_class.RAGDetail(**detail) if len(rag_detail.references) > 0: print(rag_detail.references) elif content_type == "function_call": function_call_detail = data_class.FunctionCallDetail(**detail) print(function_call_detail.video) elif content_type == "audio": audio_detail = data_class.AudioDetail(**detail) print(audio_detail) elif content_type == "video": video_detail = data_class.VideoDetail(**detail) print(video_detail) elif content_type == "status": status_detail = data_class.StatusDetail(**detail) print(status_detail) else: default_detail = data_class.DefaultDetail(**detail) print(default_detail) # 打印完整的answer结果 print(answer) ``` #### Run方法带ToolCall调用示例 以下示例展示了三种方式来使用 ToolCall 进行调用,并演示了如何在 AppBuilder 环境中配置和执行会话调用。 **方式1:使用 JSONSchema 格式直接描述 tools 调用** ```python import appbuilder from appbuilder.core.console.appbuilder_client import data_class import os # 请前往千帆AppBuilder官网创建密钥,流程详见:https://cloud.baidu.com/doc/AppBuilder/s/Olq6grrt6#1%E3%80%81%E5%88%9B%E5%BB%BA%E5%AF%86%E9%92%A5 # 设置环境变量 os.environ["APPBUILDER_TOKEN"] = "..." app_id = "..." # 已发布AppBuilder应用的ID # 初始化智能体 client = appbuilder.AppBuilderClient(app_id) # 创建会话 conversation_id = client.create_conversation() tools = [ { "type": "function", "function": { "name": "get_current_weather", "description": "仅支持中国城市的天气查询,参数location为中国城市名称,其他国家城市不支持天气查询", "parameters": { "type": "object", "properties": { "location": { "type": "string", "description": "城市名,举例:北京", }, "unit": {"type": "string", "enum": ["celsius", "fahrenheit"]}, }, "required": ["location", "unit"], }, }, } ] msg = client.run( conversation_id=conversation_id, query="今天北京天气怎么样?", tools=tools ) print(msg.model_dump_json(indent=4)) event = msg.content.events[-1] msg_2 = client.run( conversation_id=conversation_id, tool_outputs=[{"tool_call_id": event.tool_calls[-1].id, "output": "北京今天35度"}], ) print(msg_2.model_dump_json(indent=4)) ``` **方式2: 使用 function_to_model 将函数对象传递为 ToolCall 的调用** ```python import appbuilder import os # 请前往千帆AppBuilder官网创建密钥,流程详见:https://cloud.baidu.com/doc/AppBuilder/s/Olq6grrt6#1%E3%80%81%E5%88%9B%E5%BB%BA%E5%AF%86%E9%92%A5 # 设置环境变量 os.environ["APPBUILDER_TOKEN"] = "..." app_id = "..." # 已发布AppBuilder应用的ID # 初始化智能体 client = appbuilder.AppBuilderClient(app_id) # 创建会话 conversation_id = client.create_conversation() #注意:要使用此方法要为函数写好注释。最好按照谷歌规范来写 #定义示例函数 def get_current_weather(location: str, unit: str) -> str: """获取指定中国城市的当前天气信息。 仅支持中国城市的天气查询。参数 `location` 为中国城市名称,其他国家城市不支持天气查询。 Args: location (str): 城市名,例如:"北京"。 unit (int): 温度单位,支持 "celsius" 或 "fahrenheit"。 Returns: str: 天气情况描述 """ return "北京今天25度" #定义函数列表 functions = [get_current_weather] function_map = {f.__name__: f for f in functions} #调用大模型 msg = client.run( conversation_id=conversation_id, query="今天北京的天气怎么样?", tools = [appbuilder.Manifest.from_function(f) for f in functions] ) print(msg.model_dump_json(indent=4)) # 获取最后的事件和工具调用信息 event = msg.content.events[-1] tool_call = event.tool_calls[-1] # 获取函数名称和参数 name = tool_call.function.name args = tool_call.function.arguments # 将函数名称映射到具体的函数并执行 raw_result = function_map[name](**args) # 传递工具的输出 msg_2 = client.run( conversation_id=conversation_id, tool_outputs=[{ "tool_call_id": tool_call.id, "output": str(raw_result) }], ) print(msg_2.model_dump_json(indent=4)) ``` **方式3: 使用装饰器进行描述** ```python import os import json import appbuilder from appbuilder import manifest, manifest_parameter # 请前往千帆AppBuilder官网创建密钥,流程详见:https://cloud.baidu.com/doc/AppBuilder/s/Olq6grrt6#1%E3%80%81%E5%88%9B%E5%BB%BA%E5%AF%86%E9%92%A5 # 设置环境变量 os.environ["APPBUILDER_TOKEN"] = "" app_id = "" # 已发布AppBuilder应用的ID # 初始化智能体 client = appbuilder.AppBuilderClient(app_id) # 创建会话 conversation_id = client.create_conversation() #使用manifest装饰描述函数,manifest_parameter装饰器描述参数,manifest_return装饰器描述函数返回值。 @manifest(description="获取指定中国城市的当前天气信息。仅支持中国城市的天气查询。参数 `location` 为中国城市名称,其他国家城市不支持天气查询。") @manifest_parameter(name="location", description="城市名,例如:北京。") @manifest_parameter(name="unit", description="温度单位,支持 'celsius' 或 'fahrenheit'") #定义示例函数 def get_current_weather(location: str, unit: str) -> str: return "北京今天25度" print(json.dumps(appbuilder.Manifest.from_function(get_current_weather), indent=4, ensure_ascii=False)) #定义函数列表 functions = [get_current_weather] function_map = {f.__name__: f for f in functions} #调用大模型 msg = client.run( conversation_id=conversation_id, query="今天北京的天气怎么样?", tools = [appbuilder.Manifest.from_function(f) for f in functions] ) print(msg.model_dump_json(indent=4)) # 获取最后的事件和工具调用信息 event = msg.content.events[-1] tool_call = event.tool_calls[-1] # 获取函数名称和参数 name = tool_call.function.name args = tool_call.function.arguments # 将函数名称映射到具体的函数并执行 raw_result = function_map[name](**args) # 传递工具的输出 msg_2 = client.run( conversation_id=conversation_id, tool_outputs=[{ "tool_call_id": tool_call.id, "output": str(raw_result) }], ) print(msg_2.model_dump_json(indent=4) ``` #### Run方法带MCP Tool使用示例: **方式1:使用run方法直接调用** 以[官方server](https://github.com/modelcontextprotocol/quickstart-resources/blob/main/weather-server-python/weather.py)为例。我们将server代码保存为`weather.py`。 ```python import os import asyncio import appbuilder from appbuilder.mcp_server.client import MCPClient async def main(): mcp_client = MCPClient() await mcp_client.connect_to_server("./weather.py") tools = mcp_client.tools client = appbuilder.AppBuilderClient(app_id) conversation_id = client.create_conversation() msg = client.run( conversation_id=conversation_id, query="美国马塞诸塞州的天气", tools=tools, ) tool_call = msg.content.events[-1].tool_calls[-1] mcp_result = await mcp_client.call_tool( tool_name=tool_call.function.name, tool_args=tool_call.function.arguments ) msg_2 = client.run( conversation_id=conversation_id, tool_outputs=[{ "tool_call_id": tool_call.id, "output": mcp_result.content[0].text }]) print("\033[1;34m", "Agent 最终结果:{}".format( msg_2.content.answer), "\033[0m") if __name__ == "__main__": # 请前往千帆AppBuilder官网创建密钥,流程详见:https://cloud.baidu.com/doc/AppBuilder/s/Olq6grrt6#1%E3%80%81%E5%88%9B%E5%BB%BA%E5%AF%86%E9%92%A5 # 设置环境变量 os.environ["APPBUILDER_TOKEN"] = ("") # 已发布AppBuilder应用的ID app_id = "" loop = asyncio.get_event_loop() loop.run_until_complete(main()) ``` **方式2: 使用eventhandler封装调用** 以[官方server](https://github.com/modelcontextprotocol/quickstart-resources/blob/main/weather-server-python/weather.py)为例。我们将server代码保存为`weather.py`。 ```python import os import asyncio import appbuilder from appbuilder.core.console.appbuilder_client.async_event_handler import ( AsyncAppBuilderEventHandler, ) from appbuilder.mcp_server.client import MCPClient class MyEventHandler(AsyncAppBuilderEventHandler): def __init__(self, mcp_client): super().__init__() self.mcp_client = mcp_client self.functions = [] async def interrupt(self, run_context, run_response): thought = run_context.current_thought print("\033[1;31m", "-> Agent 中间思考: ", thought, "\033[0m") tool_output = [] for tool_call in run_context.current_tool_calls: function_name = tool_call.function.name function_arguments = tool_call.function.arguments result = "" function_map = {f.__name__: f for f in self.functions} if function_name in function_map: result = function_map[function_name]( **tool_call.function.arguments) print("\033[1;33m", "本地function结果: {}\n\033[0m".format(result)) else: print( "\033[1;32m", "MCP工具名称: {}, MCP参数:{}\n".format( function_name, function_arguments ), "\033[0m", ) mcp_server_result = await self.mcp_client.call_tool( function_name, function_arguments ) print("\033[1;33m", "MCP结果: {}\n\033[0m".format( mcp_server_result)) index = 0 for i, content in enumerate(mcp_server_result.content): if content.type == "text": index = i result = result + mcp_server_result.content[index].text tool_output.append( { "tool_call_id": tool_call.id, "output": result, } ) return tool_output async def success(self, run_context, run_response): print("\n\033[1;34m", "-> Agent 非流式回答: ", run_response.answer, "\033[0m") async def main(): appbuilder_client = appbuilder.AsyncAppBuilderClient(app_id) mcp_client = MCPClient() await mcp_client.connect_to_server("./weather.py") tools = mcp_client.tools conversation_id = await appbuilder_client.create_conversation() with await appbuilder_client.run_with_handler( conversation_id=conversation_id, query="美国马塞诸塞州天气", tools=tools, event_handler=MyEventHandler(mcp_client), ) as run: await run.until_done() await appbuilder_client.http_client.session.close() if __name__ == "__main__": os.environ["APPBUILDER_TOKEN"] = "" app_id = "" loop = asyncio.get_event_loop() loop.run_until_complete(main()) ``` **方式3: MCP Tool跟其他Tool一起作为Tool注册** 以[官方server](https://github.com/modelcontextprotocol/quickstart-resources/blob/main/weather-server-python/weather.py)为例。我们将server代码保存为`weather.py`。 ```python import os import asyncio import appbuilder from appbuilder.core.console.appbuilder_client.async_event_handler import ( AsyncAppBuilderEventHandler, ) from appbuilder.mcp_server.client import MCPClient @appbuilder.manifest( description="获取指定中国城市的当前天气信息。仅支持中国城市的天气查询。参数 `location` 为中国城市名称,其他国家城市不支持天气查询。" ) @appbuilder.manifest_parameter(name="location", description="城市名,例如:北京。") @appbuilder.manifest_parameter( name="unit", description="温度单位,支持 'celsius' 或 'fahrenheit'" ) def get_current_weather(location: str, unit: str) -> str: return "北京今天25度" class MyEventHandler(AsyncAppBuilderEventHandler): def __init__(self, mcp_client): super().__init__() self.mcp_client = mcp_client async def interrupt(self, run_context, run_response): thought = run_context.current_thought print("\033[1;31m", "-> Agent 中间思考: ", thought, "\033[0m") tool_output = [] for tool_call in run_context.current_tool_calls: function_name = tool_call.function.name function_arguments = tool_call.function.arguments result = "" function_map = {f.__name__: f for f in functions} if function_name in function_map: result = function_map[function_name]( **tool_call.function.arguments) print("\033[1;33m", "本地function结果: {}\n\033[0m".format(result)) else: print( "\033[1;32m", "MCP工具名称: {}, MCP参数:{}\n".format( function_name, function_arguments ), "\033[0m", ) mcp_server_result = await self.mcp_client.call_tool( function_name, function_arguments ) print("\033[1;33m", "MCP结果: {}\n\033[0m".format( mcp_server_result)) index = 0 for i, content in enumerate(mcp_server_result.content): if content.type == "text": index = i result = result + mcp_server_result.content[index].text tool_output.append( { "tool_call_id": tool_call.id, "output": result, } ) return tool_output async def success(self, run_context, run_response): print("\n\033[1;34m", "-> Agent 非流式回答: ", run_response.answer, "\033[0m") async def main(): tools = [appbuilder.Manifest.from_function(f) for f in functions] mcp_client = MCPClient() await mcp_client.connect_to_server("./weather.py") tools.extend(mcp_client.tools) appbuilder_client = appbuilder.AsyncAppBuilderClient(app_id) conversation_id = await appbuilder_client.create_conversation() with await appbuilder_client.run_with_handler( conversation_id=conversation_id, query="美国马塞诸塞州天气", tools=tools, event_handler=MyEventHandler(mcp_client), ) as run: await run.until_done() await appbuilder_client.http_client.session.close() if __name__ == "__main__": os.environ["APPBUILDER_TOKEN"] = "" app_id = "" functions = [get_current_weather] loop = asyncio.get_event_loop() loop.run_until_complete(main()) ``` #### Run方法带ToolChoice使用示例: * 注意:当前功能为试运行阶段,可能存在如下问题,如使用过程遇到其他问题,欢迎提issue或微信群讨论。 * 需开启"组件/知识库结论可直接作为回复" * 组件名称不是界面上的原始名字,而是个人空间组件列表中的英文名 * 自定义组件的参数不能使用系统参数,可以使用用户添加的参数 * 部分官方组件使用的参数与界面上的参数不一致 ```python import appbuilder import os # 请前往千帆AppBuilder官网创建密钥,流程详见:https://cloud.baidu.com/doc/AppBuilder/s/Olq6grrt6#1%E3%80%81%E5%88%9B%E5%BB%BA%E5%AF%86%E9%92%A5 # 设置环境变量 os.environ["APPBUILDER_TOKEN"] = "..." app_id = "..." # 已发布AppBuilder应用的ID # 初始化智能体 client = appbuilder.AppBuilderClient(app_id) # 创建会话 conversation_id = client.create_conversation() # 注意使用创建应用中用到的组件。名称、参数均以实际使用的组件为准。 answer = app_builder_client.run( conversation_id, "北京今天的天气", stream=False, end_user_id="user_id_toolchoice", tool_choice={ "type": "function", "function": {"name": "WeatherQuery", "input": {"city": "北京"}}, }, ) ``` #### Run方法回复工作流Agent “信息收集节点”使用示例: 使用[“飞行客服小助手”](https://cloud.baidu.com/doc/AppBuilder/s/cm38k8nqr)作为工作流Agent的示例应用。 **方式1:** SDK直接进行对话(不推荐) ```python import appbuilder import os from appbuilder.core.console.appbuilder_client import data_class # 请前往千帆AppBuilder官网创建密钥,流程详见:https://cloud.baidu.com/doc/AppBuilder/s/Olq6grrt6#1%E3%80%81%E5%88%9B%E5%BB%BA%E5%AF%86%E9%92%A5 # 设置环境变量 os.environ["APPBUILDER_TOKEN"] = ( "..." ) appbuilder.logger.setLoglevel("ERROR") # 飞行客服小助手的应用id app_id = "..." # 初始化智能体 client = appbuilder.AppBuilderClient(app_id) # 创建会话 conversation_id = client.create_conversation() interrupt_ids = [] msg = client.run(conversation_id, "查天气", stream=True) interrupt_event_id = None for ans in msg.content: for event in ans.events: if event.content_type == "publish_message": print(event.detail.get("message")) if event.content_type == "chatflow_interrupt": interrupt_event_id = event.detail.get("interrupt_event_id") break interrupt_ids.append(interrupt_event_id) msg2 = client.run( conversation_id, "查航班", stream=True, action=data_class.Action.create_resume_action(interrupt_event_id), ) interrupt_event_id = None for ans in msg2.content: for event in ans.events: if event.content_type == "publish_message": print(event.detail.get("message")) if event.content_type == "chatflow_interrupt": interrupt_event_id = event.detail.get("interrupt_event_id") break interrupt_ids.append(interrupt_event_id) msg3 = client.run( conversation_id=conversation_id, query="CA1234", stream=True, action=data_class.Action.create_resume_action(interrupt_ids.pop()), ) interrupt_event_id = None for ans in msg3.content: for event in ans.events: if event.content_type == "text": print(event.detail.get("text")) if event.content_type == "chatflow_interrupt": interrupt_event_id = event.detail.get("interrupt_event_id") break interrupt_ids.append(interrupt_event_id) msg4 = client.run( conversation_id=conversation_id, query="北京的", stream=True, action=data_class.Action.create_resume_action(interrupt_ids.pop()), ) has_multiple_dialog_event = False for ans in msg4.content: for event in ans.events: if event.content_type == "text": print(event.detail.get("text")) if event.content_type == "multiple_dialog_event": has_multiple_dialog_event = True break ``` **方式2:** 实现自己的EventHandler,更方便地进行对话(推荐) ```python import os import appbuilder from appbuilder.core.console.appbuilder_client.event_handler import ( AppBuilderEventHandler, ) class MyEventHandler(AppBuilderEventHandler): def __init__(self): super().__init__() self.interrupt_ids = [] def handle_content_type(self, run_context, run_response): interrupt_event_id = None event = run_response.events[-1] if event.content_type == "chatflow_interrupt": interrupt_event_id = event.detail.get("interrupt_event_id") if interrupt_event_id is not None: self.interrupt_ids.append(interrupt_event_id) def _create_action(self): if len(self.interrupt_ids) == 0: return None event_id = self.interrupt_ids.pop() return { "action_type": "resume", "parameters": {"interrupt_event": {"id": event_id, "type": "chat"}}, } def run(self, query=None): super().new_dialog( query=query, action=self._create_action(), ) def main(): # 请前往千帆AppBuilder官网创建密钥,流程详见:https://cloud.baidu.com/doc/AppBuilder/s/Olq6grrt6#1%E3%80%81%E5%88%9B%E5%BB%BA%E5%AF%86%E9%92%A5 # 设置环境变量 os.environ["APPBUILDER_TOKEN"] = "..." appbuilder.logger.setLoglevel("DEBUG") # 飞行客服小助手的应用id app_id = "..." # 初始化智能体 client = appbuilder.AppBuilderClient(app_id) conversation_id = client.create_conversation() event_handler = MyEventHandler() event_handler.init( appbuilder_client=client, conversation_id=conversation_id, stream=True, query="查天气", ) for data in event_handler: pass event_handler.run( query="查航班", ) for data in event_handler: pass event_handler.run( query="CA1234", ) for data in event_handler: pass event_handler.run( query="北京的", ) for data in event_handler: pass if __name__ == "__main__": main() ``` **方式3:** 实现自己的EventHandler,更方便地进行多轮对话(推荐) ```python import os import appbuilder from appbuilder.core.console.appbuilder_client.event_handler import ( AppBuilderEventHandler, ) class MyEventHandler(AppBuilderEventHandler): def __init__(self): super().__init__() self.interrupt_ids = [] def handle_content_type(self, run_context, run_response): interrupt_event_id = None event = run_response.events[-1] if event.content_type == "chatflow_interrupt": interrupt_event_id = event.detail.get("interrupt_event_id") if interrupt_event_id is not None: self.interrupt_ids.append(interrupt_event_id) def _create_action(self): if len(self.interrupt_ids) == 0: return None event_id = self.interrupt_ids.pop() return { "action_type": "resume", "parameters": {"interrupt_event": {"id": event_id, "type": "chat"}}, } def gen_action(self): while True: yield self._create_action() def main(): # 请前往千帆AppBuilder官网创建密钥,流程详见:https://cloud.baidu.com/doc/AppBuilder/s/Olq6grrt6#1%E3%80%81%E5%88%9B%E5%BB%BA%E5%AF%86%E9%92%A5 # 设置环境变量 os.environ["APPBUILDER_TOKEN"] = "..." appbuilder.logger.setLoglevel("DEBUG") # 飞行客服小助手的应用id app_id = "..." # 初始化智能体 client = appbuilder.AppBuilderClient(app_id) conversation_id = client.create_conversation() queries = ["查天气", "查航班", "CA1234", "北京的"] event_handler = MyEventHandler() event_handler = client.run_multiple_dialog_with_handler( conversation_id=conversation_id, queries=queries, event_handler=event_handler, stream=True, actions=event_handler.gen_action(), ) for data in event_handler: for ans in data: pass if __name__ == "__main__": main() ``` ## Java基本用法 ### ```new AppBuilderClient(appId)``` #### 方法参数 | 参数名称 | 参数类型 | 描述 | 示例值 | | -------- | -------- | ----------------- | -------------- | | appID | String | 线上Agent应用的ID | "正确的应用ID" | #### 方法返回值 ```AppBuilderClient```实例化对象 ### ```AppBuilderClient().createConversation()``` #### 方法参数 无 #### 方法返回值 | 参数名称 | 参数类型 | 描述 | 示例值 | | -------------- | -------- | ------------ | -------------- | | conversationId | String | 创建的会话ID | "正确的会话ID" | ### ```AppBuilderClient().run()``` #### Run方法入参`AppBuilderCientRunRequest` | 参数名称 | 参数类型 | 是否必须 | 描述 | 示例值 | | --------------- | ------------------ | -------- | ------------------------------------------------------------ | -------------------- | | query | String | 是 | query内容 | "汽车性能参数怎么样" | | conversationId | String | 是 | 对话id,可以通过createConversation()获取 | | | stream | boolean | 是 | 为true时则流式返回,为false时则一次性返回所有内容, 推荐设为true,降低首token时延 | | | tools | List[Tool] | 否 | 一个列表,其中每个字典对应一个工具的配置 | | | tools[0] | Tool | 否 | 工具配置 | | | +type | String | 否 | 枚举:
**file_retrieval**: 知识库检索工具能够理解文档内容,支持用户针对文档内容的问答。
**code_interpreter**: 代码解释器, 代码解释器能够生成并执行代码,从而协助用户解决复杂问题,涵盖科学计算(包括普通数学计算题)、数据可视化、文件编辑处理(图片、PDF文档、视频、音频等)、文件格式转换(如WAV、MP3、text、SRT、PNG、jpg、MP4、GIF、MP3等)、数据分析&清洗&处理(文件以excel、csv格式为主)、机器学习&深度学习建模&自然语言处理等多个领域。
**function**: 支持fucntion call模式调用工具 | | | +function | Function | 否 | Function工具描述
仅当**type为**`**function**` 时需要且必须填写 | | | ++name | String | 否 | 函数名
只允许数字、大小写字母和中划线和下划线,最大长度为64个字符。一次运行中唯一。 | | | ++description | String | 否 | 工具描述 | | | ++parameters | Dict | 否 | 工具参数, json_schema格式 | | | tool_outputs | List[ToolOutput] | 否 | 内容为本地的工具执行结果,以自然语言/json dump str描述 | | | tool_outputs[0] | ToolOutput | 否 | 工具执行结果 | | | +tool_call_id | String | 否 | 工具调用ID | | | +output | String | 否 | 工具输出 | | | tool_choice | ToolChoice | 否 | 控制大模型使用组件的方式,仅对自主规划Agent生效。 | | | +type | String | 否 | auto/function,auto表示由LLM自动判断调什么组件;function表示由用户指定调用哪个组件。 | | | +function | ToolChoiceFunction | 否 | 组件对象,包括组件的英文名称和入参 | | | ++name | String | 否 | 组件的英文名称(唯一标识) | | | ++input | String | 否 | 组件入参,当组件没有入参时填入空对象{} | | | action | Action | 否 | 对话时要进行的特殊操作。如回复工作流agent中“信息收集节点“的消息 | | | +action_type | String | 是 | 要执行的操作。
可选值为:
resume:回复“信息收集节点” 的消息 | | | +parameters | Object | 是 | 执行操作时所需的参数 | | #### Run方法出参 | 参数名称 | 参数类型 | 描述 | 示例值 | | ------------------------ | ------------------------ | -------------------------------------------------------------------------------- | ------ | | AppBuilderClientIterator | AppBuilderClientIterator | 回答迭代器,流式/非流式均统一返回该类型,每次迭代返回AppBuilderClientIterator类型 | | #### 迭代AppBuilderClientIterator | 参数名称 | 参数类型 | 描述 | 示例值 | | ------------- | ------------------- | -------------------- | --------------------------------------------------------------------------------------- | | +answer | String | 智能体应用返回的回答 | | | +events | Event[] | 事件列表 | | | +events[0] | Event | 具体事件内容 | | | ++code | string | 错误码 | | | ++message | string | 错误具体消息 | | | ++status | string | 事件状态 | 状态描述,preparing(准备运行)running(运行中)error(执行错误) done(执行完成) | | ++eventType | string | 事件类型 | | | ++contentType | string | 内容类型 | 可选值包括:code text, image, status,image, function_call, rag, audio、video等 | | ++detail | Map | 事件输出详情 | 代码解释器、文生图、工具组件、RAG等的详细输出内容 | | ++usage | Usage | 模型调用的token用量 | Usage(prompt_tokens=1322, completion_tokens=80, total_tokens=1402, name='DeepSeek-V3.1') | #### 示例代码 ```Java package org.example; import java.io.IOException; import java.util.*; import com.google.gson.annotations.SerializedName; import com.baidubce.appbuilder.base.exception.AppBuilderServerException; import com.baidubce.appbuilder.console.appbuilderclient.AppBuilderClient; import com.baidubce.appbuilder.model.appbuilderclient.AppBuilderClientIterator; import com.baidubce.appbuilder.model.appbuilderclient.AppBuilderClientResult; import com.baidubce.appbuilder.model.appbuilderclient.Event; import com.baidubce.appbuilder.base.utils.json.JsonUtils; class AppBuilderClientDemo { public static void main(String[] args) throws IOException, AppBuilderServerException { System.setProperty("APPBUILDER_TOKEN", "请设置正确的应用密钥"); String appId = "请设置正确的应用ID"; AppBuilderClient builder = new AppBuilderClient(appId); String conversationId = builder.createConversation(); // 填写上传文件路径 String fileId = builder.uploadLocalFile(conversationId, "/Users/zhangxiaoyu15/PycharmProjects/app-builder/test_app_builder_client/test.pdf"); // 输入query // 注意file_ids不是必填项,如果不需要引用特定文档,则将new String[]{fileId}更换为new String[]{}即可 AppBuilderClientIterator itor = builder.run("中国四大传统节日是哪四个", conversationId, new String[]{fileId}, false); StringBuilder answer = new StringBuilder(); // itor.hasNext()返回false时,表示流式调用结束 while(itor.hasNext()) { AppBuilderClientResult response = itor.next(); answer.append(response.getAnswer()); for (Event event : response.getEvents()) { switch (event.getContentType()) { case "rag": List references = (List)event.getDetail().get("references"); for (Object reference : references) { ReferenceDetail ragDetail = JsonUtils.deserialize(JsonUtils.serialize(reference), ReferenceDetail.class); System.out.println("-----------------------------------"); System.out.println("参考文献ID:"+ragDetail.getId()); System.out.println("参考文献内容:"+ragDetail.getContent()); System.out.println("来源:"+ragDetail.getFrom()); System.out.println("BaiduSearch链接:"+ragDetail.getUrl()); System.out.println("类型:"+ragDetail.getType()); System.out.println("文档片段ID:"+ragDetail.getSegmentId()); System.out.println("文档ID:"+ragDetail.getDocumentId()); System.out.println("文档名称:"+ragDetail.getDocumentName()); System.out.println("文档所属数据集ID:"+ragDetail.getDatasetId()); System.out.println("-----------------------------------"); } break; default: // System.out.println(event); } } } System.out.print("输出:"); System.out.println(answer); } } class ReferenceDetail { private int id; private String content; private String from; private String url; private String type; @SerializedName("segment_id") private String segmentId; @SerializedName("document_id") private String documentId; @SerializedName("document_name") private String documentName; @SerializedName("dataset_id") private String datasetId; @SerializedName("knowledgebase_id") private String knowledgebaseId; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getContent() { return content; } public void setContent(String content) { this.content = content; } public String getFrom() { return from; } public void setFrom(String from) { this.from = from; } public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } public String getType() { return type; } public void setType(String type) { this.type = type; } public String getSegmentId() { return segmentId; } public void setSegmentId(String segmentId) { this.segmentId = segmentId; } public String getDocumentId() { return documentId; } public void setDocumentId(String documentId) { this.documentId = documentId; } public String getDocumentName() { return documentName; } public void setDocumentName(String documentName) { this.documentName = documentName; } public String getDatasetId() { return datasetId; } public void setDatasetId(String datasetId) { this.datasetId = datasetId; } public String getKnowledgebaseId() { return knowledgebaseId; } public void setKnowledgebaseId(String knowledgebaseId) { this.knowledgebaseId = knowledgebaseId; } @Override public String toString() { return "RAGReference{" + "id=" + id + ", content='" + content + '\'' + ", from='" + from + '\'' + ", url='" + url + '\'' + ", type='" + type + '\'' + ", segmentId='" + segmentId + '\'' + ", documentId='" + documentId + '\'' + ", documentName='" + documentName + '\'' + ", datasetId='" + datasetId + '\'' + ", knowledgebaseId='" + knowledgebaseId + '\'' + '}'; } } ``` #### Run方法带ToolCall调用示例 **创建tool的json文件** ```json { "type": "function", "function": { "name": "get_cur_whether", "description": "这是一个获得指定地点天气的工具", "parameters": { "type": "object", "properties": { "location": { "type": "string", "description": "省,市名,例如:河北省" }, "unit": { "type": "string", "enum": [ "摄氏度", "华氏度" ] } }, "required": [ "location" ] } } } ``` ```java package org.example; import java.io.IOException; import java.util.*; import com.google.gson.annotations.SerializedName; import com.baidubce.appbuilder.base.exception.AppBuilderServerException; import com.baidubce.appbuilder.console.appbuilderclient.AppBuilderClient; import com.baidubce.appbuilder.model.appbuilderclient.AppBuilderClientIterator; import com.baidubce.appbuilder.model.appbuilderclient.AppBuilderClientResult; import com.baidubce.appbuilder.model.appbuilderclient.Event; import com.baidubce.appbuilder.base.utils.json.JsonUtils; class AppBuilderClientDemo { public static void main(String[] args) throws IOException, AppBuilderServerException { System.setProperty("APPBUILDER_TOKEN", "请设置正确的应用密钥"); String appId = "请设置正确的应用ID"; AppBuilderClient builder = new AppBuilderClient(appId); String conversationId = builder.createConversation(); AppBuilderClientRunRequest request = new AppBuilderClientRunRequest(appId, conversationId, "今天北京的天气怎么样?", false); String toolJson = new String(Files.readAllBytes(Paths.get("json文件所在的路径"))); request.setTools(toolJson); AppBuilderClientIterator itor = builder.run(request); String ToolCallID = ""; while (itor.hasNext()) { AppBuilderClientResult result = itor.next(); Event lastEvent = result.getEvents()[result.getEvents().length - 1]; ToolCallID = lastEvent.getToolCalls()[lastEvent.getToolCalls().length - 1].getId(); System.out.println(result); } AppBuilderClientRunRequest request2 = new AppBuilderClientRunRequest(appId, conversationId); request2.setToolOutputs(ToolCallID, "北京今天35度"); AppBuilderClientIterator itor2 = builder.run(request2); while (itor2.hasNext()) { AppBuilderClientResult result = itor2.next(); System.out.println(result); } } } ``` #### Run方法带Toolchoice使用示例 * 注意:当前功能为试运行阶段,可能存在如下问题,如使用过程遇到其他问题,欢迎提issue或微信群讨论。 * 需开启"组件/知识库结论可直接作为回复" * 组件名称不是界面上的原始名字,而是个人空间组件列表中的英文名 * 自定义组件的参数不能使用系统参数,可以使用用户添加的参数 * 部分官方组件使用的参数与界面上的参数不一致 ```java package org.example; import java.io.IOException; import java.util.*; import com.google.gson.annotations.SerializedName; import com.baidubce.appbuilder.base.exception.AppBuilderServerException; import com.baidubce.appbuilder.console.appbuilderclient.AppBuilderClient; import com.baidubce.appbuilder.model.appbuilderclient.AppBuilderClientIterator; import com.baidubce.appbuilder.model.appbuilderclient.AppBuilderClientResult; import com.baidubce.appbuilder.model.appbuilderclient.AppBuilderClientRunRequest; import com.baidubce.appbuilder.model.appbuilderclient.Event; import com.baidubce.appbuilder.base.utils.json.JsonUtils; class AppBuilderClientDemo { public static void main(String[] args) throws IOException, AppBuilderServerException { System.setProperty("APPBUILDER_TOKEN", "请设置正确的应用密钥"); String appId = "请设置正确的应用ID"; AppBuilderClient builder = new AppBuilderClient(appId); String conversationId = builder.createConversation(); AppBuilderClientRunRequest request = new AppBuilderClientRunRequest(appId, conversationId, "你能干什么", false); request.setEndUserId("java_toolchoice_demo"); // 注意使用创建应用中用到的组件。名称、参数均以实际使用的组件为准。 Map input = new HashMap<>(); input.put("city", "北京"); AppBuilderClientRunRequest.ToolChoice.Function func = new AppBuilderClientRunRequest.ToolChoice.Function( "WeatherQuery", input); AppBuilderClientRunRequest.ToolChoice choice = new AppBuilderClientRunRequest.ToolChoice("function", func); request.setToolChoice(choice); AppBuilderClientIterator itor = builder.run(request); while (itor.hasNext()) { AppBuilderClientResult result = itor.next(); System.out.println(result); } } } ``` #### Run方法回复工作流Agent “信息收集节点”使用示例: 使用[“飞行客服小助手”](https://cloud.baidu.com/doc/AppBuilder/s/cm38k8nqr)作为工作流Agent的示例应用 ```java package org.example; import java.io.IOException; import java.util.*; import com.google.gson.annotations.SerializedName; import com.baidubce.appbuilder.base.exception.AppBuilderServerException; import com.baidubce.appbuilder.console.appbuilderclient.AppBuilderClient; import com.baidubce.appbuilder.model.appbuilderclient.AppBuilderClientIterator; import com.baidubce.appbuilder.model.appbuilderclient.AppBuilderClientResult; import com.baidubce.appbuilder.model.appbuilderclient.AppBuilderClientRunRequest; import com.baidubce.appbuilder.model.appbuilderclient.Event; import com.baidubce.appbuilder.base.utils.json.JsonUtils; class AppBuilderClientDemo { public static void main(String[] args) throws IOException, AppBuilderServerException { System.setProperty("APPBUILDER_TOKEN", "请设置正确的应用密钥"); String chatflowAppId = "请设置正确的应用ID"; AppBuilderClient builder = new AppBuilderClient(chatflowAppId); String conversationId = builder.createConversation(); AppBuilderClientRunRequest request = new AppBuilderClientRunRequest(chatflowAppId, conversationId, "查天气", true); Stack interruptStack = new Stack(); AppBuilderClientIterator itor = builder.run(request); String interruptEventId = ""; while (itor.hasNext()) { AppBuilderClientResult result = itor.next(); for (Event event : result.getEvents()) { if (event.getContentType().equals(EventContent.PublishMessageContentType)) { String message = event.getDetail().get("message").toString(); System.out.println(message); } if (event.getContentType().equals(EventContent.ChatflowInterruptContentType)) { interruptEventId = event.getDetail().get("interrupt_event_id").toString(); interruptStack.push(interruptEventId); break; } } } interruptEventId = ""; AppBuilderClientRunRequest request2 = new AppBuilderClientRunRequest(chatflowAppId, conversationId, "我先查个航班动态", true); request2.setAction(AppBuilderClientRunRequest.Action.createAction(interruptStack.pop())); AppBuilderClientIterator itor2 = builder.run(request2); while (itor2.hasNext()) { AppBuilderClientResult result2 = itor2.next(); for (Event event : result2.getEvents()) { if (event.getContentType().equals(EventContent.PublishMessageContentType)) { String message = event.getDetail().get("message").toString(); System.out.println(message); } if (event.getContentType().equals(EventContent.ChatflowInterruptContentType)) { interruptEventId = event.getDetail().get("interrupt_event_id").toString(); interruptStack.push(interruptEventId); break; } } } interruptEventId = ""; AppBuilderClientRunRequest request3 = new AppBuilderClientRunRequest(chatflowAppId, conversationId, "CA1234", true); request3.setAction(AppBuilderClientRunRequest.Action.createAction(interruptStack.pop())); AppBuilderClientIterator itor3 = builder.run(request3); while (itor3.hasNext()) { AppBuilderClientResult result3 = itor3.next(); for (Event event : result3.getEvents()) { if (event.getContentType().equals(EventContent.TextContentType)) { String text = event.getDetail().get("text").toString(); System.out.println(text); } if (event.getContentType().equals(EventContent.ChatflowInterruptContentType)) { interruptEventId = event.getDetail().get("interrupt_event_id").toString(); interruptStack.push(interruptEventId); break; } } } boolean hasMultipleContentType = false; AppBuilderClientRunRequest request4 = new AppBuilderClientRunRequest(chatflowAppId, conversationId, "北京的", true); request4.setAction(AppBuilderClientRunRequest.Action.createAction(interruptStack.pop())); AppBuilderClientIterator itor4 = builder.run(request4); while (itor4.hasNext()) { AppBuilderClientResult result4 = itor4.next(); for (Event event : result4.getEvents()) { if (event.getContentType().equals(EventContent.TextContentType)) { String text = event.getDetail().get("text").toString(); System.out.println(text); } if (event.getContentType().equals(EventContent.MultipleDialogEventContentType)) { hasMultipleContentType = true; break; } } } } } ``` ## Go基本用法 ### ```NewAppBuilderClient()``` #### 方法参数 | 参数名称 | 参数类型 | 描述 | 示例值 | | -------- | --------- | ----------------- | -------------- | | app_id | string | 线上Agent应用的ID | "正确的应用ID" | | config | SDKConfig | SDK配置信息 | | ### ```CreateConversation()``` #### 方法入参 无 #### 方法出参 | 参数名称 | 参数类型 | 描述 | 示例值 | | -------------- | -------- | -------------------------------------------- | ------ | | ConversationId | str | 创建成功的对话对象,后续操作都基于该对象进行 | | ### `Run()` #### Run方法入参`AppBuilderClientRunRequest` | 参数名称 | 参数类型 | 是否必须 | 描述 | 示例值 | | -------------- | ---------- | -------- | ------------------------------------------------------------ | -------------------- | | ConversationID | string | 是 | 对话ID,可以通过CreateConversation()获取 | | | Query | string | 是 | query内容 | "汽车性能参数怎么样" | | Stream | bool | 是 | 为true时则流式返回,为false时则一次性返回所有内容, 推荐设为true,降低首token时延 | | | AppID | string | 是 | 应用ID,线上Agent应用的ID | | | Tools | []Tool | 否 | 一个列表,其中每个字典对应一个工具的配置 | | | ToolOuptus | []ToolOupt | 否 | 内容为本地的工具执行结果,以自然语言/json dump str描述 | | | ToolChoice | ToolChoice | 否 | 控制大模型使用组件的方式,仅对自主规划Agent生效。 | | `Tool`、`ToolOutput`、`ToolChoice`定义如下: ```go type Tool struct { Type string `json:"type"` Function Function `json:"function"` } type Function struct { Name string `json:"name"` Description string `json:"description"` Parameters map[string]interface{} `json:"parameters"` } type ToolOutput struct { ToolCallID string `json:"tool_call_id" description:"工具调用ID"` Output string `json:"output" description:"工具输出"` } type ToolChoice struct { Type string `json:"type"` Function ToolChoiceFunction `json:"function"` } type ToolChoiceFunction struct { Name string `json:"name"` Input map[string]interface{} `json:"input"` } ``` #### Run方法出参 | 参数名称 | 参数类型 | 描述 | 示例值 | | ------------------------ | ------------------------ | --------------------------------------- | ------ | | AppBuilderClientIterator | AppBuilderClientIterator | 回答迭代器,流式/非流式均统一返回该类型 | | | error | error | 存在错误时error不为nil,反之 | | #### 迭代AgentBuilderIterator | 参数名称 | 参数类型 | 描述 | 示例值 | | ------------- | ----------- | -------------------- | --------------------------------------------------------------------------------------- | | +Answer | string | 智能体应用返回的回答 | | | +Events | []Event | 事件列表 | | | +Events[0] | Event | 具体事件内容 | | | ++Code | string | 错误码 | | | ++Message | string | 错误具体消息 | | | ++Status | string | 事件状态 | 状态描述,preparing(准备运行)running(运行中)error(执行错误) done(执行完成) | | ++EventType | string | 事件类型 | | | ++ContentType | string | 内容类型 | 可选值包括:code text, image, status,image, function_call, rag, audio、video等 | | ++Detail | interface{} | 事件输出详情 | 代码解释器、文生图、工具组件、RAG等的详细输出内容 | | ++Usage | Usage | 模型调用的token用量 | Usage(prompt_tokens=1322, completion_tokens=80, total_tokens=1402, name='DeepSeek-V3.1') | #### Run示例代码 ```Go // 安装说明: // go get github.com/baidubce/app-builder/go/appbuilder package main import ( "errors" "fmt" "io" "os" "github.com/baidubce/app-builder/go/appbuilder" ) func main() { // 设置环境中的TOKEN,以下TOKEN请替换为您的个人TOKEN,个人TOKEN可通过该页面【获取鉴权参数】或控制台页【密钥管理】处获取 os.Setenv("APPBUILDER_TOKEN", "bce-v3/ALTAK-xxx90ea58") // 从AppBuilder控制台【个人空间】-【应用】网页获取已发布应用的ID appID := "4678492a-xxx-654538d3503c" config, err := appbuilder.NewSDKConfig("", "") if err != nil { fmt.Println("new config failed: ", err) return } builder, err := appbuilder.NewAppBuilderClient(appID, config) if err != nil { fmt.Println("new agent builder failed: ", err) return } conversationID, err := builder.CreateConversation() if err != nil { fmt.Println("create conversation failed: ", err) return } i, err := builder.Run(conversationID, "你好,你能做什么?", nil, false) if err != nil { fmt.Println("run failed: ", err) return } var answer *appbuilder.AppBuilderClientAnswer for answer, err = i.Next(); err == nil; answer, err = i.Next() { fmt.Println(answer.Answer) } } ``` #### ToolCall功能示例代码 ```go package main import ( "errors" "fmt" "io" "os" "github.com/baidubce/app-builder/go/appbuilder" ) func main() { // 设置APPBUILDER_TOKEN、GATEWAY_URL_V2环境变量 os.Setenv("APPBUILDER_TOKEN", "请设置正确的应用密钥") // 默认可不填,默认值是 https://qianfan.baidubce.com os.Setenv("GATEWAY_URL_V2", "") config, err := appbuilder.NewSDKConfig("", "") if err != nil { fmt.Println("new config failed: ", err) return } // 初始化实例 appID := "请填写正确的应用ID" builder, err := appbuilder.NewAppBuilderClient(appID, config) if err != nil { fmt.Println("new agent builder failed: ", err) return } // 创建对话ID conversationID, err := builder.CreateConversation() if err != nil { fmt.Println("create conversation failed: ", err) return } jsonStr := ` { "type": "function", "function": { "name": "get_cur_whether", "description": "这是一个获得指定地点天气的工具", "parameters": { "type": "object", "properties": { "location": { "type": "string", "description": "省,市名,例如:河北省" }, "unit": { "type": "string", "enum": ["摄氏度", "华氏度"] } }, "required": ["location"] } } }` var tool Tool err = json.Unmarshal([]byte(jsonStr), &tool) if err != nil { fmt.Println("unmarshal tool error:", err) return } i, err := client.Run(appbuilder.AppBuilderClientRunRequest{ AppID: appID, Query: "今天北京的天气怎么样?", ConversationID: conversationID, Stream: true, Tools: []appbuilder.Tool{tool}, }) if err != nil { fmt.Println("run failed:", err) } totalAnswer := "" toolCallID := "" for answer, err := i.Next(); err == nil; answer, err = i.Next() { totalAnswer += answer.Answer lastEvent := answer.Events[len(answer.Events)-1] toolCallID = lastEvent.ToolCalls[len(lastEvent.ToolCalls)-1].ID } i2, err := client.Run(appbuilder.AppBuilderClientRunRequest{ ConversationID: conversationID, AppID: appID, ToolOutputs: []appbuilder.ToolOutput{ { ToolCallID: toolCallID, Output: "北京今天35度", }, }, Stream: true, }) if err != nil { fmt.Println("run failed: ", err) } for answer, err := i2.Next(); err == nil; answer, err = i2.Next() { totalAnswer = totalAnswer + answer.Answer for _, ev := range answer.Events { evJSON, _ := json.Marshal(ev) fmt.Println(string(evJSON)) } } fmt.Println("----------------answer-------------------") fmt.Println(totalAnswer) } ``` #### ToolChoice示例代码 * 注意:当前功能为试运行阶段,可能存在如下问题,如使用过程遇到其他问题,欢迎提issue或微信群讨论。 * 需开启"组件/知识库结论可直接作为回复" * 组件名称不是界面上的原始名字,而是个人空间组件列表中的英文名 * 自定义组件的参数不能使用系统参数,可以使用用户添加的参数 * 部分官方组件使用的参数与界面上的参数不一致 ```go package main import ( "errors" "fmt" "io" "os" "github.com/baidubce/app-builder/go/appbuilder" ) func main() { // 设置APPBUILDER_TOKEN、GATEWAY_URL_V2环境变量 os.Setenv("APPBUILDER_TOKEN", "请设置正确的应用密钥") // 默认可不填,默认值是 https://qianfan.baidubce.com os.Setenv("GATEWAY_URL_V2", "") config, err := appbuilder.NewSDKConfig("", "") if err != nil { fmt.Println("new config failed: ", err) return } // 初始化实例 appID := "请填写正确的应用ID" builder, err := appbuilder.NewAppBuilderClient(appID, config) if err != nil { fmt.Println("new agent builder failed: ", err) return } // 创建对话ID conversationID, err := builder.CreateConversation() if err != nil { fmt.Println("create conversation failed: ", err) return } // 注意使用创建应用中用到的组件。名称、参数均以实际使用的组件为准。 input := make(map[string]any) input["city"] = "北京" end_user_id := "go_toolchoice_demo" i, err := client.Run(AppBuilderClientRunRequest{ ConversationID: conversationID, AppID: appID, Query: "", EndUserID: &end_user_id, Stream: false, ToolChoice: &ToolChoice{ Type: "function", Function: ToolChoiceFunction{ Name: "WeatherQuery", Input: input, }, }, }) if err != nil { fmt.Println("run failed: ", err) return } for answer, err := i.Next(); err == nil; answer, err = i.Next() { for _, ev := range answer.Events { evJSON, _ := json.Marshal(ev) fmt.Println(string(evJSON)) } } } ``` #### Run方法回复工作流Agent “信息收集节点”使用示例: 使用[“飞行客服小助手”](https://cloud.baidu.com/doc/AppBuilder/s/cm38k8nqr)作为工作流Agent的示例应用 ```go package main import ( "fmt" "os" "github.com/baidubce/app-builder/go/appbuilder" ) func main() { // 设置APPBUILDER_TOKEN、GATEWAY_URL_V2环境变量 os.Setenv("APPBUILDER_TOKEN", "请设置正确的应用密钥") // 默认可不填,默认值是 https://qianfan.baidubce.com os.Setenv("GATEWAY_URL_V2", "") config, err := appbuilder.NewSDKConfig("", "") if err != nil { fmt.Println("new config failed: ", err) return } // 初始化实例 appID := "请填写正确的应用ID" client, err := appbuilder.NewAppBuilderClient(appID, config) if err != nil { fmt.Println("new agent builder failed: ", err) return } // 创建对话ID conversationID, err := client.CreateConversation() if err != nil { fmt.Println("create conversation failed: ", err) return } i, err := client.Run(appbuilder.AppBuilderClientRunRequest{ ConversationID: conversationID, AppID: appID, Query: "查天气", Stream: true, }) if err != nil { fmt.Println("run failed: ", err) return } var interruptId string interruptStack := make([]string, 0) for answer, err := i.Next(); err == nil; answer, err = i.Next() { for _, ev := range answer.Events { if ev.ContentType == appbuilder.PublishMessageContentType { detail := ev.Detail.(appbuilder.PublishMessageDetail) message := detail.Message fmt.Println(message) break } if ev.ContentType == appbuilder.ChatflowInterruptContentType { deatil := ev.Detail.(appbuilder.ChatflowInterruptDetail) interruptId = deatil.InterruptEventID interruptStack = append(interruptStack, interruptId) break } } } if len(interruptId) == 0 { fmt.Println("interrupt id is empty") return } interruptId = "" i2, err := client.Run(appbuilder.AppBuilderClientRunRequest{ ConversationID: conversationID, AppID: appID, Query: "我先查个航班动态", Stream: true, Action: appbuilder.NewResumeAction(interruptStack[len(interruptStack)-1]), }) if err != nil { fmt.Println("run failed:", err) return } interruptStack = interruptStack[:len(interruptStack)-1] for answer, err := i2.Next(); err == nil; answer, err = i2.Next() { for _, ev := range answer.Events { if ev.ContentType == appbuilder.PublishMessageContentType { detail := ev.Detail.(appbuilder.PublishMessageDetail) message := detail.Message fmt.Println(message) break } if ev.ContentType == appbuilder.ChatflowInterruptContentType { deatil := ev.Detail.(appbuilder.ChatflowInterruptDetail) interruptId = deatil.InterruptEventID interruptStack = append(interruptStack, interruptId) break } } } if len(interruptId) == 0 { fmt.Println("interrupt id is empty") return } interruptId = "" i3, err := client.Run(appbuilder.AppBuilderClientRunRequest{ ConversationID: conversationID, AppID: appID, Query: "CA1234", Stream: true, Action: appbuilder.NewResumeAction(interruptStack[len(interruptStack)-1]), }) if err != nil { fmt.Println("run failed:", err) return } interruptStack = interruptStack[:len(interruptStack)-1] for answer, err := i3.Next(); err == nil; answer, err = i3.Next() { for _, ev := range answer.Events { if ev.ContentType == appbuilder.TextContentType { detail := ev.Detail.(appbuilder.TextDetail) text := detail.Text fmt.Println(text) break } if ev.ContentType == appbuilder.ChatflowInterruptContentType { deatil := ev.Detail.(appbuilder.ChatflowInterruptDetail) interruptId = deatil.InterruptEventID interruptStack = append(interruptStack, interruptId) break } } } if len(interruptId) == 0 { fmt.Println("interrupt id is empty") return } i4, err := client.Run(appbuilder.AppBuilderClientRunRequest{ ConversationID: conversationID, AppID: appID, Query: "北京的", Stream: true, Action: appbuilder.NewResumeAction(interruptStack[len(interruptStack)-1]), }) if err != nil { fmt.Println("run failed:", err) return } for answer, err := i4.Next(); err == nil; answer, err = i4.Next() { for _, ev := range answer.Events { if ev.ContentType == appbuilder.TextContentType { detail := ev.Detail.(appbuilder.TextDetail) text := detail.Text fmt.Println(text) break } } } } ``` ================================================ FILE: docs/BasisModule/Platform/Application/get_app_list.md ================================================ # 获取AppBuilder已发布的应用列表 ## 简介 该接口可获取用户在 AppBuilder已发布的应用列表,包括应用名称、应用描述、应用的ID、应用类型、应用发布状态等 ## Python基本用法 ### 获取app_list接口 `appbuilder.describe_apps()` #### 鉴权配置 使用组件之前,请首先申请并设置鉴权参数,可参考[组件使用流程](https://cloud.baidu.com/doc/AppBuilder/s/Olq6grrt6#1%E3%80%81%E5%88%9B%E5%BB%BA%E5%AF%86%E9%92%A5)。 ```python # 设置环境中的TOKEN,以下示例略 os.environ["APPBUILDER_TOKEN"] = "bce-YOURTOKEN" ``` #### 初始化参数 | 参数名称 | 参数类型 | 描述 | 示例值 | |------------|--------|---------|------------| | maxKeys | int | 返回结果的最大数量,默认值为10, 最大值为100 | 10 | | marker | str | 分页游标,返回结果中第一个应用的游标值,接口会返回该应用及之后的应用,用于分页查询。默认值为空字符串。 | app_id | #### 返回参数 `describe_apps`方法返回类型为 `list[AppOverview]`,其中 `AppOverview` 结构如下: ```python class AppOverview(BaseModel): id: str = Field("", description="应用ID") name: str = Field("", description="应用名称") description: str = Field("", description="应用简介") appType: Optional[str] = Field( None, description="应用类型:agent、chatflow。agent:自主规划Agent, chatflow:工作流Agent。" ) isPublished: Optional[bool] = Field(None, description="是否已发布") updateTime: Optional[int] = Field(None, description="更新时间。时间戳,单位秒") ``` #### 代码示例 下面是模型列表获取功能的代码示例: ```python import os import appbuilder # 设置环境变量和初始化 # 请前往千帆AppBuilder官网创建密钥,流程详见:https://cloud.baidu.com/doc/AppBuilder/s/Olq6grrt6#1%E3%80%81%E5%88%9B%E5%BB%BA%E5%AF%86%E9%92%A5 os.environ["APPBUILDER_TOKEN"] = "..." app_list = appbuilder.describe_apps() print(app_list) ``` 返回值为 ```shell [AppOverview(id='e97865e7-e1be-45d3-ab8a-ea84ca6e0b9a', name='二次元风格图片生成助手', description='生成二次元风格图片,一键生成你的专属动漫风格作品'), AppOverview(id='982aaa98-60d4-4120-b4ab-3404a95a61e1', name='智能客服机器人', description='智能回答文字问题,解析程序报错并给出建议'), AppOverview(id='c59cb95b-8c42-4102-8582-df07bde8d4cc', name='招聘海报大师', description='一键生成招聘海报,高效宣传职位需求'), AppOverview(id='42eb211a-14b9-43d2-9fae-193c8760ef26', name='地理小达人', description='提供地理知识解答,如地名由来、地形地貌等。')] ``` ### 获取app数目接口 `appbuilder.get_all_apps()` #### 返回参数 `get_all_apps`方法返回类型为 `list[AppOverview]`,,其中 `AppOverview` 结构如下: ```python class AppOverview(BaseModel): id: str = Field("", description="应用ID") name: str = Field("", description="应用名称") description: str = Field("", description="应用简介") appType: Optional[str] = Field( None, description="应用类型:agent、chatflow。agent:自主规划Agent, chatflow:工作流Agent。" ) isPublished: Optional[bool] = Field(None, description="是否已发布") updateTime: Optional[int] = Field(None, description="更新时间。时间戳,单位秒") ``` #### 代码示例 下面是模型列表获取功能的代码示例: ```python import os import appbuilder # 设置环境变量和初始化 # 请前往千帆AppBuilder官网创建密钥,流程详见:https://cloud.baidu.com/doc/AppBuilder/s/Olq6grrt6#1%E3%80%81%E5%88%9B%E5%BB%BA%E5%AF%86%E9%92%A5 os.environ["APPBUILDER_TOKEN"] = "..." all_apps = appbuilder.get_all_apps() for i in range(len(all_apps)): print("第{}个App,App信息:{}".format(i+1,all_apps[i])) print("创建的app总数为:{}".format(len(all_apps))) ``` ## Java基本用法 #### 接口参数及返回值 与 `python appbuilder.describe_apps()`设计一致 #### 代码示例 ```java public void GetAppsTest() throws IOException, AppBuilderServerException { AppList appList = new AppList(); AppsDescribeRequest request = new AppsDescribeRequest(); assertNotNull(appList.describeApps(request).getData()[0].getId()); } ``` ## Go基本用法 #### 接口参数及返回值 与 `python appbuilder.describe_apps()`设计一致 #### 代码示例 ```go import ( "fmt" "os" "github.com/baidubce/app-builder/go/appbuilder" ) func main() { // 设置APPBUILDER_TOKEN、GATEWAY_URL环境变量 os.Setenv("APPBUILDER_TOKEN", "请设置正确的应用密钥") config, err := appbuilder.NewSDKConfig("", "") if err != nil { fmt.Println("failed new sdk config: ", err) return } maxKeys := 10 apps, err := appbuilder.DescribeApps(appbuilder.DescribeAppsRequest{MaxKeys: &maxKeys}, config) if err != nil { fmt.Println("get apps failed: ", err) } fmt.Println(len(apps.Data)) } ``` ## 高级用法 目前该模块提供获取AppBuilder已发布应用的功能,获取的应用ID,可以配合`AppBuilderClient` SDK进行应用调用。 ## 更新记录和贡献 * 千帆模型列表获取能力 (2024-7) * 接口结构升级(2024-11) ================================================ FILE: docs/BasisModule/Platform/CustomComponents/component_client.md ================================================ # ComponentClient ## 简介 ComponentClient组件支持调用在[百度智能云千帆AppBuilder](https://cloud.baidu.com/product/AppBuilder)平台上创建的自定义工作流组件。 ### 功能介绍 具体包括运行等。 ### 特色优势 与云端工作流组件能力打通,实现低代码会话 ### 应用场景 快速、高效集成云端工作流组件能力 ### `ComponentClient().run() -> Message` #### 方法参数 | 参数名称 | 参数类型 | 是否必须 | 描述 | 示例值 | | -------------------- | -------- | -------- | ------------------------------------------------------------ | ----------------- | | component_id | String | 是 | 组件ID。可以在个人空间-组件下查看。 | | | sys_origin_query | String | 是 | query问题内容 | "今天天气怎么样?" | | version | String | 否 | 组件版本 | | | stream | Bool | 否 | 为true时则流式返回,为false时则一次性返回所有内容, 默认为false | False | | action | String | 否 | 调用方式。
默认值是tool_eval。 | | | sys_file_urls | Dict | 否 | 文件路径。对应画布中开始节点的系统参数fileUrls,格式为{"文件名": "文件路径"},例如{"xxx.pdf": "http:///"}。 | | | sys_conversatiaon_id | String | 否 | 对话id。对应画布中开始节点的系统参数conversation_id,可通过新建会话接口创建。 | | | sys_chat_history | Dict | 否 | 组件使用的累计对话历史。对应画布中开始节点的系统参数chatHistory。{"role": "", "content": ""} | | | sys_end_user_id | String | 否 | 终端用户id。对应画布中开始节点的系统参数end_user_id。 | | | input_variable_name | Object | 否 | 用户自定义参数 | | #### Run方法非流式返回值 Run非流式方法返回一个`Message`对象,`Message`通过`RunResponse`封装,该对象包含以下属性: | 参数名称 | 参数类型 | 是否必填 | 示例值 | | --------------- | ------------- | -------- | ------------------------------------------------------------ | |request_id | string | 是 | 请求request_id | |code | string | 否 | 错误代码,当发生异常时返回 | |message | string | 否 | 错误信息,当发生异常时返回 | | conversation_id | string | 是 | 会话标识UUID。 | | message_id | string | 是 | 一问或一答的标识UUID。 | | trace_id | string | 是 | 调用标识UUID。 | | user_id | string | 是 | 开发者UUID(计费依赖)。 | | end_user_id | string | 否 | 终端用户ID。 | |status | string | 是 | 状态码。
枚举值:
- running,对话进行过程中
- done,对话结束
- error,执行过程发生错误
- interrupt,中断| | is_completion | bool | 是 | 标识当前端到端的流式调用是否结束。 | | role | string | 是 | 当前消息来源,默认tool 。 | | content | list[Content] | 否 | 当前组件返回内容的主要payload,List[Content],每个 Content 包括了当前 event 的一个元素,具体见下文Content对象定义。 | `Content`类型定义如下: | 参数名称 | 参数类型 | 是否必填 | 示例值 | | ------------- | ----------- | -------- | ------------------------------------------------------------ | | type | string | 是 | 代表event 类型。该字段的取值决定了下面`text`字段的内容结构。 枚举值: text、json、code、files、urls、oral_text、references、image、chart、audio、function_call。 | | name | string | 是 | 介绍当前yield内容的step name。 | | text | dict object | 是 | 代表当前 event 元素的内容,每一种 event 对应的 text 结构固定。 | | visible_scope | string | 是 | 可见范围。 枚举值: all :全部,包括大模型和用户。 llm:大模型。 user:用户。 默认为all。 | | usage | dict | 否 | 大模型的token用量,具体见下文Usage对象定义。 | | metrics | dict | 是 | 耗时信息,具体见下文Metrics对象定义。 | | event | dict | 是 | 标识返回内容的结构、顺序、状态,具体见下文Event对象定义。 | **Usage对象** | **字段** | **类型** | **必填** | **说明** | | ----------------- | ---------- | -------- | ------------------------------------------------------------ | | prompt_tokens | int | 是 | 输入token消耗 | | completion_tokens | int | 是 | 输出token消耗 | | total_tokens | int | 是 | 总token消耗 | | nodes | list[node] | 否 | 工作流节点大模型token消耗信息,列表元素具体见下文Node对象定义。 | **Node对象** | **字段** | **类型** | **必填** | **说明** | | ------------ | ----------------- | -------- | --------------------------------------------- | | node_id | string | 是 | 节点id | | models_usage | list[model_usage] | 是 | 模型消耗列表,元素见下文model_usage对象定义。 | **model_usage对象** | **字段** | **类型** | **必填** | **说明** | | ----------------- | -------- | -------- | ------------- | | model_name | string | 是 | 模型名称 | | prompt_tokens | int | 是 | 输入token消耗 | | completion_tokens | int | 是 | 输出token消耗 | | total_tokens | int | 是 | 总token消耗 | **Metrics对象** | **字段** | **类型** | **必填** | **说明** | | ---------- | -------- | -------- | --------------------------------------------------- | | begin_time | string | 是 | 请求开始时间,示例:”2000-01-01T10:00:00.560430“。 | | duration | float | 是 | 从请求到当前event总耗时,保留3位有效数字,单位秒s。 | **Event对象** | **字段** | **类型** | **必填** | **说明** | | ------------- | -------- | -------- | ------------------------------------------------------------ | | id | string | 是 | 节点id。 | | status | string | 是 | 事件执行状态。 枚举值: preparing:运行中。 running:运行中。 error:错误。 done:执行完成。 | | name | string | 是 | 事件名。 一级深度有: component,组件api。 functioncall,自主规划agent。 chatflow,工作流agent。 二级深度是组件ID。 三级深度是组件content_type。 示例: /component/eaaccc60e222418abc0f4d3d372018af/node/ 433b4cf184064daf88e8383adc83e35f | | created_time | string | 是 | 当前event发送时间。 | | error_code | string | 否 | 错误码。 | | error_message | string | 否 | 错误细节。 | #### Run方法流式返回值 | 参数名称 | 参数类型 | 描述 | 示例值 | | -------- | ---------------- | ------------------------------------- | ------ | | content | Python Generator | 可迭代,每次迭代返回`RunResponse`类型 | 无 | #### 非流式调用示例 ```python import os import appbuilder # 请前往千帆AppBuilder官网创建密钥,流程详见:https://cloud.baidu.com/doc/AppBuilder/s/Olq6grrt6#1%E3%80%81%E5%88%9B%E5%BB%BA%E5%AF%86%E9%92%A5 # 设置环境变量 os.environ["APPBUILDER_TOKEN"] = ( "..." ) # 组件ID,可在个人空间-组件下查看 component_id = "..." client = appbuilder.ComponentClient() message = client.run(component_id=component_id, version="latest", stream=False, sys_origin_query="北京景点推荐") print(message.content.content[0].text) ``` #### 流式调用示例 ```python import os import appbuilder # 请前往千帆AppBuilder官网创建密钥,流程详见:https://cloud.baidu.com/doc/AppBuilder/s/Olq6grrt6#1%E3%80%81%E5%88%9B%E5%BB%BA%E5%AF%86%E9%92%A5 # 设置环境变量 os.environ["APPBUILDER_TOKEN"] = ( "..." ) # 组件ID,可在个人空间-组件下查看 component_id = "..." client = appbuilder.ComponentClient() message = client.run(component_id=component_id, version="latest", stream=True, sys_origin_query="北京景点推荐") for content in message.content: if len(content.content)>0: print(content.content[0].text) ``` ## Java基本用法 ### ```new ComponentClient()``` #### 方法返回值 ```ComponentClient```实例化对象 ### ```ComponentClient().run()``` #### run方法入参 | 参数名称 | 参数类型 | 是否必须 | 描述 | 示例值 | | ---------------------- | -------- | -------- | ------------------------------------------------------------ | ------ | | componentId | String | 是 | 组件ID。可以在个人空间-组件下查看。 | | | version | String | 否 | 组件版本 | | | action | String | 否 | 调用方式。
默认值是tool_eval。 | | | stream | Bool | 是 | 为true时则流式返回,为false时则一次性返回所有内容, 默认为false | false | | parameters | Map | 是 | 调用传参 | | | +_sys_origin_query | string | 是 | 用户query,对应画布中开始节点的系统参数rawQuery。 | | | +_sys_file_urls | Dict | 否 | 文件路径。对应画布中开始节点的系统参数fileUrls,格式为{"文件名": "文件路径"},例如{"xxx.pdf": "http:///"}。 | | | +_sys_conversatiaon_id | String | 否 | 对话id。对应画布中开始节点的系统参数conversation_id,可通过新建会话接口创建。 | | | +_sys_chat_history | Dict | 否 | 组件使用的累计对话历史。对应画布中开始节点的系统参数chatHistory。{"role": "", "content": ""} | | | +_sys_end_user_id | String | 否 | 终端用户id。对应画布中开始节点的系统参数end_user_id。 | | | + input_variable_name | object | 否 | 用户自定义添加的参数,对应画布中开始节点用户新增的参数。注意,用户自定义参数和系统参数为一级,同在**parameters中。**例如:

"parameters":
{
"_sys_origin_query": "今天有什么新闻",
"custom_count": 4
}
| | #### run方法出参 | 参数名称 | 参数类型 | 描述 | 示例值 | | ----------------------- | ----------------------- | ------------------------------------------------------------ | ------ | | ComponentClientIterator | ComponentClientIterator | 回答迭代器,流式/非流式均统一返回该类型,每次迭代返回ComponentClientIterator类型 | | #### 迭代ComponentClientIterator | **字段** | **类型** | **必填** | **说明** | | -------------- | ----------------- | -------- | ------------------------------------------------------------ | | conversationID | string | 是 | 会话标识UUID。 | | messageID | string | 是 | 一问或一答的标识UUID。 | | traceID | string | 是 | 调用标识UUID。 | | userID | string | 是 | 开发者UUID(计费依赖)。 | | endUserId | string | 否 | 终端用户ID。 | | isCompletion | bool | 是 | 标识当前端到端的流式调用是否结束。 | | role | string | 是 | 当前消息来源,默认tool 。 | | **content** | **list[Content]** | **否** | **当前组件返回内容的主要payload,List[Content],每个 Content 包括了当前 event 的一个元素,具体见下文Content对象定义。** | **Content对象** | **字段** | **类型** | **必填** | **说明** | | ------------ | ----------- | -------- | ------------------------------------------------------------ | | type | string | 是 | 代表event 类型,该字段的取值决定了下面`text`字段的内容结构。枚举值: text、json、code、files、urls、oral_text、references、image、chart、audio、function_call | | name | string | 是 | 介绍当前yield内容的step name | | text | dict object | 是 | 代表当前 event 元素的内容,每一种 event 对应的 text 结构固定。 | | visibleScope | string | 是 | 可见范围。枚举值:all :全部,包括大模型和用户llm:大模型user:用户默认为all | | **usage** | **dict** | **否** | **大模型的token用量,具体见下文Usage对象定义。** | | **metrics** | **dict** | **是** | **耗时信息,具体见下文Metrics对象定义。** | | **event** | **dict** | **是** | **标识返回内容的结构、顺序、状态,具体见下文Event对象定义。** | **Usage对象** | **字段** | **类型** | **必填** | **说明** | | ----------------- | -------------- | -------- | ------------------------------------------------------------ | | prompt_tokens | int | 是 | 输入token消耗 | | completion_tokens | int | 是 | 输出token消耗 | | total_tokens | int | 是 | 总token消耗 | | **nodes** | **list[node]** | **否** | **工作流节点大模型token消耗信息,列表元素****具体见下文Node对象定义。** | **Node对象** | **字段** | **类型** | **必填** | **说明** | | ---------------- | --------------------- | -------- | ------------------------------------------------- | | node_id | string | 是 | 节点id | | **models_usage** | **list[model_usage]** | **是** | **模型消耗列表,元素见下文model_usage对象定义。** | **model_usage对象** | **字段** | **类型** | **必填** | **说明** | | ----------------- | -------- | -------- | ------------- | | model_name | string | 是 | 模型名称 | | prompt_tokens | int | 是 | 输入token消耗 | | completion_tokens | int | 是 | 输出token消耗 | | total_tokens | int | 是 | 总token消耗 | **Metrics对象** | **字段** | **类型** | **必填** | **说明** | | ---------- | -------- | -------- | --------------------------------------------------- | | begin_time | string | 是 | 请求开始时间,示例:”2000-01-01T10:00:00.560430“。 | | duration | float | 是 | 从请求到当前event总耗时,保留3位有效数字,单位秒s。 | **Event对象** | **字段** | **类型** | **必填** | **说明** | | ------------ | -------- | -------- | ------------------------------------------------------------ | | id | string | 是 | 节点id | | status | string | 是 | 事件执行状态。枚举值:preparing:运行中running:运行中error:错误done:执行完成 | | name | string | 是 | 事件名。一级深度有:component,组件apifunctioncall,自主规划agentchatflow,工作流agent二级深度是组件ID三级深度是组件content_type示例:/component/eaaccc60e222418abc0f4d3d372018af/node/433b4cf184064daf88e8383adc83e35f | | createdTime | string | 是 | 当前event发送时间。 | | errorCode | string | 否 | 错误码。 | | errorMessage | string | 否 | 错误细节。 | #### 示例代码 ```Java package com.baidubce.appbuilder.demo; import com.baidubce.appbuilder.base.exception.AppBuilderServerException; import com.baidubce.appbuilder.console.componentclient.ComponentClient; import com.baidubce.appbuilder.model.componentclient.ComponentClientIterator; import com.baidubce.appbuilder.model.componentclient.ComponentClientRunRequest; import com.baidubce.appbuilder.model.componentclient.ComponentClientRunResponse; import java.io.IOException; import java.util.HashMap; import java.util.Map; public class ComponentClientDemo { public static void main(String[] args) { // 组件ID,可在个人空间-组件下查看 String componentId = "..."; try { ComponentClient client = new ComponentClient(); Map parameters = new HashMap<>(); parameters.put(ComponentClientRunRequest.SysOriginQuery, "北京景点推荐"); // Run without streaming ComponentClientIterator iter = client.run(componentId, "latest", "", false, parameters); while (iter.hasNext()) { ComponentClientRunResponse response = iter.next(); if(response.getContent().length > 0) { Map textMap = (Map) response.getContent()[0].getText(); System.out.println("Without streaming: " + textMap.toString()); } } // Run with streaming iter = client.run(componentId, "latest", "", true, parameters); Map textMap = null; while (iter.hasNext()) { ComponentClientRunResponse response = iter.next(); if (response.getContent().length > 0) { textMap = (Map) response.getContent()[0].getText(); } } if (textMap != null) { System.out.println("With streaming: " + textMap.toString()); } } catch (IOException | AppBuilderServerException e) { e.printStackTrace(); } } } ``` ## Go基本用法 ### ```NewComponentClient()``` #### 方法参数 | 参数名称 | 参数类型 | 描述 | 示例值 | | -------- | --------- | ----------- | ------ | | config | SDKConfig | SDK配置信息 | | ### `Run()` #### Run方法入参 #### | 参数名称 | 参数类型 | 是否必须 | 描述 | 示例值 | | ---------------------- | -------- | -------- | ------------------------------------------------------------ | ------ | | componentId | String | 是 | 组件ID。可以在个人空间-组件下查看。 | | | version | String | 否 | 组件版本 | | | action | String | 否 | 调用方式。
默认值是tool_eval。 | | | stream | Bool | 是 | 为true时则流式返回,为false时则一次性返回所有内容, 默认为false | false | | parameters | Map | 是 | 调用传参 | | | +_sys_origin_query | string | 是 | 用户query,对应画布中开始节点的系统参数rawQuery。 | | | +_sys_file_urls | Dict | 否 | 文件路径。对应画布中开始节点的系统参数fileUrls,格式为{"文件名": "文件路径"},例如{"xxx.pdf": "http:///"}。 | | | +_sys_conversatiaon_id | String | 否 | 对话id。对应画布中开始节点的系统参数conversation_id,可通过新建会话接口创建。 | | | +_sys_chat_history | Dict | 否 | 组件使用的累计对话历史。对应画布中开始节点的系统参数chatHistory。{"role": "", "content": ""} | | | +_sys_end_user_id | String | 否 | 终端用户id。对应画布中开始节点的系统参数end_user_id。 | | | + input_variable_name | object | 否 | 用户自定义添加的参数,对应画布中开始节点用户新增的参数。注意,用户自定义参数和系统参数为一级,同在**parameters中。**例如:

"parameters":
{
"_sys_origin_query": "今天有什么新闻",
"custom_count": 4
}
| | #### Run方法出参 | 参数名称 | 参数类型 | 描述 | 示例值 | | ----------------------- | ----------------------- | --------------------------------------- | ------ | | ComponentClientIterator | ComponentClientIterator | 回答迭代器,流式/非流式均统一返回该类型 | | | error | error | 存在错误时error不为nil,反之 | | #### 迭代ComponentClientIterator | **字段** | **类型** | **必填** | **说明** | | -------------- | ----------------- | -------- | ------------------------------------------------------------ | | ConversationID | string | 是 | 会话标识UUID。 | | MessageID | string | 是 | 一问或一答的标识UUID。 | | TraceID | string | 是 | 调用标识UUID。 | | UserID | string | 是 | 开发者UUID(计费依赖)。 | | EndUserID | string | 否 | 终端用户ID。 | | IsCompletion | bool | 是 | 标识当前端到端的流式调用是否结束。 | | Role | string | 是 | 当前消息来源,默认tool 。 | | **Content** | **list[Content]** | **否** | **当前组件返回内容的主要payload,List[Content],每个 Content 包括了当前 event 的一个元素,具体见下文Content对象定义。** | **Content对象** | **字段** | **类型** | **必填** | **说明** | | ------------ | ----------- | -------- | ------------------------------------------------------------ | | Type | string | 是 | 代表event 类型,该字段的取值决定了下面`text`字段的内容结构。枚举值: text、json、code、files、urls、oral_text、references、image、chart、audio、function_call | | Name | string | 是 | 介绍当前yield内容的step name | | Text | dict object | 是 | 代表当前 event 元素的内容,每一种 event 对应的 text 结构固定。 | | VisibleScope | string | 是 | 可见范围。枚举值:all :全部,包括大模型和用户llm:大模型user:用户默认为all | | **Usage** | **dict** | **否** | **大模型的token用量,具体见下文Usage对象定义。** | | **Metrics** | **dict** | **是** | **耗时信息,具体见下文Metrics对象定义。** | | **Event** | **dict** | **是** | **标识返回内容的结构、顺序、状态,具体见下文Event对象定义。** | **Usage对象** | **字段** | **类型** | **必填** | **说明** | | ----------------- | -------------- | -------- | ------------------------------------------------------------ | | prompt_tokens | int | 是 | 输入token消耗 | | completion_tokens | int | 是 | 输出token消耗 | | total_tokens | int | 是 | 总token消耗 | | **nodes** | **list[node]** | **否** | **工作流节点大模型token消耗信息,列表元素****具体见下文Node对象定义。** | **Node对象** | **字段** | **类型** | **必填** | **说明** | | ---------------- | --------------------- | -------- | ------------------------------------------------- | | node_id | string | 是 | 节点id | | **models_usage** | **list[model_usage]** | **是** | **模型消耗列表,元素见下文model_usage对象定义。** | **model_usage对象** | **字段** | **类型** | **必填** | **说明** | | ----------------- | -------- | -------- | ------------- | | model_name | string | 是 | 模型名称 | | prompt_tokens | int | 是 | 输入token消耗 | | completion_tokens | int | 是 | 输出token消耗 | | total_tokens | int | 是 | 总token消耗 | **Metrics对象** | **字段** | **类型** | **必填** | **说明** | | ---------- | -------- | -------- | --------------------------------------------------- | | begin_time | string | 是 | 请求开始时间,示例:”2000-01-01T10:00:00.560430“。 | | duration | float | 是 | 从请求到当前event总耗时,保留3位有效数字,单位秒s。 | **Event对象** | **字段** | **类型** | **必填** | **说明** | | ------------ | -------- | -------- | ------------------------------------------------------------ | | ID | string | 是 | 节点id | | Status | string | 是 | 事件执行状态。枚举值:preparing:运行中running:运行中error:错误done:执行完成 | | Name | string | 是 | 事件名。一级深度有:component,组件apifunctioncall,自主规划agentchatflow,工作流agent二级深度是组件ID三级深度是组件content_type示例:/component/eaaccc60e222418abc0f4d3d372018af/node/433b4cf184064daf88e8383adc83e35f | | CreatedTime | string | 是 | 当前event发送时间。 | | ErrorCode | string | 否 | 错误码。 | | ErrorMessage | string | 否 | 错误细节。 | #### Run示例代码 ```Go // 安装说明: // 支持Go 1.18以上版本 // go get github.com/baidubce/app-builder/go/appbuilder package main import ( "fmt" "os" "github.com/baidubce/app-builder/go/appbuilder" ) func main() { os.Setenv("APPBUILDER_LOGLEVEL", "DEBUG") os.Setenv("APPBUILDER_LOGFILE", "") // 请前往千帆AppBuilder官网创建密钥,流程详见:https://cloud.baidu.com/doc/AppBuilder/s/Olq6grrt6#1%E3%80%81%E5%88%9B%E5%BB%BA%E5%AF%86%E9%92%A5 config, err := appbuilder.NewSDKConfig("", "...") if err != nil { fmt.Println("new http client config failed: ", err) } // 组件ID,可在个人空间-组件下查看 componentID := "..." client, err := appbuilder.NewComponentClient(config) if err != nil { fmt.Println("new ComponentClient instance failed") } parameters := map[string]any{ appbuilder.SysOriginQuery: "北京景点推荐", } ans, err := client.Run(componentID, "latest", "", false, parameters) if err != nil { fmt.Println("run component failed: " + err.Error()) } // run non stream for answer, err := ans.Next(); err == nil; answer, err = ans.Next() { data := answer.Content[0].Text if data == nil { fmt.Println("run component failed: data is nil") return } fmt.Println("run component result: ") fmt.Println(data) } // run stream streamAns, err := client.Run(componentID, "latest", "", true, parameters) if err != nil { fmt.Println("run component failed: " + err.Error()) } var answerText any for answer, err := streamAns.Next(); err == nil; answer, err = streamAns.Next() { if len(answer.Content) == 0 { continue } answerText = answer.Content[0].Text } if answerText == nil { fmt.Println("run component failed: answer is nil") return } fmt.Println("run component result: ") fmt.Println(answerText) } ``` ================================================ FILE: docs/BasisModule/Platform/CustomComponents/components.md ================================================ # 基础能力组件 - [组件列表](https://cloud.baidu.com/doc/AppBuilder/s/Glqb6dfiz#3%E3%80%81%E5%BC%80%E9%80%9A%E7%BB%84%E4%BB%B6%E6%9C%8D%E5%8A%A1) - [组件免费额度领取](https://console.bce.baidu.com/ai-engine/old/#/ai/ocr/overview/resource/list) ================================================ FILE: docs/BasisModule/Platform/KnowledgeBase/knowledgebase.md ================================================ # 知识库组件(KnowledgeBase) ## 简介 知识库组件(KnowledgeBase)是对线上知识库操作的组件,可以通过SDK实现创建知识库、添加知识文档、查询知识库文档、删除知识文档等操作,可在平台console中查看结果。 ### 功能介绍 对console端知识库进行操作,可以通过SDK实现创建知识库、添加知识文档、查询知识库文档、删除知识文档等操作,可在平台console中查看结果。 ### 特色优势 和console端知识库操作一致,可实现快速创建、查询、删除等操作。 ### 应用场景 通过SDK代码实现console端知识库操作。 ## Python基本用法 ### 1、新建知识库`KnowledgeBase().create_knowledge_base(name: str, description: str, type: str, clusterId: str, esUserName: str, esPassword: str, location: str) -> KnowledgeBaseDetailResponse` #### 方法参数 | 参数名称 | 参数类型 | 是否必传 | 描述 | 示例值 | | ----------- | -------- | -------- | ------------------------------------- | ------------------ | | name | string | 是 | 希望创建的知识库名称 | "我的知识库" | | description | string | 否 | 知识库描述 | "我的知识库" | | type | string | 是 | 知识库索引存储配置 (public、bes、vdb) | "public" | | clusterId | string | type=bes 和 vdb 时填写 | 集群/实例 ID
请在bes、vdb控制台中查看。 | "clusterId" | | esUserName | string | type=bes 和 vdb 时填写 | 用户名/账号
请在bes、vdb控制台中查看 | "username" | | esPassword | string | type=bes 和 vdb 时填写 | 密码/API密钥
请在bes、vdb控制台中查看 | "password" | |location|string|type=bes 和 vdb 时填写|托管资源的区域,type填vdb时填写
可选值:
- bj:北京
- bd:保定
- sz:苏州
- gz:广州|"bj"| |pathPrefix|string|否|创建知识库的指定目录,最大层级为5,默认为根目录下|"/全部群组/##/##"| #### 方法返回值 `KnowledgeBaseDetailResponse` 类定义如下: ```python class KnowledgeBaseDetailResponse(BaseModel): id: str = Field(..., description="知识库ID") name: str = Field(..., description="知识库名称") description: Optional[str] = Field(None, description="知识库描述") config: Optional[KnowledgeBaseConfig] = Field(..., description="知识库配置") ``` 衍生类`KnowledgeBaseConfig`定义如下: ```python class KnowledgeBaseConfig(BaseModel): index: Optional[KnowledgeBaseConfigIndex] = Field(..., description="索引配置") catalogue: Optional[KnowledgeBaseConfigCatalogue] = Field(None, description="知识库目录配置") ``` 衍生类`KnowledgeBaseConfigIndex`定义如下: ```python class KnowledgeBaseConfigIndex(BaseModel): type: str = Field(..., description="索引类型", enum=["public", "bes", "vdb"]) clusterId: Optional[str] = Field(None, description="集群/实例 ID") username: Optional[str] = Field(None, description="bes用户名") password: Optional[str] = Field(None, description="bes密码") location: Optional[str] = Field(None, description="托管资源的区域", enum=["bj", "bd", "sz", "gz"]) ``` 衍生类`KnowledgeBaseConfigCatalogue` ```python class KnowledgeBaseConfigCatalogue(BaseModel): pathPrefix: Optional[str] = Field(None, description="知识库所属目录绝对路径") ``` #### 方法示例 ```python import os import appbuilder os.environ["APPBUILDER_TOKEN"] = "your_appbuilder_token" knowledge = appbuilder.KnowledgeBase() resp = knowledge.create_knowledge_base( name="my_knowledge", description="my_knowledge", type="public", ) print("新建的知识库ID: ", resp.id) print("新建的知识库名称: ", resp.name) # 新建的知识库ID: da51a988-cbe7-4b24-aa5b-768985e8xxxx # 新建的知识库名称: my_knowledge ``` ### 2、实例化已创建的知识库 `KnowledgeBase(knowledge_id: str)` #### 方法参数 | 参数名称 | 参数类型 | 是否必传 | 描述 | 示例值 | | ------------ | -------- | -------- | ------------ | ---------------- | | knowledge_id | string | 是 | 线上知识库ID | "正确的知识库ID" | #### 方法返回值 | 参数名称 | 参数类型 | 必然存在 | 描述 | 示例值 | | ------------- | ------------------- | -------- | ---------------- | ------ | | KnowledgeBase | class KnowledgeBase | 是 | 实例化的知识库类 | - | #### 方法示例 ```python import os import appbuilder os.environ["APPBUILDER_TOKEN"] = "your_appbuilder_token" my_knowledge_base_id = "your_knowledge_base_id" my_knowledge = appbuilder.KnowledgeBase(my_knowledge_base_id) print("知识库ID: ", my_knowledge.knowledge_id) # 知识库ID: your_knowledge_base_id ``` ### 3、获取知识库详情`get_knowledge_base_detail(knowledge_base_id: Optional[str] = None) -> KnowledgeBaseDetailResponse` #### 方法参数 | 参数名称 | 参数类型 | 是否必传 | 描述 | 示例值 | | ------------ | -------- | -------- | ------------ | ---------------- | | knowledge_id | string | 是 | 线上知识库ID | "正确的知识库ID" | #### 方法返回值 `KnowledgeBaseDetailResponse` 类定义如下: ```python class KnowledgeBaseDetailResponse(BaseModel): id: str = Field(..., description="知识库ID") name: str = Field(..., description="知识库名称") description: Optional[str] = Field(None, description="知识库描述") config: Optional[KnowledgeBaseConfig] = Field(..., description="知识库配置") ``` 衍生类`KnowledgeBaseConfig`定义如下: ```python class KnowledgeBaseConfig(BaseModel): index: Optional[KnowledgeBaseConfigIndex] = Field(..., description="索引配置") catalogue: Optional[KnowledgeBaseConfigCatalogue] = Field(None, description="知识库目录配置") ``` 衍生类`KnowledgeBaseConfigIndex`定义如下: ```python class KnowledgeBaseConfigIndex(BaseModel): type: str = Field(..., description="索引类型", enum=["public", "bes", "vdb"]) esUrl: Optional[str] = Field(..., description="ES地址") username: Optional[str] = Field(None, description="ES用户名") password: Optional[str] = Field(None, description="ES密码") ``` 衍生类`KnowledgeBaseConfigCatalogue` ```python class KnowledgeBaseConfigCatalogue(BaseModel): pathPrefix: Optional[str] = Field(None, description="知识库所属目录绝对路径") ``` #### 方法示例 ```python import os import appbuilder os.environ["APPBUILDER_TOKEN"] = "your_appbuilder_token" knowledge = appbuilder.KnowledgeBase() resp = knowledge.get_knowledge_base_detail("da51a988-cbe7-4b24-aa5b-768985e8xxxx") print("新建的知识库ID: ", resp.id) print("新建的知识库名称: ", resp.name) # 新建的知识库ID: da51a988-cbe7-4b24-aa5b-768985e8xxxx # 新建的知识库名称: my_knowledge ``` ### 4、 获取知识库列表`get_knowledge_base_list(knowledge_base_id: Optional[str] = None, maxKeys: int = 10, keyword: Optional[str] = None) -> KnowledgeBaseGetListResponse` #### 方法参数 | 参数名称 | 参数类型 | 是否必传 | 描述 | 示例值 | | ----------------- | -------- | -------- | --------------------------- | ---------------- | | knowledge_base_id | string | 否 | 起始位置,知识库id | "正确的知识库ID" | | maxKeys | int | 否 | 数据大小,默认10,最大值100 | 10 | | keyword | string | 否 | 搜索关键字 | "测试" | #### 方法返回值 `KnowledgeBaseGetListResponse` 类定义如下: ```python class KnowledgeBaseGetListResponse(BaseModel): requestId: str = Field(..., description="请求ID") data: list[KnowledgeBaseDetailResponse] = Field([], description="知识库详情列表") marker: str = Field(..., description="起始位置") nextMarker: str = Field(..., description="下一页起始位置") maxKeys: int = Field(10, description="返回文档数量大小,默认10,最大值100") isTruncated: bool = Field(..., description="是否有更多结果") ``` 衍生类`KnowledgeBaseDetailResponse` 定义如下: ```python class KnowledgeBaseDetailResponse(BaseModel): id: str = Field(..., description="知识库ID") name: str = Field(..., description="知识库名称") description: Optional[str] = Field(None, description="知识库描述") config: Optional[KnowledgeBaseConfig] = Field(..., description="知识库配置") ``` 衍生类`KnowledgeBaseConfig`定义如下: ```python class KnowledgeBaseConfig(BaseModel): index: Optional[KnowledgeBaseConfigIndex] = Field(..., description="索引配置") catalogue: Optional[KnowledgeBaseConfigCatalogue] = Field(None, description="知识库目录配置") ``` 衍生类`KnowledgeBaseConfigIndex`定义如下: ```python class KnowledgeBaseConfigIndex(BaseModel): type: str = Field(..., description="索引类型", enum=["public", "bes", "vdb"]) esUrl: Optional[str] = Field(..., description="ES地址") username: Optional[str] = Field(None, description="ES用户名") password: Optional[str] = Field(None, description="ES密码") ``` 衍生类`KnowledgeBaseConfigCatalogue` ```python class KnowledgeBaseConfigCatalogue(BaseModel): pathPrefix: Optional[str] = Field(None, description="知识库所属目录绝对路径") ``` #### 方法示例: ```python import os import appbuilder os.environ["APPBUILDER_TOKEN"] = "your_appbuilder_token" knowledge = appbuilder.KnowledgeBase() resp = knowledge.get_knowledge_base_list("da51a988-cbe7-4b24-aa5b-768985e8xxxx",10) print("获取到的知识库列表: ", resp) ``` ### 5、修改知识库`modify_knowledge_base(knowledge_base_id: Optional[str] = None, name: Optional[str] = None, description: Optional[str] = None)` #### 方法参数 | 参数名称 | 参数类型 | 是否必传 | 描述 | 示例值 | | ----------------- | -------- | -------- | --------------------------------------------- | ---------------- | | knowledge_base_id | string | 是 | 起始位置,知识库id | "正确的知识库ID" | | name | string | 否 | 修改后的知识库名称 | "new_name" | | description | string | 否 | 修改后的知识库描述 | "测试" | | pathPrefix | string | 否 | 知识库的指定目录,最大层级为5,默认为根目录下 | | #### 方法示例 ```python import os import appbuilder os.environ["APPBUILDER_TOKEN"] = "your_appbuilder_token" knowledge = appbuilder.KnowledgeBase() knowledge.modify_knowledge_base("da51a988-cbe7-4b24-aa5b-768985e8xxxx", name="new_name", description="测试") ``` ### 6、 删除知识库`delete_knowledge_base(knowledge_base_id: Optional[str] = None)` #### 方法参数 | 参数名称 | 参数类型 | 是否必传 | 描述 | 示例值 | | ----------------- | -------- | -------- | ---------- | ---------------- | | knowledge_base_id | string | 是 | 知识库的id | "正确的知识库ID" | ```python import os import appbuilder os.environ["APPBUILDER_TOKEN"] = "your_appbuilder_token" knowledge = appbuilder.KnowledgeBase() knowledge.delete_knowledge_base("da51a988-cbe7-4b24-aa5b-768985e8xxxx") ``` ### 7、 导入知识库`create_documents(id: Optional[str] = None, contentFormat: str = "", source: DocumentSource = None, processOption: DocumentProcessOption = None)` #### 方法参数 | 参数名称 | 参数类型 | 是否必传 | 描述 | 示例值 | | ------------- | --------------------- | -------------------------------------- | ------------------------------------------------------------ | ---------------- | | id | string | 是 | 知识库id | "正确的知识库ID" | | contentFormat | string | 是 | 文档格式:rawText (允许配置后续分割策略) | "rawText" | | source | DocumentSource | 是 | 数据来源 | | | processOption | DocumentProcessOption | 当contentFormat参数配置为rawText时必传 | 文档处理策略 | | `DocumentSource`类定义如下: ```python class DocumentSourceUrlConfig(BaseModel): frequency: int = Field( ..., description="更新频率,目前支持的更新频率为-1(不自动更新),1(每天),3(每3天),7(每7天),30(每30天)。", ) class DocumentSource(BaseModel): type: str = Field(..., description="数据来源类型", enum=["bos", "web"]) urls: list[str] = Field(None, description="文档URL") urlDepth: int = Field(None, description="url下钻深度,1时不下钻") urlConfigs: Optional[list[DocumentSourceUrlConfig]] = Field(None, description="该字段的长度需要和source、urls字段长度保持一致。") ``` `DocumentProcessOption`类及衍生类定义如下: ```python class DocumentProcessOption(BaseModel): template: str = Field( ..., description="模板类型,ppt:模版配置—ppt幻灯片, resume:模版配置—简历文档, paper:模版配置—论文文档, custom:自定义配置—自定义切片, default:自定义配置—默认切分", enum=["ppt", "paper", "qaPair", "resume", " custom", "default"], ) parser: Optional[DocumentChoices] = Field(None, description="解析方法(文字提取默认启动,参数不体现,layoutAnalysis版面分析,ocr光学字符识别,pageImageAnalysis文档图片解析,chartAnalysis图表解析,tableAnalysis表格深度解析,按需增加)") knowledgeAugmentation: Optional[DocumentChoices] = Field( None, description="知识增强,faq、spokenQuery、spo、shortSummary按需增加。问题生成:faq、spokenQuery,段落摘要:shortSummary,三元组知识抽取:spo" ) chunker: Optional[DocumentChunker] = Field(None, description="分段器类型") class DocumentChoices(BaseModel): choices: list[str] = Field(..., description="选择项") class DocumentChunker(BaseModel): choices: list[str] = Field(..., description="使用哪些chunker方法 (separator | pattern | onePage),separator:自定义切片—标识符,pattern:自定义切片—标识符中选择正则表达式,onePage:整文件切片") prependInfo: list[str] = Field( None, description="chunker关联元数据,可选值为title (增加标题), filename(增加文件名)", ) separator: Optional[DocumentSeparator] = Field(None, description="分隔符配置") pattern: Optional[DocumentPattern] = Field(None, description="正则表达式") class DocumentSeparator(BaseModel): separators: list[str] = Field(..., description="分隔符列表,可以使用分页符") targetLength: int = Field(..., description="分段最大长度") overlapRate: float = Field(..., description="分段重叠最大字数占比,推荐值0.25") class DocumentPattern(BaseModel): markPosition: str = Field( ..., description="命中内容放置策略, head:前序切片, tail:后序切片, drop:匹配后丢弃", enum=["head", "tail", "drop"] ) regex: str = Field(..., description="正则表达式") targetLength: int = Field(..., description="分段最大长度") overlapRate: float = Field(..., description="分段重叠最大字数占比,推荐值0.25") ``` #### 方法示例 ```python import os import appbuilder os.environ["APPBUILDER_TOKEN"] = "your_appbuilder_token" knowledge_base_id = "your_knowledge_base_id" knowledge = appbuilder.KnowledgeBase() knowledge.create_documents( id=knowledge_base_id, contentFormat="rawText", source=appbuilder.DocumentSource( type="web", urls=["https://baijiahao.baidu.com/s?id=1802527379394162441"], urlDepth=1, urlConfigs=[appbuilder.DocumentSourceUrlConfig(frequency=1)] ), processOption=appbuilder.DocumentProcessOption( template="custom", parser=appbuilder.DocumentChoices( choices=["layoutAnalysis", "ocr"] ), chunker=appbuilder.DocumentChunker( choices=["separator"], separator=appbuilder.DocumentSeparator( separators=["。"], targetLength=300, overlapRate=0.25, ), prependInfo=["title", "filename"], ), knowledgeAugmentation=appbuilder.DocumentChoices(choices=["faq"]), ), ) ``` ### 8、 上传文档到知识库`upload_documents(file_path: str, content_format: str = "rawText", id: Optional[str] = None, processOption: DocumentProcessOption = None)` #### 方法参数 | 参数名称 | 参数类型 | 是否必传 | 描述 | 示例值 | | -------------- | --------------------- | -------- | ------------------------------------------------------------ | ---------------- | | file_path | string | 是 | 文件路径 | "正确的文件路径" | | content_format | string | 否 | 文档格式:rawText (允许配置后续分割策略) | "rawText" | | id | string | 是 | 知识库ID | "正确的知识库ID" | | processOption | DocumentProcessOption | 是 | 文档处理策略 | | `DocumentProcessOption`类及衍生类定义如下: ```python class DocumentProcessOption(BaseModel): template: str = Field( ..., description="模板类型,ppt: 模版配置—ppt幻灯片, resume:模版配置—简历文档, paper:模版配置—论文文档, custom:自定义配置—自定义切片, default:自定义配置—默认切分", enum=["ppt", "paper", "qaPair", "resume", " custom", "default"], ) parser: Optional[DocumentChoices] = Field(None, description="解析器类型") knowledgeAugmentation: Optional[DocumentChoices] = Field( None, description="知识增强,faq、spokenQuery、spo、shortSummary按需增加。问题生成:faq、spokenQuery,段落摘要:shortSummary,三元组知识抽取:spo" ) chunker: Optional[DocumentChunker] = Field(None, description="分段器类型") class DocumentChoices(BaseModel): choices: list[str] = Field(..., description="选择项") class DocumentChunker(BaseModel): choices: list[str] = Field(..., description="使用哪些chunker方法 (separator | pattern | onePage), separator:自定义切片—标识符,pattern:自定义切片—标识符中选择正则表达式,onePage:整文件切片") prependInfo: list[str] = Field( ..., description="chunker关联元数据,可选值为title (增加标题), filename(增加文件名)", ) separator: Optional[DocumentSeparator] = Field(..., description="分段符号") pattern: Optional[DocumentPattern] = Field(None, description="正则表达式") class DocumentSeparator(BaseModel): separators: list[str] = Field(..., description="分段符号") targetLength: int = Field(..., description="分段最大长度") overlapRate: float = Field(..., description="分段重叠最大字数占比,推荐值0.25") class DocumentPattern(BaseModel): markPosition: str = Field( ..., description="命中内容放置策略, head:前序切片, tail:后序切片, drop:匹配后丢弃", enum=["head", "tail", "drop"] ) regex: str = Field(..., description="正则表达式") targetLength: int = Field(..., description="分段最大长度") overlapRate: float = Field(..., description="分段重叠最大字数占比,推荐值0.25") ``` #### 方法示例 ```python import os import appbuilder os.environ["APPBUILDER_TOKEN"] = "your_appbuilder_token" knowledge_base_id = "your_knowledge_base_id" knowledge = appbuilder.KnowledgeBase() knowledge.upload_documents( id=knowledge_base_id, content_format="rawText", file_path="./python/tests/data/qa_appbuilder_client_demo.pdf", processOption=appbuilder.DocumentProcessOption( template="custom", parser=appbuilder.DocumentChoices( choices=["layoutAnalysis", "ocr"] ), chunker=appbuilder.DocumentChunker( choices=["separator"], separator=appbuilder.DocumentSeparator( separators=["。"], targetLength=300, overlapRate=0.25, ), prependInfo=["title", "filename"], ), knowledgeAugmentation=appbuilder.DocumentChoices(choices=["faq"]), ), ) ``` ### 9、从知识库删除文档 `KnowledgeBase().delete_document()->KnowledgeBaseDeleteDocumentResponse` #### 方法参数 | 参数名称 | 参数类型 | 是否必传 | 描述 | 示例值 | | ----------- | -------- | -------- | -------------- | -------------------------------------- | | document_id | string | 是 | 待删除的文档ID | '5e0eb279-7688-4100-95d1-241f3d19xxxx' | #### 方法返回值 方法返回 `KnowledgeBaseDeleteDocumentResponse`, 该类的定义是 ```python class KnowledgeBaseDeleteDocumentResponse(BaseModel): request_id: str = Field(..., description="请求ID") ``` #### 方法示例 ```python import os import appbuilder os.environ["APPBUILDER_TOKEN"] = "your_appbuilder_token" my_knowledge_base_id = "your_knowledge_base_id" my_knowledge = appbuilder.KnowledgeBase(my_knowledge_base_id) print("知识库ID: ", my_knowledge.knowledge_id) upload_res = my_knowledge.upload_file("./test.txt") print("文件上传结果: ",upload_res) add_res = my_knowledge.add_document(content_type='raw_text', file_ids=[upload_res.id]) print("添加文档结果: ",add_res) delete_res = my_knowledge.delete_document(document_id=add_res.document_ids[0]) print("删除文档结果: ",delete_res) # 知识库ID: da51a988-cbe7-4b24-aa5b-768985e8xxxx # 文件上传结果: request_id='255eec22-ec87-4564-bdeb-3e5623eaxxxx' id='ef12119b-d5be-492a-997c-77f8e84axxxx' name='test.txt' # 添加文档结果: request_id='412e1630-b570-47c9-a042-caf3cd9dxxxx' knowledge_base_id='da51a988-cbe7-4b24-aa5b-768985e8xxxx' document_ids=['5e0eb279-7688-4100-95d1-241f3d19xxxx'] # 删除文档结果: request_id='ba0e8bc0-b799-45b5-bdac-0d4c50e2xxxx' ``` ### 10、获取知识库的文档列表`KnowledgeBase().get_documents_list()->KnowledgeBaseGetDocumentsListResponse` #### 方法参数 | 参数名称 | 参数类型 | 是否必传 | 描述 | 示例值 | | -------- | -------- | -------- | ------------------------------------------------------------ | -------------------------------------- | | limit | int | 否 | 单次请求列表获得的文档数量,最大100 | 10 | | after | str | 否 | 用于分页的游标。after 是一个文档的id,它定义了在列表中的位置。例如,如果你发出一个列表请求并收到 10个对象,以 app_id_123 结束,那么你后续的调用可以包含 after=app_id_123 以获取列表的下一页数据。默认为空 | '5e0eb279-7688-4100-95d1-241f3d19xxxx' | | before | str | 否 | 用于分页的游标。与after相反,填写它将获取前一页数据,如果和after都传,两个参数都会起到分页效果,默认为空 | '5e0eb279-7688-4100-95d1-241f3d19xxxx' | #### 方法返回值 方法返回类`KnowledgeBaseGetDocumentsListResponse`,定义为 ```python class KnowledgeBaseGetDocumentsListResponse(BaseModel): request_id: str = Field(..., description="请求ID") data: list[Document] = Field([], description="文档信息列表") ``` 衍生类`Document`以及`DocumentMeta`定义为: ```python class Document(BaseModel): id: str = Field(..., description="文档ID") name: str = Field(..., description="文档名称") created_at: str = Field(..., description="文档创建时间") word_count: int = Field(..., description="文档字数") enabled: bool = Field(True, description="文档是否可用") meta: Optional[DocumentMeta] = Field(..., description="文档元信息,包括source、file_id") class DocumentMeta(BaseModel): source: Optional[str] = Field(None, description="文档来源") file_id: Optional[str] = Field(None, description="文档对应的文件ID") url: Optional[str] = Field(None, description="原文件下载链接") mime_type: Optional[str] = Field( None, description="文件类型,目前支持doc/txt/docx/pdf/ppt/pptx/xlsx/xls/csv/json这几种文件类型。如果是通过url方式导入的文档,该值为url", ) file_size: Optional[int] = Field(None, description="文件大小,单位bytes") ``` #### 方法示例 ```python import os import appbuilder os.environ["APPBUILDER_TOKEN"] = "your_appbuilder_token" my_knowledge_base_id = "your_knowledge_base_id" my_knowledge = appbuilder.KnowledgeBase(my_knowledge_base_id) print("知识库ID: ", my_knowledge.knowledge_id) list_res = my_knowledge.get_documents_list() print("文档列表: ", list_res) # 知识库ID: da51a988-cbe7-4b24-aa5b-768985e8xxxx # 文档列表: request_id='f66c2193-6035-4022-811b-c4cd7743xxxx' data=[{'id': '8f388b10-5e6a-423f-8acc-dd5fdc2fxxxx', 'name': 'test.txt', 'created_at': 1719988868, 'word_count': 16886, 'enabled': True, 'meta': {'source': 'upload_file', 'file_id': '0ebb03fb-ea48-4c49-b494-cf0cec11xxxx'}}, {'id': '5e0eb279-7688-4100-95d1-241f3d19xxxx', 'name': 'test.txt', 'created_at': 1719987921, 'word_count': 16886, 'enabled': True, 'meta': {'source': 'upload_file', 'file_id': '059e2ae2-1e3c-43ea-8b42-5d988f93xxxx'}}] ``` ### 11、获取知识库全部文档`KnowledgeBase().get_all_documents()->list` #### 方法参数 | 参数名称 | 参数类型 | 是否必传 | 描述 | 示例值 | | ----------------- | -------- | -------- | ------------ | ---------------- | | knowledge_base_id | string | 是 | 线上知识库ID | "正确的知识库ID" | #### 方法返回值 list 数据类型`list[Document]` 衍生类`Document`以及`DocumentMeta`定义为: ```python class Document(BaseModel): id: str = Field(..., description="文档ID") name: str = Field(..., description="文档名称") created_at: str = Field(..., description="文档创建时间") word_count: int = Field(..., description="文档字数") enabled: bool = Field(True, description="文档是否可用") meta: Optional[DocumentMeta] = Field(..., description="文档元信息,包括source、file_id") class DocumentMeta(BaseModel): source: Optional[str] = Field(None, description="文档来源") file_id: Optional[str] = Field(None, description="文档对应的文件ID") url: Optional[str] = Field(None, description="原文件下载链接") mime_type: Optional[str] = Field( None, description="文件类型,目前支持doc/txt/docx/pdf/ppt/pptx/xlsx/xls/csv/json这几种文件类型。如果是通过url方式导入的文档,该值为url", ) file_size: Optional[int] = Field(None, description="文件大小,单位bytes") ``` #### 方法示例 ```python import os import appbuilder os.environ["APPBUILDER_TOKEN"] = "your_appbuilder_token" my_knowledge_base_id = "your_knowledge_base_id" my_knowledge = appbuilder.KnowledgeBase(my_knowledge_base_id) print("知识库ID: ", my_knowledge.knowledge_id) doc_list = my_knowledge.get_all_documents(my_knowledge_base_id) for message in doc_list: print(message) ``` ### 12. 创建切片`create_chunk(documentId: str, content: str) -> CreateChunkResponse` #### 方法参数 | 参数名称 | 参数类型 | 是否必传 | 描述 | 示例值 | | --------------- | -------- | -------- | -------- | -------------- | | knowledgeBaseId | string | 是 | 知识库ID | | | documentId | string | 是 | 文档ID | "正确的文档ID" | | content | string | 是 | 切片内容 | "内容" | #### 方法返回值 `CreateChunkResponse`类定义如下: ```python class CreateChunkResponse(BaseModel): id: str = Field(..., description="切片ID") ``` #### 方法示例 ```python import os import appbuilder os.environ["APPBUILDER_TOKEN"] = "your_appbuilder_token" my_knowledge_base_id = "your_knowledge_base_id" my_knowledge = appbuilder.KnowledgeBase(my_knowledge_base_id) print("知识库ID: ", my_knowledge.knowledge_id) resp = my_knowledge.create_chunk("your_document_id", "content", knowledgebase_id=knowledge_base_id) print("切片ID: ", resp.id) chunk_id = resp.id ``` ### 13. 修改切片信息`modify_chunk(chunkId: str, content: str, enable: bool)` #### 方法参数 | 参数名称 | 参数类型 | 是否必传 | 描述 | 示例值 | | ---------- | -------- | ------------ | -------------- | -------------- | | knowledgeBaseId | string | 是 | 知识库ID | | | chunkId | string | 是 | 文档ID | "正确的切片ID" | | content | string | 是 | 切片内容 | "内容" | | enable | bool | 是 | 是否用该切片 | True | #### 方法示例 ```python import os import appbuilder os.environ["APPBUILDER_TOKEN"] = "your_appbuilder_token" my_knowledge_base_id = "your_knowledge_base_id" my_knowledge = appbuilder.KnowledgeBase(my_knowledge_base_id) print("知识库ID: ", my_knowledge.knowledge_id) my_knowledge.modify_chunk("your_chunk_id", "content", True, knowledgebase_id=my_knowledge_base_id) ``` ### 14. 删除切片`delete_chunk(chunkId: str)` #### 方法参数 | 参数名称 | 参数类型 | 是否必传 | 描述 | 示例值 | | --------------- | -------- | -------- | -------- | -------------- | | knowledgeBaseId | string | 是 | 知识库ID | | | chunkId | string | 是 | 文档ID | "正确的切片ID" | #### 方法示例 ```python import os import appbuilder os.environ["APPBUILDER_TOKEN"] = "your_appbuilder_token" my_knowledge_base_id = "your_knowledge_base_id" my_knowledge = appbuilder.KnowledgeBase(my_knowledge_base_id) print("知识库ID: ", my_knowledge.knowledge_id) my_knowledge.delete_chunk("your_chunk_id", knowledgebase_id=my_knowledge_base_id) ``` ### 15. 获取切片信息`describe_chunk(chunkId: str)` #### 方法参数 | 参数名称 | 参数类型 | 是否必传 | 描述 | 示例值 | | --------------- | -------- | -------- | -------- | -------------- | | knowledgeBaseId | string | 是 | 知识库ID | | | chunkId | string | 是 | 文档ID | "正确的切片ID" | #### 方法返回值 `DescribeChunkResponse`类定义如下: ```python class DescribeChunkResponse(BaseModel): id: str = Field(..., description="切片ID") type: str = Field(..., description="切片类型") knowledgeBaseId: str = Field(..., description="知识库ID") documentId: str = Field(..., description="文档ID") content: str = Field(..., description="文档内容") enabled: bool = Field(..., description="是否启用") wordCount: int = Field(..., description="切片内字符数量") tokenCount: int = Field(..., description="切片内token数量") status: str = Field(..., description="切片状态") statusMessage: str = Field(..., description="切片状态信息") imageUrls: list[str] = Field(..., description="图片地址") createTime: int = Field(..., description="创建时间") updateTime: int = Field(None, description="更新时间") ``` #### 方法示例 ```python import os import appbuilder os.environ["APPBUILDER_TOKEN"] = "your_appbuilder_token" my_knowledge_base_id = "your_knowledge_base_id" my_knowledge = appbuilder.KnowledgeBase(my_knowledge_base_id) print("知识库ID: ", my_knowledge.knowledge_id) resp = my_knowledge.describe_chunk("your_chunk_id", knowledgebase_id=my_knowledge_base_id) print("切片详情:") print(resp) ``` ### 16. 获取切片列表`describe_chunks(documentId: str, marker: str = None, maxKeys: int = None, type: str = None) -> DescribeChunksResponse` #### 方法参数 | 参数名称 | 参数类型 | 是否必传 | 描述 | 示例值 | | --------------- | -------- | -------- | ------------------------------------------------------------ | -------------- | | knowledgeBaseId | string | 是 | 知识库ID | | | documentId | string | 是 | 文档ID | "正确的文档ID" | | marker | string | 否 | 起始位置,切片ID | "正确的切片ID" | | maxKeys | string | 否 | 返回文档数量大小,默认10,最大值100 | 10 | | type | string | 否 | 根据类型获取切片列表(RAW、NEW、COPY),RAW:原文切片,NEW:新增切片,COPY:复制切片 | "RAW" | | keyword | string | 否 | 根据关键字模糊匹配切片,最大长度2000字符。 | "test" | #### 方法返回值 `DescribeChunksResponse` 类定义如下: ```python class DescribeChunksResponse(BaseModel): data: list[DescribeChunkResponse] = Field(..., description="切片列表") marker: str = Field(..., description="起始位置") isTruncated: bool = Field( ..., description="true表示后面还有数据,false表示已经是最后一页" ) nextMarker: str = Field(..., description="下一页起始位置") maxKeys: int = Field(..., description="本次查询包含的最大结果集数量") ``` 衍生类`DescribeChunkResponse`定义如下: ```python class DescribeChunkResponse(BaseModel): id: str = Field(..., description="切片ID") type: str = Field(..., description="切片类型") knowledgeBaseId: str = Field(..., description="知识库ID") documentId: str = Field(..., description="文档ID") content: str = Field(..., description="文档内容") enabled: bool = Field(..., description="是否启用") wordCount: int = Field(..., description="切片内字符数量") tokenCount: int = Field(..., description="切片内token数量") status: str = Field(..., description="切片状态") statusMessage: str = Field(..., description="切片状态信息") imageUrls: list[str] = Field(..., description="图片地址") createTime: int = Field(..., description="创建时间") updateTime: int = Field(None, description="更新时间") ``` #### 方法示例 ```python import os import appbuilder os.environ["APPBUILDER_TOKEN"] = "your_appbuilder_token" my_knowledge_base_id = "your_knowledge_base_id" my_knowledge = appbuilder.KnowledgeBase(my_knowledge_base_id) print("知识库ID: ", my_knowledge.knowledge_id) resp = my_knowledge.describe_chunks("your_document_id", knowledgebase_id=my_knowledge_base_id) print("切片列表:") print(resp) ``` ### 17. 知识库检索`query_knowledge_base(query: str, knowledgebase_ids: list[str], type: Optional[data_class.QueryType] = None, metadata_filters: data_class.MetadataFilter = None,pipeline_config: data_class.QueryPipelineConfig = None, rank_score_threshold: Optional[float] = 0.4, top: int = 6, skip: int = None) -> data_class.QueryKnowledgeBaseResponse` #### 方法参数 | 参数名称 | 参数类型 | 是否必传 | 描述 | 示例值 | | --------------- | -------- | -------- | ------------------------------------------------------------ | -------------- | | query | string | 是 | 检索query,最长为1024字符,超过自动截断 |民法典第三条 | | knowledgebase_ids | list[str] | 是 | 指定知识库的id集合 | ["kb-1", "kb-2"] | | type | string | 否 | 检索策略。
可选值:
* fulltext,全文检索
* semantic,语义检索
* hybird,混合检索| "fulltext" | | metadata_filters | data_class.MetadataFilters | 否 | 元数据过滤条件,详细见MetadataFilters | - | | pipeline_config | data_class.QueryPipelineConfig | 否 | 检索配置,详细见QueryPipelineConfig | - | | rank_score_threshold | float | 否 | 重排序匹配分阈值,只有rank_score大于等于该分值的切片重排序时才会被筛选出来。
当且仅当,pipeline_config中配置了ranking节点时,该过滤条件生效。
取值范围: [0, 1]。
默认0.4 | 0.4 | | top | int | 否 | 返回前多少的条目。默认值6。如果检索结果的数量未达到top值,则按实际检索到的结果数量返回 | 6 | | skip | int | 否 | 跳过条目数(通过top和skip可以实现类似分页的效果,比如top 10 skip 0,取第一页的10个,top 10 skip 10,取第二页的10个)| 0 | `data_class.MetadataFilters` 类定义如下: ```python class MetadataFilters(BaseModel): filters: list[MetadataFilter] = Field(..., description="过滤条件") condition: str = Field(..., description="文档组合条件。and:与,or:或") ``` `data_class.MetadataFilter` 类定义如下: ```python class MetadataFilter(BaseModel): operator: str = Field(..., description="操作符名称。==:等于,in:在数组中,not_in:不在数组中") field: str = Field(None, description="字段名,目前支持doc_id") value: Union[str, list[str]] = Field( ..., description="字段值,如果是in操作符,value为数组" ) ``` `data_class.QueryPipelineConfig` 类定义如下: ```python class QueryPipelineConfig(BaseModel): id: str = Field( None, description="配置唯一标识,如果用这个id,则引用已经配置好的QueryPipeline" ) pipeline: list[Union[ElasticSearchRetrieveConfig, RankingConfig, VectorDBRetrieveConfig, SmallToBigConfig]] = Field( None, description="配置的Pipeline,如果没有用id,可以用这个对象指定一个新的配置" ) ``` `data_class.ElasticSearchRetrieveConfig` 类定义如下: ```python class ElasticSearchRetrieveConfig(BaseModel): # 托管资源为共享资源 或 BES资源时使用该配置 name: str = Field(..., description="配置名称") type: str = Field(None, description="elastic_search标志,该节点为es全文检索") threshold: float = Field(None, description="得分阈值,默认0.1") top: int = Field(None, description="召回数量,默认400") ``` `data_class.RankingConfig` 类定义如下: ```python class RankingConfig(BaseModel): name: str = Field(..., description="配置名称") type: str = Field(None, description="ranking标志,该节点为ranking节点") inputs: list[str] = Field( ..., description='输入的节点名,如es检索配置的名称为pipeline_001,则该inputs为["pipeline_001"]', ) model_name: str = Field(None, description="ranking模型名(当前仅一种,暂不生效)") top: int = Field(None, description="取切片top进行排序,默认20,最大400") ``` `data_class.VectorDBRetrieveConfig` 类定义如下: ```python class VectorDBRetrieveConfig(BaseModel): name: str = Field(..., description="该节点的自定义名称。") type: str = Field("vector_db", description="该节点的类型,默认为vector_db。") threshold: Optional[float] = Field(0.1, description="得分阈值。取值范围:[0, 1]", ge=0.0, le=1.0) top: Optional[int] = Field(400, description="召回数量。取值范围:[0, 800]", ge=0, le=800) pre_ranking: Optional[PreRankingConfig] = Field(None, description="粗排配置") ``` `data_class.PreRankingConfig` 类定义如下: ```python class PreRankingConfig(BaseModel): bm25_weight: float = Field( None, description="粗排bm25比重,取值范围在 [0, 1],默认0.75" ) vec_weight: float = Field( None, description="粗排向量余弦分比重,取值范围在 [0, 1],默认0.25" ) bm25_b: float = Field( None, description="控制文档长度对评分影响的参数,取值范围在 [0, 1],默认0.75" ) bm25_k1: float = Field( None, description="词频饱和因子,控制词频(TF)对评分的影响,常取值范围在 [1.2, 2.0],默认1.5", ) bm25_max_score: float = Field( None, description="得分归一化参数,不建议修改,默认50" ) ``` #### 方法返回值 `data_class.QueryKnowledgeBaseResponse` 类定义如下: ```python class QueryKnowledgeBaseResponse(BaseModel): requestId: str = Field(None, description="请求ID") code: str = Field(None, description="状态码") message: str = Field(None, description="状态信息") chunks: list[Chunk] = Field(..., description="切片列表") total_count: int = Field(..., description="切片总数") ``` 衍生类`Chunk`定义如下: ```python class Chunk(BaseModel): chunk_id: str = Field(..., description="切片ID") knowledgebase_id: str = Field(..., description="知识库ID") document_id: str = Field(..., description="文档ID") document_name: str = Field(None, description="文档名称") meta: dict = Field(None, description="文档元数据") chunk_type: str = Field(..., description="切片类型") content: str = Field(..., description="切片内容") create_time: datetime = Field(..., description="创建时间") update_time: datetime = Field(..., description="更新时间") retrieval_score: float = Field(..., description="粗检索得分") rank_score: float = Field(..., description="rerank得分") locations: ChunkLocation = Field(None, description="切片位置") children: List[Chunk] = Field(None, description="子切片") ``` #### 方法示例 ```python import os import appbuilder os.environ["APPBUILDER_TOKEN"] = "your_appbuilder_token" knowledge = appbuilder.KnowledgeBase() client = appbuilder.KnowledgeBase() res = client.query_knowledge_base( query="民法典第三条", type="fulltext", knowledgebase_ids=["70c6375a-1595-41f2-9a3b-e81bc9060b7f"], top=5, skip=0, metadata_filters=data_class.MetadataFilters(filters=[], condition="or"), pipeline_config=data_class.QueryPipelineConfig( id="pipeline_001", pipeline=[ { "name": "step1", "type": "elastic_search", "threshold": 0.1, "top": 400, "pre_ranking": { "bm25_weight": 0.25, "vec_weight": 0.75, "bm25_b": 0.75, "bm25_k1": 1.5, "bm25_max_score": 50, }, }, { "name": "step2", "type": "ranking", "inputs": ["step1"], "model_name": "ranker-v1", "top": 20, }, ], ), ) chunk_id = res.chunks[0].chunk_id for chunk in res.chunks: print(chunk.content) ``` ### Java基本用法 #### 方法及各方法入参/出参 参考 `python KnowledgeBase`接口文档 #### 示例代码 ```java public class KnowledgebaseTest { @Before public void setUp() { System.setProperty("APPBUILDER_TOKEN",""); System.setProperty("APPBUILDER_LOGLEVEL", "DEBUG"); } @Test public void testDocument() throws IOException, AppBuilderServerException { // 实例化Knowledgebase String knowledgeBaseId = ""; Knowledgebase knowledgebase = new Knowledgebase(); // 获取知识库文档列表 DocumentListRequest listRequest = new DocumentListRequest(); listRequest.setKonwledgeBaseId(knowledgeBaseId); listRequest.setLimit(10); Document[] documents = knowledgebase.getDocumentList(listRequest); // 从知识库删除文档 DocumentDeleteRequest deleteRequest = new DocumentDeleteRequest(); deleteRequest.setKonwledgeBaseId(knowledgeBaseId); deleteRequest.setDocumentId("期望删除的DocumentId"); knowledgebase.deleteDocument(deleteRequest); } @Test public void testCreateKnowledgebase() throws IOException, AppBuilderServerException { Knowledgebase knowledgebase = new Knowledgebase(); KnowledgeBaseDetail request = new KnowledgeBaseDetail(); request.setName("test_knowledgebase"); request.setDescription("test_knowledgebase"); // 创建知识库 KnowledgeBaseConfig.Index index = new KnowledgeBaseConfig.Index("public", "", "", "", ""); KnowledgeBaseConfig config = new KnowledgeBaseConfig(index); request.setConfig(config); KnowledgeBaseDetail response = knowledgebase.createKnowledgeBase(request); String knowledgeBaseId = response.getId(); System.out.println(knowledgeBaseId); assertNotNull(response.getId()); // 获取知识库详情 KnowledgeBaseDetail detail = knowledgebase.getKnowledgeBaseDetail(knowledgeBaseId); System.out.println(detail.getId()); assertNotNull(detail.getId()); // 获取知识库列表 KnowledgeBaseListRequest listRequest = new KnowledgeBaseListRequest(knowledgeBaseId, 10, null); KnowledgeBaseListResponse knowledgeBases = knowledgebase.getKnowledgeBaseList(listRequest); System.out.println(knowledgeBases.getMarker()); assertNotNull(knowledgeBases.getMarker()); // 更新知识库 KnowledgeBaseModifyRequest modifyRequest = new KnowledgeBaseModifyRequest(); modifyRequest.setKnowledgeBaseId(knowledgeBaseId); modifyRequest.setName("test_knowledgebase2"); modifyRequest.setDescription(knowledgeBaseId); knowledgebase.modifyKnowledgeBase(modifyRequest); // 导入知识库 DocumentsCreateRequest.Source source = new DocumentsCreateRequest.Source("web", new String[] {"https://baijiahao.baidu.com/s?id=1802527379394162441"}, 1); DocumentsCreateRequest.ProcessOption.Parser parser = new DocumentsCreateRequest.ProcessOption.Parser( new String[] {"layoutAnalysis", "ocr"}); DocumentsCreateRequest.ProcessOption.Chunker.Separator separator = new DocumentsCreateRequest.ProcessOption.Chunker.Separator(new String[] {"。"}, 300, 0.25); DocumentsCreateRequest.ProcessOption.Chunker chunker = new DocumentsCreateRequest.ProcessOption.Chunker(new String[] {"separator"}, separator, null, new String[] {"title", "filename"}); DocumentsCreateRequest.ProcessOption.KnowledgeAugmentation knowledgeAugmentation = new DocumentsCreateRequest.ProcessOption.KnowledgeAugmentation( new String[] {"faq"}); DocumentsCreateRequest.ProcessOption processOption = new DocumentsCreateRequest.ProcessOption("custom", parser, chunker, knowledgeAugmentation); DocumentsCreateRequest documentsCreateRequest = new DocumentsCreateRequest(knowledgeBaseId, "rawText", source, processOption); knowledgebase.createDocuments(documentsCreateRequest); // 上传文档 String filePath = "src/test/java/com/baidubce/appbuilder/files/test.pdf"; DocumentsCreateRequest.Source source2 = new DocumentsCreateRequest.Source("file", null, null); DocumentsCreateRequest documentsCreateRequest2 = new DocumentsCreateRequest(knowledgeBaseId, "rawText", source2, processOption); knowledgebase.uploadDocuments(filePath, documentsCreateRequest2); // 删除知识库 knowledgebase.deleteKnowledgeBase(knowledgeBaseId); } @Test public void testCreateChunk() throws IOException, AppBuilderServerException { String documentId = ""; // 知识库ID String knowledgeBaseId = ""; // Appbuilder Token String secretKey = ""; Knowledgebase knowledgebase = new Knowledgebase(knowledgeBaseID, secretKey); // 创建切片 String chunkId = knowledgebase.createChunk(documentId, "test"); // 修改切片 knowledgebase.modifyChunk(chunkId, "new test", true); // 获取切片详情 knowledgebase.describeChunk(chunkId); // 获取切片列表 knowledgebase.describeChunks(documentId, chunkId, 10, null); // 删除切片 knowledgebase.deleteChunk(chunkId); } } ``` ### Go基本用法 #### 方法及各方法入参/出参 参考 `python KnowledgeBase`接口文档 #### 示例代码 ```Go package appbuilder import ( "fmt" "os" "testing" ) func TestKnowledgeBase(t *testing.T) { os.Setenv("APPBUILDER_LOGLEVEL", "DEBUG") os.Setenv("APPBUILDER_LOGFILE", "") // 实例化KnowledgeBase knowledgeBaseID := "" config, err := NewSDKConfig("", "") if err != nil { t.Fatalf("new http client config failed: %v", err) } client, err := NewKnowledgeBase(config) if err != nil { t.Fatalf("new Knowledge base instance failed") } // 获取知识库中的文档列表 documentsRes, err := client.GetDocumentList(GetDocumentListRequest{ KnowledgeBaseID: knowledgeBaseID, }) if err != nil { t.Fatalf("create document failed: %v", err) } fmt.Println(documentsRes) // 从知识库中删除文档 err = client.DeleteDocument(DeleteDocumentRequest{ KnowledgeBaseID: knowledgeBaseID, DocumentID: "期望删除的DocumentID"}) if err != nil { t.Fatalf("delete document failed: %v", err) } } func TestCreateKnowledgeBase(t *testing.T) { os.Setenv("APPBUILDER_LOGLEVEL", "DEBUG") os.Setenv("APPBUILDER_TOKEN", "") config, err := NewSDKConfig("", "") if err != nil { t.Fatalf("new http client config failed: %v", err) } client, err := NewKnowledgeBase(config) if err != nil { t.Fatalf("new Knowledge base instance failed") } // 创建知识库 createKnowledgeBaseRes, err := client.CreateKnowledgeBase(KnowledgeBaseDetail{ Name: "test-go", Description: "test-go", Config: &KnowlegeBaseConfig{ Index: KnowledgeBaseConfigIndex{ Type: "public", }, }, }) if err != nil { t.Fatalf("create knowledge base failed: %v", err) } knowledgeBaseID := createKnowledgeBaseRes.ID fmt.Println(knowledgeBaseID) // 获取知识库详情 getKnowledgeBaseRes, err := client.GetKnowledgeBaseDetail(knowledgeBaseID) if err != nil { t.Fatalf("get knowledge base failed: %v", err) } fmt.Println(getKnowledgeBaseRes) // 获取知识库列表 knowledgeBaseListRes, err := client.GetKnowledgeBaseList( GetKnowledgeBaseListRequest{ Marker: knowledgeBaseID, }, ) if err != nil { t.Fatalf("get knowledge base list failed: %v", err) } fmt.Println(knowledgeBaseListRes) // 导入知识库 err = client.CreateDocuments(CreateDocumentsRequest{ ID: knowledgeBaseID, ContentFormat: "rawText", Source: DocumentsSource{ Type: "web", Urls: []string{"https://baijiahao.baidu.com/s?id=1802527379394162441"}, UrlDepth: 1, }, ProcessOption: &DocumentsProcessOption{ Template: "custom", Parser: &DocumentsProcessOptionParser{ Choices: []string{"layoutAnalysis", "ocr"}, }, Chunker: &DocumentsProcessOptionChunker{ Choices: []string{"separator"}, Separator: &DocumentsProcessOptionChunkerSeparator{ Separators: []string{"。"}, TargetLength: 300, OverlapRate: 0.25, }, PrependInfo: []string{"title", "filename"}, }, KnowledgeAugmentation: &DocumentsProcessOptionKnowledgeAugmentation{ Choices: []string{"faq"}, }, }, }) if err != nil { t.Fatalf("create documents failed: %v", err) } // 上传知识库文档 err = client.UploadDocuments("./files/test.pdf", CreateDocumentsRequest{ ID: knowledgeBaseID, ContentFormat: "rawText", Source: DocumentsSource{ Type: "file", }, ProcessOption: &DocumentsProcessOption{ Template: "custom", Parser: &DocumentsProcessOptionParser{ Choices: []string{"layoutAnalysis", "ocr"}, }, Chunker: &DocumentsProcessOptionChunker{ Choices: []string{"separator"}, Separator: &DocumentsProcessOptionChunkerSeparator{ Separators: []string{"。"}, TargetLength: 300, OverlapRate: 0.25, }, PrependInfo: []string{"title", "filename"}, }, KnowledgeAugmentation: &DocumentsProcessOptionKnowledgeAugmentation{ Choices: []string{"faq"}, }, }, }) if err != nil { t.Fatalf("upload documents failed: %v", err) } // 修改知识库 name := "test-go" description := "22" err = client.ModifyKnowledgeBase(ModifyKnowlegeBaseRequest{ ID: knowledgeBaseID, Name: &name, Description: &description, }) if err != nil { t.Fatalf("modify knowledge base failed: %v", err) } // 删除知识库 err = client.DeleteKnowledgeBase(knowledgeBaseID) if err != nil { t.Fatalf("delete knowledge base failed: %v", err) } } func TestChunk(t *testing.T) { os.Setenv("APPBUILDER_LOGLEVEL", "DEBUG") os.Setenv("APPBUILDER_TOKEN", "") documentID := "" knowledgeBaseID := ""; config, err := NewSDKConfig("", "") if err != nil { t.Fatalf("new http client config failed: %v", err) } client, err := NewKnowledgeBaseWithKnowledgeBaseID(knowledgeBaseID, config) if err != nil { t.Fatalf("new Knowledge base instance failed") } // 创建切片 chunkID, err := client.CreateChunk(CreateChunkRequest{ DocumentID: documentID, Content: "test", }) if err != nil { t.Fatalf("create chunk failed: %v", err) } fmt.Println(chunkID) // 修改切片 err = client.ModifyChunk(ModifyChunkRequest{ ChunkID: chunkID, Content: "new test", Enable: true, }) if err != nil { t.Fatalf("modify chunk failed: %v", err) } // 获取切片详情 describeChunkRes, err := client.DescribeChunk(chunkID) if err != nil { t.Fatalf("describe chunk failed: %v", err) } fmt.Println(describeChunkRes) // 获取切片列表 describeChunksRes, err := client.DescribeChunks(DescribeChunksRequest{ DocumnetID: documentID, Marker: chunkID, MaxKeys: 10, }) if err != nil { t.Fatalf("describe chunks failed: %v", err) } fmt.Println(describeChunksRes) // 删除切片 err = client.DeleteChunk(chunkID) if err != nil { t.Fatalf("delete chunk failed: %v", err) } } ``` ================================================ FILE: docs/BasisModule/Trace/Debug.md ================================================ # Appbuilder-SDK Debug ## 打印DEBUG日志 开启DEBUG日志,可以打印出更多的日志信息,方便调试,包括且不限于:请求URL、请求头、请求参数等。 ```bash # 可以设置环境变量开启 # 开启DEBUG export APPBUILDER_LOGLEVEL=DEBUG # 关闭DEBUG export APPBUILDER_LOGLEVEL=INFO ``` 也可以在代码中设置,优先级高于环境变量。 ```python # python appbuilder.logger.setLoglevel("DEBUG") ``` ```java // java System.setProperty("APPBUILDER_LOGLEVEL", "DEBUG"); ``` ```golang // golang os.Setenv("APPBUILDER_LOGLEVEL", "DEBUG") ``` ## 指定日志文件 如果需要将日志输出到指定文件,方便落盘。默认输出为标准输出流。 可以设置环境变量`APPBUILDER_LOGFILE`。 ```bash # 文件名及路径可以根据实际使用修改 export APPBUILDER_LOGFILE=/tmp/appbuilder.log ``` 也可以在代码中设置,优先级高于环境变量。 ```python # python appbuilder.logger.setFilename("/tmp/appbuilder.log") ``` ```java // java System.setProperty("APPBUILDER_LOGLFILE", "/tmp/appbuilder.log"); ``` ```golang // golang os.Setenv("APPBUILDER_LOGLEVEL", "/tmp/appbuilder.log") ``` ## `setLogConfig`功能 Appbuilder-SDK新增滚动日志功能 主要参数: - console_output: 数据类型bool,默认值True,LOG日志是否在控制台输出 - loglevel: 数据类型str,默认值"DEBUG",LOG日志级别 - log_path: 数据类型str,默认值"/tmp",默认日志存放路径。 - file_name: 数据类型str,默认值为进程id,日志名前缀 - rotate_frequency: 数据类型str,默认值"MIDNIGHT",LOG日志滚动更新时间单位 - "S": 以秒为单位 - "M": 以分钟为单位 - "H": 以小时为单位 - "D": 以天为时间单位 - "MIDNIGHT": 每日凌晨更新 - rotate_interval: 数据类型int,默认值1,LOG日志按时间滚动的参数,默认值为1,与when参数联合使用 - max_file_size: 数据类型Optional[int],默认值None,传入`None`或负数会自动更新为系统最大整数`sys.maxsize`,单个滚动的LOG日志文件的最大大小,例:10M即为10\*1024\*1024 即需要传入 # 以B为单位 - total_log_size: 数据类型Optional[int],默认值None,传入`None`或负数会自动更新为系统最大整数`sys.maxsize`,当前目录下可储存的LOG日志文件的最大大小,例:10M即为10\*1024\*1024 # 以B为单位 - max_log_files: 数据类型Optional[int],默认值None,传入`None`或负数会自动更新为系统最大整数`sys.maxsize`,当前目录下可储存的LOG日志文件的最大数量 **注意:`setLogConfig`会自动生成error.file_name日志与file_name日志文件分别储存`error`级别日志和`loglevel`级别的日志,且两种日志文件的滚动逻辑是独立的,不相互影响。** ```python # python appbuilder.logger.setLogConfig( console_output = False, loglevel="DEBUG" log_path="/tmp",, rotate_frequency="MIDNIGHT", # 每日凌晨更新 rotate_interval=1, max_file_size=100 * 1024 *1024, # 最大日志大小为100MB total_log_size=1024 * 1024 *1024, # 最大储存1GB的日志 max_log_files=10, # 当前目录储存的最大LOG日志数 ) ``` ================================================ FILE: docs/BasisModule/Trace/README.md ================================================ # Appbuilder Trace 文档 本文档目录包含以下内容 - [Appbuilder Trace跟踪功能基本用法](basic.md) - [Phoneix可视化软件的进阶用法](phoenix_method.md) - [Appbuilder Trace跟踪功能示例](https://github.com/baidubce/app-builder/blob/master/cookbooks/appbuilder_trace/trace.ipynb) ================================================ FILE: docs/BasisModule/Trace/basic.md ================================================ # Appbuilder-SDK TRACE ## 使用方法 ### 启动Phoenix可视化软件 **注意:没有可视化需求的可忽略此步骤** **如果未安装phoenix,需要先安装phoenix软件(这里提供清华园下载方式)** ```bash python3 -m pip install arize-phoenix==4.5.0 -i https://pypi.tuna.tsinghua.edu.cn/simple ``` **启动phoenix服务** ```bash appbuilder_trace_server ``` - 使用ctrl+c停止phoenix服务 ### 启动Appbuilder-SDK TRACE ```python from appbuilder import AppBuilderTracer tracer=AppBuilderTracer( enable_phoenix = True, enable_console = False, ) ``` - enable_phoenix:是否启动phoenix可视化跟踪 - enable_console:是否将trace信息反馈到控制台 ```python # 启动trace import os import appbuilder tracer.start_trace() os.environ["APPBUILDER_TOKEN"] = "YOUR_APPBUILDER_TOKEN" app_id = "YOUR_APP_ID" builder = appbuilder.AppBuilderClient(app_id) conversation_id = builder.create_conversation() msg = builder.run(conversation_id=conversation_id, query="你可以做什么?",stream=True) for m in msg.content: print(m) # 结束trace tracer.end_trace() ``` - Phoenix可视化效果 ![Phoenix可视化效果](https://bj.bcebos.com/v1/appbuilder-sdk-components/Phoenix%E5%8F%AF%E8%A7%86%E5%8C%96%E7%95%8C%E9%9D%A2%EF%BC%883%EF%BC%89.png?authorization=bce-auth-v1%2FALTAKGa8m4qCUasgoljdEDAzLm%2F2024-07-22T04%3A40%3A02Z%2F-1%2Fhost%2F07d2cbfb7dca01972b0f8521418669745ef6987c667747e8cedf0102caa27182) ================================================ FILE: docs/BasisModule/Trace/phoenix_method.md ================================================ # Phoneix可视化软件的进阶用法 ## 1. 选择可视化展示的选项 - 点击Columns,选择需要可视化展示的字段 ![选择可视化展示的选项](https://bj.bcebos.com/v1/appbuilder-sdk-components/%E4%BF%AE%E6%94%B9phoenix%E5%B1%95%E7%A4%BA%E5%8F%82%E6%95%B0.png?authorization=bce-auth-v1%2FALTAKGa8m4qCUasgoljdEDAzLm%2F2024-07-22T03%3A35%3A17Z%2F-1%2Fhost%2Ff9ff13fb2243ebbf1dd66008977a46def85aec56af5256be3f141fd36b6194c9) ## 2. 查看节点关键信息 - 点击需要查看的节点,查看节点关键信息,Info将展示input、ouput信息 ![查看节点关键信息 ](https://bj.bcebos.com/v1/appbuilder-sdk-components/Phoenix%E5%8F%AF%E8%A7%86%E5%8C%96%E7%95%8C%E9%9D%A2%EF%BC%883%EF%BC%89.png?authorization=bce-auth-v1%2FALTAKGa8m4qCUasgoljdEDAzLm%2F2024-07-22T03%3A36%3A11Z%2F-1%2Fhost%2Ffc471ccb9ecbc05eebf41f965e6df52132219f96bf688a46e6b6fa61f598088e) ## 3. 搜索目标节点 ### 依据节点类型搜索 - 点击搜索框,输入节点类型,搜索目标节点(eg: span_kind == 'AGENT') - 在Traces界面,只能检索到根节点、在Spans界面,可以检索到所有节点 ![依据节点类型搜索](https://bj.bcebos.com/v1/appbuilder-sdk-components/span_kind_find.png?authorization=bce-auth-v1%2FALTAKGa8m4qCUasgoljdEDAzLm%2F2024-07-22T04%3A39%3A04Z%2F-1%2Fhost%2F5bb320731860407968af9693c43c5639611776d760769d29077bcb2e968b05d1) ### 依据节点信息检索 - 依据节点信息检索可快速定位到目标节点 ![依据节点信息检索](https://bj.bcebos.com/v1/appbuilder-sdk-components/span_value_find.png?authorization=bce-auth-v1%2FALTAKGa8m4qCUasgoljdEDAzLm%2F2024-07-22T04%3A39%3A20Z%2F-1%2Fhost%2F43b20f9894586405e65195ebf6f86c21193812ab9ffd59f93287266e1a83ab03) ### 其他多种检索方式 ![其他多种检索方式](https://bj.bcebos.com/v1/appbuilder-sdk-components/every_span_find.png?authorization=bce-auth-v1%2FALTAKGa8m4qCUasgoljdEDAzLm%2F2024-07-22T04%3A39%3A35Z%2F-1%2Fhost%2Fa9b2dcf361416cf9a3727fc64d86bb370a5f24fc25286c53be15c5ecfd44e7e0) ================================================ FILE: docs/DevelopGuide/AdvancedDevelopment/README.md ================================================ # 开发指引 该文档目录包含以下内容: - [二次开发基本介绍](https://github.com/baidubce/app-builder/blob/master/docs/DevelopGuide/AdvancedDevelopment/README.md) - [AppBuilder SDK 运行环境超参配置说明](https://github.com/baidubce/app-builder/blob/master/docs/DevelopGuide/EnvironmentalParameters/env.md) ## 二次开发 当前已集成Python版本AppBuilder-SDK 0.9.4及相关依赖,方便开发者融入个人已有的大模型应用程序。此部分仍在不断建设中。 二次开发可以采用官方提供的开发镜像,便于快速安装各种依赖库。也可在镜像中使用已安装的`appbuilder_trace_server`、`appbuilder_bce_deploy`工具。 ``` shell docker pull registry.baidubce.com/appbuilder/appbuilder-sdk-devel:1.1.0 ``` ================================================ FILE: docs/DevelopGuide/ChangeLog/changelog.md ================================================ # 版本更新记录 * **2023.12.19 v0.1.0版本发布**:[Release Notes](https://github.com/baidubce/app-builder/releases/tag/0.1.0) * 初始版本发布,基础云组件支持包括BES;AI能力引擎语音、视觉类10个能力,大模型相关RAG、文本生成能力19个。 * **2024.01.03 v0.2.0版本发布** [Release Notes](https://github.com/baidubce/app-builder/releases/tag/0.2.0) * 核心升级点GBI相关组件新增,v0.1.0遗留问题修复 * **2024.01.26 v0.3.0版本发布** [Release Notes](https://github.com/baidubce/app-builder/releases/tag/0.3.0) * 新增组件:新增了百度搜索rag组件(RAGwithBaiduSearch)。[Cookbook](https://github.com/baidubce/app-builder/blob/master/cookbooks/rag_with_baidusearch.ipynb) * 模型列表获取:与千帆大模型平台模型名打通,可动态获取当前账号模型名,并在组件中使用[获取模型列表](/docs/basic_module/get_model_list.md) * 可通过官方镜像开发和运行实例代码[二次开发](/docs/develop_guide/README.md) * **2024.02.27 v0.4.0版本发布** [Release Note](https://github.com/baidubce/app-builder/releases/tag/0.4.0) * AppBuilder Console SDK发布[知识集合Cookbook](/cookbooks/end2end_application/rag/console_dataset.ipynb),[RAG调用Cookbook](/cookbooks/end2end_application/rag/rag.ipynb) * 大模型组件新增:Excel2Figure(基于Excel信息画图表) * AI能力引擎组件新增&更新:植物识别、动物识别、表格文字识别V2、手写文字识别、二维码识别、身份证混贴识别、文档矫正识别、图像内容理解、流式TTS * AgentRuntime:新增[Cookbook](/cookbooks/components/agent_runtime.ipynb) * **2024.03.13 v0.4.1版本发布** [ReleaseNote](https://github.com/baidubce/app-builder/releases/tag/0.4.1) * 支持以下功能进行FunctionCall调用:动植物识别、表格文字识别、条形码及二维码识别、身份证混贴识别、手写文字识别、text2image、excel2figure * **2024.03.20 v0.5.0版本发布** [ReleaseNote](https://github.com/baidubce/app-builder/releases/tag/0.5.0) * AgentBuilder ConsoleSDK发布 [Agent调用Cookbook](/cookbooks/end2end_application/agent/appbuilder_client.ipynb) * AI能力引擎组件新增:向量检索-VDB * 支持以下功能进行FunctionCall调用并新增[Cookbook](/cookbooks/components/general_ocr.ipynb):文本翻译-通用版、通用物体和场景识别-高级版、通用文字识别-高精度版、短语音识别-极速版 * **2024.03.21 v0.5.1版本发布** [ReleaseNote](https://github.com/baidubce/app-builder/releases/tag/0.5.1) * 问题修复:修复了在Python 3.8 及以下环境无法使用AgentBuilder ConsoleSDK的问题。同时,在即将发布的0.6.0版本中,将不再提供对Python 3.8及以下环境的支持,请升级Python版本到3.9 * **2024.04.12 v0.6.0版本发布** [ReleaseNote](https://github.com/baidubce/app-builder/releases/tag/0.6.0) * AppBuilder Console SDK 支持 JAVA 语言 [AppBuilder Java ConsoleSDK](/java/) * AppBuilder Console SDK 支持 GO 语言 [AppBuilder GO ConsoleSDK](/go/) * 首页README更新,提供免费的公共试用TOKEN,方便开发者快速体验 * **2024.04.30 v0.7.0版本发布** [ReleaseNote](https://github.com/baidubce/app-builder/releases/tag/0.7.0) * 提供Assistant SDK 功能,新增 [Cookbook](/cookbooks/pipeline/assistant_function_call.ipynb),包含流程编排与FunctionCall,搭建个性化Agent应用 * AgentBuilder组件更名为 AppBuilderClient, 后续版本将放弃对 `AgentBuilder` 的后向兼容支持 * 首页Readme与文档结构优化 * **2024.05.21 v0.7.1版本发布** [ReleaseNote](https://github.com/baidubce/app-builder/releases/tag/0.7.1) * 更新Assistant SDK 功能,为assistants/threads/messages/runs/files模块提供了完整的增删改查api, 新增`appbuilder.AssistantEventHandler`与`appbuilder.assistant.threads.runs.stream_run_with_handler`方法,更好的支持Assistant的流式调用 * 支持AppBuilder Client通过chainlit进行可视化的服务化部署 * 优化SDK的报错信息提示,方便开发者进行debug * 修复文档格式转换组件的域名错误问题 * **2024.06.11 v0.8.0版本发布** [ReleaseNote](https://github.com/baidubce/app-builder/releases/tag/0.8.0) * 提供功能更强大的Debug模式 * 支持AppBuilder Client通过chainlit进行可视化的服务化部署 * 多个组件进行了效果优化与说明文档更新 * **2024.06.28 v0.9.0版本发布** [ReleaseNote](https://github.com/baidubce/app-builder/releases/tag/0.9.0) * Python/Go/Jave Console SDK 上新,支持Token用量返回,支持`get_app_list`, 支持`KnowledgeBase`功能 * 新增AppBuilder-SDK Depoly功能,支持用户使用SDK快速部署本地组件orAgent应用到百度智能云,并对外提供服务 * 更新SDK超参,支持SDK在私有化部署环境的使用 * 更新口语化组件,优化效果 * **2024.07.25 v0.9.1版本发布** [ReleaseNote](https://github.com/baidubce/app-builder/releases/tag/0.9.1) * KnowledgeBase组件完整支持`知识库`、`知识库文档`及`文档切片`的增删改查 * 新增appbuilder_trace_server与AppBuilderTracer功能,支持组件、AppBuilderClient、Assistant的链路追踪 * **2024.08.16 v0.9.2版本发布** [ReleaseNote](https://github.com/baidubce/app-builder/releases/tag/0.9.2) * AppBuilderClient 新增ToolCall功能,支持开发者注册本地函数为组件,扩展Agent能力边界 * 新增`PPTGenerationFromFile`、`PPTGenerationFromInstruction`、`PPTGenerationFromPaper`三个组件 * **2024.08.20 v0.9.3版本发布** [ReleaseNote](https://github.com/baidubce/app-builder/releases/tag/0.9.3) * Text2Image组件接口及效果更新 * ImageUnderstand组件接口及效果更新 * **2024.09.04 v0.9.4版本发布** [ReleaseNote](https://github.com/baidubce/app-builder/releases/tag/0.9.4) * AppBuilderClient新增tool_choice / end_user_id功能 * 增加VScode setting,优化开发者使用体验 * **2024.10.18 v0.9.5版本发布** [ReleaseNote](https://github.com/baidubce/app-builder/releases/tag/0.9.5) * 更新KnowledgeBase组件,新增`切片详情`获取接口,新增切片关联的图片ID字段 * AppBuilderTrace 支持SentrySDK * AppBuilder新增[Sphinx API文档](../../API-Reference/Python/modules.md) * **2024.10.26 v0.9.6版本发布** [ReleaseNote](https://github.com/baidubce/app-builder/releases/tag/0.9.6) * 更新AppBuilderClient,简化Java & Go语言使用ToolCall的方式 * 新增长文档内容理解组件 * 优化requirements,去除部分组件的版本限制 * 简化报错堆栈,去除冗余的Trace信息 * **2024.11.27 v0.9.7版本发布** [ReleaseNote](https://github.com/baidubce/app-builder/releases/tag/0.9.7) * 新增TreeMind组件 * 新增工作流Agent回复“信息收集节点”功能,支持多轮对话事件处理 * Python的ToolCall功能支持通过函数定义、装饰器的形式等生成ToolCall参数 * **2024.12.10 v0.9.8版本发布** [ReleaseNote](https://github.com/baidubce/app-builder/releases/tag/0.9.8) * AppBuilderClient新增追问功能支持 * TTS组件新增更多语音效果 * 通用文字识别组件新增更多语言支持 * 实时语音通话功能内测 * **2025.01.03 v1.0.0版本发布** [ReleaseNote](https://github.com/baidubce/app-builder/releases/tag/1.0.0) * 工作流自定义组件支持SDK调用 * 新增RAG检索SDK * Agent Python SDK支持Async调用 * 新增滚动日志功能 * **2025.01.16 v1.0.1版本发布** [ReleaseNote](https://github.com/baidubce/app-builder/releases/tag/1.0.1) * 修复1.0.0中的Python SDK流式调用慢问题 * **2025.01.24 v1.0.2版本发布** [ReleaseNote](https://github.com/baidubce/app-builder/releases/tag/1.0.2) * 升级KnowledgebaseClient,同步更新OpenAPI的入参 * 升级KnowledgebaseClient,同步更新知识库创建入参 * 升级ComponentClient,同步更新OpenAPI的出参 * **2025.02.28 v1.0.3版本发布** [ReleaseNote](https://github.com/baidubce/app-builder/releases/tag/1.0.3) * AppBuilderClient新增点踩点赞功能支持 * 知识库支持配置目录、切片模糊搜索、文档状态信息等功能升级 * MCP协议支持 * **2025.03.27 v1.0.4版本发布** [ReleaseNote](https://github.com/baidubce/app-builder/releases/tag/1.0.4) * MCP Client新增SSE协议支持 * 新增百度AI搜索的MCP Server * AppBuilderClient调用支持显示DeepSeek-R1思考过程 * **2025.04.05 v1.0.5版本发布** [ReleaseNote](https://github.com/baidubce/app-builder/releases/tag/1.0.5) * **2025.04.24 v1.0.6版本发布** [ReleaseNote](https://github.com/baidubce/app-builder/releases/tag/1.0.6) * 组件MCP SSE Server支持多副本 * 新增 AppBuilder RAG MCP服务 * 新增 AppBuilder Agent MCP服务 * MCP Server支持添加OpenAPI tools * **2025.06.20 v1.1.0版本发布** [ReleaseNote](https://github.com/baidubce/app-builder/releases/tag/1.1.0) * Python/Java 支持AI搜索V2,支持百度搜索 * Python模型列表SDK切换v2接口,新增 * Python/Go/Java 增加应用详情SDK,支持自主规划Agent、工作流Agent * Java SDK 流式响应支持手动中断 ================================================ FILE: docs/DevelopGuide/EnvironmentalParameters/env.md ================================================ # AppBuilder SDK 运行环境超参配置说明 ## 运行超参 - `APPBUILDER_TOKEN` - 超参说明:设置当前运行环境的用户Token,用于所有接口的鉴权 - 默认值: 空字符串 - 影响范围:当前终端(Terminal)运行的所有AppBuilder程序 - `SECRET_KEY_PREFIX` - 超参说明:设置当前运行环境中AppBuilder组件(Component)的密钥前缀,SDK会自动组装最终的密钥为 `{SECRET_KEY_PREFIX} {APPBUILDER_TOKEN}`的形式,用于发起HTTP请求。常用于私有化部署的场景。 - 默认值: `Bearer` - 影响范围:当前终端(Terminal)运行的所有AppBuilder程序 - `GATEWAY_URL` - 超参说明:设置当前运行环境中AppBuilder组件(Component)网关的URL - 默认值: `https://appbuilder.baidu.com` - 影响范围:当前终端(Terminal)运行的所有AppBuilder程序中的基础组件调用请求 - `GATEWAY_URL_V2` - 超参说明:设置当前运行环境中AppBuilder OpenAPI的URL - 默认值: `https://qianfan.baidubce.com` - 影响范围:当前终端(Terminal)运行的所有AppBuilder程序中的端到端应用 及 OpenAPI能力的调用 - 注意事项:当前该参数影响以下接口 - `AppBuilderClient SDK` 所有接口 - `KnowledgeBase SDK` 所有接口 - `CONSOLE_OPENAPI_PREFIX` - 超参说明:设置当前运行环境中AppBuilder OpenAPI的URL前缀,体现在`https://qianfan.baidubce.com/{custom_prefix}/v2/app/conversation`中的`{custom_prefix}`字段。常用于私有化部署的场景。 - 默认值: 空字符串 - 影响范围:当前终端(Terminal)运行的所有AppBuilder程序中的端到端应用 及 OpenAPI能力的调用 - 注意事项:当前该参数影响以下接口 - `AppBuilderClient SDK` 所有接口 - `KnowledgeBase SDK` 所有接口 - `CONSOLE_OPENAPI_VERSION` - 超参说明:设置当前运行环境中AppBuilder OpenAPI的版本,体现在`https://qianfan.baidubce.com/{custom_prefix}/v2/app/conversation`中的`/v2`字段。常用于私有化部署的场景。 - 默认值: `v2` - 影响范围:当前终端(Terminal)运行的所有AppBuilder程序中的端到端应用 及 OpenAPI能力的调用 - 注意事项:当前该参数影响以下接口 - `AppBuilderClient SDK` 所有接口 - `KnowledgeBase SDK` 所有接口 ### 运行超参使用Tips - 私有化环境部署时,需要同时设置私有化部署的网关地址:`GATEWAY_URL`和`GATEWAY_URL_V2`,且需要使用在私有化环境中可以鉴权的用户Token:`APPBUILDER_TOKEN`与`SECRET_KEY_PREFIX` ## 调试超参 - `APPBUILDER_LOGLEVEL` - 超参说明:设置AppBuilder运行的日志级别,可选值:`DEBUG`, `INFO`, `WARNING`, `ERROR` - 默认值: INFO - 影响范围:当前终端(Terminal)运行的所有AppBuilder程序的日志级别 - 注意事项:`APPBUILDER_LOGLEVEL`生效于`import appbuilder`时,若期望该参数生效,可使用`appbuilder.logger.setLoglevel("DEBUG")`方法设置 ```python import appbuilder # NOQA appbuilder.logger.setLoglevel("DEBUG") # NOQA ``` - `APPBUILDER_LOGFILE` - 超参说明:设置AppBuilder运行的日志文件路径,最好是绝对路径 - 默认值;空 - 注意事项:`APPBUILDER_LOGFILE`生效于`import appbuilder`时,若期望该参数生效,可使用`appbuilder.logger.setLogFile("")`方法设置 ```python import appbuilder # NOQA appbuilder.logger.setFilename("/tmp/appbuilder.log") # NOQA ``` ================================================ FILE: docs/DevelopGuide/ErrorMessage/error_message.md ================================================ # SDK 错误信息 1、 `BaseRPCException` - 报错解释: - Base RPC exception, - SDK基类异常 2、 `BadRequestException` - 报错解释: - BadRequestException represent HTTP Code 400 - BadRequestException 表示请求错误,错误码为400 3、 `ForbiddenException` - 报错解释: - ForbiddenException represent HTTP Code 403 - ForbiddenException 表示禁止访问,错误码为403 4、 `NotFoundException` - 报错解释: - NotFoundException represent HTTP Code 404 - NotFoundException 表示资源不存在,错误码为404 5、 `PreconditionFailedException` - 报错解释: - PreconditionFailedException represent HTTP Code 412 - PreconditionFailedException 表示前置条件失败,错误码为412 6、 `InternalServerErrorException` - 报错解释: - InternalServerErrorException represent HTTP Code 500 - InternalServerErrorException 表示内部服务器错误,错误码为500 7、 `HTTPConnectionException` - 报错解释: - HTTPConnectionException represent HTTP Connection error - HTTPConnectionException 表示HTTP连接错误 8、 `ModelNotSupportedException` - 报错解释: - ModelNotSupportedException represent model is not supported - ModelNotSupportedException 表示模型不支持 9、 `TypeNotSupportedException` - 报错解释: - TypeNotSupportedException represent type is not supported - TypeNotSupportedException 表示类型不支持 10、 `AppBuilderServerException` - 报错解释: - AppBuilderServerException represent backend server failed response - AppBuilderServerException 表示后端服务器响应失败 11、 `AssistantServerException` - 报错解释: - AssistantSercerException represent assistant server failed response. - AssistantSercerException 表示助理服务器响应失败 12、 `InvalidRequestArgumentError` - 报错解释: - InvalidRequestArgumentError invalid request param - InvalidRequestArgumentError 表示请求参数无效 13、 `RiskInputException` - 报错解释: - RiskInputException represent risk input error - RiskInputException 表示异常输入错误 14、 `AppbuilderBuildexException` - 报错解释: - Appbuilder buledex exception - AppbuilderBuildexException 表示AppBuilder-SDK构建异常,报错使用与Appbuilder-SDK的构造代码单元检测不符合规范 15、 `AppbuilderTraceException` - 报错解释: - Appbuilder trace exception - AppbuilderTraceException 表示AppBuilder-SDK追踪框架异常,使用`export APPBUILDER_TRACE_DEBUG=TRUE`来开启Appbuilder-SDK的追踪框架的DEBUG模式,展示报错的完整链路并调试 ================================================ FILE: docs/DevelopGuide/HowToContributeCode/README.md ================================================ # SDK 贡献代码规范 ## 组件开发规范 ### 组件整体介绍 在无特殊情况下,一个官方组件(class Component)的实现可以拆解为以下几个关键模块,分别是 * def run:组件的run函数,规范体现在该函数的输入和输出 * 输入规范 * 输出规范 * def tool_eval:组件功能的核心实现,规范体现在该函数的输入和输出 * 输入规范 * 输出规范 * dict manifest:组件参与FunctionCall时,帮助大模型理解组件功能的说明,规范体现在manifest的内容和格式 * manifest规范 ### `run` 函数 #### 消息(Message) - 构建大模型应用的统一数据结构,基于Pydantic构建,在不同的Component之间流动。Message基类的默认字段是content,类型是Any。 ```python from appbuilder import Message input_dict = Message({"query": "红烧肉怎么做"}) input_list = Message(["text1", "text2", "text3"]) input_str = Message("红烧肉怎么做") ``` #### `run` 函数输入输出规范 - 所有能力单元的标准结构,以Message结构作为输入输出,内部执行逻辑可在本地执行或调用云端服务,以下是官方组件的实现示例。`run` 函数需要添加 `@components_run_trace` 装饰器,实现对组件的trace。 ```python from appbuilder.utils.trace.tracer_wrapper import components_run_trace class SimilarQuestionMeta(ComponentArguments): """ SimilarQuestionMeta """ message: Message = Field(..., variable_name="query", description="输入消息,用于模型的输入,一般为问题。") class SimilarQuestion(CompletionBaseComponent): """ 基于输入的问题, 挖掘出与该问题相关的类似问题。广泛用于客服、问答等场景。 Examples: .. code-block:: python import os import appbuilder os.environ["APPBUILDER_TOKEN"] = "..." qa_mining = appbuilder.SimilarQuestion(model="DeepSeek-V3.1") msg = "我想吃冰淇淋,哪里的冰淇淋比较好吃?" msg = appbuilder.Message(msg) answer = qa_mining(msg) print("Answer: \n{}".format(answer.content)) """ name = "similar_question" version = "v1" meta = SimilarQuestionMeta def __init__(self, model=None): """初始化SimilarQuestionMeta任务。 Args: model (str|None): 模型名称,用于指定要使用的千帆模型。 Returns: None """ super().__init__(SimilarQuestionMeta, model=model) @components_run_trace def run(self, message, stream=False, temperature=1e-10): """ 给定输入(message)到模型运行,同时指定运行参数,并返回结果。 参数: message (obj:`Message`): 输入消息,用于模型的主要输入内容。这是一个必需的参数。 stream (bool, 可选): 指定是否以流式形式返回响应。默认为 False。 temperature (float, 可选): 模型配置的温度参数,用于调整模型的生成概率。取值范围为 0.0 到 1.0,其中较低的值使生成更确定性,较高的值使生成更多样性。默认值为 1e-10。 返回: obj:`Message`: 模型运行后的输出消息。 """ return super().run(message=message, stream=stream, temperature=temperature) ``` ### `tool_eval` 函数 #### `ComponentOutput` 类 ```python class ComponentOutput(BaseModel): role: str = Field(default="tool", description="role是区分当前消息来源的重要字段,对于绝大多数组件而言,都是填写tool,标明role所在的消息来源为组件。部分思考及问答组件,role需要填写为assistant") content: list[Content] = Field(default=[], description="content是当前组件返回内容的主要payload,List[Content],每个Content Dict 包括了当前输出的一个元素") ``` #### `tool_eval` 函数输入输出规范 - 组件的核心实现,需要添加 `@components_run_stream_trace` 装饰器,实现对组件的trace。 ##### `tool_eval` 函数 输入参数 * 组件tool_eval方法的输入,除了在manifest中约定的参数外,也可能会传入以下系统变量,辅助组件的运行。 * 系统入参列表中的字段是保留字段,组件定义的manifest不能与系统参数重名。系统参数中有可以被用户设置的参数例如uploaded_files,也有不能设置的字段例如traceid等。 * 在组件的开发中,以下系统输入字段体现为 def tool_eval(self, key1, key2, \*\*kwargs)中\*\*kwargs包含的内容,key1和key2是manifest中约定的参数,kwargs中的内容是系统入参。 ##### `tool_eval` 函数 组件返回字段 * 组件返回参数统一采用json字段,固定key名称和对应的value,value默认是dict类型,value本身需要指定visible_scope。 * 非流式返回结果,按照所有流式内容的key-value进行合并,例如两个event都是references,那么需要两组references合并,所有组件需要支持非流式返回。 * 基于sse协议提供流式数据 * content 本身是个 List[Dict],每个 Dict是当前 event 的一个元素,一般有多个元素的返回例如 urls/files 才需要多个 Dict ###### 组件返回字段总览 |字段|类型|是否必须|默认值 及 取值范围|作用说明|备注| |---|---|---|---|---|---| |role|str|否|- tool 默认
- user
- assistant
|ole是区分当前消息来源的重要字段,对于绝大多数组件而言,都是填写tool,标明role所在的消息来源为组件。部分思考及问答组件,role需要填写为assistant|{"role": "tool"}| |content|list[dict]|是|[]Event|当前组件返回内容的主要payload,List[Dict],每个 Dict 包括了当前 event 的一个元素|| |+ name|str|否|part1,part2或者3d_pics,title|介绍当前yield内容的step name使用name的必要条件,是有不同content需要是属于结构上的不同字段,但又是streaming的|| |+ type|str|是|* text 默认
* code
* files
* urls
* oral_text
* references
* image
* chart
* audio
* json|代表event 类型,包括 text、code、files、urls、oral_text、references、image、chart、audio、tought、json
该字段的取值决定了下面text字段的内容结构|| |+ text|dict
object|是|{}|代表当前 event 元素的内容,每一种 event 对应的 text 结构固定|保留字段
"text": {'filename': 'chart_url.png', 'url': 'https://chart_url.png'},| |+ visible_scope|str|否|all 默认
llm
user
空|为了界面展示明确的说明字段
* llm为思考模型可见,类似function calling结果中submit的执行结果
* user为终端用户可见|workflow中存在消息通知节点,类型为notice
目前实测,llm、user、all用户都可见,只是气泡不一样。llm在下拉框中,user直接输出到气泡中。| |+ raw_data|dict
object|否|{}|内部信息,由开发者请求透传,内部系统返回的信息,例如API节点收到的resp,大模型节点的MB resp|{
"origin_response": "xxxxx"
}| |+ usage|list of dict
object|否|{}|大模型的token用量|{
"prompt_tokens": 1547,
"completion_tokens": 2,
"total_tokens": 1549,
"name": "ERNIE Speed-AppBuilder"
}| |+ metrics|dict
object|否|{}|耗时、性能、内存等trace及debug所需信息|{
"begin_timestamp": xxxxx
"end_timestamp": xxxxx
}| ##### 包含 `manifests` 定义的 `tool_eval` 函数返回示例 ```python class SimilarQuestion(CompletionBaseComponent): r""" 基于输入的问题, 挖掘出与该问题相关的类似问题。广泛用于客服、问答等场景。 Examples: .. code-block:: python import os import appbuilder os.environ["APPBUILDER_TOKEN"] = "..." qa_mining = appbuilder.SimilarQuestion(model="DeepSeek-V3.1") msg = "我想吃冰淇淋,哪里的冰淇淋比较好吃?" msg = appbuilder.Message(msg) answer = qa_mining(msg) print("Answer: \n{}".format(answer.content)) """ name = "similar_question" version = "v1" meta = SimilarQuestionMeta manifests = [ { "name": "similar_question", "description": "基于输入的问题,挖掘出与该问题相关的类似问题。", "parameters": { "type": "object", "properties": { "query": { "type": "string", "description": "输入的问题,用于大模型根据该问题输出相关的类似问题。" } }, "required": [ "query" ] } } ] def __init__( self, model: str="DeepSeek-V3.1", secret_key: Optional[str] = None, gateway: str = "", lazy_certification: bool = True, ): """初始化StyleRewrite模型。 Args: model (str|None): 模型名称,用于指定要使用的千帆模型。 secret_key (str, 可选): 用户鉴权token, 默认从环境变量中获取: os.getenv("APPBUILDER_TOKEN", ""). gateway (str, 可选): 后端网关服务地址,默认从环境变量中获取: os.getenv("GATEWAY_URL", "") lazy_certification (bool, 可选): 延迟认证,为True时在第一次运行时认证. Defaults to False. Returns: None """ super().__init__( SimilarQuestionMeta, model=model, secret_key=secret_key, gateway=gateway, lazy_certification=lazy_certification) @components_run_stream_trace def tool_eval(self, query: str, **kwargs): """ 根据给定的query和可选参数生成并返回文本输出。 Args: query (str): 需要生成文本的输入查询字符串。 **kwargs: 其他可选参数。 Returns: Generator[Output]: 返回一个生成器,生成类型为Output的对象。 """ traceid = kwargs.get("_sys_traceid") msg = Message(query) model_configs = kwargs.get('model_configs', {}) temperature = model_configs.get("temperature", 1e-10) top_p = model_configs.get("top_p", 0.0) message = super().run(message=msg, stream=False, temperature=temperature, top_p=top_p, request_id=traceid) yield self.create_output(type="text", text=str(message.content), name="text", usage=message.token_usage) ``` ### `manifest` 规范 * 若组件有tool_eval方法,则必须要求存在manifest * 现状:算法手动撰写;未来:提供工具,自动从python函数的入参及注释转manifest * mainfests是一个list[dict],是对组件多个能力的规范化描述,如无特殊情况,一般list中只有一个元素,对应tool_eval的能力 * manifest dict要满足json schema协议要求 * 要求manifest dict中parameters-properties定义的参数,与def tool_eval的入参一致 * 组件中的version字段,会影响的组件URL,参考组件API:组件调用形如: * /v2/components/${component}/version/{$version}?action=${action} * 遵循新规范的组件,因输入输出与原组件不兼容,在实现上有显著的标志区分 #### Json Schema协议 - [Json Schema协议](https://json-schema.org/overview/what-is-jsonschema),以下是示例 ```python class BaiduSearchWithModel(Component): r""" 百度搜索总结工具 """ name = "baidu_search_with_model" version = "v1" # 修改此处,会影响组件的调用URL manifests = [ { "name": "baidu_search_with_model", # 组件名称 "description": "对百度搜索结果进行大模型总结", # 组件描述,该字段重要,影响 function calling 效果 "parameters": { # parameters 描述组件入参列表 "type": "object", "properties": { # 多个参数可以指定多个 properties "query": { "type": "string", # 参数query 的类型 "description": "搜索关键词" # 参数query 的描述,该字段重要,影响 function calling 效果 } }, "required": [ "query" # query参数为必填字段 ] } } ] ``` ## 代码合入单元测试规范 * 现状: 当前开源Appbuilder-SDK已经部署了单元测试流水线,并要求90%的单元测试覆盖率合入要求,要求开发者实现完整已开发的代码的端到端的测试,并且要求代码增量行覆盖率为90% ### 单元测试规范 #### 单元测试要求 - 覆盖if-else分支 - 对于包含if-else逻辑的代码,需要编写测试用例来确保每个分支都被执行到 - 输入的边界条件检查 - 边界条件通常指的是数据范围的极值(如最小值和最大值),或者特定情况下的特殊值(如空值、空字符串、负值等) - Error raise的覆盖 - 确保测试覆盖了所有可能抛出异常的代码路径,包括代码自身的预期错误,以及访问远程服务失败后的错误处理 #### Test文件目录 * test文件需要为『test_』开头 * 测试类需要形如『class TestAgentRuntime(unittest.TestCase)::』的定义方式 * test文件需要置于appbuilder-sdk-ext/appbuilder_sdk_ext/tests路径下 #### UnitTest提供三种标签实现两种运行模式 * 添加下列标签,单元测试脚本实现cpu并行 * @unittest.skipUnless(os.getenv("TEST_CASE", "UNKNOWN") == "CPU_PARALLEL", "") * 不添加标签,单元测试脚本默认使用cpu串行 * 添加下列标签,暂时跳过当前单元测试脚本 * @unittest.skip(reason="单测暂时跳过") ##### SKIP标签代码示例 ```python @unittest.skipUnless(os.getenv("TEST_CASE", "UNKNOWN") == "CPU_PARALLEL", "") class TestCreateChatPrompt(unittest.TestCase): pass class TestCreateChatPrompt(unittest.TestCase): pass @unittest.skip(reason="单测暂时跳过") class TestCreateChatPrompt(unittest.TestCase): pass ``` #### SDK测试代码示例 下面给出一个通过parameterized库进行多种参数组合的示例,可以大幅简化单测代码,但需注意,多种参数的测试case会并行运行,对服务的QPS有要求 ```python import unittest from parameterized import parameterized, param import appbuilder class TestHandwritingOcr(unittest.TestCase): @parameterized.expand([ param(image_url, None, None), param(image_url, None, 0), param(image_url, float(120), None), param(image_url, None, 1), param(image_url, 120.5, 1), param(image_url, float(12000), None), ]) def test_normal_case(self, image, timeout, retry): """ 正常用例 """ # 创建表格识别组件实例 handwrite_ocr = appbuilder.HandwriteOCR() # 执行识别操作并获取结果 if timeout is None and retry is None: out = handwrite_ocr.run(appbuilder.Message(content={"url": image})) elif timeout is None: out = handwrite_ocr.run(appbuilder.Message(content={"url": image}), retry=retry) elif retry is None: out = handwrite_ocr.run(appbuilder.Message(content={"url": image}), timeout=timeout) else: out = handwrite_ocr.run(appbuilder.Message(content={"url": image}), timeout=timeout, retry=retry) res = out.content self.assertIsNotNone(res["contents"], "识别结果为空") self.assertEqual(len(res["contents"]), 6) @parameterized.expand([ # timeout为0 param(image_url, 0, 0, "ValueError", "timeout", 'but the timeout cannot be set to a value ' 'less than or equal to 0.'), # timeout为字符串 param(image_url, "a", 0, "appbuilder.core._exception.InvalidRequestArgumentError", "timeout", 'timeout must be float or tuple of float'), # timeout为0.1,太短了 param(image_url, float(0.1), 0, "requests.exceptions.ReadTimeout", "timeout", "Read timed out. (read timeout=0.1)"), # retry为字符串 param(image_url, float(10), "a", "TypeError", "str", "'<' not supported between instances of" " 'str' and 'int'"), # image_url错误 param("https://bj.bcebos.com/v1/appbuilder/xxx", 12.5, 1, "appbuilder.core._exception.AppBuilderServerException", "url", "service_err_message=url format illegal"), ]) def test_abnormal_case(self, image, timeout, retry, err_type, err_param, err_msg): """ 异常用例 """ try: # 创建表格识别组件实例 handwrite_ocr = appbuilder.HandwriteOCR() # 执行识别操作并获取结果 out = handwrite_ocr.run(appbuilder.Message(content={"url": image}), timeout=timeout, retry=retry) res = out.content log.info(res) assert False, "未捕获到错误信息" except Exception as e: self.assertIsInstance(e, eval(err_type), "捕获的异常不是预期的类型 实际:{}, 预期:{}".format(e, err_type)) self.assertIn(err_param, str(e), "捕获的异常参数类型不正确, 预期 参数:{}, 实际:{}".format(err_param, str(e))) self.assertIn(err_msg, str(e), "捕获的异常消息不正确, 预期:{}, 实际:{}".format(err_msg, str(e))) ``` ## 注释规范 - SDK使用注释自动生成API文档,因此非私有函数的注释需要严格按照Google代码注释规范编写 ### object类注释 ```python class AppBuilderClient(Component): r""" AppBuilderClient 组件支持调用在[百度智能云千帆AppBuilder](https://cloud.baidu.com/product/AppBuilder)平台上 构建并发布的智能体应用,具体包括创建会话、上传文档、运行对话等。 Examples: .. code-block:: python import appbuilder # 请前往千帆AppBuilder官网创建密钥,流程详见:https://cloud.baidu.com/doc/AppBuilder/s/Olq6grrt6#1%E3%80%81%E5%88%9B%E5%BB%BA%E5%AF%86%E9%92%A5 os.environ["APPBUILDER_TOKEN"] = '...' # 可在Console 应用页面获取 app_id = "app_id" client = appbuilder.AppBuilderClient("app_id") conversation_id = client.create_conversation() file_id = client.upload_local_file(conversation_id, "/path/to/file") message = client.run(conversation_id, "今天你好吗?") # 打印对话结果 print(message.content) """ ``` - 注意 - 注释必须使用 Examples:之后必须存在一行空行,.. code-block:: python之后也必须要有一行空行 - code-block前为两点(..)之后为两个冒号(::) - 方法的示例注释与此规范相同 ### 函数注释 - 私有函数如_recognize_w_post_process等无需按照规范注释函数 ```python @components_run_stream_trace def tool_eval( self, name: str, streaming: bool, origin_query: str, **kwargs, ) -> Union[Generator[str, None, None], str]: """ 执行工具函数,通过调用底层接口进行动物识别。 Args: name (str): 工具名 streaming (bool): 是否流式返回结果,True 表示流式返回,False 表示一次性返回 origin_query (str): 用户原始查询字符串 **kwargs: 工具调用的额外关键字参数 Returns: Union[Generator[str, None, None], str]: 动物识别结果。如果 streaming 为 True,则返回一个生成器,可以逐个返回识别结果; 如果 streaming 为 False,则返回一个字符串,包含识别出的动物类别和相应的置信度信息。 """ ``` ### google风格指南与规范示例 - Google详情见 [Google注释风格指南](https://google.github.io/styleguide/pyguide.html) ```python class GoogleStyle: '''Google注释风格 用 ``缩进`` 分隔, 适用于倾向水平,短而简单的文档 Attributes: dividend (int or float): 被除数 name (:obj:`str`, optional): 该类的命名 ''' def __init__(self, dividend, name='GoogleStyle'): '''初始化''' self.dividend = dividend self.name = name def divide(self, divisor): '''除法 Google注释风格的函数, 类型主要有Args、Returns、Raises、Examples Args: divisor (int):除数 Returns: 除法结果 Raises: ZeroDivisionError: division by zero Examples: .. code-block:: python # 实例代码 References: 除法_百度百科 https://baike.baidu.com/item/%E9%99%A4%E6%B3%95/6280598 ''' try: return self.dividend / divisor except ZeroDivisionError as e: return e ``` ================================================ FILE: docs/QuickStart/CurrentlySupportedProgrammingLanguages/README.md ================================================ ## SDK当前支持的编程语言 - 平台功能 SDK: 支持Pyhon/Java/Go - [应用管理](../../BasisModule/Platform/Application/get_app_list.md) - [应用调用 AppBuilderClient SDK](../../BasisModule/Platform/Application/appbuilder_client.md) - [知识库管理 KnowledgeBase SDK](../../BasisModule/Platform/KnowledgeBase/knowledgebase.md) - AI基础能力组件 SDK:支持Python - [获取模型列表](../../BasisModule/Model/get_model_list.md) - [基础能力组件](../../BasisModule/Platform/CustomComponents/components.md) ================================================ FILE: docs/QuickStart/ExamplesOfIndustrialPracticeApplications/README.md ================================================ # AppBuilder 功能组件 AppBuilder面向开发者提供AI原生应用一站式开发工具,包括基础云资源、AI能力引擎、千帆大模型以及相关能力组件,提升AI原生应用开发效率。 百度智能云千帆 AppBuilder 在提供零代码、低代码的AI原生应用搭建功能之外,也提供全代码灵活开发与集成能力。基于官方 API/SDK,开放丰富的组件服务,提供具备强大对话、思考及工具调用能力的 Agent 应用框架。 封装程度由高至低,AppBuilder 提供了三种类型的SDK | 分类 | 场景及使用方式 | 百度云文档链接 | SDK 文档链接| |--------|--------|------------|------------| | 端到端应用 | 在 AppBuilder 产品界面上通过零代码、低代码方式创建的 AI 原生应用,支持通过应用 API/SDK 进行调用 | [应用API及SDK](https://cloud.baidu.com/doc/AppBuilder/s/Plvggbuzc) | [AppBuilder Client SDK](https://github.com/baidubce/app-builder/blob/master/docs/BasisModule/Platform/Application/appbuilder_client.md) | | 工具组件 | 基于组件 SDK,可调用包括大模型组件、AI能力组件等在内的多种组件 | [组件SDK](https://cloud.baidu.com/doc/AppBuilder/s/Glqb6dfiz) | [组件列表](https://cloud.baidu.com/doc/AppBuilder/s/Glqb6dfiz#3%E3%80%81%E5%BC%80%E9%80%9A%E7%BB%84%E4%BB%B6%E6%9C%8D%E5%8A%A1) | ## 功能示例 ### 获取模型列表 AppBuilder提供获取千帆模型列表的函数,在运行具体组件之前,可以先获取当前账号下可以使用的模型列表,代码如下: ``` python import appbuilder import os # 设置环境中的TOKEN,请替换为您的个人TOKEN os.environ["APPBUILDER_TOKEN"] = "your api key" models = appbuilder.get_model_list(api_type_filter=["chat"], is_available=True) print(", ".join(models)) ``` 填写自己的Token,获取模型列表输出示例如下: ``` shell ERNIE-Bot 4.0, ERNIE-Bot, ERNIE-3.5-8K-0205, ERNIE-Speed, DeepSeek-V3.1, ERNIE-Character-8K, EB-turbo-AppBuilder专用版, ChatLaw, ERNIE-Bot-8K ``` 为方便用户更容易使用模型,以下是一些模型的短名称 | 千帆模型名 | AppBuilder-SDK短名 | |----------------------------|------------------| | ERNIE-Bot 4.0 | eb-4 | | ERNIE-Bot | eb | | ERNIE-Bot-turbo | eb-turbo | | EB-turbo-AppBuilder专用版 | ernie_speed_appbuilder | | DeepSeek-V3.1 | deepseek-v3.1-250821 | ### 空模版(Playground) ```python import appbuilder import os # 设置环境中的TOKEN,请替换为您的个人TOKEN os.environ["APPBUILDER_TOKEN"] = "your api key" # 空模版组件 template_str = "你扮演{role}, 请回答我的问题。\n\n问题:{question}。\n\n回答:" playground = appbuilder.Playground(prompt_template=template_str, model="DeepSeek-V3.1") # 定义输入,调用空模版组件 input = appbuilder.Message({"role": "java工程师", "question": "java语言的内存回收机制是什么"}) print(playground(input, stream=False, temperature=1e-10)) ``` ### 文本生成(Text Completion) ```python import appbuilder import os # 设置环境中的TOKEN,请替换为您的个人TOKEN os.environ["APPBUILDER_TOKEN"] = "your api key" # 相似问生成组件 similar_q = appbuilder.SimilarQuestion(model="DeepSeek-V3.1") # 定义输入,调用相似问生成 input = appbuilder.Message("我想吃冰淇淋,哪里的冰淇淋比较好吃?") print(similar_q(input)) ``` ### 检索增强问答 ```python import appbuilder import os # 设置环境中的TOKEN,请替换为您的个人TOKEN os.environ["APPBUILDER_TOKEN"] = "your api key" # 此处填写线上Agent应用ID,可在【AppBuilder网页端-我的应用界面】查看 # 本示例提供的Agent应用为:地理小达人 # 网页已部署的应用链接为「地理小达人」:https://appbuilder.baidu.com/s/x1tSF # 以下示例代码展示了如何代码态调用并集成到您的应用中的能力 app_id = "42eb211a-14b9-43d2-9fae-193c8760ef26" builder = appbuilder.AppBuilderClient(app_id) conversation_id = builder.create_conversation() answer = builder.run(conversation_id, "中国的首都在哪里") print(answer.content) ``` ### 应用服务化 AppBuilder-SDK提供对组件的服务化能力。通过定义Agent,开发者可以快速启动Chainlit、Flask等服务化的Demo或API提供快速体验环境。 在需要部署服务的环境中,开发者需要首先手动安装 Chainlit 库 ```shell pip install chainlit ``` 而后,使用AppBuilder的Agent服务化功能,即可快速部署服务 ```python import appbuilder # 空模版组件 playground = appbuilder.Playground( prompt_template="{query}", model="DeepSeek-V3.1" ) # 使用 AgentRuntime 来服务化playground组件 agent = appbuilder.AgentRuntime(component=playground) # 启动chainlit demo,会自动在浏览器打开体验对话框页面 agent.chainlit_demo(port=8091) ``` ================================================ FILE: docs/QuickStart/StartFirstAINativeApplication/README.md ================================================ # 快速开始 该文档目录包含以下内容: - [SDK安装](https://github.com/baidubce/app-builder/blob/master/docs/QuickStart/StartFirstAINativeApplication/install.md) - [版本更新历史](https://github.com/baidubce/app-builder/blob/master/docs/DevelopGuide/ChangeLog/changelog.md) ## 预备步骤 在正式开始使用AppBuilder-SDK之前,可以阅读以下内容: * **预备步骤** * [认证鉴权](https://cloud.baidu.com/doc/AppBuilder/s/Olq6grrt6) * [开通组件权限](https://cloud.baidu.com/doc/AppBuilder/s/Olq6grrt6#2%E3%80%81%E5%BC%80%E9%80%9A%E7%BB%84%E4%BB%B6%E6%9C%8D%E5%8A%A1) * **API文档** * [API Docs](https://cloud.baidu.com/doc/AppBuilder/s/Glqb6dfiz) ## 快速上手 ### 获取模型列表 AppBuilder提供获取千帆模型列表的函数,在运行具体组件之前,可以先获取当前账号下可以使用的模型列表,代码如下: ``` python import appbuilder import os # 设置环境中的TOKEN,请替换为您的个人TOKEN os.environ["APPBUILDER_TOKEN"] = "your api key" models = appbuilder.get_model_list(api_type_filter=["chat"], is_available=True) print(", ".join(models)) ``` 填写自己的Token,获取模型列表输出示例如下: ``` shell ERNIE-Bot 4.0, ERNIE-Bot, ERNIE-3.5-8K-0205, ERNIE-Speed, DeepSeek-V3.1, ERNIE-Character-8K, EB-turbo-AppBuilder专用版, ChatLaw, ERNIE-Bot-8K ``` 为方便用户更容易使用模型,以下是一些模型的短名称 | 千帆模型名 | AppBuilder-SDK短名 | |----------------------------|------------------------------| | ERNIE-Bot 4.0 | eb-4 | | ERNIE-Bot | eb | | ERNIE-Bot-turbo | eb-turbo | | EB-turbo-AppBuilder专用版 | ernie_speed_appbuilder | | DeepSeek-V3.1 | deepseek-v3.1-250821 | ### 空模版(Playground) ```python import appbuilder import os # 设置环境中的TOKEN,请替换为您的个人TOKEN os.environ["APPBUILDER_TOKEN"] = "your api key" # 空模版组件 template_str = "你扮演{role}, 请回答我的问题。\n\n问题:{question}。\n\n回答:" playground = appbuilder.Playground(prompt_template=template_str, model="DeepSeek-V3.1") # 定义输入,调用空模版组件 input = appbuilder.Message({"role": "java工程师", "question": "java语言的内存回收机制是什么"}) print(playground(input, stream=False, temperature=1e-10)) ``` ### 文本生成(Text Completion) ```python import appbuilder import os # 设置环境中的TOKEN,请替换为您的个人TOKEN os.environ["APPBUILDER_TOKEN"] = "your api key" # 相似问生成组件 similar_q = appbuilder.SimilarQuestion(model="DeepSeek-V3.1") # 定义输入,调用相似问生成 input = appbuilder.Message("我想吃冰淇淋,哪里的冰淇淋比较好吃?") print(similar_q(input)) ``` ### 检索增强问答 ```python import appbuilder import os # 设置环境中的TOKEN,请替换为您的个人TOKEN os.environ["APPBUILDER_TOKEN"] = "your api key" # 此处填写线上Agent应用ID,可在【AppBuilder网页端-我的应用界面】查看 # 本示例提供的Agent应用为:地理小达人 # 网页已部署的应用链接为「地理小达人」:https://appbuilder.baidu.com/s/x1tSF # 以下示例代码展示了如何代码态调用并集成到您的应用中的能力 app_id = "42eb211a-14b9-43d2-9fae-193c8760ef26" builder = appbuilder.AppBuilderClient(app_id) conversation_id = builder.create_conversation() answer = builder.run(conversation_id, "中国的首都在哪里") print(answer.content) ``` ### 应用服务化 AppBuilder-SDK提供对组件的服务化能力。通过定义Agent,开发者可以快速启动Chainlit、Flask等服务化的Demo或API提供快速体验环境。 在需要部署服务的环境中,开发者需要首先手动安装 Chainlit 库 ```shell pip install chainlit ``` 而后,使用AppBuilder的Agent服务化功能,即可快速部署服务 ```python import appbuilder # 空模版组件 playground = appbuilder.Playground( prompt_template="{query}", model="DeepSeek-V3.1" ) # 使用 AgentRuntime 来服务化playground组件 agent = appbuilder.AgentRuntime(component=playground) # 启动chainlit demo,会自动在浏览器打开体验对话框页面 agent.chainlit_demo(port=8091) ``` 也可以对AppBuilderClient进行服务化,快速部署 ```python import os from appbuilder.core.component import Component from appbuilder import ( AgentRuntime, AppBuilderClient, ) if __name__ == "__main__": # 设置环境中的TOKEN,请替换为您的个人TOKEN os.environ["APPBUILDER_TOKEN"] = "your api key" # 此处填写线上Agent应用ID,可在【AppBuilder网页端-我的应用界面】查看 # 本示例提供的Agent应用为:地理小达人 # 网页已部署的应用链接为「地理小达人」:https://appbuilder.baidu.com/s/x1tSF app_id = "42eb211a-14b9-43d2-9fae-193c8760ef26" agent_builder = AppBuilderClient(app_id) agent = AgentRuntime(component=agent_builder) agent.chainlit_agent(port=8091) ``` ================================================ FILE: docs/QuickStart/StartFirstAINativeApplication/install.md ================================================ # AppBuilder-SDK 安装 ### Python > 执行如下命令,快速安装Python语言的最新版本AppBuilder-SDK(要求Python >= 3.9)。使用MCP功能要求Python >= 3.10。 ```shell pip install --upgrade appbuilder-sdk ``` 如果在本地无法跑通appbuilder-sdk包,也可以使用我们的官方镜像来安装和运行,具体方案参考**二次开发**部分。 ### Java (仅支持调用端到端应用) > 使用AppBuilder Java ConsoleSDK要求Java版本>=8 #### Maven 在pom.xml的dependencies中添加依赖 ```xml com.baidubce appbuilder 1.1.0 ``` #### Gradle 对于Kotlin DSL,在build.gradle.kts的dependencies中添加依赖 ```kotlin implementation("com.baidubce:appbuilder:1.1.0") ``` 对于Groovy DSL,在build.gradle的dependencies中添加依赖 ```groovy implementation 'com.baidubce:appbuilder:1.1.0' ``` #### 本地导入 点击[链接](https://repo1.maven.org/maven2/com/baidubce/appbuilder/1.1.0/appbuilder-1.1.0.jar) 下载Jar包,将Jar包导入到项目目录下。 ### Go (仅支持调用端到端应用) > 支持Go 1.18.1以上版本,当前最新tag为v1.1.0 ```shell go get github.com/baidubce/app-builder/go/appbuilder ```` ### Docker (当前仅集成了Python版本AppBuilder-SDK) ``` shell docker pull registry.baidubce.com/appbuilder/appbuilder-sdk-devel:1.1.0 ``` ================================================ FILE: docs/README.md ================================================ # AppBuilder-SDK Documentation ## Github 文档 - [首页](https://github.com/baidubce/app-builder/blob/master/docs/README.md) - 快速上手: - 开始你的第一个AI原生应用: - [安装](https://github.com/baidubce/app-builder/blob/master/docs/QuickStart/StartFirstAINativeApplication/install.md) - [快速开始](https://github.com/baidubce/app-builder/blob/master/docs/QuickStart/StartFirstAINativeApplication/README.md) - 产业实践应用范例: - [SDK使用示例](https://github.com/baidubce/app-builder/blob/master/docs/QuickStart/ExamplesOfIndustrialPracticeApplications/README.md) - [SDK当前支持的编程语言](https://github.com/baidubce/app-builder/blob/master/docs/QuickStart/CurrentlySupportedProgrammingLanguages/README.md) - 基础: - 模型: - [获取模型列表](https://github.com/baidubce/app-builder/blob/master/docs/BasisModule/Model/get_model_list.md) - [组件](https://github.com/baidubce/app-builder/blob/master/docs/BasisModule/Components) - 监控: - [TRACE基础功能](https://github.com/baidubce/app-builder/blob/master/docs/BasisModule/Trace/basic.md) - [TRACE拓展功能](https://github.com/baidubce/app-builder/blob/master/docs/BasisModule/Trace/phoenix_method.md) - 部署: - [交互式前端部署](https://github.com/baidubce/app-builder/blob/master/docs/BasisModule/Deployment/AgentChainlit.md) - [公有云部署](https://github.com/baidubce/app-builder/blob/master/docs/BasisModule/Deployment/cloud.md) - [API 访问](https://github.com/baidubce/app-builder/blob/master/docs/BasisModule/Deployment/flask.md) - [AgentRuntime](https://github.com/baidubce/app-builder/blob/master/docs/BasisModule/Deployment/agentruntime.md) - [UserSession](https://github.com/baidubce/app-builder/blob/master/docs/BasisModule/Deployment/usersession.md) - 平台: - 应用: - [AppBuilderClient组件](https://github.com/baidubce/app-builder/blob/master/docs/BasisModule/Platform/Application/appbuilder_client.md) - [获取AppBuilder已发布的应用列表](https://github.com/baidubce/app-builder/blob/master/docs/BasisModule/Platform/Application/get_app_list.md) - 知识库: - [知识库组件](https://github.com/baidubce/app-builder/blob/master/docs/BasisModule/Platform/KnowledgeBase/knowledgebase.md) - 自定义组件: - [基础能力组件](https://github.com/baidubce/app-builder/blob/master/docs/BasisModule/Platform/CustomComponents/components.md) - 应用: - Agent: - [基础知识](https://github.com/baidubce/app-builder/blob/master/docs/Application/Agent/BasicKnowledge/agent.md) - [使用官方组件](https://github.com/baidubce/app-builder/blob/master/docs/Application/Agent/UseOfficialComponents/use_official_components.md) - [ToolCall](https://github.com/baidubce/app-builder/blob/master/docs/Application/Agent/ToolCall/tool_call.md) - [ToolChoice](https://github.com/baidubce/app-builder/blob/master/docs/Application/Agent/ToolChoice/tool_choice.md) - [使用异步和流式加速客户端调用](https://github.com/baidubce/app-builder/blob/master/docs/Tools/DocPass/DocPass.md) - RAG: - [基础知识](https://github.com/baidubce/app-builder/blob/master/docs/Application/RAG/BasicKnowledge/rag.md) - [知识库管理](https://github.com/baidubce/app-builder/blob/master/docs/Application/RAG/DatasetManage/dataset_manage.md) - [Reference信息处理](https://github.com/baidubce/app-builder/blob/master/docs/Tools/DocPass/DocPass.md) - Workflow: - [基础知识](https://github.com/baidubce/app-builder/blob/master/docs/Tools/DocPass/DocPass.md) - [从零使用Workflow组装一个RAG应用](https://github.com/baidubce/app-builder/blob/master/docs/Tools/DocPass/DocPass.md) - [从零使用Workflow组装一个Agent应用](https://github.com/baidubce/app-builder/blob/master/docs/Tools/DocPass/DocPass.md) - 开发者指南: - [如何贡献代码](https://github.com/baidubce/app-builder/blob/master/docs/DevelopGuide/HowToContributeCode/README.md) - [二次开发](https://github.com/baidubce/app-builder/blob/master/docs/DevelopGuide/AdvancedDevelopment/README.md) - [版本升级日志](https://github.com/baidubce/app-builder/blob/master/docs/DevelopGuide/ChangeLog/changelog.md) - [错误信息](https://github.com/baidubce/app-builder/blob/master/docs/DevelopGuide/ErrorMessage/error_message.md) - [环境参数](https://github.com/baidubce/app-builder/blob/master/docs/DevelopGuide/EnvironmentalParameters/env.md) ## 平台文档 - [产品文档](https://cloud.baidu.com/doc/AppBuilder/s/6lq7s8lli) - [平台资源](https://cloud.baidu.com/doc/AppBuilder/s/llq6grh7e) - [快速搭建应用](https://cloud.baidu.com/doc/AppBuilder/s/Tlpv3oxpy) - [开发参考](https://cloud.baidu.com/doc/AppBuilder/s/7luwm2yt0) - [SDK](https://cloud.baidu.com/doc/AppBuilder/s/Glqb6dfiz) - [OpenAPI](https://cloud.baidu.com/doc/AppBuilder/s/klv2eywua) - [Assistant API](https://cloud.baidu.com/doc/AppBuilder/s/nluzkdben) - [常见问题](https://cloud.baidu.com/doc/AppBuilder/s/qlq7sdj9z) ================================================ FILE: docs/README_en.md ================================================
logo
[![License](https://img.shields.io/badge/license-Apache%202-blue.svg)](LICENSE) ![Supported Python versions](https://img.shields.io/badge/python-3.9+-orange.svg) ![Supported OSs](https://img.shields.io/badge/os-linux%2C%20win%2C%20mac-yellow.svg)
[简体中文](../README.md) | English | [日本語](./README_ja.md)
## What is AppBuilder SDK? Baidu AI Cloud Qianfan AppBuilder SDK is a `one-stop development tool` for AI native application developers which contributed by [Baidu AI Cloud Qianfan AppBuilder](https://appbuilder.cloud.baidu.com/). Baidu AI Cloud Qianfan AppBuilder SDK provides the following essential functions for AI application developers: Baidu AI Cloud Qianfan AppBuilder-SDK offers the following essential features for AI application developers: 1. Utilization - Utilize large language models, freely accessing your models on Baidu AI Cloud Qianfan Large Model Platform to develop and optimize prompts. - Integrate capability components, providing over 40 high-quality groups originating from Baidu's ecosystem to empower Agent applications. - Integrate AI-native applications, accessing and managing AI-native applications published on [Baidu AI Cloud Qianfan AppBuilder Platform]((https://console.bce.baidu.com/ai_apaas/app)) through AppBuilderClient, and registering local functions to link end-cloud components. 2. Orchestration - Orchestrate and manage knowledge flows, managing knowledge bases through KnowledgeBase, performing create, read, update, and delete (CRUD) operations on documents and knowledge slices, and developing industry-grade RAG applications with Baidu AI Cloud Qianfan AppBuilder Platform. - Orchestrate and automate workflows, providing multi-level workflow abstractions such as `Message`, `Component`, and `AgentRuntime` to achieve workflow orchestration and integration with industry ecosystem capabilities like LangChain and OpenAI. 3. Monitoring - Providing monitoring tools such as visual Tracing and detailed DebugLog to assist developers in production environments. 4. Deployment - AgentRuntime supports deployment as an API service based on Flask and Gunicorn. - AgentRuntime supports deployment as a Chainlit-based dialog interaction front-end application. - Offering the appbuilder_bce_deploy tool for rapid deployment of programs to Baidu Cloud, providing public network API services, and enabling integration with AppBuilder's workflow functionalities. ## How to install? #### The latest version of Baidu AI Cloud Qianfan AppBuilder SDK is 1.1.0. (2025-06-20) Baidu AI Cloud Qianfan AppBuilder SDK ReleaseNote please refer to our [version description](/docs/DevelopGuide/ChangeLog/changelog.md) - We recommend installing the latest stable version of `Python` ```bash python3 -m pip install --upgrade appbuilder-sdk ``` - For installation of `Java` and `Go` versions, as well as using `Docker` images, please refer to the [Installation Instructions](/docs/QuickStart/StartFirstAINativeApplication/install.md) ## Quickly start your first AI native application! - Please install `appbuilder sdk` in a Python environment with `>=3.9` and use this end-to-end application example - The example provides a trial token, but access and QPS are restricted. Please replace it with your personal token for official use ### 1. Large Language models - The `Playground` component can be freely called. You can customize the `prompt` template and model parameters for any model you have permission on the Baidu AI Cloud Qianfan model platform #### Code example ```python import appbuilder import os # 设置环境中的TOKEN,请替换为您的个人TOKEN os.environ["APPBUILDER_TOKEN"] = "your api key" # 定义prompt模板 template_str = "你扮演{role}, 请回答我的问题。\n\n问题:{question}。\n\n回答:" # 定义输入,调用playground组件 input = appbuilder.Message({"role": "java工程师", "question": "请简要回答java语言的内存回收机制是什么,要求100字以内"}) playground = appbuilder.Playground(prompt_template=template_str, model="DeepSeek-V3.1") # 以打字机的方式,流式展示大模型回答内容 output = playground(input, stream=True, temperature=1e-10) for stream_message in output.content: print(stream_message) # 流式输出结束后,可再次打印完整的大模型对话结果,除回答内容外,还包括token的用量情况 print(output.model_dump_json(indent=4)) ``` #### Answer display ```shell Java语言的 内存回收机制是通过垃圾回收器(Garbage Collector)来实现的。 垃圾回收器会自动检测不再使用的对象,并释放其占用的内存空间,从而确保系统的内存不会被耗尽。 Java提供了多种垃圾回收器,如串行回收器、并行回收器、CMS回收器和G1回收器等,以满足不同场景下的性能需求 。 { "content": "Java语言的内存回收机制是通过垃圾回收器(Garbage Collector)来实现的。垃圾回收器会自动检测不再使用的对象,并释放其占用的内存空间,从而确保系统的内存不会被耗尽。Java提供了多种垃圾回收器,如串行回收器、并行回收器、CMS回收器和G1回收器等,以满足不同场景下的性能需求。", "name": "msg", "mtype": "dict", "id": "2bbee989-40e3-45e4-9802-e144cdc829a9", "extra": {}, "token_usage": { "prompt_tokens": 35, "completion_tokens": 70, "total_tokens": 105 } } ``` ### 2. Component - The SDK provides over 40 high-quality components sourced from the Baidu ecosystem, as listed in [Component List](https://cloud.baidu.com/doc/AppBuilder/s/Glqb6dfiz#3%E3%80%81%E5%BC%80%E9%80%9A%E7%BB%84%E4%BB%B6%E6%9C%8D%E5%8A%A1), Before calling, you need to apply for a [free trial quota](https://console.bce.baidu.com/ai-engine/old/#/ai/ocr/overview/resource/list) - The component in the example is the `RAG with Baidu Search Pro`, which combines Baidu Search's search engine technology with the semantic understanding ability of ERNIE model to more accurately understand the user's search intention and provide search results with higher relevance to the search query #### Code Example ```python import appbuilder import os # 设置环境中的TOKEN,请替换为您的个人TOKEN os.environ["APPBUILDER_TOKEN"] = "your api key" rag_with_baidu_search_pro = appbuilder.RagWithBaiduSearchPro(model="ERNIE-Lite-AppBuilder-8K") input = appbuilder.Message("9.11和9.8哪个大") result = rag_with_baidu_search_pro.run( message=input, instruction=appbuilder.Message("你是专业知识助手")) # 输出运行结果 print(result.model_dump_json(indent=4)) ``` #### Answer display ``` { "content": "9.11小于9.8。在比较两个小数的大小时,需要逐位比较它们的数值,包括整数部分和小数部分。对于9.11和9.8,整数部分都是9,所以需要在小数部分进行比较。小数点后的第一位是1和8,显然1小于8,所以9.11小于9.8。", "name": "msg", "mtype": "dict", "id": "eb31b7de-dd6a-485f-adb9-1f7921a6f4bf", "extra": { "search_baidu": [ { "content": "大模型‘智商’受质疑:9.11 vs 9...", "icon": "https://appbuilder.bj.bcebos.com/baidu-search-rag-pro/icon/souhu.ico", "url": "https://m.sohu.com/a/793754123_121924584/", "ref_id": "2", "site_name": "搜狐网", "title": "大模型‘智商’受质疑:9.11 vs 9.8的比较揭示AI理解能力的..." }, { "content": "究竟|9.11比9.8大?大模型们为何会...", "icon": "https://appbuilder.bj.bcebos.com/baidu-search-rag-pro/icon/tencent.svg.png", "url": "https://new.qq.com/rain/a/20240717A07JLV00", "ref_id": "4", "site_name": "腾讯网", "title": "究竟|9.11比9.8大?大模型们为何会在小学数学题上集体..." }, ... ] }, "token_usage": { "completion_tokens": 77, "prompt_tokens": 2008, "total_tokens": 2085 } } ``` ### 3. AI-native applications - The application in the example is: [Rap Mentor](https://appbuilder.baidu.com/s/3qfjXy7k),Click on this link to try it out on the web page #### Code Example ```python import appbuilder import os # 设置环境中的TOKEN,请替换为您的个人TOKEN os.environ["APPBUILDER_TOKEN"] = "your api key" # 从AppBuilder网页获取并传入应用ID,以下为说唱导师应用ID app_id = "4678492a-5864-472e-810a-654538d3503c" app_builder_client = appbuilder.AppBuilderClient(app_id) conversation_id = app_builder_client.create_conversation() answer = app_builder_client.run(conversation_id, "以“上班狼狈却又追逐梦想“为主题进行一首说唱创作,保持押韵, 控制在200字以内") print(answer.content.answer) ``` #### Answer display ```shell 好的,我们来以“上班狼狈却又追逐梦想”为主题,进行一段简短的说唱创作。这里是一个简单的示例,你可以根据自己的感觉进行调整: Intro: 朝九晚五,生活重压, 狼狈上班,却心怀梦想, 每一天,都是新的挑战, 为了那未来,我奋发向前。 Verse 1: 穿上西装,打好领带, 步入人群,去追逐名利, 虽然狼狈,却不曾言败, 因为心中,有梦想在激励。 Hook: 上班狼狈,却不曾放弃, 追逐梦想,是我心中的火炬, 照亮前路,指引我前行, 无论多难,我都要坚持到底。 这首小曲儿以“上班狼狈却又追逐梦想”为主题,通过押韵的方式表达了上班族虽然生活艰辛,但依然怀揣梦想,勇往直前的精神。希望你喜欢! ``` **For more examples of AI native application code, please refer to [CookBooks](./bookbooks/README.md)**. We have the following cookbooks that we recommend you to read first: - Basic Ability Components - [General Text Recognition Component](/cookbooks/components/general_ocr.ipynb) - [Basic component service-oriented deployment](/cookbooks/components/agent_runtime.ipynb) - Process orchestration - [Assistant SDK](/cookbooks/pipeline/assistant_function_call.ipynb) - End-to-end applications - [Agent](/cookbooks/agent_builder.ipynb) - [RAG](/cookbooks/end2end_application/rag/rag.ipynb) - [Enterprise level Q&A system](/cookbooks/end2end_application/rag/qa_system_2_dialogue.ipynb) - Advaned Practice - [Deploying services on public cloud](/cookbooks/advanced_application/cloud_deploy.ipynb) - [Service Tracing](/cookbooks/appbuilder_trace/trace.ipynb) ## Panorama of Baidu AI Cloud Qianfan AppBuilder SDK capability
wechat
## User Documentation - [Home](https://github.com/baidubce/app-builder/blob/master/docs/README.md) - Quick Start: - Start your first AI-native application: - [Installation](https://github.com/baidubce/app-builder/blob/master/docs/QuickStart/StartFirstAINativeApplication/install.md) - [Quick Start Guide](https://github.com/baidubce/app-builder/blob/master/docs/QuickStart/StartFirstAINativeApplication/README.md) - Industrial practice application examples: - [SDK usage examples](https://github.com/baidubce/app-builder/blob/master/docs/QuickStart/ExamplesOfIndustrialPracticeApplications/README.md) - [Currently supported programming languages by SDK](https://github.com/baidubce/app-builder/blob/master/docs/QuickStart/CurrentlySupportedProgrammingLanguages/README.md) - Basics: - Models: - [Get model list](https://github.com/baidubce/app-builder/blob/master/docs/BasisModule/Model/get_model_list.md) - [Components](https://github.com/baidubce/app-builder/blob/master/docs/BasisModule/Components) - Monitoring: - [TRACE basic functions](https://github.com/baidubce/app-builder/blob/master/docs/BasisModule/Trace/basic.md) - [TRACE extended functions](https://github.com/baidubce/app-builder/blob/master/docs/BasisModule/Trace/phoenix_method.md) - [Debug functionality](https://github.com/baidubce/app-builder/blob/master/docs/BasisModule/Trace/Debug.md) - Deployment: - [Interactive front-end deployment](https://github.com/baidubce/app-builder/blob/master/docs/BasisModule/Deployment/AgentChainlit.md) - [Public cloud deployment](https://github.com/baidubce/app-builder/blob/master/docs/BasisModule/Deployment/cloud.md) - [API access](https://github.com/baidubce/app-builder/blob/master/docs/BasisModule/Deployment/flask.md) - [AgentRuntime](https://github.com/baidubce/app-builder/blob/master/docs/BasisModule/Deployment/agentruntime.md) - [UserSession](https://github.com/baidubce/app-builder/blob/master/docs/BasisModule/Deployment/usersession.md) - Platform: - Applications: - [AppBuilderClient component](https://github.com/baidubce/app-builder/blob/master/docs/BasisModule/Platform/Application/appbuilder_client.md) - [Get the list of applications published by AppBuilder](https://github.com/baidubce/app-builder/blob/master/docs/BasisModule/Platform/Application/get_app_list.md) - Knowledge Base: - [Knowledge Base component](https://github.com/baidubce/app-builder/blob/master/docs/BasisModule/Platform/KnowledgeBase/knowledgebase.md) - Custom Components: - [Basic capabilities component](https://github.com/baidubce/app-builder/blob/master/docs/BasisModule/Platform/CustomComponents/components.md) - Applications: - Agent: - [Basic knowledge](https://github.com/baidubce/app-builder/blob/master/docs/Application/Agent/BasicKnowledge/agent.md) - [Using official components](https://github.com/baidubce/app-builder/blob/master/docs/Application/Agent/UseOfficialComponents/use_official_components.md) - [ToolCall](https://github.com/baidubce/app-builder/blob/master/docs/Application/Agent/ToolCall/tool_call.md) - [ToolChoice](https://github.com/baidubce/app-builder/blob/master/docs/Application/Agent/ToolChoice/tool_choice.md) - [Using asynchronous and streaming accelerated client calls](https://github.com/baidubce/app-builder/blob/master/docs/Tools/DocPass/DocPass.md) - RAG: - [Basic knowledge](https://github.com/baidubce/app-builder/blob/master/docs/Application/RAG/BasicKnowledge/rag.md) - [Knowledge Base Management](https://github.com/baidubce/app-builder/blob/master/docs/Application/RAG/DatasetManage/dataset_manage.md) - [Reference Information Processing](https://github.com/baidubce/app-builder/blob/master/docs/Tools/DocPass/DocPass.md) - Workflow: - [Basic knowledge](https://github.com/baidubce/app-builder/blob/master/docs/Tools/DocPass/DocPass.md) - [Assembling a RAG application from scratch using Workflow](https://github.com/baidubce/app-builder/blob/master/docs/Tools/DocPass/DocPass.md) - [Assembling an Agent application from scratch using Workflow](https://github.com/baidubce/app-builder/blob/master/docs/Tools/DocPass/DocPass.md) - Developer Guide: - [How to contribute code](https://github.com/baidubce/app-builder/blob/master/docs/DevelopGuide/HowToContributeCode/README.md) - [Secondary Development](https://github.com/baidubce/app-builder/blob/master/docs/DevelopGuide/AdvancedDevelopment/README.md) - [Version upgrade log](https://github.com/baidubce/app-builder/blob/master/docs/DevelopGuide/ChangeLog/changelog.md) - [Error messages](https://github.com/baidubce/app-builder/blob/master/docs/DevelopGuide/ErrorMessage/error_message.md) - [Environmental parameters](https://github.com/baidubce/app-builder/blob/master/docs/DevelopGuide/EnvironmentalParameters/env.md) ## Open source community and activities

AppBuilder-SDK WeChat Group QR Code

wechat
- [Github Issue](https://github.com/baidubce/app-builder/issues): Submit installation/usage issues, report bugs, suggest new features, communicate development plans, etc - [Baidu AI Cloud Qianfan Community](https://cloud.baidu.com/qianfandev) ## License AppBuilder SDK follows the Apache 2.0 open source protocol. ================================================ FILE: docs/README_ja.md ================================================
logo
[![License](https://img.shields.io/badge/license-Apache%202-blue.svg)](LICENSE) ![Supported Python versions](https://img.shields.io/badge/python-3.9+-orange.svg) ![Supported OSs](https://img.shields.io/badge/os-linux%2C%20win%2C%20mac-yellow.svg)
[简体中文](../README.md) | [English](./README_en.md) | 日本語
## AppBuilder SDKとは? Baidu AI Cloud Qianfan AppBuilder SDKは、[Baidu AI Cloud Qianfan AppBuilder](https://appbuilder.cloud.baidu.com/)によって提供されるAIネイティブアプリケーション開発者向けの「ワンストップ開発ツール」です。 Baidu AI Cloud Qianfan AppBuilder-SDKは、AIアプリケーション開発者向けに以下の基本機能を提供します: 1. 利用 - 大規模言語モデルを利用し、Baidu AI Cloud Qianfan大規模モデルプラットフォームで自由にモデルにアクセスし、プロンプトを開発および最適化します。 - 機能コンポーネントを統合し、Baiduのエコシステムから提供される40以上の高品質なグループを提供し、エージェントアプリケーションに力を与えます。 - AIネイティブアプリケーションを統合し、[Baidu AI Cloud Qianfan AppBuilderプラットフォーム](https://console.bce.baidu.com/ai_apaas/app)で公開されたAIネイティブアプリケーションにAppBuilderClientを通じてアクセスおよび管理し、エンドクラウドコンポーネントをリンクするためにローカル関数を登録します。 2. オーケストレーション - 知識フローをオーケストレーションおよび管理し、KnowledgeBaseを通じて知識ベースを管理し、文書および知識スライスの作成、読み取り、更新、削除(CRUD)操作を実行し、Baidu AI Cloud Qianfan AppBuilderプラットフォームと共に業界グレードのRAGアプリケーションを開発します。 - ワークフローをオーケストレーションおよび自動化し、`Message`、`Component`、`AgentRuntime`などの多層ワークフロー抽象を提供し、ワークフローのオーケストレーションを実現し、LangChainやOpenAIなどの業界エコシステム機能と統合します。 3. 監視 - 開発者が生産環境で使用するための可視化トレースおよび詳細なデバッグログなどの監視ツールを提供します。 4. デプロイメント - AgentRuntimeは、FlaskおよびGunicornに基づくAPIサービスとしてデプロイメントをサポートします。 - AgentRuntimeは、Chainlitに基づく対話型フロントエンドアプリケーションとしてデプロイメントをサポートします。 - プログラムをBaidu Cloudに迅速にデプロイし、パブリックネットワークAPIサービスを提供し、AppBuilderのワークフロー機能と統合するためのappbuilder_bce_deployツールを提供します。 ## どのようにインストールしますか? #### Baidu AI Cloud Qianfan AppBuilder SDKの最新バージョンは1.1.0(2025-06-20)です Baidu AI Cloud Qianfan AppBuilder SDKのリリースノートについては、[バージョン説明](DevelopGuide/ChangeLog/changelog.md)をご覧ください。 - 最新の安定バージョンの`Python`をインストールすることをお勧めします。 ```bash python3 -m pip install --upgrade appbuilder-sdk ``` - `Java`および`Go`バージョンのインストールや`Docker`イメージの使用については、[インストール手順](QuickStart/StartFirstAINativeApplication/install.md)をご覧ください。 ## 最初のAIネイティブアプリケーションをすぐに開始しましょう! - `>=3.9`のPython環境に`appbuilder sdk`をインストールし、このエンドツーエンドアプリケーションの例を使用してください。 - 例では試用トークンが提供されていますが、アクセスとQPSが制限されています。正式な使用には個人のトークンに置き換えてください。 ### 1. 大規模言語モデル - `Playground`コンポーネントは自由に呼び出すことができます。Baidu AI Cloud Qianfanモデルプラットフォームで許可された任意のモデルに対して、プロンプトテンプレートとモデルパラメータをカスタマイズできます。 #### コード例 ```python import appbuilder import os # 環境変数にTOKENを設定します。以下のTOKENはアクセスとQPSが制限された試用TOKENです。正式な使用には個人のTOKENに置き換えてください。 os.environ["APPBUILDER_TOKEN"] = "your api key" # プロンプトテンプレートを定義します。 template_str = "あなたは{role}の役割を果たします。私の質問に答えてください。\n\n質問:{question}。\n\n回答:" # 入力を定義し、playgroundコンポーネントを呼び出します。 input = appbuilder.Message({"role": "Javaエンジニア", "question": "Java言語のメモリ回収メカニズムについて簡単に説明してください。100文字以内でお願いします。"}) playground = appbuilder.Playground(prompt_template=template_str, model="DeepSeek-V3.1") # タイプライターのように、ストリーム形式で大規模モデルの回答内容を表示します。 output = playground(input, stream=True, temperature=1e-10) for stream_message in output.content: print(stream_message) # ストリーム出力が終了した後、再度完全な大規模モデルの対話結果を表示できます。回答内容の他に、トークンの使用量も含まれます。 print(output.model_dump_json(indent=4)) ``` #### 回答表示 ```shell Java言語の メモリ回収メカニズムは、ガベージコレクタ(Garbage Collector)を通じて実現されます。 ガベージコレクタは、使用されなくなったオブジェクトを自動的に検出し、その占有するメモリ空間を解放します。これにより、システムのメモリが枯渇しないようにします。 Javaは、シリアルコレクタ、パラレルコレクタ、CMSコレクタ、G1コレクタなど、さまざまなガベージコレクタを提供しており、異なるシナリオでのパフォーマンス要件に対応しています。 { "content": "Java言語のメモリ回収メカニズムは、ガベージコレクタ(Garbage Collector)を通じて実現されます。ガベージコレクタは、使用されなくなったオブジェクトを自動的に検出し、その占有するメモリ空間を解放します。これにより、システムのメモリが枯渇しないようにします。Javaは、シリアルコレクタ、パラレルコレクタ、CMSコレクタ、G1コレクタなど、さまざまなガベージコレクタを提供しており、異なるシナリオでのパフォーマンス要件に対応しています。", "name": "msg", "mtype": "dict", "id": "2bbee989-40e3-45e4-9802-e144cdc829a9", "extra": {}, "token_usage": { "prompt_tokens": 35, "completion_tokens": 70, "total_tokens": 105 } } ``` ### 2. コンポーネントの呼び出し - SDKは、Baiduのエコシステムから提供される40以上の高品質なコンポーネントを提供しています。リストは[コンポーネントリスト](https://cloud.baidu.com/doc/AppBuilder/s/Glqb6dfiz#3%E3%80%81%E5%BC%80%E9%80%9A%E7%BB%84%E4%BB%B6%E6%9C%8D%E5%8A%A1)で確認できます。呼び出す前に[無料試用クォータ](https://console.bce.baidu.com/ai-engine/old/#/ai/ocr/overview/resource/list)を申請してください。 - 例のコンポーネントは`RAG with Baidu Search Pro`で、Baidu Searchの検索エンジン技術とERNIEモデルのセマンティック理解能力を組み合わせて、ユーザーの検索意図をより正確に理解し、検索クエリに関連性の高い検索結果を提供します。 #### コード例 ```python import appbuilder import os # 環境変数にTOKENを設定します。以下のTOKENはアクセスとQPSが制限された試用TOKENです。正式な使用には個人のTOKENに置き換えてください。 os.environ["APPBUILDER_TOKEN"] = "your api key" rag_with_baidu_search_pro = appbuilder.RagWithBaiduSearchPro(model="ERNIE-Lite-AppBuilder-8K") input = appbuilder.Message("9.11と9.8のどちらが大きいですか?") result = rag_with_baidu_search_pro.run( message=input, instruction=appbuilder.Message("あなたは専門知識アシスタントです")) # 実行結果を出力します。 print(result.model_dump_json(indent=4)) ``` #### 回答表示 ```shell { "content": "9.11は9.8より小さいです。小数の大小を比較する際には、整数部分と小数部分の数値を逐次比較する必要があります。9.11と9.8の場合、整数部分はどちらも9なので、小数部分で比較する必要があります。小数点後の最初の桁は1と8であり、明らかに1は8より小さいため、9.11は9.8より小さいです。", "name": "msg", "mtype": "dict", "id": "eb31b7de-dd6a-485f-adb9-1f7921a6f4bf", "extra": { "search_baidu": [ { "content": "大規模モデルの「知能」が疑問視される:9.11 vs 9...", "icon": "https://appbuilder.bj.bcebos.com/baidu-search-rag-pro/icon/souhu.ico", "url": "https://m.sohu.com/a/793754123_121924584/", "ref_id": "2", "site_name": "搜狐网", "title": "大規模モデルの「知能」が疑問視される:9.11 vs 9.8の比較がAIの理解能力を明らかにする..." }, { "content": "究極|9.11は9.8より大きい?大規模モデルはなぜ...", "icon": "https://appbuilder.bj.bcebos.com/baidu-search-rag-pro/icon/tencent.svg.png", "url": "https://new.qq.com/rain/a/20240717A07JLV00", "ref_id": "4", "site_name": "腾讯网", "title": "究極|9.11は9.8より大きい?大規模モデルはなぜ小学校の数学問題で集団的に..." }, ... ] }, "token_usage": { "completion_tokens": 77, "prompt_tokens": 2008, "total_tokens": 2085 } } ``` ### 3. AIネイティブアプリケーションの呼び出し - 例のアプリケーションは:[ラップメンター](https://appbuilder.baidu.com/s/3qfjXy7k)です。このリンクをクリックしてウェブページで試してみてください。 #### コード例 ```python import appbuilder import os # 環境変数にTOKENを設定します。以下のTOKENはアクセスとQPSが制限された試用TOKENです。正式な使用には個人のTOKENに置き換えてください。 os.environ["APPBUILDER_TOKEN"] = "your api key" # AppBuilderのウェブページからアプリケーションIDを取得し、以下にラップメンターのアプリケーションIDを入力します。 app_id = "4678492a-5864-472e-810a-654538d3503c" app_builder_client = appbuilder.AppBuilderClient(app_id) conversation_id = app_builder_client.create_conversation() answer = app_builder_client.run(conversation_id, "「上班狼狈却又追逐梦想」をテーマにラップを作成してください。押韻を保ち、200文字以内にしてください。") print(answer.content.answer) ``` #### 回答表示 ```shell わかりました。「上班狼狈却又追逐梦想」をテーマに、簡単なラップを作成します。以下は簡単な例です。自分の感覚に合わせて調整してください。 イントロ: 朝九晚五、生活の重圧、 狼狈上班、しかし夢を追いかける、 毎日が新たな挑戦、 未来のために、私は前進する。 バース1: スーツを着て、ネクタイを締めて、 人混みに入って、名声を追い求める、 狼狈しても、決して諦めない、 心の中に、夢があるから。 フック: 上班狼狈、しかし決して諦めない、 夢を追いかける、それが私の心の灯、 前方を照らし、私を導く、 どんなに困難でも、私は最後まで頑張る。 この小曲は「上班狼狈却又追逐梦想」をテーマに、押韻を通じて上班族が生活の苦しさにもかかわらず、夢を抱いて前進する精神を表現しています。気に入っていただけると幸いです! ``` **AIネイティブアプリケーションのコード例については、[Cookbooks](./cookbooks/README.md)をご覧ください。以下のクックブックを優先的にお勧めします:** - 基本機能コンポーネント - [一般的なテキスト認識コンポーネント](/cookbooks/components/general_ocr.ipynb) - [基本コンポーネントのサービス指向デプロイメント](/cookbooks/components/agent_runtime.ipynb) - プロセスオーケストレーション - [Assistant SDK](/cookbooks/pipeline/assistant_function_call.ipynb) - エンドツーエンドアプリケーション - [エージェント](/cookbooks/agent_builder.ipynb) - [RAG](/cookbooks/end2end_application/rag/rag.ipynb) - [企業レベルのQ&Aシステム](/cookbooks/end2end_application/rag/qa_system_2_dialogue.ipynb) - 高度な実践 - [パブリッククラウドへのサービスデプロイメント](/cookbooks/advanced_application/cloud_deploy.ipynb) - [サービストレース](/cookbooks/appbuilder_trace/trace.ipynb) ## Baidu AI Cloud Qianfan AppBuilder SDKの機能全景
wechat
## ユーザードキュメント - [ホームページ](https://github.com/baidubce/app-builder/blob/master/docs/README.md) - クイックスタート: - 最初のAIネイティブアプリケーションを開始する: - [インストール](https://github.com/baidubce/app-builder/blob/master/docs/QuickStart/StartFirstAINativeApplication/install.md) - [クイックスタートガイド](https://github.com/baidubce/app-builder/blob/master/docs/QuickStart/StartFirstAINativeApplication/README.md) - 産業実践アプリケーション例: - [SDK使用例](https://github.com/baidubce/app-builder/blob/master/docs/QuickStart/ExamplesOfIndustrialPracticeApplications/README.md) - [現在SDKがサポートしているプログラミング言語](https://github.com/baidubce/app-builder/blob/master/docs/QuickStart/CurrentlySupportedProgrammingLanguages/README.md) - 基本: - モデル: - [モデルリストの取得](https://github.com/baidubce/app-builder/blob/master/docs/BasisModule/Model/get_model_list.md) - [コンポーネント](https://github.com/baidubce/app-builder/blob/master/docs/BasisModule/Components) - 監視: - [TRACE基本機能](https://github.com/baidubce/app-builder/blob/master/docs/BasisModule/Trace/basic.md) - [TRACE拡張機能](https://github.com/baidubce/app-builder/blob/master/docs/BasisModule/Trace/phoenix_method.md) - [Debug機能](https://github.com/baidubce/app-builder/blob/master/docs/BasisModule/Trace/Debug.md) - デプロイ: - [インタラクティブなフロントエンドデプロイ](https://github.com/baidubce/app-builder/blob/master/docs/BasisModule/Deployment/AgentChainlit.md) - [パブリッククラウドデプロイ](https://github.com/baidubce/app-builder/blob/master/docs/BasisModule/Deployment/cloud.md) - [API アクセス](https://github.com/baidubce/app-builder/blob/master/docs/BasisModule/Deployment/flask.md) - [AgentRuntime](https://github.com/baidubce/app-builder/blob/master/docs/BasisModule/Deployment/agentruntime.md) - [UserSession](https://github.com/baidubce/app-builder/blob/master/docs/BasisModule/Deployment/usersession.md) - プラットフォーム: - アプリケーション: - [AppBuilderClientコンポーネント](https://github.com/baidubce/app-builder/blob/master/docs/BasisModule/Platform/Application/appbuilder_client.md) - [AppBuilderで公開されたアプリケーションリストの取得](https://github.com/baidubce/app-builder/blob/master/docs/BasisModule/Platform/Application/get_app_list.md) - ナレッジベース: - [ナレッジベースコンポーネント](https://github.com/baidubce/app-builder/blob/master/docs/BasisModule/Platform/KnowledgeBase/knowledgebase.md) - カスタムコンポーネント: - [基本機能コンポーネント](https://github.com/baidubce/app-builder/blob/master/docs/BasisModule/Platform/CustomComponents/components.md) - アプリケーション: - エージェント: - [基本知識](https://github.com/baidubce/app-builder/blob/master/docs/Tools/DocPass/DocPass.md) - [公式コンポーネントの使用](https://github.com/baidubce/app-builder/blob/master/docs/Application/Agent/UseOfficialComponents/use_official_components.md) - [ToolCall](https://github.com/baidubce/app-builder/blob/master/docs/Application/Agent/ToolCall/tool_call.md) - [ToolChoice](https://github.com/baidubce/app-builder/blob/master/docs/Application/Agent/ToolChoice/tool_choice.md) - [非同期およびストリーミングを使用してクライアント呼び出しを加速する](https://github.com/baidubce/app-builder/blob/master/docs/Tools/DocPass/DocPass.md) - RAG: - [基本知識](https://github.com/baidubce/app-builder/blob/master/docs/Application/RAG/BasicKnowledge/rag.md) - [ナレッジベース管理](https://github.com/baidubce/app-builder/blob/master/docs/Application/RAG/DatasetManage/dataset_manage.md) - [Reference情報処理](https://github.com/baidubce/app-builder/blob/master/docs/Tools/DocPass/DocPass.md) - ワークフロー: - [基本知識](https://github.com/baidubce/app-builder/blob/master/docs/Tools/DocPass/DocPass.md) - [Workflowを使ってRAGアプリケーションをゼロから組み立てる](https://github.com/baidubce/app-builder/blob/master/docs/Tools/DocPass/DocPass.md) - [Workflowを使ってAgentアプリケーションをゼロから組み立てる](https://github.com/baidubce/app-builder/blob/master/docs/Tools/DocPass/DocPass.md) - 開発者ガイド: - [コードの貢献方法](https://github.com/baidubce/app-builder/blob/master/docs/DevelopGuide/HowToContributeCode/README.md) - [にじかいせっか](https://github.com/baidubce/app-builder/blob/master/docs/DevelopGuide/AdvancedDevelopment/README.md) - [バージョンアップログ](https://github.com/baidubce/app-builder/blob/master/docs/DevelopGuide/ChangeLog/changelog.md) - [エラーメッセージ](https://github.com/baidubce/app-builder/blob/master/docs/DevelopGuide/ErrorMessage/error_message.md) - [環境パラメータ](https://github.com/baidubce/app-builder/blob/master/docs/DevelopGuide/EnvironmentalParameters/env.md) ## オープンソースコミュニティと活動

AppBuilder-SDK WeChatグループQRコード

wechat
- [Github Issue](https://github.com/baidubce/app-builder/issues): インストール/使用の問題を提出し、バグを報告し、新機能を提案し、開発計画をコミュニケーションします。 - [Baidu AI Cloud Qianfan Community](https://cloud.baidu.com/qianfandev) ## ライセンス AppBuilder SDKはApache 2.0オープンソースプロトコルに従います。 ================================================ FILE: docs/Tools/DocPass/DocPass.md ================================================ # 文档更新中,敬请期待 ================================================ FILE: docs/Tools/JavaAPI/JavaAPI.md ================================================ # Java API Reference - [Java API](index.html) - [All API List](index-all.html) - [帮助文档](help-doc.html) ================================================ FILE: docs/Tools/JavaAPI/READEME.md ================================================ # Appbuilder-SDK Java 自动文档生成 ## 操作流程 - 完成SDK代码开发 - 依照google规范编写注释--仅需要对类和非私有方法进行注释 - 进入根目录的docs/Tools/JavaAPI目录下执行java_api_update.sh脚本 ## 脚本功能 - 依据注释自动生成文档,并将文档迁移到docs/API-Reference/Java目录下 ## 代码注释规范 ### 基本格式 Javadoc注释是用/**开始,用\*/结束的,位于类、方法或字段之前。例如 ```java /** * 这是一个用于演示的类。 */ public class Demo { } ``` ### 类和接口注释 对于类和接口,Javadoc注释应该解释其整体功能和用途,以及如何与其他类或接口交互 ```java /** * 这是一个计算工具类,提供静态方法来进行数学计算。 */ public class MathUtils { // ... } ``` ### 方法注释 每个公共和受保护的方法应该有Javadoc注释,说明方法的作用、参数、返回值以及可能抛出的异常。 - `@param` 用来描述参数 - `@return` 描述返回值(如果方法不返回任何内容,则不需要此标签) - `@throws` 或 `@exception` 描述可能抛出的异常 ```java /** * 计算两个整数的和。 * * @param a 第一个整数 * @param b 第二个整数 * @return 两个整数的和 */ public static int add(int a, int b) { return a + b; } ``` ### 字段注释 公共字段应有简短的注释说明其作用。如果字段的用途不是显而易见的,应该提供详细的描述。 ```java /** * 默认的错误消息。 */ public static final String DEFAULT_ERROR_MESSAGE = "An error occurred."; ``` ### 通用标签 除了上述特定标签外,Javadoc还支持以下一些通用标签: - `@see` 参考其他相关类、方法或文档 - `@since` 指明从哪个版本开始添加的 - `@version` 标明当前代码的版本 - `@deprecated` 指明方法或类不再推荐使用 ```java /** * @deprecated 由于安全问题,此方法从版本1.5开始不推荐使用。 */ @Deprecated public void oldMethod() { // ... } ``` ================================================ FILE: docs/Tools/JavaAPI/java_api_update.sh ================================================ #1、清除生成文档环境 cd ../../.. rm -rf java/doc rm -rf docs/API-Reference/Java/* # 2、生成Java API文档 cd java javadoc -d doc -sourcepath src/main/java -subpackages com.baidubce.appbuilder -exclude com.baidubce.appbuilder.base -encoding UTF-8 -charset UTF-8 -public # 3、迁移文档到docs目录,并删除java/doc目录 cd .. cp -r java/doc/* docs/API-Reference/Java rm -rf java/doc # 4、辅助Java API文档目录文档到docs目录 cp docs/Tools/JavaAPI/JavaAPI.md docs/API-Reference/Java ================================================ FILE: docs/Tools/MarkdownSh/markdown2rst.py ================================================ # The MIT License (MIT) # Copyright (c) 2016 Hitoruki Takagi # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # The above copyright notice and this permission notice shall be included in all # copies or substantial portions of the Software. #!/usr/bin/env python3 """ markdown to rst """ # -*- coding: utf-8 -*- from __future__ import print_function, unicode_literals import os import os.path import re import sys from argparse import ArgumentParser, Namespace from docutils import statemachine, nodes, io, utils from docutils.parsers import rst from docutils.core import ErrorString from docutils.utils import SafeString, column_width import mistune if sys.version_info < (3, ): from codecs import open as _open from urlparse import urlparse else: _open = open from urllib.parse import urlparse __version__ = '0.2.1' _is_sphinx = False prolog = '''\ .. role:: raw-html-m2r(raw) :format: html ''' # for command-line use parser = ArgumentParser() options = Namespace() parser.add_argument( 'input_file', nargs='*', help='files to convert to reST format') parser.add_argument( '--overwrite', action='store_true', default=False, help='overwrite output file without confirmaion') parser.add_argument( '--dry-run', action='store_true', default=False, help='print conversion result and not save output file') parser.add_argument( '--no-underscore-emphasis', action='store_true', default=False, help='do not use underscore (_) for emphasis') parser.add_argument( '--parse-relative-links', action='store_true', default=False, help='parse relative links into ref or doc directives') parser.add_argument( '--anonymous-references', action='store_true', default=False, help='use anonymous references in generated rst') parser.add_argument( '--disable-inline-math', action='store_true', default=False, help='disable parsing inline math') parser.add_argument( '--output_file', default=None, help='files to save reST file') def parse_options(): """parse_options""" parser.parse_known_args(namespace=options) class RestBlockGrammar(mistune.BlockGrammar): """RestBlockGrammar""" directive = re.compile( r'^( *\.\..*?)\n(?=\S)', re.DOTALL | re.MULTILINE, ) oneline_directive = re.compile( r'^( *\.\..*?)$', re.DOTALL | re.MULTILINE, ) rest_code_block = re.compile( r'^::\s*$', re.DOTALL | re.MULTILINE, ) class RestBlockLexer(mistune.BlockLexer): """RestBlockLexer""" grammar_class = RestBlockGrammar default_rules = [ 'directive', 'oneline_directive', 'rest_code_block', ] + mistune.BlockLexer.default_rules def parse_directive(self, m): """parse_directive""" self.tokens.append({ 'type': 'directive', 'text': m.group(1), }) def parse_oneline_directive(self, m): """parse_oneline_directive""" # reuse directive output self.tokens.append({ 'type': 'directive', 'text': m.group(1), }) def parse_rest_code_block(self, m): """parse_rest_code_block""" self.tokens.append({'type': 'rest_code_block', }) class RestInlineGrammar(mistune.InlineGrammar): """RestInlineGrammar""" image_link = re.compile( r'\[!\[(?P.*?)\]\((?P.*?)\).*?\]\((?P.*?)\)') rest_role = re.compile(r':.*?:`.*?`|`[^`]+`:.*?:') rest_link = re.compile(r'`[^`]*?`_') inline_math = re.compile(r'.*\$(.*)?\$') eol_literal_marker = re.compile(r'(\s+)?::\s*$') # add colon and space as special text text = re.compile(r'^[\s\S]+?(?=[\\[\s\S]+?)\1{2}(?!\1)') # _word_ or *word* emphasis = re.compile(r'^\b_((?:__|[^_])+?)_\b' # _word_ r'|' r'^\*(?P(?:\*\*|[^\*])+?)\*(?!\*)' # *word* ) def no_underscore_emphasis(self): """no_underscore_emphasis""" self.double_emphasis = re.compile( r'^\*{2}(?P[\s\S]+?)\*{2}(?!\*)' # **word** ) self.emphasis = re.compile( r'^\*(?P(?:\*\*|[^\*])+?)\*(?!\*)' # *word* ) class RestInlineLexer(mistune.InlineLexer): """RestInlineLexer""" grammar_class = RestInlineGrammar default_rules = [ 'image_link', 'rest_role', 'rest_link', 'eol_literal_marker', ] + mistune.InlineLexer.default_rules def __init__(self, *args, **kwargs): no_underscore_emphasis = kwargs.pop('no_underscore_emphasis', False) disable_inline_math = kwargs.pop('disable_inline_math', False) super(RestInlineLexer, self).__init__(*args, **kwargs) if not _is_sphinx: parse_options() if no_underscore_emphasis or getattr(options, 'no_underscore_emphasis', False): self.rules.no_underscore_emphasis() inline_maths = 'inline_math' in self.default_rules if disable_inline_math or getattr(options, 'disable_inline_math', False): if inline_maths: self.default_rules.remove('inline_math') elif not inline_maths: self.default_rules.insert(0, 'inline_math') def output_double_emphasis(self, m): """output_double_emphasis""" # may include code span text = self.output(m.group('text')) return self.renderer.double_emphasis(text) def output_emphasis(self, m): """output_emphasis""" # may include code span text = self.output(m.group('text') or m.group(1)) return self.renderer.emphasis(text) def output_image_link(self, m): """Pass through rest role.""" return self.renderer.image_link( m.group('url'), m.group('target'), m.group('alt')) def output_rest_role(self, m): """Pass through rest role.""" return self.renderer.rest_role(m.group(0)) def output_rest_link(self, m): """Pass through rest link.""" return self.renderer.rest_link(m.group(0)) def output_inline_math(self, m): """Pass through rest link.""" return self.renderer.inline_math(m.group(0)) def output_eol_literal_marker(self, m): """Pass through rest link.""" marker = ':' if m.group(1) is None else '' return self.renderer.eol_literal_marker(marker) class RestRenderer(mistune.Renderer): """RestRenderer""" _include_raw_html = False list_indent_re = re.compile(r'^(\s*(#\.|\*)\s)') indent = ' ' * 3 list_marker = '{#__rest_list_mark__#}' hmarks = { 1: '=', 2: '-', 3: '^', 4: '~', 5: '"', 6: '#', } def __init__(self, *args, **kwargs): self.parse_relative_links = kwargs.pop('parse_relative_links', False) self.anonymous_references = kwargs.pop('anonymous_references', False) super(RestRenderer, self).__init__(*args, **kwargs) if not _is_sphinx: parse_options() if getattr(options, 'parse_relative_links', False): self.parse_relative_links = options.parse_relative_links if getattr(options, 'anonymous_references', False): self.anonymous_references = options.anonymous_references def _indent_block(self, block): return '\n'.join(self.indent + line if line else '' for line in block.splitlines()) def _raw_html(self, html): self._include_raw_html = True return '\ :raw-html-m2r:`{}`\ '.format(html) def block_code(self, code, lang=None): """block_code""" if lang == 'math': first_line = '\n.. math::\n\n' elif lang: first_line = '\n.. code-block:: {}\n\n'.format(lang) elif _is_sphinx: first_line = '\n.. code-block:: guess\n\n' else: first_line = '\n.. code-block::\n\n' return first_line + self._indent_block(code) + '\n' def block_quote(self, text): """block_quote""" # text includes some empty line return '\n..\n\n{}\n\n'.format(self._indent_block(text.strip('\n'))) def block_html(self, html): """Rendering block level pure html content. :param html: text content of the html snippet. """ return '\n\n.. raw:: html\n\n' + self._indent_block(html) + '\n\n' def header(self, text, level, raw=None): """Rendering header/heading tags like ``

`` ``

``. :param text: rendered text content for the header. :param level: a number for the header level, for example: 1. :param raw: raw text content of the header. """ return '\n{0}\n{1}\n'.format(text, self.hmarks[level] * column_width(text)) def hrule(self): """Rendering method for ``
`` tag.""" return '\n----\n' def list(self, body, ordered=True): """Rendering list tags like ``
    `` and ``
      ``. :param body: body contents of the list. :param ordered: whether this list is ordered or not. """ mark = '#. ' if ordered else '* ' lines = body.splitlines() for i, line in enumerate(lines): if line and not line.startswith(self.list_marker): lines[i] = ' ' * len(mark) + line return '\n{}\n'.format('\n'.join(lines)).replace(self.list_marker, mark) def list_item(self, text): """Rendering list item snippet. Like ``
    1. ``.""" return '\n' + self.list_marker + text def paragraph(self, text): """Rendering paragraph tags. Like ``

      ``.""" return '\n' + text + '\n' def table(self, header, body): """Rendering table element. Wrap header and body in it. :param header: header part of the table. :param body: body part of the table. """ table = '\n.. list-table::\n' if header and not header.isspace(): table = (table + self.indent + ':header-rows: 1\n\n' + self._indent_block(header) + '\n') else: table = table + '\n' table = table + self._indent_block(body) + '\n\n' return table def table_row(self, content): """Rendering a table row. Like ````. :param content: content of current table row. """ contents = content.splitlines() if not contents: return '' clist = ['* ' + contents[0]] if len(contents) > 1: for c in contents[1:]: clist.append(' ' + c) return '\n'.join(clist) + '\n' def table_cell(self, content, **flags): """Rendering a table cell. Like ```` ````. :param content: content of current table cell. :param header: whether this is header or not. :param align: align of current table cell. """ return '- ' + content + '\n' def double_emphasis(self, text): """Rendering **strong** text. :param text: text content for emphasis. """ return '\ **{}**\ '.format(text) def emphasis(self, text): """Rendering *emphasis* text. :param text: text content for emphasis. """ return '\ *{}*\ '.format(text) def codespan(self, text): """Rendering inline `code` text. :param text: text content for inline code. """ if '``' not in text: return '\ ``{}``\ '.format(text) else: # actually, docutils split spaces in literal return self._raw_html('' '{}' ''.format( text.replace('`', '`'))) def linebreak(self): """Rendering line break like ``
      ``.""" if self.options.get('use_xhtml'): return self._raw_html('
      ') + '\n' return self._raw_html('
      ') + '\n' def strikethrough(self, text): """Rendering ~~strikethrough~~ text. :param text: text content for strikethrough. """ return self._raw_html('{}'.format(text)) def text(self, text): """Rendering unformatted text. :param text: text content. """ return text def autolink(self, link, is_email=False): """Rendering a given link or email address. :param link: link content or email address. :param is_email: whether this is an email or not. """ return link def link(self, link, title, text): """Rendering a given link with content and title. :param link: href link for ```` tag. :param title: title content for `title` attribute. :param text: text content for description. """ if self.anonymous_references: underscore = '__' else: underscore = '_' if title: return self._raw_html( '{text}'.format( link=link, title=title, text=text)) if not self.parse_relative_links: return '\ `{text} <{target}>`{underscore}\ '.format( target=link, text=text, underscore=underscore) else: url_info = urlparse(link) if url_info.scheme: return '\ `{text} <{target}>`{underscore}\ '.format( target=link, text=text, underscore=underscore) else: link_type = 'doc' anchor = url_info.fragment if url_info.fragment: if url_info.path: # Can't link to anchors via doc directive. anchor = '' else: # Example: [text](#anchor) link_type = 'ref' doc_link = '{doc_name}{anchor}'.format( # splittext approach works whether or not path is set. It # will return an empty string if unset, which leads to # anchor only ref. doc_name=os.path.splitext(url_info.path)[0], anchor=anchor) return '\ :{link_type}:`{text} <{doc_link}>`\ '.format( link_type=link_type, doc_link=doc_link, text=text) def image(self, src, title, text): """Rendering a image with title and text. :param src: source link of the image. :param title: title text of the image. :param text: alt text of the image. """ # rst does not support title option # and I couldn't find title attribute in HTML standard return '\n'.join([ '', '.. image:: {}'.format(src), ' :target: {}'.format(src), ' :alt: {}'.format(text), '', ]) def inline_html(self, html): """Rendering span level pure html content. :param html: text content of the html snippet. """ return self._raw_html(html) def newline(self): """Rendering newline element.""" return '' def footnote_ref(self, key, index): """Rendering the ref anchor of a footnote. :param key: identity key for the footnote. :param index: the index count of current footnote. """ return '\ [#fn-{}]_\ '.format(key) def footnote_item(self, key, text): """Rendering a footnote item. :param key: identity key for the footnote. :param text: text content of the footnote. """ return '.. [#fn-{0}] {1}\n'.format(key, text.strip()) def footnotes(self, text): """Wrapper for all footnotes. :param text: contents of all footnotes. """ if text: return '\n\n' + text else: return '' """Below outputs are for rst.""" def image_link(self, url, target, alt): """image_link""" return '\n'.join([ '', '.. image:: {}'.format(url), ' :target: {}'.format(target), ' :alt: {}'.format(alt), '', ]) def rest_role(self, text): """rest_role""" return text def rest_link(self, text): """rest_link""" return text def inline_math(self, math): """Extension of recommonmark""" return re.sub(r'\$(.*?)\$', lambda x: '\ :math:`{}`\ '.format(x.group(1)), math) def eol_literal_marker(self, marker): """Extension of recommonmark""" return marker def directive(self, text): """directive""" return '\n' + text + '\n' def rest_code_block(self): """rest_code_block""" return '\n\n' class M2R(mistune.Markdown): """M2R""" def __init__(self, renderer=None, inline=RestInlineLexer, block=RestBlockLexer, **kwargs): if renderer is None: renderer = RestRenderer(**kwargs) super(M2R, self).__init__( renderer, inline=inline, block=block, **kwargs) def parse(self, text): """parse""" output = super(M2R, self).parse(text) return self.post_process(output) def output_directive(self): """output_directive""" return self.renderer.directive(self.token['text']) def output_rest_code_block(self): """output_rest_code_block""" return self.renderer.rest_code_block() def post_process(self, text): """post_process""" output = (text.replace('\\ \n', '\n').replace('\n\\ ', '\n') .replace(' \\ ', ' ').replace('\\ ', ' ') .replace('\\ .', '.')) if self.renderer._include_raw_html: return prolog + output else: return output class M2RParser(rst.Parser, object): """M2RParser""" # Explicitly tell supported formats to sphinx supported = ('markdown', 'md', 'mkd') def parse(self, inputstrings, document): """parse""" if isinstance(inputstrings, statemachine.StringList): inputstring = '\n'.join(inputstrings) else: inputstring = inputstrings config = document.settings.env.config converter = M2R(no_underscore_emphasis=config.no_underscore_emphasis, parse_relative_links=config.m2r_parse_relative_links, anonymous_references=config.m2r_anonymous_references, disable_inline_math=config.m2r_disable_inline_math) super(M2RParser, self).parse(converter(inputstring), document) class MdInclude(rst.Directive): """Directive class to include markdown in sphinx. Load a file and convert it to rst and insert as a node. Currently directive-specific options are not implemented. """ required_arguments = 1 optional_arguments = 0 option_spec = { 'start-line': int, 'end-line': int, } def run(self): """Most of this method is from ``docutils.parser.rst.Directive``. docutils version: 0.12 """ if not self.state.document.settings.file_insertion_enabled: raise self.warning('"%s" directive disabled.' % self.name) source = self.state_machine.input_lines.source( self.lineno - self.state_machine.input_offset - 1) source_dir = os.path.dirname(os.path.abspath(source)) path = rst.directives.path(self.arguments[0]) path = os.path.normpath(os.path.join(source_dir, path)) path = utils.relative_path(None, path) path = nodes.reprunicode(path) # get options (currently not use directive-specific options) encoding = self.options.get( 'encoding', self.state.document.settings.input_encoding) e_handler = self.state.document.settings.input_encoding_error_handler tab_width = self.options.get('tab-width', self.state.document.settings.tab_width) # open the including file try: self.state.document.settings.record_dependencies.add(path) include_file = io.FileInput( source_path=path, encoding=encoding, error_handler=e_handler) except UnicodeEncodeError as error: raise self.severe('Problems with "%s" directive path:\n' 'Cannot encode input file path "%s" ' '(wrong locale?).' % (self.name, SafeString(path))) except IOError as error: raise self.severe('Problems with "%s" directive path:\n%s.' % (self.name, ErrorString(error))) # read from the file startline = self.options.get('start-line', None) endline = self.options.get('end-line', None) try: if startline or (endline is not None): lines = include_file.readlines() rawtext = ''.join(lines[startline:endline]) else: rawtext = include_file.read() except UnicodeError as error: raise self.severe('Problem with "%s" directive:\n%s' % (self.name, ErrorString(error))) config = self.state.document.settings.env.config converter = M2R(no_underscore_emphasis=config.no_underscore_emphasis, parse_relative_links=config.m2r_parse_relative_links, anonymous_references=config.m2r_anonymous_references, disable_inline_math=config.m2r_disable_inline_math) include_lines = statemachine.string2lines( converter(rawtext), tab_width, convert_whitespace=True) self.state_machine.insert_input(include_lines, path) return [] def setup(app): """When used for sphinx extension.""" global _is_sphinx _is_sphinx = True app.add_config_value('no_underscore_emphasis', False, 'env') app.add_config_value('m2r_parse_relative_links', False, 'env') app.add_config_value('m2r_anonymous_references', False, 'env') app.add_config_value('m2r_disable_inline_math', False, 'env') app.add_source_parser('.md', M2RParser) app.add_directive('mdinclude', MdInclude) metadata = dict( version=__version__, parallel_read_safe=True, parallel_write_safe=True, ) return metadata def convert(text, **kwargs): """convert""" return M2R(**kwargs)(text) def parse_from_file(file, encoding='utf-8', **kwargs): """parse_from_file""" if not os.path.exists(file): raise OSError('No such file exists: {}'.format(file)) with _open(file, encoding=encoding) as f: src = f.read() output = convert(src, **kwargs) return output def save_to_file(target, src, encoding='utf-8', **kwargs): """save_to_file""" if not options.overwrite and os.path.exists(target): confirm = input('{} already exists. overwrite it? [y/n]: '.format( target)) if confirm.upper() not in ('Y', 'YES'): print('skip {}'.format(target)) return with _open(target, 'w', encoding=encoding) as f: f.write(src) def main(): """main""" parse_options() # parse cli options if not options.input_file: parser.print_help() parser.exit(0) for file in options.input_file: output = parse_from_file(file) if options.dry_run: print(output) else: save_to_file(options.output_file, output) if __name__ == '__main__': main() ================================================ FILE: docs/Tools/MarkdownSh/markdown_parse.py ================================================ """ markdown 文件解析工具 使用示例: python markdown_parse.py "your_file_path" 响应结果: parse file your_file_path/README.md result: xxxx check your_file_path/README.md success/error: xxxx 如果出现 error,说明 markdown 内容缺失 简介、基本用法或者参数说明 """ import json import os import re import sys arguments = sys.argv sdk_code_dict = { "animal_recognize": "animal_recognize", "asr": "asr", "dish_recognize": "dish_recognize", "doc_crop_enhance": "doc_crop_enhance", "doc_parser": "doc_parser", "doc_splitter": "doc_splitter", "embeddings": "embeddings", "excel2figure": "excel2figure", "extract_table": "extract_table", "nl2sql": "nl2sql", "select_table": "select_table", "general_ocr": "general_ocr", "handwrite_ocr": "handwrite_ocr", "image_understand": "image_understand", "landmark_recognize": "landmark_recognize", "dialog_summary": "dialog_summary", "is_complex_query": "is_complex_query", "mrc": "mrc", "nl2pandas": "nl2pandas", "oral_query_generation": "oral_query_generation", "playground": "playground", "qa_pair_mining": "qa_pair_mining", "query_decomposition": "query_decomposition", "query_rewrite": "query_rewrite", "similar_question": "similar_question", "style_rewrite": "style_rewrite", "style_writing": "style_writing", "tag_extraction": "tag_extraction", "matching": "matching", "mix_card_ocr": "mix_card_ocr", "object_recognize": "object_recognize", "plant_recognize": "plant_recognize", "qrcode_ocr": "qrcode_ocr", "rag_with_baidu_search": "web_search", "bes": "retriever", "table_ocr": "table_ocr", "text_to_image": "image", "translate": "translate", "tts": "tts", "tts_high": "tts_high", "tts_audio": "tts_audio", "code_interpreter": "code_interpreter", "web_pilot": "web_pilot", "wolfram_alpha": "wolfram_alpha", "arxiv": "arxiv", "product_query": "product_query", "flight_query": "flight_query", "query_express_package": "query_express_package", "bing_image_search": "bing_image_search", "news_get": "news_get", "weather_query": "weather_query", "video_get": "video_get", "baidu_vdb": "baidu_vdb" } # 循环中的数据 sdk_detail_sqls = [] sdk_component_sqls = [] sdk_code_sqls = [] def parse_markdown(markdown): # 初始化结果字典和当前处理的section sections = {} current_section = None code_block = False code_lang = None code_content = "" section_content = "" need_append_content = False # 按行遍历markdown内容 for line in markdown.split('\n'): # 检查是否为一级标题 if line.startswith('# ') and 'title' not in sections: sections['title'] = line[2:].strip() sections['name'] = re.sub(r'[\((][^\))]*[\))]', '', sections['title']).strip() # 检查是否为二级标题 if line.startswith('## '): # 如果当前有正在处理的section,将其存入字典 if current_section and current_section not in sections: sections[current_section] = section_content.strip() # 更新当前section名称和重置section内容 current_section = line[3:].strip() section_content = "" need_append_content = False if current_section == '简介': sections['remark'] = '' # 检查是否为代码块开始 elif line.startswith('```') and current_section == '基本用法' and not code_block: # 如果紧接着下一行是代码语言,则提取它 code_lang = line[3:].strip() if code_lang is not None and len(code_lang) > 0: code_block = True continue # 检查是否为代码块结束 elif line.startswith('```') and current_section == '基本用法' and code_block: code_block = False # 如果提取到了代码语言,将代码内容存入字典 if code_lang: if current_section not in sections: sections[current_section] = {} sections[current_section][code_lang] = code_content.strip() code_lang = None code_content = "" continue # 如果在代码块内,则累加代码内容 if code_block: code_content += line + '\n' # 否则,累加section内容 else: # 判断当前section 是否是简介 if current_section == '简介' and not line.startswith('##') and not need_append_content: sections['remark'] = sections['remark'] + line if line.startswith('###'): need_append_content = True if need_append_content: section_content += line + '\n' # 处理最后一个section if current_section: sections[current_section] = section_content.strip() return sections def read_markdown(file_path): with open(file_path, 'r', encoding='utf-8') as file: markdown = file.read() return markdown def check_parse_result(result): msg_list = [] success = True json_data = json.loads(result) if "简介" not in json_data or ("简介" in json_data and len(json_data["简介"]) == 0): success = False msg_list.append("简介内容缺失") if "基本用法" not in json_data or ("基本用法" in json_data and len(json_data["基本用法"]) == 0): success = False msg_list.append("基本用法内容缺失") if "参数说明" not in json_data or ("参数说明" in json_data and len(json_data["参数说明"]) == 0): success = False msg_list.append("参数说明内容缺失") return success, ";".join(msg_list) def parse_file(file_path): if os.path.isfile(file_path): # 如果是文件,且为 markdown,解析文档 _, file_extension = os.path.splitext(file_path) if file_extension == '.md': markdown_content = read_markdown(file_path) parsed_content = parse_markdown(markdown_content) result = json.dumps(parsed_content, indent=2, ensure_ascii=False) print(f"parse file {file_path} result:\n {result}") success, _msg = check_parse_result(result) if success: print(f"check {file_path} success") match = re.search(r'/(\w+)/README\.md$', file_path) dir_name = match.group(1) introduce = parsed_content.get('简介').replace('\n', r'\n').replace('\'', '\'\'') interface_doc = parsed_content.get('参数说明').replace('\n', r'\n').replace('\'', '\'\'') sdk_code = sdk_code_dict.get(dir_name) if sdk_code is not None: sdk_detail_sql = f"insert into sdk_detail(sdk_code, introduce, interface_doc, deploy_package, title) values('{sdk_code}','{introduce}','{interface_doc}',null,'{parsed_content.get('title')}') on conflict(sdk_code) do update set introduce='{introduce}',interface_doc='{interface_doc}',title='{parsed_content.get('title')}';" sdk_detail_sqls.append(sdk_detail_sql) remark = parsed_content.get('remark').replace('\n', '') sdk_component_sql = f"update sdk_tool set name = '{parsed_content.get('name')}',remark='{remark}' where sdk_code = '{sdk_code}';" sdk_component_sqls.append(sdk_component_sql) for key, value in parsed_content.get('基本用法').items(): code = value.replace('\n', r'\n').replace('\'', '\'\'') sdk_code_sql = f"insert into sdk_code_demo(sdk_code, language, code_demo) values('{sdk_code}','{key}','{code}') on conflict(sdk_code,language) do update set code_demo='{code}';" sdk_code_sqls.append(sdk_code_sql) if not success: print(f"check {file_path} error: {_msg}") return else: # 获取目标目录下的所有文件和子目录 entries = os.listdir(file_path) for entry in entries: # 构建完整路径 child_path = os.path.join(file_path, entry) parse_file(child_path) parse_file(arguments[1]) # 打开文件以追加模式 ('a') # with open('data.sql', 'a') as file: # # 循环写入数据 # for line in sdk_detail_sqls: # file.write(line + '\n') # for line in sdk_code_sqls: # file.write(line + '\n') # for line in sdk_component_sqls: # file.write(line + '\n') ================================================ FILE: docs/Tools/SphinxSh/Makefile ================================================ # Minimal makefile for Sphinx documentation # # You can set these variables from the command line, and also # from the environment for the first two. SPHINXOPTS ?= SPHINXBUILD ?= sphinx-build SOURCEDIR = source BUILDDIR = build # Put it first so that "make" without argument is like "make help". help: @$(SPHINXBUILD) -M help "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O) .PHONY: help Makefile # Catch-all target: route all unknown targets to Sphinx using the new # "make mode" option. $(O) is meant as a shortcut for $(SPHINXOPTS). %: Makefile @$(SPHINXBUILD) -M $@ "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O) ================================================ FILE: docs/Tools/SphinxSh/PythonAPI.md ================================================ # Python API Reference - [Python API](appbuilder.md) - [Assistant API](appbuilder.core.assistant.md) - [Components API](appbuilder.core.components.md) - [Console API](appbuilder.core.console.md) ================================================ FILE: docs/Tools/SphinxSh/READEME.md ================================================ # Appbuilder-SDK Python 自动文档生成 ## 操作流程 - 完成SDK代码开发 - 依照google规范编写注释--仅需要对类和非私有方法进行注释 - 进入根目录的docs/Tools/SphinxSh目录下执行update_doc.sh脚本 - 执行成功后,在docs/Tools/SphinxSh/build/markdown目录下查看生成的文档是否无误 - 迁移所有生成的文档到docs/API-Reference/Python目录下 ## 脚本功能 - 依据注释自动生成文档,并将文档迁移到docs/API-Reference/Python目录下 - 将组件README.md文件按照目录格式迁移到BasisModule/Components目录下,为mkdocs生成文档提供基础链接 ## 代码注释规范 - 注释使用google规范 ### object类注释 ```python class AppBuilderClient(Component): r""" AppBuilderClient 组件支持调用在[百度智能云千帆AppBuilder](https://cloud.baidu.com/product/AppBuilder)平台上 构建并发布的智能体应用,具体包括创建会话、上传文档、运行对话等。 Examples: .. code-block:: python import appbuilder # 请前往千帆AppBuilder官网创建密钥,流程详见:https://cloud.baidu.com/doc/AppBuilder/s/Olq6grrt6#1%E3%80%81%E5%88%9B%E5%BB%BA%E5%AF%86%E9%92%A5 os.environ["APPBUILDER_TOKEN"] = '...' # 可在Console 应用页面获取 app_id = "app_id" client = appbuilder.AppBuilderClient("app_id") conversation_id = client.create_conversation() file_id = client.upload_local_file(conversation_id, "/path/to/file") message = client.run(conversation_id, "今天你好吗?") # 打印对话结果 print(message.content) """ ``` - 注意 - 注释必须使用 Examples:之后必须存在一行空行,.. code-block:: python之后也必须要有一行空行 - code-block前为两点(..)之后为两个冒号(::) - 方法的示例注释与此规范相同 ### 函数注释 - 私有函数如_recognize_w_post_process等无需按照规范注释函数 ```python @components_run_stream_trace def tool_eval( self, name: str, streaming: bool, origin_query: str, **kwargs, ) -> Union[Generator[str, None, None], str]: """ 执行工具函数,通过调用底层接口进行动物识别。 Args: name (str): 工具名 streaming (bool): 是否流式返回结果,True 表示流式返回,False 表示一次性返回 origin_query (str): 用户原始查询字符串 **kwargs: 工具调用的额外关键字参数 Returns: Union[Generator[str, None, None], str]: 动物识别结果。如果 streaming 为 True,则返回一个生成器,可以逐个返回识别结果; 如果 streaming 为 False,则返回一个字符串,包含识别出的动物类别和相应的置信度信息。 """ ``` ### google风格指南与规范示例 - Google详情见 [Google注释风格指南](https://google.github.io/styleguide/pyguide.html) ```python class GoogleStyle: '''Google注释风格 用 ``缩进`` 分隔, 适用于倾向水平,短而简单的文档 Attributes: dividend (int or float): 被除数 name (:obj:`str`, optional): 该类的命名 ''' def __init__(self, dividend, name='GoogleStyle'): '''初始化''' self.dividend = dividend self.name = name def divide(self, divisor): '''除法 Google注释风格的函数, 类型主要有Args、Returns、Raises、Examples Args: divisor (int):除数 Returns: 除法结果 Raises: ZeroDivisionError: division by zero Examples: .. code-block:: python # 实例代码 References: 除法_百度百科 https://baike.baidu.com/item/%E9%99%A4%E6%B3%95/6280598 ''' try: return self.dividend / divisor except ZeroDivisionError as e: return e ``` ================================================ FILE: docs/Tools/SphinxSh/appbuilder.core.rst ================================================ appbuilder.core package ======================= Subpackages ----------- .. toctree:: :maxdepth: 2 appbuilder.core.assistant appbuilder.core.components appbuilder.core.console Submodules ---------- appbuilder.core.agent module ---------------------------- .. automodule:: appbuilder.core.agent :members: :undoc-members: :show-inheritance: appbuilder.core.message module ------------------------------ .. automodule:: appbuilder.core.message :members: :undoc-members: :show-inheritance: appbuilder.core.component module ------------------------------ .. automodule:: appbuilder.core.component :members: :undoc-members: :show-inheritance: ================================================ FILE: docs/Tools/SphinxSh/get_components_md.py ================================================ import os def find_readme_files(base_path): readme_files = [] for root, dirs, files in os.walk(base_path): for file in files: if file.lower() == "readme.md": readme_files.append(os.path.join(root, file)) return readme_files def extract_first_line(readme_path): try: with open(readme_path, 'r', encoding='utf-8') as file: first_line = file.readline().strip() if first_line.startswith('#'): first_line = first_line[1:].strip() return first_line except Exception as e: print(f"Error reading {readme_path}: {str(e)}") return None def update_mkdocs_yml(results, mkdocs_path='../../../mkdocs.yml'): try: with open(mkdocs_path, 'r', encoding='utf-8') as file: lines = file.readlines() # 查找 " - 组件:" 行的索引 start_index = -1 end_index = -1 for i, line in enumerate(lines): if line.strip() == '- 组件:': start_index = i elif line.strip() == '- 监控:': end_index = i break if start_index == -1 or end_index == -1: print("未找到 '- 组件:' 或 '- 监控:' 行") return # 删除两标记之间的内容 del lines[start_index + 1:end_index] # 在找到的行后面插入新的结果 for result in reversed(results): lines.insert(start_index + 1, f" - {result}\n") # 写回文件 with open(mkdocs_path, 'w', encoding='utf-8') as file: file.writelines(lines) print("mkdocs.yml 更新成功") except Exception as e: print(f"Error updating {mkdocs_path}: {str(e)}") def main(): base_path = '../../BasisModule/Components' # 当前目录 readme_files = find_readme_files(base_path) results = [] for readme_path in readme_files: first_line = extract_first_line(readme_path) if first_line: relative_path = os.path.relpath(readme_path, start=base_path) result = f"{first_line}: BasisModule/Components/{relative_path.replace(os.sep, '/')}" results.append(result) # 更新 mkdocs.yml 文件 update_mkdocs_yml(results) if __name__ == "__main__": main() ================================================ FILE: docs/Tools/SphinxSh/make.bat ================================================ @ECHO OFF pushd %~dp0 REM Command file for Sphinx documentation if "%SPHINXBUILD%" == "" ( set SPHINXBUILD=sphinx-build ) set SOURCEDIR=source set BUILDDIR=build %SPHINXBUILD% >NUL 2>NUL if errorlevel 9009 ( echo. echo.The 'sphinx-build' command was not found. Make sure you have Sphinx echo.installed, then set the SPHINXBUILD environment variable to point echo.to the full path of the 'sphinx-build' executable. Alternatively you echo.may add the Sphinx directory to PATH. echo. echo.If you don't have Sphinx installed, grab it from echo.https://www.sphinx-doc.org/ exit /b 1 ) if "%1" == "" goto help %SPHINXBUILD% -M %1 %SOURCEDIR% %BUILDDIR% %SPHINXOPTS% %O% goto end :help %SPHINXBUILD% -M help %SOURCEDIR% %BUILDDIR% %SPHINXOPTS% %O% :end popd ================================================ FILE: docs/Tools/SphinxSh/requirements.txt ================================================ sphinx sphinx-markdown-builder sphinx_rtd_theme ================================================ FILE: docs/Tools/SphinxSh/source/conf.py ================================================ # Configuration file for the Sphinx documentation builder. # # For the full list of built-in configuration values, see the documentation: # https://www.sphinx-doc.org/en/master/usage/configuration.html # -- Project information ----------------------------------------------------- # https://www.sphinx-doc.org/en/master/usage/configuration.html#project-information # 指定项目路径 import os import sys sys.path.insert(0, os.path.abspath('../../../appbuilder')) project = 'Appbuilder-SDK' copyright = '2024, baidubce' author = 'baidubce' release = '1.1.0' # -- General configuration --------------------------------------------------- # https://www.sphinx-doc.org/en/master/usage/configuration.html#general-configuration extensions = [ 'sphinx.ext.autodoc', 'sphinx.ext.napoleon' ] templates_path = ['_templates'] # 排除tests目录及其子文件 exclude_patterns = [] language = 'zh_CN' # -- Options for HTML output ------------------------------------------------- # https://www.sphinx-doc.org/en/master/usage/configuration.html#options-for-html-output html_theme = 'sphinx_rtd_theme' html_static_path = ['_static'] ================================================ FILE: docs/Tools/SphinxSh/source/index.rst ================================================ .. Appbuilder-SDK documentation master file, created by sphinx-quickstart on Fri Oct 11 14:36:19 2024. You can adapt this file completely to your liking, but it should at least contain the root `toctree` directive. Appbuilder-SDK documentation ============================ Add your content using ``reStructuredText`` syntax. See the `reStructuredText `_ documentation for details. .. toctree:: :maxdepth: 2 :caption: Contents: ================================================ FILE: docs/Tools/SphinxSh/update_doc.sh ================================================ echo "========================开始更新文档========================" # 1、注释@HTTPClient\.check_param装饰器 echo "================注释@HTTPClient.check_param装饰器===============" echo "当前路径:" pwd cd ../../.. find . -name "*.py" -exec sed -i '' 's/@HTTPClient\.check_param/# @HTTPClient.check_param/g' {} \; cd docs/Tools/SphinxSh echo "===============注释@HTTPClient.check_param装饰器完成==============" # 2、安装依赖 echo "=========================安装依赖=========================" echo "当前路径:" pwd python3 -m pip install -r requirements.txt echo "安装当前目录的Appbuilder-SDK:" cd ../../.. python3 -m pip uninstall appbuilder-sdk -y rm -rf dist python3 -u setup.py bdist_wheel python3 -m pip install dist/*.whl # 更新builde目录 rm -rf build # 检查appbuilder目录是否已存在 if [ -d "appbuilder" ]; then echo "Error: Directory 'appbuilder' already exists." exit 1 fi # 检查python目录是否存在,如果存在则重命名为appbuilder if [ -d "python" ]; then mv python appbuilder echo "Directory 'python' has been renamed to 'appbuilder'." else echo "Directory 'python' does not exist." find . -name "*.py" -exec sed -i '' 's/# @HTTPClient\.check_param/@HTTPClient.check_param/g' {} \; || { echo "恢复装饰器失败"; exit 1; } exit 1 fi cd docs/Tools/SphinxSh echo "=========================安装依赖=========================" # 3、删除 build 下的所有文件夹 echo "================删除 doc/build 下的所有文件夹================" echo "当前路径:" pwd echo "删除 build 下的所有文件夹及文件:" rm -r build/* echo "删除 build 下的所有文件夹及文件完成" echo "==============删除 doc/build 下的所有文件夹完成==============" # 4、删除 doc/source 下除index.rst的所有.rst文件 echo "==========删除doc/source下除index.rst的所有.rst文件==========" echo "当前路径:" pwd echo "删除 source 下除index.rst的所有.rst文件:" cd source find . -maxdepth 1 -type f -name '*.rst' ! -name 'index.rst' -exec rm {} \;|| { echo "删除 doc/source 下除index.rst的所有.rst文件失败"; exit 1; } cd .. echo "删除 source 下除index.rst的所有.rst文件完成" echo "=========删除doc/source下除index.rst的所有.rst文件完成=========" # 5、删除原有的 docs/sphinx_md 文件夹及其文件 echo "============删除原有的 docs/sphinx_md 文件夹及其文件============" echo "当前路径:" pwd rm -rf ../../API-Reference/Python/* echo "===========删除原有的 docs/sphinx_md 文件夹及其文件完成===========" # 6、在doc目录下下执行命令 sphinx-apidoc -o source ../appbuilder/ echo "=======执行命令 sphinx-apidoc -o source ../appbuilder/=======" echo "当前路径:" pwd sphinx-apidoc -o source ../../../appbuilder/ # 删除多余文档目录 rm ./source/appbuilder.tests.* rm ./source/appbuilder.utils.* rm ./source/appbuilder.core.assistant.type.rst cp ./appbuilder.core.rst ./source/appbuilder.core.rst cp update_rst.py source/ cd source python3 update_rst.py rm -rf update_rst.py cd .. echo "======执行命令 sphinx-apidoc -o source ../appbuilder/完成======" # 7、在doc目录下执行命令 make markdown && make html echo "==============在doc目录下执行命令 make markdown================" echo "当前路径:" pwd SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" DOC_DIR="$SCRIPT_DIR" cd "$DOC_DIR" || { echo "无法切换到 $DOC_DIR 目录"; exit 1; } echo "当前路径: $(pwd)" export PATH=/path/to/your/python:$PATH # 执行 make markdown make markdown || { echo "make markdown 命令失败"; exit 1; } # 迁移目录文档 cp PythonAPI.md build/markdown/ cp -r build/markdown/ ../../API-Reference/Python echo "=============在doc目录下执行命令 make markdown 完成==============" # 8、恢复装饰器 echo "========================恢复装饰器========================" cd ../../.. echo "当前路径:" pwd find . -name "*.py" -exec sed -i '' 's/# @HTTPClient\.check_param/@HTTPClient.check_param/g' {} \; || { echo "恢复装饰器失败"; exit 1; } cd docs/Tools/SphinxSh echo "========================恢复装饰器完成========================" # 9、清理多余文件 echo "========================清理多余文件========================" echo "当前路径:" pwd cd source find . -maxdepth 1 -type f -name '*.rst' ! -name 'index.rst' -exec rm {} \;|| { echo "删除 doc/source 下除index.rst的所有.rst文件失败"; exit 1; } cd .. echo "删除 doc/source 下除index.rst的所有.rst文件完成" rm -rf /build/doctrees/* cd ../../.. if [ -d "appbuilder" ]; then mv appbuilder python echo "Directory 'appbuilder' has been renamed to 'python'." else echo "Directory 'appbuilder' does not exist." exit 1 fi cd docs/Tools/SphinxSh echo "======================清理多余文件完成======================" # 10、拷贝组件README.md文件到docs/BasisModule/Components目录 echo "====拷贝组件README.md文件到docs/BasisModule/Components目录====" echo "当前路径:" pwd cd ../../.. cp -r python/core/components/* docs/BasisModule/Components cd docs/BasisModule/Components find . -type f -name "*.py" -exec rm {} + cd ../../Tools/SphinxSh # 运行mkdocs更改文件 python3 get_components_md.py # 更改API目录文件结构 python3 update_lib.py echo "====拷贝组件README.md文件到docs/BasisModule/Components目录完成====" echo "========================更新文档完成========================" ================================================ FILE: docs/Tools/SphinxSh/update_lib.py ================================================ import subprocess def mv_new_md(input_filename, output_filename): """ 将新生成的Markdown文件移动到目标位置并删除原文件。 Args: input_filename (str): 目标文件名。 output_filename (str): 新生成的Markdown文件名。 Returns: None """ command = ['mv', output_filename, input_filename] subprocess.run(command, check=True) command = ['rm', '-rf', output_filename] subprocess.run(command, check=True) def process_line_for_assistant(line): """ 处理一行文本以供助手使用。 Args: line (str): 要处理的文本行。 Returns: str or None: 如果行中包含'module'字段且不包含"subpackages"或"submodules",则返回处理后的行。 否则返回None表示应该删除该行。 说明: 1. 仅提取存在'module'字段且不包含"subpackages"或"submodules"的行,并返回格式处理之后的行。 2. 处理后的行格式为"- [模块名](链接)",其中模块名为文本行中最后一个点后的内容, 链接为原文本行中的链接部分。 3. 如果模块名在指定的模块列表中('assistants', 'files', 'messages', 'runs', 'threads'), 则返回处理后的行,否则返回None。 """ # 仅提取存在module字段且不包含"subpackages"或"submodules"的行,并返回格式处理之后的行 if 'module' in line.lower() and 'subpackages' not in line.lower() and 'submodules' not in line.lower(): open_module = ('assistants', 'files', 'messages', 'runs', 'threads') parts = line.split('](') new_name = parts[0].split(' module')[0].split('.')[-1] if new_name in open_module: return f"- [{new_name}]({parts[-1]}" else: return None else: # 如果行中没有"module",返回None表示应该删除该行 return None def process_line_for_components(line): """ 对给定的行进行组件处理。 Args: line (str): 需要处理的行。 Returns: str or None: 处理后的行。如果行中没有包含"module"字段,或者包含"subpackages"或"submodules",则返回None,表示应该删除该行。 """ # 仅提取存在module字段且不包含"subpackages"或"submodules"的行,并返回格式处理之后的行 if 'module' in line.lower() and 'subpackages' not in line.lower() and 'submodules' not in line.lower(): parts = line.split('](') new_names = parts[0].split(' module')[0].split('.') if len(new_names) == 5: return f"- [{new_names[-2]}]({parts[-1]}" else: if new_names[-3] == 'llms': return f"- [{new_names[-2]}--(LLM)]({parts[-1]}" elif new_names[-3] == 'retriever': return f"- [{new_names[-2]}--(retriever)]({parts[-1]}" elif new_names[-3] == 'gbi': return f"- [{new_names[-2]}--(GBI)]({parts[-1]}" else: # 如果行中没有"module",返回None表示应该删除该行 return None def process_line_for_console(line): """ 对给定行进行格式处理,并返回处理后的行。 Args: line (str): 需要处理的行文本。 Returns: str: 处理后的行文本,如果行应被删除则返回None。 说明: 该函数仅处理包含"module"字段且不包含"subpackages"或"submodules"的行。 对于包含"module"的行,会提取模块名并返回格式化后的Markdown链接。 如果模块名是"data_class",则直接返回None。 如果行中包含"(appbuilder.core.console.knowledge_base.md)",则返回固定的Markdown链接。 如果行中不包含"module",则返回None表示该行应被删除。 """ # 仅提取存在module字段且不包含"subpackages"或"submodules"的行,并返回格式处理之后的行 if 'module' in line.lower() and 'subpackages' not in line.lower() and 'submodules' not in line.lower(): parts = line.split('](') new_names = parts[0].split(' module')[0].split('.') if new_names[-1] == 'data_class': return None else: return f"- [{new_names[-1]}]({parts[-1]}" elif '(appbuilder.core.console.knowledge_base.md)' in line: return "- [knowledge_base](appbuilder.core.console.knowledge_base.md)" else: # 如果行中没有"module",返回None表示应该删除该行 return None def process_file_for_assistant(input_filename, output_filename): """ 为助手处理文件。 Args: input_filename (str): 输入文件名。 output_filename (str): 输出文件名。 Returns: None """ with open(input_filename, 'r') as file: lines = file.readlines() new_lines = [] for line in lines: new_line = process_line_for_assistant(line.strip()) if new_line: new_lines.append(new_line) with open(output_filename, 'w') as file: for line in new_lines: file.write(line + '\n') mv_new_md(input_filename, output_filename) def process_file_for_components(input_filename, output_filename): """ 从文件中读取文本行,处理每行文本以提取组件信息,并将结果写入到新的文件中。 Args: input_filename (str): 输入文件的路径。 output_filename (str): 输出文件的路径。 Returns: None """ with open(input_filename, 'r') as file: lines = file.readlines() new_lines = [] for line in lines: new_line = process_line_for_components(line.strip()) if new_line: new_lines.append(new_line) with open(output_filename, 'w') as file: for line in new_lines: file.write(line + '\n') mv_new_md(input_filename, output_filename) def process_file_for_console(input_filename, output_filename): """ 将文件内容处理后输出到另一个文件,并移动原文件。 Args: input_filename (str): 输入文件名。 output_filename (str): 输出文件名。 Returns: None """ with open(input_filename, 'r') as file: lines = file.readlines() new_lines = [] for line in lines: new_line = process_line_for_console(line.strip()) if new_line: new_lines.append(new_line) with open(output_filename, 'w') as file: for line in new_lines: file.write(line + '\n') mv_new_md(input_filename, output_filename) if __name__ == "__main__": # 处理Assistant.md文件 process_file_for_assistant("../../API-Reference/Python/appbuilder.core.assistant.md", "../../API-Reference/Python/new_appbuilder.core.assistant.md") # 处理Components.md文件 process_file_for_components("../../API-Reference/Python/appbuilder.core.components.md", "../../API-Reference/Python/new_appbuilder.core.components.md") # 处理console.md文件 process_file_for_console("../../API-Reference/Python/appbuilder.core.console.md", "../../API-Reference/Python/new_appbuilder.core.console.md") ================================================ FILE: docs/Tools/SphinxSh/update_rst.py ================================================ import os def process_rst_file(filepath): """ 处理rst文件,移除包含特定文本的行。 Args: filepath (str): rst文件的路径。 Returns: None 说明: 打开rst文件,读取文件内容到lines列表中。 遍历lines列表,根据条件移除包含特定文本的行, 这些特定文本包括'base'且'appbuilder.core'、'model'且'appbuilder.core'、 'appbuilder.core.utils'且'appbuilder.core'、'data_class'且'appbuilder.core'。 每次移除满足条件的行时,最多连续移除8行,防止移除过多内容。 将修改后的内容写回原文件。 """ with open(filepath, 'r', encoding='utf-8') as file: lines = file.readlines() new_lines = [] i = 0 while i < len(lines): if 'base' in lines[i] and 'appbuilder.core' in lines[i] and 'knowledge_base' not in lines[i]: i += min(8, len(lines) - i) elif 'model' in lines[i] and 'appbuilder.core' in lines[i]: i += min(8, len(lines) - i) elif 'appbuilder.core.utils' in lines[i]: i += min(8, len(lines) - i) elif 'data_class' in lines[i] and 'appbuilder.core' in lines[i]: i += min(8, len(lines) - i) elif 'basic' in lines[i] and 'appbuilder.core' in lines[i]: i += min(8, len(lines) - i) elif 'parse_rag_pro_response' in lines[i] and 'appbuilder.core' in lines[i]: i += min(8, len(lines) - i) elif 'Module contents' in lines[i]: i += min(8, len(lines) - i) else: new_lines.append(lines[i]) i += 1 # Write the modified content back to the file with open(filepath, 'w', encoding='utf-8') as file: file.writelines(new_lines) def main(): """ 遍历当前目录下的所有.rst文件 Args: 无参数 Returns: 无返回值 """ # Traverse the current directory for all .rst files for root, dirs, files in os.walk('.'): for file in files: if file.endswith('.rst'): filepath = os.path.join(root, file) print(f'Processing {filepath}') process_rst_file(filepath) if __name__ == "__main__": main() ================================================ FILE: go/appbuilder/agent_builder.go ================================================ // Copyright (c) 2024 Baidu, Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package appbuilder import ( "bufio" "bytes" "encoding/json" "errors" "fmt" "io" "mime/multipart" "net/http" "os" "path/filepath" "time" ) // Deprecated: 请使用AppBuilderClient 代替 AgentBuilder func NewAgentBuilder(appID string, config *SDKConfig) (*AgentBuilder, error) { if len(appID) == 0 { return nil, errors.New("appID is empty") } if config == nil { return nil, errors.New("config is nil") } client := config.HTTPClient if client == nil { client = &http.Client{Timeout: 1800 * time.Second} } return &AgentBuilder{appID: appID, sdkConfig: config, client: client}, nil } type AgentBuilder struct { appID string sdkConfig *SDKConfig client HTTPClient } func (t *AgentBuilder) CreateConversation() (string, error) { request := http.Request{} header := t.sdkConfig.AuthHeaderV2() serviceURL, err := t.sdkConfig.ServiceURLV2("/app/conversation") if err != nil { return "", err } request.URL = serviceURL request.Method = "POST" header.Set("Content-Type", "application/json") request.Header = header req := map[string]string{"app_id": t.appID} data, _ := json.Marshal(req) request.Body = NopCloser(bytes.NewReader(data)) t.sdkConfig.BuildCurlCommand(&request) resp, err := t.client.Do(&request) if err != nil { return "", err } defer resp.Body.Close() requestID, err := checkHTTPResponse(resp) if err != nil { return "", fmt.Errorf("requestID=%s, err=%v", requestID, err) } data, err = io.ReadAll(resp.Body) if err != nil { return "", fmt.Errorf("requestID=%s, err=%v", requestID, err) } rsp := make(map[string]any) if err := json.Unmarshal(data, &rsp); err != nil { return "", fmt.Errorf("requestID=%s, err=%v", requestID, err) } val, ok := rsp["conversation_id"] if !ok { return "", fmt.Errorf("requestID=%s, body=%s", requestID, string(data)) } return val.(string), nil } func (t *AgentBuilder) UploadLocalFile(conversationID string, filePath string) (string, error) { var data bytes.Buffer w := multipart.NewWriter(&data) appIDPart, _ := w.CreateFormField("app_id") appIDPart.Write([]byte(t.appID)) conversationIDPart, _ := w.CreateFormField("conversation_id") conversationIDPart.Write([]byte(conversationID)) file, err := os.Open(filePath) if err != nil { return "", err } defer file.Close() filePart, _ := w.CreateFormFile("file", filepath.Base(filePath)) if _, err := io.Copy(filePart, file); err != nil { return "", err } w.Close() request := http.Request{} serviceURL, err := t.sdkConfig.ServiceURLV2("/app/conversation/file/upload") if err != nil { return "", err } request.URL = serviceURL request.Method = "POST" header := t.sdkConfig.AuthHeaderV2() header.Set("Content-Type", w.FormDataContentType()) request.Header = header request.Body = NopCloser(bytes.NewReader(data.Bytes())) resp, err := t.client.Do(&request) if err != nil { return "", err } defer resp.Body.Close() requestID, err := checkHTTPResponse(resp) if err != nil { return "", fmt.Errorf("requestID=%s, err=%v", requestID, err) } body, err := io.ReadAll(resp.Body) if err != nil { return "", fmt.Errorf("requestID=%s, err=%v", requestID, err) } rsp := make(map[string]any) if err := json.Unmarshal(body, &rsp); err != nil { return "", fmt.Errorf("requestID=%s, err=%v", requestID, err) } val, ok := rsp["id"] if !ok { return "", fmt.Errorf("requestID=%s, body=%s", requestID, string(body)) } return val.(string), nil } func (t *AgentBuilder) Run(conversationID string, query string, fileIDS []string, stream bool) (AgentBuilderIterator, error) { if len(conversationID) == 0 { return nil, errors.New("conversationID mustn't be empty") } m := map[string]any{"app_id": t.appID, "conversation_id": conversationID, "query": query, "file_ids": fileIDS, "stream": stream, } request := http.Request{} serviceURL, err := t.sdkConfig.ServiceURLV2("/app/conversation/runs") if err != nil { return nil, err } request.URL = serviceURL request.Method = "POST" header := t.sdkConfig.AuthHeaderV2() header.Set("Content-Type", "application/json") request.Header = header data, _ := json.Marshal(m) request.Body = NopCloser(bytes.NewReader(data)) t.sdkConfig.BuildCurlCommand(&request) resp, err := t.client.Do(&request) if err != nil { return nil, err } requestID, err := checkHTTPResponse(resp) if err != nil { return nil, fmt.Errorf("requestID=%s, err=%v", requestID, err) } r := NewSSEReader(1024*1024, bufio.NewReader(resp.Body)) if stream { return &AgentBuilderStreamIterator{requestID: requestID, r: r, body: resp.Body}, nil } return &AgentBuilderOnceIterator{body: resp.Body}, nil } ================================================ FILE: go/appbuilder/agent_builder_data.go ================================================ // Copyright (c) 2024 Baidu, Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package appbuilder import ( "encoding/json" "fmt" "io" "reflect" "strings" ) func (t *AgentBuilderAnswer) transform(inp *AgentBuilderRawResponse) { t.Answer = inp.Answer for _, c := range inp.Content { ev := Event{Code: c.EventCode, Message: c.EventMessage, Status: c.EventStatus, EventType: c.EventType, ContentType: c.ContentType, Detail: c.Outputs} tp, ok := TypeToStruct[ev.ContentType] if !ok { tp = reflect.TypeOf(DefaultDetail{}) } v := reflect.New(tp) _ = json.Unmarshal(c.Outputs, v.Interface()) ev.Detail = v.Elem().Interface() t.Events = append(t.Events, ev) } } // AgentBuilderIterator 定义AgentBuilder流式/非流式迭代器接口 // 初始状态可迭代,如果返回error不为空则代表迭代结束, // error为io.EOF,则代表迭代正常结束,其它则为异常结束 type AgentBuilderIterator interface { // Next 获取处理结果,如果返回error不为空,迭代器自动失效,不允许再调用此方法 Next() (*AgentBuilderAnswer, error) } type AgentBuilderStreamIterator struct { requestID string r *sseReader body io.ReadCloser } func (t *AgentBuilderStreamIterator) Next() (*AgentBuilderAnswer, error) { data, err := t.r.ReadMessageLine() if err != nil && !(err == io.EOF) { t.body.Close() return nil, fmt.Errorf("requestID=%s, err=%v", t.requestID, err) } if err != nil && err == io.EOF { t.body.Close() return nil, err } if strings.HasPrefix(string(data), "data:") { var resp AgentBuilderRawResponse if err := json.Unmarshal(data[5:], &resp); err != nil { t.body.Close() return nil, fmt.Errorf("requestID=%s, err=%v", t.requestID, err) } answer := &AgentBuilderAnswer{} answer.transform(&resp) return answer, nil } // 非SSE格式关闭连接,并返回数据 t.body.Close() return nil, fmt.Errorf("requestID=%s, body=%s", t.requestID, string(data)) } // AgentBuilderOnceIterator 非流式返回时对应的迭代器,只可迭代一次 type AgentBuilderOnceIterator struct { body io.ReadCloser requestID string } func (t *AgentBuilderOnceIterator) Next() (*AgentBuilderAnswer, error) { data, err := io.ReadAll(t.body) if err != nil { return nil, fmt.Errorf("requestID=%s, err=%v", t.requestID, err) } defer t.body.Close() var resp AgentBuilderRawResponse if err := json.Unmarshal(data, &resp); err != nil { return nil, fmt.Errorf("requestID=%s, err=%v", t.requestID, err) } answer := &AgentBuilderAnswer{} answer.transform(&resp) return answer, nil } ================================================ FILE: go/appbuilder/agent_builder_data_test.go ================================================ package appbuilder import ( "encoding/json" "testing" "bufio" "io" "strings" ) // 测试 if !ok 分支 func TestAgentBuilderAnswerTransformWithInvalidContentType(t *testing.T) { t.Parallel() // 并发运行 // 构造一个 AgentBuilderRawResponse,其中 ContentType 是不存在的 rawResponse := &AgentBuilderRawResponse{ Answer: "Test Answer", Content: []RawEventDetail{ { EventCode: 111, EventMessage: "Test Message", EventStatus: "Success", EventType: "TestType", ContentType: "InvalidContentType", // 模拟不存在的 ContentType Outputs: json.RawMessage(`{}`), // 空的输出 }, }, } // 调用 transform 方法 answer := &AgentBuilderAnswer{} answer.transform(rawResponse) } // 测试 err != nil && !(err == io.EOF) 分支 func TestAgentBuilderStreamIterator_Next_ReadError(t *testing.T) { t.Parallel() // 并发运行 // 模拟没有数据的输入 mockBody := io.NopCloser(strings.NewReader("")) reader := bufio.NewReader(mockBody) sseReader := NewSSEReader(1024, reader) streamIterator := &AgentBuilderStreamIterator{ requestID: "test-request", r: sseReader, // 使用 NewSSEReader 初始化的 sseReader body: mockBody, } // 调用 Next 并检查返回的错误 _, err := streamIterator.Next() if err != io.EOF { t.Fatalf("expected io.EOF, got %v", err) } } // 测试 json.Unmarshal 解析失败 func TestAgentBuilderStreamIterator_Next_JSONUnmarshalError(t *testing.T) { t.Parallel() // 并发运行 // 模拟 SSE 消息,data 后面跟着无效 JSON mockBody := io.NopCloser(strings.NewReader("data: invalid-json")) reader := bufio.NewReader(mockBody) sseReader := NewSSEReader(1024, reader) streamIterator := &AgentBuilderStreamIterator{ requestID: "test-request", r: sseReader, body: mockBody, } // 调用 Next 并检查返回的错误 _, err := streamIterator.Next() if err == nil || !strings.Contains(err.Error(), "invalid character") { } } // 测试非 SSE 格式数据 func TestAgentBuilderStreamIterator_Next_NonSSEFormat(t *testing.T) { t.Parallel() // 并发运行 // 模拟非 SSE 格式的消息 mockBody := io.NopCloser(strings.NewReader("not-sse-format-data")) reader := bufio.NewReader(mockBody) sseReader := NewSSEReader(1024, reader) streamIterator := &AgentBuilderStreamIterator{ requestID: "test-request", r: sseReader, body: mockBody, } // 调用 Next 并检查返回的错误 streamIterator.Next() } // 测试正常的 SSE 数据流 func TestAgentBuilderStreamIterator_Next_ValidSSE(t *testing.T) { t.Parallel() // 并发运行 // 模拟有效的 SSE 消息 mockBody := io.NopCloser(strings.NewReader("data: {\"answer\": \"Test Answer\", \"content\": []}")) reader := bufio.NewReader(mockBody) sseReader := NewSSEReader(1024, reader) streamIterator := &AgentBuilderStreamIterator{ requestID: "test-request", r: sseReader, body: mockBody, } // 调用 Next 并检查返回的结果 streamIterator.Next() } ================================================ FILE: go/appbuilder/agent_builder_test.go ================================================ // Copyright (c) 2024 Baidu, Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package appbuilder import ( "bytes" "encoding/json" "fmt" "io" "net/http" "os" "strings" "testing" ) // 模拟返回 400 错误的 HTTP 响应 type MockHTTPClient struct{} func (m *MockHTTPClient) Do(req *http.Request) (*http.Response, error) { return &http.Response{ StatusCode: 400, // 非 2xx 状态码 Body: io.NopCloser(strings.NewReader(`{"error": "Bad Request"}`)), }, nil } // FaultyHTTPClient 模拟响应读取时发生错误 type FaultyHTTPClient struct{} func (f *FaultyHTTPClient) Do(req *http.Request) (*http.Response, error) { return &http.Response{ StatusCode: 200, // 返回成功的状态码 Body: &FaultyBody{}, // 使用 FaultyBody,模拟读取时出错 }, nil } // FaultyBody 模拟响应体读取错误 type FaultyBody struct{} func (f *FaultyBody) Read(p []byte) (n int, err error) { return 0, fmt.Errorf("simulated read error") // 模拟读取时发生错误 } func (f *FaultyBody) Close() error { return nil } // 模拟无效 JSON 响应 type InvalidJSONHTTPClient struct{} func (m *InvalidJSONHTTPClient) Do(req *http.Request) (*http.Response, error) { return &http.Response{ StatusCode: 200, Body: io.NopCloser(strings.NewReader(`{invalid_json}`)), }, nil } // 模拟缺少 id 的 JSON 响应 type MissingIDHTTPClient struct{} func (m *MissingIDHTTPClient) Do(req *http.Request) (*http.Response, error) { return &http.Response{ StatusCode: 200, // 成功的状态码,但缺少 id 字段 Body: io.NopCloser(strings.NewReader(`{"message": "Upload successful", "other_field": "value"}`)), // 缺少 id 字段 }, nil } func TestNewAgentBuilderError(t *testing.T) { t.Parallel() // 并发运行 // 设置环境变量 os.Setenv("APPBUILDER_LOGLEVEL", "DEBUG") // NewAgentBuilder测试 1: appID 为空,预期返回错误 _, err := NewAgentBuilder("", &SDKConfig{}) if err == nil || err.Error() != "appID is empty" { t.Errorf("expected error for empty appID, got %v", err) } // NewAgentBuilder测试 2: config 为 nil,预期返回错误 _, err = NewAgentBuilder("validAppID", nil) if err == nil || err.Error() != "config is nil" { t.Errorf("expected error for nil config, got %v", err) } config, err := NewSDKConfig("", "") if err != nil { t.Logf("%s========== FAIL: %s ==========%s", "\033[31m", t.Name(), "\033[0m") t.Fatalf("new http client config failed: %v", err) } appID := "aa8af334-df27-4855-b3d1-0d249c61fc08" // CreateConversation测试 1: ServiceURLV2 错误 agentBuilder, err := NewAgentBuilder(appID, config) if err != nil { t.Fatalf("new AgentBuilder instance failed") } agentBuilder.sdkConfig.GatewayURLV2 = "://invalid-url" _, err = agentBuilder.CreateConversation() if err == nil { t.Errorf("expected ServiceURLV2 error, got nil") } // CreateConversation测试 2: HTTP client do error agentBuilder.sdkConfig.GatewayURLV2 = "http://192.0.2.1" _, err = agentBuilder.CreateConversation() if err == nil { t.Errorf("expected client error, got nil") } // CreateConversation测试 3: checkHTTPResponse 400 错误 agentBuilder.client = &MockHTTPClient{} _, err = agentBuilder.CreateConversation() if err == nil { t.Fatalf("expected 400 error, got nil") } // CreateConversation测试 4: 模拟读取 body 时发生错误 agentBuilder.client = &FaultyHTTPClient{} _, err = agentBuilder.CreateConversation() if err == nil { t.Fatalf("expected read error, got nil") } // CreateConversation测试 5: json.Unmarshal错误 agentBuilder.client = &InvalidJSONHTTPClient{} _, err = agentBuilder.CreateConversation() if err == nil { t.Fatalf("expected JSON unmarshal error, got nil") } // CreateConversation测试 6: 缺少 conversation_id agentBuilder.client = &MissingIDHTTPClient{} _, err = agentBuilder.CreateConversation() if err == nil { t.Fatalf("expected missing conversation_id error, got nil") } } func TestNewAgentBuilderUploadLocalFileError1(t *testing.T) { t.Parallel() // 并发运行 // 设置环境变量 os.Setenv("APPBUILDER_LOGLEVEL", "DEBUG") //正常的agentBuilder config, err := NewSDKConfig("", "") if err != nil { t.Fatalf("new http client config failed: %v", err) } appID := "aa8af334-df27-4855-b3d1-0d249c61fc08" agentBuilder, _ := NewAgentBuilder(appID, config) // 测试 UploadLocalFile 1: 文件打开错误 _, err = agentBuilder.UploadLocalFile("validConversationID", "invalidFilePath") if err == nil || !strings.Contains(err.Error(), "no such file or directory") { t.Errorf("expected file open error, got %v", err) } // 测试 UploadLocalFile 2: 文件复制错误 // 测试 UploadLocalFile 4: t.client.Do 错误 agentBuilder.sdkConfig.GatewayURLV2 = "http://192.0.2.1" _, err = agentBuilder.UploadLocalFile("5665", "./files/test.pdf") if err == nil { t.Errorf("expected client error, got nil") } // 测试 UploadLocalFile 3: 无效的ServiceURLV2 agentBuilder.sdkConfig.GatewayURLV2 = "://invalid-url" _, err = agentBuilder.UploadLocalFile("6776", "./files/test.pdf") if err == nil || !strings.Contains(err.Error(), "missing protocol scheme") { t.Errorf("expected ServiceURLV2 error, got %v", err) } } func TestNewAgentBuilderUploadLocalFileError2(t *testing.T) { t.Parallel() // 并发运行 // 设置环境变量 os.Setenv("APPBUILDER_LOGLEVEL", "DEBUG") //正常的agentBuilder config, err := NewSDKConfig("", "") if err != nil { t.Fatalf("new http client config failed: %v", err) } appID := "aa8af334-df27-4855-b3d1-0d249c61fc08" agentBuilder, _ := NewAgentBuilder(appID, config) // 测试 UploadLocalFile 5: checkHTTPResponse 错误 agentBuilder.client = &MockHTTPClient{} _, err = agentBuilder.UploadLocalFile("123321", "./files/test.pdf") if err == nil || !strings.Contains(err.Error(), "Bad Request") { t.Errorf("expected Bad Request error, got %v", err) } // 测试 UploadLocalFile 6: io.ReadAll 错误 agentBuilder.client = &FaultyHTTPClient{} _, err = agentBuilder.UploadLocalFile("2332", "./files/test.pdf") if err == nil || !strings.Contains(err.Error(), "simulated read error") { t.Errorf("expected read error, got %v", err) } // 测试 UploadLocalFile 7: json.Unmarshal 错误 agentBuilder.client = &InvalidJSONHTTPClient{} _, err = agentBuilder.UploadLocalFile("3443", "./files/test.pdf") if err == nil || !strings.Contains(err.Error(), "invalid character") { t.Errorf("expected JSON unmarshal error, got %v", err) } // 测试 UploadLocalFile 8: 缺少 id 字段 agentBuilder.client = &MissingIDHTTPClient{} _, err = agentBuilder.UploadLocalFile("4554", "./files/test.pdf") // 检查 err 是否为空,并且确保返回的错误信息包含 "id" 这个字段 if err == nil || !strings.Contains(err.Error(), "body") || !strings.Contains(err.Error(), "id") { } } func TestNewAgentBuilderRunError(t *testing.T) { t.Parallel() // 并发运行 // 测试逻辑 config, err := NewSDKConfig("", "") if err != nil { t.Logf("%s========== FAIL: %s ==========%s", "\033[31m", t.Name(), "\033[0m") t.Fatalf("new http client config failed: %v", err) } appID := "aa8af334-df27-4855-b3d1-0d249c61fc08" agentBuilder, err := NewAgentBuilder(appID, config) if err != nil { t.Logf("%s========== FAIL: %s ==========%s", "\033[31m", t.Name(), "\033[0m") t.Fatalf("new AgentBuilder instance failed") } //测试1 conversationID为空 _, err = agentBuilder.Run("", "描述简历中的候选人情况", nil, true) if err == nil { t.Errorf("expected conversationID mustn't be empty, got %v", err) } //测试2 ServiceURLV2 error 无效的ServiceURLV2 agentBuilder.sdkConfig.GatewayURLV2 = "://invalid-url" _, err = agentBuilder.Run("2135", "描述简历中的候选人情况", nil, true) if err == nil { t.Logf("%s========== FAIL: %s ==========%s", "\033[31m", t.Name(), "\033[0m") t.Errorf("expected ServiceURLV2 error, got %v", err) } //测试3 t.client.Do 错误 agentBuilder.sdkConfig.GatewayURLV2 = "http://192.0.2.1" _, err = agentBuilder.Run("1221", "描述简历中的候选人情况", nil, true) if err == nil { t.Logf("%s========== FAIL: %s ==========%s", "\033[31m", t.Name(), "\033[0m") t.Errorf("expected Bad Request error, got %v", err) } } func TestNewAgentBuilder(t *testing.T) { // 创建缓冲区来存储日志 var logBuffer bytes.Buffer // 设置环境变量 os.Setenv("APPBUILDER_LOGLEVEL", "DEBUG") // 将日志输出重定向到缓冲区 log := func(format string, args ...interface{}) { fmt.Fprintf(&logBuffer, format+"\n", args...) } // 测试逻辑 config, err := NewSDKConfig("", "") if err != nil { t.Logf("%s========== FAIL: %s ==========%s", "\033[31m", t.Name(), "\033[0m") t.Fatalf("new http client config failed: %v", err) } appID := "aa8af334-df27-4855-b3d1-0d249c61fc08" agentBuilder, err := NewAgentBuilder(appID, config) if err != nil { t.Logf("%s========== FAIL: %s ==========%s", "\033[31m", t.Name(), "\033[0m") t.Fatalf("new AgentBuilder instance failed") } //正常测试 conversationID, err := agentBuilder.CreateConversation() if err != nil { t.Logf("%s========== FAIL: %s ==========%s", "\033[31m", t.Name(), "\033[0m") t.Fatalf("create conversation failed: %v", err) } _, err = agentBuilder.UploadLocalFile(conversationID, "./files/test.pdf") if err != nil { t.Logf("%s========== FAIL: %s ==========%s", "\033[31m", t.Name(), "\033[0m") t.Fatalf("upload local file failed: %v", err) } i, err := agentBuilder.Run(conversationID, "描述简历中的候选人情况", nil, true) if err != nil { t.Logf("%s========== FAIL: %s ==========%s", "\033[31m", t.Name(), "\033[0m") t.Fatalf("run failed:%v", err) } totalAnswer := "" for answer, err := i.Next(); err == nil; answer, err = i.Next() { totalAnswer = totalAnswer + answer.Answer for _, ev := range answer.Events { switch ev.ContentType { case TextContentType: detail := ev.Detail.(TextDetail) log("---------------TextDetail------------") log("%v", detail) case CodeContentType: detail := ev.Detail.(CodeDetail) log("---------------CodeDetail------------") log("%v", detail) case ImageContentType: detail := ev.Detail.(ImageDetail) log("---------------ImageDetail------------") log("%v", detail) case RAGContentType: detail := ev.Detail.(RAGDetail) log("---------------RAGDetail------------") log("%v", detail) case FunctionCallContentType: detail := ev.Detail.(FunctionCallDetail) log("---------------FunctionCallDetail------------") log("%v", detail) case AudioContentType: detail := ev.Detail.(AudioDetail) log("---------------AudioDetail------------") log("%v", detail.Audio) case VideoContentType: detail := ev.Detail.(VideoDetail) log("---------------VideoDetail------------") log("%v", detail) case StatusContentType: // No additional detail to log default: // 默认是 json.RawMessage detail, ok := ev.Detail.(json.RawMessage) if ok { log("---------------rawMessage------------") log("%s", string(detail)) } } } } log("----------------answer-------------------") log(totalAnswer) //测试4 非流式 _, err = agentBuilder.Run(conversationID, "描述简历中的候选人情况", nil, false) if err != nil { } // 如果测试失败,则输出缓冲区中的日志 if t.Failed() { t.Logf("%s========== FAIL: %s ==========%s", "\033[31m", t.Name(), "\033[0m") fmt.Println(logBuffer.String()) } else { // else 紧跟在右大括号后面 // 测试通过,打印文件名和测试函数名 t.Logf("%s========== OK: %s ==========%s", "\033[32m", t.Name(), "\033[0m") } } ================================================ FILE: go/appbuilder/app_builder_client.go ================================================ // Copyright (c) 2024 Baidu, Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package appbuilder import ( "bufio" "bytes" "encoding/json" "errors" "fmt" "io" "mime/multipart" "net/http" "net/url" "os" "path/filepath" "reflect" "strconv" "time" ) // Deprecated: 将废弃,请使用DescribeApps替代 func GetAppList(req GetAppListRequest, config *SDKConfig) ([]App, error) { request := http.Request{} header := config.AuthHeaderV2() serviceURL, err := config.ServiceURLV2("/apps") if err != nil { return nil, err } request.URL = serviceURL request.Method = "GET" header.Set("Content-Type", "application/json") request.Header = header reqMap := make(map[string]any) reqJson, _ := json.Marshal(req) json.Unmarshal(reqJson, &reqMap) params := url.Values{} for key, value := range reqMap { switch v := value.(type) { case float64: params.Add(key, strconv.Itoa(int(v))) case string: if v == "" { continue } params.Add(key, v) } } serviceURL.RawQuery = params.Encode() config.BuildCurlCommand(&request) client := config.HTTPClient if client == nil { client = &http.Client{Timeout: 1800 * time.Second} } resp, err := client.Do(&request) if err != nil { return nil, err } defer resp.Body.Close() requestID, err := checkHTTPResponse(resp) if err != nil { return nil, fmt.Errorf("requestID=%s, err=%v", requestID, err) } data, err := io.ReadAll(resp.Body) if err != nil { return nil, fmt.Errorf("requestID=%s, err=%v", requestID, err) } rsp := GetAppListResponse{} if err := json.Unmarshal(data, &rsp); err != nil { return nil, fmt.Errorf("requestID=%s, err=%v", requestID, err) } return rsp.Data, nil } func DescribeApps(req DescribeAppsRequest, config *SDKConfig) (DescribeAppsResponse, error) { request := http.Request{} header := config.AuthHeaderV2() serviceURL, err := config.ServiceURLV2("/app?Action=DescribeApps") if err != nil { return DescribeAppsResponse{}, err } request.URL = serviceURL request.Method = "POST" header.Set("Content-Type", "application/json") request.Header = header data, _ := json.Marshal(req) request.Body = NopCloser(bytes.NewReader(data)) config.BuildCurlCommand(&request) client := config.HTTPClient if client == nil { client = &http.Client{Timeout: 1800 * time.Second} } resp, err := client.Do(&request) if err != nil { return DescribeAppsResponse{}, err } defer resp.Body.Close() requestID, err := checkHTTPResponse(resp) if err != nil { return DescribeAppsResponse{}, fmt.Errorf("requestID=%s, err=%v", requestID, err) } data, err = io.ReadAll(resp.Body) if err != nil { return DescribeAppsResponse{}, fmt.Errorf("requestID=%s, err=%v", requestID, err) } rsp := DescribeAppsResponse{} if err := json.Unmarshal(data, &rsp); err != nil { return DescribeAppsResponse{}, fmt.Errorf("requestID=%s, err=%v", requestID, err) } return rsp, nil } func DescribeApp(appID string, config *SDKConfig) (DescribeAppResponse, error) { request := http.Request{} header := config.AuthHeaderV2() serviceURL, err := config.ServiceURLV2("/app?Action=DescribeApp") if err != nil { return DescribeAppResponse{}, err } request.URL = serviceURL request.Method = "POST" header.Set("Content-Type", "application/json") request.Header = header data, _ := json.Marshal(DescribeAppRequest{ID: appID}) request.Body = NopCloser(bytes.NewReader(data)) config.BuildCurlCommand(&request) client := config.HTTPClient if client == nil { client = &http.Client{Timeout: 1800 * time.Second} } resp, err := client.Do(&request) if err != nil { return DescribeAppResponse{}, err } defer resp.Body.Close() requestID, err := checkHTTPResponse(resp) if err != nil { return DescribeAppResponse{}, fmt.Errorf("requestID=%s, err=%v", requestID, err) } data, err = io.ReadAll(resp.Body) if err != nil { return DescribeAppResponse{}, fmt.Errorf("requestID=%s, err=%v", requestID, err) } rsp := DescribeAppResponse{} if err := json.Unmarshal(data, &rsp); err != nil { return DescribeAppResponse{}, fmt.Errorf("requestID=%s, err=%v", requestID, err) } return rsp, nil } func NewAppBuilderClient(appID string, config *SDKConfig) (*AppBuilderClient, error) { if appID == "" { return nil, errors.New("appID is empty") } if config == nil { return nil, errors.New("config is nil") } client := config.HTTPClient if client == nil { client = &http.Client{Timeout: 1800 * time.Second} } return &AppBuilderClient{appID: appID, sdkConfig: config, client: client}, nil } type AppBuilderClient struct { appID string sdkConfig *SDKConfig client HTTPClient } // 在 AppBuilderClient 结构体中添加 Getter 方法 func (t *AppBuilderClient) GetSdkConfig() *SDKConfig { return t.sdkConfig } func (t *AppBuilderClient) GetClient() HTTPClient { return t.client } type HTTPClient interface { Do(req *http.Request) (*http.Response, error) } func (t *AppBuilderClient) CreateConversation() (string, error) { request := http.Request{} header := t.sdkConfig.AuthHeaderV2() serviceURL, err := t.sdkConfig.ServiceURLV2("/app/conversation") if err != nil { return "", err } request.URL = serviceURL request.Method = "POST" header.Set("Content-Type", "application/json") request.Header = header req := map[string]string{"app_id": t.appID} data, _ := json.Marshal(req) request.Body = io.NopCloser(bytes.NewReader(data)) t.sdkConfig.BuildCurlCommand(&request) resp, err := t.client.Do(&request) if err != nil { return "", err } defer resp.Body.Close() requestID, err := checkHTTPResponse(resp) if err != nil { return "", fmt.Errorf("requestID=%s, err=%v", requestID, err) } data, err = io.ReadAll(resp.Body) if err != nil { return "", fmt.Errorf("requestID=%s, err=%v", requestID, err) } rsp := make(map[string]any) if err := json.Unmarshal(data, &rsp); err != nil { return "", fmt.Errorf("requestID=%s, err=%v", requestID, err) } val, ok := rsp["conversation_id"] if !ok { return "", fmt.Errorf("requestID=%s, body=%s", requestID, string(data)) } return val.(string), nil } func (t *AppBuilderClient) UploadLocalFile(conversationID string, filePath string) (string, error) { var data bytes.Buffer w := multipart.NewWriter(&data) appIDPart, _ := w.CreateFormField("app_id") appIDPart.Write([]byte(t.appID)) conversationIDPart, _ := w.CreateFormField("conversation_id") conversationIDPart.Write([]byte(conversationID)) file, err := os.Open(filePath) if err != nil { return "", err } defer file.Close() filePart, _ := w.CreateFormFile("file", filepath.Base(filePath)) if _, err := io.Copy(filePart, file); err != nil { return "", err } w.Close() request := http.Request{} serviceURL, err := t.sdkConfig.ServiceURLV2("/app/conversation/file/upload") if err != nil { return "", err } request.URL = serviceURL request.Method = "POST" header := t.sdkConfig.AuthHeaderV2() header.Set("Content-Type", w.FormDataContentType()) request.Header = header request.Body = NopCloser(bytes.NewReader(data.Bytes())) resp, err := t.client.Do(&request) if err != nil { return "", err } defer resp.Body.Close() requestID, err := checkHTTPResponse(resp) if err != nil { return "", fmt.Errorf("requestID=%s, err=%v", requestID, err) } body, err := io.ReadAll(resp.Body) if err != nil { return "", fmt.Errorf("requestID=%s, err=%v", requestID, err) } rsp := make(map[string]any) if err := json.Unmarshal(body, &rsp); err != nil { return "", fmt.Errorf("requestID=%s, err=%v", requestID, err) } val, ok := rsp["id"] if !ok { return "", fmt.Errorf("requestID=%s, body=%s", requestID, string(body)) } return val.(string), nil } func (t *AppBuilderClient) UploadFile(req *AppBuilderClientUploadFileRequest) (string, error) { var appID string if req.AppID != "" { appID = req.AppID } else { appID = t.appID } if appID == "" { return "", errors.New("appID is required") } if req.FilePath == "" && req.FileURL == "" { return "", errors.New("either FilePath or FileURL is required") } var data bytes.Buffer w := multipart.NewWriter(&data) appIDPart, _ := w.CreateFormField("app_id") appIDPart.Write([]byte(appID)) conversationIDPart, _ := w.CreateFormField("conversation_id") conversationIDPart.Write([]byte(req.ConversationID)) if req.FilePath != "" { file, err := os.Open(req.FilePath) if err != nil { return "", err } defer file.Close() filePart, _ := w.CreateFormFile("file", filepath.Base(req.FilePath)) if _, err := io.Copy(filePart, file); err != nil { return "", err } } else { fileURLPart, _ := w.CreateFormField("file_url") fileURLPart.Write([]byte(req.FileURL)) } w.Close() request := http.Request{} serviceURL, err := t.sdkConfig.ServiceURLV2("/app/conversation/file/upload") if err != nil { return "", err } request.URL = serviceURL request.Method = "POST" header := t.sdkConfig.AuthHeaderV2() header.Set("Content-Type", w.FormDataContentType()) request.Header = header request.Body = NopCloser(bytes.NewReader(data.Bytes())) resp, err := t.client.Do(&request) if err != nil { return "", err } defer resp.Body.Close() requestID, err := checkHTTPResponse(resp) if err != nil { return "", fmt.Errorf("requestID=%s, err=%v", requestID, err) } body, err := io.ReadAll(resp.Body) if err != nil { return "", fmt.Errorf("requestID=%s, err=%v", requestID, err) } rsp := make(map[string]any) if err := json.Unmarshal(body, &rsp); err != nil { return "", fmt.Errorf("requestID=%s, err=%v", requestID, err) } val, ok := rsp["id"] if !ok { return "", fmt.Errorf("requestID=%s, body=%s", requestID, string(body)) } return val.(string), nil } func (t *AppBuilderClient) Run(param ...interface{}) (AppBuilderClientIterator, error) { if len(param) == 0 { return nil, errors.New("no arguments provided") } var err error var req AppBuilderClientRunRequest if reflect.TypeOf(param[0]) == reflect.TypeOf(AppBuilderClientRunRequest{}) { req = param[0].(AppBuilderClientRunRequest) } else { req, err = t.buildAppBuilderClientRunRequest(param...) if err != nil { return nil, err } } if len(req.ConversationID) == 0 { return nil, errors.New("conversationID mustn't be empty") } if len(req.AppID) == 0 { req.AppID = t.appID } request := http.Request{} serviceURL, err := t.sdkConfig.ServiceURLV2("/app/conversation/runs") if err != nil { return nil, err } header := t.sdkConfig.AuthHeaderV2() request.URL = serviceURL request.Method = "POST" header.Set("Content-Type", "application/json") request.Header = header data, _ := json.Marshal(req) request.Body = NopCloser(bytes.NewReader(data)) request.ContentLength = int64(len(data)) t.sdkConfig.BuildCurlCommand(&request) resp, err := t.client.Do(&request) if err != nil { return nil, err } requestID, err := checkHTTPResponse(resp) if err != nil { return nil, fmt.Errorf("requestID=%s, err=%v", requestID, err) } r := NewSSEReader(1024*1024, bufio.NewReader(resp.Body)) if req.Stream { return &AppBuilderClientStreamIterator{requestID: requestID, r: r, body: resp.Body}, nil } return &AppBuilderClientOnceIterator{body: resp.Body}, nil } func (t *AppBuilderClient) buildAppBuilderClientRunRequest(param ...interface{}) (AppBuilderClientRunRequest, error) { conversationID, ok := param[0].(string) if !ok { return AppBuilderClientRunRequest{}, errors.New("conversationID must be string type") } query, ok := param[1].(string) if !ok { return AppBuilderClientRunRequest{}, errors.New("query must be string type") } var fileIDS []string if param[2] != nil { fileIDS, ok = param[2].([]string) if !ok { fileIDS = nil } } stream, ok := param[3].(bool) if !ok { stream = false } return AppBuilderClientRunRequest{ AppID: t.appID, ConversationID: conversationID, Query: query, Stream: stream, FileIDs: fileIDS, }, nil } func (t *AppBuilderClient) Feedback(req AppBuilderClientFeedbackRequest) (string, error) { if len(req.ConversationID) == 0 { return "", errors.New("conversationID mustn't be empty") } if len(req.AppID) == 0 { req.AppID = t.appID } request := http.Request{} serviceURL, err := t.sdkConfig.ServiceURLV2("/app/conversation/feedback") if err != nil { return "", err } header := t.sdkConfig.AuthHeaderV2() request.URL = serviceURL request.Method = "POST" header.Set("Content-Type", "application/json") request.Header = header data, _ := json.Marshal(req) request.Body = NopCloser(bytes.NewReader(data)) request.ContentLength = int64(len(data)) // 手动设置长度 t.sdkConfig.BuildCurlCommand(&request) resp, err := t.client.Do(&request) if err != nil { return "", err } requestID, err := checkHTTPResponse(resp) if err != nil { return requestID, fmt.Errorf("requestID=%s, err=%v", requestID, err) } return requestID, nil } // Deprecated: Run方法已兼容此方法 func (t *AppBuilderClient) RunWithToolCall(req AppBuilderClientRunRequest) (AppBuilderClientIterator, error) { if len(req.ConversationID) == 0 { return nil, errors.New("conversationID mustn't be empty") } request := http.Request{} serviceURL, err := t.sdkConfig.ServiceURLV2("/app/conversation/runs") if err != nil { return nil, err } header := t.sdkConfig.AuthHeaderV2() request.URL = serviceURL request.Method = "POST" header.Set("Content-Type", "application/json") request.Header = header data, _ := json.Marshal(req) request.Body = NopCloser(bytes.NewReader(data)) request.ContentLength = int64(len(data)) // 手动设置长度 t.sdkConfig.BuildCurlCommand(&request) resp, err := t.client.Do(&request) if err != nil { return nil, err } requestID, err := checkHTTPResponse(resp) if err != nil { return nil, fmt.Errorf("requestID=%s, err=%v", requestID, err) } r := NewSSEReader(1024*1024, bufio.NewReader(resp.Body)) if req.Stream { return &AppBuilderClientStreamIterator{requestID: requestID, r: r, body: resp.Body}, nil } return &AppBuilderClientOnceIterator{body: resp.Body}, nil } ================================================ FILE: go/appbuilder/app_builder_client_data.go ================================================ // Copyright (c) 2024 Baidu, Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package appbuilder import ( "encoding/json" "fmt" "io" "reflect" "strings" ) const ( CodeContentType = "code" TextContentType = "text" ImageContentType = "image" RAGContentType = "rag" FunctionCallContentType = "function_call" AudioContentType = "audio" VideoContentType = "video" StatusContentType = "status" ChatflowInterruptContentType = "chatflow_interrupt" PublishMessageContentType = "publish_message" JsonContentType = "json" ChatReasoningContentType = "chat_reasoning" ) const ( ChatflowEventType = "chatflow" FollowUpQueryEventType = "FollowUpQuery" ) var TypeToStruct = map[string]reflect.Type{ CodeContentType: reflect.TypeOf(CodeDetail{}), TextContentType: reflect.TypeOf(TextDetail{}), ImageContentType: reflect.TypeOf(ImageDetail{}), RAGContentType: reflect.TypeOf(RAGDetail{}), FunctionCallContentType: reflect.TypeOf(FunctionCallDetail{}), AudioContentType: reflect.TypeOf(AudioDetail{}), VideoContentType: reflect.TypeOf(VideoDetail{}), StatusContentType: reflect.TypeOf(StatusDetail{}), ChatflowInterruptContentType: reflect.TypeOf(ChatflowInterruptDetail{}), PublishMessageContentType: reflect.TypeOf(PublishMessageDetail{}), JsonContentType: reflect.TypeOf(JsonDetail{}), ChatReasoningContentType: reflect.TypeOf(ChatReasoningDetail{}), } type AppBuilderClientRunRequest struct { AppID string `json:"app_id"` Query string `json:"query"` Stream bool `json:"stream"` EndUserID *string `json:"end_user_id"` ConversationID string `json:"conversation_id"` FileIDs []string `json:"file_ids"` Tools []Tool `json:"tools"` ToolOutputs []ToolOutput `json:"tool_outputs"` ToolChoice *ToolChoice `json:"tool_choice"` Action *Action `json:"action"` McpAuthorization *[]map[string]interface{} `json:"mcp_authorization,omitempty"` Parameters map[string]any `json:"parameters,omitempty"` CustomMetadata *CustomMetadata `json:"custom_metadata,omitempty"` } type AppBuilderClientUploadFileRequest struct { AppID string `json:"app_id"` ConversationID string `json:"conversation_id"` FilePath string `json:"file_path"` FileURL string `json:"file_url"` } type AppBuilderClientFeedbackRequest struct { AppID string `json:"app_id"` ConversationID string `json:"conversation_id"` MessageID string `json:"message_id"` Type string `json:"type"` Flag []string `json:"flag,omitempty"` Reason string `json:"reason,omitempty"` } type Tool struct { Type string `json:"type"` Function Function `json:"function"` } type Function struct { Name string `json:"name"` Description string `json:"description"` Parameters map[string]any `json:"parameters"` } type ToolOutput struct { ToolCallID string `json:"tool_call_id" description:"工具调用ID"` Output string `json:"output" description:"工具输出"` } type ToolChoice struct { Type string `json:"type"` Function ToolChoiceFunction `json:"function"` } type ToolChoiceFunction struct { Name string `json:"name"` Input map[string]interface{} `json:"input"` } type Action struct { ActionType string `json:"action_type"` Paramters *ActionParamters `json:"parameters"` } type ActionParamters struct { InterruptEvent *ActionInterruptEvent `json:"interrupt_event"` } type ActionInterruptEvent struct { ID string `json:"id"` Type string `json:"type"` } type CustomMetadata struct { OverrideRoleInstruction string `json:"override_role_instruction"` } func NewResumeAction(eventId string) *Action { return NewAction("resume", eventId, "chat") } func NewAction(actionType string, eventId string, eventType string) *Action { return &Action{ ActionType: actionType, Paramters: &ActionParamters{ InterruptEvent: &ActionInterruptEvent{ ID: eventId, Type: eventType, }, }, } } type AgentBuilderRawResponse struct { RequestID string `json:"request_id"` Date string `json:"date"` Answer string `json:"answer"` ConversationID string `json:"conversation_id"` MessageID string `json:"message_id"` IsCompletion bool `json:"is_completion"` Content []RawEventDetail `json:"content"` } type RawEventDetail struct { EventCode int `json:"event_code"` EventMessage string `json:"event_message"` EventType string `json:"event_type"` EventID string `json:"event_id"` EventStatus string `json:"event_status"` ContentType string `json:"content_type"` Outputs json.RawMessage `json:"outputs"` Usage Usage `json:"usage"` ToolCalls []ToolCall `json:"tool_calls"` } type Usage struct { PromptTokens int `json:"prompt_tokens"` CompletionTokens int `json:"completion_tokens"` TotalTokens int `json:"total_tokens"` Name string `json:"name"` } type AgentBuilderAnswer struct { Answer string Events []Event } type Event struct { Code int Message string Status string EventType string ContentType string Usage Usage Detail any ToolCalls []ToolCall } type ToolCall struct { ID string `json:"id"` // 工具调用ID Type string `json:"type"` // 需要输出的工具调用的类型。就目前而言,这始终是function Function FunctionCallOption `json:"function"` // 函数定义 } type FunctionCallOption struct { Name string `json:"name"` Arguments map[string]any `json:"arguments"` } type TextDetail struct { Text string `json:"text"` } type CodeDetail struct { Text string `json:"text"` Code string `json:"code"` Files []string `json:"files"` } type RAGDetail struct { Text string `json:"text"` References []Reference `json:"references"` } type Reference struct { ID string `json:"id"` From string `json:"from"` URL string `json:"url"` Content string `json:"content"` SegmentID string `json:"segment_id"` DocumentID string `json:"document_id"` DatasetID string `json:"dataset_id"` DocumentName string `json:"document_name"` KnowledgeBaseID string `json:"knowledgebase_id"` } type FunctionCallDetail struct { Text any `json:"text"` Image string `json:"image"` Audio string `json:"audio"` Video string `json:"video"` } type ImageDetail struct { Image string `json:"image"` } type AudioDetail struct { Audio string `json:"audio"` } type VideoDetail struct { Video string `json:"video"` } type StatusDetail struct{} type ChatflowInterruptDetail struct { InterruptEventID string `json:"interrupt_event_id"` InterruptEventType string `json:"interrupt_event_type"` } type PublishMessageDetail struct { Message string `json:"message"` MessageID string `json:"message_id"` } type ChatReasoningDetail struct { Text string `json:"text"` } type JsonDetail struct { Json FollowUpQueries `json:"json"` } type FollowUpQueries struct { FollowUpQueries []string `json:"follow_up_querys"` } type DefaultDetail struct { Text string `json:"text,omitempty"` URLS []string `json:"urls,omitempty"` Files []string `json:"files,omitempty"` Image string `json:"image,omitempty"` Video string `json:"video,omitempty"` Audio string `json:"audio,omitempty"` } type AppBuilderClientRawResponse struct { RequestID string `json:"request_id"` Date string `json:"date"` Answer string `json:"answer"` ConversationID string `json:"conversation_id"` MessageID string `json:"message_id"` IsCompletion bool `json:"is_completion"` Content []RawEventDetail `json:"content"` Code string `json:"code,omitempty"` Message string `json:"message,omitempty"` } type GetAppListRequest struct { Limit int `json:"limit"` After string `json:"after"` Before string `json:"before"` } type GetAppListResponse struct { RequestID string `json:"request_id"` Data []App `json:"data"` Code string `json:"code"` Message string `json:"message"` } type DescribeAppsRequest struct { Marker *string `json:"marker,omitempty"` MaxKeys *int `json:"maxKeys,omitempty"` } type DescribeAppsResponse struct { RequestID string `json:"requestId"` Marker string `json:"marker"` IsTruncated bool `json:"isTruncated"` NextMarker string `json:"nextMarker"` MaxKeys int `json:"maxKeys"` Data []App `json:"data"` } type DescribeAppRequest struct { ID string `json:"id"` } type DescribeAppResponse struct { RequestID string `json:"requestId"` ID string `json:"id"` Name string `json:"name"` Description string `json:"description"` Instruction string `json:"instruction"` Prologue string `json:"prologue"` ExampleQueries []string `json:"exampleQueries"` FollowUpQueries AppFollowUpQueries `json:"followUpQueries"` Components []Component `json:"components"` KnowledgeBaseConfig KnowledgeBaseConfig `json:"knowledgeBaseConfig"` ModelConfig ModelConfig `json:"modelConfig"` Background *Background `json:"background,omitempty"` } type AppFollowUpQueries struct { Type string `json:"type"` Prompt string `json:"prompt"` Round string `json:"round"` } type Component struct { Name string `json:"name,omitempty"` Description string `json:"description,omitempty"` CustomDesc string `json:"customDesc,omitempty"` } type KnowledgeBaseConfig struct { KnowledgeBases []AppKnowledgeBase `json:"knowledgeBases"` Retrieval RetrievalConfig `json:"retrieval"` } type AppKnowledgeBase struct { ID string `json:"id,omitempty"` Name string `json:"name,omitempty"` Description string `json:"description,omitempty"` } type RetrievalConfig struct { EnableWebSearch bool `json:"enableWebSearch,omitempty"` Order string `json:"order,omitempty"` Strategy string `json:"strategy,omitempty"` TopK int `json:"topK,omitempty"` Threshold float64 `json:"threshold,omitempty"` } type ModelConfig struct { Plan PlanConfig `json:"plan"` Chat ChatConfig `json:"chat"` } type PlanConfig struct { ModelID string `json:"modelId"` Model string `json:"model"` MaxRounds int `json:"maxRounds"` Config ModelParams `json:"config"` } type ChatConfig struct { ModelID string `json:"modelId"` Model string `json:"model"` HistoryChatRounds int `json:"historyChatRounds"` Config ModelParams `json:"config"` } type ModelParams struct { Temperature float64 `json:"temperature"` TopP float64 `json:"topP"` } type Background struct { ID string `json:"id,omitempty"` Path string `json:"path,omitempty"` MobileConfig *MobileConfig `json:"mobile_config,omitempty"` PCConfig *PCConfig `json:"pc_config,omitempty"` } type MobileConfig struct { Left string `json:"left,omitempty"` Top string `json:"top,omitempty"` Height string `json:"height,omitempty"` Color string `json:"color,omitempty"` } type PCConfig struct { Left string `json:"left,omitempty"` Top string `json:"top,omitempty"` Height string `json:"height,omitempty"` Color string `json:"color,omitempty"` } type App struct { ID string `json:"id"` Name string `json:"name"` Description string `json:"description"` AppType string `json:"appType,omitempty"` IsPublished bool `json:"isPublished,omitempty"` UpdateTime int64 `json:"updateTime,omitempty"` } type AppBuilderClientAnswer struct { MessageID string Answer string Events []Event Code string Message string RequestID string } func (t *AppBuilderClientAnswer) transform(inp *AppBuilderClientRawResponse) { t.Answer = inp.Answer t.MessageID = inp.MessageID t.Code = inp.Code t.Message = inp.Message t.RequestID = inp.RequestID for _, c := range inp.Content { ev := Event{Code: c.EventCode, Message: c.EventMessage, Status: c.EventStatus, EventType: c.EventType, ContentType: c.ContentType, Usage: c.Usage, Detail: c.Outputs, ToolCalls: c.ToolCalls} // 这部分新改的 tp, ok := TypeToStruct[ev.ContentType] if !ok { tp = reflect.TypeOf(DefaultDetail{}) } v := reflect.New(tp) _ = json.Unmarshal(c.Outputs, v.Interface()) ev.Detail = v.Elem().Interface() // 这部分新改的 t.Events = append(t.Events, ev) } } // AppBuilderClientIterator 定义AppBuilderClient流式/非流式迭代器接口 // 初始状态可迭代,如果返回error不为空则代表迭代结束, // error为io.EOF,则代表迭代正常结束,其它则为异常结束 type AppBuilderClientIterator interface { // Next 获取处理结果,如果返回error不为空,迭代器自动失效,不允许再调用此方法 Next() (*AppBuilderClientAnswer, error) } type AppBuilderClientStreamIterator struct { requestID string r *sseReader body io.ReadCloser } func (t *AppBuilderClientStreamIterator) Next() (*AppBuilderClientAnswer, error) { data, err := t.r.ReadMessageLine() if err != nil && !(err == io.EOF) { t.body.Close() return nil, fmt.Errorf("requestID=%s, err=%v", t.requestID, err) } if err != nil && err == io.EOF { t.body.Close() return nil, err } if strings.HasPrefix(string(data), "data:") { var resp AppBuilderClientRawResponse if err := json.Unmarshal(data[5:], &resp); err != nil { t.body.Close() return nil, fmt.Errorf("requestID=%s, err=%v", t.requestID, err) } answer := &AppBuilderClientAnswer{} answer.transform(&resp) return answer, nil } // 非SSE格式关闭连接,并返回数据 t.body.Close() return nil, fmt.Errorf("requestID=%s, body=%s", t.requestID, string(data)) } // AppBuilderClientOnceIterator 非流式返回时对应的迭代器,只可迭代一次 type AppBuilderClientOnceIterator struct { body io.ReadCloser requestID string } func (t *AppBuilderClientOnceIterator) Next() (*AppBuilderClientAnswer, error) { data, err := io.ReadAll(t.body) if err != nil { return nil, fmt.Errorf("requestID=%s, err=%v", t.requestID, err) } defer t.body.Close() var resp AppBuilderClientRawResponse if err := json.Unmarshal(data, &resp); err != nil { return nil, fmt.Errorf("requestID=%s, err=%v", t.requestID, err) } answer := &AppBuilderClientAnswer{} answer.transform(&resp) return answer, nil } ================================================ FILE: go/appbuilder/app_builder_client_test.go ================================================ // Copyright (c) 2024 Baidu, Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package appbuilder import ( "bytes" "encoding/json" "fmt" "os" "strings" "testing" ) func TestNewAppBuilderClientError(t *testing.T) { t.Parallel() // 并发运行 // 测试逻辑 config, err := NewSDKConfig("", "") if err != nil { t.Logf("%s========== FAIL: %s ==========%s", "\033[31m", t.Name(), "\033[0m") t.Fatalf("new http client config failed: %v", err) } // NewAppBuilderClient测试1 appID := "aa8af334-df27-4855-b3d1-0d249c61fc08" _, err = NewAppBuilderClient("", config) if err == nil { t.Logf("%s========== FAIL: %s ==========%s", "\033[31m", t.Name(), "\033[0m") } // NewAppBuilderClient测试2 _, err = NewAppBuilderClient(appID, nil) if err == nil { t.Logf("%s========== FAIL: %s ==========%s", "\033[31m", t.Name(), "\033[0m") } // GetSdkConfig测试 client, err := NewAppBuilderClient(appID, config) if err != nil { t.Logf("%s========== FAIL: %s ==========%s", "\033[31m", t.Name(), "\033[0m") t.Fatalf("new AppBuilderClient instance failed") } client.GetSdkConfig() // GetClient测试 client.GetClient() var GatewayURL = config.GatewayURLV2 // CreateConversation 测试1 ServiceURLV2 错误 client.sdkConfig.GatewayURLV2 = "://invalid-url" _, err = client.CreateConversation() if err == nil { t.Logf("%s========== FAIL: %s ==========%s", "\033[31m", t.Name(), "\033[0m") t.Errorf("expected ServiceURLV2 error, got %v", err) } // CreateConversation 测试2 Do 错误 client.sdkConfig.GatewayURLV2 = "http://192.0.2.1" _, err = client.CreateConversation() if err == nil { t.Logf("%s========== FAIL: %s ==========%s", "\033[31m", t.Name(), "\033[0m") t.Errorf("expected Bad Request error, got %v", err) } // CreateConversation 测试3 错误的 HTTP 响应 client.sdkConfig.GatewayURLV2 = GatewayURL client.client = &MockHTTPClient{} _, err = client.CreateConversation() if err == nil { t.Fatalf("expected 400 error, got nil") } // CreateConversation 测试 4: 模拟读取 body 时发生错误 client.sdkConfig.GatewayURLV2 = GatewayURL client.client = &FaultyHTTPClient{} _, err = client.CreateConversation() if err == nil { t.Fatalf("expected read error, got nil") } // CreateConversation 测试 5: json.Unmarshal错误 client.sdkConfig.GatewayURLV2 = GatewayURL client.client = &InvalidJSONHTTPClient{} _, err = client.CreateConversation() if err == nil { t.Fatalf("expected JSON unmarshal error, got nil") } // CreateConversation 测试 6: 缺少 id 字段 client.client = &MissingIDHTTPClient{} client.CreateConversation() // 测试1 ServiceURLV2 错误 config.GatewayURLV2 = "://invalid-url" _, err = GetAppList(GetAppListRequest{ Limit: 10, }, config) if err == nil { t.Logf("%s========== FAIL: %s ==========%s", "\033[31m", t.Name(), "\033[0m") t.Errorf("expected ServiceURLV2 error, got %v", err) } // 测试2 Do 错误 config.GatewayURLV2 = "http://192.0.2.1" _, err = GetAppList(GetAppListRequest{ Limit: 10, }, config) if err == nil { t.Logf("%s========== FAIL: %s ==========%s", "\033[31m", t.Name(), "\033[0m") t.Errorf("expected Bad Request error, got %v", err) } // 测试3 错误的 HTTP 响应 config.GatewayURLV2 = GatewayURL config.HTTPClient = &MockHTTPClient{} _, err = GetAppList(GetAppListRequest{ Limit: 10, }, config) if err == nil { t.Fatalf("expected 400 error, got nil") } // 测试 4: 模拟读取 body 时发生错误 config.GatewayURLV2 = GatewayURL config.HTTPClient = &FaultyHTTPClient{} _, err = GetAppList(GetAppListRequest{ Limit: 10, }, config) if err == nil { t.Fatalf("expected read error, got nil") } // 测试 5: json.Unmarshal错误 config.GatewayURLV2 = GatewayURL config.HTTPClient = &InvalidJSONHTTPClient{} _, err = GetAppList(GetAppListRequest{ Limit: 10, }, config) if err == nil { t.Fatalf("expected JSON unmarshal error, got nil") } } func TestClientUploadLocalFile(t *testing.T) { t.Parallel() // 并发运行 // 测试逻辑 config, err := NewSDKConfig("", "") if err != nil { t.Logf("%s========== FAIL: %s ==========%s", "\033[31m", t.Name(), "\033[0m") t.Fatalf("new http client config failed: %v", err) } var GatewayURL = config.GatewayURLV2 appID := "aa8af334-df27-4855-b3d1-0d249c61fc08" client, err := NewAppBuilderClient(appID, config) if err != nil { t.Logf("%s========== FAIL: %s ==========%s", "\033[31m", t.Name(), "\033[0m") t.Fatalf("new AppBuilderClient instance failed") } // 测试 UploadLocalFile 1: 文件打开错误 _, err = client.UploadLocalFile("validConversationID", "invalidFilePath") if err == nil || !strings.Contains(err.Error(), "no such file or directory") { t.Errorf("expected file open error, got %v", err) } // 测试 UploadLocalFile 2: t.client.Do 错误 client.sdkConfig.GatewayURLV2 = "http://192.0.2.1" _, err = client.UploadLocalFile("5678987", "./files/test.pdf") if err == nil { t.Errorf("expected client error, got nil") } // 测试 UploadLocalFile 3: 无效的ServiceURLV2 client.sdkConfig.GatewayURLV2 = "://invalid-url" _, err = client.UploadLocalFile("12345", "./files/test.pdf") if err == nil || !strings.Contains(err.Error(), "missing protocol scheme") { t.Errorf("expected ServiceURLV2 error, got %v", err) } // 测试 UploadLocalFile 4: 错误的 HTTP 响应 client.client = &MockHTTPClient{} client.sdkConfig.GatewayURLV2 = GatewayURL _, err = client.UploadLocalFile("21", "./files/test.pdf") if err == nil { t.Fatalf("expected 400 error, got nil") } // 测试 UploadLocalFile 5: 模拟读取 body 时发生错误 client.client = &FaultyHTTPClient{} client.sdkConfig.GatewayURLV2 = GatewayURL _, err = client.UploadLocalFile("22", "./files/test.pdf") if err == nil { t.Fatalf("expected read error, got nil") } // 测试 UploadLocalFile 6: json.Unmarshal错误 client.client = &InvalidJSONHTTPClient{} client.sdkConfig.GatewayURLV2 = GatewayURL _, err = client.UploadLocalFile("11", "./files/test.pdf") if err == nil { t.Fatalf("expected JSON unmarshal error, got nil") } // 测试 UploadLocalFile 7: 缺少 id 字段 client.client = &MissingIDHTTPClient{} client.sdkConfig.GatewayURLV2 = GatewayURL _, err = client.UploadLocalFile("23", "./files/test.pdf") if err == nil { t.Fatalf("expected missing conversation_id error, got nil") } } func TestClientRun(t *testing.T) { t.Parallel() // 并发运行 // 测试逻辑 config, err := NewSDKConfig("", "") if err != nil { t.Logf("%s========== FAIL: %s ==========%s", "\033[31m", t.Name(), "\033[0m") t.Fatalf("new http client config failed: %v", err) } var GatewayURL = config.GatewayURLV2 appID := "aa8af334-df27-4855-b3d1-0d249c61fc08" client, err := NewAppBuilderClient(appID, config) if err != nil { t.Logf("%s========== FAIL: %s ==========%s", "\033[31m", t.Name(), "\033[0m") t.Fatalf("new AppBuilderClient instance failed") } // 测试1 conversationID ==0 _, err = client.Run("", "描述简历中的候选人情况", nil, true) if err == nil { t.Errorf("expected conversationID mustn't be empty, got %v", err) } // 测试2 ServiceURLV2 error 无效的ServiceURLV2 client.sdkConfig.GatewayURLV2 = "://invalid-url" _, err = client.Run("12", "描述简历中的候选人情况", nil, true) if err == nil { t.Logf("%s========== FAIL: %s ==========%s", "\033[31m", t.Name(), "\033[0m") t.Errorf("expected ServiceURLV2 error, got %v", err) } // 测试3 t.client.Do 错误 client.sdkConfig.GatewayURLV2 = "http://192.0.2.1" _, err = client.Run("123", "描述简历中的候选人情况", nil, true) if err == nil { t.Logf("%s========== FAIL: %s ==========%s", "\033[31m", t.Name(), "\033[0m") t.Errorf("expected Bad Request error, got %v", err) } // 测试4 错误的 HTTP 响应 client.client = &MockHTTPClient{} client.sdkConfig.GatewayURLV2 = GatewayURL _, err = client.Run("1234", "描述简历中的候选人情况", nil, true) if err == nil { t.Fatalf("expected 400 error, got nil") } } func TestClientRunWithToolCallError(t *testing.T) { t.Parallel() // 并发运行 // 测试逻辑 config, err := NewSDKConfig("", "") if err != nil { t.Logf("%s========== FAIL: %s ==========%s", "\033[31m", t.Name(), "\033[0m") t.Fatalf("new http client config failed: %v", err) } var GatewayURL = config.GatewayURLV2 appID := "aa8af334-df27-4855-b3d1-0d249c61fc08" client, err := NewAppBuilderClient(appID, config) if err != nil { t.Logf("%s========== FAIL: %s ==========%s", "\033[31m", t.Name(), "\033[0m") t.Fatalf("new AppBuilderClient instance failed") } jsonStr := ` { "type": "function", "function": { "name": "get_cur_whether", "description": "这是一个获得指定地点天气的工具", "parameters": { "type": "object", "properties": { "location": { "type": "string", "description": "省,市名,例如:河北省" }, "unit": { "type": "string", "enum": ["摄氏度", "华氏度"] } }, "required": ["location"] } } }` var tool Tool err = json.Unmarshal([]byte(jsonStr), &tool) if err != nil { fmt.Println("unmarshal tool error:", err) } // 测试1 conversationID ==0 client.RunWithToolCall(AppBuilderClientRunRequest{ AppID: appID, Query: "今天北京的天气怎么样?", ConversationID: "", Stream: false, Tools: []Tool{tool}, }) // 测试4 非流式 client.RunWithToolCall(AppBuilderClientRunRequest{ AppID: appID, Query: "今天北京的天气怎么样?", ConversationID: "111111", Stream: false, Tools: []Tool{tool}, }) // 测试2 ServiceURLV2 error 无效的ServiceURLV2 client.sdkConfig.GatewayURLV2 = "://invalid-url" client.RunWithToolCall(AppBuilderClientRunRequest{ AppID: appID, Query: "今天北京的天气怎么样?", ConversationID: "111111111", Stream: false, Tools: []Tool{tool}, }) // 测试3 t.client.Do 错误 client.sdkConfig.GatewayURLV2 = "http://192.0.2.1" client.RunWithToolCall(AppBuilderClientRunRequest{ AppID: appID, Query: "今天北京的天气怎么样?", ConversationID: "222222", Stream: false, Tools: []Tool{tool}, }) // 测试4 错误的 HTTP 响应 client.client = &MockHTTPClient{} client.sdkConfig.GatewayURLV2 = GatewayURL client.RunWithToolCall(AppBuilderClientRunRequest{ AppID: appID, Query: "今天北京的天气怎么样?", ConversationID: "33333", Stream: false, Tools: []Tool{tool}, }) } func TestDescribeApp(t *testing.T) { var logBuffer bytes.Buffer os.Setenv("APPBUILDER_LOGLEVEL", "DEBUG") os.Setenv("APPBUILDER_LOGFILE", "") log := func(format string, args ...any) { fmt.Fprintf(&logBuffer, format+"\n", args...) } config, err := NewSDKConfig("", "") if err != nil { t.Logf("%s========== FAIL: %s ==========%s", "\033[31m", t.Name(), "\033[0m") t.Fatalf("new http client config failed: %v", err) } app, err := DescribeApp("b2a972c5-e082-46e5-b313-acbf51792422", config) if err != nil { t.Logf("%s========== FAIL: %s ==========%s", "\033[31m", t.Name(), "\033[0m") t.Fatalf("describe app failed: %v", err) } log("Get App Name: %s", app.Name) chatflowApp, err := DescribeApp("4403205e-fb83-4fac-96d8-943bdb63796f", config) if err != nil { t.Logf("%s========== FAIL: %s ==========%s", "\033[31m", t.Name(), "\033[0m") t.Fatalf("describe app failed: %v", err) } log("Get App Name: %s", chatflowApp.Name) } func TestNewAppBuilderClient(t *testing.T) { var logBuffer bytes.Buffer // 设置环境变量 os.Setenv("APPBUILDER_LOGLEVEL", "DEBUG") os.Setenv("APPBUILDER_LOGFILE", "") // 定义一个日志函数,将日志写入缓冲区 log := func(format string, args ...any) { fmt.Fprintf(&logBuffer, format+"\n", args...) } // 测试逻辑 config, err := NewSDKConfig("", "") if err != nil { t.Logf("%s========== FAIL: %s ==========%s", "\033[31m", t.Name(), "\033[0m") t.Fatalf("new http client config failed: %v", err) } apps, err := GetAppList(GetAppListRequest{ Limit: 10, }, config) if err != nil { t.Logf("%s========== FAIL: %s ==========%s", "\033[31m", t.Name(), "\033[0m") t.Fatalf("get apps failed: %v", err) } log("Number of apps: %d", len(apps)) maxKeys := 10 apps2, err := DescribeApps(DescribeAppsRequest{MaxKeys: &maxKeys}, config) if err != nil { t.Logf("%s========== FAIL: %s ==========%s", "\033[31m", t.Name(), "\033[0m") t.Fatalf("describe apps failed: %v", err) } log("Number of apps: %d", len(apps2.Data)) appID := "fb64d96b-f828-4385-ba1d-835298d635a9" client, err := NewAppBuilderClient(appID, config) if err != nil { t.Logf("%s========== FAIL: %s ==========%s", "\033[31m", t.Name(), "\033[0m") t.Fatalf("new AppBuilderClient instance failed") } conversationID, err := client.CreateConversation() if err != nil { t.Logf("%s========== FAIL: %s ==========%s", "\033[31m", t.Name(), "\033[0m") t.Fatalf("create conversation failed: %v", err) } _, err = client.UploadLocalFile(conversationID, "./files/test.pdf") if err != nil { t.Logf("%s========== FAIL: %s ==========%s", "\033[31m", t.Name(), "\033[0m") t.Fatalf("upload local file failed: %v", err) } i, err := client.Run(conversationID, "描述简历中的候选人情况", nil, true) if err != nil { t.Logf("%s========== FAIL: %s ==========%s", "\033[31m", t.Name(), "\033[0m") t.Fatalf("run failed:%v", err) } totalAnswer := "" // test follow up queries for answer, err := i.Next(); err == nil; answer, err = i.Next() { totalAnswer += answer.Answer for _, ev := range answer.Events { if ev.ContentType == JsonContentType { detail := ev.Detail.(JsonDetail) folllowUpQueries := detail.Json.FollowUpQueries fmt.Println(folllowUpQueries) if len(folllowUpQueries[0]) == 0 { t.Logf("%s========== FAIL: %s ==========%s", "\033[31m", t.Name(), "\033[0m") t.Fatal("follow up queries is empty") } } evJSON, _ := json.Marshal(ev) log(string(evJSON)) } } log("----------------answer-------------------") log(totalAnswer) // 测试4 非流式 client.Run(conversationID, "描述简历中的候选人情况", nil, false) // 如果测试失败,则输出缓冲区中的日志 if t.Failed() { fmt.Println(logBuffer.String()) } else { // else 紧跟在右大括号后面 // 测试通过,打印文件名和测试函数名 t.Logf("%s========== OK: %s ==========%s", "\033[32m", t.Name(), "\033[0m") } } func TestAppBuilderClientRunWithToolCall(t *testing.T) { var logBuffer bytes.Buffer os.Setenv("APPBUILDER_LOGLEVEL", "DEBUG") os.Setenv("APPBUILDER_LOGFILE", "") log := func(format string, args ...any) { fmt.Fprintf(&logBuffer, format+"\n", args...) } config, err := NewSDKConfig("", "") if err != nil { t.Logf("%s========== FAIL: %s ==========%s", "\033[31m", t.Name(), "\033[0m") t.Fatalf("new http client config failed: %v", err) } appID := "aa8af334-df27-4855-b3d1-0d249c61fc08" client, err := NewAppBuilderClient(appID, config) if err != nil { t.Logf("%s========== FAIL: %s ==========%s", "\033[31m", t.Name(), "\033[0m") t.Fatalf("new AgentBuidler instance failed") } conversationID, err := client.CreateConversation() if err != nil { t.Logf("%s========== FAIL: %s ==========%s", "\033[31m", t.Name(), "\033[0m") t.Fatalf("create conversation failed: %v", err) } jsonStr := ` { "type": "function", "function": { "name": "get_cur_whether", "description": "这是一个获得指定地点天气的工具", "parameters": { "type": "object", "properties": { "location": { "type": "string", "description": "省,市名,例如:河北省" }, "unit": { "type": "string", "enum": ["摄氏度", "华氏度"] } }, "required": ["location"] } } }` var tool Tool err = json.Unmarshal([]byte(jsonStr), &tool) if err != nil { fmt.Println("unmarshal tool error:", err) } i, err := client.RunWithToolCall(AppBuilderClientRunRequest{ AppID: appID, Query: "今天北京的天气怎么样?", ConversationID: conversationID, Stream: false, Tools: []Tool{tool}, }) if err != nil { t.Logf("%s========== FAIL: %s ==========%s", "\033[31m", t.Name(), "\033[0m") t.Fatalf("run failed:%v", err) } totalAnswer := "" toolCallID := "" for answer, err := i.Next(); err == nil; answer, err = i.Next() { totalAnswer += answer.Answer lastEvent := answer.Events[len(answer.Events)-1] toolCallID = lastEvent.ToolCalls[len(lastEvent.ToolCalls)-1].ID } i2, err := client.RunWithToolCall(AppBuilderClientRunRequest{ ConversationID: conversationID, AppID: appID, ToolOutputs: []ToolOutput{ { ToolCallID: toolCallID, Output: "北京今天35", }, }, }) if err != nil { t.Logf("%s========== FAIL: %s ==========%s", "\033[31m", t.Name(), "\033[0m") t.Fatalf("run failed:%v", err) } for answer, err := i2.Next(); err == nil; answer, err = i2.Next() { totalAnswer += answer.Answer for _, ev := range answer.Events { evJSON, _ := json.Marshal(ev) log(string(evJSON)) } } log("----------------answer-------------------") log(totalAnswer) // 如果测试失败,则输出缓冲区中的日志 if t.Failed() { fmt.Printf("%s========== FAIL: %s ==========%s\n", "\033[31m", t.Name(), "\033[0m") fmt.Println(logBuffer.String()) } else { // else 紧跟在右大括号后面 // 测试通过,打印文件名和测试函数名 t.Logf("%s========== OK: %s ==========%s", "\033[32m", t.Name(), "\033[0m") } } func TestAppBuilderClientRunToolChoice(t *testing.T) { var logBuffer bytes.Buffer os.Setenv("APPBUILDER_LOGLEVEL", "DEBUG") os.Setenv("APPBUILDER_LOGFILE", "") log := func(format string, args ...any) { fmt.Fprintf(&logBuffer, format+"\n", args...) } config, err := NewSDKConfig("", "") if err != nil { t.Logf("%s========== FAIL: %s ==========%s", "\033[31m", t.Name(), "\033[0m") t.Fatalf("new http client config failed: %v", err) } appID := "aa8af334-df27-4855-b3d1-0d249c61fc08" client, err := NewAppBuilderClient(appID, config) if err != nil { t.Logf("%s========== FAIL: %s ==========%s", "\033[31m", t.Name(), "\033[0m") t.Fatalf("new AgentBuidler instance failed") } conversationID, err := client.CreateConversation() if err != nil { t.Logf("%s========== FAIL: %s ==========%s", "\033[31m", t.Name(), "\033[0m") t.Fatalf("create conversation failed: %v", err) } input := make(map[string]any) input["city"] = "北京" end_user_id := "go_user_id_0" i, err := client.Run(AppBuilderClientRunRequest{ ConversationID: conversationID, AppID: appID, Query: "你能干什么", EndUserID: &end_user_id, Stream: false, ToolChoice: &ToolChoice{ Type: "function", Function: ToolChoiceFunction{ Name: "WeatherQuery", Input: input, }, }, }) if err != nil { t.Logf("%s========== FAIL: %s ==========%s", "\033[31m", t.Name(), "\033[0m") t.Fatalf("run failed:%v", err) } for answer, err := i.Next(); err == nil; answer, err = i.Next() { for _, ev := range answer.Events { evJSON, _ := json.Marshal(ev) log(string(evJSON)) } } // 如果测试失败,则输出缓冲区中的日志 if t.Failed() { t.Logf("%s========== FAIL: %s ==========%s", "\033[31m", t.Name(), "\033[0m") fmt.Println(logBuffer.String()) } else { // else 紧跟在右大括号后面 // 测试通过,打印文件名和测试函数名 t.Logf("%s========== OK: %s ==========%s", "\033[32m", t.Name(), "\033[0m") } } func TestAppBuilderClientRunChatflow(t *testing.T) { var logBuffer bytes.Buffer os.Setenv("APPBUILDER_LOGLEVEL", "DEBUG") config, err := NewSDKConfig("", "") if err != nil { t.Logf("%s========== FAIL: %s ==========%s", "\033[31m", t.Name(), "\033[0m") t.Fatalf("new http client config failed: %v", err) } appID := "4403205e-fb83-4fac-96d8-943bdb63796f" client, err := NewAppBuilderClient(appID, config) if err != nil { t.Logf("%s========== FAIL: %s ==========%s", "\033[31m", t.Name(), "\033[0m") t.Fatalf("new AgentBuidler instance failed") } conversationID, err := client.CreateConversation() if err != nil { t.Logf("%s========== FAIL: %s ==========%s", "\033[31m", t.Name(), "\033[0m") t.Fatalf("create conversation failed: %v", err) } i, err := client.Run(AppBuilderClientRunRequest{ ConversationID: conversationID, AppID: appID, Query: "查天气", Stream: true, }) if err != nil { t.Logf("%s========== FAIL: %s ==========%s", "\033[31m", t.Name(), "\033[0m") t.Fatalf("run failed:%v", err) } var interruptId string interruptStack := make([]string, 0) for answer, err := i.Next(); err == nil; answer, err = i.Next() { for _, ev := range answer.Events { if ev.ContentType == PublishMessageContentType { detail := ev.Detail.(PublishMessageDetail) message := detail.Message fmt.Println(message) break } if ev.ContentType == ChatflowInterruptContentType { deatil := ev.Detail.(ChatflowInterruptDetail) interruptId = deatil.InterruptEventID interruptStack = append(interruptStack, interruptId) break } } } if len(interruptId) == 0 { t.Logf("%s========== FAIL: %s ==========%s", "\033[31m", t.Name(), "\033[0m") t.Fatalf("interrupt id is empty") } interruptId = "" i2, err := client.Run(AppBuilderClientRunRequest{ ConversationID: conversationID, AppID: appID, Query: "我先查个航班动态", Stream: true, Action: NewResumeAction(interruptStack[len(interruptStack)-1]), }) if err != nil { t.Logf("%s========== FAIL: %s ==========%s", "\033[31m", t.Name(), "\033[0m") t.Fatalf("run failed:%v", err) } interruptStack = interruptStack[:len(interruptStack)-1] for answer, err := i2.Next(); err == nil; answer, err = i2.Next() { for _, ev := range answer.Events { if ev.ContentType == PublishMessageContentType { detail := ev.Detail.(PublishMessageDetail) message := detail.Message fmt.Println(message) break } if ev.ContentType == ChatflowInterruptContentType { deatil := ev.Detail.(ChatflowInterruptDetail) interruptId = deatil.InterruptEventID interruptStack = append(interruptStack, interruptId) break } } } if len(interruptId) == 0 { t.Logf("%s========== FAIL: %s ==========%s", "\033[31m", t.Name(), "\033[0m") t.Fatalf("interrupt id is empty") } interruptId = "" i3, err := client.Run(AppBuilderClientRunRequest{ ConversationID: conversationID, AppID: appID, Query: "CA1234", Stream: true, Action: NewResumeAction(interruptStack[len(interruptStack)-1]), }) if err != nil { t.Logf("%s========== FAIL: %s ==========%s", "\033[31m", t.Name(), "\033[0m") t.Fatalf("run failed:%v", err) } interruptStack = interruptStack[:len(interruptStack)-1] for answer, err := i3.Next(); err == nil; answer, err = i3.Next() { for _, ev := range answer.Events { if ev.ContentType == TextContentType { detail := ev.Detail.(TextDetail) text := detail.Text fmt.Println(text) break } if ev.ContentType == ChatflowInterruptContentType { deatil := ev.Detail.(ChatflowInterruptDetail) interruptId = deatil.InterruptEventID interruptStack = append(interruptStack, interruptId) break } } } i4, err := client.Run(AppBuilderClientRunRequest{ ConversationID: conversationID, AppID: appID, Query: "北京的", Stream: true, Action: NewResumeAction(interruptStack[len(interruptStack)-1]), }) if err != nil { t.Logf("%s========== FAIL: %s ==========%s", "\033[31m", t.Name(), "\033[0m") t.Fatalf("run failed:%v", err) } for answer, err := i4.Next(); err == nil; answer, err = i4.Next() { for _, ev := range answer.Events { if ev.ContentType == TextContentType { detail := ev.Detail.(TextDetail) text := detail.Text fmt.Println(text) break } } } // 如果测试失败,则输出缓冲区中的日志 if t.Failed() { t.Logf("%s========== FAIL: %s ==========%s", "\033[31m", t.Name(), "\033[0m") fmt.Println(logBuffer.String()) } else { // else 紧跟在右大括号后面 // 测试通过,打印文件名和测试函数名 t.Logf("%s========== OK: %s ==========%s", "\033[32m", t.Name(), "\033[0m") } } func TestAppbuilderClientFeedback(t *testing.T) { var logBuffer bytes.Buffer // 设置环境变量 os.Setenv("APPBUILDER_LOGLEVEL", "DEBUG") os.Setenv("APPBUILDER_LOGFILE", "") // 测试逻辑 config, err := NewSDKConfig("", "") if err != nil { t.Logf("%s========== FAIL: %s ==========%s", "\033[31m", t.Name(), "\033[0m") t.Fatalf("new http client config failed: %v", err) } appID := "fb64d96b-f828-4385-ba1d-835298d635a9" client, err := NewAppBuilderClient(appID, config) if err != nil { t.Logf("%s========== FAIL: %s ==========%s", "\033[31m", t.Name(), "\033[0m") t.Fatalf("new AppBuilderClient instance failed") } conversationID, err := client.CreateConversation() if err != nil { t.Logf("%s========== FAIL: %s ==========%s", "\033[31m", t.Name(), "\033[0m") t.Fatalf("create conversation failed: %v", err) } _, err = client.UploadLocalFile(conversationID, "./files/test.pdf") if err != nil { t.Logf("%s========== FAIL: %s ==========%s", "\033[31m", t.Name(), "\033[0m") t.Fatalf("upload local file failed: %v", err) } i, err := client.Run(conversationID, "描述简历中的候选人情况", nil, false) if err != nil { t.Logf("%s========== FAIL: %s ==========%s", "\033[31m", t.Name(), "\033[0m") t.Fatalf("run failed:%v", err) } var messageID string for answer, err := i.Next(); err == nil; answer, err = i.Next() { if answer.MessageID != "" { messageID = answer.MessageID break } } _, err = client.Feedback(AppBuilderClientFeedbackRequest{ ConversationID: conversationID, MessageID: messageID, Type: "downvote", Flag: []string{"没有帮助"}, Reason: "测试", }) if err != nil { t.Logf("%s========== FAIL: %s ==========%s", "\033[31m", t.Name(), "\033[0m") t.Fatalf("upvote failed:%v", err) } // 如果测试失败,则输出缓冲区中的日志 if t.Failed() { fmt.Println(logBuffer.String()) } else { // else 紧跟在右大括号后面 // 测试通过,打印文件名和测试函数名 t.Logf("%s========== OK: %s ==========%s", "\033[32m", t.Name(), "\033[0m") } } func TestAppBuilderClientUploadFile(t *testing.T) { var logBuffer bytes.Buffer // 设置环境变量 os.Setenv("APPBUILDER_LOGLEVEL", "DEBUG") os.Setenv("APPBUILDER_LOGFILE", "") // 测试逻辑 config, err := NewSDKConfig("", "") if err != nil { t.Logf("%s========== FAIL: %s ==========%s", "\033[31m", t.Name(), "\033[0m") t.Fatalf("new http client config failed: %v", err) } appID := "fb64d96b-f828-4385-ba1d-835298d635a9" client, err := NewAppBuilderClient(appID, config) if err != nil { t.Logf("%s========== FAIL: %s ==========%s", "\033[31m", t.Name(), "\033[0m") t.Fatalf("new AppBuilderClient instance failed") } conversationID, err := client.CreateConversation() if err != nil { t.Logf("%s========== FAIL: %s ==========%s", "\033[31m", t.Name(), "\033[0m") t.Fatalf("create conversation failed: %v", err) } req := AppBuilderClientUploadFileRequest{ ConversationID: conversationID, FilePath: "./files/test.pdf", } _, err = client.UploadFile(&req) if err != nil { t.Logf("%s========== FAIL: %s ==========%s", "\033[31m", t.Name(), "\033[0m") t.Fatalf("upload local file failed: %v", err) } req = AppBuilderClientUploadFileRequest{ ConversationID: conversationID, FileURL: "https://bj.bcebos.com/v1/appbuilder/animal_recognize_test.png?authorization=bce-auth-v1%2FALTAKGa8m4qCUasgoljdEDAzLm%2F2024-01-24T12%3A19%3A16Z%2F-1%2Fhost%2F411bad53034fa8f9c6edbe5c4909d76ecf6fad6862cf937c03f8c5260d51c6ae", } _, err = client.UploadFile(&req) if err != nil { t.Logf("%s========== FAIL: %s ==========%s", "\033[31m", t.Name(), "\033[0m") t.Fatalf("upload url file failed: %v", err) } // 如果测试失败,则输出缓冲区中的日志 if t.Failed() { fmt.Println(logBuffer.String()) } else { // else 紧跟在右大括号后面 // 测试通过,打印文件名和测试函数名 t.Logf("%s========== OK: %s ==========%s", "\033[32m", t.Name(), "\033[0m") } } func TestAppBuilderClientRunParameters(t *testing.T) { t.Parallel() // 并发运行 // 测试逻辑 config, err := NewSDKConfig("", "") if err != nil { t.Logf("%s========== FAIL: %s ==========%s", "\033[31m", t.Name(), "\033[0m") t.Fatalf("new http client config failed: %v", err) } appID := "2313e282-baa6-4db6-92dd-a21e99cfd59e" client, err := NewAppBuilderClient(appID, config) if err != nil { t.Logf("%s========== FAIL: %s ==========%s", "\033[31m", t.Name(), "\033[0m") t.Fatalf("new AppBuilderClient instance failed") } conversationID, err := client.CreateConversation() if err != nil { t.Logf("%s========== FAIL: %s ==========%s", "\033[31m", t.Name(), "\033[0m") t.Fatalf("create conversation failed: %v", err) } res, err := client.Run(AppBuilderClientRunRequest{ AppID: appID, Query: "国庆长假", Stream: false, ConversationID: conversationID, Parameters: map[string]any{ "city": "上海", }, }) if err != nil { t.Errorf("run err: %v", err) } for answer, err := res.Next(); err == nil; answer, err = res.Next() { t.Log(answer.Answer) } } func TestAppBuilderClientRunCustomMetadata(t *testing.T) { t.Parallel() // 并发运行 // 测试逻辑 config, err := NewSDKConfig("", "") if err != nil { t.Logf("%s========== FAIL: %s ==========%s", "\033[31m", t.Name(), "\033[0m") t.Fatalf("new http client config failed: %v", err) } appID := "a3654cd9-378a-4b46-a33b-2259ca3b304e" client, err := NewAppBuilderClient(appID, config) if err != nil { t.Logf("%s========== FAIL: %s ==========%s", "\033[31m", t.Name(), "\033[0m") t.Fatalf("new AppBuilderClient instance failed") } conversationID, err := client.CreateConversation() if err != nil { t.Logf("%s========== FAIL: %s ==========%s", "\033[31m", t.Name(), "\033[0m") t.Fatalf("create conversation failed: %v", err) } res, err := client.Run(AppBuilderClientRunRequest{ AppID: appID, Query: "我要回老家相亲", Stream: true, ConversationID: conversationID, CustomMetadata: &CustomMetadata{ OverrideRoleInstruction: `# 角色任务\n" + "作为高情商大师,你的主要任务是根据提问,做出最佳的建议。\n" + "\n" + "# 工具能力\n" + "\n" + "无工具集提供\n" + "\n" + "# 要求与限制\n" + "\n" + "1. 输出内容的风格为幽默\n" + "2.输出的字数限制为1000字范围"`, }, }) if err != nil { t.Errorf("run err: %v", err) } for answer, err := res.Next(); err == nil; answer, err = res.Next() { t.Log(answer.Answer) } } ================================================ FILE: go/appbuilder/component_client.go ================================================ // Copyright (c) 2024 Baidu, Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package appbuilder import ( "bufio" "bytes" "encoding/json" "errors" "fmt" "net/http" "strings" "time" ) type ComponentClient struct { sdkConfig *SDKConfig client HTTPClient } func NewComponentClient(config *SDKConfig) (*ComponentClient, error) { if config == nil { return nil, errors.New("config is nil") } client := config.HTTPClient if client == nil { client = &http.Client{Timeout: 1800 * time.Second} } return &ComponentClient{sdkConfig: config, client: client}, nil } func (t *ComponentClient) Run(component, version, action string, stream bool, parameters map[string]any) (ComponentClientIterator, error) { request := http.Request{} urlSuffix := fmt.Sprintf("/components/%s", component) if version != "" { urlSuffix += fmt.Sprintf("/version/%s", version) } if action != "" { if strings.Contains(urlSuffix, "?") { urlSuffix += fmt.Sprintf("&action=%s", action) } else { urlSuffix += fmt.Sprintf("?action=%s", action) } } serviceURL, err := t.sdkConfig.ServiceURLV2(urlSuffix) if err != nil { return nil, err } header := t.sdkConfig.AuthHeaderV2() request.URL = serviceURL request.Method = "POST" header.Set("Content-Type", "application/json") header.Set("X-Appbuilder-From", "sdk") request.Header = header req := ComponentRunRequest{ Stream: stream, Parameters: parameters, } data, _ := json.Marshal(req) request.Body = NopCloser(bytes.NewReader(data)) request.ContentLength = int64(len(data)) // 手动设置长度 t.sdkConfig.BuildCurlCommand(&request) resp, err := t.client.Do(&request) if err != nil { return nil, err } requestID, err := checkHTTPResponse(resp) if err != nil { return nil, fmt.Errorf("requestID=%s, err=%v", requestID, err) } r := NewSSEReader(1024*1024, bufio.NewReader(resp.Body)) if req.Stream { return &ComponentClientStreamIterator{requestID: requestID, r: r, body: resp.Body}, nil } return &ComponentClientOnceIterator{body: resp.Body}, nil } ================================================ FILE: go/appbuilder/component_client_data.go ================================================ // Copyright (c) 2024 Baidu, Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package appbuilder import ( "encoding/json" "fmt" "io" "strings" ) const ( SysOriginQuery = "_sys_origin_query" SysFileUrls = "_sys_file_urls" SysConversationID = "_sys_conversation_id" SysEndUserID = "_sys_end_user_id" SysChatHistory = "_sys_chat_history" ) type ComponentRunRequest struct { Stream bool `json:"stream"` Parameters map[string]any `json:"parameters"` } type Message struct { Role string `json:"role"` Content string `json:"content"` } type ComponentRunResponse struct { RequestID string `json:"request_id"` Code string `json:"code"` Message string `json:"message"` ConversationID string `json:"conversation_id"` MessageID string `json:"message_id"` TraceID string `json:"trace_id"` UserID string `json:"user_id"` EndUserID string `json:"end_user_id"` Status string `json:"status"` // 新增的字段 Role string `json:"role"` Content []Content `json:"content"` } type Content struct { Name string `json:"name"` VisibleScope string `json:"visible_scope"` RawData map[string]any `json:"raw_data"` Usage map[string]any `json:"usage"` Metrics map[string]any `json:"metrics"` Type string `json:"type"` Text map[string]any `json:"text"` Event ComponentEvent `json:"event"` } type ComponentEvent struct { ID string `json:"id"` Status string `json:"status"` Name string `json:"name"` CreatedTime string `json:"created_time"` ErrorCode string `json:"error_code"` ErrorMessage string `json:"error_message"` } type Text struct { Info string `json:"info"` } type Code struct { Code string `json:"code"` } type Files struct { Filename string `json:"filename"` Url string `json:"url"` } type Urls struct { Url string `json:"url"` } type OralText struct { Info string `json:"info"` } type References struct { Type string `json:"type"` Source string `json:"source"` DocID string `json:"doc_id"` Title string `json:"title"` Content string `json:"content"` Extra map[string]any `json:"extra"` } type Image struct { Filename string `json:"filename"` Url string `json:"url"` Byte []byte `json:"byte"` } type Chart struct { Type string `json:"type"` Data string `json:"data"` } type Audio struct { Filename string `json:"filename"` Url string `json:"url"` Byte []byte `json:"byte"` } type PlanStep struct { Name string `json:"name"` Arguments map[string]any `json:"arguments"` Thought string `json:"thought"` } type Plan struct { Detail string `json:"detail"` Steps []PlanStep `json:"steps"` } type FunctionCall struct { Thought string `json:"thought"` Name string `json:"name"` Arguments map[string]any `json:"arguments"` } type Json struct { Data string `json:"data"` } type ComponentClientIterator interface { // Next 获取处理结果,如果返回error不为空,迭代器自动失效,不允许再调用此方法 Next() (*ComponentRunResponse, error) } type ComponentClientStreamIterator struct { requestID string r *sseReader body io.ReadCloser } func (t *ComponentClientStreamIterator) Next() (*ComponentRunResponse, error) { data, err := t.r.ReadMessageLine() if err != nil && !(err == io.EOF) { t.body.Close() return nil, fmt.Errorf("requestID=%s, err=%v", t.requestID, err) } if err != nil && err == io.EOF { t.body.Close() return nil, err } if strings.HasPrefix(string(data), "data:") { var resp ComponentRunResponse if err := json.Unmarshal(data[5:], &resp); err != nil { t.body.Close() return nil, fmt.Errorf("requestID=%s, err=%v", t.requestID, err) } return &resp, nil } // 非SSE格式关闭连接,并返回数据 t.body.Close() return nil, fmt.Errorf("requestID=%s, body=%s", t.requestID, string(data)) } // ComponentClientOnceIterator 非流式返回时对应的迭代器,只可迭代一次 type ComponentClientOnceIterator struct { body io.ReadCloser requestID string } func (t *ComponentClientOnceIterator) Next() (*ComponentRunResponse, error) { data, err := io.ReadAll(t.body) if err != nil { return nil, fmt.Errorf("requestID=%s, err=%v", t.requestID, err) } defer t.body.Close() var resp ComponentRunResponse if err := json.Unmarshal(data, &resp); err != nil { return nil, fmt.Errorf("requestID=%s, err=%v", t.requestID, err) } return &resp, nil } ================================================ FILE: go/appbuilder/component_client_test.go ================================================ // Copyright (c) 2024 Baidu, Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package appbuilder import ( "bytes" "fmt" "os" "testing" ) func TestComponentClient(t *testing.T) { var logBuffer bytes.Buffer // 设置环境变量 os.Setenv("APPBUILDER_LOGLEVEL", "DEBUG") os.Setenv("APPBUILDER_LOGFILE", "") // 测试逻辑 config, err := NewSDKConfig("", "") if err != nil { t.Logf("%s========== FAIL: %s ==========%s", "\033[31m", t.Name(), "\033[0m") t.Fatalf("new http client config failed: %v", err) } componentID := "44205c67-3980-41f7-aad4-37357b577fd0" client, err := NewComponentClient(config) if err != nil { t.Logf("%s========== FAIL: %s ==========%s", "\033[31m", t.Name(), "\033[0m") t.Fatalf("new ComponentClient instance failed") } parameters := map[string]any{ SysOriginQuery: "北京景点推荐", } i, err := client.Run(componentID, "latest", "", false, parameters) if err != nil { t.Logf("%s========== FAIL: %s ==========%s", "\033[31m", t.Name(), "\033[0m") t.Fatalf("run component failed: %v", err) } // test result for answer, err := i.Next(); err == nil; answer, err = i.Next() { data := answer.Content[0].Text if data == nil { t.Logf("%s========== FAIL: %s ==========%s", "\033[31m", t.Name(), "\033[0m") t.Fatalf("run component failed: data is nil") } } i2, err := client.Run(componentID, "latest", "", true, parameters) if err != nil { t.Logf("%s========== FAIL: %s ==========%s", "\033[31m", t.Name(), "\033[0m") t.Fatalf("run component failed: %v", err) } // test stream result var answerText any for answer, err := i2.Next(); err == nil; answer, err = i2.Next() { if len(answer.Content) == 0 { continue } answerText = answer.Content[0].Text } if answerText == nil { t.Logf("%s========== FAIL: %s ==========%s", "\033[31m", t.Name(), "\033[0m") t.Fatalf("run component failed: data is nil") } // 如果测试失败,则输出缓冲区中的日志 if t.Failed() { fmt.Println(logBuffer.String()) } else { // else 紧跟在右大括号后面 // 测试通过,打印文件名和测试函数名 t.Logf("%s========== OK: %s ==========%s", "\033[32m", t.Name(), "\033[0m") } } func TestComponentClientHeader(t *testing.T) { os.Setenv("APPBUILDER_LOGLEVEL", "DEBUG") config, err := NewSDKConfig("", "") if err != nil { t.Logf("%s========== FAIL: %s ==========%s", "\033[31m", t.Name(), "\033[0m") t.Fatalf("new http client config failed: %v", err) } componentID := "c-wf-a39ee06c-808f-4a19-9f5f-544044283749" parameters := map[string]any{ SysOriginQuery: "梦到巨人,是怎么回事,请仔细分析,写一篇不少于1000字的文章", } componentClient, err := NewComponentClient(config) if err != nil { t.Error(err) return } ret, err := componentClient.Run(componentID, "latest", "", false, parameters) if err != nil { t.Error(err) return } for answer, err := ret.Next(); err == nil; answer, err = ret.Next() { t.Log(answer.Content[0].Text["info"]) } ret2, err := componentClient.Run(componentID, "latest", "", true, parameters) if err != nil { t.Error(err) return } for answer, err := ret2.Next(); err == nil; answer, err = ret2.Next() { if len(answer.Content) == 0 { continue } t.Log(answer.Content[0].Text["info"]) } } ================================================ FILE: go/appbuilder/config.go ================================================ // Copyright (c) 2024 Baidu, Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package appbuilder import ( "fmt" "io" "log" "net/http" "net/url" "os" "path" "strings" "github.com/google/uuid" ) const ( GatewayURL = "GATEWAY_URL" GatewayURLV2 = "GATEWAY_URL_V2" SecretKey = "APPBUILDER_TOKEN" ConsoleOpenAPIVersion = "CONSOLE_OPENAPI_VERSION" ConsoleOpenAPIPrefix = "CONSOLE_OPENAPI_PREFIX" SecretKeyPrefix = "SECRET_KEY_PREFIX" DatasetID = "DATASET_ID" SecretKeyV3 = "APPBUILDER_TOKEN_V3" DatasetIDV3 = "DATASET_ID_V3" DocumentIDV3 = "DOCUMENT_ID_V3" DefaultSecretKeyPrefix = "Bearer" DefaultGatewayURL = "https://appbuilder.baidu.com" DefaultGatewayURLV2 = "https://qianfan.baidubce.com" DefaultConsoleOpenAPIVersion = "/v2" DefaultConsoleOpenAPIPrefix = "" ) type SDKConfig struct { GatewayURL string GatewayURLV2 string ConsoleOpenAPIVersion string ConsoleOpenAPIPrefix string SecretKey string HTTPClient HTTPClient // custom HTTP Client, optional logger *log.Logger } func NewSDKConfig(gatewayURL, secretKey string) (*SDKConfig, error) { gatewayURL = getEnvWithDefault(GatewayURL, gatewayURL, DefaultGatewayURL) gatewayURLV2 := getEnvWithDefault(GatewayURLV2, "", DefaultGatewayURLV2) openAPIVersion := getEnvWithDefault(ConsoleOpenAPIVersion, "", DefaultConsoleOpenAPIVersion) openAPIPrefix := getEnvWithDefault(ConsoleOpenAPIPrefix, "", DefaultConsoleOpenAPIPrefix) secretKey = getEnvWithDefault(SecretKey, secretKey, "") if len(secretKey) == 0 { log.Println("Error: secret key is empty") } secretKeyPrefix := getEnvWithDefault(SecretKeyPrefix, "", DefaultSecretKeyPrefix) if !strings.HasPrefix(secretKey, secretKeyPrefix) { secretKey = secretKeyPrefix + " " + secretKey } sdkConfig := &SDKConfig{ GatewayURL: gatewayURL, GatewayURLV2: gatewayURLV2, ConsoleOpenAPIVersion: openAPIVersion, ConsoleOpenAPIPrefix: openAPIPrefix, SecretKey: secretKey, } logFile := os.Getenv("APPBUILDER_LOGFILE") if len(logFile) > 0 { f, err := os.OpenFile(logFile, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0644) if err != nil { sdkConfig.logger = log.New(os.Stdout, "", log.LstdFlags) } else { sdkConfig.logger = log.New(f, "", log.LstdFlags) } } else { sdkConfig.logger = log.New(os.Stdout, "", log.LstdFlags) } return sdkConfig, nil } func getEnvWithDefault(key, paramValue, defaultValue string) string { if paramValue != "" { return paramValue } v := os.Getenv(key) if v == "" { return defaultValue } return v } func (t *SDKConfig) AuthHeader() http.Header { header := t.authHeader() header.Set("X-Appbuilder-Authorization", t.SecretKey) t.logger.Printf("Auth Header %v", header) return header } // AuthHeaderV2 适配OpenAPI,当前仅AgentBuilder使用 func (t *SDKConfig) AuthHeaderV2() http.Header { header := t.authHeader() header.Set("Authorization", t.SecretKey) t.logger.Printf("Auth Header %v", header) return header } func (t *SDKConfig) authHeader() http.Header { header := make(http.Header) platform := os.Getenv("APPBUILDER_SDK_PLATFORM") if platform == "" { platform = "unknown" } header.Set("X-Appbuilder-Origin", "appbuilder_sdk") header.Set("X-Appbuilder-Sdk-Config", "{\"appbuilder_sdk_version\":\"1.1.0\",\"appbuilder_sdk_language\":\"go\",\"appbuilder_sdk_platform\":\""+platform+"\"}") header.Set("X-Appbuilder-Request-Id", uuid.New().String()) return header } func (t *SDKConfig) ServiceURL(suffix string) (*url.URL, error) { // 解析 GatewayURL parsedURL, err := url.Parse(t.GatewayURL) if err != nil { return nil, err } // 使用 path.Join 拼接路径 parsedURL.Path = path.Join(parsedURL.Path, suffix) // 将路径直接解析为最终 URL endpoint, err := url.Parse(suffix) if err != nil { return nil, err } // 解析相对路径 parsedURL = parsedURL.ResolveReference(endpoint) // 返回拼接后的 URL return parsedURL, nil } // ServiceURLV2 适配OpenAPI,当前仅AppbuilderClient使用 func (t *SDKConfig) ServiceURLV2(suffix string) (*url.URL, error) { suffix = path.Join(t.ConsoleOpenAPIPrefix, t.ConsoleOpenAPIVersion, suffix) return t.formatURL(t.GatewayURLV2, suffix) } func (t *SDKConfig) formatURL(absolutePath, suffix string) (*url.URL, error) { t.logger.Printf("Service URL %s", absolutePath) url, err := url.Parse(absolutePath) if err != nil { return nil, err } endpoint, err := url.Parse(suffix) if err != nil { return nil, err } url = url.ResolveReference(endpoint) return url, nil } type nopCloser struct { io.Reader } func (nopCloser) Close() error { return nil } func NopCloser(r io.Reader) io.ReadCloser { return nopCloser{Reader: r} } func (t *SDKConfig) BuildCurlCommand(req *http.Request) { curlCmd := fmt.Sprintf("curl -X %s -L '%v' \\\n", req.Method, req.URL.String()) for k, v := range req.Header { header := fmt.Sprintf("-H '%v: %v' \\\n", k, v[0]) curlCmd = fmt.Sprintf("%v %v", curlCmd, header) } if req.Method == "POST" { bodyBytes, err := io.ReadAll(req.Body) if err != nil { t.logger.Println("Failed to read request body:", err) return } req.Body.Close() req.Body = NopCloser(strings.NewReader(string(bodyBytes))) body := fmt.Sprintf("-d '%v'", string(bodyBytes)) curlCmd = fmt.Sprintf("%v %v", curlCmd, body) } else if req.Method == "GET" || req.Method == "DELETE" { curlCmd = strings.TrimSuffix(curlCmd, " \\\n") } fmt.Println("\n" + curlCmd + "\n") } ================================================ FILE: go/appbuilder/dataset.go ================================================ // Copyright (c) 2024 Baidu, Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package appbuilder import ( "bytes" "encoding/json" "errors" "fmt" "io" "mime/multipart" "net/http" "os" "path/filepath" "time" ) // Deprecated: 已废弃,请使用 NewKnowledgeBase func NewDataset(config *SDKConfig) (*Dataset, error) { if config == nil { return nil, errors.New("invalid config") } client := config.HTTPClient if client == nil { client = &http.Client{Timeout: 60 * time.Second} } return &Dataset{sdkConfig: config, client: client}, nil } type Dataset struct { sdkConfig *SDKConfig client HTTPClient } func (t *Dataset) Create(name string) (string, error) { request := http.Request{} header := t.sdkConfig.AuthHeader() serviceURL, err := t.sdkConfig.ServiceURL("/api/v1/ai_engine/agi_platform/v1/datasets/create") if err != nil { return "", err } request.URL = serviceURL request.Method = "POST" header.Set("Content-Type", "application/json") request.Header = header req := map[string]string{"name": name} data, _ := json.Marshal(req) request.Body = NopCloser(bytes.NewReader(data)) t.sdkConfig.BuildCurlCommand(&request) resp, err := t.client.Do(&request) if err != nil { return "", err } defer resp.Body.Close() requestID, err := checkHTTPResponse(resp) if err != nil { return "", fmt.Errorf("requestID=%s, err=%v", requestID, err) } data, err = io.ReadAll(resp.Body) if err != nil { return "", fmt.Errorf("requestID=%s, err=%v", requestID, err) } rsp := DatasetResponse{} if err := json.Unmarshal(data, &rsp); err != nil { return "", fmt.Errorf("requestID=%s, err=%v", requestID, err) } if rsp.Code != 0 { return "", fmt.Errorf("requestID=%s, content=%v", requestID, string(data)) } return rsp.Result["id"].(string), nil } func (t *Dataset) BatchUploadLocaleFile(datasetID string, localFilePaths []string) ([]string, error) { var fileIDs []string for _, localFilePath := range localFilePaths { fileID, err := t.uploadLocalFile(localFilePath) if err != nil { return nil, err } fileIDs = append(fileIDs, fileID) } documentIDS, err := t.addFileToDataset(datasetID, fileIDs) if err != nil { return nil, err } return documentIDS, nil } func (t *Dataset) UploadLocalFile(datasetID string, localFilePath string) (string, error) { fileID, err := t.uploadLocalFile(localFilePath) if err != nil { return "", err } documentIDs, err := t.addFileToDataset(datasetID, []string{fileID}) if err != nil { return "", fmt.Errorf("add file failed: %v", err) } return documentIDs[0], nil } func (t *Dataset) uploadLocalFile(localFilePath string) (string, error) { var data bytes.Buffer w := multipart.NewWriter(&data) file, err := os.Open(localFilePath) if err != nil { return "", err } defer file.Close() filePart, _ := w.CreateFormFile("file", filepath.Base(file.Name())) if _, err := io.Copy(filePart, file); err != nil { return "", err } w.Close() request := http.Request{} header := t.sdkConfig.AuthHeader() serviceURL, err := t.sdkConfig.ServiceURL("/api/v1/ai_engine/agi_platform/v1/datasets/files/upload") if err != nil { return "", err } request.URL = serviceURL request.Method = "POST" header.Set("Content-Type", w.FormDataContentType()) request.Header = header request.Body = NopCloser(bytes.NewReader(data.Bytes())) resp, err := t.client.Do(&request) if err != nil { return "", err } requestID, err := checkHTTPResponse(resp) if err != nil { return "", fmt.Errorf("requestID=%s, err=%v", requestID, err) } respData, err := io.ReadAll(resp.Body) if err != nil { return "", fmt.Errorf("requestID=%s, err=%v", requestID, err) } rsp := DatasetResponse{} if err := json.Unmarshal(respData, &rsp); err != nil { return "", fmt.Errorf("requestID=%s, err=%v", requestID, err) } if rsp.Code != 0 { return "", fmt.Errorf("requestID=%s, content=%s", requestID, string(respData)) } fileID := rsp.Result["id"].(string) return fileID, nil } func (t *Dataset) addFileToDataset(datasetID string, fileID []string) ([]string, error) { header := t.sdkConfig.AuthHeader() serviceURL, err := t.sdkConfig.ServiceURL("/api/v1/ai_engine/agi_platform/v1/datasets/documents") if err != nil { return nil, err } request := http.Request{} request.URL = serviceURL request.Method = "POST" header.Set("Content-Type", "application/json") request.Header = header m := map[string]any{ "file_ids": fileID, "dataset_id": datasetID} data, _ := json.Marshal(m) request.Body = NopCloser(bytes.NewReader(data)) t.sdkConfig.BuildCurlCommand(&request) resp, err := t.client.Do(&request) if err != nil { return nil, err } requestID, err := checkHTTPResponse(resp) if err != nil { return nil, fmt.Errorf("requestID=%s, err=%v", requestID, err) } respData, err := io.ReadAll(resp.Body) if err != nil { return nil, fmt.Errorf("requestID=%s, err=%v", requestID, err) } rsp := DatasetBindResponse{} if err := json.Unmarshal(respData, &rsp); err != nil { return nil, fmt.Errorf("requestID=%s, err=%v", requestID, err) } if rsp.Code != 0 { return nil, fmt.Errorf("requestID=%s, content=%s", requestID, string(respData)) } return rsp.Result.DocumentIDs, nil } func (t *Dataset) ListDocument(datasetID string, page int, limit int, keyword string) (*ListDocumentResponse, error) { header := t.sdkConfig.AuthHeader() serviceURL, err := t.sdkConfig.ServiceURL("/api/v1/ai_engine/agi_platform/v1/datasets/documents/list_page") if err != nil { return nil, err } request := http.Request{} request.URL = serviceURL request.Method = "POST" header.Set("Content-Type", "application/json") request.Header = header m := map[string]any{ "dataset_id": datasetID, "page": page, "limit": limit, "keyword": keyword, } data, _ := json.Marshal(m) request.Body = NopCloser(bytes.NewReader(data)) t.sdkConfig.BuildCurlCommand(&request) resp, err := t.client.Do(&request) if err != nil { return nil, err } defer resp.Body.Close() requestID, err := checkHTTPResponse(resp) if err != nil { return nil, fmt.Errorf("requestID=%s, err=%v", requestID, err) } respData, err := io.ReadAll(resp.Body) if err != nil { return nil, fmt.Errorf("requestID=%s, err=%v", requestID, err) } rsp := ListDocumentResponse{} if err := json.Unmarshal(respData, &rsp); err != nil { return nil, fmt.Errorf("requestID=%s, err=%v", requestID, err) } if rsp.Code != 0 { return nil, fmt.Errorf("requestID=%s, content=%s", requestID, string(respData)) } return &rsp, nil } func (t *Dataset) DeleteDocument(datasetID, documentID string) error { fmt.Println(datasetID, " ", documentID) header := t.sdkConfig.AuthHeader() serviceURL, err := t.sdkConfig.ServiceURL("/api/v1/ai_engine/agi_platform/v1/datasets/document/delete") if err != nil { return err } request := http.Request{} request.URL = serviceURL request.Method = "POST" header.Set("Content-Type", "application/json") request.Header = header m := map[string]string{ "dataset_id": datasetID, "document_id": documentID, } data, _ := json.Marshal(m) request.Body = NopCloser(bytes.NewReader(data)) resp, err := http.DefaultClient.Do(&request) if err != nil { return err } defer resp.Body.Close() requestID, err := checkHTTPResponse(resp) if err != nil { return fmt.Errorf("requestID=%s, err=%v", requestID, err) } return nil } ================================================ FILE: go/appbuilder/dataset_data.go ================================================ // Copyright (c) 2024 Baidu, Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package appbuilder type DatasetResponse struct { Code int `json:"code"` Message string `json:"message"` Result map[string]any `json:"result"` } type DatasetBindResponse struct { Code int `json:"code"` Message string `json:"message"` Result DatasetBindResult `json:"result"` } type DatasetBindResult struct { DocumentIDs []string `json:"document_ids"` } type ListDocumentResponse struct { Code int `json:"code"` Message string `json:"message"` Result ListDocumentResponseResult `json:"result"` } type ListDocumentResponseResult struct { HasMore bool `json:"has_more"` Limit int `json:"limit"` Total int `json:"total"` Page int `json:"page"` Data []FileInfo `json:"data"` } type FileInfo struct { ID string `json:"id"` Name string `json:"name"` } ================================================ FILE: go/appbuilder/dataset_test.go ================================================ // Copyright (c) 2024 Baidu, Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package appbuilder import ( // "bytes" // "fmt" "os" "testing" ) func TestDatasetError(t *testing.T) { t.Parallel() // 并发运行 // 测试逻辑 config, err := NewSDKConfig("", os.Getenv(SecretKeyV3)) if err != nil { t.Logf("%s========== FAIL: %s ==========%s", "\033[31m", t.Name(), "\033[0m") t.Fatalf("new http client config failed: %v", err) } var GatewayURL = config.GatewayURLV2 dataset, _ := NewDataset(config) //dataset.Create测试1 无效的ServiceURLV2 dataset.sdkConfig.GatewayURLV2 = "://invalid-url" _, err = dataset.Create("测试集合") if err == nil { } // 测试 UploadLocalFile 2: t.client.Do 错误 dataset.sdkConfig.GatewayURLV2 = "http://192.0.2.1" _, err = dataset.Create("测试集合") if err == nil { } // 测试 UploadLocalFile 4: 错误的 HTTP 响应 dataset.client = &MockHTTPClient{} dataset.sdkConfig.GatewayURLV2 = GatewayURL _, err = dataset.Create("测试集合") if err == nil { } // 测试 UploadLocalFile 5: 模拟读取 body 时发生错误 dataset.client = &FaultyHTTPClient{} dataset.sdkConfig.GatewayURLV2 = GatewayURL _, err = dataset.Create("测试集合") if err == nil { } //NewDataset测试1 config == nil dataset, _ = NewDataset(nil) //NewDataset测试2 client == nil config.HTTPClient = nil dataset, _ = NewDataset(config) } // func TestDataset(t *testing.T) { // t.Parallel() // 并发运行 // // 创建缓冲区来存储日志 // var logBuffer bytes.Buffer // // 定义一个日志函数,将日志写入缓冲区 // log := func(format string, args ...interface{}) { // fmt.Fprintf(&logBuffer, format+"\n", args...) // } // // 测试逻辑 // config, err := NewSDKConfig("", os.Getenv(SecretKeyV3)) // if err != nil { // t.Logf("%s========== FAIL: %s ==========%s", "\033[31m", t.Name(), "\033[0m") // t.Fatalf("new http client config failed: %v", err) // } // dataset, _ := NewDataset(config) // datasetID, err := dataset.Create("测试集合") // if err != nil { // datasetID = os.Getenv(SecretKeyV3) // } // _, err = dataset.ListDocument(datasetID, 1, 10, "") // if err != nil { // t.Logf("%s========== FAIL: %s ==========%s", "\033[31m", t.Name(), "\033[0m") // t.Fatalf("list document failed: %v", err) // } // log("Listed documents for dataset ID: %s", datasetID) // // 如果测试失败,则输出缓冲区中的日志 // if t.Failed() { // t.Logf("%s========== FAIL: %s ==========%s", "\033[31m", t.Name(), "\033[0m") // fmt.Println(logBuffer.String()) // } else { // else 紧跟在右大括号后面 // // 测试通过,打印文件名和测试函数名 // t.Logf("%s========== OK: %s ==========%s", "\033[32m", t.Name(), "\033[0m") // } // } ================================================ FILE: go/appbuilder/go.mod ================================================ module github.com/baidubce/app-builder/go/appbuilder go 1.18 require github.com/google/uuid v1.6.0 ================================================ FILE: go/appbuilder/go.sum ================================================ github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0= github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= ================================================ FILE: go/appbuilder/knowledge_base.go ================================================ // Copyright (c) 2024 Baidu, Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package appbuilder import ( "bytes" "encoding/json" "errors" "fmt" "io" "mime/multipart" "net/http" "net/url" "os" "path/filepath" "strconv" "time" "github.com/google/uuid" ) func NewKnowledgeBase(config *SDKConfig) (*KnowledgeBase, error) { if config == nil { return nil, errors.New("invalid config") } client := config.HTTPClient if client == nil { client = &http.Client{Timeout: 60 * time.Second} } return &KnowledgeBase{sdkConfig: config, client: client}, nil } func NewKnowledgeBaseWithKnowledgeBaseID(knowledgeBaseID string, config *SDKConfig) (*KnowledgeBase, error) { if config == nil { return nil, errors.New("invalid config") } client := config.HTTPClient if client == nil { client = &http.Client{Timeout: 60 * time.Second} } return &KnowledgeBase{knowledgeBaseID: knowledgeBaseID, sdkConfig: config, client: client}, nil } type KnowledgeBase struct { knowledgeBaseID string sdkConfig *SDKConfig client HTTPClient } func (t *KnowledgeBase) CreateDocument(req CreateDocumentRequest) (CreateDocumentResponse, error) { request := http.Request{} header := t.sdkConfig.AuthHeaderV2() if req.ClientToken == "" { req.ClientToken = uuid.New().String() } serviceURL, err := t.sdkConfig.ServiceURLV2("/knowledge_base/document?clientToken=" + req.ClientToken) if err != nil { return CreateDocumentResponse{}, err } request.URL = serviceURL request.Method = "POST" header.Set("Content-Type", "application/json") request.Header = header data, _ := json.Marshal(req) request.Body = NopCloser(bytes.NewReader(data)) t.sdkConfig.BuildCurlCommand(&request) resp, err := t.client.Do(&request) if err != nil { return CreateDocumentResponse{}, err } defer resp.Body.Close() requestID, err := checkHTTPResponse(resp) if err != nil { return CreateDocumentResponse{}, fmt.Errorf("requestID=%s, err=%v", requestID, err) } data, err = io.ReadAll(resp.Body) if err != nil { return CreateDocumentResponse{}, fmt.Errorf("requestID=%s, err=%v", requestID, err) } rsp := CreateDocumentResponse{} if err := json.Unmarshal(data, &rsp); err != nil { return CreateDocumentResponse{}, fmt.Errorf("requestID=%s, err=%v", requestID, err) } if rsp.Code != "" { return CreateDocumentResponse{}, fmt.Errorf("requestID=%s, code=%s, message=%s", requestID, rsp.Code, rsp.Message) } return rsp, nil } func (t *KnowledgeBase) DeleteDocument(req DeleteDocumentRequest) error { header := t.sdkConfig.AuthHeaderV2() if req.ClientToken == "" { req.ClientToken = uuid.New().String() } serviceURL, err := t.sdkConfig.ServiceURLV2("/knowledge_base/document?clientToken=" + req.ClientToken) if err != nil { return err } reqMap := make(map[string]any) reqJson, _ := json.Marshal(req) json.Unmarshal(reqJson, &reqMap) params := url.Values{} for key, value := range reqMap { switch v := value.(type) { case float64: params.Add(key, strconv.Itoa(int(v))) case string: if v == "" { continue } params.Add(key, v) } } serviceURL.RawQuery = params.Encode() request := http.Request{} request.URL = serviceURL request.Method = "DELETE" header.Set("Content-Type", "application/json") request.Header = header t.sdkConfig.BuildCurlCommand(&request) resp, err := http.DefaultClient.Do(&request) if err != nil { return err } defer resp.Body.Close() requestID, err := checkHTTPResponse(resp) if err != nil { return fmt.Errorf("requestID=%s, err=%v", requestID, err) } return nil } // Deprecated: use DescribeDocuments instead func (t *KnowledgeBase) GetDocumentList(req GetDocumentListRequest) (*GetDocumentListResponse, error) { header := t.sdkConfig.AuthHeaderV2() serviceURL, err := t.sdkConfig.ServiceURLV2("/knowledge_base/documents") if err != nil { return nil, err } reqMap := make(map[string]any) reqJson, _ := json.Marshal(req) json.Unmarshal(reqJson, &reqMap) params := url.Values{} for key, value := range reqMap { switch v := value.(type) { case float64: params.Add(key, strconv.Itoa(int(v))) case string: if v == "" { continue } params.Add(key, v) } } serviceURL.RawQuery = params.Encode() request := http.Request{} request.URL = serviceURL request.Method = "GET" header.Set("Content-Type", "application/json") request.Header = header data, _ := json.Marshal(req) request.Body = NopCloser(bytes.NewReader(data)) t.sdkConfig.BuildCurlCommand(&request) resp, err := t.client.Do(&request) if err != nil { return nil, err } defer resp.Body.Close() requestID, err := checkHTTPResponse(resp) if err != nil { return nil, fmt.Errorf("requestID=%s, err=%v", requestID, err) } respData, err := io.ReadAll(resp.Body) if err != nil { return nil, fmt.Errorf("requestID=%s, err=%v", requestID, err) } rsp := GetDocumentListResponse{} if err := json.Unmarshal(respData, &rsp); err != nil { return nil, fmt.Errorf("requestID=%s, err=%v", requestID, err) } if rsp.Code != "" { return nil, fmt.Errorf("requestID=%s, content=%s", requestID, string(respData)) } return &rsp, nil } func (t *KnowledgeBase) DescribeDocuments(req DescribeDocumentsRequest) (DescribeDocumentsResponse, error) { request := http.Request{} header := t.sdkConfig.AuthHeaderV2() serviceURL, err := t.sdkConfig.ServiceURLV2("/knowledgeBase?Action=DescribeDocuments") if err != nil { return DescribeDocumentsResponse{}, err } if req.KnowledgeBaseID == "" && t.knowledgeBaseID != "" { req.KnowledgeBaseID = t.knowledgeBaseID } request.URL = serviceURL request.Method = "POST" header.Set("Content-Type", "application/json") request.Header = header data, _ := json.Marshal(req) request.Body = NopCloser(bytes.NewReader(data)) t.sdkConfig.BuildCurlCommand(&request) resp, err := t.client.Do(&request) if err != nil { return DescribeDocumentsResponse{}, err } defer resp.Body.Close() requestID, err := checkHTTPResponse(resp) if err != nil { return DescribeDocumentsResponse{}, fmt.Errorf("requestID=%s, err=%v", requestID, err) } data, err = io.ReadAll(resp.Body) if err != nil { return DescribeDocumentsResponse{}, fmt.Errorf("requestID=%s, err=%v", requestID, err) } rsp := DescribeDocumentsResponse{} if err := json.Unmarshal(data, &rsp); err != nil { return DescribeDocumentsResponse{}, fmt.Errorf("requestID=%s, err=%v", requestID, err) } return rsp, nil } // Deprecated: 此功能即将废弃 func (t *KnowledgeBase) UploadFile(localFilePath string) (string, error) { var data bytes.Buffer w := multipart.NewWriter(&data) file, err := os.Open(localFilePath) if err != nil { return "", err } defer file.Close() filePart, _ := w.CreateFormFile("file", filepath.Base(file.Name())) if _, err := io.Copy(filePart, file); err != nil { return "", err } w.Close() request := http.Request{} header := t.sdkConfig.AuthHeaderV2() serviceURL, err := t.sdkConfig.ServiceURLV2("/file") if err != nil { return "", err } request.URL = serviceURL request.Method = "POST" header.Set("Content-Type", w.FormDataContentType()) request.Header = header request.Body = NopCloser(bytes.NewReader(data.Bytes())) resp, err := t.client.Do(&request) if err != nil { return "", err } requestID, err := checkHTTPResponse(resp) if err != nil { return "", fmt.Errorf("requestID=%s, err=%v", requestID, err) } respData, err := io.ReadAll(resp.Body) if err != nil { return "", fmt.Errorf("requestID=%s, err=%v", requestID, err) } rsp := UploadFileResponse{} if err := json.Unmarshal(respData, &rsp); err != nil { return "", fmt.Errorf("requestID=%s, err=%v", requestID, err) } if rsp.Code != "" { return "", fmt.Errorf("requestID=%s, content=%s", requestID, string(respData)) } fileID := rsp.FileID return fileID, nil } func (t *KnowledgeBase) CreateKnowledgeBase(req KnowledgeBaseDetail) (KnowledgeBaseDetail, error) { request := http.Request{} header := t.sdkConfig.AuthHeaderV2() if req.ClientToken == "" { req.ClientToken = uuid.New().String() } serviceURL, err := t.sdkConfig.ServiceURLV2("/knowledgeBase?Action=CreateKnowledgeBase&clientToken=" + req.ClientToken) if err != nil { return KnowledgeBaseDetail{}, err } request.URL = serviceURL request.Method = "POST" header.Set("Content-Type", "application/json") request.Header = header data, _ := json.Marshal(req) request.Body = NopCloser(bytes.NewReader(data)) t.sdkConfig.BuildCurlCommand(&request) resp, err := t.client.Do(&request) if err != nil { return KnowledgeBaseDetail{}, err } defer resp.Body.Close() requestID, err := checkHTTPResponse(resp) if err != nil { return KnowledgeBaseDetail{}, fmt.Errorf("requestID=%s, err=%v", requestID, err) } data, err = io.ReadAll(resp.Body) if err != nil { return KnowledgeBaseDetail{}, fmt.Errorf("requestID=%s, err=%v", requestID, err) } rsp := KnowledgeBaseDetail{} if err := json.Unmarshal(data, &rsp); err != nil { return KnowledgeBaseDetail{}, fmt.Errorf("requestID=%s, err=%v", requestID, err) } return rsp, nil } func (t *KnowledgeBase) GetKnowledgeBaseDetail(knowledgeBaseID string) (KnowledgeBaseDetail, error) { request := http.Request{} header := t.sdkConfig.AuthHeaderV2() serviceURL, err := t.sdkConfig.ServiceURLV2("/knowledgeBase?Action=DescribeKnowledgeBase") if err != nil { return KnowledgeBaseDetail{}, err } req := KnowledgeBaseDetail{} req.ID = knowledgeBaseID request.URL = serviceURL request.Method = "POST" header.Set("Content-Type", "application/json") request.Header = header data, _ := json.Marshal(req) request.Body = NopCloser(bytes.NewReader(data)) t.sdkConfig.BuildCurlCommand(&request) resp, err := t.client.Do(&request) if err != nil { return KnowledgeBaseDetail{}, err } defer resp.Body.Close() requestID, err := checkHTTPResponse(resp) if err != nil { return KnowledgeBaseDetail{}, fmt.Errorf("requestID=%s, err=%v", requestID, err) } data, err = io.ReadAll(resp.Body) if err != nil { return KnowledgeBaseDetail{}, fmt.Errorf("requestID=%s, err=%v", requestID, err) } rsp := KnowledgeBaseDetail{} if err := json.Unmarshal(data, &rsp); err != nil { return KnowledgeBaseDetail{}, fmt.Errorf("requestID=%s, err=%v", requestID, err) } return rsp, nil } func (t *KnowledgeBase) GetKnowledgeBaseList(req GetKnowledgeBaseListRequest) (GetKnowledgeBaseListResponse, error) { request := http.Request{} header := t.sdkConfig.AuthHeaderV2() serviceURL, err := t.sdkConfig.ServiceURLV2("/knowledgeBase?Action=DescribeKnowledgeBases") if err != nil { return GetKnowledgeBaseListResponse{}, err } request.URL = serviceURL request.Method = "POST" header.Set("Content-Type", "application/json") request.Header = header data, _ := json.Marshal(req) request.Body = NopCloser(bytes.NewReader(data)) t.sdkConfig.BuildCurlCommand(&request) resp, err := t.client.Do(&request) if err != nil { return GetKnowledgeBaseListResponse{}, err } defer resp.Body.Close() requestID, err := checkHTTPResponse(resp) if err != nil { return GetKnowledgeBaseListResponse{}, fmt.Errorf("requestID=%s, err=%v", requestID, err) } data, err = io.ReadAll(resp.Body) if err != nil { return GetKnowledgeBaseListResponse{}, fmt.Errorf("requestID=%s, err=%v", requestID, err) } rsp := GetKnowledgeBaseListResponse{} if err := json.Unmarshal(data, &rsp); err != nil { return GetKnowledgeBaseListResponse{}, fmt.Errorf("requestID=%s, err=%v", requestID, err) } return rsp, nil } func (t *KnowledgeBase) ModifyKnowledgeBase(req ModifyKnowlegeBaseRequest) error { request := http.Request{} header := t.sdkConfig.AuthHeaderV2() if req.ClientToken == "" { req.ClientToken = uuid.New().String() } serviceURL, err := t.sdkConfig.ServiceURLV2("/knowledgeBase?Action=ModifyKnowledgeBase&clientToken=" + req.ClientToken) if err != nil { return err } request.URL = serviceURL request.Method = "POST" header.Set("Content-Type", "application/json") request.Header = header data, _ := json.Marshal(req) request.Body = NopCloser(bytes.NewReader(data)) t.sdkConfig.BuildCurlCommand(&request) resp, err := t.client.Do(&request) if err != nil { return err } defer resp.Body.Close() requestID, err := checkHTTPResponse(resp) if err != nil { return fmt.Errorf("requestID=%s, err=%v", requestID, err) } _, err = io.ReadAll(resp.Body) if err != nil { return fmt.Errorf("requestID=%s, err=%v", requestID, err) } return nil } func (t *KnowledgeBase) DeleteKnowledgeBase(knowledgeBaseID string) error { return t.deleteKnowledgeBase(knowledgeBaseID, "") } func (t *KnowledgeBase) DeleteKnowledgeBaseWithReq(req DeleteKnowlegeBaseRequest) error { return t.deleteKnowledgeBase(req.ID, req.ClientToken) } func (t *KnowledgeBase) deleteKnowledgeBase(knowledgeBaseID string, clientToken string) error { request := http.Request{} header := t.sdkConfig.AuthHeaderV2() if clientToken == "" { clientToken = uuid.New().String() } serviceURL, err := t.sdkConfig.ServiceURLV2("/knowledgeBase?Action=DeleteKnowledgeBase&clientToken=" + clientToken) if err != nil { return err } req := KnowledgeBaseDetail{} req.ID = knowledgeBaseID request.URL = serviceURL request.Method = "POST" header.Set("Content-Type", "application/json") request.Header = header data, _ := json.Marshal(req) request.Body = NopCloser(bytes.NewReader(data)) t.sdkConfig.BuildCurlCommand(&request) resp, err := t.client.Do(&request) if err != nil { return err } defer resp.Body.Close() requestID, err := checkHTTPResponse(resp) if err != nil { return fmt.Errorf("requestID=%s, err=%v", requestID, err) } _, err = io.ReadAll(resp.Body) if err != nil { return fmt.Errorf("requestID=%s, err=%v", requestID, err) } return nil } // Deprecated: 此功能即将废弃 func (t *KnowledgeBase) CreateDocuments(req CreateDocumentsRequest) error { request := http.Request{} header := t.sdkConfig.AuthHeaderV2() if req.ClientToken == "" { req.ClientToken = uuid.New().String() } serviceURL, err := t.sdkConfig.ServiceURLV2("/knowledgeBase?Action=CreateDocuments&clientToken=" + req.ClientToken) if err != nil { return err } request.URL = serviceURL request.Method = "POST" header.Set("Content-Type", "application/json") request.Header = header data, _ := json.Marshal(req) request.Body = NopCloser(bytes.NewReader(data)) t.sdkConfig.BuildCurlCommand(&request) resp, err := t.client.Do(&request) if err != nil { return err } defer resp.Body.Close() requestID, err := checkHTTPResponse(resp) if err != nil { return fmt.Errorf("requestID=%s, err=%v", requestID, err) } _, err = io.ReadAll(resp.Body) if err != nil { return fmt.Errorf("requestID=%s, err=%v", requestID, err) } return nil } func (t *KnowledgeBase) CreateDocumentsWithResp(req CreateDocumentsRequest) (CreateDocumentsResponse, error) { request := http.Request{} header := t.sdkConfig.AuthHeaderV2() if req.ClientToken == "" { req.ClientToken = uuid.New().String() } serviceURL, err := t.sdkConfig.ServiceURLV2("/knowledgeBase?Action=CreateDocuments&clientToken=" + req.ClientToken) if err != nil { return CreateDocumentsResponse{}, err } request.URL = serviceURL request.Method = "POST" header.Set("Content-Type", "application/json") request.Header = header data, _ := json.Marshal(req) request.Body = NopCloser(bytes.NewReader(data)) t.sdkConfig.BuildCurlCommand(&request) resp, err := t.client.Do(&request) if err != nil { return CreateDocumentsResponse{}, err } defer resp.Body.Close() requestID, err := checkHTTPResponse(resp) if err != nil { return CreateDocumentsResponse{}, fmt.Errorf("requestID=%s, err=%v", requestID, err) } data, err = io.ReadAll(resp.Body) if err != nil { return CreateDocumentsResponse{}, fmt.Errorf("requestID=%s, err=%v", requestID, err) } rsp := CreateDocumentsResponse{} if err := json.Unmarshal(data, &rsp); err != nil { return CreateDocumentsResponse{}, fmt.Errorf("requestID=%s, err=%v", requestID, err) } return rsp, nil } func (t *KnowledgeBase) UploadDocuments(localFilePath string, req CreateDocumentsRequest) error { var data bytes.Buffer w := multipart.NewWriter(&data) file, err := os.Open(localFilePath) if err != nil { return err } defer file.Close() filePart, _ := w.CreateFormFile("file", filepath.Base(file.Name())) if _, err := io.Copy(filePart, file); err != nil { return err } jsonData, err := json.Marshal(req) if err != nil { return fmt.Errorf("failed to marshal request: %w", err) } jsonPart, err := w.CreateFormField("payload") if err != nil { return fmt.Errorf("failed to create form field: %w", err) } if _, err := jsonPart.Write(jsonData); err != nil { return fmt.Errorf("failed to write JSON data: %w", err) } w.Close() request := http.Request{} header := t.sdkConfig.AuthHeaderV2() if req.ClientToken == "" { req.ClientToken = uuid.New().String() } serviceURL, err := t.sdkConfig.ServiceURLV2("/knowledgeBase?Action=UploadDocuments&clientToken=" + req.ClientToken) if err != nil { return err } request.URL = serviceURL request.Method = "POST" request.Header = header header.Set("Content-Type", w.FormDataContentType()) request.Body = NopCloser(bytes.NewReader(data.Bytes())) resp, err := t.client.Do(&request) if err != nil { return err } defer resp.Body.Close() requestID, err := checkHTTPResponse(resp) if err != nil { return fmt.Errorf("requestID=%s, err=%v", requestID, err) } _, err = io.ReadAll(resp.Body) if err != nil { return fmt.Errorf("requestID=%s, err=%v", requestID, err) } return nil } func (t *KnowledgeBase) UploadDocumentsWithResp(localFilePath string, req CreateDocumentsRequest) (UploadDocumentsResponse, error) { var data bytes.Buffer w := multipart.NewWriter(&data) file, err := os.Open(localFilePath) if err != nil { return UploadDocumentsResponse{}, err } defer file.Close() filePart, _ := w.CreateFormFile("file", filepath.Base(file.Name())) if _, err := io.Copy(filePart, file); err != nil { return UploadDocumentsResponse{}, err } jsonData, err := json.Marshal(req) if err != nil { return UploadDocumentsResponse{}, fmt.Errorf("failed to marshal request: %w", err) } jsonPart, err := w.CreateFormField("payload") if err != nil { return UploadDocumentsResponse{}, fmt.Errorf("failed to create form field: %w", err) } if _, err := jsonPart.Write(jsonData); err != nil { return UploadDocumentsResponse{}, fmt.Errorf("failed to write JSON data: %w", err) } w.Close() request := http.Request{} header := t.sdkConfig.AuthHeaderV2() if req.ClientToken == "" { req.ClientToken = uuid.New().String() } serviceURL, err := t.sdkConfig.ServiceURLV2("/knowledgeBase?Action=UploadDocuments&clientToken=" + req.ClientToken) if err != nil { return UploadDocumentsResponse{}, err } request.URL = serviceURL request.Method = "POST" request.Header = header header.Set("Content-Type", w.FormDataContentType()) request.Body = NopCloser(bytes.NewReader(data.Bytes())) resp, err := t.client.Do(&request) if err != nil { return UploadDocumentsResponse{}, err } defer resp.Body.Close() requestID, err := checkHTTPResponse(resp) if err != nil { return UploadDocumentsResponse{}, fmt.Errorf("requestID=%s, err=%v", requestID, err) } jsonData, err = io.ReadAll(resp.Body) if err != nil { return UploadDocumentsResponse{}, fmt.Errorf("requestID=%s, err=%v", requestID, err) } rsp := UploadDocumentsResponse{} if err := json.Unmarshal(jsonData, &rsp); err != nil { return UploadDocumentsResponse{}, fmt.Errorf("requestID=%s, err=%v", requestID, err) } return rsp, nil } func (t *KnowledgeBase) CreateChunk(req CreateChunkRequest) (string, error) { request := http.Request{} header := t.sdkConfig.AuthHeaderV2() if req.ClientToken == "" { req.ClientToken = uuid.New().String() } if req.KnowledgeBaseID == "" && t.knowledgeBaseID != "" { req.KnowledgeBaseID = t.knowledgeBaseID } serviceURL, err := t.sdkConfig.ServiceURLV2("/knowledgeBase?Action=CreateChunk&clientToken=" + req.ClientToken) if err != nil { return "", err } request.URL = serviceURL request.Method = "POST" header.Set("Content-Type", "application/json") request.Header = header data, _ := json.Marshal(req) request.Body = NopCloser(bytes.NewReader(data)) t.sdkConfig.BuildCurlCommand(&request) resp, err := t.client.Do(&request) if err != nil { return "", err } defer resp.Body.Close() requestID, err := checkHTTPResponse(resp) if err != nil { return "", fmt.Errorf("requestID=%s, err=%v", requestID, err) } data, err = io.ReadAll(resp.Body) if err != nil { return "", fmt.Errorf("requestID=%s, err=%v", requestID, err) } rsp := CreateChunkResponse{} if err := json.Unmarshal(data, &rsp); err != nil { return "", fmt.Errorf("requestID=%s, err=%v", requestID, err) } return rsp.ID, nil } func (t *KnowledgeBase) ModifyChunk(req ModifyChunkRequest) error { request := http.Request{} header := t.sdkConfig.AuthHeaderV2() if req.ClientToken == "" { req.ClientToken = uuid.New().String() } if req.KnowledgeBaseID == "" && t.knowledgeBaseID != "" { req.KnowledgeBaseID = t.knowledgeBaseID } serviceURL, err := t.sdkConfig.ServiceURLV2("/knowledgeBase?Action=ModifyChunk&clientToken=" + req.ClientToken) if err != nil { return err } request.URL = serviceURL request.Method = "POST" header.Set("Content-Type", "application/json") request.Header = header data, _ := json.Marshal(req) request.Body = NopCloser(bytes.NewReader(data)) t.sdkConfig.BuildCurlCommand(&request) resp, err := t.client.Do(&request) if err != nil { return err } defer resp.Body.Close() requestID, err := checkHTTPResponse(resp) if err != nil { return fmt.Errorf("requestID=%s, err=%v", requestID, err) } data, err = io.ReadAll(resp.Body) if err != nil { return fmt.Errorf("requestID=%s, err=%v", requestID, err) } rsp := CreateChunkResponse{} if err := json.Unmarshal(data, &rsp); err != nil { return fmt.Errorf("requestID=%s, err=%v", requestID, err) } return nil } func (t *KnowledgeBase) DeleteChunk(chunkID string) error { return t.deleteChunk(chunkID, "") } func (t *KnowledgeBase) DeleteChunkWithReq(req DeleteChunkRequest) error { return t.deleteChunk(req.ChunkID, req.ClientToken) } func (t *KnowledgeBase) deleteChunk(chunkID string, clientToken string) error { request := http.Request{} header := t.sdkConfig.AuthHeaderV2() if clientToken == "" { clientToken = uuid.New().String() } serviceURL, err := t.sdkConfig.ServiceURLV2("/knowledgeBase?Action=DeleteChunk&clientToken=" + clientToken) if err != nil { return err } request.URL = serviceURL request.Method = "POST" header.Set("Content-Type", "application/json") request.Header = header req := DeleteChunkRequest{ ChunkID: chunkID, } if t.knowledgeBaseID != "" { req.KnowledgeBaseID = t.knowledgeBaseID } data, _ := json.Marshal(req) request.Body = NopCloser(bytes.NewReader(data)) t.sdkConfig.BuildCurlCommand(&request) resp, err := t.client.Do(&request) if err != nil { return err } defer resp.Body.Close() requestID, err := checkHTTPResponse(resp) if err != nil { return fmt.Errorf("requestID=%s, err=%v", requestID, err) } data, err = io.ReadAll(resp.Body) if err != nil { return fmt.Errorf("requestID=%s, err=%v", requestID, err) } rsp := CreateChunkResponse{} if err := json.Unmarshal(data, &rsp); err != nil { return fmt.Errorf("requestID=%s, err=%v", requestID, err) } return nil } func (t *KnowledgeBase) DescribeChunk(chunkID string) (DescribeChunkResponse, error) { request := http.Request{} header := t.sdkConfig.AuthHeaderV2() serviceURL, err := t.sdkConfig.ServiceURLV2("/knowledgeBase?Action=DescribeChunk") if err != nil { return DescribeChunkResponse{}, err } request.URL = serviceURL request.Method = "POST" header.Set("Content-Type", "application/json") request.Header = header req := DescribeChunkRequest{ ChunkID: chunkID, } if t.knowledgeBaseID != "" { req.KnowledgeBaseID = t.knowledgeBaseID } data, _ := json.Marshal(req) request.Body = NopCloser(bytes.NewReader(data)) t.sdkConfig.BuildCurlCommand(&request) resp, err := t.client.Do(&request) if err != nil { return DescribeChunkResponse{}, err } defer resp.Body.Close() requestID, err := checkHTTPResponse(resp) if err != nil { return DescribeChunkResponse{}, fmt.Errorf("requestID=%s, err=%v", requestID, err) } data, err = io.ReadAll(resp.Body) if err != nil { return DescribeChunkResponse{}, fmt.Errorf("requestID=%s, err=%v", requestID, err) } rsp := DescribeChunkResponse{} if err := json.Unmarshal(data, &rsp); err != nil { return DescribeChunkResponse{}, fmt.Errorf("requestID=%s, err=%v", requestID, err) } return rsp, nil } func (t *KnowledgeBase) DescribeChunks(req DescribeChunksRequest) (DescribeChunksResponse, error) { request := http.Request{} header := t.sdkConfig.AuthHeaderV2() serviceURL, err := t.sdkConfig.ServiceURLV2("/knowledgeBase?Action=DescribeChunks") if err != nil { return DescribeChunksResponse{}, err } if req.KnowledgeBaseID == "" && t.knowledgeBaseID != "" { req.KnowledgeBaseID = t.knowledgeBaseID } request.URL = serviceURL request.Method = "POST" header.Set("Content-Type", "application/json") request.Header = header data, _ := json.Marshal(req) request.Body = NopCloser(bytes.NewReader(data)) t.sdkConfig.BuildCurlCommand(&request) resp, err := t.client.Do(&request) if err != nil { return DescribeChunksResponse{}, err } defer resp.Body.Close() requestID, err := checkHTTPResponse(resp) if err != nil { return DescribeChunksResponse{}, fmt.Errorf("requestID=%s, err=%v", requestID, err) } data, err = io.ReadAll(resp.Body) if err != nil { return DescribeChunksResponse{}, fmt.Errorf("requestID=%s, err=%v", requestID, err) } rsp := DescribeChunksResponse{} if err := json.Unmarshal(data, &rsp); err != nil { return DescribeChunksResponse{}, fmt.Errorf("requestID=%s, err=%v", requestID, err) } return rsp, nil } func (t *KnowledgeBase) QueryKnowledgeBase(req QueryKnowledgeBaseRequest) (QueryKnowledgeBaseResponse, error) { // 检查 RankScoreThreshold 是否为 nil,如果是,则设置默认值 if req.RankScoreThreshold == nil { defaultThreshold := 0.4 req.RankScoreThreshold = &defaultThreshold } request := http.Request{} header := t.sdkConfig.AuthHeaderV2() serviceURL, err := t.sdkConfig.ServiceURLV2("/knowledgebases/query") if err != nil { return QueryKnowledgeBaseResponse{}, err } request.URL = serviceURL request.Method = "POST" header.Set("Content-Type", "application/json") request.Header = header data, _ := json.Marshal(req) request.Body = NopCloser(bytes.NewReader(data)) t.sdkConfig.BuildCurlCommand(&request) resp, err := t.client.Do(&request) if err != nil { return QueryKnowledgeBaseResponse{}, err } defer resp.Body.Close() requestID, err := checkHTTPResponse(resp) if err != nil { return QueryKnowledgeBaseResponse{}, fmt.Errorf("requestID=%s, err=%v", requestID, err) } data, err = io.ReadAll(resp.Body) if err != nil { return QueryKnowledgeBaseResponse{}, fmt.Errorf("requestID=%s, err=%v", requestID, err) } rsp := QueryKnowledgeBaseResponse{} if err := json.Unmarshal(data, &rsp); err != nil { return QueryKnowledgeBaseResponse{}, fmt.Errorf("requestID=%s, err=%v", requestID, err) } return rsp, nil } ================================================ FILE: go/appbuilder/knowledge_base_data.go ================================================ // Copyright (c) 2024 Baidu, Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package appbuilder type QueryType string const ( Fulltext QueryType = "fulltext" Semantic QueryType = "semantic" Hybrid QueryType = "hybrid" ) const ( ContentTypeRawText = "raw_text" ContentTypeQA = "qa" ) type CreateDocumentRequest struct { KnowledgeBaseID string `json:"knowledge_base_id"` ContentType string `json:"content_type"` IsEnhanced bool `json:"is_enhanced"` FileIDS []string `json:"file_ids,omitempty"` CustomProcessRule *CustomProcessRule `json:"custom_process_rule,omitempty"` ClientToken string `json:"client_token,omitempty"` } type DeleteDocumentRequest struct { KnowledgeBaseID string `json:"knowledge_base_id"` DocumentID string `json:"document_id"` ClientToken string `json:"client_token,omitempty"` } type GetDocumentListRequest struct { KnowledgeBaseID string `json:"knowledge_base_id"` Limit int `json:"limit,omitempty"` After string `json:"after,omitempty"` Before string `json:"before,omitempty"` } type CustomProcessRule struct { Separators []string `json:"separators"` TargetLength int64 `json:"target_length"` OverlapRate float64 `json:"overlap_rate"` } type CreateDocumentResponse struct { RequestID string `json:"request_id"` KnowledgeBaseID string `json:"knowledge_base_id"` DocumentsIDS []string `json:"document_ids"` Code string `json:"code"` Message string `json:"message"` } type GetDocumentListResponse struct { RequestID string `json:"request_id"` Data []Document `json:"data"` Code string `json:"code"` Message string `json:"message"` } type Document struct { ID string `json:"id"` Name string `json:"name"` CreatedAt any `json:"created_at"` WordCount int64 `json:"word_count"` Enabled bool `json:"enabled"` Meta DocumentMeta `json:"meta"` } type DocumentMeta struct { Source string `json:"source"` FileID string `json:"file_id"` } type UploadFileResponse struct { RequestID string `json:"request_id"` FileID string `json:"id"` FileName string `json:"name"` Code string `json:"code"` Message string `json:"message"` } type KnowlegeBaseConfig struct { Index KnowledgeBaseConfigIndex `json:"index"` Catalogue *KnowledgeBaseConfigCatalogue `json:"catalogue,omitempty"` } type KnowledgeBaseConfigIndex struct { Type string `json:"type"` ClusterId string `json:"clusterId"` Username string `json:"username"` Password string `json:"password"` Location string `json:"location"` } type KnowledgeBaseConfigCatalogue struct { PathPrefix string `json:"pathPrefix,omitempty"` } type KnowledgeBaseDetail struct { ID string `json:"id,omitempty"` Name string `json:"name,omitempty"` Description string `json:"description,omitempty"` Config *KnowlegeBaseConfig `json:"config,omitempty"` ClientToken string `json:"client_token,omitempty"` } type ModifyKnowlegeBaseRequest struct { ID string `json:"id"` Name *string `json:"name,omitempty"` Description *string `json:"description,omitempty"` Config *KnowlegeBaseConfig `json:"config,omitempty"` ClientToken string `json:"client_token,omitempty"` } type DeleteKnowlegeBaseRequest struct { ID string `json:"id"` ClientToken string `json:"client_token,omitempty"` } type GetKnowledgeBaseListRequest struct { Marker string `json:"marker,omitempty"` Keyword string `json:"keyword,omitempty"` MaxKeys int `json:"maxKeys,omitempty"` } type GetKnowledgeBaseListResponse struct { RequestID string `json:"requestId"` Data []KnowledgeBaseDetail `json:"data"` Marker string `json:"marker"` IsTruncated bool `json:"isTruncated"` NextMarker string `json:"nextMarker"` MaxKeys int `json:"maxKeys"` } type DocumentsSourceUrlConfig struct { Frequency int `json:"frequency"` } type DocumentsSource struct { Type string `json:"type"` Urls []string `json:"urls,omitempty"` UrlDepth int `json:"url_depth,omitempty"` UrlConfigs *[]DocumentsSourceUrlConfig `json:"url_configs,omitempty"` } type DocumentsProcessOptionParser struct { Choices []string `json:"choices"` } type DocumentsProcessOptionChunkerSeparator struct { Separators []string `json:"separators"` TargetLength int64 `json:"targetLength"` OverlapRate float64 `json:"overlapRate"` } type DocumentsProcessOptionChunkerPattern struct { MarkPosition string `json:"markPosition"` Regex string `json:"regex"` TargetLength int64 `json:"targetLength"` OverlapRate float64 `json:"overlapRate"` } type DocumentsProcessOptionChunker struct { Choices []string `json:"choices"` PrependInfo []string `json:"prependInfo"` Separator *DocumentsProcessOptionChunkerSeparator `json:"separator,omitempty"` Pattern *DocumentsProcessOptionChunkerPattern `json:"pattern,omitempty"` } type DocumentsProcessOptionKnowledgeAugmentation struct { Choices []string `json:"choices"` } type DocumentsProcessOption struct { Template string `json:"template"` Parser *DocumentsProcessOptionParser `json:"parser,omitempty"` Chunker *DocumentsProcessOptionChunker `json:"chunker,omitempty"` KnowledgeAugmentation *DocumentsProcessOptionKnowledgeAugmentation `json:"knowledgeAugmentation,omitempty"` } type CreateDocumentsRequest struct { ID string `json:"id"` ContentFormat string `json:"contentFormat"` Source DocumentsSource `json:"source"` ProcessOption *DocumentsProcessOption `json:"processOption,omitempty"` ClientToken string `json:"client_token,omitempty"` } type CreateDocumentsResponse struct { RequestID string `json:"requestId"` DocumentIDS []string `json:"documentIds"` } type UploadDocumentsResponse struct { RequestID string `json:"requestId"` DocumentID string `json:"documentId"` } type CreateChunkRequest struct { KnowledgeBaseID string `json:"knowledgeBaseId"` DocumentID string `json:"documentId"` Content string `json:"content"` ClientToken string `json:"client_token,omitempty"` } type CreateChunkResponse struct { ID string `json:"id"` } type ModifyChunkRequest struct { KnowledgeBaseID string `json:"knowledgeBaseId"` ChunkID string `json:"chunkId"` Content string `json:"content"` Enable bool `json:"enable"` ClientToken string `json:"client_token,omitempty"` } type DeleteChunkRequest struct { KnowledgeBaseID string `json:"knowledgeBaseId"` ChunkID string `json:"chunkId"` ClientToken string `json:"client_token,omitempty"` } type DescribeChunkRequest struct { KnowledgeBaseID string `json:"knowledgeBaseId"` ChunkID string `json:"chunkId"` } type DescribeChunkResponse struct { ID string `json:"id"` Type string `json:"type"` KnowledgeBaseID string `json:"knowledgeBaseId"` DocumentID string `json:"documentId"` Content string `json:"content"` WordCount int64 `json:"wordCount"` TokenCount int64 `json:"tokenCount"` Enabled bool `json:"enabled"` Status string `json:"status"` StatusMessage string `json:"statusMessage"` ImageUrls []string `json:"imageUrls"` CreatedAt int64 `json:"createTime"` UpdatedAt int64 `json:"updateTime"` } type DescribeDocumentsRequest struct { KnowledgeBaseID string `json:"knowledgeBaseId"` Marker string `json:"marker,omitempty"` MaxKeys int `json:"maxKeys,omitempty"` } type DescribeDocumentResponse struct { ID string `json:"id"` Name string `json:"name"` CreatedAt string `json:"createdAt"` DisplayStatus string `json:"displayStatus"` WordCount int64 `json:"wordCount"` Enabled bool `json:"enabled"` Meta DescribeDocumentMeta `json:"meta"` } type DescribeDocumentMeta struct { Source string `json:"source"` FileID string `json:"fileId"` URL string `json:"url"` MimeType string `json:"mime_type"` FileSize int64 `json:"file_size"` } type DescribeDocumentsResponse struct { Data []DescribeDocumentResponse `json:"data"` Marker string `json:"marker"` IsTruncated bool `json:"isTruncated"` NextMarker string `json:"nextMarker"` MaxKeys int `json:"maxKeys"` RequestID string `json:"requestId"` } type DescribeChunksRequest struct { KnowledgeBaseID string `json:"knowledgeBaseId"` DocumnetID string `json:"documentId"` Marker string `json:"marker,omitempty"` MaxKeys int `json:"maxKeys,omitempty"` Type string `json:"type,omitempty"` Keyword string `json:"keyword,omitempty"` } type DescribeChunksResponse struct { Data []DescribeChunkResponse `json:"data"` Marker string `json:"marker"` IsTruncated bool `json:"isTruncated"` NextMarker string `json:"nextMarker"` MaxKeys int `json:"maxKeys"` } type MetadataFilter struct { Operator string `json:"operator"` Field string `json:"field,omitempty"` Value any `json:"value"` } type MetadataFilters struct { Filters []MetadataFilter `json:"filters"` Condition string `json:"condition"` } type PreRankingConfig struct { Bm25Weight float64 `json:"bm25_weight"` VecWeight float64 `json:"vec_weight"` Bm25B float64 `json:"bm25_b"` Bm25K1 float64 `json:"bm25_k1"` Bm25MaxScore float64 `json:"bm25_max_score"` } type ElasticSearchRetrieveConfig struct { Name string `json:"name"` Type string `json:"type"` Threshold float64 `json:"threshold"` Top int `json:"top"` } type VectorDBRetrieveConfig struct { Name string `json:"name"` Type string `json:"type"` Threshold float64 `json:"threshold"` Top int `json:"top"` } type SmallToBigConfig struct { Name string `json:"name"` Type string `json:"type"` } type RankingConfig struct { Name string `json:"name"` Type string `json:"type"` Inputs []string `json:"inputs"` ModelName string `json:"model_name"` Top int `json:"top"` } type QueryPipelineConfig struct { ID string `json:"id"` Pipeline []any `json:"pipeline"` } type QueryKnowledgeBaseRequest struct { Query string `json:"query"` KnowledgebaseIDs []string `json:"knowledgebase_ids"` Type *QueryType `json:"type,omitempty"` Top int `json:"top,omitempty"` Skip int `json:"skip,omitempty"` RankScoreThreshold *float64 `json:"rank_score_threshold,omitempty"` MetadataFileters MetadataFilters `json:"metadata_fileters,omitempty"` PipelineConfig QueryPipelineConfig `json:"pipeline_config,omitempty"` } type RowLine struct { Key string `json:"key"` Index int `json:"index"` Value string `json:"value"` EnableIndexing bool `json:"enable_indexing"` EnableResponse bool `json:"enable_response"` } type ChunkLocation struct { PageNum []int `json:"paget_num"` Box [][]int `json:"box"` } type Chunk struct { ChunkID string `json:"chunk_id"` KnowledgebaseID string `json:"knowledgebase_id"` DocumentID string `json:"document_id"` DocumentName string `json:"document_name"` Meta map[string]any `json:"meta"` Type string `json:"type"` Content string `json:"content"` CreateTime string `json:"create_time"` UpdateTime string `json:"update_time"` RetrievalScore float64 `json:"retrieval_score"` RankScore float64 `json:"rank_score"` Locations ChunkLocation `json:"locations"` Children []Chunk `json:"children"` NeighbourChunks []Chunk `json:"neighbour_chunks"` OriginalChunkId string `json:"original_chunk_id"` OriginalChunkOffset int `json:"original_chunk_offset"` } type QueryKnowledgeBaseResponse struct { RequestId string `json:"requestId"` Code string `json:"code"` Message string `json:"message"` Chunks []Chunk `json:"chunks"` TotalCount int `json:"total_count"` } ================================================ FILE: go/appbuilder/knowledge_base_test.go ================================================ // Copyright (c) 2024 Baidu, Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package appbuilder import ( "bytes" "encoding/json" "fmt" "os" "strings" "testing" "time" ) func TestAddDocumentError(t *testing.T) { t.Parallel() // 并发运行 os.Setenv("APPBUILDER_LOGLEVEL", "DEBUG") os.Setenv("APPBUILDER_LOGFILE", "") // NewKnowledgeBase测试1 config== nil _, err := NewKnowledgeBase(nil) if err == nil { t.Errorf("expected config= nil error, got %v", err) } knowledgeBaseID := os.Getenv(DatasetIDV3) config, err := NewSDKConfig("", os.Getenv(SecretKeyV3)) if err != nil { t.Logf("%s========== FAIL: %s ==========%s", "\033[31m", t.Name(), "\033[0m") t.Fatalf("new http client config failed: %v", err) } client, err := NewKnowledgeBase(config) if err != nil { t.Logf("%s========== FAIL: %s ==========%s", "\033[31m", t.Name(), "\033[0m") t.Fatalf("new Knowledge base instance failed") } var GatewayURL = client.sdkConfig.GatewayURLV2 var clientT = client.client // 测试 UploadLocalFile 1: 文件打开错误 _, err = client.UploadFile("invalidFilePath") if err == nil || !strings.Contains(err.Error(), "no such file or directory") { t.Errorf("expected file open error, got %v", err) } // 测试 UploadLocalFile 2: t.client.Do 错误 client.sdkConfig.GatewayURLV2 = "http://192.0.2.1" _, err = client.UploadFile("./files/test.pdf") if err == nil { t.Errorf("expected client error, got nil") } // 测试 UploadLocalFile 3: 无效的ServiceURLV2 client.sdkConfig.GatewayURLV2 = "://invalid-url" _, err = client.UploadFile("./files/test.pdf") if err == nil || !strings.Contains(err.Error(), "missing protocol scheme") { t.Errorf("expected ServiceURLV2 error, got %v", err) } // 测试 UploadLocalFile 4: 错误的 HTTP 响应 client.client = &MockHTTPClient{} client.sdkConfig.GatewayURLV2 = GatewayURL _, err = client.UploadFile("./files/test.pdf") if err == nil { t.Fatalf("expected 400 error, got nil") } // 测试 UploadLocalFile 5: 模拟读取 body 时发生错误 client.client = &FaultyHTTPClient{} client.sdkConfig.GatewayURLV2 = GatewayURL _, err = client.UploadFile("./files/test.pdf") if err == nil { t.Fatalf("expected read error, got nil") } // 测试 UploadLocalFile 6: json.Unmarshal错误 client.client = &InvalidJSONHTTPClient{} client.sdkConfig.GatewayURLV2 = GatewayURL _, err = client.UploadFile("./files/test.pdf") if err == nil { t.Fatalf("expected JSON unmarshal error, got nil") } // 测试 UploadLocalFile 7: 缺少 id 字段 client.client = &MissingIDHTTPClient{} client.sdkConfig.GatewayURLV2 = GatewayURL client.UploadFile("./files/test.pdf") // 正常测试 client.client = clientT client.sdkConfig.GatewayURLV2 = GatewayURL fileID, err := client.UploadFile("./files/test.pdf") if err != nil { t.Logf("%s========== FAIL: %s ==========%s", "\033[31m", t.Name(), "\033[0m") t.Fatalf("upload file failed: %v", err) } // CreateDocument 测试1 ServiceURLV2 错误 client.sdkConfig.GatewayURLV2 = "://invalid-url" _, err = client.CreateDocument(CreateDocumentRequest{ KnowledgeBaseID: knowledgeBaseID, ContentType: ContentTypeRawText, FileIDS: []string{fileID}, CustomProcessRule: &CustomProcessRule{ Separators: []string{"。"}, TargetLength: 300, OverlapRate: 0.25, }, }) if err == nil { t.Logf("%s========== FAIL: %s ==========%s", "\033[31m", t.Name(), "\033[0m") t.Errorf("expected ServiceURLV2 error, got %v", err) } // CreateDocument 测试2 Do 错误 client.sdkConfig.GatewayURLV2 = "http://192.0.2.1" _, err = client.CreateDocument(CreateDocumentRequest{ KnowledgeBaseID: knowledgeBaseID, ContentType: ContentTypeRawText, FileIDS: []string{fileID}, CustomProcessRule: &CustomProcessRule{ Separators: []string{"。"}, TargetLength: 300, OverlapRate: 0.25, }, }) if err == nil { t.Logf("%s========== FAIL: %s ==========%s", "\033[31m", t.Name(), "\033[0m") t.Errorf("expected Bad Request error, got %v", err) } // CreateDocument 测试3 错误的 HTTP 响应 client.sdkConfig.GatewayURLV2 = GatewayURL client.client = &MockHTTPClient{} _, err = client.CreateDocument(CreateDocumentRequest{ KnowledgeBaseID: knowledgeBaseID, ContentType: ContentTypeRawText, FileIDS: []string{fileID}, CustomProcessRule: &CustomProcessRule{ Separators: []string{"。"}, TargetLength: 300, OverlapRate: 0.25, }, }) if err == nil { t.Fatalf("expected 400 error, got nil") } // CreateDocument 测试 4: 模拟读取 body 时发生错误 client.sdkConfig.GatewayURLV2 = GatewayURL client.client = &FaultyHTTPClient{} _, err = client.CreateDocument(CreateDocumentRequest{ KnowledgeBaseID: knowledgeBaseID, ContentType: ContentTypeRawText, FileIDS: []string{fileID}, CustomProcessRule: &CustomProcessRule{ Separators: []string{"。"}, TargetLength: 300, OverlapRate: 0.25, }, }) if err == nil { t.Fatalf("expected read error, got nil") } // CreateDocument 测试 5: json.Unmarshal错误 client.sdkConfig.GatewayURLV2 = GatewayURL client.client = &InvalidJSONHTTPClient{} _, err = client.CreateDocument(CreateDocumentRequest{ KnowledgeBaseID: knowledgeBaseID, ContentType: ContentTypeRawText, FileIDS: []string{fileID}, CustomProcessRule: &CustomProcessRule{ Separators: []string{"。"}, TargetLength: 300, OverlapRate: 0.25, }, }) if err == nil { t.Fatalf("expected JSON unmarshal error, got nil") } // CreateDocument 测试 6: 缺少 id 字段 client.client = &MissingIDHTTPClient{} client.CreateDocument(CreateDocumentRequest{ KnowledgeBaseID: knowledgeBaseID, ContentType: ContentTypeRawText, FileIDS: []string{fileID}, CustomProcessRule: &CustomProcessRule{ Separators: []string{"。"}, TargetLength: 300, OverlapRate: 0.25, }, }) // 还原设置 client.client = clientT client.sdkConfig.GatewayURLV2 = GatewayURL createDocumentRes, err := client.CreateDocument(CreateDocumentRequest{ KnowledgeBaseID: knowledgeBaseID, ContentType: ContentTypeRawText, FileIDS: []string{fileID}, CustomProcessRule: &CustomProcessRule{ Separators: []string{"。"}, TargetLength: 300, OverlapRate: 0.25, }, }) if err != nil { t.Logf("%s========== FAIL: %s ==========%s", "\033[31m", t.Name(), "\033[0m") t.Fatalf("create document failed: %v", err) } // DeleteDocument 测试1 ServiceURLV2 错误 client.sdkConfig.GatewayURLV2 = "://invalid-url" err = client.DeleteDocument(DeleteDocumentRequest{ KnowledgeBaseID: knowledgeBaseID, DocumentID: createDocumentRes.DocumentsIDS[0]}) if err == nil { t.Logf("%s========== FAIL: %s ==========%s", "\033[31m", t.Name(), "\033[0m") } // DeleteDocument 测试2 Do 错误 client.sdkConfig.GatewayURLV2 = "http://192.0.2.1" err = client.DeleteDocument(DeleteDocumentRequest{ KnowledgeBaseID: knowledgeBaseID, DocumentID: createDocumentRes.DocumentsIDS[0]}) if err == nil { t.Logf("%s========== FAIL: %s ==========%s", "\033[31m", t.Name(), "\033[0m") } // DeleteDocument 测试3 错误的 HTTP 响应 client.sdkConfig.GatewayURLV2 = GatewayURL client.client = &MockHTTPClient{} err = client.DeleteDocument(DeleteDocumentRequest{ KnowledgeBaseID: knowledgeBaseID, DocumentID: createDocumentRes.DocumentsIDS[0]}) if err == nil { } // 如果测试失败,则输出缓冲区中的日志 if t.Failed() { } else { // else 紧跟在右大括号后面 // 测试通过,打印文件名和测试函数名 } } func TestCreateKnowledgeBaseError(t *testing.T) { t.Parallel() // 并发运行 os.Setenv("APPBUILDER_LOGLEVEL", "DEBUG") config, err := NewSDKConfig("", os.Getenv(SecretKeyV3)) if err != nil { } client, err := NewKnowledgeBase(config) if err != nil { } var GatewayURL = client.sdkConfig.GatewayURLV2 var clientT = client.client // CreateKnowledgeBase 测试1 ServiceURLV2 错误 client.sdkConfig.GatewayURLV2 = "://invalid-url" _, err = client.CreateKnowledgeBase(KnowledgeBaseDetail{ Name: "test-go", Description: "test-go", Config: &KnowlegeBaseConfig{ Index: KnowledgeBaseConfigIndex{ Type: "public", Password: "elastic", Username: "elastic", }, }, }) if err == nil { } // CreateKnowledgeBase 测试2 Do 错误 client.sdkConfig.GatewayURLV2 = "http://192.0.2.1" _, err = client.CreateKnowledgeBase(KnowledgeBaseDetail{ Name: "test-go", Description: "test-go", Config: &KnowlegeBaseConfig{ Index: KnowledgeBaseConfigIndex{ Type: "public", Password: "elastic", Username: "elastic", }, }, }) if err == nil { } // CreateKnowledgeBase 测试3 错误的 HTTP 响应 client.sdkConfig.GatewayURLV2 = GatewayURL client.client = &MockHTTPClient{} _, err = client.CreateKnowledgeBase(KnowledgeBaseDetail{ Name: "test-go", Description: "test-go", Config: &KnowlegeBaseConfig{ Index: KnowledgeBaseConfigIndex{ Type: "public", Password: "elastic", Username: "elastic", }, }, }) if err == nil { } // CreateKnowledgeBase 测试 4: 模拟读取 body 时发生错误 client.sdkConfig.GatewayURLV2 = GatewayURL client.client = &FaultyHTTPClient{} _, err = client.CreateKnowledgeBase(KnowledgeBaseDetail{ Name: "test-go", Description: "test-go", Config: &KnowlegeBaseConfig{ Index: KnowledgeBaseConfigIndex{ Type: "public", Password: "elastic", Username: "elastic", }, }, }) if err == nil { } // CreateDocument 测试 5: json.Unmarshal错误 client.sdkConfig.GatewayURLV2 = GatewayURL client.client = &InvalidJSONHTTPClient{} _, err = client.CreateKnowledgeBase(KnowledgeBaseDetail{ Name: "test-go", Description: "test-go", Config: &KnowlegeBaseConfig{ Index: KnowledgeBaseConfigIndex{ Type: "public", Password: "elastic", Username: "elastic", }, }, }) if err == nil { } client.client = clientT var knowledgeBaseID string needDeleteKnowledgeBase := false // 成功 创建知识库 createKnowledgeBaseRes, err := client.CreateKnowledgeBase(KnowledgeBaseDetail{ Name: "test-go", Description: "test-go", Config: &KnowlegeBaseConfig{ Index: KnowledgeBaseConfigIndex{ Type: "public", Password: "elastic", Username: "elastic", }, }, }) if err == nil { needDeleteKnowledgeBase = true knowledgeBaseID = createKnowledgeBaseRes.ID } else { knowledgeBaseID = os.Getenv(SecretKeyV3) } client.client = clientT // GetKnowledgeBaseDetail 测试1 ServiceURLV2 错误 client.sdkConfig.GatewayURLV2 = "://invalid-url" _, err = client.GetKnowledgeBaseDetail(knowledgeBaseID) if err == nil { } // GetKnowledgeBaseDetail 测试2 Do 错误 client.sdkConfig.GatewayURLV2 = "http://192.0.2.1" _, err = client.GetKnowledgeBaseDetail(knowledgeBaseID) if err == nil { } // GetKnowledgeBaseDetail 测试3 错误的 HTTP 响应 client.sdkConfig.GatewayURLV2 = GatewayURL client.client = &MockHTTPClient{} _, err = client.GetKnowledgeBaseDetail(knowledgeBaseID) if err == nil { } // GetKnowledgeBaseDetail 测试 4: 模拟读取 body 时发生错误 client.sdkConfig.GatewayURLV2 = GatewayURL client.client = &FaultyHTTPClient{} _, err = client.GetKnowledgeBaseDetail(knowledgeBaseID) if err == nil { } // GetKnowledgeBaseDetail 测试 5: json.Unmarshal错误 client.sdkConfig.GatewayURLV2 = GatewayURL client.client = &InvalidJSONHTTPClient{} _, err = client.GetKnowledgeBaseDetail(knowledgeBaseID) if err == nil { } client.client = clientT // GetKnowledgeBaseList 测试1 ServiceURLV2 错误 client.sdkConfig.GatewayURLV2 = "://invalid-url" _, err = client.GetKnowledgeBaseList( GetKnowledgeBaseListRequest{ Marker: knowledgeBaseID, }, ) if err == nil { } // GetKnowledgeBaseList 测试2 Do 错误 client.sdkConfig.GatewayURLV2 = "http://192.0.2.1" _, err = client.GetKnowledgeBaseList( GetKnowledgeBaseListRequest{ Marker: knowledgeBaseID, }, ) if err == nil { } // GetKnowledgeBaseList 测试3 错误的 HTTP 响应 client.sdkConfig.GatewayURLV2 = GatewayURL client.client = &MockHTTPClient{} _, err = client.GetKnowledgeBaseList( GetKnowledgeBaseListRequest{ Marker: knowledgeBaseID, }, ) if err == nil { } // GetKnowledgeBaseList 测试 4: 模拟读取 body 时发生错误 client.sdkConfig.GatewayURLV2 = GatewayURL client.client = &FaultyHTTPClient{} _, err = client.GetKnowledgeBaseList( GetKnowledgeBaseListRequest{ Marker: knowledgeBaseID, }, ) if err == nil { } // GetKnowledgeBaseList 测试 5: json.Unmarshal错误 client.sdkConfig.GatewayURLV2 = GatewayURL client.client = &InvalidJSONHTTPClient{} _, err = client.GetKnowledgeBaseList( GetKnowledgeBaseListRequest{ Marker: knowledgeBaseID, }, ) if err == nil { } client.client = clientT // 导入知识库 测试1 // 导入知识库 测试1 ServiceURLV2 错误 client.sdkConfig.GatewayURLV2 = "://invalid-url" err = client.CreateDocuments(CreateDocumentsRequest{ ID: knowledgeBaseID, ContentFormat: "rawText", Source: DocumentsSource{ Type: "web", Urls: []string{"https://baijiahao.baidu.com/s?id=1802527379394162441"}, UrlDepth: 1, }, ProcessOption: &DocumentsProcessOption{ Template: "custom", Parser: &DocumentsProcessOptionParser{ Choices: []string{"layoutAnalysis", "ocr"}, }, Chunker: &DocumentsProcessOptionChunker{ Choices: []string{"separator"}, Separator: &DocumentsProcessOptionChunkerSeparator{ Separators: []string{"。"}, TargetLength: 300, OverlapRate: 0.25, }, PrependInfo: []string{"title", "filename"}, }, KnowledgeAugmentation: &DocumentsProcessOptionKnowledgeAugmentation{ Choices: []string{"faq"}, }, }, }) if err == nil { } // 导入知识库 测试2 Do 错误 client.sdkConfig.GatewayURLV2 = "http://192.0.2.1" err = client.CreateDocuments(CreateDocumentsRequest{ ID: knowledgeBaseID, ContentFormat: "rawText", Source: DocumentsSource{ Type: "web", Urls: []string{"https://baijiahao.baidu.com/s?id=1802527379394162441"}, UrlDepth: 1, }, ProcessOption: &DocumentsProcessOption{ Template: "custom", Parser: &DocumentsProcessOptionParser{ Choices: []string{"layoutAnalysis", "ocr"}, }, Chunker: &DocumentsProcessOptionChunker{ Choices: []string{"separator"}, Separator: &DocumentsProcessOptionChunkerSeparator{ Separators: []string{"。"}, TargetLength: 300, OverlapRate: 0.25, }, PrependInfo: []string{"title", "filename"}, }, KnowledgeAugmentation: &DocumentsProcessOptionKnowledgeAugmentation{ Choices: []string{"faq"}, }, }, }) if err == nil { } // 导入知识库 测试3 错误的 HTTP 响应 client.sdkConfig.GatewayURLV2 = GatewayURL client.client = &MockHTTPClient{} err = client.CreateDocuments(CreateDocumentsRequest{ ID: knowledgeBaseID, ContentFormat: "rawText", Source: DocumentsSource{ Type: "web", Urls: []string{"https://baijiahao.baidu.com/s?id=1802527379394162441"}, UrlDepth: 1, }, ProcessOption: &DocumentsProcessOption{ Template: "custom", Parser: &DocumentsProcessOptionParser{ Choices: []string{"layoutAnalysis", "ocr"}, }, Chunker: &DocumentsProcessOptionChunker{ Choices: []string{"separator"}, Separator: &DocumentsProcessOptionChunkerSeparator{ Separators: []string{"。"}, TargetLength: 300, OverlapRate: 0.25, }, PrependInfo: []string{"title", "filename"}, }, KnowledgeAugmentation: &DocumentsProcessOptionKnowledgeAugmentation{ Choices: []string{"faq"}, }, }, }) if err == nil { } // 导入知识库 测试 4: 模拟读取 body 时发生错误 client.sdkConfig.GatewayURLV2 = GatewayURL client.client = &FaultyHTTPClient{} err = client.CreateDocuments(CreateDocumentsRequest{ ID: knowledgeBaseID, ContentFormat: "rawText", Source: DocumentsSource{ Type: "web", Urls: []string{"https://baijiahao.baidu.com/s?id=1802527379394162441"}, UrlDepth: 1, }, ProcessOption: &DocumentsProcessOption{ Template: "custom", Parser: &DocumentsProcessOptionParser{ Choices: []string{"layoutAnalysis", "ocr"}, }, Chunker: &DocumentsProcessOptionChunker{ Choices: []string{"separator"}, Separator: &DocumentsProcessOptionChunkerSeparator{ Separators: []string{"。"}, TargetLength: 300, OverlapRate: 0.25, }, PrependInfo: []string{"title", "filename"}, }, KnowledgeAugmentation: &DocumentsProcessOptionKnowledgeAugmentation{ Choices: []string{"faq"}, }, }, }) if err == nil { } client.client = clientT // 测试上传知识库文档 UploadDocuments 1: 文件打开错误 err = client.UploadDocuments("./files/test.pdf", CreateDocumentsRequest{ ID: knowledgeBaseID, ContentFormat: "rawText", Source: DocumentsSource{ Type: "file", }, ProcessOption: &DocumentsProcessOption{ Template: "custom", Parser: &DocumentsProcessOptionParser{ Choices: []string{"layoutAnalysis", "ocr"}, }, Chunker: &DocumentsProcessOptionChunker{ Choices: []string{"separator"}, Separator: &DocumentsProcessOptionChunkerSeparator{ Separators: []string{"。"}, TargetLength: 300, OverlapRate: 0.25, }, PrependInfo: []string{"title", "filename"}, }, KnowledgeAugmentation: &DocumentsProcessOptionKnowledgeAugmentation{ Choices: []string{"faq"}, }, }, }) if err == nil || !strings.Contains(err.Error(), "no such file or directory") { } // 测试上传知识库文档 UploadDocuments 2: t.client.Do 错误 client.sdkConfig.GatewayURLV2 = "http://192.0.2.1" err = client.UploadDocuments("./files/test.pdf", CreateDocumentsRequest{ ID: knowledgeBaseID, ContentFormat: "rawText", Source: DocumentsSource{ Type: "file", }, ProcessOption: &DocumentsProcessOption{ Template: "custom", Parser: &DocumentsProcessOptionParser{ Choices: []string{"layoutAnalysis", "ocr"}, }, Chunker: &DocumentsProcessOptionChunker{ Choices: []string{"separator"}, Separator: &DocumentsProcessOptionChunkerSeparator{ Separators: []string{"。"}, TargetLength: 300, OverlapRate: 0.25, }, PrependInfo: []string{"title", "filename"}, }, KnowledgeAugmentation: &DocumentsProcessOptionKnowledgeAugmentation{ Choices: []string{"faq"}, }, }, }) if err == nil { } // 测试上传知识库文档 UploadDocuments 3: 无效的ServiceURLV2 client.sdkConfig.GatewayURLV2 = "://invalid-url" err = client.UploadDocuments("./files/test.pdf", CreateDocumentsRequest{ ID: knowledgeBaseID, ContentFormat: "rawText", Source: DocumentsSource{ Type: "file", }, ProcessOption: &DocumentsProcessOption{ Template: "custom", Parser: &DocumentsProcessOptionParser{ Choices: []string{"layoutAnalysis", "ocr"}, }, Chunker: &DocumentsProcessOptionChunker{ Choices: []string{"separator"}, Separator: &DocumentsProcessOptionChunkerSeparator{ Separators: []string{"。"}, TargetLength: 300, OverlapRate: 0.25, }, PrependInfo: []string{"title", "filename"}, }, KnowledgeAugmentation: &DocumentsProcessOptionKnowledgeAugmentation{ Choices: []string{"faq"}, }, }, }) if err == nil || !strings.Contains(err.Error(), "missing protocol scheme") { } // 测试上传知识库文档 UploadDocuments 4: 错误的 HTTP 响应 client.client = &MockHTTPClient{} client.sdkConfig.GatewayURLV2 = GatewayURL err = client.UploadDocuments("./files/test.pdf", CreateDocumentsRequest{ ID: knowledgeBaseID, ContentFormat: "rawText", Source: DocumentsSource{ Type: "file", }, ProcessOption: &DocumentsProcessOption{ Template: "custom", Parser: &DocumentsProcessOptionParser{ Choices: []string{"layoutAnalysis", "ocr"}, }, Chunker: &DocumentsProcessOptionChunker{ Choices: []string{"separator"}, Separator: &DocumentsProcessOptionChunkerSeparator{ Separators: []string{"。"}, TargetLength: 300, OverlapRate: 0.25, }, PrependInfo: []string{"title", "filename"}, }, KnowledgeAugmentation: &DocumentsProcessOptionKnowledgeAugmentation{ Choices: []string{"faq"}, }, }, }) if err == nil { } // 测试上传知识库文档 UploadDocuments 5: 模拟读取 body 时发生错误 client.client = &FaultyHTTPClient{} client.sdkConfig.GatewayURLV2 = GatewayURL err = client.UploadDocuments("./files/test.pdf", CreateDocumentsRequest{ ID: knowledgeBaseID, ContentFormat: "rawText", Source: DocumentsSource{ Type: "file", }, ProcessOption: &DocumentsProcessOption{ Template: "custom", Parser: &DocumentsProcessOptionParser{ Choices: []string{"layoutAnalysis", "ocr"}, }, Chunker: &DocumentsProcessOptionChunker{ Choices: []string{"separator"}, Separator: &DocumentsProcessOptionChunkerSeparator{ Separators: []string{"。"}, TargetLength: 300, OverlapRate: 0.25, }, PrependInfo: []string{"title", "filename"}, }, KnowledgeAugmentation: &DocumentsProcessOptionKnowledgeAugmentation{ Choices: []string{"faq"}, }, }, }) if err == nil { } client.client = clientT name := "test-go" description := "22" // 测试修改知识库 GetKnowledgeBaseDetail 测试1 ServiceURLV2 错误 client.sdkConfig.GatewayURLV2 = "://invalid-url" err = client.ModifyKnowledgeBase(ModifyKnowlegeBaseRequest{ ID: knowledgeBaseID, Name: &name, Description: &description, }) if err == nil { } // 测试修改知识库 GetKnowledgeBaseDetail 测试2 Do 错误 client.sdkConfig.GatewayURLV2 = "http://192.0.2.1" err = client.ModifyKnowledgeBase(ModifyKnowlegeBaseRequest{ ID: knowledgeBaseID, Name: &name, Description: &description, }) if err == nil { } // 测试修改知识库 GetKnowledgeBaseDetail 测试3 错误的 HTTP 响应 client.sdkConfig.GatewayURLV2 = GatewayURL client.client = &MockHTTPClient{} err = client.ModifyKnowledgeBase(ModifyKnowlegeBaseRequest{ ID: knowledgeBaseID, Name: &name, Description: &description, }) if err == nil { } // 测试修改知识库 GetKnowledgeBaseDetail 测试 4: 模拟读取 body 时发生错误 client.sdkConfig.GatewayURLV2 = GatewayURL client.client = &FaultyHTTPClient{} err = client.ModifyKnowledgeBase(ModifyKnowlegeBaseRequest{ ID: knowledgeBaseID, Name: &name, Description: &description, }) if err == nil { } client.client = clientT // 测试删除知识库 GetKnowledgeBaseDetail 测试1 ServiceURLV2 错误 client.sdkConfig.GatewayURLV2 = "://invalid-url" err = client.DeleteKnowledgeBase(knowledgeBaseID) if err == nil { } // 测试删除知识库 GetKnowledgeBaseDetail 测试2 Do 错误 client.sdkConfig.GatewayURLV2 = "http://192.0.2.1" err = client.DeleteKnowledgeBase(knowledgeBaseID) if err == nil { } // 测试删除知识库 GetKnowledgeBaseDetail 测试3 错误的 HTTP 响应 client.sdkConfig.GatewayURLV2 = GatewayURL client.client = &MockHTTPClient{} err = client.DeleteKnowledgeBase(knowledgeBaseID) if err == nil { } // 测试删除知识库 GetKnowledgeBaseDetail 测试 4: 模拟读取 body 时发生错误 client.sdkConfig.GatewayURLV2 = GatewayURL client.client = &FaultyHTTPClient{} err = client.DeleteKnowledgeBase(knowledgeBaseID) if err == nil { } client.client = clientT // 删除知识库 if needDeleteKnowledgeBase { err = client.DeleteKnowledgeBase(knowledgeBaseID) if err != nil { } } } func TestChunkError(t *testing.T) { t.Parallel() // 并发运行 os.Setenv("APPBUILDER_LOGLEVEL", "DEBUG") knowledgeBaseID := os.Getenv(DatasetID) config, err := NewSDKConfig("", os.Getenv(SecretKey)) if err != nil { t.Logf("%s========== FAIL: %s ==========%s", "\033[31m", t.Name(), "\033[0m") t.Fatalf("new http client config failed: %v", err) } client, err := NewKnowledgeBaseWithKnowledgeBaseID(knowledgeBaseID, config) if err != nil { t.Logf("%s========== FAIL: %s ==========%s", "\033[31m", t.Name(), "\033[0m") t.Fatalf("new Knowledge base instance failed") } documentsRes, err := client.GetDocumentList(GetDocumentListRequest{ KnowledgeBaseID: knowledgeBaseID, }) if err != nil { t.Logf("%s========== FAIL: %s ==========%s", "\033[31m", t.Name(), "\033[0m") t.Fatalf("get document list failed: %v", err) } documentID := documentsRes.Data[0].ID var clientT = client.client var GatewayURL = client.sdkConfig.GatewayURLV2 // 测试创建切片 CreateChunk 测试1 ServiceURLV2 错误 client.sdkConfig.GatewayURLV2 = "://invalid-url" _, err = client.CreateChunk(CreateChunkRequest{ DocumentID: documentID, Content: "test", }) if err == nil { } // 测试创建切片 CreateChunk 测试2 Do 错误 client.sdkConfig.GatewayURLV2 = "http://192.0.2.1" _, err = client.CreateChunk(CreateChunkRequest{ DocumentID: documentID, Content: "test", }) if err == nil { } // 测试创建切片 CreateChunk 测试3 错误的 HTTP 响应 client.sdkConfig.GatewayURLV2 = GatewayURL client.client = &MockHTTPClient{} _, err = client.CreateChunk(CreateChunkRequest{ DocumentID: documentID, Content: "test", }) if err == nil { } // 测试创建切片 CreateChunk 测试 4: 模拟读取 body 时发生错误 client.sdkConfig.GatewayURLV2 = GatewayURL client.client = &FaultyHTTPClient{} _, err = client.CreateChunk(CreateChunkRequest{ DocumentID: documentID, Content: "test", }) if err == nil { } // 还原设置 client.sdkConfig.GatewayURLV2 = GatewayURL client.client = clientT // 创建切片 chunkID, err := client.CreateChunk(CreateChunkRequest{ DocumentID: documentID, Content: "test23", }) if err != nil { t.Logf("%s========== FAIL: %s ==========%s", "\033[31m", t.Name(), "\033[0m") t.Fatalf("create chunk failed: %v", err) } // 还原设置 client.sdkConfig.GatewayURLV2 = GatewayURL client.client = clientT // 修改切片 ModifyChunk 测试1 ServiceURLV2 错误 client.sdkConfig.GatewayURLV2 = "://invalid-url" err = client.ModifyChunk(ModifyChunkRequest{ ChunkID: chunkID, Content: "new test", Enable: true, }) if err == nil { } // 修改切片 ModifyChunk 测试2 Do 错误 client.sdkConfig.GatewayURLV2 = "http://192.0.2.1" err = client.ModifyChunk(ModifyChunkRequest{ ChunkID: chunkID, Content: "new test", Enable: true, }) if err == nil { } // 修改切片 ModifyChunk 测试3 错误的 HTTP 响应 client.sdkConfig.GatewayURLV2 = GatewayURL client.client = &MockHTTPClient{} err = client.ModifyChunk(ModifyChunkRequest{ ChunkID: chunkID, Content: "new test", Enable: true, }) if err == nil { } // 修改切片 ModifyChunk 测试 4: 模拟读取 body 时发生错误 client.sdkConfig.GatewayURLV2 = GatewayURL client.client = &FaultyHTTPClient{} err = client.ModifyChunk(ModifyChunkRequest{ ChunkID: chunkID, Content: "new test", Enable: true, }) if err == nil { } // 修改切片 ModifyChunk 测试 5: json.Unmarshal错误 client.sdkConfig.GatewayURLV2 = GatewayURL client.client = &InvalidJSONHTTPClient{} err = client.ModifyChunk(ModifyChunkRequest{ ChunkID: chunkID, Content: "new test", Enable: true, }) if err == nil { } // 还原设置 client.sdkConfig.GatewayURLV2 = GatewayURL client.client = clientT // 获取切片详情 DescribeChunk 测试1 ServiceURLV2 错误 client.sdkConfig.GatewayURLV2 = "://invalid-url" _, err = client.DescribeChunk(chunkID) if err == nil { } // 获取切片详情 DescribeChunk 测试2 Do 错误 client.sdkConfig.GatewayURLV2 = "http://192.0.2.1" _, err = client.DescribeChunk(chunkID) if err == nil { } // 获取切片详情 DescribeChunk 测试3 错误的 HTTP 响应 client.sdkConfig.GatewayURLV2 = GatewayURL client.client = &MockHTTPClient{} _, err = client.DescribeChunk(chunkID) if err == nil { } // 获取切片详情 DescribeChunk 测试 4: 模拟读取 body 时发生错误 client.sdkConfig.GatewayURLV2 = GatewayURL client.client = &FaultyHTTPClient{} _, err = client.DescribeChunk(chunkID) if err == nil { } // 获取切片详情 DescribeChunk 测试 5: json.Unmarshal错误 client.sdkConfig.GatewayURLV2 = GatewayURL client.client = &InvalidJSONHTTPClient{} _, err = client.DescribeChunk(chunkID) if err == nil { } // 还原设置 client.sdkConfig.GatewayURLV2 = GatewayURL client.client = clientT // 获取切片详情 DescribeChunk 测试1 ServiceURLV2 错误 client.sdkConfig.GatewayURLV2 = "://invalid-url" _, err = client.DescribeChunks(DescribeChunksRequest{ DocumnetID: documentID, Marker: chunkID, MaxKeys: 10, }) if err == nil { } // 获取切片详情 DescribeChunk 测试2 Do 错误 client.sdkConfig.GatewayURLV2 = "http://192.0.2.1" _, err = client.DescribeChunks(DescribeChunksRequest{ DocumnetID: documentID, Marker: chunkID, MaxKeys: 10, }) if err == nil { } // 获取切片详情 DescribeChunk 测试3 错误的 HTTP 响应 client.sdkConfig.GatewayURLV2 = GatewayURL client.client = &MockHTTPClient{} _, err = client.DescribeChunks(DescribeChunksRequest{ DocumnetID: documentID, Marker: chunkID, MaxKeys: 10, }) if err == nil { } // 获取切片详情 DescribeChunk 测试 4: 模拟读取 body 时发生错误 client.sdkConfig.GatewayURLV2 = GatewayURL client.client = &FaultyHTTPClient{} _, err = client.DescribeChunks(DescribeChunksRequest{ DocumnetID: documentID, Marker: chunkID, MaxKeys: 10, }) if err == nil { } // 获取切片详情 DescribeChunk 测试 5: json.Unmarshal错误 client.sdkConfig.GatewayURLV2 = GatewayURL client.client = &InvalidJSONHTTPClient{} _, err = client.DescribeChunks(DescribeChunksRequest{ DocumnetID: documentID, Marker: chunkID, MaxKeys: 10, }) if err == nil { } time.Sleep(10 * time.Second) // 还原设置 client.sdkConfig.GatewayURLV2 = GatewayURL client.client = clientT // 删除切片 DeleteChunk 测试1 ServiceURLV2 错误 client.sdkConfig.GatewayURLV2 = "://invalid-url" err = client.DeleteChunk(chunkID) if err == nil { } // 删除切片 DeleteChunk 测试2 Do 错误 client.sdkConfig.GatewayURLV2 = "http://192.0.2.1" err = client.DeleteChunk(chunkID) if err == nil { } // 删除切片 DeleteChunk 测试3 错误的 HTTP 响应 client.sdkConfig.GatewayURLV2 = GatewayURL client.client = &MockHTTPClient{} err = client.DeleteChunk(chunkID) if err == nil { } // 删除切片 DeleteChunk 测试 4: 模拟读取 body 时发生错误 client.sdkConfig.GatewayURLV2 = GatewayURL client.client = &FaultyHTTPClient{} err = client.DeleteChunk(chunkID) if err == nil { } // 删除切片 DeleteChunk 测试 5: json.Unmarshal错误 client.sdkConfig.GatewayURLV2 = GatewayURL client.client = &InvalidJSONHTTPClient{} err = client.DeleteChunk(chunkID) if err == nil { } // 还原设置 client.sdkConfig.GatewayURLV2 = GatewayURL client.client = clientT // 删除切片 err = client.DeleteChunk(chunkID) if err != nil { t.Logf("%s========== FAIL: %s ==========%s", "\033[31m", t.Name(), "\033[0m") t.Fatalf("delete chunk failed: %v", err) } } func TestAddDocument(t *testing.T) { t.Parallel() // 并发运行 var logBuffer bytes.Buffer os.Setenv("APPBUILDER_LOGLEVEL", "DEBUG") os.Setenv("APPBUILDER_LOGFILE", "") // 定义日志函数 log := func(format string, args ...any) { fmt.Fprintf(&logBuffer, format+"\n", args...) } knowledgeBaseID := os.Getenv(DatasetIDV3) config, err := NewSDKConfig("", os.Getenv(SecretKeyV3)) if err != nil { t.Logf("%s========== FAIL: %s ==========%s", "\033[31m", t.Name(), "\033[0m") t.Fatalf("new http client config failed: %v", err) } client, err := NewKnowledgeBase(config) if err != nil { t.Logf("%s========== FAIL: %s ==========%s", "\033[31m", t.Name(), "\033[0m") t.Fatalf("new Knowledge base instance failed") } documentsRes, err := client.GetDocumentList(GetDocumentListRequest{ KnowledgeBaseID: knowledgeBaseID, }) if err != nil { t.Logf("%s========== FAIL: %s ==========%s", "\033[31m", t.Name(), "\033[0m") t.Fatalf("get document list failed: %v", err) } log("Documents retrieved: %+v", documentsRes) fileID, err := client.UploadFile("./files/test.pdf") if err != nil { t.Logf("%s========== FAIL: %s ==========%s", "\033[31m", t.Name(), "\033[0m") t.Fatalf("upload file failed: %v", err) } log("File uploaded with ID: %s", fileID) createDocumentRes, err := client.CreateDocument(CreateDocumentRequest{ KnowledgeBaseID: knowledgeBaseID, ContentType: ContentTypeRawText, FileIDS: []string{fileID}, CustomProcessRule: &CustomProcessRule{ Separators: []string{"。"}, TargetLength: 300, OverlapRate: 0.25, }, }) if err != nil { t.Logf("%s========== FAIL: %s ==========%s", "\033[31m", t.Name(), "\033[0m") t.Fatalf("create document failed: %v", err) } log("Document created: %+v", createDocumentRes) // 正常测试部分 err = client.DeleteDocument(DeleteDocumentRequest{ KnowledgeBaseID: knowledgeBaseID, DocumentID: createDocumentRes.DocumentsIDS[0]}) if err != nil { t.Logf("%s========== FAIL: %s ==========%s", "\033[31m", t.Name(), "\033[0m") t.Fatalf("delete document failed: %v", err) } log("Document deleted with ID: %s", createDocumentRes.DocumentsIDS[0]) // 如果测试失败,则输出缓冲区中的日志 if t.Failed() { t.Logf("%s========== FAIL: %s ==========%s", "\033[31m", t.Name(), "\033[0m") fmt.Println(logBuffer.String()) } else { // else 紧跟在右大括号后面 // 测试通过,打印文件名和测试函数名 t.Logf("%s========== OK: %s ==========%s", "\033[32m", t.Name(), "\033[0m") } } func TestCreateKnowledgeBase(t *testing.T) { var logBuffer bytes.Buffer os.Setenv("APPBUILDER_LOGLEVEL", "DEBUG") log := func(format string, args ...any) { fmt.Fprintf(&logBuffer, format+"\n", args...) } config, err := NewSDKConfig("", os.Getenv(SecretKeyV3)) if err != nil { t.Logf("%s========== FAIL: %s ==========%s", "\033[31m", t.Name(), "\033[0m") t.Fatalf("new http client config failed: %v", err) } client, err := NewKnowledgeBase(config) if err != nil { t.Logf("%s========== FAIL: %s ==========%s", "\033[31m", t.Name(), "\033[0m") t.Fatalf("new Knowledge base instance failed") } // 创建知识库 var knowledgeBaseID string needDeleteKnowledgeBase := false createKnowledgeBaseRes, err := client.CreateKnowledgeBase(KnowledgeBaseDetail{ Name: "test-go", Description: "test-go", Config: &KnowlegeBaseConfig{ Index: KnowledgeBaseConfigIndex{ Type: "public", Password: "elastic", Username: "elastic", }, }, }) if err != nil { knowledgeBaseID = os.Getenv(DatasetIDV3) } else { needDeleteKnowledgeBase = true knowledgeBaseID = createKnowledgeBaseRes.ID } log("Knowledge base created with ID: %s", knowledgeBaseID) // 获取知识库详情 getKnowledgeBaseRes, err := client.GetKnowledgeBaseDetail(knowledgeBaseID) if err != nil { t.Logf("%s========== FAIL: %s ==========%s", "\033[31m", t.Name(), "\033[0m") t.Fatalf("get knowledge base failed: %v", err) } log("Knowledge base details: %+v", getKnowledgeBaseRes) // 获取知识库列表 knowledgeBaseListRes, err := client.GetKnowledgeBaseList( GetKnowledgeBaseListRequest{ Marker: knowledgeBaseID, }, ) if err != nil { t.Logf("%s========== FAIL: %s ==========%s", "\033[31m", t.Name(), "\033[0m") t.Fatalf("get knowledge base list failed: %v", err) } log("Knowledge base list: %+v", knowledgeBaseListRes) // 导入知识库 err = client.CreateDocuments(CreateDocumentsRequest{ ID: knowledgeBaseID, ContentFormat: "rawText", Source: DocumentsSource{ Type: "web", Urls: []string{"https://baijiahao.baidu.com/s?id=1802527379394162441"}, UrlDepth: 1, UrlConfigs: &[]DocumentsSourceUrlConfig{ { Frequency: 1, }, }, }, ProcessOption: &DocumentsProcessOption{ Template: "custom", Parser: &DocumentsProcessOptionParser{ Choices: []string{"layoutAnalysis", "ocr"}, }, Chunker: &DocumentsProcessOptionChunker{ Choices: []string{"separator"}, Separator: &DocumentsProcessOptionChunkerSeparator{ Separators: []string{"。"}, TargetLength: 300, OverlapRate: 0.25, }, PrependInfo: []string{"title", "filename"}, }, KnowledgeAugmentation: &DocumentsProcessOptionKnowledgeAugmentation{ Choices: []string{"faq"}, }, }, }) if err != nil { t.Logf("%s========== FAIL: %s ==========%s", "\033[31m", t.Name(), "\033[0m") t.Fatalf("create documents failed: %v", err) } log("Documents imported to knowledge base") // 导入知识库 createDocumentsRes, err := client.CreateDocumentsWithResp(CreateDocumentsRequest{ ID: knowledgeBaseID, ContentFormat: "rawText", Source: DocumentsSource{ Type: "web", Urls: []string{"https://baijiahao.baidu.com/s?id=1802527379394162441"}, UrlDepth: 1, }, ProcessOption: &DocumentsProcessOption{ Template: "custom", Parser: &DocumentsProcessOptionParser{ Choices: []string{"layoutAnalysis", "ocr"}, }, Chunker: &DocumentsProcessOptionChunker{ Choices: []string{"separator"}, Separator: &DocumentsProcessOptionChunkerSeparator{ Separators: []string{"。"}, TargetLength: 300, OverlapRate: 0.25, }, PrependInfo: []string{"title", "filename"}, }, KnowledgeAugmentation: &DocumentsProcessOptionKnowledgeAugmentation{ Choices: []string{"faq"}, }, }, }) if err != nil { t.Logf("%s========== FAIL: %s ==========%s", "\033[31m", t.Name(), "\033[0m") t.Fatalf("create documents failed: %v", err) } if len(createDocumentsRes.DocumentIDS) == 0 { t.Logf("%s========== FAIL: %s ==========%s", "\033[31m", t.Name(), "\033[0m") t.Fatalf("no documents imported to knowledge base") } log("Documents imported to knowledge base") // 上传知识库文档 err = client.UploadDocuments("./files/test.pdf", CreateDocumentsRequest{ ID: knowledgeBaseID, ContentFormat: "rawText", Source: DocumentsSource{ Type: "file", }, ProcessOption: &DocumentsProcessOption{ Template: "custom", Parser: &DocumentsProcessOptionParser{ Choices: []string{"layoutAnalysis", "ocr"}, }, Chunker: &DocumentsProcessOptionChunker{ Choices: []string{"separator"}, Separator: &DocumentsProcessOptionChunkerSeparator{ Separators: []string{"。"}, TargetLength: 300, OverlapRate: 0.25, }, PrependInfo: []string{"title", "filename"}, }, KnowledgeAugmentation: &DocumentsProcessOptionKnowledgeAugmentation{ Choices: []string{"faq"}, }, }, }) if err != nil { t.Logf("%s========== FAIL: %s ==========%s", "\033[31m", t.Name(), "\033[0m") t.Fatalf("upload documents failed: %v", err) } log("Documents uploaded to knowledge base") uploadDocumentsRes, err := client.UploadDocumentsWithResp("./files/test.pdf", CreateDocumentsRequest{ ID: knowledgeBaseID, ContentFormat: "rawText", Source: DocumentsSource{ Type: "file", }, ProcessOption: &DocumentsProcessOption{ Template: "custom", Parser: &DocumentsProcessOptionParser{ Choices: []string{"layoutAnalysis", "ocr"}, }, Chunker: &DocumentsProcessOptionChunker{ Choices: []string{"separator"}, Separator: &DocumentsProcessOptionChunkerSeparator{ Separators: []string{"。"}, TargetLength: 300, OverlapRate: 0.25, }, PrependInfo: []string{"title", "filename"}, }, KnowledgeAugmentation: &DocumentsProcessOptionKnowledgeAugmentation{ Choices: []string{"faq"}, }, }, }) if err != nil { t.Logf("%s========== FAIL: %s ==========%s", "\033[31m", t.Name(), "\033[0m") t.Fatalf("upload documents failed: %v", err) } if uploadDocumentsRes.DocumentID == "" { t.Logf("%s========== FAIL: %s ==========%s", "\033[31m", t.Name(), "\033[0m") t.Fatalf("no documents uploaded to knowledge base") } log("Documents uploaded to knowledge base") // 修改知识库 name := "test-go" description := "22" err = client.ModifyKnowledgeBase(ModifyKnowlegeBaseRequest{ ID: knowledgeBaseID, Name: &name, Description: &description, }) if err != nil { t.Logf("%s========== FAIL: %s ==========%s", "\033[31m", t.Name(), "\033[0m") t.Fatalf("modify knowledge base failed: %v", err) } log("Knowledge base modified with new name: %s", name) // 删除知识库 if needDeleteKnowledgeBase { err = client.DeleteKnowledgeBase(knowledgeBaseID) if err != nil { t.Logf("%s========== FAIL: %s ==========%s", "\033[31m", t.Name(), "\033[0m") t.Fatalf("delete knowledge base failed: %v", err) } log("Knowledge base deleted with ID: %s", knowledgeBaseID) } // 测试通过,打印文件名和测试函数名 t.Logf("%s========== OK: %s ==========%s", "\033[32m", t.Name(), "\033[0m") // 如果测试失败,则输出缓冲区中的日志 if t.Failed() { fmt.Println(logBuffer.String()) } } func TestChunk(t *testing.T) { t.Parallel() // 并发运行 var logBuffer bytes.Buffer os.Setenv("APPBUILDER_LOGLEVEL", "DEBUG") log := func(format string, args ...any) { fmt.Fprintf(&logBuffer, format+"\n", args...) } knowledgeBaseID := os.Getenv(DatasetID) config, err := NewSDKConfig("", os.Getenv(SecretKey)) if err != nil { t.Logf("%s========== FAIL: %s ==========%s", "\033[31m", t.Name(), "\033[0m") t.Fatalf("new http client config failed: %v", err) } client, err := NewKnowledgeBaseWithKnowledgeBaseID(knowledgeBaseID, config) if err != nil { t.Logf("%s========== FAIL: %s ==========%s", "\033[31m", t.Name(), "\033[0m") t.Fatalf("new Knowledge base instance failed") } _, err = client.GetDocumentList(GetDocumentListRequest{ KnowledgeBaseID: knowledgeBaseID, }) if err != nil { t.Logf("%s========== FAIL: %s ==========%s", "\033[31m", t.Name(), "\033[0m") t.Fatalf("get document list failed: %v", err) } documentsRes, err := client.DescribeDocuments(DescribeDocumentsRequest{KnowledgeBaseID: knowledgeBaseID}) if err != nil { t.Logf("%s========== FAIL: %s ==========%s", "\033[31m", t.Name(), "\033[0m") t.Fatalf("describe documents failed: %v", err) } log("Documents retrieved: %+v", documentsRes) documentID := documentsRes.Data[0].ID // 创建切片 chunkID, err := client.CreateChunk(CreateChunkRequest{ KnowledgeBaseID: knowledgeBaseID, DocumentID: documentID, Content: "test", }) if err != nil { t.Logf("%s========== FAIL: %s ==========%s", "\033[31m", t.Name(), "\033[0m") t.Fatalf("create chunk failed: %v", err) } log("Chunk created with ID: %s", chunkID) // 修改切片 err = client.ModifyChunk(ModifyChunkRequest{ KnowledgeBaseID: knowledgeBaseID, ChunkID: chunkID, Content: "new test", Enable: true, }) if err != nil { t.Logf("%s========== FAIL: %s ==========%s", "\033[31m", t.Name(), "\033[0m") t.Fatalf("modify chunk failed: %v", err) } log("Chunk modified with new content") // 获取切片详情 describeChunkRes, err := client.DescribeChunk(chunkID) if err != nil { t.Logf("%s========== FAIL: %s ==========%s", "\033[31m", t.Name(), "\033[0m") t.Fatalf("describe chunk failed: %v", err) } log("Chunk details: %+v", describeChunkRes) // 获取切片列表 describeChunksRes, err := client.DescribeChunks(DescribeChunksRequest{ KnowledgeBaseID: knowledgeBaseID, DocumnetID: documentID, MaxKeys: 10, Keyword: "test", }) if err != nil { t.Logf("%s========== FAIL: %s ==========%s", "\033[31m", t.Name(), "\033[0m") t.Fatalf("describe chunks failed: %v", err) } log("Chunks described: %+v", describeChunksRes) time.Sleep(10 * time.Second) // 删除切片 err = client.DeleteChunk(chunkID) if err != nil { t.Logf("%s========== FAIL: %s ==========%s", "\033[31m", t.Name(), "\033[0m") t.Fatalf("delete chunk failed: %v", err) } log("Chunk deleted with ID: %s", chunkID) // 如果测试失败,则输出缓冲区中的日志 if t.Failed() { t.Logf("%s========== FAIL: %s ==========%s", "\033[31m", t.Name(), "\033[0m") fmt.Println(logBuffer.String()) } else { // else 紧跟在右大括号后面 // 测试通过,打印文件名和测试函数名 t.Logf("%s========== OK: %s ==========%s", "\033[32m", t.Name(), "\033[0m") } } func TestQueryKnowledgeBase(t *testing.T) { t.Parallel() // 并发运行 var logBuffer bytes.Buffer os.Setenv("APPBUILDER_LOGLEVEL", "DEBUG") log := func(format string, args ...any) { fmt.Fprintf(&logBuffer, format+"\n", args...) } config, err := NewSDKConfig("", os.Getenv(SecretKey)) if err != nil { t.Logf("%s========== FAIL: %s ==========%s", "\033[31m", t.Name(), "\033[0m") t.Fatalf("new http client config failed: %v", err) } client, err := NewKnowledgeBase(config) if err != nil { t.Logf("%s========== FAIL: %s ==========%s", "\033[31m", t.Name(), "\033[0m") t.Fatalf("new Knowledge base instance failed") } jsonStr := ` { "type": "fulltext", "query": "民法典第三条", "knowledgebase_ids": [ "70c6375a-1595-41f2-9a3b-e81bc9060b7f" ], "metadata_filters": { "filters": [ ], "condition": "or" }, "pipeline_config": { "id": "pipeline_001", "pipeline": [ { "name": "step1", "type": "elastic_search", "threshold": 0.1, "top": 400, "pre_ranking": { "bm25_weight": 0.25, "vec_weight": 0.75, "bm25_b": 0.75, "bm25_k1": 1.5, "bm25_max_score": 50 } }, { "name": "step2", "type": "ranking", "inputs": ["step1"], "model_name": "ranker-v1", "top": 20 } ] }, "top": 5, "skip": 0 }` var request QueryKnowledgeBaseRequest err = json.Unmarshal([]byte(jsonStr), &request) if err != nil { fmt.Println("unmarshal tool error:", err) } queryKnowledgeBaseResponse, err := client.QueryKnowledgeBase(request) if err != nil { t.Logf("%s========== FAIL: %s ==========%s", "\033[31m", t.Name(), "\033[0m") t.Fatalf("create chunk failed: %v", err) } chunkID := queryKnowledgeBaseResponse.Chunks[0].ChunkID log("query got chunk ID: %s", chunkID) if len(chunkID) == 0 { t.Logf("%s========== FAIL: %s ==========%s", "\033[31m", t.Name(), "\033[0m") t.Fatalf("query knowledge base failed: %v", err) } // 如果测试失败,则输出缓冲区中的日志 if t.Failed() { t.Logf("%s========== FAIL: %s ==========%s", "\033[31m", t.Name(), "\033[0m") fmt.Println(logBuffer.String()) } else { // else 紧跟在右大括号后面 // 测试通过,打印文件名和测试函数名 t.Logf("%s========== OK: %s ==========%s", "\033[32m", t.Name(), "\033[0m") } } ================================================ FILE: go/appbuilder/rag.go ================================================ // Copyright (c) 2024 Baidu, Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package appbuilder import ( "bufio" "bytes" "encoding/json" "errors" "fmt" "net/http" "time" ) func NewRAG(appID string, config *SDKConfig) (*RAG, error) { if len(appID) == 0 { return nil, errors.New("appID is empty") } if config == nil { return nil, errors.New("invalid config") } client := config.HTTPClient if client == nil { client = &http.Client{Timeout: 500 * time.Second} } return &RAG{appID: appID, sdkConfig: config, client: client}, nil } type RAG struct { appID string sdkConfig *SDKConfig client HTTPClient } func (t *RAG) Run(conversationID string, query string, stream bool) (RAGIterator, error) { request := http.Request{} header := t.sdkConfig.AuthHeader() serviceURL, err := t.sdkConfig.ServiceURL("/api/v1/ai_engine/agi_platform/v1/instance/integrated") if err != nil { return nil, err } request.URL = serviceURL request.Method = "POST" header.Set("Content-Type", "application/json") request.Header = header req := map[string]string{"conversation_id": conversationID, "response_mode": "blocking", "query": query, "app_id": t.appID, } if stream { req["response_mode"] = "streaming" } data, _ := json.Marshal(req) request.Body = NopCloser(bytes.NewReader(data)) t.sdkConfig.BuildCurlCommand(&request) resp, err := t.client.Do(&request) if err != nil { return nil, err } requestID, err := checkHTTPResponse(resp) if err != nil { return nil, fmt.Errorf("requestID=%s, err=%v", requestID, err) } r := NewSSEReader(1024*1024, bufio.NewReader(resp.Body)) if stream { return &RAGStreamIterator{requestID: requestID, r: r, body: resp.Body}, nil } return &RAGOnceIterator{body: resp.Body, requestID: requestID}, nil } ================================================ FILE: go/appbuilder/rag_data.go ================================================ // Copyright (c) 2024 Baidu, Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package appbuilder import ( "encoding/json" "fmt" "io" "strings" ) type RAGRunResponse struct { Code int `json:"code"` Message string `json:"message"` Result RAGResult `json:"result"` } type RAGResult struct { ConversationID string `json:"conversation_id"` Answer string `json:"answer"` Content []RAGEvent `json:"content"` } type RAGEvent struct { Event string `json:"event"` EventStatus string `json:"event_status"` EventID string `json:"event_id"` EventType string `json:"type"` Text json.RawMessage `json:"text"` } type RAGAnswer struct { Answer string ConversationID string Events []RAGEvent } func (t *RAGAnswer) transform(res *RAGRunResponse) { t.Answer = res.Result.Answer t.ConversationID = res.Result.ConversationID t.Events = res.Result.Content } // RAGIterator 定义RAG流式/非流式迭代器接口 // 初始状态可迭代,如果返回error不为空则代表迭代结束, // error为io.EOF,则代表迭代正常结束,其它则为异常结束 type RAGIterator interface { // Next 获取处理结果,如果返回error不为空,迭代器自动失效,不允许再调用此方法 Next() (*RAGAnswer, error) } type RAGStreamIterator struct { requestID string r *sseReader body io.ReadCloser } func (t *RAGStreamIterator) Next() (*RAGAnswer, error) { data, err := t.r.ReadMessageLine() if err != nil && !(err == io.EOF) { t.body.Close() return nil, fmt.Errorf("requestID=%s, err=%v", t.requestID, err) } if err != nil && err == io.EOF { t.body.Close() return nil, err } if strings.HasPrefix(string(data), "data:") { var resp RAGRunResponse resp.Code = -1 if err := json.Unmarshal(data[5:], &resp); err != nil { t.body.Close() return nil, fmt.Errorf("requestID=%s, err=%v", t.requestID, err) } if resp.Code != 0 { t.body.Close() return nil, fmt.Errorf("requestID=%s, body=%s", t.requestID, string(data)) } answer := &RAGAnswer{} answer.transform(&resp) return answer, nil } // 非SSE格式关闭连接,并返回数据 t.body.Close() return nil, fmt.Errorf("requestID=%s, body=%s", t.requestID, string(data)) } // RAGOnceIterator 非流式返回时对应的迭代器,只可迭代一次 type RAGOnceIterator struct { body io.ReadCloser eoi bool requestID string } func (t *RAGOnceIterator) Next() (*RAGAnswer, error) { if t.eoi { return nil, io.EOF } data, err := io.ReadAll(t.body) if err != nil { return nil, fmt.Errorf("requestID=%s, err=%v", t.requestID, err) } defer t.body.Close() var resp RAGRunResponse resp.Code = -1 if err := json.Unmarshal(data, &resp); err != nil { return nil, fmt.Errorf("requestID=%s, err=%v", t.requestID, err) } if resp.Code != 0 { t.body.Close() return nil, fmt.Errorf("requestID=%s, body=%s", t.requestID, string(data)) } t.eoi = true answer := &RAGAnswer{} answer.transform(&resp) return answer, nil } ================================================ FILE: go/appbuilder/rag_test.go ================================================ // Copyright (c) 2024 Baidu, Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package appbuilder import ( "encoding/json" "errors" "fmt" "io" "os" "testing" ) func TestNewRAGError(t *testing.T) { t.Parallel() // 并发运行 // 设置环境变量 os.Setenv("APPBUILDER_LOGLEVEL", "DEBUG") // 测试逻辑 config, err := NewSDKConfig("", "") if err != nil { t.Logf("%s========== FAIL: %s ==========%s", "\033[31m", t.Name(), "\033[0m") t.Fatalf("new http client config failed: %v", err) } appID := "06e3f5c9-885d-4f85-af57-97dc85ee4606" // NewRAG测试 1: appID 为空,预期返回错误 _, err = NewRAG("", &SDKConfig{}) if err == nil || err.Error() != "appID is empty" { } // NewRAG测试 2: config 为 nil,预期返回错误 _, err = NewRAG("validAppID", nil) if err == nil || err.Error() != "config is nil" { } //RAG测试 rag, err := NewRAG(appID, config) if err != nil { } // CreateConversation测试 1: ServiceURLV2 错误 rag.sdkConfig.GatewayURLV2 = "://invalid-url" _, err = rag.Run("", "北京有多少小学生", true) if err == nil { } // CreateConversation测试 2: HTTP client do error rag.sdkConfig.GatewayURLV2 = "http://192.0.2.1" _, err = rag.Run("", "北京有多少小学生", true) if err == nil { } // CreateConversation测试 3: checkHTTPResponse 400 错误 rag.client = &MockHTTPClient{} _, err = rag.Run("", "北京有多少小学生", true) if err == nil { } // CreateConversation测试 4: 非流式运行 rag.client = &FaultyHTTPClient{} _, err = rag.Run("", "北京有多少小学生", false) if err == nil { } } func TestNewRAG(t *testing.T) { // 设置环境变量 os.Setenv("APPBUILDER_LOGLEVEL", "DEBUG") // 测试逻辑 config, err := NewSDKConfig("", os.Getenv(SecretKey)) if err != nil { t.Logf("%s========== FAIL: %s ==========%s", "\033[31m", t.Name(), "\033[0m") t.Fatalf("new http client config failed: %v", err) } appID := "06e3f5c9-885d-4f85-af57-97dc85ee4606" //RAG测试 rag, err := NewRAG(appID, config) if err != nil { t.Fatalf("new RAG instance failed") } i, err := rag.Run("", "北京有多少小学生", true) if err != nil { t.Fatalf("run RAG failed: %v", err) } var answer *RAGAnswer for answer, err = i.Next(); err == nil; answer, err = i.Next() { data, _ := json.Marshal(answer) fmt.Println(string(data)) fmt.Println(answer.ConversationID) } if !errors.Is(err, io.EOF) { fmt.Println(err) } } ================================================ FILE: go/appbuilder/util.go ================================================ // Copyright (c) 2024 Baidu, Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package appbuilder import ( "bufio" "bytes" "errors" "fmt" "io" "log" "net/http" ) type SSEEvent struct { LastEventID string Type string Data string } func checkHTTPResponse(rsp *http.Response) (string, error) { requestID := rsp.Header.Get("X-Appbuilder-Request-Id") if rsp.StatusCode == http.StatusOK { log.Printf("Successful HTTP response. RequestID: %s", requestID) return requestID, nil } data, err := io.ReadAll(rsp.Body) if err != nil { log.Printf("Failed to read response body. RequestID: %s, Error: %v", requestID, err) return requestID, err } log.Printf("HTTP response with unexpected status code. RequestID: %s, StatusCode: %d, Content: %s", requestID, rsp.StatusCode, string(data)) return requestID, fmt.Errorf("http status code is %d, content is %s", rsp.StatusCode, string(data)) } func NewSSEReader(bufSize int, reader *bufio.Reader) *sseReader { //buf := make([]byte, bufSize) return &sseReader{reader: reader, buf: bytes.Buffer{}} } type sseReader struct { reader *bufio.Reader buf bytes.Buffer } func (t *sseReader) ReadMessageLine() ([]byte, error) { t.buf.Reset() for { line, isPrefix, err := t.reader.ReadLine() if err != nil { return nil, err } t.buf.Grow(len(line)) t.buf.Write(line) if !isPrefix { break } } // 读取空行 line, _, err := t.reader.ReadLine() if err != nil || len(line) != 0 { t.buf.Grow(len(line)) return nil, errors.New(t.buf.String()) } return t.buf.Bytes(), nil } ================================================ FILE: go/run_go_test.sh ================================================ #!/bin/bash # 启用错误检测和管道失败检测 set -o pipefail # 初始化错误标志 error_flag=0 # 用于存储错误消息 error_messages=() # 检查并添加必要的路径 export PATH="$HOME/.local/bin:$PATH" export PATH="$PATH:$(go env GOPATH)/bin" pip install diff-cover || { error_flag=1; error_messages+=("Failed to install diff-cover."); } # 检查 diff-cover 是否已安装 if ! command -v diff-cover &> /dev/null; then error_flag=1 error_messages+=("diff-cover installation failed. Please check your Python and pip installation.") fi echo "diff-cover is installed." # 安装 gocov 和 gocov-xml,如果未安装 if ! command -v gocov &> /dev/null; then echo "gocov not found, installing..." go install github.com/axw/gocov/gocov@latest || { error_flag=1; error_messages+=("Failed to install gocov."); } fi if ! command -v gocov-xml &> /dev/null; then echo "gocov-xml not found, installing..." go install github.com/AlekSi/gocov-xml@latest || { error_flag=1; error_messages+=("Failed to install gocov-xml."); } fi # 添加 GOPATH/bin 到 PATH,以便找到 gocov 和 gocov-xml export PATH="$PATH:$(go env GOPATH)/bin" # 验证 gocov 和 gocov-xml 是否安装成功 if ! command -v gocov &> /dev/null; then error_flag=1 error_messages+=("gocov installation failed.") fi if ! command -v gocov-xml &> /dev/null; then error_flag=1 error_messages+=("gocov-xml installation failed.") fi echo "gocov and gocov-xml are installed." # 初始化计数器 total_tests=0 skipped_tests=0 failed_tests=0 passed_tests=0 # 用于存储跳过和失败的测试函数 skipped_list=() failed_list=() # 创建临时文件用于存储测试输出和覆盖率数据 test_output=$(mktemp) coverage_file=$(mktemp) # 确保临时文件创建成功 if [ ! -f "$test_output" ] || [ ! -f "$coverage_file" ]; then echo "无法创建临时文件。" exit 1 fi # 运行所有包的测试并保存输出 echo "运行所有包的测试并生成覆盖率报告..." set +e cd appbuilder go test ./... -coverprofile="$coverage_file" -covermode=atomic -timeout 20m -v > "$test_output" 2>&1 GO_TEST_EXIT_CODE=$? set -e echo "Go test 退出代码: $GO_TEST_EXIT_CODE" # 检查覆盖率文件是否生成且非空 if [ ! -s "$coverage_file" ]; then echo "覆盖率文件未生成或为空。" error_flag=1 error_messages+=("Coverage profile not generated or empty.") fi # 解析测试结果 current_test="" while IFS= read -r line; do if [[ "$line" == "=== RUN"* ]]; then # 提取测试函数名称 test_name=$(echo "$line" | awk '{print $3}') # 提取包路径 pkg=$(echo "$line" | awk '{print $2}' | sed 's/(//;s/)//') current_test="$pkg.$test_name" elif [[ "$line" == "--- PASS:"* ]]; then echo "[OK] $current_test" passed_tests=$((passed_tests + 1)) passed_list+=("$current_test") elif [[ "$line" == "--- FAIL:"* ]]; then echo "[FAIL] $current_test" failed_tests=$((failed_tests + 1)) failed_list+=("$current_test") elif [[ "$line" == "--- SKIP:"* ]]; then echo "[SKIP] $current_test" skipped_tests=$((skipped_tests + 1)) skipped_list+=("$current_test") fi done < "$test_output" # 计算总测试数 total_tests=$((passed_tests + failed_tests + skipped_tests)) # 输出测试总结 echo "" echo "=== 测试总结 ===" echo "总测试数: $total_tests" echo "成功: $passed_tests" echo "失败: $failed_tests" echo "跳过: $skipped_tests" # 检查错误标志,如果有错误则输出错误消息并退出 if [ $error_flag -ne 0 ]; then echo "在过程中检测到以下错误:" for msg in "${error_messages[@]}"; do echo "- $msg" done exit 1 fi # 打印测试失败时的详细日志 if [ $GO_TEST_EXIT_CODE -ne 0 ]; then echo "测试运行过程中失败,错误代码: $GO_TEST_EXIT_CODE" echo "请查看详细的测试日志:" echo "----------------------------------------" cat "$test_output" # 打印测试的输出日志 echo "----------------------------------------" exit 1 fi # 输出覆盖率摘要 echo "--------------------------" echo "全量代码覆盖率为:" go tool cover -func=$coverage_file # 将覆盖率数据转换为 XML 格式 echo "Converting coverage data to XML format..." if ! gocov convert $coverage_file | gocov-xml > coverage.xml; then error_flag=1 error_messages+=("Failed to convert coverage data to XML format.") fi # 检查 coverage.xml 是否非空 if [ ! -s coverage.xml ]; then error_flag=1 error_messages+=("Coverage XML file is empty or invalid.") fi # 生成包含所有文件的差异文件 echo "Generating full diff..." if ! git diff $(git hash-object -t tree /dev/null) HEAD > full_diff.patch; then error_flag=1 error_messages+=("Failed to generate full diff.") fi # 使用 diff-cover 生成全量覆盖率报告 echo "Generating full coverage report..." if ! diff-cover coverage.xml --diff-file full_diff.patch --html-report coverage_full.html; then error_flag=1 error_messages+=("Failed to generate full coverage report.") else echo "Full coverage report generated at coverage_full.html" fi # 计算增量代码的单测覆盖率 base_branch="upstream/master" # 生成增量覆盖率报告 echo "--------------------------" echo "增量代码覆盖率为:" git diff $base_branch --name-only -- '*.go' > diff_files.txt # 检查是否有修改的 go 文件 if [ -s diff_files.txt ]; then if ! diff-cover coverage.xml --compare-branch=$base_branch --html-report coverage_diff.html; then error_flag=1 error_messages+=("Failed to generate incremental coverage report.") else echo "Incremental coverage report generated at coverage_diff.html" fi else echo "No Go files changed relative to $base_branch. Incremental coverage not generated." fi # 清理 rm diff_files.txt rm full_diff.patch # 清理临时文件 rm "$test_output" rm "$coverage_file" # 检查错误标志,如果有错误则输出错误消息并退出 if [ $error_flag -ne 0 ]; then echo "Errors were detected during the process:" for msg in "${error_messages[@]}"; do echo "- $msg" done exit 1 fi ================================================ FILE: java/parse_tests_and_coverage.py ================================================ #!/usr/bin/env python3 import os import sys import subprocess import glob # 添加这一行 from lxml import etree from git import Repo from collections import defaultdict def parse_surefire_reports(): """解析 Maven Surefire 生成的测试报告,打印每个测试的结果,并汇总测试统计信息。""" surefire_reports = glob.glob('target/surefire-reports/*.xml') if not surefire_reports: print("未找到 Surefire 报告文件(target/surefire-reports/*.xml)。") sys.stdout.flush() # 立即刷新输出 return None total_tests = 0 total_failures = 0 total_errors = 0 total_skipped = 0 passed_tests = [] failed_tests = [] print("\n=== 测试结果 ===") sys.stdout.flush() # 立即刷新输出 for report in surefire_reports: try: tree = etree.parse(report) root = tree.getroot() test_suite_name = root.get('name', 'Unknown Test Suite') for test_case in root.findall('testcase'): test_name = test_case.get('name') class_name = test_case.get('classname') status = "OK" error_message = "" if test_case.find('failure') is not None: status = "FAIL" error = test_case.find('failure') error_message = error.text.strip() if error.text else "未知错误" failed_tests.append((class_name, test_name, error_message)) total_failures += 1 elif test_case.find('error') is not None: status = "ERROR" error = test_case.find('error') error_message = error.text.strip() if error.text else "未知错误" failed_tests.append((class_name, test_name, error_message)) total_errors += 1 elif test_case.find('skipped') is not None: status = "SKIPPED" total_skipped += 1 else: passed_tests.append((class_name, test_name)) total_tests += 1 # 打印每个测试的结果 if status == "OK": print(f"[OK] {class_name}.{test_name}") elif status in ["FAIL", "ERROR"]: print(f"[{status}] {class_name}.{test_name}") print(f" 错误信息: {error_message}") elif status == "SKIPPED": print(f"[SKIPPED] {class_name}.{test_name}") sys.stdout.flush() # 立即刷新输出 except etree.XMLSyntaxError as e: print(f"XML 解析错误在文件 {report}: {e}") sys.stdout.flush() # 立即刷新输出 except Exception as e: print(f"解析报告文件 {report} 时发生错误: {e}") sys.stdout.flush() # 立即刷新输出 # 打印测试总结 print("\n=== 测试总结 ===") print(f"总测试数: {total_tests}") print(f"成功: {len(passed_tests)}") print(f"失败: {total_failures}") print(f"错误: {total_errors}") print(f"跳过: {total_skipped}") sys.stdout.flush() # 立即刷新输出 return { "total_tests": total_tests, "passed": len(passed_tests), "failures": total_failures, "errors": total_errors, "skipped": total_skipped } def parse_jacoco(): """解析 JaCoCo XML 报告,打印覆盖率详情并返回包含类名和未覆盖行号的字典。""" JACOCO_XML = "target/site/jacoco/jacoco.xml" if not os.path.isfile(JACOCO_XML): print("jacoco.xml 未找到。请先运行 'mvn jacoco:report' 生成报告。") sys.stdout.flush() # 立即刷新输出 return {} try: parser = etree.XMLParser(load_dtd=False, no_network=True, recover=True) tree = etree.parse(JACOCO_XML, parser) root = tree.getroot() except etree.XMLSyntaxError as e: print(f"XML 解析错误: {e}") sys.stdout.flush() # 立即刷新输出 return {} except Exception as e: print(f"解析 jacoco.xml 时发生错误: {e}") sys.stdout.flush() # 立即刷新输出 return {} # 初始化总计数器 total_lines_missed = 0 total_lines_covered = 0 total_branches_missed = 0 total_branches_covered = 0 # 创建数据表 table_data = [["Class", "Line Coverage (%)", "Branch Coverage (%)", "Missing Lines", "Missing Branches"]] # 初始化存储结果的字典 coverage_data = {} # 遍历所有 class 元素 for class_element in root.findall('.//class'): class_name = class_element.get('name') # 行覆盖率 counter_line = class_element.find("counter[@type='LINE']") if counter_line is not None: lines_missed = int(counter_line.get('missed', '0')) lines_covered = int(counter_line.get('covered', '0')) else: lines_missed = 0 lines_covered = 0 total_lines_missed += lines_missed total_lines_covered += lines_covered # 分支覆盖率 counter_branch = class_element.find("counter[@type='BRANCH']") if counter_branch is not None: branches_missed = int(counter_branch.get('missed', '0')) branches_covered = int(counter_branch.get('covered', '0')) total_branches = branches_missed + branches_covered if total_branches > 0: branch_coverage = f"{(branches_covered / total_branches) * 100:.2f}%" else: branch_coverage = "N/A" else: branches_missed = 0 branches_covered = 0 branch_coverage = "N/A" total_lines_missed += lines_missed total_lines_covered += lines_covered total_branches_missed += branches_missed total_branches_covered += branches_covered # 获取 sourcefilename 属性 sourcefilename = class_element.get('sourcefilename') if sourcefilename: package_element = class_element.getparent() if package_element is not None and package_element.tag == 'package': sourcefile_element = package_element.find(f"sourcefile[@name='{sourcefilename}']") if sourcefile_element is not None: # 查找 mi > 0 的行号(未覆盖的行) missing_lines = [ int(line.get('nr')) for line in sourcefile_element.findall('line') if line.get('mi') and int(line.get('mi')) > 0 ] missing_lines_str = ",".join(map(str, missing_lines)) if missing_lines else "-" # 查找 mb > 0 的分支(未覆盖的分支) missing_branches = [ int(line.get('nr')) for line in sourcefile_element.findall('line') if line.get('mb') and int(line.get('mb')) > 0 ] missing_branches_str = ",".join(map(str, missing_branches)) if missing_branches else "-" else: missing_lines_str = "N/A" missing_branches_str = "N/A" else: missing_lines_str = "N/A" missing_branches_str = "N/A" else: missing_lines_str = "N/A" missing_branches_str = "N/A" # 计算行覆盖率 total_lines = lines_missed + lines_covered if total_lines > 0: line_coverage = (lines_covered / total_lines) * 100 else: line_coverage = 0.0 table_data.append([class_name, f"{line_coverage:.2f}%", branch_coverage, missing_lines_str, missing_branches_str]) # Populate coverage_data dictionary if there are missing lines if missing_lines_str != "N/A" and missing_lines_str != "-": coverage_data[class_name] = [int(line) for line in missing_lines_str.split(',')] # 计算总覆盖率 total_lines = total_lines_missed + total_lines_covered if total_lines > 0: total_line_coverage = (total_lines_covered / total_lines) * 100 else: total_line_coverage = 0.0 total_branches = total_branches_missed + total_branches_covered if total_branches > 0: total_branch_coverage = (total_branches_covered / total_branches) * 100 else: total_branch_coverage = "N/A" # 添加总覆盖率到数据表 table_data.append(["-----------------------------", "----------------", "----------------", "----------------", "----------------"]) table_data.append(["Total Coverage:", f"{total_line_coverage:.2f}%", f"{total_branch_coverage}", "", ""]) # 计算每列的最大宽度 num_columns = len(table_data[0]) col_widths = [0] * num_columns for row in table_data: for idx, col in enumerate(row): if len(col) > col_widths[idx]: col_widths[idx] = len(col) # 打印覆盖率详情 print("\n=== 覆盖率详情 ===") for row in table_data: if len(row) == 1: print(row[0]) else: row_str = "" for idx, col in enumerate(row): # 左对齐并加上适当的空格 row_str += col.ljust(col_widths[idx] + 2) print(row_str) sys.stdout.flush() # 立即刷新输出 return coverage_data def get_modified_files(repo, base_branch, path_pattern='src/main/**/*.java'): """ 获取相对于 base_branch 的修改文件及其修改的行号 返回一个字典:{file_path: set(line_numbers)} """ # 获取 diff 输出,带有行号 diff_command = [ 'git', 'diff', base_branch, '--unified=0', '--', path_pattern ] try: diff_output = subprocess.check_output(diff_command, stderr=subprocess.STDOUT).decode('utf-8') except subprocess.CalledProcessError as e: print(f"执行 git diff 失败: {e.output.decode('utf-8')}") sys.stdout.flush() sys.exit(1) modified_files = defaultdict(set) # {file_path: set(line_numbers)} current_file = None line_num = 0 for line in diff_output.splitlines(): if line.startswith('diff --git'): parts = line.split() if len(parts) >= 4: a_path = parts[2][2:] b_path = parts[3][2:] current_file = b_path # 使用新文件路径 elif line.startswith('@@'): if current_file: # 解析 hunk header # 格式: @@ -start,count +start,count @@ hunk_header = line try: hunk_info = hunk_header.split(' ')[1:3] new_hunk = hunk_info[1] start, count = new_hunk[1:].split(',') start = int(start) count = int(count) except Exception as e: print(f"解析 hunk header 失败: {hunk_header}, 错误: {e}") sys.stdout.flush() continue line_num = start elif line.startswith('+') and not line.startswith('+++'): if current_file: modified_files[current_file].add(line_num) line_num += 1 elif line.startswith('-') and not line.startswith('---'): # 删除的行,不需要增加 line_num pass else: # 其他情况,不处理 pass return modified_files def generate_incremental_coverage_report(modified_files, coverage_data): """ 生成增量代码覆盖率报告 """ total_modified = 0 total_uncovered = 0 per_file_report = [] # 遍历修改的文件和行号 for file_path, modified_lines in modified_files.items(): # 将文件路径转换为类名,去掉 'java/src/main/java/' 和 '.java' class_name = file_path.replace('java/src/main/java/', '').replace('.java', '') # 从 coverage_data 中查找对应的类名 missing_lines = coverage_data.get(class_name, []) # 计算被覆盖和未被覆盖的行 uncovered_in_modified = modified_lines.intersection(missing_lines) covered_in_modified = modified_lines.difference(missing_lines) total_modified += len(modified_lines) total_uncovered += len(uncovered_in_modified) # 保存每个文件的报告 per_file_report.append({ 'file': file_path, 'modified': sorted(modified_lines), 'covered': sorted(covered_in_modified), 'uncovered': sorted(uncovered_in_modified) }) # 计算增量覆盖率 coverage_percent = ((total_modified - total_uncovered) / total_modified) * 100 if total_modified > 0 else 0.0 # 生成报告输出 report_lines = [] report_lines.append("=== 增量代码覆盖率报告 ===\n") for file_report in per_file_report: report_lines.append(f"文件: {file_report['file']}") report_lines.append(f"修改的行数: {len(file_report['modified'])}") report_lines.append(f"被覆盖的行数: {len(file_report['covered'])}") report_lines.append(f"未被覆盖的行数: {len(file_report['uncovered'])}") if file_report['uncovered']: report_lines.append(f"未覆盖的行号: {', '.join(map(str, file_report['uncovered']))}") report_lines.append("\n") # 增量覆盖率总结 report_lines.append("=== 总结 ===") report_lines.append(f"总修改行数: {total_modified}") report_lines.append(f"总未被覆盖行数: {total_uncovered}") report_lines.append(f"增量覆盖率: {coverage_percent:.2f}%") report = "\n".join(report_lines) print(report) sys.stdout.flush() return { 'total_modified': total_modified, 'total_uncovered': total_uncovered, 'coverage_percent': coverage_percent, 'details': per_file_report } def main(): """主函数,执行所有步骤。""" parse_surefire_reports() # 假设 parse_jacoco() 已经正确返回了覆盖率数据字典 coverage_data = parse_jacoco() # 获取增量修改的文件及行号 repo = Repo(os.getcwd(), search_parent_directories=True) base_branch = "upstream/master" modified_files = get_modified_files(repo, base_branch, path_pattern='src/main/**/*.java') # 生成增量覆盖率报告 generate_incremental_coverage_report(modified_files, coverage_data) if __name__ == "__main__": main() ================================================ FILE: java/pom.xml ================================================ 4.0.0 com.baidubce appbuilder 1.1.3 jar app-builder The Java SDK for Baidu AppBuilder Platform. https://github.com/baidubce/app-builder The Apache License, Version 2.0 http://www.apache.org/licenses/LICENSE-2.0.txt bce Baidu Cloud https://cloud.baidu.com/ scm:git:git://github.com/baidubce/app-builder.git scm:git:ssh://github.com:baidubce/app-builder.git https://github.com/baidubce/app-builder/tree/master 1.8 ${java.version} ${java.version} UTF-8 org.apache.httpcomponents.client5 httpclient5 5.2.1 com.google.code.gson gson 2.10.1 junit junit 4.13.2 test org.mockito mockito-core 4.0.0 test org.apache.maven.plugins maven-compiler-plugin 3.12.1 ${java.version} ${java.version} org.apache.maven.plugins maven-source-plugin 3.3.0 attach-sources jar-no-fork org.apache.maven.plugins maven-javadoc-plugin 3.6.3 attach-javadocs jar org.jacoco jacoco-maven-plugin 0.8.7 prepare-agent report report jacoco-check check BUNDLE INSTRUCTION COVEREDRATIO 0.00 BRANCH COVEREDRATIO 0.00 LINE COVEREDRATIO 0.00 org.codehaus.mojo exec-maven-plugin 3.0.0 java com.baidubce.appbuilder.MainClass org.apache.maven.plugins maven-gpg-plugin 3.1.0 sign-artifacts verify sign org.sonatype.central central-publishing-maven-plugin 0.9.0 true central central org.apache.maven.plugins maven-gpg-plugin 3.1.0 sign-artifacts verify sign ================================================ FILE: java/print_coverage.sh ================================================ #!/bin/bash # 设置脚本退出时错误码 set -e # 运行 Maven 测试并生成 JaCoCo 报告,捕获输出 echo "运行 Maven 测试并生成 JaCoCo 报告..." if mvn clean test jacoco:report jacoco:check > mvn_output.log 2>&1; then echo "Maven 测试成功。" else echo "Maven 测试失败。查看详细错误日志:" cat mvn_output.log exit 1 # 直接退出 fi # 更新 PATH export PATH="$HOME/.local/bin:$PATH" # 运行 Python 脚本解析测试和覆盖率报告 python parse_tests_and_coverage.py ================================================ FILE: java/src/main/java/com/baidubce/appbuilder/base/component/Component.java ================================================ package com.baidubce.appbuilder.base.component; import com.baidubce.appbuilder.base.config.AppBuilderConfig; import com.baidubce.appbuilder.base.utils.http.HttpClient; public class Component { protected HttpClient httpClient; public Component() { //从环境变量获取 initClient("", ""); } public Component(String secretKey) { initClient(secretKey, ""); } public Component(String secretKey, String gateway) { initClient(secretKey, gateway); } private void initClient(String secretKey, String gateway) { gateway = getEnvWithDefault(AppBuilderConfig.APPBUILDER_GATEWAY_URL, gateway, AppBuilderConfig.APPBUILDER_DEFAULT_GATEWAY); String gatewayV2 = getEnvWithDefault(AppBuilderConfig.APPBUILDER_GATEWAY_URL_V2, "", AppBuilderConfig.APPBUILDER_DEFAULT_GATEWAY_V2); secretKey = getEnvWithDefault(AppBuilderConfig.APPBUILDER_TOKEN, secretKey, ""); if (secretKey.isEmpty()) { throw new RuntimeException("param secretKey is null and env APPBUILDER_TOKEN not set!"); } String secretKeyPrefix = getEnvWithDefault(AppBuilderConfig.APPBUIDLER_SECRET_KEY_PREFIX, "", AppBuilderConfig.APPBUILDER_DEFAULT_SECRET_KEY_PREFIX); if (!secretKey.startsWith(secretKeyPrefix)) { secretKey = String.format("%s %s", secretKeyPrefix, secretKey); } this.httpClient = new HttpClient(secretKey, gateway, gatewayV2); this.httpClient.ConsoleOpenAPIPrefix = getEnvWithDefault(AppBuilderConfig.APPBUILDER_CONSOLE_OPENAPI_PREFIX, "", AppBuilderConfig.APPBUILDER_DEFAULT_CONSOLE_OPENAPI_PREFIX); this.httpClient.ConsoleOpenAPIVersion = getEnvWithDefault(AppBuilderConfig.APPBUILDER_CONSOLE_OPENAPI_VERSION, "", AppBuilderConfig.APPBUILDER_DEFAULT_CONSOLE_OPENAPI_VERSION); } private String getEnvWithDefault(String propertyKey, String currentValue, String defaultValue) { if (currentValue == null || currentValue.isEmpty()) { currentValue = System.getProperty(propertyKey); if (currentValue == null) { currentValue = System.getenv(propertyKey); } if (currentValue == null) { currentValue = defaultValue; } } return currentValue; } } ================================================ FILE: java/src/main/java/com/baidubce/appbuilder/base/config/AppBuilderConfig.java ================================================ package com.baidubce.appbuilder.base.config; public class AppBuilderConfig { public static final String APPBUILDER_TOKEN = "APPBUILDER_TOKEN"; public static final String APPBUILDER_GATEWAY_URL = "GATEWAY_URL"; public static final String APPBUILDER_GATEWAY_URL_V2 = "GATEWAY_URL_V2"; public static final String APPBUILDER_CONSOLE_OPENAPI_VERSION = "CONSOLE_OPENAPI_VERSION"; public static final String APPBUILDER_CONSOLE_OPENAPI_PREFIX = "CONSOLE_OPENAPI_PREFIX"; public static final String APPBUIDLER_SECRET_KEY_PREFIX = "SECRET_KEY_PREFIX"; public static final String APPBUILDER_REQUEST_ID = "X-Appbuilder-Request-Id"; public static final String APPBUILDER_DEFAULT_GATEWAY = "https://appbuilder.baidu.com"; public static final String APPBUILDER_DEFAULT_GATEWAY_V2 = "https://qianfan.baidubce.com"; public static final String APPBUILDER_DEFAULT_CONSOLE_OPENAPI_VERSION = "/v2"; public static final String APPBUILDER_DEFAULT_CONSOLE_OPENAPI_PREFIX = ""; public static final String APPBUILDER_DEFAULT_SECRET_KEY_PREFIX = "Bearer"; public static final String APPBUILDER_LOGLEVEL = "APPBUILDER_LOGLEVEL"; public static final String APPBUILDER_LOGFILE = "APPBUILDER_LOGFILE"; // http client请求超时时间,秒 public static final int HTTP_CLIENT_CONNECTION_TIMEOUT = 1800; // appbuilderclient // 应用列表 public static final String APP_LIST_URL = "/apps"; public static final String APPS_DESCRIBE_URL = "/app?Action=DescribeApps"; // 应用详情 public static final String APP_DESCRIBE_URL = "/app?Action=DescribeApp"; // 创建会话 public static final String CREATE_CONVERSATION_URL = "/app/conversation"; // 上传文件 public static final String UPLOAD_FILE_URL = "/app/conversation/file/upload"; // 运行appbuilder public static final String AGENTBUILDER_RUN_URL = "/app/conversation/runs"; // 点踩点赞 public static final String FEEDBACK_URL = "/app/conversation/feedback"; // knowledgebase // 上传文件 public static final String KNOWLEDGEBASE_UPLOAD_FILE_URL = "/file"; // 新增知识库文档 public static final String KNOWLEDGEBASE_ADD_DOCUMENT_URL = "/knowledge_base/document"; // 获取知识库文档列表 public static final String KNOWLEDGEBASE_DOCUMENT_LIST_URL = "/knowledge_base/documents"; public static final String DESCRIBE_DOCUMENTS_URL = "/knowledgeBase?Action=DescribeDocuments"; // 删除知识库文档 public static final String KNOWLEDGEBASE_DELETE_DOCUMENT_URL = "/knowledge_base/document"; // 创建知识库 public static final String KNOWLEDGEBASE_CREATE_URL = "/knowledgeBase?Action=CreateKnowledgeBase"; // 获取知识库详情 public static final String KNOWLEDGEBASE_DETAIL_URL = "/knowledgeBase?Action=DescribeKnowledgeBase"; // 删除知识库 public static final String KNOWLEDGEBASE_DELETE_URL = "/knowledgeBase?Action=DeleteKnowledgeBase"; // 获取知识库列表 public static final String KNOWLEDGEBASE_LIST_URL = "/knowledgeBase?Action=DescribeKnowledgeBases"; // 更新知识库 public static final String KNOWLEDGEBASE_MODIFY_URL = "/knowledgeBase?Action=ModifyKnowledgeBase"; // 导入知识库 public static final String KNOWLEDGEBASE_CREATE_DOCUMENTS_URL = "/knowledgeBase?Action=CreateDocuments"; // 上传文件到知识库 public static final String KNOWLEDGEBASE_UPLOAD_DOCUMENTS_URL = "/knowledgeBase?Action=UploadDocuments"; // 创建切片 public static final String CHUNK_CREATE_URL = "/knowledgeBase?Action=CreateChunk"; // 修改切片 public static final String CHUNK_MODIFY_URL = "/knowledgeBase?Action=ModifyChunk"; // 获取切片详情 public static final String CHUNK_DESCRIBE_URL = "/knowledgeBase?Action=DescribeChunk"; // 获取切片列表 public static final String CHUNKS_DESCRIBE_URL = "/knowledgeBase?Action=DescribeChunks"; // 删除切片 public static final String CHUNK_DELETE_URL = "/knowledgeBase?Action=DeleteChunk"; // 知识库检索 public static final String QUERY_KNOWLEDGEBASE_URL = "/knowledgebases/query"; // 组件调用 public static final String COMPONENT_RUN_URL = "/components"; // AI搜索、基础搜索 public static final String AI_SEARCH_URL = "/ai_search/chat/completions"; // 运行rag public static final String RAG_RUN_URL = "/api/v1/ai_engine/agi_platform/v1/instance/integrated"; // dataset // 创建数据集 public static final String DATASET_CREATE_URL = "/api/v1/ai_engine/agi_platform/v1/datasets/create"; // 新增文档 public static final String DATASET_ADD_FILE_URL = "/api/v1/ai_engine/agi_platform/v1/datasets/documents"; // 获取文档列表 public static final String DATASET_GET_FILE_LIST_URL = "/api/v1/ai_engine/agi_platform/v1/datasets/documents/list_page"; // 删除文档 public static final String DATASET_DELETE_FILE_URL = "/api/v1/ai_engine/agi_platform/v1/datasets/document/delete"; // 上传文件 public static final String DATASET_UPLOAD_FILE_URL = "/api/v1/ai_engine/agi_platform/v1/datasets/files/upload"; private AppBuilderConfig() {} } ================================================ FILE: java/src/main/java/com/baidubce/appbuilder/base/exception/AppBuilderServerException.java ================================================ package com.baidubce.appbuilder.base.exception; public class AppBuilderServerException extends Exception { private final String requestId; private final int code; private final String message; private int appbuilderCode; private String appbuilderMessage; private String responseBody; public AppBuilderServerException(String requestId, int code, String message) { this.requestId = requestId; this.code = code; this.message = message; } public AppBuilderServerException(String requestId, int code, String message, int appbuilderCode, String appbuilderMessage) { this(requestId, code, message); this.appbuilderCode = appbuilderCode; this.appbuilderMessage = appbuilderMessage; } public AppBuilderServerException(String requestId, int code, String message, String responseBody) { this(requestId, code, message); this.responseBody = responseBody; } public String getRequestId() { return requestId; } public int getCode() { return code; } public String getMessage() { return message; } public int getAppbuilderCode() { return appbuilderCode; } public String getAppbuilderMessage() { return appbuilderMessage; } public String getResponseBody() { return responseBody; } @Override public String toString() { return "AppBuilderServerException{" + "requestId='" + requestId + '\'' + ", code=" + code + ", message='" + message + '\'' + ", appbuilderCode=" + appbuilderCode + ", appbuilderMessage='" + appbuilderMessage + '\'' + ", responseBody='" + responseBody + '\'' + '}'; } } ================================================ FILE: java/src/main/java/com/baidubce/appbuilder/base/utils/http/HttpClient.java ================================================ package com.baidubce.appbuilder.base.utils.http; import com.baidubce.appbuilder.base.component.Component; import com.baidubce.appbuilder.base.config.AppBuilderConfig; import com.baidubce.appbuilder.base.exception.AppBuilderServerException; import com.baidubce.appbuilder.base.utils.iterator.StreamIterator; import com.baidubce.appbuilder.base.utils.json.JsonUtils; import org.apache.hc.client5.http.classic.methods.HttpDelete; import org.apache.hc.client5.http.classic.methods.HttpGet; import org.apache.hc.client5.http.classic.methods.HttpPost; import org.apache.hc.client5.http.classic.methods.HttpUriRequestBase; import org.apache.hc.client5.http.config.RequestConfig; import org.apache.hc.client5.http.impl.classic.CloseableHttpClient; import org.apache.hc.client5.http.impl.classic.CloseableHttpResponse; import org.apache.hc.client5.http.impl.classic.HttpClients; import org.apache.hc.core5.http.ClassicHttpRequest; import org.apache.hc.core5.http.Header; import org.apache.hc.core5.http.HttpEntity; import org.apache.hc.core5.http.ParseException; import org.apache.hc.core5.http.io.entity.EntityUtils; import java.io.IOException; import java.lang.reflect.Type; import java.net.URLEncoder; import java.util.LinkedHashMap; import java.util.Map; import java.util.concurrent.TimeUnit; import java.util.logging.ConsoleHandler; import java.util.logging.FileHandler; import java.util.logging.Level; import java.util.logging.Logger; public class HttpClient { public String SecretKey; public String Gateway; public String GatewayV2; public String ConsoleOpenAPIVersion; public String ConsoleOpenAPIPrefix; private final CloseableHttpClient client; private static final Logger LOGGER = Logger.getLogger(Component.class.getName()); public HttpClient(String secretKey, String gateway, String gatewayV2) { RequestConfig requestConfig = RequestConfig.custom().setResponseTimeout( AppBuilderConfig.HTTP_CLIENT_CONNECTION_TIMEOUT, TimeUnit.SECONDS).build(); this.client = HttpClients.custom().setDefaultRequestConfig(requestConfig).build(); this.SecretKey = secretKey; this.Gateway = gateway; this.GatewayV2 = gatewayV2; ConsoleHandler handler = new ConsoleHandler(); String systemLogLevel = System.getProperty(AppBuilderConfig.APPBUILDER_LOGLEVEL); if (systemLogLevel == null || systemLogLevel.isEmpty()) { systemLogLevel = System.getenv(AppBuilderConfig.APPBUILDER_LOGLEVEL); } if (systemLogLevel == null || systemLogLevel.isEmpty()) { LOGGER.setLevel(Level.INFO); handler.setLevel(Level.INFO); } else { switch (systemLogLevel.toLowerCase()) { case "debug": LOGGER.setLevel(Level.FINE); handler.setLevel(Level.FINE); break; case "warning": LOGGER.setLevel(Level.WARNING); handler.setLevel(Level.WARNING); break; case "error": LOGGER.setLevel(Level.SEVERE); handler.setLevel(Level.SEVERE); break; default: LOGGER.setLevel(Level.INFO); handler.setLevel(Level.INFO); break; } } LOGGER.addHandler(handler); String systemLogFile = System.getProperty(AppBuilderConfig.APPBUILDER_LOGFILE); if (systemLogFile == null || systemLogFile.isEmpty()) { systemLogFile = System.getenv(AppBuilderConfig.APPBUILDER_LOGFILE); } if (systemLogFile != null && !systemLogFile.isEmpty()) { try { FileHandler fileHandler = new FileHandler(systemLogFile); LOGGER.addHandler(fileHandler); } catch (Exception e) { throw new RuntimeException("Failed to create log file: " + systemLogFile, e); } } } public ClassicHttpRequest createPostRequest(String url, HttpEntity entity) { String requestURL = Gateway + url; LOGGER.log(Level.FINE, "requestURL: " + requestURL); HttpPost httpPost = new HttpPost(requestURL); httpPost.setHeader("X-Appbuilder-Authorization", this.SecretKey); httpPost.setHeader("X-Appbuilder-Origin", "appbuilder_sdk"); String platform = System.getenv("APPBUILDER_SDK_PLATFORM") != null ? System.getenv("APPBUILDER_SDK_PLATFORM") : "unknown"; httpPost.setHeader("X-Appbuilder-Sdk-Config", "{\"appbuilder_sdk_version\":\"1.1.0\",\"appbuilder_sdk_language\":\"java\",\"appbuilder_sdk_platform\":\"" + platform + "\"}"); httpPost.setHeader("X-Appbuilder-Request-Id", java.util.UUID.randomUUID().toString()); httpPost.setEntity(entity); String headers = "headers: \n"; for (Header header : httpPost.getHeaders()) { headers += header + "\n"; } LOGGER.log(Level.FINE, "\n" + headers); return httpPost; } /** * 创建一个用于发送 POST 请求的 ClassicHttpRequest 对象 适配OpenAPI,目前仅AgentBuilder使用 * * @param url 请求的 URL * @param entity 请求的实体 * @return 返回创建的 ClassicHttpRequest 对象 */ public ClassicHttpRequest createPostRequestV2(String url, HttpEntity entity) { String requestURL = GatewayV2 + ConsoleOpenAPIPrefix + ConsoleOpenAPIVersion + url; LOGGER.log(Level.FINE, "requestURL: " + requestURL); HttpPost httpPost = new HttpPost(requestURL); httpPost.setHeader("Authorization", this.SecretKey); httpPost.setHeader("X-Appbuilder-Origin", "appbuilder_sdk"); String platform = System.getenv("APPBUILDER_SDK_PLATFORM") != null ? System.getenv("APPBUILDER_SDK_PLATFORM") : "unknown"; httpPost.setHeader("X-Appbuilder-Sdk-Config", "{\"appbuilder_sdk_version\":\"1.1.0\",\"appbuilder_sdk_language\":\"java\",\"appbuilder_sdk_platform\":\"" + platform + "\"}"); httpPost.setHeader("X-Appbuilder-Request-Id", java.util.UUID.randomUUID().toString()); httpPost.setEntity(entity); String headers = "headers: \n"; for (Header header : httpPost.getHeaders()) { headers += header + "\n"; } LOGGER.log(Level.FINE, "\n" + headers); return httpPost; } public ClassicHttpRequest createGetRequestV2(String url, Map map) { String urlParams = toQueryString(map); String requestURL = GatewayV2 + ConsoleOpenAPIPrefix + ConsoleOpenAPIVersion + url + "?" + urlParams; LOGGER.log(Level.FINE, "requestURL: " + requestURL); HttpGet httpGet = new HttpGet(requestURL); httpGet.setHeader("Authorization", this.SecretKey); httpGet.setHeader("X-Appbuilder-Origin", "appbuilder_sdk"); String platform = System.getenv("APPBUILDER_SDK_PLATFORM") != null ? System.getenv("APPBUILDER_SDK_PLATFORM") : "unknown"; httpGet.setHeader("X-Appbuilder-Sdk-Config", "{\"appbuilder_sdk_version\":\"1.1.0\",\"appbuilder_sdk_language\":\"java\",\"appbuilder_sdk_platform\":\"" + platform + "\"}"); httpGet.setHeader("X-Appbuilder-Request-Id", java.util.UUID.randomUUID().toString()); String headers = "headers: \n"; for (Header header : httpGet.getHeaders()) { headers += header + "\n"; } LOGGER.log(Level.FINE, "\n" + headers); return httpGet; } public ClassicHttpRequest createDeleteRequestV2(String url, Map map) { // 处理查询参数 String urlParams = toQueryString(map); // 如果 URL 已经包含 '?', 不需要再添加 String requestURL = GatewayV2 + ConsoleOpenAPIPrefix + ConsoleOpenAPIVersion + url + (url.contains("?") ? "&" : "?") + urlParams; LOGGER.log(Level.FINE, "requestURL: " + requestURL); HttpDelete httpDelete = new HttpDelete(requestURL); httpDelete.setHeader("Authorization", this.SecretKey); httpDelete.setHeader("X-Appbuilder-Origin", "appbuilder_sdk"); String platform = System.getenv("APPBUILDER_SDK_PLATFORM") != null ? System.getenv("APPBUILDER_SDK_PLATFORM") : "unknown"; httpDelete.setHeader("X-Appbuilder-Sdk-Config", "{\"appbuilder_sdk_version\":\"1.1.0\",\"appbuilder_sdk_language\":\"java\",\"appbuilder_sdk_platform\":\"" + platform + "\"}"); httpDelete.setHeader("X-Appbuilder-Request-Id", java.util.UUID.randomUUID().toString()); String headers = "headers: \n"; for (Header header : httpDelete.getHeaders()) { headers += header + "\n"; } LOGGER.log(Level.FINE, "\n" + headers); return httpDelete; } public HttpResponse execute(ClassicHttpRequest request, Type bodyType) throws IOException, AppBuilderServerException { if (LOGGER.getLevel() == Level.FINE) { buildCurlCommand(request); } HttpResponse httpResponse = client.execute(request, resp -> { Map headers = new LinkedHashMap<>(); for (Header header : resp.getHeaders()) { headers.put(header.getName(), header.getValue()); } String requestId = headers.get(AppBuilderConfig.APPBUILDER_REQUEST_ID); String stringBody = EntityUtils.toString(resp.getEntity()); HttpResponse response = new HttpResponse().setCode(resp.getCode()).setMessage(resp.getReasonPhrase()) .setRequestId(requestId).setHeaders(headers).setStringBody(stringBody); if (resp.getCode() == 200) { LOGGER.log(Level.FINE, "Successful response with code 200 for request ID: {0}", new Object[]{requestId}); if (bodyType != null) { response.setBody(JsonUtils.deserialize(stringBody, bodyType)); } } else { LOGGER.log(Level.SEVERE, "Error response with code {0} for request ID: {1}, message: {2}", new Object[]{resp.getCode(), requestId, resp.getReasonPhrase()}); } return response; }); if (httpResponse.getCode() != 200) { String errorMessage = String.format( "Error after processing response with code %d for request ID: %s, message: %s", httpResponse.getCode(), httpResponse.getRequestId(), httpResponse.getMessage() ); LOGGER.log(Level.SEVERE, errorMessage); throw new AppBuilderServerException(httpResponse.getRequestId(), httpResponse.getCode(), httpResponse.getMessage(), httpResponse.getStringBody()); } return httpResponse; } public HttpResponse> executeSSE(ClassicHttpRequest request, Type bodyType) throws IOException, AppBuilderServerException { if (LOGGER.getLevel() == Level.FINE) { buildCurlCommand(request); } CloseableHttpResponse resp = client.execute(request); Map headers = new LinkedHashMap<>(); for (Header header : resp.getHeaders()) { headers.put(header.getName(), header.getValue()); } String requestId = headers.get(AppBuilderConfig.APPBUILDER_REQUEST_ID); if (resp.getCode() != 200) { String stringBody = ""; try { stringBody = EntityUtils.toString(resp.getEntity()); } catch (ParseException ignored) { } throw new AppBuilderServerException(requestId, resp.getCode(), resp.getReasonPhrase(), stringBody); } return new HttpResponse>().setCode(resp.getCode()) .setMessage(resp.getReasonPhrase()).setRequestId(requestId).setHeaders(headers) .setBody(new StreamIterator<>(resp, bodyType, (HttpUriRequestBase) request)); } private String toQueryString(Map map) { StringBuilder stringBuilder = new StringBuilder(); for (Map.Entry entry : map.entrySet()) { if (entry.getValue() != null) { if (stringBuilder.length() != 0) { stringBuilder.append('&'); } try { stringBuilder.append(URLEncoder.encode(entry.getKey(), "UTF-8")); stringBuilder.append('='); stringBuilder.append(URLEncoder.encode(entry.getValue().toString(), "UTF-8")); } catch (Exception e) { // Should never happen. } } } return stringBuilder.toString(); } private void buildCurlCommand(ClassicHttpRequest request) { StringBuilder curlCmd = new StringBuilder("curl"); // Append method curlCmd.append(" -X ").append(request.getMethod()); curlCmd.append(" -L"); try { curlCmd.append(" ").append("\'").append(request.getUri()).append("\'").append(" \\\n"); } catch (Exception e) { LOGGER.log(Level.SEVERE, "Invalid URL: ", e); } // Append headers for (Header header : request.getHeaders()) { curlCmd.append("-H \'").append(header.getName()).append(": ").append(header.getValue()) .append("\'"); curlCmd.append(" \\\n"); } if ("GET".equals(request.getMethod()) || "DELETE".equals(request.getMethod())) { curlCmd = new StringBuilder(curlCmd.toString().replaceAll(" \\\\\n$", "")); } // Append body HttpEntity entity = request.getEntity(); if (entity != null && entity.isRepeatable()) { try { String body = EntityUtils.toString(entity); curlCmd.append(" -d '").append(body).append("'"); } catch (ParseException | IOException e) { } } LOGGER.log(Level.FINE, "Curl Command: \n" + curlCmd.toString() + "\n"); } } ================================================ FILE: java/src/main/java/com/baidubce/appbuilder/base/utils/http/HttpResponse.java ================================================ package com.baidubce.appbuilder.base.utils.http; import java.util.Map; public class HttpResponse { private int code; private String message; private String requestId; private Map headers; private T body; private String stringBody; public int getCode() { return code; } protected HttpResponse setCode(int code) { this.code = code; return this; } public String getMessage() { return message; } public HttpResponse setMessage(String message) { this.message = message; return this; } public String getRequestId() { return requestId; } public HttpResponse setRequestId(String requestId) { this.requestId = requestId; return this; } public Map getHeaders() { return headers; } protected HttpResponse setHeaders(Map headers) { this.headers = headers; return this; } public T getBody() { return body; } protected HttpResponse setBody(T body) { this.body = body; return this; } public String getStringBody() { return stringBody; } protected HttpResponse setStringBody(String stringBody) { this.stringBody = stringBody; return this; } } ================================================ FILE: java/src/main/java/com/baidubce/appbuilder/base/utils/iterator/StreamIterator.java ================================================ package com.baidubce.appbuilder.base.utils.iterator; import com.baidubce.appbuilder.base.utils.json.JsonUtils; import org.apache.hc.client5.http.classic.methods.HttpUriRequestBase; import org.apache.hc.client5.http.impl.classic.CloseableHttpResponse; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.lang.reflect.Type; import java.util.Iterator; import java.util.NoSuchElementException; public class StreamIterator implements Iterator, AutoCloseable { private final CloseableHttpResponse resp; private final BufferedReader reader; private final Type bodyType; private final HttpUriRequestBase request; private String nextLine; public StreamIterator(CloseableHttpResponse resp, Type type, HttpUriRequestBase request) throws IOException { this.resp = resp; this.reader = new BufferedReader(new InputStreamReader(resp.getEntity().getContent())); this.bodyType = type; this.request = request; } @Override public boolean hasNext() { if (this.nextLine != null) { return true; } try { this.nextLine = this.reader.readLine(); // 跳过空白行 this.reader.readLine(); } catch (IOException e) { close(); return false; } if (this.nextLine == null) { close(); return false; } return true; } @Override public T next() { if (hasNext()) { String currentLine = this.nextLine; this.nextLine = null; String respBody = currentLine.replaceFirst("data: ", ""); return JsonUtils.deserialize(respBody, this.bodyType); } else { close(); throw new NoSuchElementException("No more lines available"); } } @Override public void close() { if (request != null) { request.abort(); } try { if (reader != null) { reader.close(); } } catch (Exception ignored) { // ignore } finally { try { if (resp != null) { resp.close(); } } catch (Exception ignored) { // ignore } } } } ================================================ FILE: java/src/main/java/com/baidubce/appbuilder/base/utils/json/JsonUtils.java ================================================ package com.baidubce.appbuilder.base.utils.json; import com.google.gson.Gson; import java.lang.reflect.Type; public class JsonUtils { private static final Gson gson = new Gson(); public static String serialize(Object object) { return gson.toJson(object); } public static T deserialize(String json, Type type) { return gson.fromJson(json, type); } } ================================================ FILE: java/src/main/java/com/baidubce/appbuilder/console/agentbuilder/AgentBuilder.java ================================================ package com.baidubce.appbuilder.console.agentbuilder; import com.baidubce.appbuilder.base.component.Component; import com.baidubce.appbuilder.base.config.AppBuilderConfig; import com.baidubce.appbuilder.base.exception.AppBuilderServerException; import com.baidubce.appbuilder.base.utils.http.HttpResponse; import com.baidubce.appbuilder.base.utils.iterator.StreamIterator; import com.baidubce.appbuilder.base.utils.json.JsonUtils; import com.baidubce.appbuilder.model.agentbuilder.*; import java.io.File; import java.io.IOException; import java.lang.Deprecated; import java.nio.charset.StandardCharsets; import java.util.*; import org.apache.hc.client5.http.entity.mime.HttpMultipartMode; import org.apache.hc.client5.http.entity.mime.MultipartEntityBuilder; import org.apache.hc.core5.http.ClassicHttpRequest; import org.apache.hc.core5.http.io.entity.StringEntity; public class AgentBuilder extends Component { public String appID; @Deprecated public AgentBuilder(String appID) { super(); this.appID = appID; } @Deprecated public AgentBuilder(String appID, String secretKey) { super(secretKey); this.appID = appID; } @Deprecated public AgentBuilder(String appID, String secretKey, String gateway) { super(secretKey, gateway); this.appID = appID; } /** * 创建会话 * * @return 返回会话ID * @throws IOException 当请求失败时抛出IOException * @throws AppBuilderServerException 当服务器返回错误码时抛出AppBuilderServerException */ public String createConversation() throws IOException, AppBuilderServerException { String url = AppBuilderConfig.CREATE_CONVERSATION_URL; if (this.appID == null || this.appID.isEmpty()) { throw new RuntimeException("Param 'appID' is required!"); } Map requestBody = new HashMap<>(); requestBody.put("app_id", this.appID); String jsonBody = JsonUtils.serialize(requestBody); ClassicHttpRequest postRequest = httpClient.createPostRequestV2(url, new StringEntity(jsonBody, StandardCharsets.UTF_8)); postRequest.setHeader("Content-Type", "application/json"); HttpResponse response = httpClient.execute(postRequest, ConversationResponse.class); ConversationResponse respBody = response.getBody(); return respBody.getConversationId(); } /** * 上传本地文件到指定会话中 * * @param conversationId 会话ID * @param filePath 文件路径 * @return 上传后的文件ID * @throws IOException 当请求失败时抛出IOException * @throws AppBuilderServerException 当服务器返回错误码时抛出AppBuilderServerException */ public String uploadLocalFile(String conversationId, String filePath) throws IOException, AppBuilderServerException { String url = AppBuilderConfig.UPLOAD_FILE_URL; if (this.appID == null || this.appID.isEmpty()) { throw new RuntimeException("Param 'appID' is required!"); } MultipartEntityBuilder builder = MultipartEntityBuilder.create() .setMode(HttpMultipartMode.LEGACY) .setCharset(StandardCharsets.UTF_8); builder.addBinaryBody("file", new File(filePath)); builder.addTextBody("app_id", this.appID); builder.addTextBody("conversation_id", conversationId); builder.addTextBody("scenario", "assistant"); ClassicHttpRequest postRequest = httpClient.createPostRequestV2(url, builder.build()); HttpResponse response = httpClient.execute(postRequest, FileUploadResponse.class); FileUploadResponse respBody = response.getBody(); return respBody.getFileId(); } /** * 运行AgentBuilder,根据输入的问题、会话ID、文件ID数组以及是否以流模式返回结果,返回AgentBuilderIterator迭代器。 * * @param query 查询字符串 * @param conversationId 会话ID * @param fileIds 文件ID数组 * @param stream 是否以流的形式返回结果 * @return AgentBuilderIterator 迭代器,包含 AgentBuilder 的运行结果 * @throws IOException 如果在 I/O 操作过程中发生错误 * @throws AppBuilderServerException 如果 AppBuilder 服务器返回错误 */ public AgentBuilderIterator run(String query, String conversationId, String[] fileIds, boolean stream) throws IOException, AppBuilderServerException { String url = AppBuilderConfig.AGENTBUILDER_RUN_URL; if (this.appID == null || this.appID.isEmpty()) { throw new RuntimeException("Param 'appID' is required!"); } Map requestBody = new HashMap<>(); requestBody.put("app_id", this.appID); requestBody.put("query", query); requestBody.put("conversation_id", conversationId); requestBody.put("file_ids", fileIds); requestBody.put("stream", stream); String jsonBody = JsonUtils.serialize(requestBody); ClassicHttpRequest postRequest = httpClient.createPostRequestV2(url, new StringEntity(jsonBody, StandardCharsets.UTF_8)); postRequest.setHeader("Content-Type", "application/json"); HttpResponse> response = httpClient.executeSSE(postRequest, AgentBuilderResponse.class); return new AgentBuilderIterator(response.getBody()); } } ================================================ FILE: java/src/main/java/com/baidubce/appbuilder/console/aisearch/AISearch.java ================================================ package com.baidubce.appbuilder.console.aisearch; import java.io.IOException; import java.nio.charset.StandardCharsets; import org.apache.hc.core5.http.ClassicHttpRequest; import org.apache.hc.core5.http.io.entity.StringEntity; import com.baidubce.appbuilder.base.component.Component; import com.baidubce.appbuilder.base.config.AppBuilderConfig; import com.baidubce.appbuilder.base.exception.AppBuilderServerException; import com.baidubce.appbuilder.base.utils.http.HttpResponse; import com.baidubce.appbuilder.base.utils.iterator.StreamIterator; import com.baidubce.appbuilder.base.utils.json.JsonUtils; import com.baidubce.appbuilder.model.aisearch.*; public class AISearch extends Component { public AISearch() { super(); } public AISearch(String secretKey) { super(secretKey); } public AISearch(String secretKey, String gateway) { super(secretKey, gateway); } public AISearchIterator run(AISearchRequest request) throws IOException, AppBuilderServerException { String url = AppBuilderConfig.AI_SEARCH_URL; String jsonBody = JsonUtils.serialize(request); ClassicHttpRequest postRequest = httpClient.createPostRequestV2(url, new StringEntity(jsonBody, StandardCharsets.UTF_8)); postRequest.setHeader("Content-Type", "application/json"); HttpResponse> response = httpClient.executeSSE(postRequest, AISearchResponse.class); return new AISearchIterator(response.getBody()); } } ================================================ FILE: java/src/main/java/com/baidubce/appbuilder/console/appbuilderclient/App.java ================================================ package com.baidubce.appbuilder.console.appbuilderclient; import java.io.IOException; import java.nio.charset.StandardCharsets; import org.apache.hc.core5.http.ClassicHttpRequest; import org.apache.hc.core5.http.io.entity.StringEntity; import com.baidubce.appbuilder.base.component.Component; import com.baidubce.appbuilder.base.config.AppBuilderConfig; import com.baidubce.appbuilder.base.exception.AppBuilderServerException; import com.baidubce.appbuilder.base.utils.http.HttpResponse; import com.baidubce.appbuilder.base.utils.json.JsonUtils; import com.baidubce.appbuilder.model.appbuilderclient.AppDescribeRequest; import com.baidubce.appbuilder.model.appbuilderclient.AppDescribeResponse; public class App extends Component { public App() { super(); } /** * 描述应用程序信息 * * @param appId 应用ID * @return 包含应用程序描述信息的响应对象 * @throws IOException 如果发生I/O异常 * @throws AppBuilderServerException 如果发生AppBuilder服务器异常 */ public AppDescribeResponse describeApp(String appId) throws IOException, AppBuilderServerException { String url = AppBuilderConfig.APP_DESCRIBE_URL; AppDescribeRequest request = new AppDescribeRequest(); request.setId(appId); String jsonBody = JsonUtils.serialize(request); ClassicHttpRequest postRequest = httpClient.createPostRequestV2(url, new StringEntity(jsonBody, StandardCharsets.UTF_8)); postRequest.setHeader("Content-Type", "application/json"); HttpResponse response = httpClient.execute(postRequest, AppDescribeResponse.class); AppDescribeResponse respBody = response.getBody(); return respBody; } } ================================================ FILE: java/src/main/java/com/baidubce/appbuilder/console/appbuilderclient/AppBuilderClient.java ================================================ package com.baidubce.appbuilder.console.appbuilderclient; import com.baidubce.appbuilder.base.component.Component; import com.baidubce.appbuilder.base.config.AppBuilderConfig; import com.baidubce.appbuilder.base.exception.AppBuilderServerException; import com.baidubce.appbuilder.base.utils.http.HttpResponse; import com.baidubce.appbuilder.base.utils.iterator.StreamIterator; import com.baidubce.appbuilder.base.utils.json.JsonUtils; import com.baidubce.appbuilder.model.appbuilderclient.*; import java.io.File; import java.io.IOException; import java.nio.charset.StandardCharsets; import java.util.*; import org.apache.hc.client5.http.entity.mime.HttpMultipartMode; import org.apache.hc.client5.http.entity.mime.MultipartEntityBuilder; import org.apache.hc.core5.http.ClassicHttpRequest; import org.apache.hc.core5.http.io.entity.StringEntity; public class AppBuilderClient extends Component { public String appID; public AppBuilderClient(String appID) { super(); this.appID = appID; } public AppBuilderClient(String appID, String secretKey) { super(secretKey); this.appID = appID; } public AppBuilderClient(String appID, String secretKey, String gateway) { super(secretKey, gateway); this.appID = appID; } /** * 创建会话 * * @return 返回会话ID * @throws IOException 当请求失败时抛出IOException * @throws AppBuilderServerException 当服务器返回错误码时抛出AppBuilderServerException */ public String createConversation() throws IOException, AppBuilderServerException { return innerCreateConversation(); } private String innerCreateConversation() throws IOException, AppBuilderServerException { String url = AppBuilderConfig.CREATE_CONVERSATION_URL; if (this.appID == null || this.appID.isEmpty()) { throw new RuntimeException("Param 'appID' is required!"); } Map requestBody = new HashMap<>(); requestBody.put("app_id", this.appID); String jsonBody = JsonUtils.serialize(requestBody); ClassicHttpRequest postRequest = httpClient.createPostRequestV2(url, new StringEntity(jsonBody, StandardCharsets.UTF_8)); postRequest.setHeader("Content-Type", "application/json"); HttpResponse response = httpClient.execute(postRequest, ConversationResponse.class); ConversationResponse respBody = response.getBody(); return respBody.getConversationId(); } /** * 上传本地文件到指定会话中 * * @param conversationId 会话ID * @param filePath 文件路径 * @return 上传后的文件ID * @throws IOException 当请求失败时抛出IOException * @throws AppBuilderServerException 当服务器返回错误码时抛出AppBuilderServerException */ public String uploadLocalFile(String conversationId, String filePath) throws IOException, AppBuilderServerException { return innerUploadLocalFile(conversationId, filePath, ""); } public String uploadFile(String conversationId, String filePath, String fileUrl) throws IOException, AppBuilderServerException { return innerUploadLocalFile(conversationId, filePath, fileUrl); } private String innerUploadLocalFile(String conversationId, String filePath, String fileUrl) throws IOException, AppBuilderServerException { String url = AppBuilderConfig.UPLOAD_FILE_URL; if (this.appID == null || this.appID.isEmpty()) { throw new RuntimeException("Param 'appID' is required!"); } MultipartEntityBuilder builder = MultipartEntityBuilder.create() .setMode(HttpMultipartMode.LEGACY).setCharset(StandardCharsets.UTF_8); if(filePath != null && !filePath.isEmpty()) { builder.addBinaryBody("file", new File(filePath)); } else if (fileUrl != null && !fileUrl.isEmpty()) { builder.addTextBody("file_url", fileUrl); } builder.addTextBody("app_id", this.appID); builder.addTextBody("conversation_id", conversationId); builder.addTextBody("scenario", "assistant"); ClassicHttpRequest postRequest = httpClient.createPostRequestV2(url, builder.build()); HttpResponse response = httpClient.execute(postRequest, FileUploadResponse.class); FileUploadResponse respBody = response.getBody(); return respBody.getFileId(); } /** * 运行AppBuilderClient,根据输入的问题、会话ID、文件ID数组以及是否以流模式返回结果,返回AgentBuilderIterator迭代器。 * * @param query 查询字符串 * @param conversationId 会话ID * @param fileIds 文件ID数组 * @param stream 是否以流的形式返回结果 * @return AgentBuilderIterator 迭代器,包含 AgentBuilder 的运行结果 * @throws IOException 如果在 I/O 操作过程中发生错误 * @throws AppBuilderServerException 如果 AppBuilder 服务器返回错误 */ public AppBuilderClientIterator run(String query, String conversationId, String[] fileIds, boolean stream) throws IOException, AppBuilderServerException { String url = AppBuilderConfig.AGENTBUILDER_RUN_URL; if (this.appID == null || this.appID.isEmpty()) { throw new RuntimeException("Param 'appID' is required!"); } Map requestBody = new HashMap<>(); requestBody.put("app_id", this.appID); requestBody.put("query", query); requestBody.put("conversation_id", conversationId); requestBody.put("file_ids", fileIds); requestBody.put("stream", stream); String jsonBody = JsonUtils.serialize(requestBody); ClassicHttpRequest postRequest = httpClient.createPostRequestV2(url, new StringEntity(jsonBody, StandardCharsets.UTF_8)); postRequest.setHeader("Content-Type", "application/json"); HttpResponse> response = httpClient.executeSSE(postRequest, AppBuilderClientResponse.class); return new AppBuilderClientIterator(response.getBody()); } /** * 执行应用构建客户端运行请求 * * @param requestBody 请求体,包含运行所需的所有信息 * @return 返回包含构建客户端响应的迭代器 * @throws IOException 如果在执行请求时发生I/O错误 * @throws AppBuilderServerException 如果应用构建服务器返回错误响应 */ public AppBuilderClientIterator run(AppBuilderClientRunRequest requestBody) throws IOException, AppBuilderServerException { String url = AppBuilderConfig.AGENTBUILDER_RUN_URL; if (this.appID == null || this.appID.isEmpty()) { throw new RuntimeException("Param 'appID' is required!"); } String jsonBody = JsonUtils.serialize(requestBody); ClassicHttpRequest postRequest = httpClient.createPostRequestV2(url, new StringEntity(jsonBody, StandardCharsets.UTF_8)); postRequest.setHeader("Content-Type", "application/json"); HttpResponse> response = httpClient.executeSSE(postRequest, AppBuilderClientResponse.class); return new AppBuilderClientIterator(response.getBody()); } /** * 对对话结果进行点踩点赞 * * @param requestBody 请求体,包含运行所需的所有信息 * @return 返回包含构建客户端响应的迭代器 * @throws IOException 如果在执行请求时发生I/O错误 * @throws AppBuilderServerException 如果应用构建服务器返回错误响应 */ public AppBuilderClientFeedbackResponse feedback(AppBuilderClientFeedbackRequest requestBody) throws IOException, AppBuilderServerException { String url = AppBuilderConfig.FEEDBACK_URL; if (requestBody.getAppId() == null || requestBody.getAppId().isEmpty()) { requestBody.setAppId(this.appID); } if (requestBody.getAppId() == null || requestBody.getAppId().isEmpty()) { throw new RuntimeException("Param 'appID' is required!"); } String jsonBody = JsonUtils.serialize(requestBody); ClassicHttpRequest postRequest = httpClient.createPostRequestV2(url, new StringEntity(jsonBody, StandardCharsets.UTF_8)); postRequest.setHeader("Content-Type", "application/json"); HttpResponse response = httpClient.execute(postRequest, AppBuilderClientFeedbackResponse.class); AppBuilderClientFeedbackResponse respBody = response.getBody(); return respBody; } } ================================================ FILE: java/src/main/java/com/baidubce/appbuilder/console/appbuilderclient/AppList.java ================================================ package com.baidubce.appbuilder.console.appbuilderclient; import java.io.IOException; import java.nio.charset.StandardCharsets; import org.apache.hc.core5.http.ClassicHttpRequest; import org.apache.hc.core5.http.io.entity.StringEntity; import com.baidubce.appbuilder.base.component.Component; import com.baidubce.appbuilder.base.config.AppBuilderConfig; import com.baidubce.appbuilder.base.exception.AppBuilderServerException; import com.baidubce.appbuilder.base.utils.http.HttpResponse; import com.baidubce.appbuilder.base.utils.json.JsonUtils; import com.baidubce.appbuilder.model.appbuilderclient.App; import com.baidubce.appbuilder.model.appbuilderclient.AppListResponse; import com.baidubce.appbuilder.model.appbuilderclient.AppsDescribeRequest; import com.baidubce.appbuilder.model.appbuilderclient.AppsDescribeResponse; import com.baidubce.appbuilder.model.appbuilderclient.AppListRequest; public class AppList extends Component { public AppList() { super(); } /** * @deprecated 该方法已被弃用,请改用新方法 * * 根据请求获取应用列表 * * @param request 请求参数 * @return 应用列表数组 * @throws IOException 如果发生输入输出异常 * @throws AppBuilderServerException 如果发生应用构建服务器异常 */ @Deprecated public App[] getAppList(AppListRequest request) throws IOException, AppBuilderServerException { String url = AppBuilderConfig.APP_LIST_URL; ClassicHttpRequest getRequest = httpClient.createGetRequestV2(url, request.toMap()); getRequest.setHeader("Content-Type", "application/json"); HttpResponse response = httpClient.execute(getRequest, AppListResponse.class); AppListResponse respBody = response.getBody(); return respBody.getData(); } /** * 描述应用程序信息 * * @param request 包含应用程序描述信息的请求对象 * @return 包含应用程序描述信息的响应对象 * @throws IOException 如果发生I/O异常 * @throws AppBuilderServerException 如果发生AppBuilder服务器异常 */ public AppsDescribeResponse describeApps(AppsDescribeRequest request) throws IOException, AppBuilderServerException { String url = AppBuilderConfig.APPS_DESCRIBE_URL; String jsonBody = JsonUtils.serialize(request); ClassicHttpRequest postRequest = httpClient.createPostRequestV2(url, new StringEntity(jsonBody, StandardCharsets.UTF_8)); postRequest.setHeader("Content-Type", "application/json"); HttpResponse response = httpClient.execute(postRequest, AppsDescribeResponse.class); AppsDescribeResponse respBody = response.getBody(); return respBody; } } ================================================ FILE: java/src/main/java/com/baidubce/appbuilder/console/componentclient/ComponentClient.java ================================================ package com.baidubce.appbuilder.console.componentclient; import java.io.IOException; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.nio.charset.StandardCharsets; import com.baidubce.appbuilder.base.utils.iterator.StreamIterator; import org.apache.hc.core5.http.ClassicHttpRequest; import org.apache.hc.core5.http.io.entity.StringEntity; import com.baidubce.appbuilder.base.component.Component; import com.baidubce.appbuilder.base.config.AppBuilderConfig; import com.baidubce.appbuilder.base.exception.AppBuilderServerException; import com.baidubce.appbuilder.base.utils.http.HttpResponse; import com.baidubce.appbuilder.base.utils.json.JsonUtils; import com.baidubce.appbuilder.model.componentclient.ComponentClientIterator; import com.baidubce.appbuilder.model.componentclient.ComponentClientRunResponse; public class ComponentClient extends Component { public ComponentClient() { super(); } public ComponentClient(String secretKey) { super(secretKey); } public ComponentClient(String secretKey, String gateway) { super(secretKey, gateway); } /** * 运行Component,根据输入的问题、会话ID、文件ID数组以及是否以流模式等信息返回结果,返回ComponentClientIterator迭代器。 * * * @param componentId 组件ID * @param version 组件版本 * @param action 参数动作 * @param stream 是否以流的形式返回结果 * @param parameters 参数列表 * @return ComponentCientIterator 迭代器,包含 ComponentCientIterator 的运行结果 * @throws IOException 如果在 I/O 操作过程中发生错误 * @throws AppBuilderServerException 如果 AppBuilder 服务器返回错误 */ public ComponentClientIterator run(String componentId, String version, String action, boolean stream, Map parameters) throws IOException, AppBuilderServerException { String url = AppBuilderConfig.COMPONENT_RUN_URL; String urlSuffix = String.format("%s/%s", url, componentId); if (!version.isEmpty()) { urlSuffix += String.format("/version/%s", version); } if (!action.isEmpty()) { if (urlSuffix.contains("?")) { urlSuffix += String.format("&action=%s", action); } else { urlSuffix += String.format("?action=%s", action); } } Map requestBody = new HashMap<>(); requestBody.put("parameters", parameters); requestBody.put("stream", stream); String jsonBody = JsonUtils.serialize(requestBody); ClassicHttpRequest postRequest = httpClient.createPostRequestV2(urlSuffix, new StringEntity(jsonBody, StandardCharsets.UTF_8)); postRequest.setHeader("Content-Type", "application/json"); postRequest.setHeader("X-Appbuilder-From", "sdk"); HttpResponse> response = httpClient.executeSSE(postRequest, ComponentClientRunResponse.class); return new ComponentClientIterator(response.getBody()); } } ================================================ FILE: java/src/main/java/com/baidubce/appbuilder/console/dataset/Dataset.java ================================================ package com.baidubce.appbuilder.console.dataset; import java.io.File; import java.io.IOException; import java.nio.charset.StandardCharsets; import java.util.*; import com.baidubce.appbuilder.model.dataset.*; import com.baidubce.appbuilder.base.component.Component; import com.baidubce.appbuilder.base.config.AppBuilderConfig; import com.baidubce.appbuilder.base.exception.AppBuilderServerException; import com.baidubce.appbuilder.base.utils.http.HttpResponse; import com.baidubce.appbuilder.base.utils.json.JsonUtils; import org.apache.hc.client5.http.entity.mime.HttpMultipartMode; import org.apache.hc.client5.http.entity.mime.MultipartEntityBuilder; import org.apache.hc.core5.http.ClassicHttpRequest; import org.apache.hc.core5.http.io.entity.StringEntity; public class Dataset extends Component { String datasetId; @Deprecated public Dataset() { super(); } @Deprecated public Dataset(String secretKey) { super(secretKey); } @Deprecated public Dataset(String secretKey, String datasetId) { super(secretKey); this.datasetId = datasetId; } public void setDatasetId(String datasetId) { this.datasetId = datasetId; } /** * 创建数据集 * * @param datasetName 数据集名称 * @return 返回创建成功后的数据集ID * @throws IOException 当请求失败时抛出IOException * @throws AppBuilderServerException 当服务器返回错误码时抛出AppBuilderServerException */ public String createDataset(String datasetName) throws IOException, AppBuilderServerException { String url = AppBuilderConfig.DATASET_CREATE_URL; Map requestBody = new HashMap<>(); requestBody.put("name", datasetName); String jsonBody = JsonUtils.serialize(requestBody); ClassicHttpRequest postRequest = httpClient.createPostRequest(url, new StringEntity(jsonBody, StandardCharsets.UTF_8)); postRequest.setHeader("Content-Type", "application/json"); HttpResponse response = httpClient.execute(postRequest, DatasetCreateResponse.class); DatasetCreateResponse respBody = response.getBody(); if (respBody.getCode() != 0) { throw new AppBuilderServerException(response.getRequestId(), response.getCode(), response.getMessage(), respBody.getCode(), respBody.getMessage()); } this.datasetId = respBody.getResult().getId(); return this.datasetId; } /** * 上传文档 * * @param filePath 文件路径 * @return 上传成功后的文档ID * @throws IOException 当文件上传失败时抛出IOException * @throws AppBuilderServerException 当服务器返回错误码时抛出AppBuilderServerException */ private String uploadDocument(String filePath) throws IOException, AppBuilderServerException { String url = AppBuilderConfig.DATASET_UPLOAD_FILE_URL; MultipartEntityBuilder builder = MultipartEntityBuilder.create() .setMode(HttpMultipartMode.LEGACY) .setCharset(StandardCharsets.UTF_8); builder.addBinaryBody("file", new File(filePath)); ClassicHttpRequest postRequest = httpClient.createPostRequest(url, builder.build()); HttpResponse response = httpClient.execute(postRequest, FileUploadResponse.class); FileUploadResponse respBody = response.getBody(); if (respBody.getCode() != 0) { throw new AppBuilderServerException(response.getRequestId(), response.getCode(), response.getMessage(), respBody.getCode(), respBody.getMessage()); } return respBody.getResult().getId(); } /** * 向数据集中添加文档 * * @param filePaths 要添加的文档文件路径列表 * @param isCustomProcessRule 是否使用自定义处理规则 * @param customProcessRule 自定义处理规则,当isCustomProcessRule为true时,该参数不为空 * @param isEnhanced 是否开启增强模式 * @throws IOException 当文件上传失败时抛出IOException * @throws AppBuilderServerException 当服务器返回错误码时抛出AppBuilderServerException */ public String[] addDocuments(List filePaths, boolean isCustomProcessRule, Map customProcessRule, boolean isEnhanced) throws IOException, AppBuilderServerException { String url = AppBuilderConfig.DATASET_ADD_FILE_URL; if (this.datasetId == null || this.datasetId.isEmpty()) { throw new RuntimeException("Param 'datasetId' is required! Please set param or call createDataset() first"); } ArrayList fileIds = new ArrayList<>(filePaths.size()); for (String filePath : filePaths) { String fileId = uploadDocument(filePath); fileIds.add(fileId); } Map requestBody = new HashMap<>(); requestBody.put("dataset_id", this.datasetId); requestBody.put("file_ids", fileIds); requestBody.put("is_custom_process_rule", isCustomProcessRule); requestBody.put("is_enhanced", isEnhanced); if (isCustomProcessRule && customProcessRule != null) { requestBody.put("custom_process_rule", customProcessRule); } String jsonBody = JsonUtils.serialize(requestBody); ClassicHttpRequest postRequest = httpClient.createPostRequest(url, new StringEntity(jsonBody, StandardCharsets.UTF_8)); postRequest.setHeader("Content-Type", "application/json"); HttpResponse response = httpClient.execute(postRequest, DocumentAddResponse.class); DocumentAddResponse respBody = response.getBody(); if (respBody.getCode() != 0) { throw new AppBuilderServerException(response.getRequestId(), response.getCode(), response.getMessage(), respBody.getCode(), respBody.getMessage()); } return respBody.getResult().getDocumentIds(); } /** * 获取文档列表 * * @param page 页码 * @param limit 每页文档数量 * @param keywork 搜索关键字 * @return 文档列表 * @throws IOException 当请求失败时抛出IOException * @throws AppBuilderServerException 当服务器返回错误码时抛出AppBuilderServerException */ public DocumentListResponse getDocumentList(int page, int limit, String keywork) throws IOException, AppBuilderServerException { String url = AppBuilderConfig.DATASET_GET_FILE_LIST_URL; if (this.datasetId == null || this.datasetId.isEmpty()) { throw new RuntimeException("Param 'datasetId' is required! Please set param or call createDataset() first"); } Map requestBody = new HashMap<>(); requestBody.put("dataset_id", this.datasetId); requestBody.put("page", page); requestBody.put("limit", limit); requestBody.put("keyword", keywork); String jsonBody = JsonUtils.serialize(requestBody); ClassicHttpRequest postRequest = httpClient.createPostRequest(url, new StringEntity(jsonBody, StandardCharsets.UTF_8)); postRequest.setHeader("Content-Type", "application/json"); HttpResponse response = httpClient.execute(postRequest, DocumentListResponse.class); DocumentListResponse respBody = response.getBody(); if (respBody.getCode() != 0) { throw new AppBuilderServerException(response.getRequestId(), response.getCode(), response.getMessage(), respBody.getCode(), respBody.getMessage()); } return respBody; } /** * 从数据集中删除文档 * * @param documentId 要删除的文档ID * @throws IOException 当请求失败时抛出IOException * @throws AppBuilderServerException 当服务器返回错误码时抛出AppBuilderServerException */ public void deleteDocument(String documentId) throws IOException, AppBuilderServerException { String url = AppBuilderConfig.DATASET_DELETE_FILE_URL; if (this.datasetId == null || this.datasetId.isEmpty()) { throw new RuntimeException("Param 'datasetId' is required! Please set param or call createDataset() first"); } Map requestBody = new HashMap<>(); requestBody.put("dataset_id", this.datasetId); requestBody.put("document_id", documentId); String jsonBody = JsonUtils.serialize(requestBody); ClassicHttpRequest postRequest = httpClient.createPostRequest(url, new StringEntity(jsonBody, StandardCharsets.UTF_8)); postRequest.setHeader("Content-Type", "application/json"); HttpResponse response = httpClient.execute(postRequest, DocumentDeleteResponse.class); DocumentDeleteResponse respBody = response.getBody(); if (respBody.getCode() != 0) { throw new AppBuilderServerException(response.getRequestId(), response.getCode(), response.getMessage(), respBody.getCode(), respBody.getMessage()); } } /** * 从数据集中批量删除多个文档 * * @param documentIds 要删除的文档ID数组 * @throws IOException 当请求失败时抛出IOException * @throws AppBuilderServerException 当服务器返回错误码时抛出AppBuilderServerException */ public void deleteDocuments(String[] documentIds) throws IOException, AppBuilderServerException { for (String documentId : documentIds) { deleteDocument(documentId); } } } ================================================ FILE: java/src/main/java/com/baidubce/appbuilder/console/knowledgebase/Knowledgebase.java ================================================ package com.baidubce.appbuilder.console.knowledgebase; import java.io.File; import java.io.IOException; import java.nio.charset.StandardCharsets; import org.apache.hc.client5.http.entity.mime.HttpMultipartMode; import org.apache.hc.client5.http.entity.mime.MultipartEntityBuilder; import org.apache.hc.core5.http.ClassicHttpRequest; import org.apache.hc.core5.http.io.entity.StringEntity; import com.baidubce.appbuilder.base.component.Component; import com.baidubce.appbuilder.base.config.AppBuilderConfig; import com.baidubce.appbuilder.base.exception.AppBuilderServerException; import com.baidubce.appbuilder.base.utils.http.HttpResponse; import com.baidubce.appbuilder.base.utils.json.JsonUtils; import com.baidubce.appbuilder.model.knowledgebase.*; public class Knowledgebase extends Component { private String knowledgeBaseId; public Knowledgebase() { super(); } public Knowledgebase(String SecretKey) { super(SecretKey); } public Knowledgebase(String knowledgeBaseId, String SecretKey) { super(SecretKey); this.knowledgeBaseId = knowledgeBaseId; } /** * 上传文档 * * @param filePath 文件路径 * @return 上传成功后的文档ID * @throws IOException 当文件上传失败时抛出IOException * @throws AppBuilderServerException 当服务器返回错误码时抛出AppBuilderServerException */ @Deprecated public String uploadFile(String filePath) throws IOException, AppBuilderServerException { return innerUploadFile(filePath, java.util.UUID.randomUUID().toString()); } /** * 上传文件 * * @param filePath 文件路径 * @param clientToken 客户端令牌 * @return 上传文件的结果 * @throws IOException 如果发生I/O错误 * @throws AppBuilderServerException 如果应用构建服务器发生错误 */ @Deprecated public String uploadFile(String filePath, String clientToken) throws IOException, AppBuilderServerException { return innerUploadFile(filePath, clientToken); } /** * 上传文件到指定服务器。 * * @param filePath 文件路径 * @param clientToken 客户端令牌 * @return 文件ID * @throws IOException 当发生输入输出异常时抛出 * @throws AppBuilderServerException 当发生应用构建服务器异常时抛出 */ private String innerUploadFile(String filePath, String clientToken) throws IOException, AppBuilderServerException { String url = AppBuilderConfig.KNOWLEDGEBASE_UPLOAD_FILE_URL; MultipartEntityBuilder builder = MultipartEntityBuilder.create() .setMode(HttpMultipartMode.LEGACY).setCharset(StandardCharsets.UTF_8); builder.addBinaryBody("file", new File(filePath)); url = url + "?clientToken=" + clientToken; ClassicHttpRequest postRequest = httpClient.createPostRequestV2(url, builder.build()); HttpResponse response = httpClient.execute(postRequest, FileUploadResponse.class); FileUploadResponse respBody = response.getBody(); if (!(respBody.getCode() == null)) { throw new AppBuilderServerException(response.getRequestId(), response.getCode(), response.getMessage(), respBody.toString()); } return respBody.getId(); } /** * 新增知识库文档 * * @param req 请求参数 * @return documentIds 文档ID * * @throws IOException 当文件上传失败时抛出IOException * @throws AppBuilderServerException 当服务器返回错误码时抛出AppBuilderServerException */ @Deprecated public String[] addDocument(DocumentAddRequest req) throws IOException, AppBuilderServerException { return innerAddDocument(req, java.util.UUID.randomUUID().toString()); } /** * 向应用程序中添加文档 * * @param req 文档添加请求对象,包含需要添加的文档信息 * @param clientToken 客户端令牌,用于验证请求来源 * @return 返回一个字符串数组,包含操作结果 * @throws IOException 如果发生输入/输出异常,抛出此异常 * @throws AppBuilderServerException 如果应用程序构建服务器发生异常,抛出此异常 */ @Deprecated public String[] addDocument(DocumentAddRequest req, String clientToken) throws IOException, AppBuilderServerException { return innerAddDocument(req, clientToken); } /** * 向知识库中添加文档 * * @param req 文档添加请求对象 * @param clientToken 客户端令牌 * @return 文档ID数组 * @throws IOException 如果发生I/O异常 * @throws AppBuilderServerException 如果应用构建服务器异常 */ private String[] innerAddDocument(DocumentAddRequest req, String clientToken) throws IOException, AppBuilderServerException { String url = AppBuilderConfig.KNOWLEDGEBASE_ADD_DOCUMENT_URL; String jsonBody = JsonUtils.serialize(req); url = url + "?clientToken=" + clientToken; ClassicHttpRequest postRequest = httpClient.createPostRequestV2(url, new StringEntity(jsonBody, StandardCharsets.UTF_8)); postRequest.setHeader("Content-Type", "application/json"); HttpResponse response = httpClient.execute(postRequest, DocumentAddResponse.class); DocumentAddResponse respBody = response.getBody(); if (!(respBody.getCode() == null)) { throw new AppBuilderServerException(response.getRequestId(), response.getCode(), response.getMessage(), respBody.toString()); } return respBody.getDocumentIds(); } /** * 获取文档列表 * * @param request 文档列表请求对象,包含请求参数 * @return 文档数组 * @throws IOException 当发生输入输出异常时抛出 * @throws AppBuilderServerException 当应用构建服务器发生异常时抛出 */ @Deprecated public Document[] getDocumentList(DocumentListRequest request) throws IOException, AppBuilderServerException { String url = AppBuilderConfig.KNOWLEDGEBASE_DOCUMENT_LIST_URL; ClassicHttpRequest getRequest = httpClient.createGetRequestV2(url, request.toMap()); getRequest.setHeader("Content-Type", "application/json"); HttpResponse response = httpClient.execute(getRequest, DocumentListResponse.class); DocumentListResponse respBody = response.getBody(); return respBody.getData(); } public DocumentsDescribeResponse describeDocuments(DocumentsDescribeRequest request) throws IOException, AppBuilderServerException { String url = AppBuilderConfig.DESCRIBE_DOCUMENTS_URL; if (request.getKnowledgeBaseId().isEmpty() && !this.knowledgeBaseId.isEmpty()) { request.setKnowledgeBaseId(this.knowledgeBaseId); } String jsonBody = JsonUtils.serialize(request); ClassicHttpRequest postRequest = httpClient.createPostRequestV2(url, new StringEntity(jsonBody, StandardCharsets.UTF_8)); postRequest.setHeader("Content-Type", "application/json"); HttpResponse response = httpClient.execute(postRequest, DocumentsDescribeResponse.class); DocumentsDescribeResponse respBody = response.getBody(); return respBody; } /** * 删除文档 * * @param request 文档删除请求对象 * @throws IOException 如果在删除文档过程中发生I/O异常 * @throws AppBuilderServerException 如果在删除文档过程中发生AppBuilder服务器异常 */ public void deleteDocument(DocumentDeleteRequest request) throws IOException, AppBuilderServerException { innerDeleteDocument(request, java.util.UUID.randomUUID().toString()); } /** * 删除文档 * * @param request 删除文档的请求对象,包含要删除的文档ID等信息 * @param clientToken 客户端令牌,用于验证请求合法性 * @throws IOException 如果发生输入输出异常 * @throws AppBuilderServerException 如果发生应用构建服务器异常 */ public void deleteDocument(DocumentDeleteRequest request, String clientToken) throws IOException, AppBuilderServerException { innerDeleteDocument(request, clientToken); } /** * 删除文档 * * @param request 删除文档请求 * @param clientToken 客户端令牌 * @throws IOException IO异常 * @throws AppBuilderServerException 应用构建服务器异常 */ private void innerDeleteDocument(DocumentDeleteRequest request, String clientToken) throws IOException, AppBuilderServerException { String url = AppBuilderConfig.KNOWLEDGEBASE_DELETE_DOCUMENT_URL; url = url + "?clientToken=" + clientToken; ClassicHttpRequest getRequest = httpClient.createDeleteRequestV2(url, request.toMap()); getRequest.setHeader("Content-Type", "application/json"); HttpResponse response = httpClient.execute(getRequest, DocumentDeleteResponse.class); DocumentDeleteResponse respBody = response.getBody(); if (!(respBody.getCode() == null)) { throw new AppBuilderServerException(response.getRequestId(), response.getCode(), response.getMessage(), respBody.toString()); } } /** * 创建知识库详情 * * @param request 请求体,包含创建知识库所需的信息 * @return 创建成功后的知识库详情 * @throws IOException 当输入输出操作发生错误时抛出 * @throws AppBuilderServerException 当应用构建服务器发生错误时抛出 */ public KnowledgeBaseDetail createKnowledgeBase(KnowledgeBaseDetail request) throws IOException, AppBuilderServerException { return innerCreateKnowledgeBase(request, java.util.UUID.randomUUID().toString()); } /** * 创建知识库详情 * * @param request 包含创建知识库详情所需的参数 * @param clientToken 客户端令牌,用于身份验证 * @return 创建成功后的知识库详情对象 * @throws IOException 如果发生I/O错误 * @throws AppBuilderServerException 如果发生应用程序构建服务器异常 */ public KnowledgeBaseDetail createKnowledgeBase(KnowledgeBaseDetail request, String clientToken) throws IOException, AppBuilderServerException { return innerCreateKnowledgeBase(request, clientToken); } /** * 创建一个知识库详情 * * @param request 知识库详情请求对象 * @param clientToken 客户端令牌 * @return 创建成功后的知识库详情对象 * @throws IOException IO异常 * @throws AppBuilderServerException AppBuilder服务器异常 */ private KnowledgeBaseDetail innerCreateKnowledgeBase(KnowledgeBaseDetail request, String clientToken) throws IOException, AppBuilderServerException { String url = AppBuilderConfig.KNOWLEDGEBASE_CREATE_URL; url = url + "&clientToken=" + clientToken; String jsonBody = JsonUtils.serialize(request); ClassicHttpRequest postRequest = httpClient.createPostRequestV2(url, new StringEntity(jsonBody, StandardCharsets.UTF_8)); postRequest.setHeader("Content-Type", "application/json"); HttpResponse response = httpClient.execute(postRequest, KnowledgeBaseDetail.class); KnowledgeBaseDetail respBody = response.getBody(); return respBody; } /** * 根据知识库ID获取知识库详情 * * @param knowledgeBaseId 知识库ID * @return KnowledgeBaseDetail 知识库详情对象 * @throws IOException 如果在发送HTTP请求或解析响应时发生IO异常 * @throws AppBuilderServerException 如果发生AppBuilder服务器异常 */ public KnowledgeBaseDetail getKnowledgeBaseDetail(String knowledgeBaseId) throws IOException, AppBuilderServerException { String url = AppBuilderConfig.KNOWLEDGEBASE_DETAIL_URL; KnowledgeBaseDetailRequest request = new KnowledgeBaseDetailRequest(); request.setKnowledgeBaseId(knowledgeBaseId); String jsonBody = JsonUtils.serialize(request); ClassicHttpRequest postRequest = httpClient.createPostRequestV2(url, new StringEntity(jsonBody, StandardCharsets.UTF_8)); postRequest.setHeader("Content-Type", "application/json"); HttpResponse response = httpClient.execute(postRequest, KnowledgeBaseDetail.class); KnowledgeBaseDetail respBody = response.getBody(); return respBody; } /** * 删除知识库 * * @param knowledgeBaseId 知识库ID * @throws IOException 当发生输入输出异常时抛出 * @throws AppBuilderServerException 当应用构建服务器异常时抛出 */ public void deleteKnowledgeBase(String knowledgeBaseId) throws IOException, AppBuilderServerException { innerDeleteKnowledgeBase(knowledgeBaseId, java.util.UUID.randomUUID().toString()); } /** * 删除知识库 * * @param knowledgeBaseId 知识库ID * @param clientToken 客户端令牌 * @throws IOException 如果发生输入输出异常 * @throws AppBuilderServerException 如果发生应用构建服务器异常 */ public void deleteKnowledgeBase(String knowledgeBaseId, String clientToken) throws IOException, AppBuilderServerException { innerDeleteKnowledgeBase(knowledgeBaseId, clientToken); } /** * 删除知识库 * * @param knowledgeBaseId 知识库ID * @param clientToken 客户端令牌 * @throws IOException IO异常 * @throws AppBuilderServerException AppBuilder服务器异常 */ private void innerDeleteKnowledgeBase(String knowledgeBaseId, String clientToken) throws IOException, AppBuilderServerException { String url = AppBuilderConfig.KNOWLEDGEBASE_DELETE_URL; KnowledgeBaseDetailRequest request = new KnowledgeBaseDetailRequest(); request.setKnowledgeBaseId(knowledgeBaseId); String jsonBody = JsonUtils.serialize(request); url = url + "&clientToken=" + clientToken; ClassicHttpRequest postRequest = httpClient.createPostRequestV2(url, new StringEntity(jsonBody, StandardCharsets.UTF_8)); postRequest.setHeader("Content-Type", "application/json"); httpClient.execute(postRequest, null); } /** * 修改知识库。 * * @param request 知识库修改请求对象 * @throws IOException 如果在I/O操作过程中发生错误,则抛出此异常 * @throws AppBuilderServerException 如果应用构建服务器发生错误,则抛出此异常 */ public void modifyKnowledgeBase(KnowledgeBaseModifyRequest request) throws IOException, AppBuilderServerException { modifyKnowledgeBase(request, java.util.UUID.randomUUID().toString()); } /** * 修改知识库 * * @param request 修改请求对象,包含需要修改的内容 * @param clientToken 客户端令牌,用于验证请求来源的合法性 * @throws IOException 如果发生输入输出异常 * @throws AppBuilderServerException 如果应用构建服务器发生异常 */ public void modifyKnowledgeBase(KnowledgeBaseModifyRequest request, String clientToken) throws IOException, AppBuilderServerException { innerModifyKnowledgeBase(request, clientToken); } /** * 修改知识库 * * @param request 修改知识库的请求对象 * @param clientToken 客户端令牌 * @throws IOException 当请求过程中发生I/O异常时抛出 * @throws AppBuilderServerException 当请求过程中发生服务器异常时抛出 */ private void innerModifyKnowledgeBase(KnowledgeBaseModifyRequest request, String clientToken) throws IOException, AppBuilderServerException { String url = AppBuilderConfig.KNOWLEDGEBASE_MODIFY_URL; String jsonBody = JsonUtils.serialize(request); url = url + "&clientToken=" + clientToken; ClassicHttpRequest postRequest = httpClient.createPostRequestV2(url, new StringEntity(jsonBody, StandardCharsets.UTF_8)); postRequest.setHeader("Content-Type", "application/json"); httpClient.execute(postRequest, null); } /** * 获取知识库列表 * * @param request 包含请求参数的知识库列表请求对象 * @return 知识库列表响应对象 * @throws IOException 如果发生I/O异常,抛出此异常 * @throws AppBuilderServerException 如果应用构建服务器发生异常,抛出此异常 */ public KnowledgeBaseListResponse getKnowledgeBaseList(KnowledgeBaseListRequest request) throws IOException, AppBuilderServerException { String url = AppBuilderConfig.KNOWLEDGEBASE_LIST_URL; String jsonBody = JsonUtils.serialize(request); ClassicHttpRequest postRequest = httpClient.createPostRequestV2(url, new StringEntity(jsonBody, StandardCharsets.UTF_8)); postRequest.setHeader("Content-Type", "application/json"); HttpResponse response = httpClient.execute(postRequest, KnowledgeBaseListResponse.class); KnowledgeBaseListResponse respBody = response.getBody(); return respBody; } /** * 创建文档 * * @param request 文档创建请求 * @return 创建文档的响应结果 * @throws IOException 当发生输入输出异常时抛出 * @throws AppBuilderServerException 当应用构建服务器发生异常时抛出 */ public DocumentsCreateResponse createDocuments(DocumentsCreateRequest request) throws IOException, AppBuilderServerException { return innerCreateDocuments(request, java.util.UUID.randomUUID().toString()); } /** * 创建文档 * * @param request 包含创建文档所需信息的请求对象 * @param clientToken 客户端令牌,用于身份验证 * @return 包含创建文档结果的响应对象 * @throws IOException 如果发生输入/输出错误 * @throws AppBuilderServerException 如果应用程序构建服务器发生错误 */ public DocumentsCreateResponse createDocuments(DocumentsCreateRequest request, String clientToken) throws IOException, AppBuilderServerException { return innerCreateDocuments(request, clientToken); } /** * 创建文档的内部方法 * * @param request 创建文档的请求参数 * @param clientToken 客户端令牌 * @return 创建文档的响应结果 * @throws IOException 如果发生输入输出异常 * @throws AppBuilderServerException 如果应用构建服务器发生异常 */ private DocumentsCreateResponse innerCreateDocuments(DocumentsCreateRequest request, String clientToken) throws IOException, AppBuilderServerException { String url = AppBuilderConfig.KNOWLEDGEBASE_CREATE_DOCUMENTS_URL; String jsonBody = JsonUtils.serialize(request); url = url + "&clientToken=" + clientToken; ClassicHttpRequest postRequest = httpClient.createPostRequestV2(url, new StringEntity(jsonBody, StandardCharsets.UTF_8)); postRequest.setHeader("Content-Type", "application/json"); httpClient.execute(postRequest, null); HttpResponse response = httpClient.execute(postRequest, DocumentsCreateResponse.class); DocumentsCreateResponse respBody = response.getBody(); return respBody; } /** * 上传文档 * * @param filePath 文件路径 * @param request 文档创建请求 * @return 文档上传响应 * @throws IOException 如果发生I/O错误,则抛出此异常 * @throws AppBuilderServerException 如果发生应用程序构建服务器错误,则抛出此异常 */ public DocumentsUploadResponse uploadDocuments(String filePath, DocumentsCreateRequest request) throws IOException, AppBuilderServerException { return innerUploadDocuments(filePath, request, java.util.UUID.randomUUID().toString()); } /** * 上传文档 * * @param filePath 文件路径 * @param request 文档上传请求对象 * @param clientToken 客户端Token * @return 文档上传响应对象 * @throws IOException 抛出IO异常 * @throws AppBuilderServerException 抛出应用构建服务器异常 */ public DocumentsUploadResponse uploadDocuments(String filePath, DocumentsCreateRequest request, String clientToken) throws IOException, AppBuilderServerException { return innerUploadDocuments(filePath, request, clientToken); } /** * 上传文档到知识库 * * @param filePath 要上传的文件的路径 * @param request 文档上传请求对象 * @param clientToken 客户端令牌 * @return 上传文档响应对象 * @throws IOException 如果在IO操作过程中发生错误 * @throws AppBuilderServerException 如果在应用构建服务器操作过程中发生错误 */ private DocumentsUploadResponse innerUploadDocuments(String filePath, DocumentsCreateRequest request, String clientToken) throws IOException, AppBuilderServerException { String url = AppBuilderConfig.KNOWLEDGEBASE_UPLOAD_DOCUMENTS_URL; MultipartEntityBuilder builder = MultipartEntityBuilder.create() .setMode(HttpMultipartMode.LEGACY).setCharset(StandardCharsets.UTF_8); builder.addBinaryBody("file", new File(filePath)); String jsonBody = JsonUtils.serialize(request); builder.addTextBody("payload", jsonBody); url = url + "&clientToken=" + clientToken; ClassicHttpRequest postRequest = httpClient.createPostRequestV2(url, builder.build()); HttpResponse response = httpClient.execute(postRequest, DocumentsUploadResponse.class); DocumentsUploadResponse respBody = response.getBody(); return respBody; } /** * 根据给定的文档ID和内容创建一个块 * * @param documentId 文档ID * @param content 块的内容 * @return 创建的块的字符串表示 * @throws IOException 如果在文件操作中发生错误 * @throws AppBuilderServerException 如果在应用程序构建服务器操作中发生错误 */ public String createChunk(String documentId, String content) throws IOException, AppBuilderServerException { return innerCreateChunk(documentId, content, java.util.UUID.randomUUID().toString()); } /** * 创建文档块 * * @param documentId 文档ID * @param content 文档内容 * @param clientToken 客户端令牌 * @return 创建的文档块字符串 * @throws IOException 如果发生I/O错误 * @throws AppBuilderServerException 如果应用程序构建服务器异常 */ public String createChunk(String documentId, String content, String clientToken) throws IOException, AppBuilderServerException { return innerCreateChunk(documentId, content, clientToken); } /** * 内部创建文档片段的方法 * * @param documentId 文档ID * @param content 文档内容 * @param clientToken 客户端令牌 * @return 创建的文档片段ID * @throws IOException IO异常 * @throws AppBuilderServerException 应用构建服务器异常 */ private String innerCreateChunk(String documentId, String content, String clientToken) throws IOException, AppBuilderServerException { String url = AppBuilderConfig.CHUNK_CREATE_URL; ChunkCreateRequest request; if(this.knowledgeBaseId.isEmpty()) { request = new ChunkCreateRequest(documentId, content); } else { request = new ChunkCreateRequest(this.knowledgeBaseId, documentId, content); } String jsonBody = JsonUtils.serialize(request); url = url + "&clientToken=" + clientToken; ClassicHttpRequest postRequest = httpClient.createPostRequestV2(url, new StringEntity(jsonBody, StandardCharsets.UTF_8)); postRequest.setHeader("Content-Type", "application/json"); HttpResponse response = httpClient.execute(postRequest, ChunkCreateResponse.class); ChunkCreateResponse respBody = response.getBody(); return respBody.getChunkId(); } /** * 修改指定块的内容 * * @param chunkId 块标识符 * @param content 要设置的内容 * @param enable 是否启用块 * @throws IOException 当发生输入输出异常时抛出 * @throws AppBuilderServerException 当发生应用构建服务器异常时抛出 */ public void modifyChunk(String chunkId, String content, boolean enable) throws IOException, AppBuilderServerException { innerModifyChunk(chunkId, content, enable, java.util.UUID.randomUUID().toString()); } /** * 修改指定区块的内容及其启用状态 * * @param chunkId 区块的ID * @param content 需要设置的新内容 * @param enable 是否启用该区块,true表示启用,false表示禁用 * @param clientToken 客户端令牌,用于验证客户端身份 * @throws IOException 如果发生I/O错误 * @throws AppBuilderServerException 如果发生应用构建服务器错误 */ public void modifyChunk(String chunkId, String content, boolean enable, String clientToken) throws IOException, AppBuilderServerException { innerModifyChunk(chunkId, content, enable, clientToken); } /** * 修改指定的块内容 * * @param chunkId 块的ID * @param content 块的新内容 * @param enable 是否启用块,true 表示启用,false 表示禁用 * @param clientToken 客户端令牌 * @throws IOException 如果发生I/O错误 * @throws AppBuilderServerException 如果应用构建服务器发生错误 */ private void innerModifyChunk(String chunkId, String content, boolean enable, String clientToken) throws IOException, AppBuilderServerException { String url = AppBuilderConfig.CHUNK_MODIFY_URL; ChunkModifyRequest request; if (this.knowledgeBaseId.isEmpty()) { request = new ChunkModifyRequest(chunkId, content, enable); } else { request = new ChunkModifyRequest(this.knowledgeBaseId, chunkId, content, enable); } String jsonBody = JsonUtils.serialize(request); url = url + "&clientToken=" + clientToken; ClassicHttpRequest postRequest = httpClient.createPostRequestV2(url, new StringEntity(jsonBody, StandardCharsets.UTF_8)); postRequest.setHeader("Content-Type", "application/json"); httpClient.execute(postRequest, ChunkCreateResponse.class); } /** * 删除指定的文件块。 * * @param chunkId 要删除的文件块的ID * @throws IOException 如果发生I/O错误 * @throws AppBuilderServerException 如果发生应用构建服务器异常 */ public void deleteChunk(String chunkId) throws IOException, AppBuilderServerException { innderDeleteChunk(chunkId, java.util.UUID.randomUUID().toString()); } /** * 删除指定的块。 * * @param chunkId 块标识 * @param clientToken 客户端令牌 * @throws IOException 如果发生输入输出异常 * @throws AppBuilderServerException 如果发生应用程序构建服务器异常 */ public void deleteChunk(String chunkId, String clientToken) throws IOException, AppBuilderServerException { innderDeleteChunk(chunkId, clientToken); } /** * 删除指定块 * * @param chunkId 块ID * @param clientToken 客户端令牌 * @throws IOException 当I/O操作失败时抛出 * @throws AppBuilderServerException 当应用构建服务器异常时抛出 */ private void innderDeleteChunk(String chunkId, String clientToken) throws IOException, AppBuilderServerException { String url = AppBuilderConfig.CHUNK_DELETE_URL; ChunkDeleteRequest request = new ChunkDeleteRequest(); request.setChunkId(chunkId); if (!this.knowledgeBaseId.isEmpty()) { request.setKnowledgeBaseId(this.knowledgeBaseId); } String jsonBody = JsonUtils.serialize(request); url = url + "&clientToken=" + clientToken; ClassicHttpRequest postRequest = httpClient.createPostRequestV2(url, new StringEntity(jsonBody, StandardCharsets.UTF_8)); postRequest.setHeader("Content-Type", "application/json"); httpClient.execute(postRequest, ChunkCreateResponse.class); } /** * 根据块ID描述块 * * @param chunkId 块ID * @return 描述块的响应对象 * @throws IOException 如果发生输入输出异常 * @throws AppBuilderServerException 如果发生应用构建服务器异常 */ public ChunkDescribeResponse describeChunk(String chunkId) throws IOException, AppBuilderServerException { String url = AppBuilderConfig.CHUNK_DESCRIBE_URL; ChunkDescribeRequest request = new ChunkDescribeRequest(); request.setChunkId(chunkId); if (!this.knowledgeBaseId.isEmpty()) { request.setKnowledgeBaseId(this.knowledgeBaseId); } String jsonBody = JsonUtils.serialize(request); ClassicHttpRequest postRequest = httpClient.createPostRequestV2(url, new StringEntity(jsonBody, StandardCharsets.UTF_8)); postRequest.setHeader("Content-Type", "application/json"); HttpResponse response = httpClient.execute(postRequest, ChunkDescribeResponse.class); ChunkDescribeResponse respBody = response.getBody(); return respBody; } /** * 描述文档的分块信息 * * @param documentId 文档ID * @param marker 分页标记 * @param maxKeys 返回的最大分块数量 * @param type 分块类型 * @return 返回包含文档分块信息的ChunksDescribeResponse对象 * @throws IOException 如果发生I/O异常 * @throws AppBuilderServerException 如果发生AppBuilder服务器异常 */ public ChunksDescribeResponse describeChunks(String documentId, String marker, Integer maxKeys, String type) throws IOException, AppBuilderServerException { String url = AppBuilderConfig.CHUNKS_DESCRIBE_URL; ChunksDescribeRequest request = new ChunksDescribeRequest(documentId, marker, maxKeys, type); if (!this.knowledgeBaseId.isEmpty()) { request.setKnowledgeBaseId(this.knowledgeBaseId); } String jsonBody = JsonUtils.serialize(request); ClassicHttpRequest postRequest = httpClient.createPostRequestV2(url, new StringEntity(jsonBody, StandardCharsets.UTF_8)); postRequest.setHeader("Content-Type", "application/json"); HttpResponse response = httpClient.execute(postRequest, ChunksDescribeResponse.class); ChunksDescribeResponse respBody = response.getBody(); return respBody; } public ChunksDescribeResponse describeChunks(ChunksDescribeRequest request) throws IOException, AppBuilderServerException { String url = AppBuilderConfig.CHUNKS_DESCRIBE_URL; if (!this.knowledgeBaseId.isEmpty()) { request.setKnowledgeBaseId(this.knowledgeBaseId); } String jsonBody = JsonUtils.serialize(request); ClassicHttpRequest postRequest = httpClient.createPostRequestV2(url, new StringEntity(jsonBody, StandardCharsets.UTF_8)); postRequest.setHeader("Content-Type", "application/json"); HttpResponse response = httpClient.execute(postRequest, ChunksDescribeResponse.class); ChunksDescribeResponse respBody = response.getBody(); return respBody; } public QueryKnowledgeBaseResponse queryKnowledgeBase(QueryKnowledgeBaseRequest request) throws IOException, AppBuilderServerException { if (request.getRank_score_threshold() == null) { request.setRank_score_threshold(0.4f); } String url = AppBuilderConfig.QUERY_KNOWLEDGEBASE_URL; String jsonBody = JsonUtils.serialize(request); ClassicHttpRequest postRequest = httpClient.createPostRequestV2(url, new StringEntity(jsonBody, StandardCharsets.UTF_8)); postRequest.setHeader("Content-Type", "application/json"); HttpResponse response = httpClient.execute(postRequest, QueryKnowledgeBaseResponse.class); QueryKnowledgeBaseResponse respBody = response.getBody(); return respBody; } public QueryKnowledgeBaseResponse queryKnowledgeBase(String query, String type, Integer top, Integer skip, String[] knowledgebaseIDs, QueryKnowledgeBaseRequest.MetadataFilters filters, QueryKnowledgeBaseRequest.QueryPipelineConfig pipelineConfig) throws IOException, AppBuilderServerException { float rank_score_threshold = 0.4f; String url = AppBuilderConfig.QUERY_KNOWLEDGEBASE_URL; QueryKnowledgeBaseRequest request = new QueryKnowledgeBaseRequest(query, type, rank_score_threshold, top, skip, knowledgebaseIDs, filters, pipelineConfig); String jsonBody = JsonUtils.serialize(request); ClassicHttpRequest postRequest = httpClient.createPostRequestV2(url, new StringEntity(jsonBody, StandardCharsets.UTF_8)); postRequest.setHeader("Content-Type", "application/json"); HttpResponse response = httpClient.execute(postRequest, QueryKnowledgeBaseResponse.class); QueryKnowledgeBaseResponse respBody = response.getBody(); return respBody; } public QueryKnowledgeBaseResponse queryKnowledgeBase(String query, String type, Float rank_score_threshold, Integer top, Integer skip, String[] knowledgebaseIDs, QueryKnowledgeBaseRequest.MetadataFilters filters, QueryKnowledgeBaseRequest.QueryPipelineConfig pipelineConfig) throws IOException, AppBuilderServerException { if (rank_score_threshold == null) { rank_score_threshold = 0.4f; } String url = AppBuilderConfig.QUERY_KNOWLEDGEBASE_URL; QueryKnowledgeBaseRequest request = new QueryKnowledgeBaseRequest(query, type, rank_score_threshold, top, skip, knowledgebaseIDs, filters, pipelineConfig); String jsonBody = JsonUtils.serialize(request); ClassicHttpRequest postRequest = httpClient.createPostRequestV2(url, new StringEntity(jsonBody, StandardCharsets.UTF_8)); postRequest.setHeader("Content-Type", "application/json"); HttpResponse response = httpClient.execute(postRequest, QueryKnowledgeBaseResponse.class); QueryKnowledgeBaseResponse respBody = response.getBody(); return respBody; } } ================================================ FILE: java/src/main/java/com/baidubce/appbuilder/console/rag/RAG.java ================================================ package com.baidubce.appbuilder.console.rag; import java.io.IOException; import java.nio.charset.StandardCharsets; import java.util.HashMap; import java.util.Map; import com.baidubce.appbuilder.base.component.Component; import com.baidubce.appbuilder.base.config.AppBuilderConfig; import com.baidubce.appbuilder.base.exception.AppBuilderServerException; import com.baidubce.appbuilder.base.utils.iterator.StreamIterator; import com.baidubce.appbuilder.model.rag.RAGIterator; import com.baidubce.appbuilder.model.rag.RAGResponse; import com.baidubce.appbuilder.base.utils.http.HttpResponse; import com.baidubce.appbuilder.base.utils.json.JsonUtils; import org.apache.hc.core5.http.ClassicHttpRequest; import org.apache.hc.core5.http.io.entity.StringEntity; public class RAG extends Component { public String appID; public RAG(String appID) { super(); this.appID = appID; } public RAG(String appID, String secretKey) { super(secretKey); this.appID = appID; } public RAG(String appID, String secretKey, String gateway) { super(secretKey, gateway); this.appID = appID; } /** * 运行RAG模型,根据输入的问题、会话ID以及是否以流模式返回结果,返回RAGResponse的迭代器。 * * @param query 问题 * @param conversationId 会话ID * @param stream 是否以流模式返回结果 * @return RAGResponse的迭代器 * @throws IOException 当请求失败时抛出IOException * @throws AppBuilderServerException 当服务器返回错误码时抛出AppBuilderServerException */ public RAGIterator run(String query, String conversationId, boolean stream) throws IOException, AppBuilderServerException { String url = AppBuilderConfig.RAG_RUN_URL; if (this.appID == null || this.appID.isEmpty()) { throw new RuntimeException("Param 'appID' is required!"); } Map requestBody = new HashMap<>(); requestBody.put("app_id", this.appID); requestBody.put("query", query); requestBody.put("conversation_id", conversationId); requestBody.put("response_mode", stream ? "streaming" : "blocking"); String jsonBody = JsonUtils.serialize(requestBody); ClassicHttpRequest postRequest = httpClient.createPostRequest(url, new StringEntity(jsonBody, StandardCharsets.UTF_8)); postRequest.setHeader("Content-Type", "application/json"); HttpResponse> response = httpClient.executeSSE(postRequest, RAGResponse.class); return new RAGIterator(response); } } ================================================ FILE: java/src/main/java/com/baidubce/appbuilder/model/agentbuilder/AgentBuilderIterator.java ================================================ package com.baidubce.appbuilder.model.agentbuilder; import com.baidubce.appbuilder.base.utils.iterator.StreamIterator; import java.util.stream.IntStream; public class AgentBuilderIterator { private final StreamIterator iterator; public AgentBuilderIterator(StreamIterator iterator) { this.iterator = iterator; } public boolean hasNext() { return iterator.hasNext(); } public AgentBuilderResult next() { AgentBuilderResponse response = iterator.next(); Event[] events = new Event[response.getContent().length]; EventContent[] contents = response.getContent(); IntStream.range(0, contents.length).forEach(i -> { events[i] = new Event() .setCode(contents[i].getEventCode()) .setMessage(contents[i].getEnentMessage()) .setStatus(contents[i].getEventStatus()) .setEventType(contents[i].getEventType()) .setContentType(contents[i].getContentType()) .setDetail(contents[i].getOutputs()); }); return new AgentBuilderResult() .setAnswer(response.getAnswer()) .setEvents(events); } public void close(){ iterator.close(); } } ================================================ FILE: java/src/main/java/com/baidubce/appbuilder/model/agentbuilder/AgentBuilderResponse.java ================================================ package com.baidubce.appbuilder.model.agentbuilder; import com.google.gson.annotations.SerializedName; import java.util.Arrays; public class AgentBuilderResponse { @SerializedName("request_id") private String requestId; private String data; private String answer; @SerializedName("conversation_id") private String conversationId; @SerializedName("message_id") private String messageId; @SerializedName("is_completion") private boolean isCompletion; private EventContent[] content; public String getRequestId() { return requestId; } public void setRequestId(String requestId) { this.requestId = requestId; } public String getData() { return data; } public void setData(String data) { this.data = data; } public String getAnswer() { return answer; } public void setAnswer(String answer) { this.answer = answer; } public String getConversationId() { return conversationId; } public void setConversationId(String conversationId) { this.conversationId = conversationId; } public String getMessageId() { return messageId; } public void setMessageId(String messageId) { this.messageId = messageId; } public boolean isCompletion() { return isCompletion; } public void setCompletion(boolean completion) { isCompletion = completion; } public EventContent[] getContent() { return content; } public void setContent(EventContent[] content) { this.content = content; } @Override public String toString() { return "AgentBuilderResponse{" + "requestId='" + requestId + '\'' + ", data='" + data + '\'' + ", answer='" + answer + '\'' + ", conversationId='" + conversationId + '\'' + ", messageId='" + messageId + '\'' + ", isCompletion=" + isCompletion + ", content=" + Arrays.toString(content) + '}'; } } ================================================ FILE: java/src/main/java/com/baidubce/appbuilder/model/agentbuilder/AgentBuilderResult.java ================================================ package com.baidubce.appbuilder.model.agentbuilder; import java.util.Arrays; public class AgentBuilderResult { private String answer; private Event[] events; public String getAnswer() { return answer; } public AgentBuilderResult setAnswer(String answer) { this.answer = answer; return this; } public Event[] getEvents() { return events; } public AgentBuilderResult setEvents(Event[] events) { this.events = events; return this; } @Override public String toString() { return "AgentBuilderResult{" + "answer='" + answer + '\'' + ", events=" + Arrays.toString(events) + '}'; } } ================================================ FILE: java/src/main/java/com/baidubce/appbuilder/model/agentbuilder/ConversationResponse.java ================================================ package com.baidubce.appbuilder.model.agentbuilder; import com.google.gson.annotations.SerializedName; public class ConversationResponse { private String requestId; @SerializedName("conversation_id") private String conversationId; public String getRequestId() { return requestId; } public void setRequestId(String requestId) { this.requestId = requestId; } public String getConversationId() { return conversationId; } public void setConversationId(String conversationId) { this.conversationId = conversationId; } @Override public String toString() { return "ConversationResponse{" + "requestId='" + requestId + '\'' + ", conversationId='" + conversationId + '\'' + '}'; } } ================================================ FILE: java/src/main/java/com/baidubce/appbuilder/model/agentbuilder/Event.java ================================================ package com.baidubce.appbuilder.model.agentbuilder; import java.util.Map; public class Event { private String code; private String message; private String eventType; private String status; private String contentType; private Map detail; public String getCode() { return code; } public Event setCode(String code) { this.code = code; return this; } public String getMessage() { return message; } public Event setMessage(String message) { this.message = message; return this; } public String getEventType() { return eventType; } public Event setEventType(String eventType) { this.eventType = eventType; return this; } public String getStatus() { return status; } public Event setStatus(String status) { this.status = status; return this; } public String getContentType() { return contentType; } public Event setContentType(String contentType) { this.contentType = contentType; return this; } public Map getDetail() { return detail; } public Event setDetail(Map detail) { this.detail = detail; return this; } @Override public String toString() { return "Event{" + "code='" + code + '\'' + ", message='" + message + '\'' + ", eventType='" + eventType + '\'' + ", status='" + status + '\'' + ", contentType='" + contentType + '\'' + ", detail=" + detail + '}'; } } ================================================ FILE: java/src/main/java/com/baidubce/appbuilder/model/agentbuilder/EventContent.java ================================================ package com.baidubce.appbuilder.model.agentbuilder; import com.google.gson.annotations.SerializedName; import java.util.HashMap; import java.util.Map; public class EventContent { @SerializedName("event_code") private String eventCode; @SerializedName("event_message") private String enentMessage; @SerializedName("event_type") private String eventType; @SerializedName("event_id") private String eventId; @SerializedName("event_status") private String eventStatus; @SerializedName("content_type") private String contentType; private Map outputs; public String getEventCode() { return eventCode; } public void setEventCode(String eventCode) { this.eventCode = eventCode; } public String getEnentMessage() { return enentMessage; } public void setEnentMessage(String enentMessage) { this.enentMessage = enentMessage; } public String getEventType() { return eventType; } public void setEventType(String eventType) { this.eventType = eventType; } public String getEventId() { return eventId; } public void setEventId(String eventId) { this.eventId = eventId; } public String getEventStatus() { return eventStatus; } public void setEventStatus(String eventStatus) { this.eventStatus = eventStatus; } public String getContentType() { return contentType; } public void setContentType(String contentType) { this.contentType = contentType; } public Map getOutputs() { return outputs; } public void setOutputs(Map outputs) { this.outputs = outputs; } @Override public String toString() { return "EventContent{" + "eventCode='" + eventCode + '\'' + ", enentMessage='" + enentMessage + '\'' + ", eventType='" + eventType + '\'' + ", eventId='" + eventId + '\'' + ", eventStatus='" + eventStatus + '\'' + ", contentType='" + contentType + '\'' + ", outputs=" + outputs + '}'; } } ================================================ FILE: java/src/main/java/com/baidubce/appbuilder/model/agentbuilder/FileUploadResponse.java ================================================ package com.baidubce.appbuilder.model.agentbuilder; import com.google.gson.annotations.SerializedName; public class FileUploadResponse { private String requestId; @SerializedName("id") private String fileId; @SerializedName("conversation_id") private String conversationId; public String getRequestId() { return requestId; } public void setRequestId(String requestId) { this.requestId = requestId; } public String getFileId() { return fileId; } @Override public String toString() { return "FileUploadResponse{" + "requestId='" + requestId + '\'' + ", fileId='" + fileId + '\'' + ", conversationId='" + conversationId + '\'' + '}'; } public void setFileId(String fileId) { this.fileId = fileId; } public String getConversationId() { return conversationId; } public void setConversationId(String conversationId) { this.conversationId = conversationId; } } ================================================ FILE: java/src/main/java/com/baidubce/appbuilder/model/aisearch/AISearchIterator.java ================================================ package com.baidubce.appbuilder.model.aisearch; import com.baidubce.appbuilder.base.utils.iterator.StreamIterator; public class AISearchIterator { private final StreamIterator iterator; public AISearchIterator(StreamIterator iterator) { this.iterator = iterator; } public boolean hasNext() { return iterator.hasNext(); } public AISearchResponse next() { return iterator.next(); } public void close(){ iterator.close(); } } ================================================ FILE: java/src/main/java/com/baidubce/appbuilder/model/aisearch/AISearchRequest.java ================================================ package com.baidubce.appbuilder.model.aisearch; import com.google.gson.annotations.SerializedName; public class AISearchRequest { // region 主字段 @SerializedName("messages") private Message[] messages; @SerializedName("search_source") private String searchSource = "baidu_search_v1"; @SerializedName("resource_type_filter") private SearchResource[] resourceTypeFilter; @SerializedName("search_filter") private SearchFilter searchFilter; @SerializedName("search_recency_filter") private String searchRecencyFilter; @SerializedName("search_domain_filter") private String[] searchDomainFilter; @SerializedName("model") private String model; @SerializedName("instruction") private String instruction = ""; @SerializedName("temperature") private Double temperature = 1e-10; @SerializedName("top_p") private Double topP = 1e-10; @SerializedName("prompt_template") private String promptTemplate; @SerializedName("search_mode") private String searchMode = "auto"; @SerializedName("enable_reasoning") private Boolean enableReasoning = true; @SerializedName("enable_deep_search") private Boolean enableDeepSearch = false; @SerializedName("additional_knowledge") private Knowledge[] additionalKnowledge; @SerializedName("max_completion_tokens") private Integer maxCompletionTokens = 2048; @SerializedName("response_format") private String responseFormat = "auto"; @SerializedName("enable_corner_markers") private Boolean enableCornerMarkers = true; @SerializedName("enable_followup_queries") private Boolean enableFollowupQueries = false; @SerializedName("stream") private Boolean stream = false; @SerializedName("safety_level") private String safetyLevel; @SerializedName("max_refer_search_items") private Integer maxReferSearchItems = 100; @SerializedName("config_id") private String configId = ""; @SerializedName("model_appid") private String modelAppid = ""; public static class Message { @SerializedName("role") private String role; @SerializedName("content") private Object content; // String or List public Message(String role, Object content) { this.role = role; this.content = content; } public void setRole(String role) { this.role = role; } public void setContent(Object content) { this.content = content; } public String getRole() { return role; } public Object getContent() { return content; } } public static class SearchResource { @SerializedName("top_k") private int topK; @SerializedName("type") private String type; public SearchResource(int topK, String type) { this.topK = topK; this.type = type; } public int getTopK() { return topK; } public String getType() { return type; } public void setTopK(int topK) { this.topK = topK; } public void setType(String type) { this.type = type; } } public static class SearchFilter { @SerializedName("range") private Range range; @SerializedName("match") private Match match; public SearchFilter(Range range, Match match) { this.range = range; this.match = match; } public Range getRange() { return range; } public Match getMatch() { return match; } public void setRange(Range range) { this.range = range; } public void setMatch(Match match) { this.match = match; } } public static class Range { @SerializedName("page_time") private PageTime pageTime; public Range(PageTime pageTime) { this.pageTime = pageTime; } public PageTime getPageTime() { return pageTime; } public void setPageTime(PageTime pageTime) { this.pageTime = pageTime; } } public static class PageTime { @SerializedName("gth") private String gth = ""; @SerializedName("gt") private String gt = ""; @SerializedName("lth") private String lth = ""; @SerializedName("lt") private String lt = ""; public PageTime(String gth, String gt, String lth, String lt) { this.gth = gth; this.gt = gt; this.lth = lth; this.lt = lt; } public String getGth() { return gth; } public String getGt() { return gt; } public String getLth() { return lth; } public String getLt() { return lt; } public void setGth(String gth) { this.gth = gth; } public void setGt(String gt) { this.gt = gt; } public void setLth(String lth) { this.lth = lth; } public void setLt(String lt) { this.lt = lt; } } public static class Match { @SerializedName("site") private String[] site; public Match(String[] site) { this.site = site; } public String[] getSite() { return site; } public void setSite(String[] site) { this.site = site; } } public static class Knowledge { @SerializedName("priority") private Integer priority = 0; @SerializedName("data_type") private String dataType; @SerializedName("data") private KnowledgeData data; public Knowledge(Integer priority, String dataType, KnowledgeData data) { this.priority = priority; this.dataType = dataType; this.data = data; } public Integer getPriority() { return priority; } public String getDataType() { return dataType; } public KnowledgeData getData() { return data; } public void setPriority(Integer priority) { this.priority = priority; } public void setDataType(String dataType) { this.dataType = dataType; } public void setData(KnowledgeData data) { this.data = data; } } public static class KnowledgeData { @SerializedName("content") private String content; @SerializedName("title") private String title; @SerializedName("url") private String url; @SerializedName("release_date") private String releaseDate; public KnowledgeData(String content, String title, String url, String releaseDate) { this.content = content; this.title = title; this.url = url; this.releaseDate = releaseDate; } public String getContent() { return content; } public String getTitle() { return title; } public String getUrl() { return url; } public String getReleaseDate() { return releaseDate; } public void setContent(String content) { this.content = content; } public void setTitle(String title) { this.title = title; } public void setUrl(String url) { this.url = url; } public void setReleaseDate(String releaseDate) { this.releaseDate = releaseDate; } } public Message[] getMessages() { return messages; } public AISearchRequest setMessages(Message[] messages) { this.messages = messages; return this; } public String getSearchSource() { return searchSource; } public AISearchRequest setSearchSource(String searchSource) { this.searchSource = searchSource; return this; } public SearchResource[] getResourceTypeFilter() { return resourceTypeFilter; } public AISearchRequest setResourceTypeFilter(SearchResource[] resourceTypeFilter) { this.resourceTypeFilter = resourceTypeFilter; return this; } public SearchFilter getSearchFilter() { return searchFilter; } public AISearchRequest setSearchFilter(SearchFilter searchFilter) { this.searchFilter = searchFilter; return this; } public String getSearchRecencyFilter() { return searchRecencyFilter; } public AISearchRequest setSearchRecencyFilter(String searchRecencyFilter) { this.searchRecencyFilter = searchRecencyFilter; return this; } public String[] getSearchDomainFilter() { return searchDomainFilter; } public AISearchRequest setSearchDomainFilter(String[] searchDomainFilter) { this.searchDomainFilter = searchDomainFilter; return this; } public String getModel() { return model; } public AISearchRequest setModel(String model) { this.model = model; return this; } public String getInstruction() { return instruction; } public AISearchRequest setInstruction(String instruction) { this.instruction = instruction; return this; } public Double getTemperature() { return temperature; } public AISearchRequest setTemperature(Double temperature) { this.temperature = temperature; return this; } public Double getTopP() { return topP; } public AISearchRequest setTopP(Double topP) { this.topP = topP; return this; } public String getPromptTemplate() { return promptTemplate; } public AISearchRequest setPromptTemplate(String promptTemplate) { this.promptTemplate = promptTemplate; return this; } public String getSearchMode() { return searchMode; } public AISearchRequest setSearchMode(String searchMode) { this.searchMode = searchMode; return this; } public Boolean getEnableReasoning() { return enableReasoning; } public AISearchRequest setEnableReasoning(Boolean enableReasoning) { this.enableReasoning = enableReasoning; return this; } public Boolean getEnableDeepSearch() { return enableDeepSearch; } public AISearchRequest setEnableDeepSearch(Boolean enableDeepSearch) { this.enableDeepSearch = enableDeepSearch; return this; } public Knowledge[] getAdditionalKnowledge() { return additionalKnowledge; } public AISearchRequest setAdditionalKnowledge(Knowledge[] additionalKnowledge) { this.additionalKnowledge = additionalKnowledge; return this; } public Integer getMaxCompletionTokens() { return maxCompletionTokens; } public AISearchRequest setMaxCompletionTokens(Integer maxCompletionTokens) { this.maxCompletionTokens = maxCompletionTokens; return this; } public String getResponseFormat() { return responseFormat; } public AISearchRequest setResponseFormat(String responseFormat) { this.responseFormat = responseFormat; return this; } public Boolean getEnableCornerMarkers() { return enableCornerMarkers; } public AISearchRequest setEnableCornerMarkers(Boolean enableCornerMarkers) { this.enableCornerMarkers = enableCornerMarkers; return this; } public Boolean getEnableFollowupQueries() { return enableFollowupQueries; } public AISearchRequest setEnableFollowupQueries(Boolean enableFollowupQueries) { this.enableFollowupQueries = enableFollowupQueries; return this; } public Boolean getStream() { return stream; } public AISearchRequest setStream(Boolean stream) { this.stream = stream; return this; } public String getSafetyLevel() { return safetyLevel; } public AISearchRequest setSafetyLevel(String safetyLevel) { this.safetyLevel = safetyLevel; return this; } public Integer getMaxReferSearchItems() { return maxReferSearchItems; } public AISearchRequest setMaxReferSearchItems(Integer maxReferSearchItems) { this.maxReferSearchItems = maxReferSearchItems; return this; } public String getConfigId() { return configId; } public AISearchRequest setConfigId(String configId) { this.configId = configId; return this; } public String getModelAppid() { return modelAppid; } public AISearchRequest setModelAppid(String modelAppid) { this.modelAppid = modelAppid; return this; } } ================================================ FILE: java/src/main/java/com/baidubce/appbuilder/model/aisearch/AISearchResponse.java ================================================ package com.baidubce.appbuilder.model.aisearch; import com.google.gson.annotations.SerializedName; import java.util.List; public class AISearchResponse { @SerializedName("request_id") private String requestId; @SerializedName("is_safe") private Boolean isSafe; private List choices; private String code; private String message; private Usage usage; private List references; @SerializedName("followup_queries") private List followupQueries; public String getRequestId() { return requestId; } public AISearchResponse setRequestId(String requestId) { this.requestId = requestId; return this; } public Boolean getIsSafe() { return isSafe; } public AISearchResponse setIsSafe(Boolean isSafe) { this.isSafe = isSafe; return this; } public List getChoices() { return choices; } public AISearchResponse setChoices(List choices) { this.choices = choices; return this; } public String getCode() { return code; } public AISearchResponse setCode(String code) { this.code = code; return this; } public String getMessage() { return message; } public AISearchResponse setMessage(String message) { this.message = message; return this; } public Usage getUsage() { return usage; } public AISearchResponse setUsage(Usage usage) { this.usage = usage; return this; } public List getReferences() { return references; } public AISearchResponse setReferences(List references) { this.references = references; return this; } public List getFollowupQueries() { return followupQueries; } public AISearchResponse setFollowupQueries(List followupQueries) { this.followupQueries = followupQueries; return this; } // region 内部类 public static class Usage { @SerializedName("completion_tokens") private Integer completionTokens; @SerializedName("prompt_tokens") private Integer promptTokens; @SerializedName("total_tokens") private Integer totalTokens; // getters/setters public Integer getCompletionTokens() { return completionTokens; } public Usage setCompletionTokens(Integer completionTokens) { this.completionTokens = completionTokens; return this; } public Integer getPromptTokens() { return promptTokens; } public Usage setPromptTokens(Integer promptTokens) { this.promptTokens = promptTokens; return this; } public Integer getTotalTokens() { return totalTokens; } public Usage setTotalTokens(Integer totalTokens) { this.totalTokens = totalTokens; return this; } } public static class VideoDetail { private String url; private String height; private String width; private String size; private String duration; @SerializedName("hover_pic") private String hoverPic; // getters/setters public String getUrl() { return url; } public VideoDetail setUrl(String url) { this.url = url; return this; } public String getHeight() { return height; } public VideoDetail setHeight(String height) { this.height = height; return this; } public String getWidth() { return width; } public VideoDetail setWidth(String width) { this.width = width; return this; } public String getSize() { return size; } public VideoDetail setSize(String size) { this.size = size; return this; } public String getDuration() { return duration; } public VideoDetail setDuration(String duration) { this.duration = duration; return this; } @SerializedName("hover_pic") public String getHoverPic() { return hoverPic; } public VideoDetail setHoverPic(String hoverPic) { this.hoverPic = hoverPic; return this; } } public static class ImageDetail { private String url; private String height; private String width; // getters/setters public String getUrl() { return url; } public ImageDetail setUrl(String url) { this.url = url; return this; } public String getHeight() { return height; } public ImageDetail setHeight(String height) { this.height = height; return this; } public String getWidth() { return width; } public ImageDetail setWidth(String width) { this.width = width; return this; } } public static class Reference { private Integer id; private String title; private String url; @SerializedName("web_anchor") private String webAnchor; private String icon; private String content; private String date; private String type; private ImageDetail image; private VideoDetail video; // getters/setters public Integer getId() { return id; } public Reference setId(Integer id) { this.id = id; return this; } public String getTitle() { return title; } public Reference setTitle(String title) { this.title = title; return this; } public String getUrl() { return url; } public Reference setUrl(String url) { this.url = url; return this; } public String getWebAnchor() { return webAnchor; } public Reference setWebAnchor(String webAnchor) { this.webAnchor = webAnchor; return this; } public String getIcon() { return icon; } public Reference setIcon(String icon) { this.icon = icon; return this; } public String getContent() { return content; } public Reference setContent(String content) { this.content = content; return this; } public String getDate() { return date; } public Reference setDate(String date) { this.date = date; return this; } public String getType() { return type; } public Reference setType(String type) { this.type = type; return this; } public ImageDetail getImage() { return image; } public Reference setImage(ImageDetail image) { this.image = image; return this; } public VideoDetail getVideo() { return video; } public Reference setVideo(VideoDetail video) { this.video = video; return this; } } public static class Delta { private String content; private String role; @SerializedName("reasoning_content") private String reasoningContent; // getters/setters public Delta setContent(String content) { this.content = content; return this; } public String getContent() { return content; } public String getRole() { return role; } public Delta setRole(String role) { this.role = role; return this; } public String getReasoningContent() { return reasoningContent; } public Delta setReasoningContent(String reasoningContent) { this.reasoningContent = reasoningContent; return this; } } public static class ChoiceMessage { private String content; private String role; @SerializedName("reasoning_content") private String reasoningContent; public String getContent() { return content; } public ChoiceMessage setContent(String content) { this.content = content; return this; } public String getRole() { return role; } public ChoiceMessage setRole(String role) { this.role = role; return this; } public String getReasoningContent() { return reasoningContent; } public ChoiceMessage setReasoningContent(String reasoningContent) { this.reasoningContent = reasoningContent; return this; } } public static class Choice { private int index; @SerializedName("finish_reason") private String finishReason; private ChoiceMessage message; private Delta delta; public int getIndex() { return index; } public Choice setIndex(int index) { this.index = index; return this; } public String getFinishReason() { return finishReason; } public Choice setFinishReason(String finishReason) { this.finishReason = finishReason; return this; } public ChoiceMessage getMessage() { return message; } public Choice setMessage(ChoiceMessage message) { this.message = message; return this; } public Delta getDelta() { return delta; } public Choice setDelta(Delta delta) { this.delta = delta; return this; } } } ================================================ FILE: java/src/main/java/com/baidubce/appbuilder/model/appbuilderclient/App.java ================================================ package com.baidubce.appbuilder.model.appbuilderclient; public class App { private String id; private String name; private String description; private String appType; private boolean isPublic; private Integer updateTime; // getters public String getId() { return id; } public String getName() { return name; } public String getDescription() { return description; } // setters public void setId(String id) { this.id = id; } public void setName(String name) { this.name = name; } public void setDescription(String description) { this.description = description; } public String getAppType() { return appType; } public void setAppType(String appType) { this.appType = appType; } public boolean isPublic() { return isPublic; } public void setPublic(boolean aPublic) { isPublic = aPublic; } public Integer getUpdateTime() { return updateTime; } public void setUpdateTime(Integer updateTime) { this.updateTime = updateTime; } } ================================================ FILE: java/src/main/java/com/baidubce/appbuilder/model/appbuilderclient/AppBuilderClientFeedbackRequest.java ================================================ package com.baidubce.appbuilder.model.appbuilderclient; import com.google.gson.annotations.SerializedName; public class AppBuilderClientFeedbackRequest { @SerializedName("app_id") private String appId; @SerializedName("conversation_id") private String conversationId; @SerializedName("message_id") private String messageId; private String type; private String[] flag; private String reason; public AppBuilderClientFeedbackRequest(String appId, String conversationId, String messageId, String type, String[] flag, String reason) { this.appId = appId; this.conversationId = conversationId; this.messageId = messageId; this.type = type; this.flag = flag; this.reason = reason; } public String getAppId() { return appId; } public void setAppId(String appId) { this.appId = appId; } public String getConversationId() { return conversationId; } public void setConversationId(String conversationId) { this.conversationId = conversationId; } public String getMessageId() { return messageId; } public void setMessageId(String messageId) { this.messageId = messageId; } public String getType() { return type; } public void setType(String type) { this.type = type; } public String[] getFlag() { return flag; } public void setFlag(String[] flag) { this.flag = flag; } public String getReason() { return reason; } public void setReason(String reason) { this.reason = reason; } } ================================================ FILE: java/src/main/java/com/baidubce/appbuilder/model/appbuilderclient/AppBuilderClientFeedbackResponse.java ================================================ package com.baidubce.appbuilder.model.appbuilderclient; import com.google.gson.annotations.SerializedName; public class AppBuilderClientFeedbackResponse { @SerializedName("request_id") private String requestId; private String code; private String message; public String getRequestId() { return requestId; } public void setRequestId(String requestId) { this.requestId = requestId; } public String getCode() { return code; } public void setCode(String code) { this.code = code; } public String getMessage() { return message; } public void setMessage(String message) { this.message = message; } } ================================================ FILE: java/src/main/java/com/baidubce/appbuilder/model/appbuilderclient/AppBuilderClientIterator.java ================================================ package com.baidubce.appbuilder.model.appbuilderclient; import com.baidubce.appbuilder.base.utils.iterator.StreamIterator; import java.util.stream.IntStream; public class AppBuilderClientIterator { private final StreamIterator iterator; public AppBuilderClientIterator(StreamIterator iterator) { this.iterator = iterator; } public boolean hasNext() { return iterator.hasNext(); } public AppBuilderClientResult next() { AppBuilderClientResponse response = iterator.next(); if(response.getContent() == null) { return new AppBuilderClientResult().setAnswer(response.getAnswer()).setMessageId(response.getMessageId()).setRequestId(response.getRequestId()).setCode(response.getCode()).setMessage(response.getMessage()); } Event[] events = new Event[response.getContent().length]; EventContent[] contents = response.getContent(); IntStream.range(0, contents.length).forEach(i -> { events[i] = new Event().setCode(contents[i].getEventCode()) .setMessage(contents[i].getEnentMessage()) .setStatus(contents[i].getEventStatus()) .setEventType(contents[i].getEventType()) .setContentType(contents[i].getContentType()) .setDetail(contents[i].getOutputs()).setUsage(contents[i].getUsage()) .setToolCalls(contents[i].getToolCalls()); }); return new AppBuilderClientResult().setAnswer(response.getAnswer()).setMessageId(response.getMessageId()).setEvents(events).setRequestId(response.getRequestId()); } public void close() { iterator.close(); } } ================================================ FILE: java/src/main/java/com/baidubce/appbuilder/model/appbuilderclient/AppBuilderClientResponse.java ================================================ package com.baidubce.appbuilder.model.appbuilderclient; import com.google.gson.annotations.SerializedName; import java.util.Arrays; public class AppBuilderClientResponse { @SerializedName("request_id") private String requestId; private String data; private String date; private String answer; @SerializedName("conversation_id") private String conversationId; @SerializedName("message_id") private String messageId; @SerializedName("is_completion") private boolean isCompletion; private EventContent[] content; private String code; private String message; public String getRequestId() { return requestId; } public void setRequestId(String requestId) { this.requestId = requestId; } public String getData() { return data; } public void setData(String data) { this.data = data; } public String getAnswer() { return answer; } public void setAnswer(String answer) { this.answer = answer; } public String getConversationId() { return conversationId; } public void setConversationId(String conversationId) { this.conversationId = conversationId; } public String getMessageId() { return messageId; } public void setMessageId(String messageId) { this.messageId = messageId; } public boolean isCompletion() { return isCompletion; } public void setCompletion(boolean completion) { isCompletion = completion; } public EventContent[] getContent() { return content; } public void setContent(EventContent[] content) { this.content = content; } public String getDate() { return date; } public void setDate(String date) { this.date = date; } public String getCode() { return code; } public void setCode(String code) { this.code = code; } public String getMessage() { return message; } public void setMessage(String message) { this.message = message; } @Override public String toString() { return "AgentBuilderResponse{" + "requestId='" + requestId + '\'' + ", date='" + date + '\'' + ", answer='" + answer + '\'' + ", conversationId='" + conversationId + '\'' + ", messageId='" + messageId + '\'' + ", isCompletion=" + isCompletion + ", content=" + Arrays.toString(content) + '}'; } } ================================================ FILE: java/src/main/java/com/baidubce/appbuilder/model/appbuilderclient/AppBuilderClientResult.java ================================================ package com.baidubce.appbuilder.model.appbuilderclient; import java.util.Arrays; import com.google.gson.annotations.SerializedName; public class AppBuilderClientResult { private String requestId; private String answer; @SerializedName("message_id") private String messageId; private Event[] events; private String code; private String message; public String getAnswer() { return answer; } public AppBuilderClientResult setAnswer(String answer) { this.answer = answer; return this; } public String getRequestId() { return requestId; } public AppBuilderClientResult setRequestId(String requestId) { this.requestId = requestId; return this; } public String getMessageId() { return messageId; } public AppBuilderClientResult setMessageId(String messageId) { this.messageId = messageId; return this; } public Event[] getEvents() { return events; } public AppBuilderClientResult setEvents(Event[] events) { this.events = events; return this; } public String getCode() { return code; } public AppBuilderClientResult setCode(String code) { this.code = code; return this; } public String getMessage() { return message; } public AppBuilderClientResult setMessage(String message) { this.message = message; return this; } @Override public String toString() { return "AppBuilderClientResult{" + "answer='" + answer + '\'' + ", events=" + Arrays.toString(events) + '}'; } } ================================================ FILE: java/src/main/java/com/baidubce/appbuilder/model/appbuilderclient/AppBuilderClientRunRequest.java ================================================ package com.baidubce.appbuilder.model.appbuilderclient; import java.util.List; import java.util.Map; import com.google.gson.Gson; import com.google.gson.annotations.SerializedName; public class AppBuilderClientRunRequest { @SerializedName("app_id") private String appId; private String query; private boolean stream; @SerializedName("conversation_id") private String conversationID; @SerializedName("end_user_id") private String endUserId; private Tool[] tools; @SerializedName("tool_outputs") private ToolOutput[] ToolOutputs; @SerializedName("tool_choice") private ToolChoice ToolChoice; private Action action; @SerializedName("mcp_authorization") private List> mcpAuthorization = null; private Map parameters; @SerializedName("custom_metadata") private CustomMetadata customMetadata; public AppBuilderClientRunRequest() { } public AppBuilderClientRunRequest(String appID) { this.appId = appID; } public AppBuilderClientRunRequest(String appID, String conversationID) { this.appId = appID; this.conversationID = conversationID; } public AppBuilderClientRunRequest(String appID, String conversationID, String query, Boolean stream) { this.appId = appID; this.conversationID = conversationID; this.query = query; this.stream = stream; } public String getAppId() { return appId; } public void setAppId(String appId) { this.appId = appId; } public String getQuery() { return query; } public void setQuery(String query) { this.query = query; } public boolean isStream() { return stream; } public void setStream(boolean stream) { this.stream = stream; } public String getConversationID() { return conversationID; } public void setConversationID(String conversationID) { this.conversationID = conversationID; } public String getEndUserId() { return endUserId; } public void setEndUserId(String endUserId) { this.endUserId = endUserId; } public Tool[] getTools() { return tools; } public void setTools(Tool[] tools) { this.tools = tools; } public void setTools(String toolJson) { Gson gson = new Gson(); Tool tool = gson.fromJson(toolJson, Tool.class); this.tools = new Tool[] { tool }; } public void setTools(String[] toolJsons) { Gson gson = new Gson(); this.tools = new Tool[toolJsons.length]; for (int i = 0; i < toolJsons.length; i++) { Tool tool = gson.fromJson(toolJsons[i], Tool.class); this.tools[i] = tool; } } public ToolOutput[] getToolOutputs() { return ToolOutputs; } public void setToolOutputs(ToolOutput[] toolOutputs) { this.ToolOutputs = toolOutputs; } public void setToolOutputs(String toolCallID, String outputString) { ToolOutput output = new ToolOutput(toolCallID, outputString); this.ToolOutputs = new ToolOutput[] { output }; } public ToolChoice getToolChoice() { return ToolChoice; } public void setToolChoice(ToolChoice toolChoice) { this.ToolChoice = toolChoice; } public Action getAction() { return action; } public void setAction(Action action) { this.action = action; } public AppBuilderClientRunRequest setMcpAuthorization(List> mcpAuthorization) { this.mcpAuthorization = mcpAuthorization; return this; } public List> getMcpAuthorization() { return mcpAuthorization; } public Map getParameters() { return parameters; } public void setParameters(Map parameters) { this.parameters = parameters; } public void setCustomMetadata(CustomMetadata customMetadata) { this.customMetadata = customMetadata; } public static class Tool { private String type; private Function function; public Tool(String type, Function function) { this.type = type; this.function = function; } public String getType() { return type; } public Function getFunction() { return function; } public static class Function { private String name; private String description; private Map parameters; public Function(String name, String description, Map parameters) { this.name = name; this.description = description; this.parameters = parameters; } public String getName() { return name; } public String getDescription() { return description; } public Map getParameters() { return parameters; } } } public static class ToolOutput { @SerializedName("tool_call_id") private String toolCallID; private String output; public ToolOutput(String toolCallID, String output) { this.toolCallID = toolCallID; this.output = output; } public String getToolCallID() { return toolCallID; } public String getOutput() { return output; } } public static class ToolChoice { private String type; private Function function; public ToolChoice(String type, Function function) { this.type = type; this.function = function; } public String getType() { return type; } public Function getFunction() { return function; } public static class Function { private String name; private Map input; public Function(String name, Map input) { this.name = name; this.input = input; } public String getName() { return name; } public Map getInput() { return input; } } } public static class Action { @SerializedName("action_type") private String actionType; private Parameters parameters; // 回复消息节点构造方法 public static Action createAction(String interruptId) { return createAction("resume", interruptId, "chat"); } public static Action createAction(String actionType, String id, String type) { Parameters.InterruptEvent interruptEvent = new Parameters.InterruptEvent(id, type); Parameters parameters = new Parameters(interruptEvent); return new Action(actionType, parameters); } public Action(String actionType, Parameters parameters) { this.actionType = actionType; this.parameters = parameters; } public String getActionType() { return actionType; } public Parameters getParameters() { return parameters; } public static class Parameters { @SerializedName("interrupt_event") private InterruptEvent interruptEvent; public Parameters(InterruptEvent interruptEvent) { this.interruptEvent = interruptEvent; } public InterruptEvent getInterruptEvent() { return interruptEvent; } public static class InterruptEvent { private String id; private String type; public InterruptEvent(String id, String type) { this.id = id; this.type = type; } public String getId() { return id; } public String getType() { return type; } } } } public static class CustomMetadata{ @SerializedName("override_role_instruction") private String overrideRoleInstruction; public CustomMetadata(String overrideRoleInstruction) { this.overrideRoleInstruction = overrideRoleInstruction; } public void setOverrideRoleInstruction(String overrideRoleInstruction) { this.overrideRoleInstruction = overrideRoleInstruction; } public String getOverrideRoleInstruction() { return overrideRoleInstruction; } } } ================================================ FILE: java/src/main/java/com/baidubce/appbuilder/model/appbuilderclient/AppDescribeRequest.java ================================================ package com.baidubce.appbuilder.model.appbuilderclient; public class AppDescribeRequest { private String id; public String getId() { return id; } public void setId(String id) { this.id = id; } } ================================================ FILE: java/src/main/java/com/baidubce/appbuilder/model/appbuilderclient/AppDescribeResponse.java ================================================ package com.baidubce.appbuilder.model.appbuilderclient; public class AppDescribeResponse { private String requestId; private String id; private String name; private String description; private String instruction; private String prologue; private String[] exampleQueries; private FollowUpQueries followUpQueries; private Component[] components; private KnowledgeBaseConfig knowledgeBaseConfig; private ModelConfig modelConfig; private BackgroundConfig background; // Getters and Setters public String getRequestId() { return requestId; } public void setRequestId(String requestId) { this.requestId = requestId; } public String getId() { return id; } public void setId(String id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public String getInstruction() { return instruction; } public void setInstruction(String instruction) { this.instruction = instruction; } public String getPrologue() { return prologue; } public void setPrologue(String prologue) { this.prologue = prologue; } public String[] getExampleQueries() { return exampleQueries; } public void setExampleQueries(String[] exampleQueries) { this.exampleQueries = exampleQueries; } public FollowUpQueries getFollowUpQueries() { return followUpQueries; } public void setFollowUpQueries(FollowUpQueries followUpQueries) { this.followUpQueries = followUpQueries; } public Component[] getComponents() { return components; } public void setComponents(Component[] components) { this.components = components; } public KnowledgeBaseConfig getKnowledgeBaseConfig() { return knowledgeBaseConfig; } public void setKnowledgeBaseConfig(KnowledgeBaseConfig knowledgeBaseConfig) { this.knowledgeBaseConfig = knowledgeBaseConfig; } public ModelConfig getModelConfig() { return modelConfig; } public void setModelConfig(ModelConfig modelConfig) { this.modelConfig = modelConfig; } public BackgroundConfig getBackground() { return background; } public void setBackground(BackgroundConfig background) { this.background = background; } public static class FollowUpQueries { private String type; private String prompt; private String round; // Getters and Setters public String getType() { return type; } public void setType(String type) { this.type = type; } public String getPrompt() { return prompt; } public void setPrompt(String prompt) { this.prompt = prompt; } public String getRound() { return round; } public void setRound(String round) { this.round = round; } } public static class Component { private String name; private String description; private String customDesc; // Getters and Setters public String getName() { return name; } public void setName(String name) { this.name = name; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public String getCustomDesc() { return customDesc; } public void setCustomDesc(String customDesc) { this.customDesc = customDesc; } } public static class KnowledgeBaseConfig { private KnowledgeBase[] knowledgeBases; private RetrievalConfig retrieval; // Getters and Setters public KnowledgeBase[] getKnowledgeBases() { return knowledgeBases; } public void setKnowledgeBases(KnowledgeBase[] knowledgeBases) { this.knowledgeBases = knowledgeBases; } public RetrievalConfig getRetrieval() { return retrieval; } public void setRetrieval(RetrievalConfig retrieval) { this.retrieval = retrieval; } public static class KnowledgeBase { private String id; private String name; private String description; // Getters and Setters public String getId() { return id; } public void setId(String id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } } public static class RetrievalConfig { private Boolean enableWebSearch; private String order; private String strategy; private Integer topK; private Float threshold; // Getters and Setters public Boolean getEnableWebSearch() { return enableWebSearch; } public void setEnableWebSearch(Boolean enableWebSearch) { this.enableWebSearch = enableWebSearch; } public String getOrder() { return order; } public void setOrder(String order) { this.order = order; } public String getStrategy() { return strategy; } public void setStrategy(String strategy) { this.strategy = strategy; } public Integer getTopK() { return topK; } public void setTopK(Integer topK) { this.topK = topK; } public Float getThreshold() { return threshold; } public void setThreshold(Float threshold) { this.threshold = threshold; } } } public static class ModelConfig { private PlanConfig plan; private ChatConfig chat; // Getters and Setters public PlanConfig getPlan() { return plan; } public void setPlan(PlanConfig plan) { this.plan = plan; } public ChatConfig getChat() { return chat; } public void setChat(ChatConfig chat) { this.chat = chat; } public static class PlanConfig { private String modelId; private String model; private Integer maxRounds; private Config config; // Getters and Setters public String getModelId() { return modelId; } public void setModelId(String modelId) { this.modelId = modelId; } public String getModel() { return model; } public void setModel(String model) { this.model = model; } public Integer getMaxRounds() { return maxRounds; } public void setMaxRounds(Integer maxRounds) { this.maxRounds = maxRounds; } public Config getConfig() { return config; } public void setConfig(Config config) { this.config = config; } public static class Config { private Float temperature; private Float topP; // Getters and Setters public Float getTemperature() { return temperature; } public void setTemperature(Float temperature) { this.temperature = temperature; } public Float getTopP() { return topP; } public void setTopP(Float topP) { this.topP = topP; } } } public static class ChatConfig { private String modelId; private String model; private Integer historyChatRounds; private Config config; // Getters and Setters... public String getModelId() { return modelId; } public void setModelId(String modelId) { this.modelId = modelId; } public String getModel() { return model; } public void setModel(String model) { this.model = model; } public Integer getHistoryChatRounds() { return historyChatRounds; } public void setHistoryChatRounds(Integer historyChatRounds) { this.historyChatRounds = historyChatRounds; } public Config getConfig() { return config; } public void setConfig(Config config) { this.config = config; } public static class Config { private Float temperature; private Float topP; // Getters and Setters public Float getTemperature() { return temperature; } public void setTemperature(Float temperature) { this.temperature = temperature; } public Float getTopP() { return topP; } public void setTopP(Float topP) { this.topP = topP; } } } } public static class BackgroundConfig { private String id; private String path; private MobileConfig mobileConfig; private PcConfig pcConfig; // Getters and Setters public String getId() { return id; } public void setId(String id) { this.id = id; } public String getPath() { return path; } public void setPath(String path) { this.path = path; } public MobileConfig getMobileConfig() { return mobileConfig; } public void setMobileConfig(MobileConfig mobileConfig) { this.mobileConfig = mobileConfig; } public PcConfig getPcConfig() { return pcConfig; } public void setPcConfig(PcConfig pcConfig) { this.pcConfig = pcConfig; } public static class MobileConfig { private String left; private String top; private String height; private String color; // Getters and Setters... public String getLeft() { return left; } public void setLeft(String left) { this.left = left; } public String getTop() { return top; } public void setTop(String top) { this.top = top; } public String getHeight() { return height; } public void setHeight(String height) { this.height = height; } public String getColor() { return color; } public void setColor(String color) { this.color = color; } } public static class PcConfig { private String left; private String top; private String height; private String color; // Getters and Setters... public String getLeft() { return left; } public void setLeft(String left) { this.left = left; } public String getTop() { return top; } public void setTop(String top) { this.top = top; } public String getHeight() { return height; } public void setHeight(String height) { this.height = height; } public String getColor() { return color; } public void setColor(String color) { this.color = color; } } } } ================================================ FILE: java/src/main/java/com/baidubce/appbuilder/model/appbuilderclient/AppListRequest.java ================================================ package com.baidubce.appbuilder.model.appbuilderclient; import java.util.HashMap; import java.util.Map; public class AppListRequest { private int limit; private String after; private String before; // getters and setters public int getLimit() { return limit; } public void setLimit(int limit) { this.limit = limit; } public String getAfter() { return after; } public void setAfter(String after) { this.after = after; } public String getBefore() { return before; } public void setBefore(String before) { this.before = before; } public Map toMap() { Map map = new HashMap<>(); if (limit != 0) { map.put("limit", limit); } map.put("after", after); map.put("before", before); return map; } } ================================================ FILE: java/src/main/java/com/baidubce/appbuilder/model/appbuilderclient/AppListResponse.java ================================================ package com.baidubce.appbuilder.model.appbuilderclient; import com.google.gson.annotations.SerializedName; public class AppListResponse { @SerializedName("request_id") private String requestId; private App[] data; private String code; private String message; public String getRequestId() { return requestId; } public void setRequestId(String requestId) { this.requestId = requestId; } public App[] getData() { return data; } public void setData(App[] data) { this.data = data; } public String getCode() { return code; } public void setCode(String code) { this.code = code; } public String getMessage() { return message; } public void setMessage(String message) { this.message = message; } } ================================================ FILE: java/src/main/java/com/baidubce/appbuilder/model/appbuilderclient/AppsDescribeRequest.java ================================================ package com.baidubce.appbuilder.model.appbuilderclient; public class AppsDescribeRequest { private String marker; private Integer maxKeys; public AppsDescribeRequest(String marker, Integer maxKeys) { this.marker = marker; this.maxKeys = maxKeys; } public AppsDescribeRequest() { this.maxKeys = 10; } public AppsDescribeRequest(Integer maxKeys) { this.maxKeys = maxKeys; } public AppsDescribeRequest(String marker) { this.marker = marker; } public String getMarker() { return marker; } public Integer getMaxKeys() { return maxKeys; } } ================================================ FILE: java/src/main/java/com/baidubce/appbuilder/model/appbuilderclient/AppsDescribeResponse.java ================================================ package com.baidubce.appbuilder.model.appbuilderclient; public class AppsDescribeResponse { private String requestId; private String marker; private Boolean isTruncated; private String nextMarker; private Integer maxKeys; private App[] data; public String getRequestId() { return requestId; } public void setRequestId(String requestId) { this.requestId = requestId; } public String getMarker() { return marker; } public void setMarker(String marker) { this.marker = marker; } public Boolean getIsTruncated() { return isTruncated; } public void setIsTruncated(Boolean isTruncated) { this.isTruncated = isTruncated; } public String getNextMarker() { return nextMarker; } public void setNextMarker(String nextMarker) { this.nextMarker = nextMarker; } public Integer getMaxKeys() { return maxKeys; } public void setMaxKeys(Integer maxKeys) { this.maxKeys = maxKeys; } public App[] getData() { return data; } public void setData(App[] data) { this.data = data; } } ================================================ FILE: java/src/main/java/com/baidubce/appbuilder/model/appbuilderclient/ConversationResponse.java ================================================ package com.baidubce.appbuilder.model.appbuilderclient; import com.google.gson.annotations.SerializedName; public class ConversationResponse { private String requestId; @SerializedName("conversation_id") private String conversationId; public String getRequestId() { return requestId; } public void setRequestId(String requestId) { this.requestId = requestId; } public String getConversationId() { return conversationId; } public void setConversationId(String conversationId) { this.conversationId = conversationId; } @Override public String toString() { return "ConversationResponse{" + "requestId='" + requestId + '\'' + ", conversationId='" + conversationId + '\'' + '}'; } } ================================================ FILE: java/src/main/java/com/baidubce/appbuilder/model/appbuilderclient/Event.java ================================================ package com.baidubce.appbuilder.model.appbuilderclient; import java.util.Map; import com.google.gson.annotations.SerializedName; public class Event { public static final String ChatflowEventType = "chatflow"; public static final String FollowUpQueryEventType = "FollowUpQuery"; private String code; private String message; private String eventType; private String status; private String contentType; private Map detail; private Map usage; @SerializedName("tool_calls") private ToolCall[] toolCalls; public String getCode() { return code; } public Event setCode(String code) { this.code = code; return this; } public String getMessage() { return message; } public Event setMessage(String message) { this.message = message; return this; } public String getEventType() { return eventType; } public Event setEventType(String eventType) { this.eventType = eventType; return this; } public String getStatus() { return status; } public Event setStatus(String status) { this.status = status; return this; } public String getContentType() { return contentType; } public Event setContentType(String contentType) { this.contentType = contentType; return this; } public Map getDetail() { return detail; } public Event setDetail(Map detail) { this.detail = detail; return this; } public Map getUsage() { return usage; } public Event setUsage(Map usage) { this.usage = usage; return this; } public ToolCall[] getToolCalls() { return toolCalls; } public Event setToolCalls(ToolCall[] toolCalls) { this.toolCalls = toolCalls; return this; } @Override public String toString() { return "Event{" + "code='" + code + '\'' + ", message='" + message + '\'' + ", eventType='" + eventType + '\'' + ", status='" + status + '\'' + ", contentType='" + contentType + '\'' + ", detail=" + detail + '\'' + ", usage=" + usage + '\'' + ", toolCalls=" + toolCalls + '}'; } } ================================================ FILE: java/src/main/java/com/baidubce/appbuilder/model/appbuilderclient/EventContent.java ================================================ package com.baidubce.appbuilder.model.appbuilderclient; import com.google.gson.annotations.SerializedName; import java.util.Map; public class EventContent { public static final String CodeContentType = "code"; public static final String TextContentType = "text"; public static final String ImageContentType = "image"; public static final String RAGContentType = "rag"; public static final String FunctionCallContentType = "function_call"; public static final String AudioContentType = "audio"; public static final String VideoContentType = "video"; public static final String StatusContentType = "status"; public static final String ChatflowInterruptContentType = "chatflow_interrupt"; public static final String PublishMessageContentType = "publish_message"; public static final String MultipleDialogEventContentType = "multiple_dialog_event"; public static final String JsonContentType = "json"; @SerializedName("event_code") private String eventCode; @SerializedName("event_message") private String enentMessage; @SerializedName("event_type") private String eventType; @SerializedName("event_id") private String eventId; @SerializedName("event_status") private String eventStatus; @SerializedName("content_type") private String contentType; private Map outputs; private Map usage; @SerializedName("tool_calls") private ToolCall[] toolCalls; public String getEventCode() { return eventCode; } public void setEventCode(String eventCode) { this.eventCode = eventCode; } public String getEnentMessage() { return enentMessage; } public void setEnentMessage(String enentMessage) { this.enentMessage = enentMessage; } public String getEventType() { return eventType; } public void setEventType(String eventType) { this.eventType = eventType; } public String getEventId() { return eventId; } public void setEventId(String eventId) { this.eventId = eventId; } public String getEventStatus() { return eventStatus; } public void setEventStatus(String eventStatus) { this.eventStatus = eventStatus; } public String getContentType() { return contentType; } public void setContentType(String contentType) { this.contentType = contentType; } public Map getOutputs() { return outputs; } public void setOutputs(Map outputs) { this.outputs = outputs; } public Map getUsage() { return usage; } public void setUsage(Map usage) { this.usage = usage; } public ToolCall[] getToolCalls() { return toolCalls; } public void setToolCalls(ToolCall[] toolCalls) { this.toolCalls = toolCalls; } @Override public String toString() { return "EventContent{" + "eventCode='" + eventCode + '\'' + ", eventMessage='" + enentMessage + '\'' + ", eventType='" + eventType + '\'' + ", eventId='" + eventId + '\'' + ", eventStatus='" + eventStatus + '\'' + ", contentType='" + contentType + '\'' + ", outputs=" + outputs + '\'' + "usage=" + usage + '\'' + ", toolCalls=" + toolCalls + '}'; } } ================================================ FILE: java/src/main/java/com/baidubce/appbuilder/model/appbuilderclient/FileUploadResponse.java ================================================ package com.baidubce.appbuilder.model.appbuilderclient; import com.google.gson.annotations.SerializedName; public class FileUploadResponse { private String requestId; @SerializedName("id") private String fileId; @SerializedName("conversation_id") private String conversationId; public String getRequestId() { return requestId; } public void setRequestId(String requestId) { this.requestId = requestId; } public String getFileId() { return fileId; } @Override public String toString() { return "FileUploadResponse{" + "requestId='" + requestId + '\'' + ", fileId='" + fileId + '\'' + ", conversationId='" + conversationId + '\'' + '}'; } public void setFileId(String fileId) { this.fileId = fileId; } public String getConversationId() { return conversationId; } public void setConversationId(String conversationId) { this.conversationId = conversationId; } } ================================================ FILE: java/src/main/java/com/baidubce/appbuilder/model/appbuilderclient/ToolCall.java ================================================ package com.baidubce.appbuilder.model.appbuilderclient; public class ToolCall { private String id; private String type; public String getId() { return id; } public void setId(String id) { this.id = id; } public String getType() { return type; } public void setType(String type) { this.type = type; } } ================================================ FILE: java/src/main/java/com/baidubce/appbuilder/model/componentclient/ComponentClientIterator.java ================================================ package com.baidubce.appbuilder.model.componentclient; import com.baidubce.appbuilder.base.utils.iterator.StreamIterator; public class ComponentClientIterator { private final StreamIterator iterator; public ComponentClientIterator(StreamIterator iterator) { this.iterator = iterator; } public boolean hasNext() { return iterator.hasNext(); } public ComponentClientRunResponse next() { return iterator.next(); } public void close(){ iterator.close(); } } ================================================ FILE: java/src/main/java/com/baidubce/appbuilder/model/componentclient/ComponentClientRunRequest.java ================================================ package com.baidubce.appbuilder.model.componentclient; import java.util.HashMap; import java.util.Map; public class ComponentClientRunRequest { public static final String SysOriginQuery = "_sys_origin_query"; public static final String SysFileUrls = "_sys_file_urls"; public static final String SysConversationID = "_sys_conversation_id"; public static final String SysEndUserID = "_sys_end_user_id"; public static final String SysChatHistory = "_sys_chat_history"; private boolean stream; private Map parameters = new HashMap<>(); public boolean isStream() { return stream; } public void setStream(boolean stream) { this.stream = stream; } public Map getParameters() { return parameters; } public void setParameters(Map parameters) { this.parameters = parameters; } } ================================================ FILE: java/src/main/java/com/baidubce/appbuilder/model/componentclient/ComponentClientRunResponse.java ================================================ package com.baidubce.appbuilder.model.componentclient; import java.util.Map; import com.google.gson.annotations.SerializedName; import java.util.HashMap; public class ComponentClientRunResponse { @SerializedName("request_id") private String requestID; private String code; private String message; @SerializedName("conversation_id") private String conversationID; @SerializedName("message_id") private String messageID; @SerializedName("trace_id") private String traceID; @SerializedName("user_id") private String userID; @SerializedName("end_user_id") private String endUserID; private String status; // 新增的字段 private String role; private Content[] content; // Getters and Setters public String getRequestID() { return requestID; } public void setRequestID(String requestID) { this.requestID = requestID; } public String getCode() { return code; } public void setCode(String code) { this.code = code; } public String getMessage() { return message; } public void setMessage(String message) { this.message = message; } public String getConversationID() { return conversationID; } public void setConversationID(String conversationID) { this.conversationID = conversationID; } public String getMessageID() { return messageID; } public void setMessageID(String messageID) { this.messageID = messageID; } public String getTraceID() { return traceID; } public void setTraceID(String traceID) { this.traceID = traceID; } public String getUserID() { return userID; } public void setUserID(String userID) { this.userID = userID; } public String getEndUserID() { return endUserID; } public void setEndUserID(String endUserID) { this.endUserID = endUserID; } public String getStatus() { return status; } public void setStatus(String status) { this.status = status; } public String getRole() { return role; } public void setRole(String role) { this.role = role; } public Content[] getContent() { return content; } public void setContent(Content[] content) { this.content = content; } public static class Content { private String name; @SerializedName("visible_scope") private String visibleScope; @SerializedName("raw_data") private Map rawData = new HashMap<>(); private Map usage = new HashMap<>(); private Map metrics = new HashMap<>(); private String type; private Map text = new HashMap<>(); private ComponentEvent event; // Getters and Setters public String getName() { return name; } public void setName(String name) { this.name = name; } public String getVisibleScope() { return visibleScope; } public void setVisibleScope(String visibleScope) { this.visibleScope = visibleScope; } public Map getRawData() { return rawData; } public void setRawData(Map rawData) { this.rawData = rawData; } public Map getUsage() { return usage; } public void setUsage(Map usage) { this.usage = usage; } public Map getMetrics() { return metrics; } public void setMetrics(Map metrics) { this.metrics = metrics; } public String getType() { return type; } public void setType(String type) { this.type = type; } public Map getText() { return text; } public void setText(Map text) { this.text = text; } public ComponentEvent getEvent() { return event; } public void setEvent(ComponentEvent event) { this.event = event; } public static class ComponentEvent { private String id; private String status; private String name; @SerializedName("created_time") private String createdTime; @SerializedName("error_code") private String errorCode; @SerializedName("error_message") private String errorMessage; // Getters and Setters public String getId() { return id; } public void setId(String id) { this.id = id; } public String getStatus() { return status; } public void setStatus(String status) { this.status = status; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getCreatedTime() { return createdTime; } public void setCreatedTime(String createdTime) { this.createdTime = createdTime; } public String getErrorCode() { return errorCode; } public void setErrorCode(String errorCode) { this.errorCode = errorCode; } public String getErrorMessage() { return errorMessage; } public void setErrorMessage(String errorMessage) { this.errorMessage = errorMessage; } } } } ================================================ FILE: java/src/main/java/com/baidubce/appbuilder/model/dataset/DatasetCreateResponse.java ================================================ package com.baidubce.appbuilder.model.dataset; public class DatasetCreateResponse { private int code; private String message; private DatasetCreateResult result; public int getCode() { return code; } public void setCode(int code) { this.code = code; } public String getMessage() { return message; } public void setMessage(String message) { this.message = message; } public DatasetCreateResult getResult() { return result; } public void setResult(DatasetCreateResult result) { this.result = result; } @Override public String toString() { return "DatasetCreateResponse{" + "code=" + code + ", message='" + message + '\'' + ", result=" + result + '}'; } } ================================================ FILE: java/src/main/java/com/baidubce/appbuilder/model/dataset/DatasetCreateResult.java ================================================ package com.baidubce.appbuilder.model.dataset; import com.google.gson.annotations.SerializedName; public class DatasetCreateResult { private String id; private String name; private String description; @SerializedName("indexing_technique") private String indexingTechnique; @SerializedName("document_count") private int documentCount; @SerializedName("word_count") private int wordCount; @SerializedName("created_by") private String createdBy; @SerializedName("created_at") private long createdAt; @SerializedName("updated_by") private String updatedBy; @SerializedName("updated_at") private long updatedAt; @SerializedName("is_priority") private boolean isPriority; public String getId() { return id; } public void setId(String id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public String getIndexingTechnique() { return indexingTechnique; } public void setIndexingTechnique(String indexingTechnique) { this.indexingTechnique = indexingTechnique; } public int getDocumentCount() { return documentCount; } public void setDocumentCount(int documentCount) { this.documentCount = documentCount; } public int getWordCount() { return wordCount; } public void setWordCount(int wordCount) { this.wordCount = wordCount; } public String getCreatedBy() { return createdBy; } public void setCreatedBy(String createdBy) { this.createdBy = createdBy; } public long getCreatedAt() { return createdAt; } public void setCreatedAt(long createdAt) { this.createdAt = createdAt; } public String getUpdatedBy() { return updatedBy; } public void setUpdatedBy(String updatedBy) { this.updatedBy = updatedBy; } public long getUpdatedAt() { return updatedAt; } public void setUpdatedAt(long updatedAt) { this.updatedAt = updatedAt; } public boolean isPriority() { return isPriority; } public void setPriority(boolean priority) { isPriority = priority; } @Override public String toString() { return "DatasetCreateResult{" + "id='" + id + '\'' + ", name='" + name + '\'' + ", description='" + description + '\'' + ", indexingTechnique='" + indexingTechnique + '\'' + ", documentCount=" + documentCount + ", wordCount=" + wordCount + ", createdBy='" + createdBy + '\'' + ", createdAt=" + createdAt + ", updatedBy='" + updatedBy + '\'' + ", updatedAt=" + updatedAt + ", isPriority=" + isPriority + '}'; } } ================================================ FILE: java/src/main/java/com/baidubce/appbuilder/model/dataset/DocumentAddResponse.java ================================================ package com.baidubce.appbuilder.model.dataset; public class DocumentAddResponse { private int code; private String message; private DocumentAddResult result; public int getCode() { return code; } public void setCode(int code) { this.code = code; } public String getMessage() { return message; } public void setMessage(String message) { this.message = message; } public DocumentAddResult getResult() { return result; } public void setResult(DocumentAddResult result) { this.result = result; } @Override public String toString() { return "DocumentAddResponse{" + "code=" + code + ", message='" + message + '\'' + ", result=" + result + '}'; } } ================================================ FILE: java/src/main/java/com/baidubce/appbuilder/model/dataset/DocumentAddResult.java ================================================ package com.baidubce.appbuilder.model.dataset; import com.google.gson.annotations.SerializedName; import java.util.Arrays; public class DocumentAddResult { @SerializedName("dataset_id") private String datasetId; @SerializedName("document_ids") private String[] documentIds; public String getDatasetId() { return datasetId; } public void setDatasetId(String datasetId) { this.datasetId = datasetId; } public String[] getDocumentIds() { return documentIds; } public void setDocumentIds(String[] documentIds) { this.documentIds = documentIds; } @Override public String toString() { return "DocumentAddResult{" + "datasetId='" + datasetId + '\'' + ", documentIds=" + Arrays.toString(documentIds) + '}'; } } ================================================ FILE: java/src/main/java/com/baidubce/appbuilder/model/dataset/DocumentDeleteResponse.java ================================================ package com.baidubce.appbuilder.model.dataset; public class DocumentDeleteResponse { private int code; private String message; private Object result; public int getCode() { return code; } public void setCode(int code) { this.code = code; } public String getMessage() { return message; } public void setMessage(String message) { this.message = message; } public Object getResult() { return result; } public void setResult(Object result) { this.result = result; } @Override public String toString() { return "DocumentDeleteResponse{" + "code=" + code + ", message='" + message + '\'' + ", result=" + result + '}'; } } ================================================ FILE: java/src/main/java/com/baidubce/appbuilder/model/dataset/DocumentListData.java ================================================ package com.baidubce.appbuilder.model.dataset; import com.google.gson.annotations.SerializedName; import java.util.Map; public class DocumentListData { private String id; private String name; @SerializedName("dataset_process_rule_id") private String datasetProcessRuleId; @SerializedName("data_source_type") private String dataSourceType; private int position; @SerializedName("data_source_info") private Map dataSourceInfo; @SerializedName("created_from") private String createdFrom; @SerializedName("created_by") private String createdBy; @SerializedName("created_at") private long createdAt; @SerializedName("indexing_status") private String indexingStatus; private Object error; private boolean enabled; @SerializedName("display_status") private String displayStatus; @SerializedName("word_count") private int wordCount; @SerializedName("estimated_waiting_minutes") private int estimatedWaitingMinutes; @SerializedName("disabled_at") private Object disabledAt; @SerializedName("disabled_by") private Object disabledBy; public String getId() { return id; } public void setId(String id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getDatasetProcessRuleId() { return datasetProcessRuleId; } public void setDatasetProcessRuleId(String datasetProcessRuleId) { this.datasetProcessRuleId = datasetProcessRuleId; } public String getDataSourceType() { return dataSourceType; } public void setDataSourceType(String dataSourceType) { this.dataSourceType = dataSourceType; } public int getPosition() { return position; } public void setPosition(int position) { this.position = position; } public Map getDataSourceInfo() { return dataSourceInfo; } public void setDataSourceInfo(Map dataSourceInfo) { this.dataSourceInfo = dataSourceInfo; } public String getCreatedFrom() { return createdFrom; } public void setCreatedFrom(String createdFrom) { this.createdFrom = createdFrom; } public String getCreatedBy() { return createdBy; } public void setCreatedBy(String createdBy) { this.createdBy = createdBy; } public long getCreatedAt() { return createdAt; } public void setCreatedAt(long createdAt) { this.createdAt = createdAt; } public String getIndexingStatus() { return indexingStatus; } public void setIndexingStatus(String indexingStatus) { this.indexingStatus = indexingStatus; } public Object getError() { return error; } public void setError(Object error) { this.error = error; } public boolean isEnabled() { return enabled; } public void setEnabled(boolean enabled) { this.enabled = enabled; } public String getDisplayStatus() { return displayStatus; } public void setDisplayStatus(String displayStatus) { this.displayStatus = displayStatus; } public int getWordCount() { return wordCount; } public void setWordCount(int wordCount) { this.wordCount = wordCount; } public int getEstimatedWaitingMinutes() { return estimatedWaitingMinutes; } public void setEstimatedWaitingMinutes(int estimatedWaitingMinutes) { this.estimatedWaitingMinutes = estimatedWaitingMinutes; } public Object getDisabledAt() { return disabledAt; } public void setDisabledAt(Object disabledAt) { this.disabledAt = disabledAt; } public Object getDisabledBy() { return disabledBy; } public void setDisabledBy(Object disabledBy) { this.disabledBy = disabledBy; } @Override public String toString() { return "DocumentListData{" + "id='" + id + '\'' + ", name='" + name + '\'' + ", datasetProcessRuleId='" + datasetProcessRuleId + '\'' + ", dataSourceType='" + dataSourceType + '\'' + ", position=" + position + ", dataSourceInfo=" + dataSourceInfo + ", createdFrom='" + createdFrom + '\'' + ", createdBy='" + createdBy + '\'' + ", createdAt=" + createdAt + ", indexingStatus='" + indexingStatus + '\'' + ", error=" + error + ", enabled=" + enabled + ", displayStatus='" + displayStatus + '\'' + ", wordCount=" + wordCount + ", estimatedWaitingMinutes=" + estimatedWaitingMinutes + ", disabledAt=" + disabledAt + ", disabledBy=" + disabledBy + '}'; } } ================================================ FILE: java/src/main/java/com/baidubce/appbuilder/model/dataset/DocumentListResponse.java ================================================ package com.baidubce.appbuilder.model.dataset; public class DocumentListResponse { private int code; private String message; private DocumentListResult result; public int getCode() { return code; } public void setCode(int code) { this.code = code; } public String getMessage() { return message; } public void setMessage(String message) { this.message = message; } public DocumentListResult getResult() { return result; } public void setResult(DocumentListResult result) { this.result = result; } @Override public String toString() { return "DocumentListResponse{" + "code=" + code + ", message='" + message + '\'' + ", result=" + result + '}'; } } ================================================ FILE: java/src/main/java/com/baidubce/appbuilder/model/dataset/DocumentListResult.java ================================================ package com.baidubce.appbuilder.model.dataset; import com.google.gson.annotations.SerializedName; import java.util.Arrays; public class DocumentListResult { @SerializedName("has_more") private boolean hasMore; private int limit; private int page; private int total; private DocumentListData[] data; public boolean isHasMore() { return hasMore; } public void setHasMore(boolean hasMore) { this.hasMore = hasMore; } public int getLimit() { return limit; } public void setLimit(int limit) { this.limit = limit; } public int getPage() { return page; } public void setPage(int page) { this.page = page; } public int getTotal() { return total; } public void setTotal(int total) { this.total = total; } public DocumentListData[] getData() { return data; } public void setData(DocumentListData[] data) { this.data = data; } @Override public String toString() { return "DocumentListResult{" + "hasMore=" + hasMore + ", limit=" + limit + ", page=" + page + ", total=" + total + ", data=" + Arrays.toString(data) + '}'; } } ================================================ FILE: java/src/main/java/com/baidubce/appbuilder/model/dataset/FileUploadResponse.java ================================================ package com.baidubce.appbuilder.model.dataset; public class FileUploadResponse { private int code; private String message; private FileUploadResult result; public int getCode() { return code; } public void setCode(int code) { this.code = code; } public String getMessage() { return message; } public void setMessage(String message) { this.message = message; } public FileUploadResult getResult() { return result; } public void setResult(FileUploadResult result) { this.result = result; } @Override public String toString() { return "FileUploadResponse{" + "code=" + code + ", message='" + message + '\'' + ", result=" + result + '}'; } } ================================================ FILE: java/src/main/java/com/baidubce/appbuilder/model/dataset/FileUploadResult.java ================================================ package com.baidubce.appbuilder.model.dataset; import com.google.gson.annotations.SerializedName; public class FileUploadResult { private String id; private String name; private int size; private String extension; @SerializedName("mime_type") private String mimeType; @SerializedName("created_by") private String createdBy; @SerializedName("created_at") protected long createdAt; public String getId() { return id; } public void setId(String id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getSize() { return size; } public void setSize(int size) { this.size = size; } public String getExtension() { return extension; } public void setExtension(String extension) { this.extension = extension; } public String getMimeType() { return mimeType; } public void setMimeType(String mimeType) { this.mimeType = mimeType; } public String getCreatedBy() { return createdBy; } public void setCreatedBy(String createdBy) { this.createdBy = createdBy; } public long getCreatedAt() { return createdAt; } public void setCreatedAt(long createdAt) { this.createdAt = createdAt; } @Override public String toString() { return "FileUploadResult{" + "id='" + id + '\'' + ", name='" + name + '\'' + ", size=" + size + ", extension='" + extension + '\'' + ", mimeType='" + mimeType + '\'' + ", createdBy='" + createdBy + '\'' + ", createdAt=" + createdAt + '}'; } } ================================================ FILE: java/src/main/java/com/baidubce/appbuilder/model/knowledgebase/ChunkCreateRequest.java ================================================ package com.baidubce.appbuilder.model.knowledgebase; public class ChunkCreateRequest { private String knowledgeBaseId; private String documentId; private String content; public ChunkCreateRequest(String documetId, String content) { this.documentId = documetId; this.content = content; } public ChunkCreateRequest(String knowledgeBaseId, String documetId, String content) { this.knowledgeBaseId = knowledgeBaseId; this.documentId = documetId; this.content = content; } public String getKnowledgeBaseId() { return knowledgeBaseId; } public void setKnowledgeBaseId(String knowledgeBaseId) { this.knowledgeBaseId = knowledgeBaseId; } public String getDocumentId() { return documentId; } public void setDocumentId(String documentId) { this.documentId = documentId; } public String getContent() { return content; } public void setContent(String content) { this.content = content; } } ================================================ FILE: java/src/main/java/com/baidubce/appbuilder/model/knowledgebase/ChunkCreateResponse.java ================================================ package com.baidubce.appbuilder.model.knowledgebase; import com.google.gson.annotations.SerializedName; public class ChunkCreateResponse { @SerializedName("id") private String chunkId; public void setChunkId(String chunkId) { this.chunkId = chunkId; } public String getChunkId() { return chunkId; } } ================================================ FILE: java/src/main/java/com/baidubce/appbuilder/model/knowledgebase/ChunkDeleteRequest.java ================================================ package com.baidubce.appbuilder.model.knowledgebase; public class ChunkDeleteRequest { private String knowledgeBaseId; private String chunkId; public void setKnowledgeBaseId(String knowledgeBaseId) { this.knowledgeBaseId = knowledgeBaseId; } public String getKnowledgeBaseId() { return knowledgeBaseId; } public void setChunkId(String chunkId) { this.chunkId = chunkId; } public String getChunkId() { return chunkId; } } ================================================ FILE: java/src/main/java/com/baidubce/appbuilder/model/knowledgebase/ChunkDescribeRequest.java ================================================ package com.baidubce.appbuilder.model.knowledgebase; public class ChunkDescribeRequest { private String knowledgeBaseId; private String chunkId; public void setChunkId(String chunkId) { this.chunkId = chunkId; } public void setKnowledgeBaseId(String knowledgeBaseId) { this.knowledgeBaseId = knowledgeBaseId; } public String getChunkId() { return chunkId; } public String getKnowledgeBaseId() { return knowledgeBaseId; } } ================================================ FILE: java/src/main/java/com/baidubce/appbuilder/model/knowledgebase/ChunkDescribeResponse.java ================================================ package com.baidubce.appbuilder.model.knowledgebase; import com.google.gson.annotations.SerializedName; public class ChunkDescribeResponse { @SerializedName("id") private String chunkId; private String type; private String knowledgeBaseId; private String documentId; private String content; private Integer wordCount; private Integer tokenCount; private boolean enabled; private String status; private String statusMessage; private String[] imageUrls; private Integer createTime; private Integer updateTime; public void setChunkId(String chunkId) { this.chunkId = chunkId; } public String getChunkId() { return chunkId; } public void setType(String type) { this.type = type; } public String getType() { return type; } public void setKnowledgeBaseId(String knowledgeBaseId) { this.knowledgeBaseId = knowledgeBaseId; } public String getKnowledgeBaseId() { return knowledgeBaseId; } public void setDocumentId(String documentId) { this.documentId = documentId; } public String getDocumentId() { return documentId; } public void setContent(String content) { this.content = content; } public String getContent() { return content; } public void setWordCount(Integer wordCount) { this.wordCount = wordCount; } public Integer getWordCount() { return wordCount; } public void setTokenCount(Integer tokenCount) { this.tokenCount = tokenCount; } public Integer getTokenCount() { return tokenCount; } public void setEnabled(boolean enabled) { this.enabled = enabled; } public boolean getEnabled() { return enabled; } public void setStatus(String status) { this.status = status; } public String getStatus() { return status; } public void setStatusMessage(String statusMessage) { this.statusMessage = statusMessage; } public String getStatusMessage() { return statusMessage; } public void setImageUrls(String[] imageUrls) { this.imageUrls = imageUrls; } public String[] getImageUrls() { return imageUrls; } public void setCreateTime(Integer createTime) { this.createTime = createTime; } public Integer getCreateTime() { return createTime; } public void setUpdateTime(Integer updateTime) { this.updateTime = updateTime; } public Integer getUpdateTime() { return updateTime; } } ================================================ FILE: java/src/main/java/com/baidubce/appbuilder/model/knowledgebase/ChunkModifyRequest.java ================================================ package com.baidubce.appbuilder.model.knowledgebase; public class ChunkModifyRequest { private String knowledgeBaseId; private String chunkId; private String content; private boolean enable; public ChunkModifyRequest(String chunkId, String content, boolean enable) { this.chunkId = chunkId; this.content = content; this.enable = enable; } public ChunkModifyRequest(String knowledgeBaseId, String chunkId, String content, boolean enable) { this.knowledgeBaseId = knowledgeBaseId; this.chunkId = chunkId; this.content = content; this.enable = enable; } public String getKnowledgeBaseId() { return knowledgeBaseId; } public void setKnowledgeBaseId(String knowledgeBaseId) { this.knowledgeBaseId = knowledgeBaseId; } public String getChunkId() { return chunkId; } public void setChunkId(String chunkId) { this.chunkId = chunkId; } public String getContent() { return content; } public void setContent(String content) { this.content = content; } public boolean getEnable() { return enable; } public void setEnable(boolean enable) { this.enable = enable; } } ================================================ FILE: java/src/main/java/com/baidubce/appbuilder/model/knowledgebase/ChunksDescribeRequest.java ================================================ package com.baidubce.appbuilder.model.knowledgebase; public class ChunksDescribeRequest { private String knowledgeBaseId; private String documentId; private String marker; private Integer maxKeys; private String type; private String keyword; public ChunksDescribeRequest(String documentId, String marker, Integer maxKeys, String type) { this.documentId = documentId; this.marker = marker; this.maxKeys = maxKeys; this.type = type; } public ChunksDescribeRequest(String knowledgeBaseId, String documentId, String marker, Integer maxKeys, String type) { this.knowledgeBaseId = knowledgeBaseId; this.documentId = documentId; this.marker = marker; this.maxKeys = maxKeys; this.type = type; } public ChunksDescribeRequest(String knowledgeBaseId, String documentId, String marker, Integer maxKeys, String type, String keyword) { this.knowledgeBaseId = knowledgeBaseId; this.documentId = documentId; this.marker = marker; this.maxKeys = maxKeys; this.type = type; this.keyword = keyword; } public String getKnowledgeBaseId() { return knowledgeBaseId; } public void setKnowledgeBaseId(String knowledgeBaseId) { this.knowledgeBaseId = knowledgeBaseId; } public String getDocumentId() { return documentId; } public void setDocumentId(String documentId) { this.documentId = documentId; } public String getMarker() { return marker; } public void setMarker(String marker) { this.marker = marker; } public Integer getMaxKeys() { return maxKeys; } public void setMaxKeys(Integer maxKeys) { this.maxKeys = maxKeys; } public String getType() { return type; } public void setType(String type) { this.type = type; } public void setKeyword(String keyword) { this.keyword = keyword; } public String getKeyword() { return keyword; } } ================================================ FILE: java/src/main/java/com/baidubce/appbuilder/model/knowledgebase/ChunksDescribeResponse.java ================================================ package com.baidubce.appbuilder.model.knowledgebase; public class ChunksDescribeResponse { private ChunkDescribeResponse[] data; private String marker; private boolean isTruncated; private String nextMarker; private Integer maxKeys; public ChunkDescribeResponse[] getData() { return data; } public void setData(ChunkDescribeResponse[] data) { this.data = data; } public String getMarker() { return marker; } public void setMarker(String marker) { this.marker = marker; } public boolean isTruncated() { return isTruncated; } public void setTruncated(boolean isTruncated) { this.isTruncated = isTruncated; } public String getNextMarker() { return nextMarker; } public void setNextMarker(String nextMarker) { this.nextMarker = nextMarker; } public Integer getMaxKeys() { return maxKeys; } public void setMaxKeys(Integer maxKeys) { this.maxKeys = maxKeys; } } ================================================ FILE: java/src/main/java/com/baidubce/appbuilder/model/knowledgebase/Document.java ================================================ package com.baidubce.appbuilder.model.knowledgebase; import com.google.gson.annotations.SerializedName; public class Document { private String id; private String name; @SerializedName("created_at") private String createdAt; @SerializedName("word_count") private int wordCount; private boolean enabled; private Meta meta; public String getId() { return id; } public void setId(String id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getCreatedAt() { return createdAt; } public void setCreatedAt(String createdAt) { this.createdAt = createdAt; } public int getWordCount() { return wordCount; } public void setWordCount(int wordCount) { this.wordCount = wordCount; } public boolean isEnabled() { return enabled; } public void setEnabled(boolean enabled) { this.enabled = enabled; } public Meta getMeta() { return meta; } public void setMeta(Meta meta) { this.meta = meta; } public static class Meta { private String source; @SerializedName("file_id") private String fileId; public String getSource() { return source; } public void setSource(String source) { this.source = source; } public String getFileId() { return fileId; } public void setFileId(String fileId) { this.fileId = fileId; } } } ================================================ FILE: java/src/main/java/com/baidubce/appbuilder/model/knowledgebase/DocumentAddRequest.java ================================================ package com.baidubce.appbuilder.model.knowledgebase; import com.google.gson.annotations.SerializedName; public class DocumentAddRequest { @SerializedName("knowledge_base_id") private String knowledgeBaseId; @SerializedName("content_type") private String contentType; @SerializedName("is_enhanced") private boolean isEnhanced; @SerializedName("file_ids") private String[] fileIds; @SerializedName("custom_process_rule") private CustomProcessRule customProcessRule; public String getKnowledgeBaseId() { return knowledgeBaseId; } public void setKnowledgeBaseId(String knowledgeBaseId) { this.knowledgeBaseId = knowledgeBaseId; } public String getContentType() { return contentType; } public void setContentType(String contentType) { this.contentType = contentType; } public boolean isEnhanced() { return isEnhanced; } public void setEnhanced(boolean enhanced) { isEnhanced = enhanced; } public String[] getFileIds() { return fileIds; } public void setFileIds(String[] fileIds) { this.fileIds = fileIds; } public CustomProcessRule getCustomProcessRule() { return customProcessRule; } public void setCustomProcessRule(CustomProcessRule customProcessRule) { this.customProcessRule = customProcessRule; } public static class CustomProcessRule { @SerializedName("separators") private String[] separators; @SerializedName("target_length") private int targetLength; @SerializedName("overlap_rate") private double overlapRate; public String[] getSeparators() { return separators; } public void setSeparators(String[] separators) { this.separators = separators; } public int getTargetLength() { return targetLength; } public void setTargetLength(int targetLength) { this.targetLength = targetLength; } public double getOverlapRate() { return overlapRate; } public void setOverlapRate(double overlapRate) { this.overlapRate = overlapRate; } } } ================================================ FILE: java/src/main/java/com/baidubce/appbuilder/model/knowledgebase/DocumentAddResponse.java ================================================ package com.baidubce.appbuilder.model.knowledgebase; import com.google.gson.annotations.SerializedName; public class DocumentAddResponse { @SerializedName("request_id") private String requestId; @SerializedName("knowledge_base_id") private String knowledgeBaseId; @SerializedName("document_ids") private String[] documentIds; private String code; private String message; public String getRequestId() { return requestId; } public void setRequestId(String requestId) { this.requestId = requestId; } public String getKnowledgeBaseId() { return knowledgeBaseId; } public void setKnowledgeBaseId(String id) { this.knowledgeBaseId = id; } public String[] getDocumentIds() { return documentIds; } public void setDocumentIds(String[] documentIds) { this.documentIds = documentIds; } public String getCode() { return code; } public void setCode(String code) { this.code = code; } public String getMessage() { return message; } public void setMessage(String message) { this.message = message; } @Override public String toString() { return "FileUploadResponse{" + "request_id=" + requestId + ", code='" + code + '\'' + ", message='" + message + '}'; } } ================================================ FILE: java/src/main/java/com/baidubce/appbuilder/model/knowledgebase/DocumentDeleteRequest.java ================================================ package com.baidubce.appbuilder.model.knowledgebase; import java.util.HashMap; import java.util.Map; import com.google.gson.annotations.SerializedName; public class DocumentDeleteRequest { @SerializedName("knowledge_base_id") private String konwledgeBaseId; @SerializedName("document_id") private String documentId; // getters and setters public String getKonwledgeBaseId() { return konwledgeBaseId; } public void setKonwledgeBaseId(String konwledgeBaseId) { this.konwledgeBaseId = konwledgeBaseId; } public String getDocumentId() { return documentId; } public void setDocumentId(String documentId) { this.documentId = documentId; } public Map toMap() { Map map = new HashMap<>(); map.put("knowledge_base_id", konwledgeBaseId); map.put("document_id", documentId); return map; } } ================================================ FILE: java/src/main/java/com/baidubce/appbuilder/model/knowledgebase/DocumentDeleteResponse.java ================================================ package com.baidubce.appbuilder.model.knowledgebase; import com.google.gson.annotations.SerializedName; public class DocumentDeleteResponse { @SerializedName("request_id") private String requestId; private String code; private String message; public String getRequestId() { return requestId; } public void setRequestId(String requestId) { this.requestId = requestId; } public String getCode() { return code; } public void setCode(String code) { this.code = code; } public String getMessage() { return message; } public void setMessage(String message) { this.message = message; } @Override public String toString() { return "DocumentDeleteResponse{" + "request_id=" + requestId + ", code='" + code + '\'' + ", message='" + message + '}'; } } ================================================ FILE: java/src/main/java/com/baidubce/appbuilder/model/knowledgebase/DocumentDescribeResponse.java ================================================ package com.baidubce.appbuilder.model.knowledgebase; public class DocumentDescribeResponse { private String id; private String name; private String createdAt; private String displayStatus; private Integer wordCount; private Boolean enabled; private Meta meta; public String getId() { return id; } public void setId(String id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getCreatedAt() { return createdAt; } public void setCreatedAt(String createdAt) { this.createdAt = createdAt; } public String getDisplayStatus() { return displayStatus; } public void setDisplayStatus(String displayStatus) { this.displayStatus = displayStatus; } public Integer getWordCount() { return wordCount; } public void setWordCount(Integer wordCount) { this.wordCount = wordCount; } public Boolean getEnabled() { return enabled; } public void setEnabled(Boolean enabled) { this.enabled = enabled; } public Meta getMeta() { return meta; } public void setMeta(Meta meta) { this.meta = meta; } public static class Meta { private String source; private String fileId; private String url; private String mime_type; private Integer file_size; public String getSource() { return source; } public void setSource(String source) { this.source = source; } public String getFileId() { return fileId; } public void setFileId(String fileId) { this.fileId = fileId; } public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } public String getMimeType() { return mime_type; } public void setMimeType(String mime_type) { this.mime_type = mime_type; } public Integer getFileSize() { return file_size; } public void setFileSize(Integer file_size) { this.file_size = file_size; } } } ================================================ FILE: java/src/main/java/com/baidubce/appbuilder/model/knowledgebase/DocumentListRequest.java ================================================ package com.baidubce.appbuilder.model.knowledgebase; import java.util.HashMap; import java.util.Map; import com.google.gson.annotations.SerializedName; public class DocumentListRequest { @SerializedName("knowledge_base_id") private String konwledgeBaseId; private int limit; private String after; private String before; // getters and setters public String getKonwledgeBaseId() { return konwledgeBaseId; } public void setKonwledgeBaseId(String konwledgeBaseId) { this.konwledgeBaseId = konwledgeBaseId; } public int getLimit() { return limit; } public void setLimit(int limit) { this.limit = limit; } public String getAfter() { return after; } public void setAfter(String after) { this.after = after; } public String getBefore() { return before; } public void setBefore(String before) { this.before = before; } public Map toMap() { Map map = new HashMap<>(); map.put("knowledge_base_id", konwledgeBaseId); if (limit != 0) { map.put("limit", limit); } map.put("after", after); map.put("before", before); return map; } } ================================================ FILE: java/src/main/java/com/baidubce/appbuilder/model/knowledgebase/DocumentListResponse.java ================================================ package com.baidubce.appbuilder.model.knowledgebase; import com.google.gson.annotations.SerializedName; public class DocumentListResponse { @SerializedName("request_id") private String requestId; private Document[] data; private String code; private String message; public String getRequestId() { return requestId; } public void setRequestId(String requestId) { this.requestId = requestId; } public Document[] getData() { return data; } public void setData(Document[] data) { this.data = data; } public String getCode() { return code; } public void setCode(String code) { this.code = code; } public String getMessage() { return message; } public void setMessage(String message) { this.message = message; } } ================================================ FILE: java/src/main/java/com/baidubce/appbuilder/model/knowledgebase/DocumentsCreateRequest.java ================================================ package com.baidubce.appbuilder.model.knowledgebase; import com.google.gson.annotations.SerializedName; public class DocumentsCreateRequest { @SerializedName("id") private String knowledgeBaseId; private String contentFormat; private Source source; private ProcessOption processOption; public DocumentsCreateRequest(String knowledgeBaseId, String contentFormat, Source source, ProcessOption processOption) { this.knowledgeBaseId = knowledgeBaseId; this.contentFormat = contentFormat; this.source = source; this.processOption = processOption; } public String getKnowledgeBaseId() { return knowledgeBaseId; } public String getContentFormat() { return contentFormat; } public Source getSource() { return source; } public ProcessOption getProcessOption() { return processOption; } public static class Source { private String type; private String[] urls; private Integer urlDepth; private UrlConfig[] urlConfigs; public Source(String type, String[] urls, Integer urlDepth) { this.type = type; this.urls = urls; this.urlDepth = urlDepth; } public Source(String type, String[] urls, Integer urlDepth, UrlConfig[] urlConfigs) { this.type = type; this.urls = urls; this.urlDepth = urlDepth; this.urlConfigs = urlConfigs; } public String getType() { return type; } public String[] getUrls() { return urls; } public Integer getUrlDepth() { return urlDepth; } public UrlConfig[] getUrlConfigs() { return urlConfigs; } public void setUrlConfigs(UrlConfig[] urlConfigs) { this.urlConfigs = urlConfigs; } public static class UrlConfig { private Integer frequency; public UrlConfig(Integer frequency) { this.frequency = frequency; } public Integer getFrequency() { return frequency; } public void setFrequency(Integer frequency) { this.frequency = frequency; } } } public static class ProcessOption { private String template; private Parser parser; private Chunker chunker; private KnowledgeAugmentation knowledgeAugmentation; public ProcessOption(String template, Parser parser, Chunker chunker, KnowledgeAugmentation knowledgeAugmentation) { this.template = template; this.parser = parser; this.chunker = chunker; this.knowledgeAugmentation = knowledgeAugmentation; } public String getTemplate() { return template; } public Parser getParser() { return parser; } public Chunker getChunker() { return chunker; } public KnowledgeAugmentation getKnowledgeAugmentation() { return knowledgeAugmentation; } public static class Parser { private String[] choices; public Parser(String[] choices) { this.choices = choices; } public String[] getChoices() { return choices; } } public static class Chunker { private String[] choices; private Separator separator; private Pattern pattern; private String[] prependInfo; public Chunker(String[] choices, Separator separator, Pattern pattern, String[] prependInfo) { this.choices = choices; this.separator = separator; this.pattern = pattern; this.prependInfo = prependInfo; } public String[] getChoices() { return choices; } public Separator getSeparator() { return separator; } public Pattern getPattern() { return pattern; } public String[] getPrependInfo() { return prependInfo; } public static class Separator { private String[] separators; private Integer targetLength; private Double overlapRate; public Separator(String[] separators, Integer targetLength, Double overlapRate) { this.separators = separators; this.targetLength = targetLength; this.overlapRate = overlapRate; } public String[] getSeparators() { return separators; } public Integer getTargetLength() { return targetLength; } public Double getOverlapRate() { return overlapRate; } } public static class Pattern { private String markPosition; private String regex; private Integer targetLength; private Double overlapRate; public Pattern(String markPosition, String regex, Integer targetLength, Double overlapRate) { this.markPosition = markPosition; this.regex = regex; this.targetLength = targetLength; this.overlapRate = overlapRate; } public String getMarkPosition() { return markPosition; } public String getRegex() { return regex; } public Integer getTargetLength() { return targetLength; } public Double getOverlapRate() { return overlapRate; } } } public static class KnowledgeAugmentation { private String[] choices; public KnowledgeAugmentation(String[] choices) { this.choices = choices; } public String[] getChoices() { return choices; } } } } ================================================ FILE: java/src/main/java/com/baidubce/appbuilder/model/knowledgebase/DocumentsCreateResponse.java ================================================ package com.baidubce.appbuilder.model.knowledgebase; public class DocumentsCreateResponse { private String requestId; private String[] documentIds; public String getRequestId() { return requestId; } public void setRequestId(String requestId) { this.requestId = requestId; } public String[] getDocumentIds() { return documentIds; } public void setDocumentIds(String[] documentIds) { this.documentIds = documentIds; } } ================================================ FILE: java/src/main/java/com/baidubce/appbuilder/model/knowledgebase/DocumentsDescribeRequest.java ================================================ package com.baidubce.appbuilder.model.knowledgebase; public class DocumentsDescribeRequest { private String knowledgeBaseId; private String marker; private Integer maxKeys; public DocumentsDescribeRequest(String marker, Integer maxKeys) { this.marker = marker; this.maxKeys = maxKeys; } public DocumentsDescribeRequest(String knowledgeBaseId, String marker, Integer maxKeys) { this.knowledgeBaseId = knowledgeBaseId; this.marker = marker; this.maxKeys = maxKeys; } public String getKnowledgeBaseId() { return knowledgeBaseId; } public void setKnowledgeBaseId(String knowledgeBaseId) { this.knowledgeBaseId = knowledgeBaseId; } public String getMarker() { return marker; } public void setMarker(String marker) { this.marker = marker; } public Integer getMaxKeys() { return maxKeys; } public void setMaxKeys(Integer maxKeys) { this.maxKeys = maxKeys; } } ================================================ FILE: java/src/main/java/com/baidubce/appbuilder/model/knowledgebase/DocumentsDescribeResponse.java ================================================ package com.baidubce.appbuilder.model.knowledgebase; public class DocumentsDescribeResponse { private DocumentDescribeResponse[] data; private String marker; private boolean isTruncated; private String nextMarker; private Integer maxKeys; public DocumentDescribeResponse[] getData() { return data; } public void setData(DocumentDescribeResponse[] data) { this.data = data; } public String getMarker() { return marker; } public void setMarker(String marker) { this.marker = marker; } public boolean isTruncated() { return isTruncated; } public void setTruncated(boolean isTruncated) { this.isTruncated = isTruncated; } public String getNextMarker() { return nextMarker; } public void setNextMarker(String nextMarker) { this.nextMarker = nextMarker; } public Integer getMaxKeys() { return maxKeys; } public void setMaxKeys(Integer maxKeys) { this.maxKeys = maxKeys; } } ================================================ FILE: java/src/main/java/com/baidubce/appbuilder/model/knowledgebase/DocumentsUploadResponse.java ================================================ package com.baidubce.appbuilder.model.knowledgebase; public class DocumentsUploadResponse { private String requestId; private String documentId; public String getRequestId() { return requestId; } public void setRequestId(String requestId) { this.requestId = requestId; } public String getDocumentId() { return documentId; } public void setDocumentId(String documentId) { this.documentId = documentId; } } ================================================ FILE: java/src/main/java/com/baidubce/appbuilder/model/knowledgebase/FileUploadResponse.java ================================================ package com.baidubce.appbuilder.model.knowledgebase; import com.google.gson.annotations.SerializedName; public class FileUploadResponse { @SerializedName("request_id") private String requestId; private String id; private String code; private String message; public String getRequestId() { return requestId; } public void setRequestId(String requestId) { this.requestId = requestId; } public String getId() { return id; } public void setId(String id) { this.id = id; } public String getCode() { return code; } public void setCode(String code) { this.code = code; } public String getMessage() { return message; } public void setMessage(String message) { this.message = message; } @Override public String toString() { return "FileUploadResponse{" + "request_id=" + requestId + ", code='" + code + '\'' + ", message='" + message + '}'; } } ================================================ FILE: java/src/main/java/com/baidubce/appbuilder/model/knowledgebase/KnowledgeBaseConfig.java ================================================ package com.baidubce.appbuilder.model.knowledgebase; public class KnowledgeBaseConfig { private Index index; private Catalogue catalogue; public KnowledgeBaseConfig(Index index) { this.index = index; } public KnowledgeBaseConfig(Index index, Catalogue catalogue) { this.index = index; this.catalogue = catalogue; } public Index getIndex() { return index; } public void setIndex(Index index) { this.index = index; } public void setCatalogue(Catalogue catalogue) { this.catalogue = catalogue; } public Catalogue getCatalogue() { return catalogue; } public static class Index { private String type; private String clusterId; private String username; private String password; private String location; public Index(String type, String clusterId, String username, String password, String location) { this.type = type; this.clusterId = clusterId; this.username = username; this.password = password; this.location = location; } public String getType() { return type; } public String getClusterId() { return clusterId; } public String getUsername() { return username; } public String getPassword() { return password; } public String getLocation() { return location; } } public static class Catalogue { private String pathPrefix; public void setPathPrefix(String pathPrefix) { this.pathPrefix = pathPrefix; } public String getPathPrefix() { return pathPrefix; } } } ================================================ FILE: java/src/main/java/com/baidubce/appbuilder/model/knowledgebase/KnowledgeBaseDetail.java ================================================ package com.baidubce.appbuilder.model.knowledgebase; public class KnowledgeBaseDetail { private String id; private String name; private String description; private KnowledgeBaseConfig config; public String getId() { return id; } public void setId(String id) { this.id = id; } public KnowledgeBaseConfig getConfig() { return config; } public void setConfig(KnowledgeBaseConfig config) { this.config = config; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } } ================================================ FILE: java/src/main/java/com/baidubce/appbuilder/model/knowledgebase/KnowledgeBaseDetailRequest.java ================================================ package com.baidubce.appbuilder.model.knowledgebase; import com.google.gson.annotations.SerializedName; public class KnowledgeBaseDetailRequest { @SerializedName("id") private String knowledgeBaseId; public String getKnowledgeBaseId() { return knowledgeBaseId; } public void setKnowledgeBaseId(String knowledgeBaseId) { this.knowledgeBaseId = knowledgeBaseId; } } ================================================ FILE: java/src/main/java/com/baidubce/appbuilder/model/knowledgebase/KnowledgeBaseListRequest.java ================================================ package com.baidubce.appbuilder.model.knowledgebase; public class KnowledgeBaseListRequest { // 起始位置 private String marker; // 数据大小,默认10,最大值100 private Integer maxKeys; // 搜索关键字 private String keyword; public KnowledgeBaseListRequest(String marker, Integer maxKeys, String keyword) { this.maxKeys = maxKeys; this.marker = marker; this.keyword = keyword; } public String getMarker() { return marker; } public int getMaxKeys() { return maxKeys; } public String getKeyword() { return keyword; } } ================================================ FILE: java/src/main/java/com/baidubce/appbuilder/model/knowledgebase/KnowledgeBaseListResponse.java ================================================ package com.baidubce.appbuilder.model.knowledgebase; public class KnowledgeBaseListResponse { private String requestId; private KnowledgeBaseDetail[] data; private String marker; private boolean isTruncated; private String nextMarker; private int maxKeys; public String getRequestId() { return requestId; } public void setRequestId(String requestId) { this.requestId = requestId; } public KnowledgeBaseDetail[] getData() { return data; } public void setData(KnowledgeBaseDetail[] data) { this.data = data; } public String getMarker() { return marker; } public void setMarker(String marker) { this.marker = marker; } public boolean isTruncated() { return isTruncated; } public void setTruncated(boolean isTruncated) { this.isTruncated = isTruncated; } public String getNextMarker() { return nextMarker; } public void setNextMarker(String nextMarker) { this.nextMarker = nextMarker; } public int getMaxKeys() { return maxKeys; } public void setMaxKeys(int maxKeys) { this.maxKeys = maxKeys; } } ================================================ FILE: java/src/main/java/com/baidubce/appbuilder/model/knowledgebase/KnowledgeBaseModifyRequest.java ================================================ package com.baidubce.appbuilder.model.knowledgebase; import com.google.gson.annotations.SerializedName; public class KnowledgeBaseModifyRequest { @SerializedName("id") private String knowledgeBaseId; private String name; private String description; private KnowledgeBaseConfig config; public String getKnowledgeBaseId() { return knowledgeBaseId; } public void setKnowledgeBaseId(String knowledgeBaseId) { this.knowledgeBaseId = knowledgeBaseId; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public KnowledgeBaseConfig getConfig() { return config; } public void setConfig(KnowledgeBaseConfig config) { this.config = config; } } ================================================ FILE: java/src/main/java/com/baidubce/appbuilder/model/knowledgebase/QueryKnowledgeBaseRequest.java ================================================ package com.baidubce.appbuilder.model.knowledgebase; import java.util.List; public class QueryKnowledgeBaseRequest { private String query; private String type; private Float rank_score_threshold; private Integer top; private Integer skip; private String[] knowledgebase_ids; private MetadataFilters metadata_filters; private QueryPipelineConfig pipeline_config; public QueryKnowledgeBaseRequest(String query, String type, Float rank_score_threshold, Integer top, Integer skip, String[] knowledgebase_ids, MetadataFilters metadata_filters, QueryPipelineConfig pipeline_config) { this.query = query; this.type = type; this.rank_score_threshold = rank_score_threshold; this.top = top; this.skip = skip; this.knowledgebase_ids = knowledgebase_ids; this.metadata_filters = metadata_filters; this.pipeline_config = pipeline_config; } public String getQuery() { return query; } public void setQuery(String query) { this.query = query; } public String getType() { return type; } public void setType(String type) { this.type = type; } public Float getRank_score_threshold() { return rank_score_threshold; } public void setRank_score_threshold(Float rank_score_threshold) { this.rank_score_threshold = rank_score_threshold; } public Integer getTop() { return top; } public void setTop(Integer top) { this.top = top; } public Integer getSkip() { return skip; } public void setSkip(Integer skip) { this.skip = skip; } public String[] getKnowledgebase_ids() { return knowledgebase_ids; } public void setKnowledgebase_ids(String[] knowledgebase_ids) { this.knowledgebase_ids = knowledgebase_ids; } public MetadataFilters getMetadata_filters() { return metadata_filters; } public void setMetadata_filters(MetadataFilters metadata_filters) { this.metadata_filters = metadata_filters; } public QueryPipelineConfig getPipeline_config() { return pipeline_config; } public void setPipeline_config(QueryPipelineConfig pipeline_config) { this.pipeline_config = pipeline_config; } public static class MetadataFilter { private String operator; private String field; private Object value; public String getOperator() { return operator; } public void setOperator(String operator) { this.operator = operator; } public String getField() { return field; } public void setField(String field) { this.field = field; } public Object getValue() { return value; } public void setValue(Object value) { this.value = value; } } public static class MetadataFilters { private List filters; private String condition; public List getFilters() { return filters; } public void setFilters(List filters) { this.filters = filters; } public String getCondition() { return condition; } public void setCondition(String condition) { this.condition = condition; } } public static class PreRankingConfig { private Double bm25_weight; private Double vec_weight; private Double bm25_b; private Double bm25_k1; private Double bm25_max_score; public Double getBm25_weight() { return bm25_weight; } public void setBm25_weight(Double bm25_weight) { this.bm25_weight = bm25_weight; } public Double getVec_weight() { return vec_weight; } public void setVec_weight(Double vec_weight) { this.vec_weight = vec_weight; } public Double getBm25_b() { return bm25_b; } public void setBm25_b(Double bm25_b) { this.bm25_b = bm25_b; } public Double getBm25_k1() { return bm25_k1; } public void setBm25_k1(Double bm25_k1) { this.bm25_k1 = bm25_k1; } public Double getBm25_max_score() { return bm25_max_score; } public void setBm25_max_score(Double bm25_max_score) { this.bm25_max_score = bm25_max_score; } } public static class ElasticSearchRetrieveConfig { private String name; private String type; private Double threshold; private Integer top; public String getName() { return name; } public void setName(String name) { this.name = name; } public String getType() { return type; } public void setType(String type) { this.type = type; } public Double getThreshold() { return threshold; } public void setThreshold(Double threshold) { this.threshold = threshold; } public Integer getTop() { return top; } public void setTop(Integer top) { this.top = top; } } public static class VectorDBRetrieveConfig { private String name; private String type; private Double threshold; private Integer top; public String getName() { return name; } public void setName(String name) { this.name = name; } public String getType() { return type; } public void setType(String type) { this.type = type; } public Double getThreshold() { return threshold; } public void setThreshold(Double threshold) { this.threshold = threshold; } public Integer getTop() { return top; } public void setTop(Integer top) { this.top = top; } } public static class RankingConfig { private String name; private String type; private List inputs; private String model_name; private Integer top; public String getName() { return name; } public void setName(String name) { this.name = name; } public String getType() { return type; } public void setType(String type) { this.type = type; } public List getInputs() { return inputs; } public void setInputs(List inputs) { this.inputs = inputs; } public String getModel_name() { return model_name; } public void setModel_name(String model_name) { this.model_name = model_name; } public Integer getTop() { return top; } public void setTop(Integer top) { this.top = top; } } public static class SmallToBigConfig { private String name; private String type; public String getName() { return name; } public void setName(String name) { this.name = name; } public String getType() { return type; } public void setType(String type) { this.type = type; } } public static class QueryPipelineConfig { private String id; private List pipeline; public String getId() { return id; } public void setId(String id) { this.id = id; } public List getPipeline() { return pipeline; } public void setPipeline(List pipeline) { this.pipeline = pipeline; } } } ================================================ FILE: java/src/main/java/com/baidubce/appbuilder/model/knowledgebase/QueryKnowledgeBaseResponse.java ================================================ package com.baidubce.appbuilder.model.knowledgebase; import java.util.List; import java.util.Map; public class QueryKnowledgeBaseResponse { private String requestId; private String code; private String message; private List chunks; private int total_count; public String getRequestId() { return requestId; } public void setRequestId(String requestId) { this.requestId = requestId; } public String getCode() { return code; } public void setCode(String code) { this.code = code; } public String getMessage() { return message; } public void setMessage(String message) { this.message = message; } public List getChunks() { return chunks; } public void setChunks(List chunks) { this.chunks = chunks; } public int getTotal_count() { return total_count; } public void setTotal_count(int total_count) { this.total_count = total_count; } public static class Chunk { private String chunk_id; private String knowledgebase_id; private String document_id; private String document_name; private Map meta; private String type; private String content; private String create_time; private String update_time; private float retrieval_score; private float rank_score; private ChunkLocation locations; private List children; private List neighbour_chunks; private String original_chunk_id; private Integer original_chunk_offset; public String getChunk_id() { return chunk_id; } public void setChunk_id(String chunk_id) { this.chunk_id = chunk_id; } public String getKnowledgebase_id() { return knowledgebase_id; } public void setKnowledgebase_id(String knowledgebase_id) { this.knowledgebase_id = knowledgebase_id; } public String getDocument_id() { return document_id; } public void setDocument_id(String document_id) { this.document_id = document_id; } public String getDocument_name() { return document_name; } public void setDocument_name(String document_name) { this.document_name = document_name; } public Map getMeta() { return meta; } public void setMeta(Map meta) { this.meta = meta; } public String getType() { return type; } public void setType(String type) { this.type = type; } public String getContent() { return content; } public void setContent(String content) { this.content = content; } public String getCreate_time() { return create_time; } public void setCreate_time(String create_time) { this.create_time = create_time; } public String getUpdate_time() { return update_time; } public void setUpdate_time(String update_time) { this.update_time = update_time; } public float getRetrieval_score() { return retrieval_score; } public void setRetrieval_score(float retrieval_score) { this.retrieval_score = retrieval_score; } public float getRank_score() { return rank_score; } public void setRank_score(float rank_score) { this.rank_score = rank_score; } public ChunkLocation getLocations() { return locations; } public void setLocations(ChunkLocation locations) { this.locations = locations; } public List getChildren() { return children; } public void setChildren(List children) { this.children = children; } public List getNeighbour_chunks() { return neighbour_chunks; } public void setNeighbour_chunks(List neighbour_chunks) { this.neighbour_chunks = neighbour_chunks; } public String getOriginal_chunk_id() { return original_chunk_id; } public void setOriginal_chunk_id(String original_chunk_id) { this.original_chunk_id = original_chunk_id; } public Integer getOriginal_chunk_offset() { return original_chunk_offset; } public void setOriginal_chunk_offset(Integer original_chunk_offset) { this.original_chunk_offset = original_chunk_offset; } } public static class ChunkLocation { private List paget_num; private List> box; public List getPaget_num() { return paget_num; } public void setPaget_num(List paget_num) { this.paget_num = paget_num; } public List> getBox() { return box; } public void setBox(List> box) { this.box = box; } } } ================================================ FILE: java/src/main/java/com/baidubce/appbuilder/model/rag/EventContent.java ================================================ package com.baidubce.appbuilder.model.rag; import com.google.gson.annotations.SerializedName; import java.util.Arrays; import java.util.HashMap; import java.util.Map; public class EventContent { @SerializedName("event_code") String eventCode; @SerializedName("event_message") String enentMessage; @SerializedName("node_name") String nodeName; @SerializedName("dependency_nodes") String[] dependencyNodes; @SerializedName("event_type") String eventType; @SerializedName("event_id") String eventId; @SerializedName("event_status") String eventStatus; @SerializedName("content_type") String contentType; Map outputs; HashMap detail; public String getEventCode() { return eventCode; } public void setEventCode(String eventCode) { this.eventCode = eventCode; } public String getEnentMessage() { return enentMessage; } public void setEnentMessage(String enentMessage) { this.enentMessage = enentMessage; } public String getNodeName() { return nodeName; } public void setNodeName(String nodeName) { this.nodeName = nodeName; } public String[] getDependencyNodes() { return dependencyNodes; } public void setDependencyNodes(String[] dependencyNodes) { this.dependencyNodes = dependencyNodes; } public String getEventType() { return eventType; } public void setEventType(String eventType) { this.eventType = eventType; } public String getEventId() { return eventId; } public void setEventId(String eventId) { this.eventId = eventId; } public String getEventStatus() { return eventStatus; } public void setEventStatus(String eventStatus) { this.eventStatus = eventStatus; } public String getContentType() { return contentType; } public void setContentType(String contentType) { this.contentType = contentType; } public Map getOutputs() { return outputs; } public void setOutputs(Map outputs) { this.outputs = outputs; } public HashMap getDetail() { return detail; } public void setDetail(HashMap detail) { this.detail = detail; } @Override public String toString() { return "EventContent{" + "eventCode='" + eventCode + '\'' + ", enentMessage='" + enentMessage + '\'' + ", nodeName='" + nodeName + '\'' + ", dependencyNodes=" + Arrays.toString(dependencyNodes) + ", eventType='" + eventType + '\'' + ", eventId='" + eventId + '\'' + ", eventStatus='" + eventStatus + '\'' + ", contentType='" + contentType + '\'' + ", outputs=" + outputs + ", detail=" + detail + '}'; } } ================================================ FILE: java/src/main/java/com/baidubce/appbuilder/model/rag/RAGIterator.java ================================================ package com.baidubce.appbuilder.model.rag; import com.baidubce.appbuilder.base.exception.AppBuilderServerException; import com.baidubce.appbuilder.base.utils.http.HttpResponse; import com.baidubce.appbuilder.base.utils.iterator.StreamIterator; public class RAGIterator { private final HttpResponse> resp; private final StreamIterator iterator; public RAGIterator(HttpResponse> resp) { this.resp = resp; this.iterator = resp.getBody(); } public boolean hasNext() { return iterator.hasNext(); } public RAGResponse next() throws AppBuilderServerException { RAGResponse ragResponse = iterator.next(); if (ragResponse.getCode() != 0) { throw new AppBuilderServerException(resp.getRequestId(), resp.getCode(), resp.getMessage(), ragResponse.getCode(), ragResponse.getMessage()); } return ragResponse; } public void close(){ iterator.close(); } } ================================================ FILE: java/src/main/java/com/baidubce/appbuilder/model/rag/RAGResponse.java ================================================ package com.baidubce.appbuilder.model.rag; import com.google.gson.annotations.SerializedName; public class RAGResponse { private int code; private String message; @SerializedName("trace_id") private String traceId; private long time; private RAGResult result; public String getTraceId() { return traceId; } public void setTraceId(String traceId) { this.traceId = traceId; } public long getTime() { return time; } public void setTime(int time) { this.time = time; } public RAGResult getResult() { return result; } public void setResult(RAGResult result) { this.result = result; } public int getCode() { return code; } public void setCode(int code) { this.code = code; } public String getMessage() { return message; } public void setMessage(String message) { this.message = message; } @Override public String toString() { return "RAGResponse{" + "code=" + code + ", message='" + message + '\'' + ", traceId='" + traceId + '\'' + ", time=" + time + ", result=" + result + '}'; } } ================================================ FILE: java/src/main/java/com/baidubce/appbuilder/model/rag/RAGResult.java ================================================ package com.baidubce.appbuilder.model.rag; import com.google.gson.annotations.SerializedName; import java.util.Arrays; public class RAGResult { private String answer; @SerializedName("conversation_id") private String conversationId; @SerializedName("message_id") private String messageId; @SerializedName("is_completion") private Object isCompletion; private String prototype; private EventContent[] content; public String getAnswer() { return answer; } public void setAnswer(String answer) { this.answer = answer; } public String getConversationId() { return conversationId; } public void setConversationId(String conversationId) { this.conversationId = conversationId; } public String getMessageId() { return messageId; } public void setMessageId(String messageId) { this.messageId = messageId; } public Object getIsCompletion() { return isCompletion; } public void setIsCompletion(Object isCompletion) { this.isCompletion = isCompletion; } public String getPrototype() { return prototype; } public void setPrototype(String prototype) { this.prototype = prototype; } public EventContent[] getContent() { return content; } public void setContent(EventContent[] content) { this.content = content; } @Override public String toString() { return "RAGResult{" + "answer='" + answer + '\'' + ", conversationId='" + conversationId + '\'' + ", messageId='" + messageId + '\'' + ", isCompletion=" + isCompletion + ", prototype='" + prototype + '\'' + ", content=" + Arrays.toString(content) + '}'; } } ================================================ FILE: java/src/test/java/com/baidubce/appbuilder/AISearchTest.java ================================================ package com.baidubce.appbuilder; import static org.junit.Assert.assertTrue; import java.io.IOException; import org.junit.Before; import org.junit.Test; import com.google.gson.Gson; import com.baidubce.appbuilder.base.exception.AppBuilderServerException; import com.baidubce.appbuilder.console.aisearch.AISearch; import com.baidubce.appbuilder.model.aisearch.AISearchIterator; import com.baidubce.appbuilder.model.aisearch.AISearchRequest; import com.baidubce.appbuilder.model.aisearch.AISearchResponse; public class AISearchTest { @Before public void setUp() { System.setProperty("APPBUILDER_TOKEN", System.getenv("APPBUILDER_TOKEN")); System.setProperty("APPBUILDER_LOGLEVEL", "DEBUG"); } @Test public void TestBaseSearch() throws IOException, AppBuilderServerException { AISearch client = new AISearch(); AISearchRequest request = new AISearchRequest(); AISearchRequest.Message[] messages = { new AISearchRequest.Message("user", "查询今天天气") }; request.setMessages(messages); AISearchIterator iter = client.run(request); while (iter.hasNext()) { AISearchResponse response = iter.next(); Gson gson = new Gson(); String json = gson.toJson(response); System.out.println(json); assertTrue(response.getReferences().size() > 0); } } @Test public void TestAISearch() throws IOException, AppBuilderServerException { AISearch client = new AISearch(); AISearchRequest request = new AISearchRequest(); AISearchRequest.Message[] messages = { new AISearchRequest.Message("user", "查询今天天气") }; request.setMessages(messages).setModel("deepseek-v3.1-250821"); AISearchIterator iter = client.run(request); while (iter.hasNext()) { AISearchResponse response = iter.next(); Gson gson = new Gson(); String json = gson.toJson(response); System.out.println(json); assertTrue(response.getReferences().size() > 0); } } @Test public void TestAISearchStream() throws IOException, AppBuilderServerException { AISearch client = new AISearch(); AISearchRequest request = new AISearchRequest(); AISearchRequest.Message[] messages = { new AISearchRequest.Message("user", "查询今天天气") }; request.setMessages(messages).setModel("deepseek-v3.1-250821").setStream(true); AISearchIterator iter = client.run(request); while (iter.hasNext()) { AISearchResponse response = iter.next(); Gson gson = new Gson(); String json = gson.toJson(response); System.out.println(json); } } } ================================================ FILE: java/src/test/java/com/baidubce/appbuilder/AgentBuilderTest.java ================================================ package com.baidubce.appbuilder; import com.baidubce.appbuilder.base.exception.AppBuilderServerException; import com.baidubce.appbuilder.model.agentbuilder.AgentBuilderIterator; import java.io.IOException; import com.baidubce.appbuilder.model.agentbuilder.AgentBuilderResult; import org.junit.Before; import org.junit.Test; import static org.junit.Assert.*; import com.baidubce.appbuilder.console.agentbuilder.AgentBuilder; public class AgentBuilderTest{ String appId; @Before public void setUp() { System.setProperty("APPBUILDER_TOKEN", System.getenv("APPBUILDER_TOKEN")); System.setProperty("APPBUILDER_LOGLEVEL", "INFO"); appId = "aa8af334-df27-4855-b3d1-0d249c61fc08"; } @Test public void testAgentBuilder() throws IOException, AppBuilderServerException { AgentBuilder builder = new AgentBuilder(appId); String conversationId = builder.createConversation(); assertNotNull(conversationId); String fileId = builder.uploadLocalFile(conversationId, "src/test/java/com/baidubce/appbuilder/files/test.pdf"); assertNotNull(fileId); AgentBuilderIterator itor = builder.run("北京有多少小学生", conversationId, new String[]{fileId}, true); assertTrue(itor.hasNext()); while (itor.hasNext()) { AgentBuilderResult result = itor.next(); System.out.println(result); } } @Test(expected = AppBuilderServerException.class) public void testCreateConversation_AppBuilderServerException() throws IOException, AppBuilderServerException { AgentBuilder builder = new AgentBuilder("appId"); builder.createConversation(); } } ================================================ FILE: java/src/test/java/com/baidubce/appbuilder/AppBuilderClientTest.java ================================================ package com.baidubce.appbuilder; import java.io.IOException; import java.nio.file.Paths; import java.nio.file.Files; import java.util.HashMap; import java.util.Map; import java.util.Stack; import java.util.List; import org.junit.Before; import org.junit.Test; import com.baidubce.appbuilder.model.appbuilderclient.AppBuilderClientIterator; import com.baidubce.appbuilder.model.appbuilderclient.AppBuilderClientResult; import com.baidubce.appbuilder.base.exception.AppBuilderServerException; import com.baidubce.appbuilder.console.appbuilderclient.AppBuilderClient; import com.baidubce.appbuilder.console.appbuilderclient.AppList; import com.baidubce.appbuilder.console.appbuilderclient.App; import com.baidubce.appbuilder.model.appbuilderclient.AppListRequest; import com.baidubce.appbuilder.model.appbuilderclient.AppsDescribeRequest; import com.baidubce.appbuilder.model.appbuilderclient.Event; import com.baidubce.appbuilder.model.appbuilderclient.EventContent; import com.baidubce.appbuilder.model.appbuilderclient.AppBuilderClientRunRequest; import com.baidubce.appbuilder.model.appbuilderclient.AppDescribeResponse; import com.baidubce.appbuilder.model.appbuilderclient.AppBuilderClientFeedbackRequest; import com.baidubce.appbuilder.model.appbuilderclient.AppBuilderClientFeedbackResponse; import static org.junit.Assert.*; public class AppBuilderClientTest { String appId; String chatflowAppId; String followupqueryId; String describeAppId; @Before public void setUp() { System.setProperty("APPBUILDER_TOKEN", System.getenv("APPBUILDER_TOKEN")); System.setProperty("APPBUILDER_LOGLEVEL", "DEBUG"); appId = "aa8af334-df27-4855-b3d1-0d249c61fc08"; describeAppId = "b2a972c5-e082-46e5-b313-acbf51792422"; chatflowAppId = "4403205e-fb83-4fac-96d8-943bdb63796f"; followupqueryId = "fb64d96b-f828-4385-ba1d-835298d635a9"; } @Test public void GetAppsTest() throws IOException, AppBuilderServerException { AppList builder = new AppList(); AppListRequest request = new AppListRequest(); request.setLimit(10); assertNotNull(builder.getAppList(request)[0].getId()); } @Test public void DescribeAppTest() throws IOException, AppBuilderServerException { App app = new App(); AppDescribeResponse appInfo = app.describeApp(describeAppId); System.out.println(appInfo); assertNotNull(appInfo); AppDescribeResponse chatflowAppInfo = app.describeApp(chatflowAppId); System.out.println(chatflowAppInfo); assertNotNull(chatflowAppInfo); } @Test public void DescribeAppsTest() throws IOException, AppBuilderServerException { AppList appList = new AppList(); AppsDescribeRequest request = new AppsDescribeRequest(); assertNotNull(appList.describeApps(request).getData()[0].getId()); } @Test public void AppBuilderClientRunTest() throws IOException, AppBuilderServerException { AppBuilderClient builder = new AppBuilderClient(followupqueryId); String conversationId = builder.createConversation(); assertNotNull(conversationId); builder.uploadFile(conversationId, "src/test/java/com/baidubce/appbuilder/files/test.pdf", ""); builder.uploadFile(conversationId, "", "https://bj.bcebos.com/v1/appbuilder/animal_recognize_test.png?authorization=bce-auth-v1%2FALTAKGa8m4qCUasgoljdEDAzLm%2F2024-01-24T12%3A19%3A16Z%2F-1%2Fhost%2F411bad53034fa8f9c6edbe5c4909d76ecf6fad6862cf937c03f8c5260d51c6ae"); String fileId = builder.uploadLocalFile(conversationId, "src/test/java/com/baidubce/appbuilder/files/test.pdf"); assertNotNull(fileId); AppBuilderClientIterator itor = builder.run("北京有多少小学生", conversationId, new String[] {fileId}, true); assertTrue(itor.hasNext()); while (itor.hasNext()) { AppBuilderClientResult result = itor.next(); for (Event event : result.getEvents()) { if (!event.getContentType().equals(EventContent.JsonContentType) || !event.getEventType().equals(Event.FollowUpQueryEventType)) { continue; } Object json = event.getDetail().get("json"); if (!(json instanceof Map)) { continue; } for (Map.Entry entry : ((Map) json).entrySet()) { if (!(entry.getKey() instanceof String && entry.getValue() instanceof List && !((List) entry.getValue()).isEmpty() && ((List) entry.getValue()).get(0) instanceof String)) { continue; } String key = (String) entry.getKey(); String stringValue = (String) ((List) entry.getValue()).get(0); if (key.equals("follow_up_querys")) { System.out.println(stringValue); assert !stringValue.isEmpty(); } } } } } @Test(expected = AppBuilderServerException.class) public void testCreateConversation_AppBuilderServerException() throws IOException, AppBuilderServerException { AppBuilderClient builder = new AppBuilderClient("appId"); builder.createConversation(); } @Test public void AppBuilderClientRunFuncTest() throws IOException, AppBuilderServerException { AppBuilderClient builder = new AppBuilderClient(appId); String conversationId = builder.createConversation(); assertNotNull(conversationId); AppBuilderClientRunRequest request = new AppBuilderClientRunRequest(appId, conversationId, "今天北京的天气怎么样?", false); String toolJson = new String(Files.readAllBytes(Paths.get("src/test/java/com/baidubce/appbuilder/files/toolcall.json"))); request.setTools(toolJson); AppBuilderClientIterator itor = builder.run(request); assertTrue(itor.hasNext()); String ToolCallID = ""; while (itor.hasNext()) { AppBuilderClientResult result = itor.next(); Event lastEvent = result.getEvents()[result.getEvents().length - 1]; ToolCallID = lastEvent.getToolCalls()[lastEvent.getToolCalls().length - 1].getId(); System.out.println(result); } AppBuilderClientRunRequest request2 = new AppBuilderClientRunRequest(appId, conversationId); request2.setToolOutputs(ToolCallID, "北京今天35度"); AppBuilderClientIterator itor2 = builder.run(request2); assertTrue(itor2.hasNext()); while (itor2.hasNext()) { AppBuilderClientResult result = itor2.next(); System.out.println(result); } } @Test public void AppBuilderClientRunToolChoiceTest() throws IOException, AppBuilderServerException { AppBuilderClient builder = new AppBuilderClient(appId); String conversationId = builder.createConversation(); assertNotNull(conversationId); AppBuilderClientRunRequest request = new AppBuilderClientRunRequest(appId, conversationId, "你能干什么", false); request.setEndUserId("java_test_user_0"); Map input = new HashMap<>(); input.put("city", "北京"); AppBuilderClientRunRequest.ToolChoice.Function func = new AppBuilderClientRunRequest.ToolChoice.Function( "WeatherQuery", input); AppBuilderClientRunRequest.ToolChoice choice = new AppBuilderClientRunRequest.ToolChoice("function", func); request.setToolChoice(choice); AppBuilderClientIterator itor = builder.run(request); assertTrue(itor.hasNext()); while (itor.hasNext()) { AppBuilderClientResult result = itor.next(); System.out.println(result); } } @Test public void AppBuilderClientRunParametersTest() throws IOException, AppBuilderServerException { appId = "2313e282-baa6-4db6-92dd-a21e99cfd59e"; AppBuilderClient builder = new AppBuilderClient(appId); String conversationId = builder.createConversation(); assertNotNull(conversationId); AppBuilderClientRunRequest request = new AppBuilderClientRunRequest(appId, conversationId, "国庆假期我要回老家", false); Map parameters = new HashMap<>(); parameters.put("city", "信阳"); request.setParameters(parameters); AppBuilderClientIterator itor = builder.run(request); assertTrue(itor.hasNext()); while (itor.hasNext()) { AppBuilderClientResult result = itor.next(); System.out.println(result); } } @Test public void AppBuilderClientRunChatflowTest() throws IOException, AppBuilderServerException { AppBuilderClient builder = new AppBuilderClient(chatflowAppId); String conversationId = builder.createConversation(); assertNotNull(conversationId); AppBuilderClientRunRequest request = new AppBuilderClientRunRequest(chatflowAppId, conversationId, "查天气", true); AppBuilderClientIterator itor = builder.run(request); assertTrue(itor.hasNext()); Stack interruptStack = new Stack(); String interruptEventId = ""; while (itor.hasNext()) { AppBuilderClientResult result = itor.next(); for (Event event : result.getEvents()) { if (event.getContentType().equals(EventContent.PublishMessageContentType)) { String message = event.getDetail().get("message").toString(); System.out.println(message); } if (event.getContentType().equals(EventContent.ChatflowInterruptContentType)) { assertEquals(event.getEventType(), Event.ChatflowEventType); interruptEventId = event.getDetail().get("interrupt_event_id").toString(); interruptStack.push(interruptEventId); break; } } } assert interruptEventId != null && !interruptEventId.isEmpty(); interruptEventId = ""; AppBuilderClientRunRequest request2 = new AppBuilderClientRunRequest(chatflowAppId, conversationId, "我先查个航班动态", true); request2.setAction(AppBuilderClientRunRequest.Action.createAction(interruptStack.pop())); AppBuilderClientIterator itor2 = builder.run(request2); assertTrue(itor2.hasNext()); while (itor2.hasNext()) { AppBuilderClientResult result2 = itor2.next(); for (Event event : result2.getEvents()) { if (event.getContentType().equals(EventContent.PublishMessageContentType)) { String message = event.getDetail().get("message").toString(); System.out.println(message); } if (event.getContentType().equals(EventContent.ChatflowInterruptContentType)) { assertEquals(event.getEventType(), Event.ChatflowEventType); interruptEventId = event.getDetail().get("interrupt_event_id").toString(); interruptStack.push(interruptEventId); break; } } } assert interruptEventId != null && !interruptEventId.isEmpty(); interruptEventId = ""; AppBuilderClientRunRequest request3 = new AppBuilderClientRunRequest(chatflowAppId, conversationId, "CA1234", true); request3.setAction(AppBuilderClientRunRequest.Action.createAction(interruptStack.pop())); AppBuilderClientIterator itor3 = builder.run(request3); assertTrue(itor3.hasNext()); while (itor3.hasNext()) { AppBuilderClientResult result3 = itor3.next(); for (Event event : result3.getEvents()) { if (event.getContentType().equals(EventContent.TextContentType)) { String text = event.getDetail().get("text").toString(); System.out.println(text); } if (event.getContentType().equals(EventContent.ChatflowInterruptContentType)) { assertEquals(event.getEventType(), Event.ChatflowEventType); interruptEventId = event.getDetail().get("interrupt_event_id").toString(); interruptStack.push(interruptEventId); break; } } } assert interruptEventId != null && !interruptEventId.isEmpty(); boolean hasMultipleContentType = false; AppBuilderClientRunRequest request4 = new AppBuilderClientRunRequest(chatflowAppId, conversationId, "北京的", true); request4.setAction(AppBuilderClientRunRequest.Action.createAction(interruptStack.pop())); AppBuilderClientIterator itor4 = builder.run(request4); assertTrue(itor4.hasNext()); while (itor4.hasNext()) { AppBuilderClientResult result4 = itor4.next(); for (Event event : result4.getEvents()) { if (event.getContentType().equals(EventContent.TextContentType)) { String text = event.getDetail().get("text").toString(); System.out.println(text); } if (event.getContentType().equals(EventContent.MultipleDialogEventContentType)) { assertEquals(event.getEventType(), Event.ChatflowEventType); hasMultipleContentType = true; break; } } } assertTrue(hasMultipleContentType); } @Test public void AppBuilderClientFeedbackTest() throws IOException, AppBuilderServerException { AppBuilderClient builder = new AppBuilderClient(followupqueryId); String conversationId = builder.createConversation(); assertNotNull(conversationId); String fileId = builder.uploadLocalFile(conversationId, "src/test/java/com/baidubce/appbuilder/files/test.pdf"); assertNotNull(fileId); AppBuilderClientIterator itor = builder.run("北京有多少小学生", conversationId, new String[] { fileId }, true); assertTrue(itor.hasNext()); String messageId = ""; while (itor.hasNext()) { AppBuilderClientResult result = itor.next(); messageId = result.getMessageId(); if (messageId != null && !messageId.isEmpty()) { break; } } AppBuilderClientFeedbackRequest request = new AppBuilderClientFeedbackRequest(followupqueryId, conversationId, messageId, "downvote", new String[] { "没有帮助" }, "测试"); AppBuilderClientFeedbackResponse result = builder.feedback(request); assertNotNull(result.getRequestId()); } @Test public void AppBuilderClientRunCustomMetadataTest() throws IOException, AppBuilderServerException { appId = "a3654cd9-378a-4b46-a33b-2259ca3b304e"; AppBuilderClient builder = new AppBuilderClient(appId); String conversationId = builder.createConversation(); assertNotNull(conversationId); AppBuilderClientRunRequest request = new AppBuilderClientRunRequest(appId, conversationId, "我要回老家相亲", false); AppBuilderClientRunRequest.CustomMetadata customMetadata = new AppBuilderClientRunRequest.CustomMetadata("这是自定义的role instruction"); customMetadata.setOverrideRoleInstruction("# 角色任务\n" + "作为高情商大师,你的主要任务是根据提问,做出最佳的建议。\n" + "\n" + "# 工具能力\n" + "\n" + "无工具集提供\n" + "\n" + "# 要求与限制\n" + "\n" + "1. 输出内容的风格为幽默\n" + "2.输出的字数限制为100字以内"); request.setCustomMetadata(customMetadata); AppBuilderClientIterator itor = builder.run(request); assertTrue(itor.hasNext()); while (itor.hasNext()) { AppBuilderClientResult result = itor.next(); System.out.println(result.getAnswer()); } } @Test public void AppBuilderClientClose()throws IOException, AppBuilderServerException{ String appId = "8badfd05-5e95-4115-9b21-4c86137f1fb9"; String text = "你是一位顶尖的跨学科专家,任务是解决一个高度复杂、信息不完整且具有现实模糊性的问题。请遵循以下原则进行深度、严谨、分阶段的思考:\n" + "不要急于给出结论。首先识别问题中的关键变量、隐含假设、潜在矛盾与信息缺口。\n" + "分阶段推理:\n" + "阶段一:解构问题,列出所有可能的解释框架(如经济学、系统论、博弈论、伦理学等);\n" + "阶段二:为每个框架构建逻辑链条,评估其适用性与局限性;\n" + "阶段三:整合多视角,识别交叉点与冲突点;\n" + "阶段四:提出一个稳健的综合方案,并明确其前提条件与风险边界。\n" + "主动质疑自身推理:在每一步,问自己:“这个假设是否可靠?是否有反例?是否有更底层的机制?”\n" + "量化不确定性:对关键判断标注置信度(如高/中/低),并说明依据。\n" + "最终输出必须包含:\n" + "核心洞见(1–2 句)\n" + "完整推理路径(分步骤,带编号)\n" + "未解决问题与进一步研究建议\n" + "对初始问题的重新定义(如果发现原问题表述有缺陷)\n" + "现在,请针对以下问题展开深度思考:在全球供应链高度脆弱的背景下,一家中国新能源车企应如何重构其电池原材料采购策略,以同时满足成本控制、地缘政治风险规避、ESG 合规与技术迭代加速四大目标?"; AppBuilderClient builder = new AppBuilderClient(appId); String conversationId = builder.createConversation(); AppBuilderClientIterator itor = builder.run(text, conversationId, new String[] {}, true); StringBuilder answer = new StringBuilder(); int a=1; while (itor.hasNext()) { if (a==50) { long start = System.currentTimeMillis(); itor.close(); long duration = System.currentTimeMillis() - start; System.out.println("duration: " + duration + "ms"); break; } AppBuilderClientResult response = itor.next(); answer.append(response.getAnswer()); a++; } System.out.println(answer); } } ================================================ FILE: java/src/test/java/com/baidubce/appbuilder/ComponentClientTest.java ================================================ package com.baidubce.appbuilder; import org.junit.Before; import org.junit.Test; import java.io.IOException; import java.util.HashMap; import java.util.Map; import static org.junit.Assert.*; import com.baidubce.appbuilder.base.exception.AppBuilderServerException; import com.baidubce.appbuilder.console.componentclient.ComponentClient; import com.baidubce.appbuilder.model.componentclient.ComponentClientIterator; import com.baidubce.appbuilder.model.componentclient.ComponentClientRunRequest; import com.baidubce.appbuilder.model.componentclient.ComponentClientRunResponse; public class ComponentClientTest { String componentId; @Before public void setUp() { System.setProperty("APPBUILDER_TOKEN", System.getenv("APPBUILDER_TOKEN")); System.setProperty("APPBUILDER_LOGLEVEL", "DEBUG"); componentId = "44205c67-3980-41f7-aad4-37357b577fd0"; } @Test public void TestComponentClientRun() throws IOException, AppBuilderServerException { ComponentClient client = new ComponentClient(); Map parameters = new HashMap<>(); parameters.put(ComponentClientRunRequest.SysOriginQuery, "北京景点推荐"); ComponentClientIterator iter = client.run(componentId, "latest", "", false, parameters); while (iter.hasNext()) { ComponentClientRunResponse response = iter.next(); assertNotNull(response.getContent()[0].getText()); } } @Test public void TestComponentClientRunStream() throws IOException, AppBuilderServerException { ComponentClient client = new ComponentClient(); Map parameters = new HashMap<>(); parameters.put(ComponentClientRunRequest.SysOriginQuery, "北京景点推荐"); ComponentClientIterator iter = client.run(componentId, "latest", "", true, parameters); Object text = null; while (iter.hasNext()) { ComponentClientRunResponse response = iter.next(); if (response.getContent().length > 0) { text = response.getContent()[0].getText(); } } assertNotNull(text); } @Test public void TestComponentClientHeaderRun() throws IOException, AppBuilderServerException { this.componentId = "c-wf-a39ee06c-808f-4a19-9f5f-544044283749"; ComponentClient client = new ComponentClient(); Map parameters = new HashMap<>(); parameters.put(ComponentClientRunRequest.SysOriginQuery, "梦到巨人"); ComponentClientIterator iter = client.run(componentId, "latest", "", false, parameters); while (iter.hasNext()) { ComponentClientRunResponse response = iter.next(); System.out.println((response.getContent()[0].getText().get("info"))); } } @Test public void TestComponentClientHeaderRunStream() throws IOException, AppBuilderServerException { this.componentId = "c-wf-a39ee06c-808f-4a19-9f5f-544044283749"; ComponentClient client = new ComponentClient(); Map parameters = new HashMap<>(); parameters.put(ComponentClientRunRequest.SysOriginQuery, "梦到巨人"); ComponentClientIterator iter = client.run(componentId, "latest", "", true, parameters); while (iter.hasNext()) { ComponentClientRunResponse response = iter.next(); if (response.getContent().length > 0) { System.out.println((response.getContent()[0].getText().get("info"))); } } } } ================================================ FILE: java/src/test/java/com/baidubce/appbuilder/DatasetTest.java ================================================ package com.baidubce.appbuilder; import static org.junit.Assert.*; import org.junit.Before; import org.junit.Test; import com.baidubce.appbuilder.base.exception.AppBuilderServerException; import com.baidubce.appbuilder.console.dataset.Dataset; import com.baidubce.appbuilder.model.dataset.DocumentListResponse; import java.io.IOException; import java.util.ArrayList; import java.util.Collections; public class DatasetTest { @Before public void setUp() { System.setProperty("APPBUILDER_TOKEN", System.getenv("APPBUILDER_TOKEN_V3")); } // @Test // public void testCreateDataset() throws IOException, AppBuilderServerException { // Dataset dataset = new Dataset(); // String datasetId = ""; // try { // datasetId = dataset.createDataset("dataset_name"); // assertNotNull(datasetId); // } catch (Exception e) { // datasetId = System.getenv("DATASET_ID_V3"); // dataset.setDatasetId(datasetId); // } // String filePath = "src/test/java/com/baidubce/appbuilder/files/test.pdf"; // String[] documentIds = dataset.addDocuments(new ArrayList<>(Collections.singletonList(filePath)), false, null, false); // assertNotEquals(documentIds.length, 0); // DocumentListResponse resp = dataset.getDocumentList(1, 20, ""); // assertNotEquals(resp.getResult().getTotal(), 0); // dataset.deleteDocuments(documentIds); // } } ================================================ FILE: java/src/test/java/com/baidubce/appbuilder/KnowledgebaseTest.java ================================================ package com.baidubce.appbuilder; import static org.junit.Assert.assertNotNull; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Paths; import org.junit.Before; import org.junit.Test; import com.baidubce.appbuilder.base.exception.AppBuilderServerException; import com.baidubce.appbuilder.console.knowledgebase.Knowledgebase; import com.baidubce.appbuilder.model.knowledgebase.*; import com.google.gson.Gson; import static org.junit.Assert.assertTrue; public class KnowledgebaseTest { @Before public void setUp() { System.setProperty("APPBUILDER_TOKEN", System.getenv("APPBUILDER_TOKEN_V3")); System.setProperty("APPBUILDER_LOGLEVEL", "DEBUG"); } @Test public void testAddDocument() throws IOException, AppBuilderServerException { String knowledgeBaseId = System.getenv("DATASET_ID_V3"); Knowledgebase knowledgebase = new Knowledgebase(); DocumentsDescribeRequest desribeDocumentsRequest = new DocumentsDescribeRequest(knowledgeBaseId, null, 10); knowledgebase.describeDocuments(desribeDocumentsRequest); DocumentListRequest listRequest = new DocumentListRequest(); listRequest.setKonwledgeBaseId(knowledgeBaseId); listRequest.setLimit(10); Document[] documents = knowledgebase.getDocumentList(listRequest); assertTrue(documents.length > 0); assertNotNull(documents[0].getId()); String fileId = knowledgebase.uploadFile("src/test/java/com/baidubce/appbuilder/files/test.pdf"); System.out.println(fileId); assertNotNull(fileId); DocumentAddRequest request = new DocumentAddRequest(); request.setKnowledgeBaseId(knowledgeBaseId); request.setContentType("raw_text"); request.setFileIds(new String[] {fileId}); DocumentAddRequest.CustomProcessRule customProcessRule = new DocumentAddRequest.CustomProcessRule(); customProcessRule.setSeparators(new String[] {"。"}); customProcessRule.setTargetLength(300); customProcessRule.setOverlapRate(0.25); request.setCustomProcessRule(customProcessRule); String[] documentsRes = knowledgebase.addDocument(request); // Ensure that documentsRes array is not empty assertTrue(documentsRes.length > 0); assertNotNull(documentsRes); DocumentDeleteRequest deleteRequest = new DocumentDeleteRequest(); deleteRequest.setKonwledgeBaseId(knowledgeBaseId); deleteRequest.setDocumentId(documentsRes[0]); knowledgebase.deleteDocument(deleteRequest); } @Test public void testCreateKnowledgebase() throws IOException, AppBuilderServerException { Knowledgebase knowledgebase = new Knowledgebase(); KnowledgeBaseDetail request = new KnowledgeBaseDetail(); request.setName("test_knowledgebase"); request.setDescription("test_knowledgebase"); // 创建知识库 KnowledgeBaseConfig.Index index = new KnowledgeBaseConfig.Index("public", "", "", "", ""); KnowledgeBaseConfig config = new KnowledgeBaseConfig(index); request.setConfig(config); String knowledgeBaseId = ""; boolean needDeleteKnowledgebase = false; try { KnowledgeBaseDetail response = knowledgebase.createKnowledgeBase(request); knowledgeBaseId = response.getId(); assertNotNull(response.getId()); needDeleteKnowledgebase = true; } catch (Exception e) { knowledgeBaseId = System.getenv("DATASET_ID_V3"); } // 获取知识库详情 KnowledgeBaseDetail detail = knowledgebase.getKnowledgeBaseDetail(knowledgeBaseId); System.out.println(detail.getId()); assertNotNull(detail.getId()); // 获取知识库列表 KnowledgeBaseListRequest listRequest = new KnowledgeBaseListRequest(knowledgeBaseId, 10, null); KnowledgeBaseListResponse knowledgeBases = knowledgebase.getKnowledgeBaseList(listRequest); System.out.println(knowledgeBases.getMarker()); assertNotNull(knowledgeBases.getMarker()); // 更新知识库 KnowledgeBaseModifyRequest modifyRequest = new KnowledgeBaseModifyRequest(); modifyRequest.setKnowledgeBaseId(knowledgeBaseId); modifyRequest.setName("test_knowledgebase2"); modifyRequest.setDescription(knowledgeBaseId); knowledgebase.modifyKnowledgeBase(modifyRequest); // 导入知识库 DocumentsCreateRequest.Source.UrlConfig[] urlConfigs = {new DocumentsCreateRequest.Source.UrlConfig(1)}; DocumentsCreateRequest.Source source = new DocumentsCreateRequest.Source("web", new String[] {"https://baijiahao.baidu.com/s?id=1802527379394162441"}, 1, urlConfigs); DocumentsCreateRequest.ProcessOption.Parser parser = new DocumentsCreateRequest.ProcessOption.Parser( new String[] {"layoutAnalysis", "ocr"}); DocumentsCreateRequest.ProcessOption.Chunker.Separator separator = new DocumentsCreateRequest.ProcessOption.Chunker.Separator(new String[] {"。"}, 300, 0.25); DocumentsCreateRequest.ProcessOption.Chunker chunker = new DocumentsCreateRequest.ProcessOption.Chunker(new String[] {"separator"}, separator, null, new String[] {"title", "filename"}); DocumentsCreateRequest.ProcessOption.KnowledgeAugmentation knowledgeAugmentation = new DocumentsCreateRequest.ProcessOption.KnowledgeAugmentation( new String[] {"faq"}); DocumentsCreateRequest.ProcessOption processOption = new DocumentsCreateRequest.ProcessOption("custom", parser, chunker, knowledgeAugmentation); DocumentsCreateRequest documentsCreateRequest = new DocumentsCreateRequest(knowledgeBaseId, "rawText", source, processOption); DocumentsCreateResponse documentsCreateResponse = knowledgebase.createDocuments(documentsCreateRequest); assertNotNull(documentsCreateResponse.getDocumentIds()); // 上传文档 String filePath = "src/test/java/com/baidubce/appbuilder/files/test.pdf"; DocumentsCreateRequest.Source source2 = new DocumentsCreateRequest.Source("file", null, null); DocumentsCreateRequest documentsCreateRequest2 = new DocumentsCreateRequest(knowledgeBaseId, "rawText", source2, processOption); DocumentsUploadResponse documentsUploadResponse = knowledgebase.uploadDocuments(filePath, documentsCreateRequest2); assertNotNull(documentsUploadResponse.getDocumentId()); // 删除知识库 if(needDeleteKnowledgebase) { knowledgebase.deleteKnowledgeBase(knowledgeBaseId); } } @Test public void testCreateChunk() throws IOException, AppBuilderServerException { String knowledgeBaseID = System.getenv("DATASET_ID"); String secretKey = System.getenv("APPBUILDER_TOKEN"); Knowledgebase knowledgebase = new Knowledgebase(knowledgeBaseID, secretKey); DocumentListRequest listRequest = new DocumentListRequest(); listRequest.setKonwledgeBaseId(knowledgeBaseID); listRequest.setLimit(10); Document[] documents = knowledgebase.getDocumentList(listRequest); String documentId = documents[0].getId(); // 创建切片 String chunkId = knowledgebase.createChunk(documentId, "test"); // 修改切片 knowledgebase.modifyChunk(chunkId, "new test", true); // 获取切片详情 knowledgebase.describeChunk(chunkId); // 获取切片列表 knowledgebase.describeChunks(documentId, chunkId, 10, null); // 获取切片列表 ChunksDescribeRequest request = new ChunksDescribeRequest(knowledgeBaseID, documentId, null, 10, null, "test"); knowledgebase.describeChunks(request); try { // 延时 Thread.sleep(10000); } catch (InterruptedException e) { e.printStackTrace(); } // 删除切片 knowledgebase.deleteChunk(chunkId); } @Test public void testQueryKnowledgeBase() throws IOException, AppBuilderServerException { System.setProperty("APPBUILDER_TOKEN", System.getenv("APPBUILDER_TOKEN")); Knowledgebase knowledgebase = new Knowledgebase(); // 查询知识库 Gson gson = new Gson(); String requestJson = new String( Files.readAllBytes(Paths.get("src/test/java/com/baidubce/appbuilder/files/query_knowledgebase.json"))); QueryKnowledgeBaseRequest request = gson.fromJson(requestJson, QueryKnowledgeBaseRequest.class); QueryKnowledgeBaseResponse response = knowledgebase.queryKnowledgeBase(request); assertNotNull(response.getChunks().get(0).getChunk_id()); } @Test public void testQueryKnowledgeBaseV2() throws IOException, AppBuilderServerException { System.setProperty("APPBUILDER_TOKEN", System.getenv("APPBUILDER_TOKEN")); Knowledgebase knowledgebase = new Knowledgebase(); // 查询知识库 Gson gson = new Gson(); String requestJson = new String( Files.readAllBytes(Paths.get("src/test/java/com/baidubce/appbuilder/files/query_knowledgebase.json"))); QueryKnowledgeBaseRequest request = gson.fromJson(requestJson, QueryKnowledgeBaseRequest.class); QueryKnowledgeBaseResponse response = knowledgebase.queryKnowledgeBase(request.getQuery(), request.getType(), request.getRank_score_threshold(), request.getTop(), request.getSkip(), request.getKnowledgebase_ids(), request.getMetadata_filters(), request.getPipeline_config()); assertNotNull(response.getChunks().get(0).getChunk_id()); } } ================================================ FILE: java/src/test/java/com/baidubce/appbuilder/RAGTest.java ================================================ package com.baidubce.appbuilder; import org.junit.Before; import org.junit.Test; import static org.junit.Assert.assertTrue; import java.io.IOException; import com.baidubce.appbuilder.base.exception.AppBuilderServerException; import com.baidubce.appbuilder.console.rag.RAG; import com.baidubce.appbuilder.model.rag.RAGResponse; import com.baidubce.appbuilder.model.rag.RAGIterator; import com.baidubce.appbuilder.console.agentbuilder.AgentBuilder; public class RAGTest { String appId; @Before public void setUp() { System.setProperty("APPBUILDER_TOKEN", System.getenv("APPBUILDER_TOKEN_V3")); appId = "aa8af334-df27-4855-b3d1-0d249c61fc08"; } /* @Test public void testRAG() throws IOException, AppBuilderServerException { AgentBuilder builder = new AgentBuilder(appId); String conversationId = builder.createConversation(); RAG rag = new RAG(appId); RAGIterator itor = rag.run("合同中的甲方是谁?", conversationId, true); assertTrue(itor.hasNext()); while (itor.hasNext()) { RAGResponse response = itor.next(); } }*/ } ================================================ FILE: java/src/test/java/com/baidubce/appbuilder/base/exception/AppBuilderServerExceptionTest.java ================================================ package com.baidubce.appbuilder.base.exception; import org.junit.Test; import static org.junit.Assert.*; public class AppBuilderServerExceptionTest { @Test public void testConstructorWithBasicFields() { AppBuilderServerException exception = new AppBuilderServerException("request123", 500, "Internal Server Error"); assertEquals("request123", exception.getRequestId()); assertEquals(500, exception.getCode()); assertEquals("Internal Server Error", exception.getMessage()); assertEquals(0, exception.getAppbuilderCode()); // default value assertNull(exception.getAppbuilderMessage()); assertNull(exception.getResponseBody()); } @Test public void testConstructorWithAppbuilderFields() { AppBuilderServerException exception = new AppBuilderServerException("request456", 400, "Bad Request", 1001, "Invalid parameter"); assertEquals("request456", exception.getRequestId()); assertEquals(400, exception.getCode()); assertEquals("Bad Request", exception.getMessage()); assertEquals(1001, exception.getAppbuilderCode()); assertEquals("Invalid parameter", exception.getAppbuilderMessage()); assertNull(exception.getResponseBody()); } @Test public void testConstructorWithResponseBody() { AppBuilderServerException exception = new AppBuilderServerException("request789", 404, "Not Found", "Response body content"); assertEquals("request789", exception.getRequestId()); assertEquals(404, exception.getCode()); assertEquals("Not Found", exception.getMessage()); assertEquals("Response body content", exception.getResponseBody()); assertEquals(0, exception.getAppbuilderCode()); // default value assertNull(exception.getAppbuilderMessage()); } @Test public void testToString() { AppBuilderServerException exception = new AppBuilderServerException("request101", 401, "Unauthorized", 2002, "Access denied"); exception.toString(); String expectedString = "AppBuilderServerException{" + "requestId='request101'" + ", code=401" + ", message='Unauthorized'" + ", appbuilderCode=2002" + ", appbuilderMessage='Access denied'" + ", responseBody='null'" + '}'; assertEquals(expectedString, exception.toString()); } } ================================================ FILE: java/src/test/java/com/baidubce/appbuilder/base/utils/json/JsonUtilsTest.java ================================================ package com.baidubce.appbuilder.base.utils.json; import com.google.gson.reflect.TypeToken; import org.junit.Test; import static org.junit.Assert.assertEquals; import java.util.Map; public class JsonUtilsTest { @Test public void testSerialize() { // 准备测试数据 TestObject testObject = new TestObject("example", 123); // 进行序列化 String json = JsonUtils.serialize(testObject); // 期望的JSON字符串 String expectedJson = "{\"name\":\"example\",\"value\":123}"; // 验证结果 assertEquals(expectedJson, json); } @Test public void testDeserialize() { // 准备JSON字符串 String json = "{\"name\":\"example\",\"value\":123}"; // 进行反序列化 TestObject testObject = JsonUtils.deserialize(json, TestObject.class); // 验证结果 assertEquals("example", testObject.getName()); assertEquals(123, testObject.getValue()); } @Test public void testDeserializeToMap() { // 准备JSON字符串 String json = "{\"key1\":\"value1\",\"key2\":\"value2\"}"; // 进行反序列化到Map Map map = JsonUtils.deserialize(json, new TypeToken>(){}.getType()); // 验证结果 assertEquals("value1", map.get("key1")); assertEquals("value2", map.get("key2")); } // 内部类用于测试对象 static class TestObject { private String name; private int value; public TestObject(String name, int value) { this.name = name; this.value = value; } public String getName() { return name; } public int getValue() { return value; } } } ================================================ FILE: java/src/test/java/com/baidubce/appbuilder/files/query_knowledgebase.json ================================================ { "type": "fulltext", "query": "民法典第三条", "knowledgebase_ids": [ "70c6375a-1595-41f2-9a3b-e81bc9060b7f" ], "metadata_filters": { "filters": [], "condition": "or" }, "pipeline_config": { "id": "pipeline_001", "pipeline": [ { "name": "step1", "type": "elastic_search", "threshold": 0.1, "top": 400, "pre_ranking": { "bm25_weight": 0.25, "vec_weight": 0.75, "bm25_b": 0.75, "bm25_k1": 1.5, "bm25_max_score": 50 } }, { "name": "step2", "type": "ranking", "inputs": [ "step1" ], "model_name": "ranker-v1", "top": 20 } ] }, "top": 5, "skip": 0 } ================================================ FILE: java/src/test/java/com/baidubce/appbuilder/files/toolcall.json ================================================ { "type": "function", "function": { "name": "get_cur_whether", "description": "这是一个获得指定地点天气的工具", "parameters": { "type": "object", "properties": { "location": { "type": "string", "description": "省,市名,例如:河北省" }, "unit": { "type": "string", "enum": [ "摄氏度", "华氏度" ] } }, "required": [ "location" ] } } } ================================================ FILE: java/src/test/java/com/baidubce/appbuilder/model/agentbuilder/AgentBuilderResponseTest.java ================================================ package com.baidubce.appbuilder.model.agentbuilder; import org.junit.Before; import org.junit.Test; import static org.junit.Assert.*; public class AgentBuilderResponseTest { private AgentBuilderResponse response; @Before public void setUp() { response = new AgentBuilderResponse(); } @Test public void testRequestId() { response.setRequestId("test_request_id"); assertEquals("test_request_id", response.getRequestId()); } @Test public void testData() { response.setData("test_data"); assertEquals("test_data", response.getData()); } @Test public void testAnswer() { response.setAnswer("test_answer"); assertEquals("test_answer", response.getAnswer()); } @Test public void testConversationId() { response.setConversationId("test_conversation_id"); assertEquals("test_conversation_id", response.getConversationId()); } @Test public void testMessageId() { response.setMessageId("test_message_id"); assertEquals("test_message_id", response.getMessageId()); } @Test public void testIsCompletion() { response.setCompletion(true); assertTrue(response.isCompletion()); response.setCompletion(false); assertFalse(response.isCompletion()); } @Test public void testContent() { EventContent[] contentArray = new EventContent[1]; response.setContent(contentArray); assertArrayEquals(contentArray, response.getContent()); } @Test public void testToString() { response.setRequestId("test_request_id"); response.setData("test_data"); response.setAnswer("test_answer"); response.setConversationId("test_conversation_id"); response.setMessageId("test_message_id"); response.setCompletion(true); EventContent[] contentArray = new EventContent[1]; response.setContent(contentArray); String expectedString = "AgentBuilderResponse{" + "requestId='test_request_id', data='test_data', answer='test_answer', " + "conversationId='test_conversation_id', messageId='test_message_id', " + "isCompletion=true, content=[null]}"; assertEquals(expectedString, response.toString()); } @Test public void testNullContent() { response.setContent(null); assertNull(response.getContent()); } } ================================================ FILE: java/src/test/java/com/baidubce/appbuilder/model/agentbuilder/AgentBuilderResultTest.java ================================================ package com.baidubce.appbuilder.model.agentbuilder; import org.junit.Before; import org.junit.Test; import static org.junit.Assert.*; public class AgentBuilderResultTest { private AgentBuilderResult agentBuilderResult; private Event event1; private Event event2; @Before public void setUp() { agentBuilderResult = new AgentBuilderResult(); // Initialize Event objects event1 = new Event().setCode("eventCode1").setMessage("First event"); event2 = new Event().setCode("eventCode2").setMessage("Second event"); agentBuilderResult.setAnswer("This is an answer") .setEvents(new Event[]{event1, event2}); } @Test public void testGetAnswer() { assertEquals("This is an answer", agentBuilderResult.getAnswer()); } @Test public void testGetEvents() { Event[] events = agentBuilderResult.getEvents(); assertNotNull(events); assertEquals(2, events.length); assertEquals("eventCode1", events[0].getCode()); assertEquals("First event", events[0].getMessage()); assertEquals("eventCode2", events[1].getCode()); assertEquals("Second event", events[1].getMessage()); } @Test public void testToString() { String expectedString = "AgentBuilderResult{" + "answer='This is an answer'" + ", events=[Event{code='eventCode1', message='First event', eventType='null', status='null', contentType='null', detail=null}, " + "Event{code='eventCode2', message='Second event', eventType='null', status='null', contentType='null', detail=null}]" + '}'; assertEquals(expectedString, agentBuilderResult.toString()); } } ================================================ FILE: java/src/test/java/com/baidubce/appbuilder/model/agentbuilder/ConversationResponseTest.java ================================================ package com.baidubce.appbuilder.model.agentbuilder; import org.junit.Before; import org.junit.Test; import static org.junit.Assert.*; public class ConversationResponseTest { private ConversationResponse conversationResponse; @Before public void setUp() { conversationResponse = new ConversationResponse(); conversationResponse.setRequestId("testRequestId"); conversationResponse.setConversationId("testConversationId"); } @Test public void testRequestId() { assertEquals("testRequestId", conversationResponse.getRequestId()); } @Test public void testConversationId() { assertEquals("testConversationId", conversationResponse.getConversationId()); } @Test public void testToString() { String expectedString = "ConversationResponse{" + "requestId='testRequestId', conversationId='testConversationId'}"; assertEquals(expectedString, conversationResponse.toString()); } } ================================================ FILE: java/src/test/java/com/baidubce/appbuilder/model/agentbuilder/EventContentTest.java ================================================ package com.baidubce.appbuilder.model.agentbuilder; import org.junit.Before; import org.junit.Test; import java.util.HashMap; import java.util.Map; import static org.junit.Assert.*; public class EventContentTest { private EventContent eventContent; @Before public void setUp() { eventContent = new EventContent(); Map outputs = new HashMap<>(); outputs.put("key1", "value1"); outputs.put("key2", 100); eventContent.setEventCode("event123"); eventContent.setEnentMessage("Event message"); eventContent.setEventType("EventType"); eventContent.setEventId("eventId123"); eventContent.setEventStatus("success"); eventContent.setContentType("application/json"); eventContent.setOutputs(outputs); } @Test public void testEventCode() { assertEquals("event123", eventContent.getEventCode()); } @Test public void testEnentMessage() { assertEquals("Event message", eventContent.getEnentMessage()); } @Test public void testEventType() { assertEquals("EventType", eventContent.getEventType()); } @Test public void testEventId() { assertEquals("eventId123", eventContent.getEventId()); } @Test public void testEventStatus() { assertEquals("success", eventContent.getEventStatus()); } @Test public void testContentType() { assertEquals("application/json", eventContent.getContentType()); } @Test public void testOutputs() { Map outputs = eventContent.getOutputs(); assertNotNull(outputs); assertEquals(2, outputs.size()); assertEquals("value1", outputs.get("key1")); assertEquals(100, outputs.get("key2")); } @Test public void testToString() { String expectedString = "EventContent{" + "eventCode='event123'" + ", enentMessage='Event message'" + ", eventType='EventType'" + ", eventId='eventId123'" + ", eventStatus='success'" + ", contentType='application/json'" + ", outputs={key1=value1, key2=100}" + '}'; assertEquals(expectedString, eventContent.toString()); } } ================================================ FILE: java/src/test/java/com/baidubce/appbuilder/model/agentbuilder/EventTest.java ================================================ package com.baidubce.appbuilder.model.agentbuilder; import org.junit.Before; import org.junit.Test; import java.util.HashMap; import java.util.Map; import static org.junit.Assert.*; public class EventTest { private Event event; @Before public void setUp() { event = new Event(); Map detail = new HashMap<>(); detail.put("key1", "value1"); detail.put("key2", 100); event.setCode("eventCode123") .setMessage("Event occurred") .setEventType("eventType") .setStatus("success") .setContentType("application/json") .setDetail(detail); } @Test public void testCode() { assertEquals("eventCode123", event.getCode()); } @Test public void testMessage() { assertEquals("Event occurred", event.getMessage()); } @Test public void testEventType() { assertEquals("eventType", event.getEventType()); } @Test public void testStatus() { assertEquals("success", event.getStatus()); } @Test public void testContentType() { assertEquals("application/json", event.getContentType()); } @Test public void testDetail() { Map detail = event.getDetail(); assertNotNull(detail); assertEquals(2, detail.size()); assertEquals("value1", detail.get("key1")); assertEquals(100, detail.get("key2")); } @Test public void testToString() { String expectedString = "Event{" + "code='eventCode123'" + ", message='Event occurred'" + ", eventType='eventType'" + ", status='success'" + ", contentType='application/json'" + ", detail={key1=value1, key2=100}" + '}'; assertEquals(expectedString, event.toString()); } } ================================================ FILE: java/src/test/java/com/baidubce/appbuilder/model/agentbuilder/FileUploadResponseTest.java ================================================ package com.baidubce.appbuilder.model.agentbuilder; import org.junit.Before; import org.junit.Test; import static org.junit.Assert.*; public class FileUploadResponseTest { private FileUploadResponse fileUploadResponse; @Before public void setUp() { fileUploadResponse = new FileUploadResponse(); fileUploadResponse.setRequestId("testRequestId"); fileUploadResponse.setFileId("testFileId"); fileUploadResponse.setConversationId("testConversationId"); } @Test public void testGetRequestId() { assertEquals("testRequestId", fileUploadResponse.getRequestId()); } @Test public void testGetFileId() { assertEquals("testFileId", fileUploadResponse.getFileId()); } @Test public void testGetConversationId() { assertEquals("testConversationId", fileUploadResponse.getConversationId()); } @Test public void testToString() { String expectedString = "FileUploadResponse{" + "requestId='testRequestId'" + ", fileId='testFileId'" + ", conversationId='testConversationId'" + '}'; assertEquals(expectedString, fileUploadResponse.toString()); } } ================================================ FILE: java/src/test/java/com/baidubce/appbuilder/model/appbuilderclient/AppBuilderClientResponseTest.java ================================================ package com.baidubce.appbuilder.model.appbuilderclient; import org.junit.Before; import org.junit.Test; import static org.junit.Assert.*; public class AppBuilderClientResponseTest { private AppBuilderClientResponse response; @Before public void setUp() { response = new AppBuilderClientResponse(); } @Test public void testRequestId() { response.setRequestId("test_request_id"); assertEquals("test_request_id", response.getRequestId()); } @Test public void testData() { response.setData("test_data"); assertEquals("test_data", response.getData()); } @Test public void testAnswer() { response.setAnswer("test_answer"); assertEquals("test_answer", response.getAnswer()); } @Test public void testConversationId() { response.setConversationId("test_conversation_id"); assertEquals("test_conversation_id", response.getConversationId()); } @Test public void testMessageId() { response.setMessageId("test_message_id"); assertEquals("test_message_id", response.getMessageId()); } @Test public void testIsCompletion() { response.setCompletion(true); assertTrue(response.isCompletion()); } @Test public void testContent() { EventContent[] contentArray = new EventContent[1]; response.setContent(contentArray); assertArrayEquals(contentArray, response.getContent()); } @Test public void testToString() { response.setRequestId("test_request_id"); response.setDate("test_date"); response.setAnswer("test_answer"); response.setConversationId("test_conversation_id"); response.setMessageId("test_message_id"); response.setCompletion(true); EventContent[] contentArray = new EventContent[1]; response.setContent(contentArray); String expectedString = "AgentBuilderResponse{" + "requestId='test_request_id', date='test_date', answer='test_answer', " + "conversationId='test_conversation_id', messageId='test_message_id', " + "isCompletion=true, content=[null]}"; assertEquals(expectedString, response.toString()); } } ================================================ FILE: java/src/test/java/com/baidubce/appbuilder/model/appbuilderclient/AppBuilderClientRunRequestTest.java ================================================ package com.baidubce.appbuilder.model.appbuilderclient; import org.junit.Before; import org.junit.Test; import static org.junit.Assert.*; import java.util.HashMap; import java.util.Map; public class AppBuilderClientRunRequestTest { private AppBuilderClientRunRequest request; private AppBuilderClientRunRequest.Tool tool; private AppBuilderClientRunRequest.Tool.Function toolFunction; private AppBuilderClientRunRequest.ToolOutput toolOutput; private AppBuilderClientRunRequest.ToolChoice toolChoice; private AppBuilderClientRunRequest.ToolChoice.Function toolChoiceFunction; @Before public void setUp() { // Initialize Tool and Tool.Function Map parameters = new HashMap<>(); parameters.put("param1", "value1"); toolFunction = new AppBuilderClientRunRequest.Tool.Function("testFunction", "testDescription", parameters); tool = new AppBuilderClientRunRequest.Tool("testType", toolFunction); // Initialize ToolOutput toolOutput = new AppBuilderClientRunRequest.ToolOutput("toolCallID1", "output1"); // Initialize ToolChoice and ToolChoice.Function Map input = new HashMap<>(); input.put("input1", "value1"); toolChoiceFunction = new AppBuilderClientRunRequest.ToolChoice.Function("choiceFunction", input); toolChoice = new AppBuilderClientRunRequest.ToolChoice("choiceType", toolChoiceFunction); // Initialize main class request = new AppBuilderClientRunRequest(); request.setAppId("testAppId"); request.setQuery("testQuery"); request.setStream(true); request.setConversationID("testConversationId"); request.setEndUserId("testEndUserId"); request.setTools(new AppBuilderClientRunRequest.Tool[]{tool}); request.setToolOutputs(new AppBuilderClientRunRequest.ToolOutput[]{toolOutput}); request.setToolChoice(toolChoice); } @Test public void testAppId() { assertEquals("testAppId", request.getAppId()); } @Test public void testQuery() { assertEquals("testQuery", request.getQuery()); } @Test public void testStream() { assertTrue(request.isStream()); } @Test public void testConversationID() { assertEquals("testConversationId", request.getConversationID()); } @Test public void testEndUserId() { assertEquals("testEndUserId", request.getEndUserId()); } @Test public void testTools() { assertEquals(1, request.getTools().length); assertEquals("testType", request.getTools()[0].getType()); assertEquals("testFunction", request.getTools()[0].getFunction().getName()); assertEquals("testDescription", request.getTools()[0].getFunction().getDescription()); assertEquals("value1", request.getTools()[0].getFunction().getParameters().get("param1")); } @Test public void testToolOutputs() { assertEquals(1, request.getToolOutputs().length); assertEquals("toolCallID1", request.getToolOutputs()[0].getToolCallID()); assertEquals("output1", request.getToolOutputs()[0].getOutput()); } @Test public void testToolChoice() { assertEquals("choiceType", request.getToolChoice().getType()); assertEquals("choiceFunction", request.getToolChoice().getFunction().getName()); assertEquals("value1", request.getToolChoice().getFunction().getInput().get("input1")); } @Test public void testToolFunction() { assertEquals("testFunction", toolFunction.getName()); assertEquals("testDescription", toolFunction.getDescription()); assertEquals("value1", toolFunction.getParameters().get("param1")); } @Test public void testToolChoiceFunction() { assertEquals("choiceFunction", toolChoiceFunction.getName()); assertEquals("value1", toolChoiceFunction.getInput().get("input1")); } } ================================================ FILE: java/src/test/java/com/baidubce/appbuilder/model/appbuilderclient/AppListRequestTest.java ================================================ package com.baidubce.appbuilder.model.appbuilderclient; import org.junit.Before; import org.junit.Test; import java.util.Map; import static org.junit.Assert.*; public class AppListRequestTest { private AppListRequest appListRequest; @Before public void setUp() { appListRequest = new AppListRequest(); } @Test public void testGetLimit() { appListRequest.setLimit(10); assertEquals(10, appListRequest.getLimit()); } @Test public void testSetLimit() { appListRequest.setLimit(20); assertEquals(20, appListRequest.getLimit()); } @Test public void testGetAfter() { appListRequest.setAfter("afterValue"); assertEquals("afterValue", appListRequest.getAfter()); } @Test public void testSetAfter() { appListRequest.setAfter("newAfterValue"); assertEquals("newAfterValue", appListRequest.getAfter()); } @Test public void testGetBefore() { appListRequest.setBefore("beforeValue"); assertEquals("beforeValue", appListRequest.getBefore()); } @Test public void testSetBefore() { appListRequest.setBefore("newBeforeValue"); assertEquals("newBeforeValue", appListRequest.getBefore()); } @Test public void testToMap_WithLimit() { appListRequest.setLimit(15); appListRequest.setAfter("afterExample"); appListRequest.setBefore("beforeExample"); Map resultMap = appListRequest.toMap(); assertNotNull(resultMap); assertEquals(3, resultMap.size()); assertEquals(15, resultMap.get("limit")); assertEquals("afterExample", resultMap.get("after")); assertEquals("beforeExample", resultMap.get("before")); } @Test public void testToMap_WithoutLimit() { appListRequest.setAfter("afterExample"); appListRequest.setBefore("beforeExample"); Map resultMap = appListRequest.toMap(); assertNotNull(resultMap); assertEquals(2, resultMap.size()); assertNull(resultMap.get("limit")); assertEquals("afterExample", resultMap.get("after")); assertEquals("beforeExample", resultMap.get("before")); } } ================================================ FILE: java/src/test/java/com/baidubce/appbuilder/model/appbuilderclient/AppListResponseTest.java ================================================ package com.baidubce.appbuilder.model.appbuilderclient; import org.junit.Before; import org.junit.Test; import static org.junit.Assert.assertEquals; public class AppListResponseTest { private AppListResponse appListResponse; @Before public void setUp() { appListResponse = new AppListResponse(); } @Test public void testGetSetRequestId() { appListResponse.setRequestId("req123"); assertEquals("req123", appListResponse.getRequestId()); } @Test public void testGetSetData() { App[] apps = new App[2]; apps[0] = new App(); // Assuming App class has a default constructor apps[1] = new App(); appListResponse.setData(apps); assertEquals(apps, appListResponse.getData()); } @Test public void testGetSetCode() { appListResponse.setCode("200"); assertEquals("200", appListResponse.getCode()); } @Test public void testGetSetMessage() { appListResponse.setMessage("Success"); assertEquals("Success", appListResponse.getMessage()); } } ================================================ FILE: java/src/test/java/com/baidubce/appbuilder/model/appbuilderclient/AppTest.java ================================================ package com.baidubce.appbuilder.model.appbuilderclient; import org.junit.Before; import org.junit.Test; import static org.junit.Assert.assertEquals; public class AppTest { private App app; @Before public void setUp() { app = new App(); } @Test public void testSetGetId() { app.setId("app123"); assertEquals("app123", app.getId()); } @Test public void testSetGetName() { app.setName("Test App"); assertEquals("Test App", app.getName()); } @Test public void testSetGetDescription() { app.setDescription("This is a test app."); assertEquals("This is a test app.", app.getDescription()); } } ================================================ FILE: java/src/test/java/com/baidubce/appbuilder/model/appbuilderclient/ConversationResponseTest.java ================================================ package com.baidubce.appbuilder.model.appbuilderclient; import org.junit.Before; import org.junit.Test; import static org.junit.Assert.assertEquals; public class ConversationResponseTest { private ConversationResponse conversationResponse; @Before public void setUp() { conversationResponse = new ConversationResponse(); } @Test public void testSetGetRequestId() { conversationResponse.setRequestId("req123"); assertEquals("req123", conversationResponse.getRequestId()); } @Test public void testSetGetConversationId() { conversationResponse.setConversationId("conv456"); assertEquals("conv456", conversationResponse.getConversationId()); } @Test public void testToString() { conversationResponse.setRequestId("req123"); conversationResponse.setConversationId("conv456"); String expected = "ConversationResponse{" + "requestId='req123'" + ", conversationId='conv456'" + '}'; assertEquals(expected, conversationResponse.toString()); } } ================================================ FILE: java/src/test/java/com/baidubce/appbuilder/model/appbuilderclient/EventContentTest.java ================================================ package com.baidubce.appbuilder.model.appbuilderclient; import org.junit.Before; import org.junit.Test; import java.util.HashMap; import java.util.Map; import static org.junit.Assert.*; public class EventContentTest { private EventContent eventContent; private ToolCall[] toolCalls; @Before public void setUp() { eventContent = new EventContent(); toolCalls = new ToolCall[]{new ToolCall(), new ToolCall()}; } @Test public void testGetSetEventCode() { eventContent.setEventCode("event123"); assertEquals("event123", eventContent.getEventCode()); } @Test public void testGetSetEventMessage() { eventContent.setEnentMessage("message123"); assertEquals("message123", eventContent.getEnentMessage()); } @Test public void testGetSetEventType() { eventContent.setEventType("eventType123"); assertEquals("eventType123", eventContent.getEventType()); } @Test public void testGetSetEventId() { eventContent.setEventId("eventId123"); assertEquals("eventId123", eventContent.getEventId()); } @Test public void testGetSetEventStatus() { eventContent.setEventStatus("status123"); assertEquals("status123", eventContent.getEventStatus()); } @Test public void testGetSetContentType() { eventContent.setContentType("contentType123"); assertEquals("contentType123", eventContent.getContentType()); } @Test public void testGetSetOutputs() { Map outputs = new HashMap<>(); outputs.put("key", "value"); eventContent.setOutputs(outputs); assertEquals(outputs, eventContent.getOutputs()); } @Test public void testGetSetUsage() { Map usage = new HashMap<>(); usage.put("cpu", "80%"); eventContent.setUsage(usage); assertEquals(usage, eventContent.getUsage()); } @Test public void testGetSetToolCalls() { eventContent.setToolCalls(toolCalls); assertArrayEquals(toolCalls, eventContent.getToolCalls()); } @Test public void testToString() { eventContent.setEventCode("event123"); eventContent.setEnentMessage("message123"); eventContent.setEventType("eventType123"); eventContent.setEventId("eventId123"); eventContent.setEventStatus("status123"); eventContent.setContentType("contentType123"); String expected = "EventContent{eventCode='event123', eventMessage='message123', eventType='eventType123', eventId='eventId123', eventStatus='status123', contentType='contentType123', outputs=null'usage=null', toolCalls=null}"; assertEquals(expected, eventContent.toString()); } } ================================================ FILE: java/src/test/java/com/baidubce/appbuilder/model/appbuilderclient/EventTest.java ================================================ package com.baidubce.appbuilder.model.appbuilderclient; import org.junit.Before; import org.junit.Test; import java.util.HashMap; import java.util.Map; import static org.junit.Assert.assertEquals; public class EventTest { private Event event; private Map detail; private Map usage; private ToolCall[] toolCalls; @Before public void setUp() { detail = new HashMap<>(); detail.put("key1", "value1"); usage = new HashMap<>(); usage.put("usageKey", "usageValue"); toolCalls = new ToolCall[2]; toolCalls[0] = new ToolCall(); // 假设 ToolCall 类有默认构造函数 toolCalls[1] = new ToolCall(); event = new Event() .setCode("200") .setMessage("Success") .setEventType("eventType") .setStatus("completed") .setContentType("application/json") .setDetail(detail) .setUsage(usage) .setToolCalls(toolCalls); } @Test public void testGetCode() { assertEquals("200", event.getCode()); } @Test public void testGetMessage() { assertEquals("Success", event.getMessage()); } @Test public void testGetEventType() { assertEquals("eventType", event.getEventType()); } @Test public void testGetStatus() { assertEquals("completed", event.getStatus()); } @Test public void testGetContentType() { assertEquals("application/json", event.getContentType()); } @Test public void testGetDetail() { assertEquals(detail, event.getDetail()); } @Test public void testGetUsage() { assertEquals(usage, event.getUsage()); } @Test public void testGetToolCalls() { assertEquals(toolCalls, event.getToolCalls()); } @Test public void testToString() { String expected = "Event{" + "code='200'" + ", message='Success'" + ", eventType='eventType'" + ", status='completed'" + ", contentType='application/json'" + ", detail=" + detail + '\'' + ", usage=" + usage + '\'' + ", toolCalls=" + toolCalls + '}'; assertEquals(expected, event.toString()); } } ================================================ FILE: java/src/test/java/com/baidubce/appbuilder/model/appbuilderclient/FileUploadResponseTest.java ================================================ package com.baidubce.appbuilder.model.appbuilderclient; import org.junit.Before; import org.junit.Test; import static org.junit.Assert.assertEquals; public class FileUploadResponseTest { private FileUploadResponse fileUploadResponse; @Before public void setUp() { fileUploadResponse = new FileUploadResponse(); } @Test public void testSetGetRequestId() { fileUploadResponse.setRequestId("request123"); assertEquals("request123", fileUploadResponse.getRequestId()); } @Test public void testSetGetFileId() { fileUploadResponse.setFileId("file456"); assertEquals("file456", fileUploadResponse.getFileId()); } @Test public void testSetGetConversationId() { fileUploadResponse.setConversationId("conversation789"); assertEquals("conversation789", fileUploadResponse.getConversationId()); } @Test public void testToString() { fileUploadResponse.setRequestId("request123"); fileUploadResponse.setFileId("file456"); fileUploadResponse.setConversationId("conversation789"); String expected = "FileUploadResponse{" + "requestId='request123'" + ", fileId='file456'" + ", conversationId='conversation789'" + '}'; assertEquals(expected, fileUploadResponse.toString()); } } ================================================ FILE: java/src/test/java/com/baidubce/appbuilder/model/appbuilderclient/ToolCallTest.java ================================================ package com.baidubce.appbuilder.model.appbuilderclient; import org.junit.Before; import org.junit.Test; import static org.junit.Assert.*; public class ToolCallTest { private ToolCall toolCall; @Before public void setUp() { toolCall = new ToolCall(); } @Test public void testGetId() { toolCall.setId("testId"); assertEquals("testId", toolCall.getId()); } @Test public void testSetId() { toolCall.setId("newTestId"); assertEquals("newTestId", toolCall.getId()); } @Test public void testGetType() { toolCall.setType("testType"); assertEquals("testType", toolCall.getType()); } @Test public void testSetType() { toolCall.setType("newTestType"); assertEquals("newTestType", toolCall.getType()); } } ================================================ FILE: java/src/test/java/com/baidubce/appbuilder/model/dataset/DatasetCreateResultTest.java ================================================ package com.baidubce.appbuilder.model.dataset; import org.junit.Before; import org.junit.Test; import static org.junit.Assert.*; public class DatasetCreateResultTest { private DatasetCreateResult datasetCreateResult; @Before public void setUp() { datasetCreateResult = new DatasetCreateResult(); } @Test public void testId() { datasetCreateResult.setId("test_id"); assertEquals("test_id", datasetCreateResult.getId()); } @Test public void testName() { datasetCreateResult.setName("test_name"); assertEquals("test_name", datasetCreateResult.getName()); } @Test public void testDescription() { datasetCreateResult.setDescription("test_description"); assertEquals("test_description", datasetCreateResult.getDescription()); } @Test public void testIndexingTechnique() { datasetCreateResult.setIndexingTechnique("test_indexing_technique"); assertEquals("test_indexing_technique", datasetCreateResult.getIndexingTechnique()); } @Test public void testDocumentCount() { datasetCreateResult.setDocumentCount(123); assertEquals(123, datasetCreateResult.getDocumentCount()); } @Test public void testWordCount() { datasetCreateResult.setWordCount(456); assertEquals(456, datasetCreateResult.getWordCount()); } @Test public void testCreatedBy() { datasetCreateResult.setCreatedBy("test_created_by"); assertEquals("test_created_by", datasetCreateResult.getCreatedBy()); } @Test public void testCreatedAt() { datasetCreateResult.setCreatedAt(123456789L); assertEquals(123456789L, datasetCreateResult.getCreatedAt()); } @Test public void testUpdatedBy() { datasetCreateResult.setUpdatedBy("test_updated_by"); assertEquals("test_updated_by", datasetCreateResult.getUpdatedBy()); } @Test public void testUpdatedAt() { datasetCreateResult.setUpdatedAt(987654321L); assertEquals(987654321L, datasetCreateResult.getUpdatedAt()); } @Test public void testIsPriority() { datasetCreateResult.setPriority(true); assertTrue(datasetCreateResult.isPriority()); datasetCreateResult.setPriority(false); assertFalse(datasetCreateResult.isPriority()); } @Test public void testToString() { datasetCreateResult.setId("test_id"); datasetCreateResult.setName("test_name"); datasetCreateResult.setDescription("test_description"); datasetCreateResult.setIndexingTechnique("test_indexing_technique"); datasetCreateResult.setDocumentCount(123); datasetCreateResult.setWordCount(456); datasetCreateResult.setCreatedBy("test_created_by"); datasetCreateResult.setCreatedAt(123456789L); datasetCreateResult.setUpdatedBy("test_updated_by"); datasetCreateResult.setUpdatedAt(987654321L); datasetCreateResult.setPriority(true); String expectedString = "DatasetCreateResult{" + "id='test_id', name='test_name', description='test_description', " + "indexingTechnique='test_indexing_technique', documentCount=123, wordCount=456, " + "createdBy='test_created_by', createdAt=123456789, updatedBy='test_updated_by', " + "updatedAt=987654321, isPriority=true}"; assertEquals(expectedString, datasetCreateResult.toString()); } } ================================================ FILE: java/src/test/java/com/baidubce/appbuilder/model/dataset/DocumentAddResultTest.java ================================================ package com.baidubce.appbuilder.model.dataset; import org.junit.Before; import org.junit.Test; import static org.junit.Assert.*; import java.util.Arrays; public class DocumentAddResultTest { private DocumentAddResult documentAddResult; @Before public void setUp() { documentAddResult = new DocumentAddResult(); documentAddResult.setDatasetId("testDatasetId"); documentAddResult.setDocumentIds(new String[] { "doc1", "doc2", "doc3" }); } @Test public void testGetDatasetId() { assertEquals("testDatasetId", documentAddResult.getDatasetId()); } @Test public void testSetDatasetId() { documentAddResult.setDatasetId("newDatasetId"); assertEquals("newDatasetId", documentAddResult.getDatasetId()); } @Test public void testGetDocumentIds() { String[] documentIds = documentAddResult.getDocumentIds(); assertNotNull(documentIds); assertArrayEquals(new String[] { "doc1", "doc2", "doc3" }, documentIds); } @Test public void testSetDocumentIds() { documentAddResult.setDocumentIds(new String[] { "docA", "docB" }); assertArrayEquals(new String[] { "docA", "docB" }, documentAddResult.getDocumentIds()); } @Test public void testToString() { String expectedString = "DocumentAddResult{" + "datasetId='testDatasetId'" + ", documentIds=" + Arrays.toString(new String[] { "doc1", "doc2", "doc3" }) + '}'; assertEquals(expectedString, documentAddResult.toString()); } } ================================================ FILE: java/src/test/java/com/baidubce/appbuilder/model/dataset/DocumentListDataTest.java ================================================ package com.baidubce.appbuilder.model.dataset; import org.junit.Before; import org.junit.Test; import static org.junit.Assert.*; import java.util.HashMap; import java.util.Map; public class DocumentListDataTest { private DocumentListData documentListData; @Before public void setUp() { documentListData = new DocumentListData(); } @Test public void testId() { documentListData.setId("test_id"); assertEquals("test_id", documentListData.getId()); } @Test public void testName() { documentListData.setName("test_name"); assertEquals("test_name", documentListData.getName()); } @Test public void testDatasetProcessRuleId() { documentListData.setDatasetProcessRuleId("test_rule_id"); assertEquals("test_rule_id", documentListData.getDatasetProcessRuleId()); } @Test public void testDataSourceType() { documentListData.setDataSourceType("test_source_type"); assertEquals("test_source_type", documentListData.getDataSourceType()); } @Test public void testPosition() { documentListData.setPosition(5); assertEquals(5, documentListData.getPosition()); } @Test public void testDataSourceInfo() { Map dataSourceInfo = new HashMap<>(); dataSourceInfo.put("key1", "value1"); documentListData.setDataSourceInfo(dataSourceInfo); assertEquals(dataSourceInfo, documentListData.getDataSourceInfo()); } @Test public void testCreatedFrom() { documentListData.setCreatedFrom("test_created_from"); assertEquals("test_created_from", documentListData.getCreatedFrom()); } @Test public void testCreatedBy() { documentListData.setCreatedBy("test_created_by"); assertEquals("test_created_by", documentListData.getCreatedBy()); } @Test public void testCreatedAt() { documentListData.setCreatedAt(123456789L); assertEquals(123456789L, documentListData.getCreatedAt()); } @Test public void testIndexingStatus() { documentListData.setIndexingStatus("indexing"); assertEquals("indexing", documentListData.getIndexingStatus()); } @Test public void testError() { Object error = new Object(); documentListData.setError(error); assertEquals(error, documentListData.getError()); } @Test public void testEnabled() { documentListData.setEnabled(true); assertTrue(documentListData.isEnabled()); documentListData.setEnabled(false); assertFalse(documentListData.isEnabled()); } @Test public void testDisplayStatus() { documentListData.setDisplayStatus("displaying"); assertEquals("displaying", documentListData.getDisplayStatus()); } @Test public void testWordCount() { documentListData.setWordCount(1000); assertEquals(1000, documentListData.getWordCount()); } @Test public void testEstimatedWaitingMinutes() { documentListData.setEstimatedWaitingMinutes(30); assertEquals(30, documentListData.getEstimatedWaitingMinutes()); } @Test public void testDisabledAt() { Object disabledAt = new Object(); documentListData.setDisabledAt(disabledAt); assertEquals(disabledAt, documentListData.getDisabledAt()); } @Test public void testDisabledBy() { Object disabledBy = new Object(); documentListData.setDisabledBy(disabledBy); assertEquals(disabledBy, documentListData.getDisabledBy()); } @Test public void testToString() { documentListData.setId("test_id"); documentListData.setName("test_name"); documentListData.setDatasetProcessRuleId("test_rule_id"); documentListData.setDataSourceType("test_source_type"); documentListData.setPosition(5); Map dataSourceInfo = new HashMap<>(); dataSourceInfo.put("key1", "value1"); documentListData.setDataSourceInfo(dataSourceInfo); documentListData.setCreatedFrom("test_created_from"); documentListData.setCreatedBy("test_created_by"); documentListData.setCreatedAt(123456789L); documentListData.setIndexingStatus("indexing"); documentListData.setError(null); documentListData.setEnabled(true); documentListData.setDisplayStatus("displaying"); documentListData.setWordCount(1000); documentListData.setEstimatedWaitingMinutes(30); documentListData.setDisabledAt(null); documentListData.setDisabledBy(null); String expectedString = "DocumentListData{" + "id='test_id', name='test_name', datasetProcessRuleId='test_rule_id', dataSourceType='test_source_type', " + "position=5, dataSourceInfo={key1=value1}, createdFrom='test_created_from', createdBy='test_created_by', " + "createdAt=123456789, indexingStatus='indexing', error=null, enabled=true, displayStatus='displaying', " + "wordCount=1000, estimatedWaitingMinutes=30, disabledAt=null, disabledBy=null}"; assertEquals(expectedString, documentListData.toString()); } } ================================================ FILE: java/src/test/java/com/baidubce/appbuilder/model/dataset/DocumentListResponseTest.java ================================================ package com.baidubce.appbuilder.model.dataset; import org.junit.Before; import org.junit.Test; import static org.junit.Assert.*; public class DocumentListResponseTest { private DocumentListResponse documentListResponse; private DocumentListResult documentListResult; @Before public void setUp() { documentListResponse = new DocumentListResponse(); // Initialize DocumentListResult (assuming it has a default constructor and setters) documentListResult = new DocumentListResult(); documentListResult.setTotal(100); documentListResult.setPage(1); } @Test public void testCode() { documentListResponse.setCode(200); assertEquals(200, documentListResponse.getCode()); } @Test public void testMessage() { documentListResponse.setMessage("Request successful"); assertEquals("Request successful", documentListResponse.getMessage()); } @Test public void testResult() { documentListResponse.setResult(documentListResult); assertNotNull(documentListResponse.getResult()); assertEquals(100, documentListResponse.getResult().getTotal()); assertEquals(1, documentListResponse.getResult().getPage()); } @Test public void testToString() { documentListResponse.setCode(200); documentListResponse.setMessage("Request successful"); documentListResponse.setResult(documentListResult); String expectedString = "DocumentListResponse{" + "code=200, message='Request successful', result=" + documentListResult + "}"; assertEquals(expectedString, documentListResponse.toString()); } } ================================================ FILE: java/src/test/java/com/baidubce/appbuilder/model/dataset/DocumentListResultTest.java ================================================ package com.baidubce.appbuilder.model.dataset; import org.junit.Before; import org.junit.Test; import static org.junit.Assert.*; public class DocumentListResultTest { private DocumentListResult documentListResult; @Before public void setUp() { documentListResult = new DocumentListResult(); } @Test public void testHasMore() { documentListResult.setHasMore(true); assertTrue(documentListResult.isHasMore()); documentListResult.setHasMore(false); assertFalse(documentListResult.isHasMore()); } @Test public void testLimit() { documentListResult.setLimit(10); assertEquals(10, documentListResult.getLimit()); } @Test public void testPage() { documentListResult.setPage(2); assertEquals(2, documentListResult.getPage()); } @Test public void testTotal() { documentListResult.setTotal(100); assertEquals(100, documentListResult.getTotal()); } @Test public void testData() { DocumentListData data1 = new DocumentListData(); data1.setId("doc1"); data1.setName("Document 1"); DocumentListData data2 = new DocumentListData(); data2.setId("doc2"); data2.setName("Document 2"); DocumentListData[] dataArray = {data1, data2}; documentListResult.setData(dataArray); assertEquals(2, documentListResult.getData().length); assertEquals("doc1", documentListResult.getData()[0].getId()); assertEquals("Document 1", documentListResult.getData()[0].getName()); assertEquals("doc2", documentListResult.getData()[1].getId()); assertEquals("Document 2", documentListResult.getData()[1].getName()); } @Test public void testToString() { DocumentListData data1 = new DocumentListData(); data1.setId("doc1"); data1.setName("Document 1"); DocumentListData[] dataArray = {data1}; documentListResult.setHasMore(true); documentListResult.setLimit(5); documentListResult.setPage(1); documentListResult.setTotal(50); documentListResult.setData(dataArray); String expectedString = "DocumentListResult{" + "hasMore=true, limit=5, page=1, total=50, data=[DocumentListData{id='doc1', name='Document 1', datasetProcessRuleId='null', dataSourceType='null', position=0, dataSourceInfo=null, createdFrom='null', createdBy='null', createdAt=0, indexingStatus='null', error=null, enabled=false, displayStatus='null', wordCount=0, estimatedWaitingMinutes=0, disabledAt=null, disabledBy=null}]}"; assertEquals(expectedString, documentListResult.toString()); } } ================================================ FILE: java/src/test/java/com/baidubce/appbuilder/model/dataset/FileUploadResponseTest.java ================================================ package com.baidubce.appbuilder.model.dataset; import org.junit.Before; import org.junit.Test; import static org.junit.Assert.*; public class FileUploadResponseTest { private FileUploadResponse fileUploadResponse; private FileUploadResult fileUploadResult; @Before public void setUp() { fileUploadResponse = new FileUploadResponse(); fileUploadResult = new FileUploadResult(); fileUploadResult.setId("file123"); fileUploadResult.setName("testFile.txt"); fileUploadResult.setSize(1024); fileUploadResult.setExtension(".txt"); fileUploadResult.setMimeType("text/plain"); fileUploadResult.setCreatedBy("user123"); fileUploadResult.setCreatedAt(123456789L); } @Test public void testCode() { fileUploadResponse.setCode(200); assertEquals(200, fileUploadResponse.getCode()); } @Test public void testMessage() { fileUploadResponse.setMessage("Upload successful"); assertEquals("Upload successful", fileUploadResponse.getMessage()); } @Test public void testResult() { fileUploadResponse.setResult(fileUploadResult); assertNotNull(fileUploadResponse.getResult()); assertEquals("file123", fileUploadResponse.getResult().getId()); assertEquals("testFile.txt", fileUploadResponse.getResult().getName()); assertEquals(1024, fileUploadResponse.getResult().getSize()); assertEquals(".txt", fileUploadResponse.getResult().getExtension()); assertEquals("text/plain", fileUploadResponse.getResult().getMimeType()); assertEquals("user123", fileUploadResponse.getResult().getCreatedBy()); assertEquals(123456789L, fileUploadResponse.getResult().getCreatedAt()); } @Test public void testToString() { fileUploadResponse.setCode(200); fileUploadResponse.setMessage("Upload successful"); fileUploadResponse.setResult(fileUploadResult); String expectedString = "FileUploadResponse{" + "code=200, message='Upload successful', result=FileUploadResult{id='file123', name='testFile.txt', size=1024, extension='.txt', mimeType='text/plain', createdBy='user123', createdAt=123456789}}"; assertEquals(expectedString, fileUploadResponse.toString()); } } ================================================ FILE: java/src/test/java/com/baidubce/appbuilder/model/dataset/FileUploadResultTest.java ================================================ package com.baidubce.appbuilder.model.dataset; import org.junit.Before; import org.junit.Test; import static org.junit.Assert.*; public class FileUploadResultTest { private FileUploadResult fileUploadResult; @Before public void setUp() { fileUploadResult = new FileUploadResult(); } @Test public void testId() { fileUploadResult.setId("test_id"); assertEquals("test_id", fileUploadResult.getId()); } @Test public void testName() { fileUploadResult.setName("test_name"); assertEquals("test_name", fileUploadResult.getName()); } @Test public void testSize() { fileUploadResult.setSize(1024); assertEquals(1024, fileUploadResult.getSize()); } @Test public void testExtension() { fileUploadResult.setExtension(".txt"); assertEquals(".txt", fileUploadResult.getExtension()); } @Test public void testMimeType() { fileUploadResult.setMimeType("text/plain"); assertEquals("text/plain", fileUploadResult.getMimeType()); } @Test public void testCreatedBy() { fileUploadResult.setCreatedBy("test_user"); assertEquals("test_user", fileUploadResult.getCreatedBy()); } @Test public void testCreatedAt() { fileUploadResult.setCreatedAt(123456789L); assertEquals(123456789L, fileUploadResult.getCreatedAt()); } @Test public void testToString() { fileUploadResult.setId("test_id"); fileUploadResult.setName("test_name"); fileUploadResult.setSize(1024); fileUploadResult.setExtension(".txt"); fileUploadResult.setMimeType("text/plain"); fileUploadResult.setCreatedBy("test_user"); fileUploadResult.setCreatedAt(123456789L); String expectedString = "FileUploadResult{" + "id='test_id', name='test_name', size=1024, extension='.txt', mimeType='text/plain', " + "createdBy='test_user', createdAt=123456789}"; assertEquals(expectedString, fileUploadResult.toString()); } } ================================================ FILE: java/src/test/java/com/baidubce/appbuilder/model/dataset/ResponseTest.java ================================================ package com.baidubce.appbuilder.model.dataset; import org.junit.Before; import org.junit.Test; import static org.junit.Assert.*; public class ResponseTest { private DatasetCreateResponse datasetCreateResponse; private DocumentAddResponse documentAddResponse; private DocumentDeleteResponse documentDeleteResponse; @Before public void setUp() { // Initialize DatasetCreateResponse datasetCreateResponse = new DatasetCreateResponse(); DatasetCreateResult datasetCreateResult = new DatasetCreateResult(); // Assume default constructor datasetCreateResponse.setCode(200); datasetCreateResponse.setMessage("Dataset created successfully"); datasetCreateResponse.setResult(datasetCreateResult); // Initialize DocumentAddResponse documentAddResponse = new DocumentAddResponse(); DocumentAddResult documentAddResult = new DocumentAddResult(); // Assume default constructor documentAddResponse.setCode(201); documentAddResponse.setMessage("Document added successfully"); documentAddResponse.setResult(documentAddResult); // Initialize DocumentDeleteResponse documentDeleteResponse = new DocumentDeleteResponse(); documentDeleteResponse.setCode(204); documentDeleteResponse.setMessage("Document deleted successfully"); documentDeleteResponse.setResult(null); // Assume result can be null } @Test public void testDatasetCreateResponse() { assertEquals(200, datasetCreateResponse.getCode()); assertEquals("Dataset created successfully", datasetCreateResponse.getMessage()); assertNotNull(datasetCreateResponse.getResult()); String expectedString = "DatasetCreateResponse{" + "code=200" + ", message='Dataset created successfully'" + ", result=" + datasetCreateResponse.getResult() + '}'; assertEquals(expectedString, datasetCreateResponse.toString()); } @Test public void testDocumentAddResponse() { assertEquals(201, documentAddResponse.getCode()); assertEquals("Document added successfully", documentAddResponse.getMessage()); assertNotNull(documentAddResponse.getResult()); String expectedString = "DocumentAddResponse{" + "code=201" + ", message='Document added successfully'" + ", result=" + documentAddResponse.getResult() + '}'; assertEquals(expectedString, documentAddResponse.toString()); } @Test public void testDocumentDeleteResponse() { assertEquals(204, documentDeleteResponse.getCode()); assertEquals("Document deleted successfully", documentDeleteResponse.getMessage()); assertNull(documentDeleteResponse.getResult()); String expectedString = "DocumentDeleteResponse{" + "code=204" + ", message='Document deleted successfully'" + ", result=null" + '}'; assertEquals(expectedString, documentDeleteResponse.toString()); } } ================================================ FILE: java/src/test/java/com/baidubce/appbuilder/model/knowledgebase/ChunkCreateRequestTest.java ================================================ package com.baidubce.appbuilder.model.knowledgebase; import org.junit.Before; import org.junit.Test; import static org.junit.Assert.assertEquals; public class ChunkCreateRequestTest { private ChunkCreateRequest chunkCreateRequest; @Before public void setUp() { chunkCreateRequest = new ChunkCreateRequest("doc123", "This is the content of the chunk."); } @Test public void testGetDocumentId() { assertEquals("doc123", chunkCreateRequest.getDocumentId()); } @Test public void testGetContent() { assertEquals("This is the content of the chunk.", chunkCreateRequest.getContent()); } } ================================================ FILE: java/src/test/java/com/baidubce/appbuilder/model/knowledgebase/ChunkCreateResponseTest.java ================================================ package com.baidubce.appbuilder.model.knowledgebase; import org.junit.Before; import org.junit.Test; import static org.junit.Assert.*; public class ChunkCreateResponseTest { private ChunkCreateResponse chunkCreateResponse; @Before public void setUp() { // 初始化 ChunkCreateResponse 对象 chunkCreateResponse = new ChunkCreateResponse(); } @Test public void testSetAndGetChunkId() { // 设置 chunkId chunkCreateResponse.setChunkId("chunk123"); // 验证是否正确返回设置的 chunkId assertEquals("chunk123", chunkCreateResponse.getChunkId()); } } ================================================ FILE: java/src/test/java/com/baidubce/appbuilder/model/knowledgebase/ChunkDeleteRequestTest.java ================================================ package com.baidubce.appbuilder.model.knowledgebase; import org.junit.Before; import org.junit.Test; import static org.junit.Assert.assertEquals; public class ChunkDeleteRequestTest { private ChunkDeleteRequest chunkDeleteRequest; @Before public void setUp() { chunkDeleteRequest = new ChunkDeleteRequest(); } @Test public void testSetAndGetChunkId() { String expectedChunkId = "chunk123"; chunkDeleteRequest.setChunkId(expectedChunkId); assertEquals(expectedChunkId, chunkDeleteRequest.getChunkId()); } } ================================================ FILE: java/src/test/java/com/baidubce/appbuilder/model/knowledgebase/ChunkDescribeRequestTest.java ================================================ package com.baidubce.appbuilder.model.knowledgebase; import org.junit.Before; import org.junit.Test; import static org.junit.Assert.*; public class ChunkDescribeRequestTest { private ChunkDescribeRequest chunkDescribeRequest; @Before public void setUp() { // 初始化 ChunkDescribeRequest 对象 chunkDescribeRequest = new ChunkDescribeRequest(); } @Test public void testSetAndGetChunkId() { // 设置 chunkId chunkDescribeRequest.setChunkId("chunk123"); // 验证是否正确返回设置的 chunkId assertEquals("chunk123", chunkDescribeRequest.getChunkId()); } } ================================================ FILE: java/src/test/java/com/baidubce/appbuilder/model/knowledgebase/ChunkDescribeResponseTest.java ================================================ package com.baidubce.appbuilder.model.knowledgebase; import org.junit.Before; import org.junit.Test; import static org.junit.Assert.*; public class ChunkDescribeResponseTest { private ChunkDescribeResponse chunkDescribeResponse; @Before public void setUp() { chunkDescribeResponse = new ChunkDescribeResponse(); } @Test public void testChunkId() { chunkDescribeResponse.setChunkId("test_chunk_id"); assertEquals("test_chunk_id", chunkDescribeResponse.getChunkId()); } @Test public void testType() { chunkDescribeResponse.setType("test_type"); assertEquals("test_type", chunkDescribeResponse.getType()); } @Test public void testKnowledgeBaseId() { chunkDescribeResponse.setKnowledgeBaseId("test_knowledge_base_id"); assertEquals("test_knowledge_base_id", chunkDescribeResponse.getKnowledgeBaseId()); } @Test public void testDocumentId() { chunkDescribeResponse.setDocumentId("test_document_id"); assertEquals("test_document_id", chunkDescribeResponse.getDocumentId()); } @Test public void testContent() { chunkDescribeResponse.setContent("test_content"); assertEquals("test_content", chunkDescribeResponse.getContent()); } @Test public void testWordCount() { chunkDescribeResponse.setWordCount(123); assertEquals(Integer.valueOf(123), chunkDescribeResponse.getWordCount()); } @Test public void testTokenCount() { chunkDescribeResponse.setTokenCount(456); assertEquals(Integer.valueOf(456), chunkDescribeResponse.getTokenCount()); } @Test public void testEnabled() { chunkDescribeResponse.setEnabled(true); assertTrue(chunkDescribeResponse.getEnabled()); chunkDescribeResponse.setEnabled(false); assertFalse(chunkDescribeResponse.getEnabled()); } @Test public void testStatus() { chunkDescribeResponse.setStatus("test_status"); assertEquals("test_status", chunkDescribeResponse.getStatus()); } @Test public void testStatusMessage() { chunkDescribeResponse.setStatusMessage("test_status_message"); assertEquals("test_status_message", chunkDescribeResponse.getStatusMessage()); } @Test public void testCreateTime() { chunkDescribeResponse.setCreateTime(789); assertEquals(Integer.valueOf(789), chunkDescribeResponse.getCreateTime()); } @Test public void testUpdateTime() { chunkDescribeResponse.setUpdateTime(101112); assertEquals(Integer.valueOf(101112), chunkDescribeResponse.getUpdateTime()); } } ================================================ FILE: java/src/test/java/com/baidubce/appbuilder/model/knowledgebase/ChunkModifyRequestTest.java ================================================ package com.baidubce.appbuilder.model.knowledgebase; import org.junit.Before; import org.junit.Test; import static org.junit.Assert.*; public class ChunkModifyRequestTest { private ChunkModifyRequest chunkModifyRequest; @Before public void setUp() { // 初始化 ChunkModifyRequest 对象 chunkModifyRequest = new ChunkModifyRequest("chunk123", "new content", true); } @Test public void testGetChunkId() { assertEquals("chunk123", chunkModifyRequest.getChunkId()); } @Test public void testGetContent() { assertEquals("new content", chunkModifyRequest.getContent()); } @Test public void testGetEnable() { assertTrue(chunkModifyRequest.getEnable()); } } ================================================ FILE: java/src/test/java/com/baidubce/appbuilder/model/knowledgebase/ChunksDescribeRequestTest.java ================================================ package com.baidubce.appbuilder.model.knowledgebase; import org.junit.Before; import org.junit.Test; import static org.junit.Assert.*; public class ChunksDescribeRequestTest { private ChunksDescribeRequest chunksDescribeRequest; @Before public void setUp() { // 初始化 ChunksDescribeRequest 对象 chunksDescribeRequest = new ChunksDescribeRequest("doc123", "marker123", 10, "chunkType"); } @Test public void testGetDocumentId() { assertEquals("doc123", chunksDescribeRequest.getDocumentId()); } @Test public void testGetMarker() { assertEquals("marker123", chunksDescribeRequest.getMarker()); } @Test public void testGetMaxKeys() { assertEquals(Integer.valueOf(10), chunksDescribeRequest.getMaxKeys()); } @Test public void testGetType() { assertEquals("chunkType", chunksDescribeRequest.getType()); } } ================================================ FILE: java/src/test/java/com/baidubce/appbuilder/model/knowledgebase/ChunksDescribeResponseTest.java ================================================ package com.baidubce.appbuilder.model.knowledgebase; import org.junit.Before; import org.junit.Test; import static org.junit.Assert.*; public class ChunksDescribeResponseTest { private ChunksDescribeResponse chunksDescribeResponse; private ChunkDescribeResponse chunk1; private ChunkDescribeResponse chunk2; @Before public void setUp() { chunksDescribeResponse = new ChunksDescribeResponse(); // Initialize ChunkDescribeResponse objects (assuming ChunkDescribeResponse has default constructor and setters) chunk1 = new ChunkDescribeResponse(); chunk1.setChunkId("chunk1"); chunk1.setContent("Content of chunk 1"); chunk2 = new ChunkDescribeResponse(); chunk2.setChunkId("chunk2"); chunk2.setContent("Content of chunk 2"); chunksDescribeResponse.setData(new ChunkDescribeResponse[]{chunk1, chunk2}); chunksDescribeResponse.setMarker("testMarker"); chunksDescribeResponse.setTruncated(true); chunksDescribeResponse.setNextMarker("testNextMarker"); chunksDescribeResponse.setMaxKeys(100); } @Test public void testData() { ChunkDescribeResponse[] data = chunksDescribeResponse.getData(); assertNotNull(data); assertEquals(2, data.length); assertEquals("chunk1", data[0].getChunkId()); assertEquals("Content of chunk 1", data[0].getContent()); assertEquals("chunk2", data[1].getChunkId()); assertEquals("Content of chunk 2", data[1].getContent()); } @Test public void testMarker() { assertEquals("testMarker", chunksDescribeResponse.getMarker()); } @Test public void testIsTruncated() { assertTrue(chunksDescribeResponse.isTruncated()); } @Test public void testNextMarker() { assertEquals("testNextMarker", chunksDescribeResponse.getNextMarker()); } @Test public void testMaxKeys() { assertEquals(Integer.valueOf(100), chunksDescribeResponse.getMaxKeys()); } } ================================================ FILE: java/src/test/java/com/baidubce/appbuilder/model/knowledgebase/DocumentAddRequestTest.java ================================================ package com.baidubce.appbuilder.model.knowledgebase; import org.junit.Before; import org.junit.Test; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; public class DocumentAddRequestTest { private DocumentAddRequest documentAddRequest; private DocumentAddRequest.CustomProcessRule customProcessRule; @Before public void setUp() { documentAddRequest = new DocumentAddRequest(); customProcessRule = new DocumentAddRequest.CustomProcessRule(); } @Test public void testSetAndGetKnowledgeBaseId() { String knowledgeBaseId = "kb123"; documentAddRequest.setKnowledgeBaseId(knowledgeBaseId); assertEquals(knowledgeBaseId, documentAddRequest.getKnowledgeBaseId()); } @Test public void testSetAndGetContentType() { String contentType = "text"; documentAddRequest.setContentType(contentType); assertEquals(contentType, documentAddRequest.getContentType()); } @Test public void testSetAndGetIsEnhanced() { boolean isEnhanced = true; documentAddRequest.setEnhanced(isEnhanced); assertEquals(isEnhanced, documentAddRequest.isEnhanced()); } @Test public void testSetAndGetFileIds() { String[] fileIds = {"file1", "file2"}; documentAddRequest.setFileIds(fileIds); assertArrayEquals(fileIds, documentAddRequest.getFileIds()); } @Test public void testSetAndGetCustomProcessRule() { String[] separators = {",", ";"}; int targetLength = 100; double overlapRate = 0.5; customProcessRule.setSeparators(separators); customProcessRule.setTargetLength(targetLength); customProcessRule.setOverlapRate(overlapRate); documentAddRequest.setCustomProcessRule(customProcessRule); assertArrayEquals(separators, documentAddRequest.getCustomProcessRule().getSeparators()); assertEquals(targetLength, documentAddRequest.getCustomProcessRule().getTargetLength()); assertEquals(overlapRate, documentAddRequest.getCustomProcessRule().getOverlapRate(), 0); } } ================================================ FILE: java/src/test/java/com/baidubce/appbuilder/model/knowledgebase/DocumentDeleteRequestTest.java ================================================ package com.baidubce.appbuilder.model.knowledgebase; import org.junit.Before; import org.junit.Test; import java.util.Map; import static org.junit.Assert.*; public class DocumentDeleteRequestTest { private DocumentDeleteRequest documentDeleteRequest; @Before public void setUp() { // 初始化 DocumentDeleteRequest 对象 documentDeleteRequest = new DocumentDeleteRequest(); } @Test public void testSetAndGetKonwledgeBaseId() { // 设置 knowledgeBaseId documentDeleteRequest.setKonwledgeBaseId("kb123"); // 验证是否正确返回设置的 knowledgeBaseId assertEquals("kb123", documentDeleteRequest.getKonwledgeBaseId()); } @Test public void testSetAndGetDocumentId() { // 设置 documentId documentDeleteRequest.setDocumentId("doc456"); // 验证是否正确返回设置的 documentId assertEquals("doc456", documentDeleteRequest.getDocumentId()); } @Test public void testToMap() { // 设置字段 documentDeleteRequest.setKonwledgeBaseId("kb123"); documentDeleteRequest.setDocumentId("doc456"); // 验证 toMap() 方法是否正确返回 map Map resultMap = documentDeleteRequest.toMap(); assertEquals("kb123", resultMap.get("knowledge_base_id")); assertEquals("doc456", resultMap.get("document_id")); } } ================================================ FILE: java/src/test/java/com/baidubce/appbuilder/model/knowledgebase/DocumentDeleteResponseTest.java ================================================ package com.baidubce.appbuilder.model.knowledgebase; import org.junit.Before; import org.junit.Test; import static org.junit.Assert.assertEquals; public class DocumentDeleteResponseTest { private DocumentDeleteResponse documentDeleteResponse; @Before public void setUp() { documentDeleteResponse = new DocumentDeleteResponse(); } @Test public void testGetSetRequestId() { documentDeleteResponse.setRequestId("req123"); assertEquals("req123", documentDeleteResponse.getRequestId()); } @Test public void testGetSetCode() { documentDeleteResponse.setCode("200"); assertEquals("200", documentDeleteResponse.getCode()); } @Test public void testGetSetMessage() { documentDeleteResponse.setMessage("Success"); assertEquals("Success", documentDeleteResponse.getMessage()); } @Test public void testToString() { documentDeleteResponse.setRequestId("req123"); documentDeleteResponse.setCode("200"); documentDeleteResponse.setMessage("Success"); String expectedString = "DocumentDeleteResponse{" + "request_id=req123" + ", code='200'" + ", message='Success" + '}'; assertEquals(expectedString, documentDeleteResponse.toString()); } } ================================================ FILE: java/src/test/java/com/baidubce/appbuilder/model/knowledgebase/DocumentListRequestTest.java ================================================ package com.baidubce.appbuilder.model.knowledgebase; import org.junit.Before; import org.junit.Test; import java.util.Map; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; public class DocumentListRequestTest { private DocumentListRequest documentListRequest; @Before public void setUp() { documentListRequest = new DocumentListRequest(); } @Test public void testGetSetKonwledgeBaseId() { documentListRequest.setKonwledgeBaseId("kb123"); assertEquals("kb123", documentListRequest.getKonwledgeBaseId()); } @Test public void testGetSetLimit() { documentListRequest.setLimit(10); assertEquals(10, documentListRequest.getLimit()); } @Test public void testGetSetAfter() { documentListRequest.setAfter("afterToken"); assertEquals("afterToken", documentListRequest.getAfter()); } @Test public void testGetSetBefore() { documentListRequest.setBefore("beforeToken"); assertEquals("beforeToken", documentListRequest.getBefore()); } @Test public void testToMapWithAllValues() { documentListRequest.setKonwledgeBaseId("kb123"); documentListRequest.setLimit(10); documentListRequest.setAfter("afterToken"); documentListRequest.setBefore("beforeToken"); Map resultMap = documentListRequest.toMap(); assertEquals(4, resultMap.size()); assertEquals("kb123", resultMap.get("knowledge_base_id")); assertEquals(10, resultMap.get("limit")); assertEquals("afterToken", resultMap.get("after")); assertEquals("beforeToken", resultMap.get("before")); } @Test public void testToMapWithLimitZero() { documentListRequest.setKonwledgeBaseId("kb123"); documentListRequest.setLimit(0); // limit set to 0 documentListRequest.setAfter("afterToken"); documentListRequest.setBefore("beforeToken"); Map resultMap = documentListRequest.toMap(); assertEquals(3, resultMap.size()); // limit should not be included assertEquals("kb123", resultMap.get("knowledge_base_id")); assertEquals("afterToken", resultMap.get("after")); assertEquals("beforeToken", resultMap.get("before")); assertTrue(!resultMap.containsKey("limit")); // Ensure limit is not included when it's 0 } } ================================================ FILE: java/src/test/java/com/baidubce/appbuilder/model/knowledgebase/DocumentListResponseTest.java ================================================ package com.baidubce.appbuilder.model.knowledgebase; import org.junit.Before; import org.junit.Test; import static org.junit.Assert.*; public class DocumentListResponseTest { private DocumentListResponse documentListResponse; private Document document1; private Document document2; @Before public void setUp() { documentListResponse = new DocumentListResponse(); // Initialize Document objects (assuming Document has default constructor and setters) document1 = new Document(); document1.setId("doc1"); document1.setName("Document 1"); document2 = new Document(); document2.setId("doc2"); document2.setName("Document 2"); documentListResponse.setRequestId("testRequestId"); documentListResponse.setData(new Document[]{document1, document2}); documentListResponse.setCode("200"); documentListResponse.setMessage("Request successful"); } @Test public void testRequestId() { assertEquals("testRequestId", documentListResponse.getRequestId()); } @Test public void testData() { Document[] data = documentListResponse.getData(); assertNotNull(data); assertEquals(2, data.length); assertEquals("doc1", data[0].getId()); assertEquals("Document 1", data[0].getName()); assertEquals("doc2", data[1].getId()); assertEquals("Document 2", data[1].getName()); } @Test public void testCode() { assertEquals("200", documentListResponse.getCode()); } @Test public void testMessage() { assertEquals("Request successful", documentListResponse.getMessage()); } } ================================================ FILE: java/src/test/java/com/baidubce/appbuilder/model/knowledgebase/DocumentTest.java ================================================ package com.baidubce.appbuilder.model.knowledgebase; import org.junit.Before; import org.junit.Test; import static org.junit.Assert.*; public class DocumentTest { private Document document; private Document.Meta meta; @Before public void setUp() { document = new Document(); meta = new Document.Meta(); } @Test public void testId() { document.setId("doc123"); assertEquals("doc123", document.getId()); } @Test public void testName() { document.setName("Test Document"); assertEquals("Test Document", document.getName()); } @Test public void testCreatedAt() { document.setCreatedAt("2024-01-01T00:00:00Z"); assertEquals("2024-01-01T00:00:00Z", document.getCreatedAt()); } @Test public void testWordCount() { document.setWordCount(500); assertEquals(500, document.getWordCount()); } @Test public void testEnabled() { document.setEnabled(true); assertTrue(document.isEnabled()); document.setEnabled(false); assertFalse(document.isEnabled()); } @Test public void testMeta() { meta.setSource("http://example.com"); meta.setFileId("file123"); document.setMeta(meta); assertEquals("http://example.com", document.getMeta().getSource()); assertEquals("file123", document.getMeta().getFileId()); } } ================================================ FILE: java/src/test/java/com/baidubce/appbuilder/model/knowledgebase/DocumentsCreateRequestTest.java ================================================ package com.baidubce.appbuilder.model.knowledgebase; import org.junit.Before; import org.junit.Test; import static org.junit.Assert.*; public class DocumentsCreateRequestTest { private DocumentsCreateRequest documentsCreateRequest; private DocumentsCreateRequest.Source source; private DocumentsCreateRequest.ProcessOption processOption; private DocumentsCreateRequest.ProcessOption.Parser parser; private DocumentsCreateRequest.ProcessOption.Chunker chunker; private DocumentsCreateRequest.ProcessOption.Chunker.Separator separator; private DocumentsCreateRequest.ProcessOption.Chunker.Pattern pattern; private DocumentsCreateRequest.ProcessOption.KnowledgeAugmentation knowledgeAugmentation; @Before public void setUp() { // Initialize inner classes parser = new DocumentsCreateRequest.ProcessOption.Parser(new String[]{"choice1", "choice2"}); separator = new DocumentsCreateRequest.ProcessOption.Chunker.Separator( new String[]{","}, 100, 0.5); pattern = new DocumentsCreateRequest.ProcessOption.Chunker.Pattern( "start", "\\w+", 200, 0.3); chunker = new DocumentsCreateRequest.ProcessOption.Chunker( new String[]{"chunkChoice1"}, separator, pattern, new String[]{"info1"}); knowledgeAugmentation = new DocumentsCreateRequest.ProcessOption.KnowledgeAugmentation( new String[]{"augment1", "augment2"}); processOption = new DocumentsCreateRequest.ProcessOption( "template1", parser, chunker, knowledgeAugmentation); source = new DocumentsCreateRequest.Source("url", new String[]{"http://example.com"}, 2); // Initialize main class documentsCreateRequest = new DocumentsCreateRequest( "knowledge_base_1", "text/plain", source, processOption); } @Test public void testKnowledgeBaseId() { assertEquals("knowledge_base_1", documentsCreateRequest.getKnowledgeBaseId()); } @Test public void testContentFormat() { assertEquals("text/plain", documentsCreateRequest.getContentFormat()); } @Test public void testSource() { assertEquals("url", documentsCreateRequest.getSource().getType()); assertArrayEquals(new String[]{"http://example.com"}, documentsCreateRequest.getSource().getUrls()); assertEquals(Integer.valueOf(2), documentsCreateRequest.getSource().getUrlDepth()); } @Test public void testProcessOption() { assertEquals("template1", documentsCreateRequest.getProcessOption().getTemplate()); // Test Parser assertArrayEquals(new String[]{"choice1", "choice2"}, documentsCreateRequest.getProcessOption().getParser().getChoices()); // Test Chunker assertArrayEquals(new String[]{"chunkChoice1"}, documentsCreateRequest.getProcessOption().getChunker().getChoices()); assertArrayEquals(new String[]{"info1"}, documentsCreateRequest.getProcessOption().getChunker().getPrependInfo()); // Test Separator assertArrayEquals(new String[]{","}, documentsCreateRequest.getProcessOption().getChunker().getSeparator().getSeparators()); assertEquals(Integer.valueOf(100), documentsCreateRequest.getProcessOption().getChunker().getSeparator().getTargetLength()); assertEquals(Double.valueOf(0.5), documentsCreateRequest.getProcessOption().getChunker().getSeparator().getOverlapRate()); // Test Pattern assertEquals("start", documentsCreateRequest.getProcessOption().getChunker().getPattern().getMarkPosition()); assertEquals("\\w+", documentsCreateRequest.getProcessOption().getChunker().getPattern().getRegex()); assertEquals(Integer.valueOf(200), documentsCreateRequest.getProcessOption().getChunker().getPattern().getTargetLength()); assertEquals(Double.valueOf(0.3), documentsCreateRequest.getProcessOption().getChunker().getPattern().getOverlapRate()); // Test Knowledge Augmentation assertArrayEquals(new String[]{"augment1", "augment2"}, documentsCreateRequest.getProcessOption().getKnowledgeAugmentation().getChoices()); } } ================================================ FILE: java/src/test/java/com/baidubce/appbuilder/model/knowledgebase/FileUploadResponseTest.java ================================================ package com.baidubce.appbuilder.model.knowledgebase; import org.junit.Before; import org.junit.Test; import static org.junit.Assert.assertEquals; public class FileUploadResponseTest { private FileUploadResponse fileUploadResponse; @Before public void setUp() { fileUploadResponse = new FileUploadResponse(); } @Test public void testSetGetRequestId() { fileUploadResponse.setRequestId("request123"); assertEquals("request123", fileUploadResponse.getRequestId()); } @Test public void testSetGetId() { fileUploadResponse.setId("file123"); assertEquals("file123", fileUploadResponse.getId()); } @Test public void testSetGetCode() { fileUploadResponse.setCode("200"); assertEquals("200", fileUploadResponse.getCode()); } @Test public void testSetGetMessage() { fileUploadResponse.setMessage("Upload successful"); assertEquals("Upload successful", fileUploadResponse.getMessage()); } @Test public void testToString() { fileUploadResponse.setRequestId("request123"); fileUploadResponse.setId("file123"); fileUploadResponse.setCode("200"); fileUploadResponse.setMessage("Upload successful"); String expected = "FileUploadResponse{" + "request_id=request123" + ", code='200'" + ", message='Upload successful" + '}'; assertEquals(expected, fileUploadResponse.toString()); } } ================================================ FILE: java/src/test/java/com/baidubce/appbuilder/model/knowledgebase/KnowledgeBaseConfigTest.java ================================================ package com.baidubce.appbuilder.model.knowledgebase; import org.junit.Before; import org.junit.Test; import static org.junit.Assert.assertEquals; import java.beans.Transient; public class KnowledgeBaseConfigTest { private KnowledgeBaseConfig knowledgeBaseConfig; private KnowledgeBaseConfig.Index index; @Before public void setUp() { index = new KnowledgeBaseConfig.Index("es", "clusterId", "user", "password", "bj"); knowledgeBaseConfig = new KnowledgeBaseConfig(index); } @Test public void testGetIndex() { assertEquals(index, knowledgeBaseConfig.getIndex()); } @Test public void testIndexType() { assertEquals("es", index.getType()); } @Test public void testIndexClusterId() { assertEquals("clusterId", index.getClusterId()); } @Test public void testIndexUsername() { assertEquals("user", index.getUsername()); } @Test public void testIndexPassword() { assertEquals("password", index.getPassword()); } @Test public void testIndexLocation() { assertEquals("bj", index.getLocation()); } } ================================================ FILE: java/src/test/java/com/baidubce/appbuilder/model/knowledgebase/KnowledgeBaseDetailRequestTest.java ================================================ package com.baidubce.appbuilder.model.knowledgebase; import org.junit.Before; import org.junit.Test; import static org.junit.Assert.*; public class KnowledgeBaseDetailRequestTest { private KnowledgeBaseDetailRequest knowledgeBaseDetailRequest; @Before public void setUp() { knowledgeBaseDetailRequest = new KnowledgeBaseDetailRequest(); } @Test public void testGetKnowledgeBaseId() { knowledgeBaseDetailRequest.setKnowledgeBaseId("testKnowledgeBaseId"); assertEquals("testKnowledgeBaseId", knowledgeBaseDetailRequest.getKnowledgeBaseId()); } @Test public void testSetKnowledgeBaseId() { knowledgeBaseDetailRequest.setKnowledgeBaseId("newKnowledgeBaseId"); assertEquals("newKnowledgeBaseId", knowledgeBaseDetailRequest.getKnowledgeBaseId()); } } ================================================ FILE: java/src/test/java/com/baidubce/appbuilder/model/knowledgebase/KnowledgeBaseDetailTest.java ================================================ package com.baidubce.appbuilder.model.knowledgebase; import org.junit.Before; import org.junit.Test; import static org.junit.Assert.*; public class KnowledgeBaseDetailTest { private KnowledgeBaseDetail knowledgeBaseDetail; private KnowledgeBaseConfig knowledgeBaseConfig; @Before public void setUp() { knowledgeBaseDetail = new KnowledgeBaseDetail(); knowledgeBaseConfig = new KnowledgeBaseConfig(new KnowledgeBaseConfig.Index("type1", "clusterId", "user", "pass", "location")); } @Test public void testSetGetId() { knowledgeBaseDetail.setId("kb123"); assertEquals("kb123", knowledgeBaseDetail.getId()); } @Test public void testSetGetName() { knowledgeBaseDetail.setName("Knowledge Base Name"); assertEquals("Knowledge Base Name", knowledgeBaseDetail.getName()); } @Test public void testSetGetDescription() { knowledgeBaseDetail.setDescription("This is a knowledge base description."); assertEquals("This is a knowledge base description.", knowledgeBaseDetail.getDescription()); } @Test public void testSetGetConfig() { knowledgeBaseDetail.setConfig(knowledgeBaseConfig); assertEquals(knowledgeBaseConfig, knowledgeBaseDetail.getConfig()); } } ================================================ FILE: java/src/test/java/com/baidubce/appbuilder/model/knowledgebase/KnowledgeBaseListRequestTest.java ================================================ package com.baidubce.appbuilder.model.knowledgebase; import org.junit.Before; import org.junit.Test; import static org.junit.Assert.*; public class KnowledgeBaseListRequestTest { private KnowledgeBaseListRequest knowledgeBaseListRequest; @Before public void setUp() { // 初始化 KnowledgeBaseListRequest 对象 knowledgeBaseListRequest = new KnowledgeBaseListRequest("marker123", 20, "searchKeyword"); } @Test public void testGetMarker() { assertEquals("marker123", knowledgeBaseListRequest.getMarker()); } @Test public void testGetMaxKeys() { assertEquals(20, knowledgeBaseListRequest.getMaxKeys()); } @Test public void testGetKeyword() { assertEquals("searchKeyword", knowledgeBaseListRequest.getKeyword()); } } ================================================ FILE: java/src/test/java/com/baidubce/appbuilder/model/knowledgebase/KnowledgeBaseListResponseTest.java ================================================ package com.baidubce.appbuilder.model.knowledgebase; import org.junit.Before; import org.junit.Test; import static org.junit.Assert.*; public class KnowledgeBaseListResponseTest { private KnowledgeBaseListResponse knowledgeBaseListResponse; private KnowledgeBaseDetail knowledgeBaseDetail1; private KnowledgeBaseDetail knowledgeBaseDetail2; @Before public void setUp() { knowledgeBaseListResponse = new KnowledgeBaseListResponse(); // Initialize KnowledgeBaseDetail objects (assuming KnowledgeBaseDetail has default constructor and setters) knowledgeBaseDetail1 = new KnowledgeBaseDetail(); knowledgeBaseDetail1.setId("kb1"); knowledgeBaseDetail1.setName("KnowledgeBase 1"); knowledgeBaseDetail2 = new KnowledgeBaseDetail(); knowledgeBaseDetail2.setId("kb2"); knowledgeBaseDetail2.setName("KnowledgeBase 2"); knowledgeBaseListResponse.setRequestId("testRequestId"); knowledgeBaseListResponse.setData(new KnowledgeBaseDetail[]{knowledgeBaseDetail1, knowledgeBaseDetail2}); knowledgeBaseListResponse.setMarker("testMarker"); knowledgeBaseListResponse.setTruncated(true); knowledgeBaseListResponse.setNextMarker("testNextMarker"); knowledgeBaseListResponse.setMaxKeys(100); } @Test public void testRequestId() { assertEquals("testRequestId", knowledgeBaseListResponse.getRequestId()); } @Test public void testData() { KnowledgeBaseDetail[] data = knowledgeBaseListResponse.getData(); assertNotNull(data); assertEquals(2, data.length); assertEquals("kb1", data[0].getId()); assertEquals("KnowledgeBase 1", data[0].getName()); assertEquals("kb2", data[1].getId()); assertEquals("KnowledgeBase 2", data[1].getName()); } @Test public void testMarker() { assertEquals("testMarker", knowledgeBaseListResponse.getMarker()); } @Test public void testIsTruncated() { assertTrue(knowledgeBaseListResponse.isTruncated()); } @Test public void testNextMarker() { assertEquals("testNextMarker", knowledgeBaseListResponse.getNextMarker()); } @Test public void testMaxKeys() { assertEquals(100, knowledgeBaseListResponse.getMaxKeys()); } } ================================================ FILE: java/src/test/java/com/baidubce/appbuilder/model/knowledgebase/KnowledgeBaseModifyRequestTest.java ================================================ package com.baidubce.appbuilder.model.knowledgebase; import org.junit.Before; import org.junit.Test; import static org.junit.Assert.assertEquals; public class KnowledgeBaseModifyRequestTest { private KnowledgeBaseModifyRequest knowledgeBaseModifyRequest; @Before public void setUp() { knowledgeBaseModifyRequest = new KnowledgeBaseModifyRequest(); } @Test public void testSetGetKnowledgeBaseId() { knowledgeBaseModifyRequest.setKnowledgeBaseId("kb123"); assertEquals("kb123", knowledgeBaseModifyRequest.getKnowledgeBaseId()); } @Test public void testSetGetName() { knowledgeBaseModifyRequest.setName("New Knowledge Base"); assertEquals("New Knowledge Base", knowledgeBaseModifyRequest.getName()); } @Test public void testSetGetDescription() { knowledgeBaseModifyRequest.setDescription("This is a description for the knowledge base."); assertEquals("This is a description for the knowledge base.", knowledgeBaseModifyRequest.getDescription()); } } ================================================ FILE: java/src/test/java/com/baidubce/appbuilder/model/rag/EventContentTest.java ================================================ package com.baidubce.appbuilder.model.rag; import org.junit.Before; import org.junit.Test; import java.util.HashMap; import java.util.Map; import static org.junit.Assert.*; public class EventContentTest { private EventContent eventContent; @Before public void setUp() { eventContent = new EventContent(); } @Test public void testGetSetEventCode() { eventContent.setEventCode("eventCode123"); assertEquals("eventCode123", eventContent.getEventCode()); } @Test public void testGetSetEnentMessage() { eventContent.setEnentMessage("message123"); assertEquals("message123", eventContent.getEnentMessage()); } @Test public void testGetSetNodeName() { eventContent.setNodeName("nodeName123"); assertEquals("nodeName123", eventContent.getNodeName()); } @Test public void testGetSetDependencyNodes() { String[] dependencyNodes = new String[]{"node1", "node2"}; eventContent.setDependencyNodes(dependencyNodes); assertArrayEquals(dependencyNodes, eventContent.getDependencyNodes()); } @Test public void testGetSetEventType() { eventContent.setEventType("eventType123"); assertEquals("eventType123", eventContent.getEventType()); } @Test public void testGetSetEventId() { eventContent.setEventId("eventId123"); assertEquals("eventId123", eventContent.getEventId()); } @Test public void testGetSetEventStatus() { eventContent.setEventStatus("eventStatus123"); assertEquals("eventStatus123", eventContent.getEventStatus()); } @Test public void testGetSetContentType() { eventContent.setContentType("contentType123"); assertEquals("contentType123", eventContent.getContentType()); } @Test public void testGetSetOutputs() { Map outputs = new HashMap<>(); outputs.put("outputKey", "outputValue"); eventContent.setOutputs(outputs); assertEquals(outputs, eventContent.getOutputs()); } @Test public void testGetSetDetail() { HashMap detail = new HashMap<>(); detail.put("key1", "value1"); eventContent.setDetail(detail); assertEquals(detail, eventContent.getDetail()); } @Test public void testToString() { eventContent.setEventCode("eventCode123"); eventContent.setEnentMessage("message123"); eventContent.setNodeName("nodeName123"); eventContent.setDependencyNodes(new String[]{"node1", "node2"}); eventContent.setEventType("eventType123"); eventContent.setEventId("eventId123"); eventContent.setEventStatus("eventStatus123"); eventContent.setContentType("contentType123"); String expected = "EventContent{eventCode='eventCode123', enentMessage='message123', nodeName='nodeName123', dependencyNodes=[node1, node2], eventType='eventType123', eventId='eventId123', eventStatus='eventStatus123', contentType='contentType123', outputs=null, detail=null}"; assertEquals(expected, eventContent.toString()); } } ================================================ FILE: java/src/test/java/com/baidubce/appbuilder/model/rag/RAGResponseTest.java ================================================ package com.baidubce.appbuilder.model.rag; import org.junit.Before; import org.junit.Test; import static org.junit.Assert.assertEquals; public class RAGResponseTest { private RAGResponse ragResponse; @Before public void setUp() { ragResponse = new RAGResponse(); } @Test public void testSetGetCode() { ragResponse.setCode(200); assertEquals(200, ragResponse.getCode()); } @Test public void testSetGetMessage() { ragResponse.setMessage("Success"); assertEquals("Success", ragResponse.getMessage()); } @Test public void testSetGetTraceId() { ragResponse.setTraceId("trace12345"); assertEquals("trace12345", ragResponse.getTraceId()); } @Test public void testSetGetTime() { ragResponse.setTime(123456789); assertEquals(123456789L, ragResponse.getTime()); } @Test public void testSetGetResult() { RAGResult mockResult = new RAGResult(); // 假设有 RAGResult 类 ragResponse.setResult(mockResult); assertEquals(mockResult, ragResponse.getResult()); } @Test public void testToString() { ragResponse.setCode(200); ragResponse.setMessage("Success"); ragResponse.setTraceId("trace12345"); ragResponse.setTime(123456789); RAGResult mockResult = new RAGResult(); // 假设有 RAGResult 类 ragResponse.setResult(mockResult); String expected = "RAGResponse{" + "code=200" + ", message='Success'" + ", traceId='trace12345'" + ", time=123456789" + ", result=" + mockResult + '}'; assertEquals(expected, ragResponse.toString()); } } ================================================ FILE: java/src/test/java/com/baidubce/appbuilder/model/rag/RAGResultTest.java ================================================ package com.baidubce.appbuilder.model.rag; import org.junit.Before; import org.junit.Test; import java.util.Arrays; // 导入 java.util.Arrays import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertArrayEquals; public class RAGResultTest { private RAGResult ragResult; @Before public void setUp() { ragResult = new RAGResult(); } @Test public void testSetGetAnswer() { ragResult.setAnswer("This is an answer."); assertEquals("This is an answer.", ragResult.getAnswer()); } @Test public void testSetGetConversationId() { ragResult.setConversationId("conv123"); assertEquals("conv123", ragResult.getConversationId()); } @Test public void testSetGetMessageId() { ragResult.setMessageId("msg456"); assertEquals("msg456", ragResult.getMessageId()); } @Test public void testSetGetIsCompletion() { ragResult.setIsCompletion(true); // 可以是任意对象,通常是Boolean assertEquals(true, ragResult.getIsCompletion()); } @Test public void testSetGetPrototype() { ragResult.setPrototype("prototype data"); assertEquals("prototype data", ragResult.getPrototype()); } @Test public void testSetGetContent() { EventContent[] mockContent = new EventContent[2]; mockContent[0] = new EventContent(); mockContent[0].setEventCode("event1"); mockContent[1] = new EventContent(); mockContent[1].setEventCode("event2"); ragResult.setContent(mockContent); assertArrayEquals(mockContent, ragResult.getContent()); } @Test public void testToString() { ragResult.setAnswer("This is an answer."); ragResult.setConversationId("conv123"); ragResult.setMessageId("msg456"); ragResult.setIsCompletion(true); ragResult.setPrototype("prototype data"); EventContent[] mockContent = new EventContent[2]; mockContent[0] = new EventContent(); mockContent[0].setEventCode("event1"); mockContent[1] = new EventContent(); mockContent[1].setEventCode("event2"); ragResult.setContent(mockContent); String expected = "RAGResult{" + "answer='This is an answer.'" + ", conversationId='conv123'" + ", messageId='msg456'" + ", isCompletion=true" + ", prototype='prototype data'" + ", content=" + Arrays.toString(mockContent) + '}'; assertEquals(expected, ragResult.toString()); } } ================================================ FILE: mkdocs.yml ================================================ site_name: Appbuilder-SDK # 网站页面结构和导航配置 nav: - 首页: README.md - 快速上手: - 开始你的第一个AI原生应用: - 安装: QuickStart/StartFirstAINativeApplication/install.md - 快速开始: QuickStart/StartFirstAINativeApplication/README.md - 产业实践应用范例: - SDK使用示例: QuickStart/ExamplesOfIndustrialPracticeApplications/README.md - SDK当前支持的编程语言: QuickStart/CurrentlySupportedProgrammingLanguages/README.md - 基础: - 模型: - 获取模型列表: BasisModule/Model/get_model_list.md - 组件: - 语义匹配(Matching): BasisModule/Components/matching/README.md - 表格文字识别 (TableOCR): BasisModule/Components/table_ocr/README.md - 文件生成PPT(PPTGenerationFromFile): BasisModule/Components/ppt_generation_from_file/README.md - GBI 选表: BasisModule/Components/gbi/select_table/README.md - GBI 问表: BasisModule/Components/gbi/nl2sql/README.md - 向量计算(Embedding): BasisModule/Components/embeddings/README.md - 论文生成PPT(PPTGenerationFromPaper): BasisModule/Components/ppt_generation_from_paper/README.md - 地标识别(LandmarkRecognition): BasisModule/Components/landmark_recognize/README.md - 手写文字识别 (HandwriteOCR): BasisModule/Components/handwrite_ocr/README.md - 通用文字识别-高精度版(GeneralOCR): BasisModule/Components/general_ocr/README.md - 文本翻译-通用版(Translation): BasisModule/Components/translate/README.md - 百度搜索RAG(deprecate): BasisModule/Components/rag_with_baidu_search/README.md - 文档切分(DocSplitter): BasisModule/Components/doc_splitter/README.md - 表格抽取组件(ExtractTableFromDoc): BasisModule/Components/extract_table/README.md - 向量检索: BasisModule/Components/retriever/README.md - 文本精排(Reranker): BasisModule/Components/retriever/reranker/README.md - 向量检索-VectorDB(BaiduVectorDBRetriever): BasisModule/Components/retriever/baidu_vdb/README.md - 向量检索-BES(BaiduElasticSearchRetriever): BasisModule/Components/retriever/bes/README.md - 通用物体和场景识别-高级版(ObjectRecognition): BasisModule/Components/object_recognize/README.md - 文档解析(DocParser): BasisModule/Components/doc_parser/README.md - 文档格式转换 (DocFormatConverter): BasisModule/Components/doc_format_converter/README.md - 身份证混贴识别(MixCardOCR): BasisModule/Components/mix_card_ocr/README.md - 短语音识别-极速版 (Automatic Speech Recognition): BasisModule/Components/asr/README.md - 文生图 (Text2Image): BasisModule/Components/text_to_image/README.md - 长文档内容理解(DocumentUnderstanding): BasisModule/Components/document_understanding/README.md - 短文本在线合成(TTS): BasisModule/Components/tts/README.md - 植物识别(PlantRecognition): BasisModule/Components/plant_recognize/README.md - 树图 (TreeMind): BasisModule/Components/tree_mind/README.md - 菜品识别(DishRecognition): BasisModule/Components/dish_recognize/README.md - 指令生成PPT(PPTGenerationFromInstruction): BasisModule/Components/ppt_generation_from_instruction/README.md - 动物识别 (AnimalRecognition): BasisModule/Components/animal_recognize/README.md - 百度搜索RAG_PRO: BasisModule/Components/rag_with_baidu_search_pro/README.md - 二维码识别 (QRcodeOCR): BasisModule/Components/qrcode_ocr/README.md - 复杂Query判定(IsComplexQuery): BasisModule/Components/llms/is_complex_query/README.md - 空应用(Playground): BasisModule/Components/llms/playground/README.md - 口语化Query生成(Oral Query Generation): BasisModule/Components/llms/oral_query_generation/README.md - 阅读理解问答(MRC): BasisModule/Components/llms/mrc/README.md - 多轮改写 (QueryRewrite): BasisModule/Components/llms/query_rewrite/README.md - 风格写作(StyleWriting): BasisModule/Components/llms/style_writing/README.md - 复杂Query分解(QueryDecomposition): BasisModule/Components/llms/query_decomposition/README.md - 会话小结(DialogSummary): BasisModule/Components/llms/dialog_summary/README.md - 幻觉检测(Hallucination Detection): BasisModule/Components/llms/hallucination_detection/README.md - 相似问生成(SimilarQuestion): BasisModule/Components/llms/similar_question/README.md - 标签抽取(TagExtraction): BasisModule/Components/llms/tag_extraction/README.md - 问答对挖掘(QAPairMining): BasisModule/Components/llms/qa_pair_mining/README.md - 风格转写 (StyleRewrite): BasisModule/Components/llms/style_rewrite/README.md - 自然语言转pandas (nl2pandas): BasisModule/Components/llms/nl2pandas/README.md - 文档矫正增强 (DocCropEnhance): BasisModule/Components/doc_crop_enhance/README.md - 图像内容理解 (ImageUnderstand): BasisModule/Components/image_understand/README.md - 监控: - TRACE基础功能: BasisModule/Trace/basic.md - TRACE拓展功能: BasisModule/Trace/phoenix_method.md - Debug功能: BasisModule/Trace/Debug.md - 部署: - 交互式前端部署: BasisModule/Deployment/AgentChainlit.md - 公有云部署: BasisModule/Deployment/cloud.md - API 访问: BasisModule/Deployment/flask.md - AgentRuntime: BasisModule/Deployment/agentruntime.md - UserSession: BasisModule/Deployment/usersession.md - 平台: - 应用: - AppBuilderClient组件: BasisModule/Platform/Application/appbuilder_client.md - 获取AppBuilder已发布的应用列表: BasisModule/Platform/Application/get_app_list.md - 知识库: - 知识库组件: BasisModule/Platform/KnowledgeBase/knowledgebase.md - 自定义组件: - 基础能力组件: BasisModule/Platform/CustomComponents/components.md - 应用: - Agent: - 基础知识: Application/Agent/BasicKnowledge/agent.md - 使用官方组件: Application/Agent/UseOfficialComponents/use_official_components.md - ToolCall: Application/Agent/ToolCall/tool_call.md - ToolChoice: Application/Agent/ToolChoice/tool_choice.md # - 使用异步和流式加速客户端调用: - RAG: - 基础知识: Application/RAG/BasicKnowledge/rag.md - 知识库管理: Application/RAG/DatasetManage/dataset_manage.md # - Reference信息处理: # - Workflow: # - 基础知识: # - 从零使用Workflow组装一个RAG应用: # - 从零使用Workflow组装一个Agent应用: - 开发者指南: - 如何贡献代码: DevelopGuide/HowToContributeCode/README.md - 二次开发: DevelopGuide/AdvancedDevelopment/README.md - 版本升级日志: DevelopGuide/ChangeLog/changelog.md - 错误信息: DevelopGuide/ErrorMessage/error_message.md - 环境参数: DevelopGuide/EnvironmentalParameters/env.md - API Reference: - Python API Reference: API-Reference/Python/PythonAPI.md - Java API Reference: API-Reference/Java/JavaAPI.md # - Go API Reference: # 主题设置 theme: name: material # 插件列表 plugins: - search # 其他配置 markdown_extensions: - codehilite - toc: permalink: true ================================================ FILE: python/__init__.py ================================================ # Copyright (c) 2023 Baidu, Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. __version__ = '1.1.5' import os import sys import copy import pydantic class PythonVersionChecker: def __init__(self): self.min_version = (3, 9) self.current_version = sys.version_info self.check_version() def check_version(self): if self.current_version < self.min_version: raise EnvironmentError( f"Mismatched Python version. Expected Python version >= {self.min_version[0]}.{self.min_version[1]}, " f"Got Python version {self.current_version[0]}.{self.current_version[1]}.") # Creating an instance to test the function checker = PythonVersionChecker() checker.current_version class SDKReportConfig(pydantic.BaseModel): appbuilder_sdk_version: str = __version__ appbuilder_sdk_language: str = "python" appbuilder_sdk_platform: str = os.environ.get("APPBUILDER_SDK_PLATFORM", "unknown") appbuilder_sdk_mcp_context: str = None def get_default_header(mcp_context: str = None): if not mcp_context: mcp_context = os.environ.get( "APPBUILDER_SDK_MCP_CONTEXT", None ) if mcp_context: sdk_report_config = SDKReportConfig(appbuilder_sdk_mcp_context=mcp_context) else: sdk_report_config = SDKReportConfig() default_header = { "X-Appbuilder-Sdk-Config": sdk_report_config.model_dump_json(exclude_none=True), "X-Appbuilder-Origin": "appbuilder_sdk", } return copy.deepcopy(default_header) from .core import * from .core.components.rag_with_baidu_search_pro import RagWithBaiduSearchPro from .core.components.rag_with_baidu_search import RAGWithBaiduSearch from .core import console from .core.components.llms.mrc import MRC from .core.components.llms.oral_query_generation import OralQueryGeneration from .core.components.llms.qa_pair_mining import QAPairMining from .core.components.llms.similar_question import SimilarQuestion from .core.components.llms.style_writing import StyleWriting from .core.components.llms.style_rewrite import StyleRewrite from .core.components.llms.tag_extraction import TagExtraction from .core.components.llms.nl2pandas import Nl2pandasComponent from .core.components.llms.query_rewrite import QueryRewrite from .core.components.llms.dialog_summary import DialogSummary from .core.components.llms.is_complex_query import IsComplexQuery from .core.components.llms.query_decomposition import QueryDecomposition from .core.components.llms.hallucination_detection import HallucinationDetection from .core.components.llms.playground import Playground from .core.components.asr.component import ASR from .core.components.general_ocr.component import GeneralOCR from .core.components.object_recognize.component import ObjectRecognition from .core.components.text_to_image.component import Text2Image from .core.components.landmark_recognize.component import LandmarkRecognition from .core.components.tts.component import TTS from .core.components.extract_table.component import ExtractTableFromDoc from .core.components.doc_parser.component import DocParser, ParserConfig from .core.components.doc_splitter.component import DocSplitter from .core.components.retriever.bes.component import BESRetriever from .core.components.retriever.bes.component import BESVectorStoreIndex from .core.components.retriever.baidu_vdb.component import BaiduVDBVectorStoreIndex from .core.components.retriever.baidu_vdb.component import BaiduVDBRetriever from .core.components.retriever.baidu_vdb.component import TableParams from .core.components.retriever.reranker.component import Reranker from .core.components.ppt_generation_from_instruction.component import PPTGenerationFromInstruction from .core.components.ppt_generation_from_paper.component import PPTGenerationFromPaper from .core.components.ppt_generation_from_file.component import PPTGenerationFromFile from .core.components.dish_recognize.component import DishRecognition from .core.components.translate.component import Translation from .core.components.animal_recognize.component import AnimalRecognition from .core.components.doc_crop_enhance.component import DocCropEnhance from .core.components.qrcode_ocr.component import QRcodeOCR from .core.components.table_ocr.component import TableOCR from .core.components.doc_format_converter.component import DocFormatConverter from .core.components.embeddings import Embedding from .core.components.matching import Matching from .core.components.gbi.nl2sql.component import NL2Sql from .core.components.gbi.select_table.component import SelectTable from .core.components.plant_recognize.component import PlantRecognition from .core.components.handwrite_ocr.component import HandwriteOCR from .core.components.image_understand.component import ImageUnderstand from .core.components.mix_card_ocr.component import MixCardOCR from .core.components.document_understanding.component import DocumentUnderstanding from .core.components.tree_mind.component import TreeMind __COMPONENTS__ = [ "RagWithBaiduSearchPro", "RAGWithBaiduSearch", "MRC", "OralQueryGeneration", "QAPairMining", "SimilarQuestion", "StyleWriting", "StyleRewrite", "TagExtraction", "Nl2pandasComponent", "QueryRewrite", "DialogSummary", "HallucinationDetection", "Playground", "ASR", "GeneralOCR", "ObjectRecognition", "Text2Image", "LandmarkRecognition", "TTS", "ExtractTableFromDoc", "DocParser", "DocSplitter", "BESRetriever", "BESVectorStoreIndex", "BaiduVDBVectorStoreIndex", "BaiduVDBRetriever", "TableParams", "Reranker", "PPTGenerationFromInstruction", "PPTGenerationFromPaper", "PPTGenerationFromFile", "DishRecognition", "Translation", "AnimalRecognition", "DocCropEnhance", "QRcodeOCR", "TableOCR", "DocFormatConverter", "Embedding", "Matching", "NL2Sql", "SelectTable", "PlantRecognition", "HandwriteOCR", "ImageUnderstand", "MixCardOCR", "DocumentUnderstanding", "TreeMind" ] # NOQA from appbuilder.core.message import Message from appbuilder.core.agent import AgentRuntime from appbuilder.core.user_session import UserSession from appbuilder.utils.logger_util import logger from appbuilder.core.manifest.manifest_decorator import manifest, manifest_parameter from appbuilder.core.manifest.models import Manifest from appbuilder.core.utils import get_model_list from appbuilder.core.console.appbuilder_client.appbuilder_client import AppBuilderClient from appbuilder.core.console.appbuilder_client.async_appbuilder_client import AsyncAppBuilderClient from appbuilder.core.console.ai_search import AISearch from appbuilder.core.console.appbuilder_client.appbuilder_client import AgentBuilder from appbuilder.core.console.appbuilder_client.appbuilder_client import get_app_list, get_all_apps, describe_apps, describe_app from appbuilder.core.console.component_client.component_client import ComponentClient from appbuilder.core.console.knowledge_base.knowledge_base import KnowledgeBase from appbuilder.core.console.knowledge_base.data_class import CustomProcessRule, DocumentSource, DocumentChoices, DocumentChunker, DocumentSeparator, DocumentPattern, DocumentProcessOption, DocumentSourceUrlConfig from .core._exception import ( BadRequestException, ForbiddenException, NotFoundException, PreconditionFailedException, InternalServerErrorException, HTTPConnectionException, AppBuilderServerException, AppbuilderTraceException, ) from appbuilder.core.assistant.base import assistant from appbuilder.core.assistant.threads.runs import StreamRunContext from appbuilder.core.assistant.threads.runs import AssistantEventHandler from appbuilder.core.assistant.threads.runs import AssistantStreamManager from appbuilder.utils.trace.tracer import AppBuilderTracer, AppbuilderInstrumentor from .utils.logger_file_headler import SizeAndTimeRotatingFileHandler __all__ = [ "logger", "SizeAndTimeRotatingFileHandler", "BadRequestException", "ForbiddenException", "NotFoundException", "PreconditionFailedException", "InternalServerErrorException", "HTTPConnectionException", "AppBuilderServerException", "AppbuilderTraceException", "AppbuilderTestToolEval", "AutomaticTestToolEval", "get_model_list", "AppBuilderClient", "AsyncAppBuilderClient", "AISearch", "AgentBuilder", "ComponentClient", "get_app_list", "get_all_apps", "describe_apps", "describe_app", "KnowledgeBase", "CustomProcessRule", "DocumentSource", "DocumentChoices", "DocumentChunker", "DocumentSeparator", "DocumentPattern", "DocumentProcessOption", "DocumentSourceUrlConfig" "assistant", "StreamRunContext", "AssistantEventHandler", "AssistantStreamManager", "AppBuilderTracer", "AppbuilderInstrumentor", ] + __COMPONENTS__ ================================================ FILE: python/core/__init__.py ================================================ # Copyright (c) 2023 Baidu, Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. ================================================ FILE: python/core/_client.py ================================================ # Copyright (c) 2023 Baidu, Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Base client for interact with backend server""" import os import uuid from typing import Optional import requests from requests.adapters import HTTPAdapter, Retry from aiohttp import ClientResponse from appbuilder.utils.logger_util import logger from appbuilder import get_default_header from appbuilder.core._exception import * from appbuilder.core._session import InnerSession, AsyncInnerSession from appbuilder.core.constants import ( GATEWAY_URL, GATEWAY_URL_V2, CONSOLE_OPENAPI_VERSION, CONSOLE_OPENAPI_PREFIX, SECRET_KEY_PREFIX, ) from appbuilder.utils.logger_util import logger class HTTPClient: r"""HTTPClient类,实现与后端服务交互的公共方法""" def __init__( self, secret_key: Optional[str] = None, gateway: str = "", gateway_v2: str = "" ): r"""HTTPClient初始化方法. 参数: secret_key(str,可选): 用户鉴权token, 默认从环境变量中获取: os.getenv("APPBUILDER_TOKEN", ""). gateway(str, 可选): 后端网关服务地址,默认从环境变量中获取: os.getenv("GATEWAY_URL", "") gateway_v2(str, 可选): 后端OpenAPI网关服务地址,当前仅AgentBuilder使用。默认从环境变量中获取: os.getenv("GATEWAY_URL_V2", "") 返回: 无 """ self._init_secret_key(secret_key) # Component self._init_gateway_url(gateway) # Console OpenAPI self._init_gateway_url_v2(gateway_v2) self.session = InnerSession() self.retry = Retry(total=0, backoff_factor=0.1) self.session.mount(self.gateway, HTTPAdapter(max_retries=self.retry)) def _init_gateway_url(self, gateway: str): if not gateway and not os.getenv("GATEWAY_URL"): self.gateway = GATEWAY_URL else: self.gateway = gateway if gateway else os.getenv("GATEWAY_URL", "") if not self.gateway.startswith("http"): self.gateway = "https://" + self.gateway def _init_gateway_url_v2(self, gateway_v2: str): if not gateway_v2 and not os.getenv("GATEWAY_URL_V2"): self.gateway_v2 = GATEWAY_URL_V2 else: self.gateway_v2 = ( gateway_v2 if gateway_v2 else os.getenv("GATEWAY_URL_V2", "") ) if not self.gateway_v2.startswith("http"): self.gateway_v2 = "https://" + self.gateway_v2 self.console_openapi_verion = os.getenv( "CONSOLE_OPENAPI_VERSION", CONSOLE_OPENAPI_VERSION ) self.console_openapi_prefix = os.getenv( "CONSOLE_OPENAPI_PREFIX", CONSOLE_OPENAPI_PREFIX ) def _init_secret_key(self, secret_key: str): self.secret_key = ( secret_key if secret_key else os.getenv("APPBUILDER_TOKEN", "") ) if not self.secret_key: raise ValueError( "secret_key is empty, please pass a nonempty secret_key " 'or set a secret_key in environment variable "APPBUILDER_TOKEN"' ) secret_key_prefix = os.getenv("SECRET_KEY_PREFIX", SECRET_KEY_PREFIX) if not self.secret_key.startswith(secret_key_prefix): self.secret_key = "{} {}".format( secret_key_prefix, self.secret_key) logger.debug("AppBuilder Secret key: {}\n".format(self.secret_key)) @staticmethod def check_response_header(response: requests.Response): r"""check_response_header is a helper method for check head status . :param response: requests.Response. :rtype: """ status_code = response.status_code if status_code == requests.codes.ok: response_headers = "\n\t".join([f"{key} : {value}" for key, value in response.headers.items()]) message = "\nrequest_id : {} \nhttp status : {}\nresponse headers : \n\t{}".format( __class__.response_request_id(response), status_code, response_headers ) logger.debug(message) return message = "request_id={} , http status code is {}, body is {}".format( __class__.response_request_id(response), status_code, response.text ) if status_code == requests.codes.bad_request: logger.error(message) raise BadRequestException(message) elif status_code == requests.codes.unauthorized: logger.error(message) raise UnAuthorizedException(message) elif status_code == requests.codes.forbidden: logger.error(message) raise ForbiddenException(message) elif status_code == requests.codes.not_found: logger.error(message) raise NotFoundException(message) elif status_code == requests.codes.method_not_allowed: logger.error(message) raise MethodNotAllowedException(message) elif status_code == requests.codes.conflict: logger.error(message) raise ConflictException(message) elif status_code == requests.codes.length_required: logger.error(message) raise MissingContentLengthException(message) elif status_code == requests.codes.precondition_required: logger.error(message) raise PreconditionFailedException(message) elif status_code == requests.codes.unprocessable_entity: logger.error(message) raise UnprocessableEntityException(message) elif status_code == requests.codes.failed_dependency: logger.error(message) raise DependencyFailedException(message) elif status_code == requests.codes.too_many_requests: logger.error(message) raise TooManyRequestsException(message) elif status_code == requests.codes.internal_server_error: logger.error(message) raise InternalServerErrorException(message) elif status_code == requests.codes.insufficient_storage: logger.error(message) raise InsufficientStorageException(message) else: logger.error(message) raise BaseRPCException(message) def service_url(self, sub_path: str, prefix: str = None): r"""service_url is a helper method for concatenate service url. :param sub_path: service unique sub path. :param prefix: service prefix. :rtype: str. """ # host + fix prefix + sub service path prefix = prefix if prefix else "/rpc/2.0/cloud_hub" final_url = self.gateway + prefix + sub_path logger.debug("Service url: {}\n".format(final_url)) return final_url def service_url_v2(self, sub_path: str, client_token: str = None): r"""service_url is a helper method for concatenate service url for OpenAPI, only used by AppBuilderClient. :param sub_path: service unique sub path. :rtype: str. """ # console_prefix = final_url = ( self.gateway_v2 + self.console_openapi_prefix + self.console_openapi_verion + sub_path ) if client_token: if "?" in final_url: final_url += "&clientToken=" + client_token else: final_url += "?clientToken=" + client_token logger.debug("Service url: {}\n".format(final_url)) return final_url @staticmethod def check_response_json(data: dict): r"""check_response_json is a helper method for check backend server response. :param: dict, body response data. :rtype: str. """ if "code" in data and "message" in data and "requestId" in data: raise AppBuilderServerException( data["requestId"], data["code"], data["message"] ) @staticmethod def check_console_response(response: requests.Response): r"""check_console_response is a helper method for console check backend server response. :param: dict, body response data. :rtype: str. """ data = response.json() if "code" in data and data.get("code") != 0: requestId = __class__.response_request_id(response) raise AppBuilderServerException( requestId, data["code"], data["message"]) def auth_header(self, request_id: Optional[str] = None): r"""auth_header is a helper method return auth info""" auth_header = get_default_header() new_request_id = str(uuid.uuid4()) auth_header["X-Appbuilder-Request-Id"] = ( request_id if request_id else new_request_id ) auth_header["X-Bce-Request-Id"] = request_id if request_id else new_request_id auth_header["X-Appbuilder-Authorization"] = self.secret_key logger.debug("Request header: {}\n".format(auth_header)) return auth_header def auth_header_v2(self, request_id: Optional[str] = None, mcp_context = None): r"""auth_header_v2 is a helper method return auth info for OpenAPI, only used by AppBuilderClient""" auth_header = get_default_header(mcp_context) new_request_id = str(uuid.uuid4()) auth_header["X-Appbuilder-Request-Id"] = ( request_id if request_id else new_request_id ) auth_header["X-Bce-Request-Id"] = request_id if request_id else new_request_id auth_header["Authorization"] = self.secret_key logger.debug("Request header: {}\n".format(auth_header)) return auth_header @staticmethod def response_request_id(response: requests.Response): r"""response_request_id is a helper method get unique request id""" return response.headers.get("X-Appbuilder-Request-Id", "") @staticmethod def check_param(func): def inner(*args, **kwargs): retry = kwargs.get("retry", 0) if retry < 0 or not isinstance(retry, int): raise InvalidRequestArgumentError( 'Rqeuest argument "retry" format error. Expected retry >=0. Got {}'.format( retry ) ) timeout = kwargs.get("timeout", None) if timeout and not ( isinstance(timeout, float) or isinstance(timeout, tuple) ): raise InvalidRequestArgumentError( 'Request argument "timeout" format error, Expected timeout be float or tuple of float' ) return func(*args, **kwargs) return inner @staticmethod def classify_exception(e): """classify exception type and raise""" from requests.exceptions import HTTPError # 定义需要直接抛出的异常类型列表 custom_exceptions = ( AppBuilderServerException, NoFileUploadedExecption, InvalidRequestArgumentError, RetryableExecption, RiskInputException, InternalServerException, AssistantServerException ) if isinstance(e, HTTPError): __class__.check_response_header(e.response) elif isinstance(e, custom_exceptions): # 检查异常是否属于自定义的类型 raise e else: #未定义的错误使用InternalServerException兜底 raise InternalServerException(str(e)) class AsyncHTTPClient(HTTPClient): def __init__(self, secret_key=None, gateway="", gateway_v2=""): super().__init__(secret_key, gateway, gateway_v2) self.session = AsyncInnerSession() @staticmethod async def check_response_header(response: ClientResponse): r"""check_response_header is a helper method for check head status . :param response: requests.Response. :rtype: """ status_code = response.status if status_code == requests.codes.ok: return message = "request_id={} , http status code is {}, body is {}".format( await __class__.response_request_id(response), status_code, await response.text() ) if status_code == requests.codes.bad_request: logger.error(message) raise BadRequestException(message) elif status_code == requests.codes.unauthorized: logger.error(message) raise UnAuthorizedException(message) elif status_code == requests.codes.forbidden: logger.error(message) raise ForbiddenException(message) elif status_code == requests.codes.not_found: logger.error(message) raise NotFoundException(message) elif status_code == requests.codes.method_not_allowed: logger.error(message) raise MethodNotAllowedException(message) elif status_code == requests.codes.conflict: logger.error(message) raise ConflictException(message) elif status_code == requests.codes.length_required: logger.error(message) raise MissingContentLengthException(message) elif status_code == requests.codes.precondition_required: logger.error(message) raise PreconditionFailedException(message) elif status_code == requests.codes.unprocessable_entity: logger.error(message) raise UnprocessableEntityException(message) elif status_code == requests.codes.failed_dependency: logger.error(message) raise DependencyFailedException(message) elif status_code == requests.codes.too_many_requests: logger.error(message) raise TooManyRequestsException(message) elif status_code == requests.codes.internal_server_error: logger.error(message) raise InternalServerErrorException(message) elif status_code == requests.codes.insufficient_storage: logger.error(message) raise InsufficientStorageException(message) else: logger.error(message) raise BaseRPCException(message) @staticmethod async def response_request_id(response: ClientResponse): r"""response_request_id is a helper method to get the unique request id""" return response.headers.get("X-Appbuilder-Request-Id", "") @staticmethod async def classify_exception(e): """classify exception type and raise""" from requests.exceptions import HTTPError # 定义需要直接抛出的异常类型列表 custom_exceptions = ( AppBuilderServerException, NoFileUploadedExecption, InvalidRequestArgumentError, RetryableExecption, RiskInputException, InternalServerException, AssistantServerException ) if isinstance(e, HTTPError): await __class__.check_response_header(e.response) elif isinstance(e, custom_exceptions): # 检查异常是否属于自定义的类型 raise e else: #未定义的错误使用InternalServerException兜底 raise InternalServerException(str(e)) class AssistantHTTPClient(HTTPClient): def service_url(self, sub_path: str, prefix: str = None): """ 根据给定的子路径和前缀,返回完整的服务URL。 Args: sub_path (str): 子路径,例如 "/api/v1/user"。 prefix (str, optional): URL前缀,例如 "http://example.com"。默认为None。 Returns: str: 完整的服务URL,例如 "http://example.com/api/v1/user"。 """ prefix = prefix if prefix else "" return self.gateway + prefix + sub_path def auth_header(self, request_id: Optional[str] = None): """ 返回一个包含认证信息的字典 Args: 无参数。 """ r"""auth_header is a helper method return auth info""" auth_header = get_default_header() auth_header["Authorization"] = self.secret_key new_request_id = str(uuid.uuid4()) auth_header["X-Appbuilder-Request-Id"] = ( request_id if request_id else new_request_id ) auth_header["X-Bce-Request-Id"] = request_id if request_id else new_request_id auth_header["X-Appbuilder-Authorization"] = self.secret_key auth_header["Content-Type"] = "application/json" logger.debug("Request header: {}\n".format(auth_header)) return auth_header @staticmethod def check_assistant_response(request_id, data): """ 检查助手的响应结果,如果返回了错误信息,则抛出 AssistantServerException 异常。 Args: request_id (str): 请求 ID。 data (dict): 助手返回的响应数据。 Returns: None Raises: AssistantServerException: 如果助手返回了错误信息,则抛出该异常。 """ if "error" in data: raise AssistantServerException( request_id=request_id, code=data["error"]["code"], message=data["error"]["message"], type=data["error"]["type"], params=( data["error"]["param"] if "param" in data["error"] else data["error"]["params"] ), ) ================================================ FILE: python/core/_exception.py ================================================ # Copyright (c) 2023 Baidu, Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """include HTTP and backend server exception. """ class BaseRPCException(Exception): r"""Base RPC exception. """ pass class BadRequestException(BaseRPCException): r""" BadRequestException represent HTTP Code 400. """ pass class UnAuthorizedException(BaseRPCException): r"""UnAuthorizedException represent HTTP Code 401. """ pass class ForbiddenException(BaseRPCException): r"""BadRequestException represent HTTP Code 403. """ pass class NotFoundException(BaseRPCException): r"""NotFoundException represent HTTP Code 404. """ pass class MethodNotAllowedException(BaseRPCException): r"""MethodNotAllowedException represent HTTP Code 405. """ pass class ConflictException(BaseRPCException): r"""ConflictException represent HTTP Code 409. """ pass class MissingContentLengthException(BaseRPCException): r"""MissingContentLengthException represent HTTP Code 411. """ pass class PreconditionFailedException(BaseRPCException): r"""PreconditionFailedException represent HTTP Code 412. """ pass class UnprocessableEntityException(BaseRPCException): r"""UnprocessableEntityException represent HTTP Code 422. """ pass class DependencyFailedException(BaseRPCException): r"""DependencyFailedException represent HTTP Code 424. """ pass class TooManyRequestsException(BaseRPCException): r"""TooManyRequestsException represent HTTP Code 429. """ pass class InternalServerErrorException(BaseRPCException): r"""InternalServerErrorException represent HTTP Code 500. """ pass class InsufficientStorageException(BaseRPCException): r"""TooManyRequestsException represent HTTP Code 507. """ pass class HTTPConnectionException(BaseRPCException): r"""HTTPConnectionException represent HTTP Connection error. """ pass class ModelNotSupportedException(BaseRPCException): r"""ModelNotSupportedException represent model is not supported """ pass class TypeNotSupportedException(BaseRPCException): r"""TypeNotSupportedException represent type is not supported """ pass class AppBuilderServerException(BaseRPCException): r"""AppBuilderServerException represent backend server failed response. """ description: str = "Interal Server Error" code: int = 500 def __init__(self, request_id="", code="", message="", service_err_code="", service_err_message=""): self.description = "request_id={}, code={}, message={}, service_err_code={}, service_err_message={} ".format( request_id, code, message, service_err_code, service_err_message) self.code = code if code else self.code def __str__(self): return self.description class AssistantServerException(BaseRPCException): r"""AssistantSercerException represent assistant server failed response. """ description: str = "Interal Server Error" code: int = 500 def __init__(self, request_id= "", code="", message="", type="", params=""): self.description = "request_id={}, code={}, message={}, type={}, params={} ".format( request_id, code, message, type, params) self.code = code if code else self.code def __str__(self): return self.description class InvalidRequestArgumentError(BaseRPCException): r"""InvalidRequestArgumentError invalid request param """ description: str = "Invalid Request Params Error" code: int = 400 def __init__(self, message="", request_id= "", code=""): self.description = "request_id={}, code={}, message={}".format( request_id, code, message) self.code = code if code else self.code def __str__(self): return self.description class RiskInputException(BaseRPCException): r"""RiskInputException """ pass class AppbuilderBuildexException(BaseRPCException): r"""AppbuilderBuildxException """ pass class AppbuilderTraceException(BaseRPCException): r"""AppbuilderTraceException """ pass class RetryableExecption(Exception): r"""RetryableExecption """ pass class InternalServerException(BaseRPCException): r"""InternalServerException """ pass class NoFileUploadedExecption(Exception): r"""NoFileUploadedExecption""" pass class CustomError(Exception): """自定义错误类,包含错误码""" def __init__(self, code, message=""): """ 初始化自定义错误 Args: message (str): 错误消息 code (int/str): 错误码 """ super().__init__(message) self.code = code self.message = message def __str__(self): if self.code: return f"[{self.code}] {self.message}" return self.message ================================================ FILE: python/core/_session.py ================================================ # Copyright (c) 2024 Baidu, Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import requests import json import aiohttp from aiohttp import ClientSession, hdrs from appbuilder.utils.logger_util import logger from appbuilder.utils.trace.tracer_wrapper import session_post class InnerSession(requests.sessions.Session): def __init__(self, *args, **kwargs): """ Initialize inner session. """ super(InnerSession, self).__init__(*args, **kwargs) def build_curl(self, request: requests.PreparedRequest) -> str: """ Generate cURL command from prepared request object. """ curl = "curl -X {0} -L '{1}' \\\n".format(request.method, request.url) headers = [ "-H '{0}: {1}' \\".format(k, v) for k, v in request.headers.items() if k != "Content-Length" ] if headers: headers[-1] = headers[-1].rstrip(" \\") curl += "\n".join(headers) if request.body: try: body = json.loads(request.body) body = "'{0}'".format(json.dumps(body, ensure_ascii=False)) curl += " \\\n-d {0}".format(body) except: curl += " \\\n-d '{0}'".format(request.body) return curl def send(self, request, **kwargs): """ Send request using inner session. """ logger.debug("Curl Command:\n" + self.build_curl(request) + "\n") return super(InnerSession, self).send(request, **kwargs) @session_post def post(self, url, data=None, json=None, **kwargs): return super().post(url=url, data=data, json=json, **kwargs) @session_post def delete(self, url, **kwargs): return super().delete(url=url, **kwargs) @session_post def get(self, url, **kwargs): return super().get(url=url, **kwargs) @session_post def put(self, url, data=None, **kwargs): return super().put(url=url, data=data, **kwargs) class AsyncInnerSession(ClientSession): def __init__(self, *args, **kwargs): """ Initialize inner session. """ super(AsyncInnerSession, self).__init__(*args, **kwargs) async def build_curl(self, method, url, data=None, json_data=None, **kwargs) -> str: """ Generate cURL command from prepared request object. """ curl = "curl -X {0} -L '{1}' \\\n".format(method, url) headers = kwargs.get("headers", {}) headers_strs = [ "-H '{0}: {1}' \\".format(k, v) for k, v in headers.items()] if headers_strs: headers_strs[-1] = headers_strs[-1].rstrip(" \\") curl += "\n".join(headers_strs) if data: try: body = "'{0}'".format(json.dumps(data, ensure_ascii=False)) curl += " \\\n-d {0}".format(body) except: pass elif json_data: body = "'{0}'".format(json.dumps(json_data, ensure_ascii=False)) curl += " \\\n-d {0}".format(body) return curl async def post(self, url, data=None, json=None, **kwargs): logger.debug("Curl Command:\n" + await self.build_curl(hdrs.METH_POST, url, data=data, json_data=json, **kwargs) + "\n") return await super().post(url=url, data=data, json=json, **kwargs) async def delete(self, url, **kwargs): logger.debug("Curl Command:\n" + await self.build_curl(hdrs.METH_DELETE, url, **kwargs) + "\n") return await super().delete(url=url, **kwargs) async def get(self, url, **kwargs): logger.debug("Curl Command:\n" + await self.build_curl(hdrs.METH_GET, url, **kwargs) + "\n") return await super().get(url=url, **kwargs) async def put(self, url, data=None, **kwargs): logger.debug("Curl Command:\n" + await self.build_curl(hdrs.METH_PUT, url, data=data, **kwargs) + "\n") return await super().put(url=url, data=data, **kwargs) ================================================ FILE: python/core/agent.py ================================================ # Copyright (c) 2023 Baidu, Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import sys import copy import os import logging import uuid import json import shutil import inspect from pydantic import BaseModel, model_validator, Extra from typing import Optional, Dict, Any, Union import appbuilder from appbuilder.core.context import init_context from appbuilder.core.component import Component from appbuilder.core.message import Message from appbuilder.utils.logger_util import logger from appbuilder.core.console.appbuilder_client.data_class import ToolChoiceFunction, ToolChoice, Action # 流式场景首包超时时,最大重试次数 MAX_RETRY_COUNT = 3 class AgentRuntime(BaseModel): r""" AgentRuntime 是对组件调用的服务化封装,开发者不是必须要用 AgentRuntime 才能运行自己的组件服务。 但 AgentRuntime 可以快速帮助开发者服务化组件服务,并且提供API、对话框等部署方式。 此外,结合 Component 和 Message 自带的运行和调试接口,可以方便开发者快速获得一个调试 Agent 的服务。 Args: component (Component): 可运行的 Component, 需要实现 run(message, stream, args) 方法 user_session_config (sqlalchemy.engine.URL|str|None): Session 输出存储配置字符串。默认使用 sqlite:///user_session.db 遵循 sqlalchemy 后端定义,参考文档:https://docs.sqlalchemy.org/en/20/core/engines.html#backend-specific-urls tool_choice (ToolChoice): 可用于Agent强制执行的组件工具 Examples: .. code-block:: python import os import sys import appbuilder os.environ["APPBUILDER_TOKEN"] = '...' component = appbuilder.Playground( prompt_template="{query}", model="eb-4" ) agent = appbuilder.AgentRuntime(component=component) message = appbuilder.Message({"query": "你好"}) print(agent.chat(message, stream=False)) .. code-block:: python import os import sys import appbuilder os.environ["APPBUILDER_TOKEN"] = '...' component = appbuilder.Playground( prompt_template="{query}", model="eb-4" ) user_session_config = "sqlite:///foo.db" agent = appbuilder.AgentRuntime( component=component, user_session_config=user_session_config) agent.serve(debug=False, port=8091) .. code-block:: python import os import sys import appbuilder os.environ["APPBUILDER_TOKEN"] = '...' component = appbuilder.Playground( prompt_template="{query}", model="eb-4" ) agent = appbuilder.AgentRuntime(component=component) agent.chainlit_demo(port=8091) Session 数据管理 : 除去上述简单应用外,还支持 Session 数据管理,下面是一个例子 .. code-block:: python import os import sys from appbuilder.core.component import Component from appbuilder import ( AgentRuntime, UserSession, Message, QueryRewrite, Playground, ) os.environ["APPBUILDER_TOKEN"] = '...' class PlaygroundWithHistory(Component): def __init__(self): super().__init__() self.query_rewrite = QueryRewrite(model="DeepSeek-V3.1") self.play = Playground( prompt_template="{query}", model="eb-4" ) def run(self, message: Message, stream: bool=False): user_session = UserSession() # 获取 Session 历史数据 history_queries = user_session.get_history("query", limit=1) history_answers = user_session.get_history("answer", limit=1) if history_queries and history_answers: history = [] for query, answer in zip(history_queries, history_answers): history.extend([query.content, answer.content]) logging.info(f"history: {history}") message = self.query_rewrite( Message(history + [message.content]), rewrite_type="带机器人回复") logging.info(f"message: {message}") answer = self.play.run(message, stream) # 保存本轮数据 user_session.append({ "query": message, "answer": answer, }) return answer agent = AgentRuntime(component=PlaygroundWithHistory()) agent.chainlit_demo(port=8091) 请求时认证 : component在创建时可以不进行认证,由AgentRuntime服务化后带入AppbuilderToken .. code-block:: python import appbuilder component = appbuilder.Playground( prompt_template="{query}", model="eb-4", lazy_certification=True, # 在创建时不进行认证 ) agent = appbuilder.AgentRuntime(component=component) agent.serve(debug=False, port=8091) .. code-block:: shell curl --location 'http://0.0.0.0:8091/chat' \ --header 'Content-Type: application/json' \ --header 'X-Appbuilder-Token: ...' \ --data '{ "message": "你是谁", "stream": false }' Session 信息查看 : 查看本地user_session.db数据库内部信息,下面是一个例子 .. code-block:: python import sqlite3 import json # 连接到 SQLite 数据库 # 如果文件不存在,会自动在当前目录创建: user_session_path = 'your_user_session.db地址' conn = sqlite3.connect(user_session_path) cursor = conn.cursor() # 执行一条 SQL 语句,列出所有表 cursor.execute("SELECT name FROM sqlite_master WHERE type='table';") print(cursor.fetchall()) # 查询appbuilder_session_messages表的列信息 cursor.execute("PRAGMA table_info(appbuilder_session_messages);") columns_info = cursor.fetchall() column_names = [info[1] for info in columns_info] # info[1]是列名的位置 for column_name in column_names: print(column_name) # 查询特定表中的数据 cursor.execute("SELECT message_value FROM appbuilder_session_messages;") for row in cursor.fetchall(): print(json.loads(row[0])) # 关闭 Connection: conn.close() """ component: Component user_session_config: Optional[Union[Any, str]] = None user_session: Optional[Any] = None tool_choice: ToolChoice = None class Config: """ 检查配置 Attributes: extra (Extra): 额外属性,默认为 Extra.forbid,即禁止添加任何额外的属性 arbitrary_types_allowed (bool): 任意类型是否允许,默认为 True """ extra = Extra.forbid # 不能传入类定义中未声明的字段 arbitrary_types_allowed = True # 此设置允许在模型中使用自定义类型的字段 @model_validator(mode='before') @classmethod def init(cls, values: Dict) -> Dict: """ 初始化 AgentRuntime,UserSession 会在这里被初始化 Args: values (Dict): 初始化参数 Returns: None """ # 初始化 UserSession from appbuilder.core.user_session import UserSession values.update({ "user_session": UserSession(values.get("user_session_config")) }) return values def chat(self, message: Message, stream: bool = False, **args) -> Message: """ 执行一次对话 Args: message (Message): 该次对话用户输入的 Message stream (bool): 是否流式请求 **args: 其他参数,会被透传到 component Returns: Message(Message): 返回的 Message """ return self.component.run(message=message, stream=stream, **args) def create_flask_app(self, url_rule="/chat"): """ 创建 Flask 应用,主要用于 Gunicorn 这样的 WSGI 服务器来运行服务。 Args: None Returns: Flask """ # lazy import flask try: from flask import Flask, current_app, request, Response from flask_restful import reqparse, Resource from werkzeug.exceptions import BadRequest from flask import stream_with_context except ImportError: raise ImportError("Flask module is not installed. Please install it using 'pip install " "flask~=2.3.2 flask-restful==0.3.9'.") app = Flask(__name__) app.json.ensure_ascii = False @app.errorhandler(BadRequest) def handle_bad_request(e): return {"code": 400, "message": f'{e}', "result": None}, 400 @app.errorhandler(Exception) def handle_bad_request(e): if hasattr(e, "code"): return {"code": e.code, "message": str(e), "result": None}, 200 else: return {"code": 500, "message": "Internal Server Error", "result": None}, 200 def warp(): """ 根据component的lazy_certification属性处理请求。 Args: 无参数。 Returns: 如果stream为True,则返回流式响应(Content-Type为text/event-stream)。 如果stream为False,则返回包含处理结果的字典。 Raises: BadRequest: 当请求头中缺少必要的X-Appbuilder-Authorization时抛出。 BadRequest: 当请求体中缺少必要的message字段时抛出。 BadRequest: 当请求体中session_id字段不是字符串类型时抛出。 BadRequest: 当请求体中stream字段不是布尔类型时抛出。 """ # 根据component是否lazy_certification,分成两种情况: # 1. lazy_certification为True,初始化时未被认证,每次请求都需要带入AppbuilderToken # 2. lazy_certification为False,初始化时已经认证,请求时不需要带入AppbuilderToken,并且带入也无效 if self.component.lazy_certification: app_builder_token = None for key in ["X-Appbuilder-Token", "X-Appbuilder-Authorization"]: if key in request.headers: app_builder_token = request.headers[key] break if not app_builder_token: raise BadRequest( "X-Appbuilder-Authorization is required in Headers") try: self.component.set_secret_key_and_gateway( secret_key=app_builder_token) except appbuilder.core._exception.BaseRPCException as e: logging.error(f"failed to verify. err={e}", exc_info=True) raise BadRequest("X-Appbuilder-Authorization invalid") except Exception as e: logging.error(f"failed to verify. err={e}", exc_info=True) raise e else: pass data = request.get_json() if "message" not in data: raise BadRequest("message is required") message = Message(data.pop('message')) if "session_id" not in data: session_id = str(uuid.uuid4()) else: session_id = data.pop("session_id") if not isinstance(session_id, str): raise BadRequest("session_id must be str type") if "stream" not in data: stream = False else: stream = data.pop("stream") if not isinstance(stream, bool): raise BadRequest("stream must be bool type") request_id = request.headers.get("X-Appbuilder-Request-Id", str(uuid.uuid4())) user_id = request.headers.get("X-Appbuilder-User-Id", None) init_context(session_id=session_id, request_id=request_id, user_id=user_id) logging.info( f"request_id={request_id}, session_id={session_id}] message={message}," f" stream={stream}, data={data}, start run...") def gen_sse_resp(): with app.app_context(): received_first_packet = False retry_count = 0 while retry_count < MAX_RETRY_COUNT: try: answer = self.chat(message, stream, **data) except Exception as e: # 调用chat方法报错,直接返回 code = 500 if not hasattr(e, "code") else e.code err_resp = {"code": code, "message": "InternalServerError", "result": None} logging.error( f"request_id={request_id}, session_id={session_id}, err={e}, execute self.chat failed", exc_info=True) yield "data: " + json.dumps(err_resp, ensure_ascii=False) + "\n\n" return else: # 调用chat方法成功,开始生成流式事件 content_iterator = iter(answer.content) answer.content = None result = None try: for sub_content in content_iterator: result = copy.deepcopy(answer) result.content = sub_content yield "data: " + json.dumps({ "code": 0, "message": "", "result": { "session_id": session_id, "is_completion": False, "answer_message": json.loads(result.json(exclude_none=True)) } }, ensure_ascii=False) + "\n\n" received_first_packet = True except Exception as e: retry_count += 1 logging.error( f"[request_id={request_id}, session_id={session_id}] err={e}, " f"retry_count={retry_count}", exc_info=True) # 如果未收到首包且重试次数小于最大重试次数,则尝试重新执行一次chat方法 if not received_first_packet and retry_count < MAX_RETRY_COUNT: continue else: # 其它情况返回 logging.error( f"[request_id={request_id}, session_id={session_id}] err={e}, " f"retry_count={retry_count}, received_first_packet={received_first_packet}" , exc_info=True) code = 500 if not hasattr(e, "code") else e.code err_resp = {"code": code, "message": "InternalServerError", "result": None} yield "data: " + json.dumps(err_resp, ensure_ascii=False) + "\n\n" return result.content = "" yield "data: " + json.dumps({ "code": 0, "message": "", "result": { "session_id": session_id, "is_completion": True, "answer_message": json.loads(result.json(exclude_none=True)) } }, ensure_ascii=False) + "\n\n" logging.info( f"request_id={request_id}, session_id={session_id}]" f"retry_count={retry_count}, success response", exc_info=True) self.user_session._post_append() return # 正常返回 if stream: # 流式 return Response(stream_with_context(gen_sse_resp()), 200, {'Content-Type': 'text/event-stream; charset=utf-8'}) if not stream: # 非流式 try: answer = self.chat(message, stream, **data) blocking_result = json.loads(copy.deepcopy(answer).json(exclude_none=True)) logging.debug(f"[request_id={request_id}, session_id={session_id}] blocking_result={blocking_result}") self.user_session._post_append() return { "code": 0, "message": "", "result": {"session_id": session_id, "answer_message": blocking_result} } except Exception as e: logging.error( f"[request_id={request_id}, session_id={session_id}] err={e}", exc_info=True) code = 500 if not hasattr(e, "code") else e.code return {"code": code, "message": "InternalServerError", "result": None} app.add_url_rule(url_rule, 'chat', warp, methods=['POST']) return app def serve(self, host='0.0.0.0', debug=True, port=8092, url_rule="/chat"): """ 将 component 服务化,提供 Flask http API 接口 Args: host (str): 服务运行的host地址,默认为'0.0.0.0' debug (bool): 是否开启debug模式,默认为True port (int): 服务运行的端口号,默认为8092 url_rule (str): 服务的URL规则,默认为"/chat" Returns: None """ app = self.create_flask_app(url_rule=url_rule) app.run(host=host, debug=debug, port=port) def prepare_chainlit_readme(self): """ 准备 Chainlit 的 README 文件 Args: 无 Returns: 无 Raises: 无 说明: 从 utils 文件夹中拷贝 chainlit.md 文件到当前工作目录下,如果当前工作目录下已存在 chainlit.md 文件,则不拷贝。 """ try: # 获取当前python命令执行的路径,而不是文件的位置 cwd_path = os.getcwd() # 获取当前文件的路径所在文件夹 current_file_path = os.path.dirname( os.path.dirname(os.path.abspath(__file__))) chainlit_readme_path = os.path.join( current_file_path, "utils", "chainlit.md") # 拷贝chainlit_readme到cwd_path # 如果cwd_path下已经存在chainlit_readme,则不拷贝 if not os.path.exists(os.path.join(cwd_path, "chainlit.md")): shutil.copy(chainlit_readme_path, cwd_path) except: logger.error("Failed to copy chainlit.md to current directory") def chainlit_demo(self, host='0.0.0.0', port=8091): """ 将 component 服务化,提供 chainlit demo 页面 Args: host (str): 服务 host port (int): 服务 port Returns: None """ # lazy import chainlit try: import chainlit as cl import chainlit.cli except ImportError: raise ImportError("chainlit module is not installed. Please install it using 'pip install " "chainlit~=1.0.200'.") import click from click.testing import CliRunner self.prepare_chainlit_readme() @cl.on_message # this function will be called every time a user inputs a message in the UI async def main(message: cl.Message): session_id = cl.user_session.get("id") request_id = str(uuid.uuid4()) init_context(session_id=session_id, request_id=request_id) msg = cl.Message(content="") await msg.send() stream_message = self.chat(Message(message.content), stream=True) for part in stream_message.content: if token := part or "": await msg.stream_token(token) await msg.update() self.user_session._post_append() # start chainlit service if os.getenv('APPBUILDER_RUN_CHAINLIT') == '1': pass else: os.environ['APPBUILDER_RUN_CHAINLIT'] = '1' target = sys.argv[0] runner = CliRunner() runner.invoke( chainlit.cli.chainlit_run, [target, '--watch', "--port", port, "--host", host]) def chainlit_agent(self, host='0.0.0.0', port=8091): """ 将 appbuilder client 服务化,提供 chainlit demo 页面 Args: host (str): 服务 host port (int): 服务 port Returns: None """ # lazy import chainlit try: import chainlit as cl import chainlit.cli except ImportError: raise ImportError("chainlit module is not installed. Please install it using 'pip install " "chainlit~=1.0.200'.") import click from click.testing import CliRunner if not isinstance(self.component, appbuilder.AppBuilderClient): raise ValueError( "chainlit_agent require component must be an instance of AppBuilderClient") self.prepare_chainlit_readme() conversation_ids = [] interrupt_dict = {} def _chat(message: cl.Message): if len(conversation_ids) == 0: raise ValueError("create new conversation failed!") conversation_id = conversation_ids[-1] file_ids = [] if len(message.elements) > 0: file_id = self.component.upload_local_file( conversation_id, message.elements[0].path) file_ids.append(file_id) interrupt_ids = interrupt_dict.get(conversation_id, []) interrupt_event_id = interrupt_ids.pop() if len(interrupt_ids) > 0 else None action = None if interrupt_event_id is not None: action = Action.create_resume_action(interrupt_event_id) tmp_message = self.component.run(conversation_id=conversation_id, query=message.content, file_ids=file_ids, stream=True, tool_choice=self.tool_choice, action=action) res_message=list(tmp_message.content) interrupt_event_id = None for ans in res_message: for event in ans.events: if event.content_type == "chatflow_interrupt": interrupt_event_id = event.detail.get("interrupt_event_id") if event.content_type == "publish_message" and event.event_type == "chatflow": answer = event.detail.get("message") ans.answer += answer if interrupt_event_id is not None: interrupt_ids.append(interrupt_event_id) interrupt_dict[conversation_id] = interrupt_ids tmp_message.content = res_message return tmp_message @cl.on_chat_start async def start(): session_id = cl.user_session.get("id") request_id = str(uuid.uuid4()) init_context(session_id=session_id, request_id=request_id) conversation_ids.append(self.component.create_conversation()) interrupt_dict[conversation_ids[-1]] = [] @cl.on_message # this function will be called every time a user inputs a message in the UI async def main(message: cl.Message): msg = cl.Message(content="") await msg.send() await msg.update() stream_message = _chat(message) detail_json_list = [] for part in stream_message.content: if token := part.answer or "": await msg.stream_token(token) for event in part.events: detail = event.detail detail_json = json.dumps( detail, indent=4, ensure_ascii=False) detail_json_list.append(detail_json) await msg.update() @cl.step(name="详细信息") def show_json(detail_json): return "```json\n" + detail_json + "\n```" for detail_json in detail_json_list: if len(detail_json) > 2: show_json(detail_json) await msg.update() self.user_session._post_append() # start chainlit service if os.getenv('APPBUILDER_RUN_CHAINLIT') == '1': pass else: os.environ['APPBUILDER_RUN_CHAINLIT'] = '1' target = sys.argv[0] runner = CliRunner() runner.invoke( chainlit.cli.chainlit_run, [target, '--watch', "--port", port, "--host", host]) ================================================ FILE: python/core/assistant/__init__.py ================================================ # Copyright (c) 2024 Baidu, Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. ================================================ FILE: python/core/assistant/assistants/__init__.py ================================================ # Copyright (c) 2024 Baidu, Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from .assistants import ( Assistants ) from .files import ( Files ) __all__ = [ 'Assistants', 'Files', ] ================================================ FILE: python/core/assistant/assistants/assistants.py ================================================ # Copyright (c) 2024 Baidu, Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import os from typing import Optional from appbuilder.core.assistant.type import assistant_type from appbuilder.utils.collector import Collector from appbuilder.utils.collector import AssistantKeys from appbuilder.core._client import AssistantHTTPClient from appbuilder.core.assistant.assistants.files import Files from appbuilder.utils.trace.tracer_wrapper import assistent_tool_trace class Assistants(object): def __init__(self): self._http_client = AssistantHTTPClient() @property def files(self): """ 获取当前工作目录下的文件对象。 Args: 无 Returns: Files: 返回当前工作目录下的文件对象。 """ return Files() @assistent_tool_trace def create(self, name: str, description: str, model: Optional[str] = "ERNIE-4.0T-8K", response_format: Optional[str] = 'text', instructions: Optional[str] = "你是百度制作的AI助手", thought_instructions: Optional[str] = "", chat_instructions: Optional[str] = "", tools: Optional[list[assistant_type.AssistantTool]] = [], file_ids: Optional[list[str]] = [], metadata: Optional[dict] = {}, ) -> assistant_type.AssistantCreateResponse: """ 创建助手实例 Args: name (str): 助手名称 description (str): 助手描述 model (Optional[str], optional): 模型名称. Defaults to "ERNIE-4.0T-8K". response_format (Optional[str], optional): 响应格式. Defaults to 'text'. instructions (Optional[str], optional): 指令. Defaults to "". thought_instructions (Optional[str], optional): 思考指令. Defaults to "". chat_instructions (Optional[str], optional): 聊天指令. Defaults to "". tools (Optional[list[assistant_type.AssistantTool]], optional): 工具列表. Defaults to []. file_ids (Optional[list[str]], optional): 文件ID列表. Defaults to []. metadata (Optional[dict], optional): 元数据. Defaults to {}. Returns: assistant_type.AssistantCreateResponse: 助手创建响应 """ headers = self._http_client.auth_header() url = self._http_client.service_url("/v2/assistants") req = assistant_type.AssistantCreateRequest( name=name, description=description, model=model, response_format=response_format, instructions=instructions, thought_instructions=thought_instructions, chat_instructions=chat_instructions, tools=tools, file_ids=file_ids, metadata=metadata, ) response = self._http_client.session.post( url=url, headers=headers, json=req.model_dump(), timeout=None ) self._http_client.check_response_header(response) data = response.json() request_id = self._http_client.response_request_id(response) self._http_client.check_assistant_response(request_id, data) resp = assistant_type.AssistantCreateResponse(**data) Collector().add_to_collection(AssistantKeys.ASSISTANT, resp, resp.id) return resp @assistent_tool_trace def update(self, assistant_id: str, model: Optional[str], name: Optional[str], description: Optional[str], instructions: Optional[str] = "", tools: Optional[list[assistant_type.AssistantTool]] = [], thought_instructions: Optional[str] = "", chat_instructions: Optional[str] = "", response_format: Optional[str] = "text", file_ids: Optional[list[str]] = [], metadata: Optional[dict] = {} ) -> assistant_type.AssistantUpdateResponse: """ 根据assistant_id修改一个已创建的Assistant Args: assistant_id (str): 助手ID。 model (Optional[str]): 助手模型。 name (Optional[str]): 助手名称。 description (Optional[str]): 助手描述。 response_format (Optional[str], optional): 响应格式。默认为None。 instructions (Optional[str], optional): 助手指令。默认为None。 thought_instructions (Optional[str], optional): 思考指令。默认为None。 chat_instructions (Optional[str], optional): 聊天指令。默认为None。 tools (Optional[list[assistant_type.AssistantTool]], optional): 助手工具列表。默认为空列表。 file_ids (Optional[list[str]], optional): 文件ID列表。默认为空列表。 metadata (Optional[dict], optional): 助手元数据。默认为空字典。 Returns: assistant_type.AssistantUpdateResponse: 助手更新响应。 """ headers = self._http_client.auth_header() url = self._http_client.service_url("/v2/assistants/update") req = assistant_type.AssistantUpdateRequest( assistant_id=assistant_id, model=model, name=name, description=description, response_format=response_format, instructions=instructions, thought_instructions=thought_instructions, chat_instructions=chat_instructions, tools=tools, file_ids=file_ids, metadata=metadata, ) response = self._http_client.session.post( url=url, headers=headers, json=req.model_dump(), timeout=None ) self._http_client.check_response_header(response) data = response.json() request_id = self._http_client.response_request_id(response) self._http_client.check_assistant_response(request_id, data) resp = assistant_type.AssistantUpdateResponse(**data) return resp @assistent_tool_trace def list(self, limit: Optional[int] = 20, order: Optional[str] = "desc", after: Optional[str] = "", before: Optional[str] = "", ) -> assistant_type.AssistantListResponse: """ 查询当前用户已创建的assistant列表 Args: limit (Optional[int], optional): 返回助手列表的最大数量,默认为20。 order (Optional[str], optional): 返回助手列表的排序方式,可选值为"asc"或"desc",默认为"desc"。 after (Optional[str], optional): 返回助手列表中id在指定id之后的助手,默认为空字符串。 before (Optional[str], optional): 返回助手列表中id在指定id之前的助手,默认为空字符串。 Returns: assistant_type.AssistantListResponse: 助手列表响应体。 """ headers = self._http_client.auth_header() url = self._http_client.service_url("/v2/assistants/list") req = assistant_type.AssistantListRequest( limit=limit, order=order, after=after, before=before ) response = self._http_client.session.post( url=url, headers=headers, json=req.model_dump(), timeout=None ) self._http_client.check_response_header(response) data = response.json() request_id = self._http_client.response_request_id(response) self._http_client.check_assistant_response(request_id, data) resp = assistant_type.AssistantListResponse(**data) return resp @assistent_tool_trace def query(self, assistant_id: Optional[str]) -> assistant_type.AssistantQueryResponse: """ 根据assistant_id查询Assistant信息 Args: assistant_id (Optional[str]): 助手ID Returns: assistant_type.AssistantQueryResponse: 助手查询响应结果 Raises: HTTPError: 请求失败,抛出HTTPError异常 """ headers = self._http_client.auth_header() url = self._http_client.service_url("/v2/assistants/query") req = assistant_type.AssistantQueryRequest( assistant_id=assistant_id ) response = self._http_client.session.post( url=url, headers=headers, json=req.model_dump(), timeout=None ) self._http_client.check_response_header(response) data = response.json() request_id = self._http_client.response_request_id(response) self._http_client.check_assistant_response(request_id, data) resp = assistant_type.AssistantQueryResponse(**data) return resp @assistent_tool_trace def delete(self, assistant_id: Optional[str]) -> assistant_type.AssistantDeleteResponse: """ 根据assistant_id删除指定Assitant Args: assistant_id (Optional[str]): 待删除的助手实例ID。 Returns: assistant_type.AssistantDeleteResponse: 删除助手实例后的响应结果。 Raises: HttpRequestError: 发送HTTP请求时发生错误。 """ headers = self._http_client.auth_header() url = self._http_client.service_url("/v2/assistants/delete") req = assistant_type.AssistantDeleteRequest( assistant_id=assistant_id ) response = self._http_client.session.post( url=url, headers=headers, json=req.model_dump(), timeout=None ) self._http_client.check_response_header(response) data = response.json() request_id = self._http_client.response_request_id(response) self._http_client.check_assistant_response(request_id, data) resp = assistant_type.AssistantDeleteResponse(**data) return resp @assistent_tool_trace def mount_files(self, assistant_id: Optional[str], file_id: Optional[str] ) -> assistant_type.AssistantFilesResponse: """ 指定file_id和assistant_id,挂载File到对应的Assistant Args: assistant_id (Optional[str]): 助理ID。 file_id (Optional[str]): 文件ID。 Returns: assistant_type.AssistantFilesResponse: 助理文件列表响应对象。 """ if not isinstance(assistant_id, str): raise TypeError("assistant_id must be a string") if not assistant_id: raise ValueError("assistant_id can't be empty") if not isinstance(file_id, str): raise TypeError("file_id must be a string") if not file_id: raise ValueError("file_id can't be empty") try: self.files.query(file_id) except: raise FileNotFoundError("can't find file with id {}".format(file_id)) headers = self._http_client.auth_header() url = self._http_client.service_url("/v2/assistants/files") req = assistant_type.AssistantFilesRequest( assistant_id=assistant_id, file_id=file_id ) response = self._http_client.session.post( url=url, headers=headers, json=req.model_dump(), timeout=None ) self._http_client.check_response_header(response) data = response.json() request_id = self._http_client.response_request_id(response) self._http_client.check_assistant_response(request_id, data) resp = assistant_type.AssistantFilesResponse(**data) return resp @assistent_tool_trace def mounted_files_list(self, assistant_id: Optional[str], limit: Optional[int] = 20, order: Optional[str] = 'desc' , after: Optional[str] = "", before: Optional[str] = "") -> assistant_type.AssistantMountedFilesListResponse: """ 查询Assistant挂载的File列表 Args: assistant_id (Optional[str]): 助手ID,为空时获取当前登录用户的助手文件列表。 limit (Optional[int], optional): 每页最多显示多少个文件。默认为20。 order (Optional[AssistantListRole], optional): 文件列表排序方式。可选值为 'asc' 或 'desc'。默认为 'desc'。 after (Optional[str], optional): 返回文件ID大于该值的文件列表。默认为空字符串。 before (Optional[str], optional): 返回文件ID小于该值的文件列表。默认为空字符串。 Returns: assistant_type.AssistantFilesListResponse: 包含文件列表信息的响应对象。 """ headers = self._http_client.auth_header() url = self._http_client.service_url("/v2/assistants/files/list") req = assistant_type.AssistantMountedFilesListRequest( assistant_id=assistant_id, limit=limit, order=order, after=after, before=before ) response = self._http_client.session.post( url=url, headers=headers, json=req.model_dump(), timeout=None ) self._http_client.check_response_header(response) data = response.json() request_id = self._http_client.response_request_id(response) self._http_client.check_assistant_response(request_id, data) resp = assistant_type.AssistantMountedFilesListResponse(**data) return resp @assistent_tool_trace def unmount_files(self, assistant_id: Optional[str], file_id: Optional[str] ) -> assistant_type.AssistantFilesDeleteResponse: """ 指定assistant_id和file_id,解绑Assistant中对应File的关联 Args: assistant_id (Optional[str]): 助理ID。 file_id (Optional[str]): 文件ID。 Returns: assistant_type.AssistantFilesDeleteResponse: 响应对象。 """ if not isinstance(assistant_id, str): raise TypeError("assistant_id must be a string") if not assistant_id: raise ValueError("assistant_id can't be empty") if not isinstance(file_id, str): raise TypeError("file_id must be a string") if not file_id: raise ValueError("file_id can't be empty") try: list_response=self.mounted_files_list(assistant_id, limit=2147483647) exist_files = False for data in list_response.data: if data.id == file_id: exist_files = True break if exist_files == False: raise FileNotFoundError except: raise FileNotFoundError("can't find file with id {}".format(file_id)) headers = self._http_client.auth_header() url = self._http_client.service_url("/v2/assistants/files/delete") req = assistant_type.AssistantFilesDeleteRequest( assistant_id=assistant_id, file_id=file_id ) response = self._http_client.session.post( url=url, headers=headers, json=req.model_dump(), timeout=None ) self._http_client.check_response_header(response) data = response.json() request_id = self._http_client.response_request_id(response) self._http_client.check_assistant_response(request_id, data) resp = assistant_type.AssistantFilesDeleteResponse(**data) return resp ================================================ FILE: python/core/assistant/assistants/files.py ================================================ # Copyright (c) 2024 Baidu, Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # -*- coding: utf-8 -*- import os import json from typing import Optional from appbuilder.core.assistant.type import assistant_type from appbuilder.core._client import AssistantHTTPClient from appbuilder.core._exception import AppBuilderServerException,HTTPConnectionException from appbuilder.utils.trace.tracer_wrapper import assistent_tool_trace class Files(object): def __init__(self): self._http_client = AssistantHTTPClient() @assistent_tool_trace def create(self, file_path: str, purpose: str = "assistant") -> assistant_type.AssistantFilesCreateResponse: """ 上传文件到助理存储中。 Args: file_path (str): 要上传的文件路径。 purpose (str, optional): 上传文件的用途。默认为 "assistant"。 Returns: assistant_type.AssistantFilesCreateResponse: 上传文件后返回的响应对象。 Raises: ValueError: 如果指定的文件路径不存在,则会引发此异常。 """ headers = self._http_client.auth_header() headers.pop("Content-Type") url = self._http_client.service_url("/v2/storage/files") if not os.path.exists(file_path): raise ValueError("File {} not exists".format(file_path)) with open(file_path, 'rb') as f: files = [ ('file',(os.path.basename(file_path), f)) ] response = self._http_client.session.post( url, headers=headers, files=files, params={ 'purpose': purpose } ) self._http_client.check_response_header(response) request_id = self._http_client.response_request_id(response) data = response.json() self._http_client.check_assistant_response(request_id, data) resp = assistant_type.AssistantFilesCreateResponse(**data) return resp @assistent_tool_trace def list(self) -> assistant_type.AssistantFilesListResponse: """ 列出存储中的文件列表。 此方法向存储服务发送请求,获取已上传的文件列表。返回的文件列表包含每个文件的详细信息, 包括文件ID、大小、用途、审核状态、创建时间、文件名、文件分类ID等。 Args: 无 Returns: assistant_type.AssistantFilesListResponse: 文件列表的响应对象,包含以下属性: - object (str): 表示对象类型,默认值为 "list" - data (list[AssistantFilesListData]): 包含文件信息的列表,列表中的每个元素为 AssistantFilesListData 对象。该对象包含以下属性: - id (str): 文件ID - bytes (int): 文件大小(字节) - object (str): 文件对象标识 - purpose (str): 文件用途 - censored (AuditStatus): 文件的审核状态 - create_at (int): 文件创建时间戳 - filename (str): 文件名 - classification_id (str): 文件分类ID - file_type (str): 文件类型 Raises: assistant_type.AssistantError: 请求发生错误时抛出,具体错误信息可通过 `error_msg` 属性获取。 """ headers = self._http_client.auth_header() # 获取身份认证头 headers['Content-Type'] = 'application/json' # 设置请求头为JSON格式 url = self._http_client.service_url("/v2/storage/files/list") # 拼接存储服务的URL response = self._http_client.session.post( # 向存储服务发送POST请求,获取文件列表 url=url, headers=headers, json={}, # 发送空的JSON请求体 timeout=None # 设置为无超时限制 ) self._http_client.check_response_header(response) # 检查响应头是否合法 request_id = self._http_client.response_request_id(response) # 从响应中获取请求ID data = response.json() # 将响应内容转换为JSON格式 self._http_client.check_assistant_response(request_id, data) # 检查Assistant响应是否有错误 resp = assistant_type.AssistantFilesListResponse(**data) # 将响应数据映射为AssistantFilesListResponse对象 return resp # 返回文件列表响应对象 @assistent_tool_trace def query(self, file_id: str, ) -> assistant_type.AssistantFilesQueryResponse: """ 根据文件ID查询文件信息 Args: file_id (str): 文件ID Returns: assistant_type.AssistantFilesQueryResponse: 文件查询响应对象 Raises: TypeError: 如果file_id不是str类型 ValueError: 如果file_id不存在 """ if not isinstance(file_id, str): raise TypeError("file_id must be str") headers = self._http_client.auth_header() headers['Content-Type'] = 'application/json' url = self._http_client.service_url("/v2/storage/files/query") response = self._http_client.session.post( url=url, headers=headers, json={ 'file_id': file_id }, timeout=None ) try: self._http_client.check_response_header(response) request_id = self._http_client.response_request_id(response) data = response.json() self._http_client.check_assistant_response(request_id, data) resp = assistant_type.AssistantFilesQueryResponse(**data) except AssertionError: raise ValueError('file_id {} is not exist'.format(file_id)) except TypeError: raise ValueError('file_id {} is not exist'.format(file_id)) return resp @assistent_tool_trace def delete(self, file_id: str, ) -> assistant_type.AssistantFilesDeleteResponse: """ 删除文件 Args: file_id (str): 文件ID Returns: assistant_type.AssistantFilesDeleteResponse: 删除文件后的响应对象。 Raises: 无 """ headers = self._http_client.auth_header() headers['Content-Type'] = 'application/json' url = self._http_client.service_url("/v2/storage/files/delete") response = self._http_client.session.post( url=url, headers=headers, json={ 'file_id': file_id }, timeout=None ) self._http_client.check_response_header(response) request_id = self._http_client.response_request_id(response) data = response.json() self._http_client.check_assistant_response(request_id, data) resp = assistant_type.AssistantFilesDeleteResponse(**data) return resp @assistent_tool_trace def download(self, file_id:str, file_path:str="", # 要求若文件路径不为空,需要以/结尾,默认下载到当前文件夹 timeout:Optional[int]=None, ): """ 下载文件 Args: file_id (str): 文件ID file_path (str, optional): 文件保存路径,默认为空字符串。如果未指定,则使用文件名的默认值。要求若文件路径不为空,需要以/结尾。 timeout (Optional[int], optional): 请求超时时间,单位秒。如果未指定,则使用默认超时时间。 Returns: None Raises: TypeError: 当file_path或file_id类型不为str时引发此异常。 ValueError: 当file_id为空或None时,或file_path不是文件目录时引发此异常。 FileNotFoundError: 当指定的文件路径或文件不存在时引发此异常。 OSError: 当磁盘空间不足时引发此异常。 HTTPConnectionException: 当请求失败时引发此异常。 Exception: 当发生其他异常时引发此异常。 """ if not isinstance(file_path, str): raise TypeError("file_path must be str") if not isinstance(file_id, str): raise TypeError("file_id must be str") if file_id == "" or file_id is None: raise ValueError("file_id cannot be empty or None") try: self.query(file_id) except: raise FileNotFoundError("file_id {} not found".format(file_id)) if file_path != "" and not os.path.exists(file_path): raise FileNotFoundError("file_path {} not found".format(file_path)) if file_path != "" and not os.path.isdir(file_path): raise ValueError("file_path must be a file directory") headers = self._http_client.auth_header() url = self._http_client.service_url("/v2/storage/files/download") try: response = self._http_client.session.post( url=url, headers=headers, json={ 'file_id': file_id }, timeout=timeout ) except: raise HTTPConnectionException("request failed") self._http_client.check_response_header(response) filename=response.headers['Content-Disposition'].split("filename=")[-1] file_path+=filename try: with open(file_path,'wb') as file: for chunk in response.iter_content(): if chunk: file.write(chunk) except FileNotFoundError as e: raise FileNotFoundError("请检查文件路径是否正确,错误信息{}".format(e)) except OSError as e: raise OSError("磁盘空间不足,错误信息{}".format(e)) except Exception as e: raise Exception("出现错误,错误信息{}".format(e)) @assistent_tool_trace def content(self, file_id:str, timeout:Optional[int]=None): """ 获取指定文件的内容 Args: file_id (str): 文件ID timeout (Optional[int], optional): 请求超时时间,单位秒. Defaults to None. Returns: assistant_type.AssistantFilesContentResponse: 包含文件内容的响应对象 Raises: TypeError: 当file_id不是字符串类型时引发此异常 FileNotFoundError: 当指定的文件路径不存在时引发此异常 HTTPConnectionException: 当请求失败时引发此异常 """ if not isinstance(file_id, str): raise TypeError("file_id must be str") try: self.query(file_id) except: raise FileNotFoundError("can't find file with id {}".format(file_id)) headers = self._http_client.auth_header() headers['Content-Type'] = 'application/json' url = self._http_client.service_url("/v2/storage/files/content") try: response = self._http_client.session.post( url=url, headers=headers, json={ 'file_id': file_id }, timeout=timeout ) except: raise HTTPConnectionException("request failed") self._http_client.check_response_header(response) content=b'' for chunk in response.iter_content(): if chunk: content+=chunk res=assistant_type.AssistantFilesContentResponse( content_type =response.headers['Content-Type'], content = content ) return res ================================================ FILE: python/core/assistant/base.py ================================================ # Copyright (c) 2024 Baidu, Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. class BetaAssistant(object): @property def assistants(self): from appbuilder.core.assistant.assistants import Assistants return Assistants() @property def threads(self): from appbuilder.core.assistant.threads import Threads return Threads() @property def type(self): from appbuilder.core.assistant import type return type @property def assistant_type(self): from appbuilder.core.assistant.type import assistant_type return assistant_type @property def thread_type(self): from appbuilder.core.assistant.type import thread_type return thread_type @property def public_type(self): from appbuilder.core.assistant.type import public_type return public_type assistant = BetaAssistant() ================================================ FILE: python/core/assistant/threads/__init__.py ================================================ # Copyright (c) 2024 Baidu, Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from .threads import ( Threads ) from .messages import ( Messages, ) from .runs import ( Runs, Steps ) ___all__ = [ 'Threads', 'Messages', 'Runs', 'Steps' ] ================================================ FILE: python/core/assistant/threads/messages/__init__.py ================================================ # Copyright (c) 2024 Baidu, Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from .messages import ( Messages ) __all__ = [ 'Messages', ] ================================================ FILE: python/core/assistant/threads/messages/messages.py ================================================ # Copyright (c) 2024 Baidu, Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import os from appbuilder.core.assistant.type import thread_type from appbuilder.core._client import AssistantHTTPClient from typing import Optional from appbuilder.utils.trace.tracer_wrapper import assistent_tool_trace class Messages(object): def __init__(self): self._http_client = AssistantHTTPClient() @assistent_tool_trace def create(self, thread_id: str, content: str, role: Optional[str] = "user", file_ids: Optional[list[str]] = []) -> thread_type.AssistantMessageCreateResponse: """ 创建一条消息。 Args: thread_id (str): 线程ID。 content (str): 消息内容。 role (Optional[str], optional): 角色,可选值为"user"或"assistant"。默认为"user"。 file_ids (Optional[list[str]], optional): 消息中包含的文件ID列表。默认为空列表。 Returns: thread_type.AssistantMessageCreateResponse: 消息创建响应对象。 Raises: HttpError: 如果请求失败,则抛出HttpError异常。 """ headers = self._http_client.auth_header() url = self._http_client.service_url("/v2/threads/messages") req = thread_type.AssistantMessageCreateRequest( thread_id=thread_id, content=content, role=role, file_ids=file_ids ) response = self._http_client.session.post( url=url, headers=headers, json=req.model_dump(), timeout=None ) self._http_client.check_response_header(response) data = response.json() request_id = self._http_client.response_request_id(response) self._http_client.check_assistant_response(request_id, data) response = thread_type.AssistantMessageCreateResponse(**data) return response @assistent_tool_trace def update(self, thread_id: str, message_id: str, content: Optional[str], file_ids: Optional[list[str]] = []) -> thread_type.AssistantMessageUpdateResponse: """ 修改Message对象,允许content和file_ids字段 Args: thread_id (str): 线程ID。 message_id (str): 消息ID。 content (Optional[str], optional): 消息内容。默认为空字符串。 file_ids (Optional[list[str]], optional): 消息中包含的文件ID列表。默认为空列表。 Returns: thread_type.AssistantMessageUpdateResponse: 消息更新响应对象。 Raises: HttpError: 如果请求失败,则抛出HttpError异常。 """ headers = self._http_client.auth_header() url = self._http_client.service_url("/v2/threads/messages/update") req = thread_type.AssistantMessageUpdateRequest( thread_id = thread_id, message_id = message_id, content = content, file_ids = file_ids ) response = self._http_client.session.post( url=url, headers=headers, json=req.model_dump(), timeout=None ) self._http_client.check_response_header(response) data = response.json() request_id = self._http_client.response_request_id(response) self._http_client.check_assistant_response(request_id, data) response = thread_type.AssistantMessageUpdateResponse(**data) return response @assistent_tool_trace def list(self, thread_id: str, limit: int = 20, order: str = "desc", after: str = "", before: str = "") -> thread_type.AssistantMessageListResponse: """ 查询指定Thread下的Message列表 Args: thread_id (str): 线程ID。 limit (int, optional): 返回消息的最大数量,取值范围为[1,20]。默认为-20。 order (Optional[str], optional): 排序方式,可选值为"asc"或"desc"。默认为"desc"。 after (Optional[str], optional): 查询指定message_id之后创建的Message。 before (Optional[str], optional): 查询指定message_id之前创建的Message Returns: thread_type.AssistantMessageListResponse: 查询thread下的message列表响应对象。 Raises: HttpError: 如果请求失败,则抛出HttpError异常。 """ headers = self._http_client.auth_header() url = self._http_client.service_url("/v2/threads/messages/list") req = thread_type.AssistantMessageListRequest( thread_id = thread_id, limit = limit, order = order, after = after, before = before ) response = self._http_client.session.post( url=url, headers=headers, json=req.model_dump(), timeout=None ) self._http_client.check_response_header(response) data = response.json() request_id = self._http_client.response_request_id(response) self._http_client.check_assistant_response(request_id, data) response = thread_type.AssistantMessageListResponse(**data) return response @assistent_tool_trace def query(self, thread_id:str, message_id:str) -> thread_type.AssistantMessageQueryResponse: """ 根据message_id查询指定Message的信息 Args: thread_id (str): 线程ID message_id (str): 消息ID Returns: thread_type.AssistantMessageQueryResponse: 消息信息响应 Raises: HttpError: 如果请求失败,则抛出HttpError异常。 """ headers = self._http_client.auth_header() url = self._http_client.service_url("/v2/threads/messages/query") req = thread_type.AssistantMessageQueryRequest( thread_id = thread_id, message_id = message_id ) response = self._http_client.session.post( url=url, headers=headers, json=req.model_dump(), timeout=None ) self._http_client.check_response_header(response) data = response.json() request_id = self._http_client.response_request_id(response) self._http_client.check_assistant_response(request_id, data) response = thread_type.AssistantMessageQueryResponse(**data) return response @assistent_tool_trace def files(self, thread_id:str, message_id:str, limit:Optional[int] = 20, order:Optional[str] = "desc", after:Optional[str] = "", before:Optional[str] = "") -> thread_type.AssistantMessageFilesResponse: """ 获取指定消息 ID 的附件信息。 Args: thread_id (str): 线程 ID。 messsages_id (str): 消息 ID。 limit (Optional[int], optional): 返回结果的最大数量,默认为 20。 order (Optional[str], optional): 排序方式,可选值为 "asc" 或 "desc",默认为 "desc"。 after (Optional[str], optional): 返回结果的时间范围,只返回时间晚于该时间戳的消息附件,默认为空。 before (Optional[str], optional): 返回结果的时间范围,只返回时间早于该时间戳的消息附件,默认为空。 Returns: thread_type.AssistantMessageFilesResponse: 附件信息响应对象。 """ headers = self._http_client.auth_header() url = self._http_client.service_url("/v2/threads/messages/files/list") req = thread_type.AssistantMessageFilesRequest( thread_id = thread_id, message_id = message_id, limit = limit, order = order, after = after, before = before ) response = self._http_client.session.post( url=url, headers=headers, json=req.model_dump(), timeout=None ) self._http_client.check_response_header(response) data = response.json() request_id = self._http_client.response_request_id(response) self._http_client.check_assistant_response(request_id, data) response = thread_type.AssistantMessageFilesResponse(**data) return response ================================================ FILE: python/core/assistant/threads/runs/__init__.py ================================================ # Copyright (c) 2024 Baidu, Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from .runs import ( Runs ) from .steps import ( Steps, ) from .stream_helper import ( StreamRunContext, AssistantEventHandler, AssistantStreamManager, ) __all__ = [ 'Runs', 'Steps', 'StreamRunContext', 'AssistantEventHandler', 'AssistantStreamManager' ] ================================================ FILE: python/core/assistant/threads/runs/runs.py ================================================ # Copyright (c) 2024 Baidu, Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import os import json from typing import Optional, Union from appbuilder.core.assistant.threads.runs.steps import Steps from appbuilder.core.assistant.threads.runs.stream_helper import AssistantStreamManager from appbuilder.core.assistant.threads.runs.stream_helper import AssistantEventHandler from appbuilder.core.assistant.type import thread_type from appbuilder.core.assistant.type import assistant_type from appbuilder.core.assistant.type import public_type from appbuilder.core._client import AssistantHTTPClient from appbuilder.utils.sse_util import SSEClient from appbuilder.utils.trace.tracer_wrapper import assistent_tool_trace, assistant_run_trace, assistent_stream_run_trace, assistent_stream_run_with_handler_trace class Runs(): def __init__(self) -> None: self._http_client = AssistantHTTPClient() @property def steps(self) -> Steps: """ 返回步骤对象 Args: 无 Returns: Steps: 返回一个新的Steps对象 """ return Steps() @assistant_run_trace def run(self, assistant_id: str, thread_id: Optional[str] = "", thread: Optional[thread_type.AssistantThread] = None, model: Optional[str] = None, response_format: Optional[str] = "text", instructions: Optional[str] = None, thought_instructions: Optional[str] = None, chat_instructions: Optional[str] = None, tools: Optional[list[assistant_type.AssistantTool]] = [], metadata: Optional[dict] = {}, tool_output: Optional[thread_type.ToolOutput] = None, model_parameters: Optional[public_type.AssistantModelParameters] = None, user_info: Optional[public_type.AssistantUserInfo] = None, user_loc: Optional[public_type.AssistantUserLoc] = None, ) -> thread_type.RunResult: """ Args: assistant_id (str): 助手id thread_id (Optional[str], optional): 对话id. Defaults to "". thread (Optional[thread_type.AssistantThread], optional): 对话信息. Defaults to None. model (Optional[str], optional): 模型名称. Defaults to None. response_format (Optional[str], optional): 返回格式. Defaults to "text". instructions (Optional[str], optional): 指令信息. Defaults to None. thought_instructions (Optional[str], optional): 思考指令信息. Defaults to None. chat_instructions (Optional[str], optional): 闲聊指令信息. Defaults to None. tools (Optional[list[assistant_type.AssistantTool]], optional): 工具列表. Defaults to []. metadata (Optional[dict], optional): 元数据. Defaults to {}. tool_output (Optional[thread_type.ToolOutput], optional): 工具输出. Defaults to None. model_parameters (Optional[public_type.AssistantModelParameters], optional): 模型运行参数. Defaults to None. user_info (Optional[public_type.AssistantUserInfo], optional): 用户身份信息. Defaults to None. user_loc (Optional[public_type.AssistantUserLoc], optional): 用户定位信息. Defaults to None. Returns: thread_type.RunResult: 运行结果 Raises: ValueError: thread_id和thread不能同时为空,model_parameters的各个参数不在规定范围内 Note: 1. 如果thread_id没有传,则thread必须要传值 2. 如果这里不传值,thread_id查出来的历史对话,最后一条消息的role必须为user 3. 如果这里传值,则需要保证thread_id查出来的历史对话 + 本轮追加的thread对话,最后一条消息的role必须为user """ headers = self._http_client.auth_header() url = self._http_client.service_url("/v2/threads/runs") if thread_id == "" and thread is None: raise ValueError("Runs().run() argument thread_id && thread can't be empty at the same time") if model_parameters: chat_temperature = model_parameters.chat_parameters.temperature chat_top_p = model_parameters.chat_parameters.top_p chat_penalty_score = model_parameters.chat_parameters.penalty_score thought_temperature = model_parameters.thought_parameters.temperature thought_top_p = model_parameters.thought_parameters.top_p thought_penalty_score = model_parameters.thought_parameters.penalty_score if chat_temperature < 0 or chat_temperature > 1 or thought_temperature < 0 or thought_temperature > 1: raise ValueError("chat_temperature and thought_temperature must be in range [0, 1]") if chat_top_p < 0 or chat_top_p > 1 or thought_top_p < 0 or thought_top_p > 1: raise ValueError("chat_top_p and thought_top_p must be in range [0, 1]") if chat_penalty_score < 1 or chat_penalty_score > 2 or thought_penalty_score < 1 or thought_penalty_score > 2: raise ValueError("chat_penalty_score and thought_penalty_score must be in range [1, 2]") req = thread_type.AssistantRunRequest( thread_id=thread_id, thread=thread, model=model, assistant_id=assistant_id, response_format=response_format, instructions=instructions, thought_instructions=thought_instructions, chat_instructions=chat_instructions, model_parameters = model_parameters, stream=False, tools=tools, metadata=metadata, tool_output=tool_output, user_info=user_info, user_loc=user_loc ) response = self._http_client.session.post( url=url, headers=headers, json=req.model_dump(), timeout=None ) self._http_client.check_response_header(response) data = response.json() request_id = self._http_client.response_request_id(response) self._http_client.check_assistant_response(request_id, data) resp = thread_type.RunResult(**data) return resp def _stream(self, assistant_id: str, thread_id: Optional[str] = "", thread: Optional[thread_type.AssistantThread] = None, model: Optional[str] = None, response_format: Optional[str] = "text", instructions: Optional[str] = None, thought_instructions: Optional[str] = None, chat_instructions: Optional[str] = None, tools: Optional[list[assistant_type.AssistantTool]] = [], metadata: Optional[dict] = {}, tool_output: Optional[thread_type.ToolOutput] = None, model_parameters: Optional[public_type.AssistantModelParameters] = None, user_info: Optional[public_type.AssistantUserInfo] = None, user_loc: Optional[public_type.AssistantUserLoc] = None, ): """ 启动一个流式运行的对话,用于处理对话流中的消息。 Args: assistant_id (str): 助理ID。 thread_id (Optional[str], optional): 线程ID,用于恢复历史对话。默认为空字符串。 thread (Optional[thread_type.AssistantThread], optional): 线程对象,用于恢复历史对话。默认为None。 model (Optional[str], optional): 使用的模型名称。默认为None。 response_format (Optional[str], optional): 响应格式,支持"text"和"json"两种格式。默认为"text"。 instructions (Optional[str], optional): 指令文本。默认为 None。 thought_instructions (Optional[str], optional): 思考指令文本。默认为 None。 chat_instructions (Optional[str], optional): 聊天指令文本。默认为 None。 tools (Optional[list[assistant_type.AssistantTool]], optional): 使用的工具列表。默认为空列表。 metadata (Optional[dict], optional): 元数据字典。默认为空字典。 tool_output (Optional[thread_type.ToolOutput], optional): 工具输出对象。默认为None。 model_parameters (Optional[public_type.AssistantModelParameters], optional): 模型运行参数. Defaults to None. Returns: Iterator[thread_type.AssistantRunEvent]: 返回一个迭代器,用于遍历流式运行中的事件。 Raises: ValueError: 如果thread_id和thread参数同时为空,则会引发ValueError异常。model_parameters的各个参数不在规定范围内。 Note: 1. 如果thread_id没有传,则thread必须要传值。 2. 如果这里不传值,thread_id查出来的历史对话,最后一条消息的role必须为user。 3. 如果这里传值,则需要保证thread_id查出来的历史对话 + 本轮追加的thread对话,最后一条消息的role必须为user。 """ headers = self._http_client.auth_header() url = self._http_client.service_url("/v2/threads/runs") """ 注意: 1. 若thread_id没有传,则thread必须要传值 2. 若这里不传值,thread_id查出来的历史对话,最后一条消息的role必须为user 3. 若这里传值,则需要保证thread_id查出来的历史对话 + 本轮追加的thread对话,最后一条消息的role必须为user """ if thread_id == "" and thread is None: raise ValueError("Runs().run() argument thread_id and thread can't be empty at the same time") if model_parameters: chat_temperature = model_parameters.chat_parameters.temperature chat_top_p = model_parameters.chat_parameters.top_p chat_penalty_score = model_parameters.chat_parameters.penalty_score thought_temperature = model_parameters.thought_parameters.temperature thought_top_p = model_parameters.thought_parameters.top_p thought_penalty_score = model_parameters.thought_parameters.penalty_score if chat_temperature < 0 or chat_temperature > 1 or thought_temperature < 0 or thought_temperature > 1: raise ValueError("chat_temperature and thought_temperature must be in range [0, 1]") if chat_top_p < 0 or chat_top_p > 1 or thought_top_p < 0 or thought_top_p > 1: raise ValueError("chat_top_p and thought_top_p must be in range [0, 1]") if chat_penalty_score < 1 or chat_penalty_score > 2 or thought_penalty_score < 1 or thought_penalty_score > 2: raise ValueError("chat_penalty_score and thought_penalty_score must be in range [1, 2]") req = thread_type.AssistantRunRequest( thread_id=thread_id, thread=thread, model=model, assistant_id=assistant_id, response_format=response_format, instructions=instructions, thought_instructions=thought_instructions, chat_instructions=chat_instructions, stream=True, model_parameters=model_parameters, tools=tools, metadata=metadata, tool_output=tool_output, user_info=user_info, user_loc=user_loc ) response = self._http_client.session.post( url=url, headers=headers, json=req.model_dump(), stream=True, timeout=None ) return response @assistent_stream_run_trace def stream_run(self, assistant_id: str, thread_id: Optional[str] = "", thread: Optional[thread_type.AssistantThread] = None, model: Optional[str] = None, response_format: Optional[str] = "text", instructions: Optional[str] = None, thought_instructions: Optional[str] = None, chat_instructions: Optional[str] = None, tools: Optional[list[assistant_type.AssistantTool]] = [], metadata: Optional[dict] = {}, tool_output: Optional[thread_type.ToolOutput] = None, model_parameters: Optional[public_type.AssistantModelParameters] = None, user_info: Optional[public_type.AssistantUserInfo] = None, user_loc: Optional[public_type.AssistantUserLoc] = None, ) -> Union[thread_type.StreamRunStatus, thread_type.StreamRunMessage, None]: """ 启动一个流式运行的对话,用于处理对话流中的消息。 Args: assistant_id (str): 助理ID。 thread_id (Optional[str], optional): 线程ID,用于恢复历史对话。默认为空字符串。 thread (Optional[thread_type.AssistantThread], optional): 线程对象,用于恢复历史对话。默认为None。 model (Optional[str], optional): 使用的模型名称。默认为None。 response_format (Optional[str], optional): 响应格式,支持"text"和"json"两种格式。默认为"text"。 instructions (Optional[str], optional): 指令文本。默认为 None。 thought_instructions (Optional[str], optional): 思考指令文本。默认为 None。 chat_instructions (Optional[str], optional): 聊天指令文本。默认为 None。 tools (Optional[list[assistant_type.AssistantTool]], optional): 使用的工具列表。默认为空列表。 metadata (Optional[dict], optional): 元数据字典。默认为空字典。 tool_output (Optional[thread_type.ToolOutput], optional): 工具输出对象。默认为None。 model_parameters (Optional[public_type.AssistantModelParameters], optional): 模型参数对象。默认为None。 Returns: Union[thread_type.StreamRunStatus, thread_type.StreamRunMessage, None]: 返回一个迭代器,每次迭代返回一个处理结果对象,可能是 StreamRunStatus 或 StreamRunMessage。 Raises: ValueError: 如果thread_id和thread参数同时为空,则会引发ValueError异常。 Note: 1. 如果thread_id没有传,则thread必须要传值。 2. 如果这里不传值,thread_id查出来的历史对话,最后一条消息的role必须为user。 3. 如果这里传值,则需要保证thread_id查出来的历史对话 + 本轮追加的thread对话,最后一条消息的role必须为user。 """ response = self._stream( assistant_id=assistant_id, thread_id=thread_id, thread=thread, model=model, response_format=response_format, instructions=instructions, thought_instructions=thought_instructions, chat_instructions=chat_instructions, model_parameters=model_parameters, tools=tools, metadata=metadata, tool_output=tool_output, user_info=user_info, user_loc=user_loc ) self._http_client.check_response_header(response) sse_client = SSEClient(response) return self._iterate_events(sse_client.events()) @assistent_stream_run_with_handler_trace def stream_run_with_handler(self, assistant_id: str, thread_id: Optional[str] = "", thread: Optional[thread_type.AssistantThread] = None, model: Optional[str] = None, response_format: Optional[str] = "text", instructions: Optional[str] = None, thought_instructions: Optional[str] = None, chat_instructions: Optional[str] = None, tools: Optional[list[assistant_type.AssistantTool]] = [], metadata: Optional[dict] = {}, tool_output: Optional[thread_type.ToolOutput] = None, event_handler: Optional[AssistantEventHandler] = None, model_parameters: Optional[public_type.AssistantModelParameters] = None, user_info: Optional[public_type.AssistantUserInfo] = None, user_loc: Optional[public_type.AssistantUserLoc] = None, ) -> AssistantStreamManager: """ 使用带有事件处理器的流运行助手 Args: assistant_id (str): 助手的唯一标识符 thread_id (Optional[str], optional): 会话线程的标识符,默认为空字符串. 默认为 "". thread (Optional[thread_type.AssistantThread], optional): 会话线程对象,默认为None. 默认为 None. model (Optional[str], optional): 模型标识符,默认为None. 默认为 None. response_format (Optional[str], optional): 响应格式,可选值为"text"或"json",默认为"text". 默认为 "text". instructions (Optional[str], optional): 主要指令,默认为空字符串. 默认为 None. thought_instructions (Optional[str], optional): 思维指令,默认为空字符串. 默认为 None. chat_instructions (Optional[str], optional): 聊天指令,默认为空字符串. 默认为 None. tools (Optional[list[assistant_type.AssistantTool]], optional): 助手工具列表,默认为空列表. 默认为 []. metadata (Optional[dict], optional): 元数据字典,默认为空字典. 默认为 {}. tool_output (Optional[thread_type.ToolOutput], optional): 工具输出对象,默认为None. 默认为 None. event_handler (Optional[AssistantEventHandler], optional): 事件处理器对象,默认为None. 默认为 None. model_parameters (Optional[public_type.AssistantModelParameters], optional): 模型参数对象,默认为None. 默认为 None. user_info (Optional[public_type.AssistantUserInfo], optional): 用户信息对象,默认为None. 默认为 None. user_loc (Optional[public_type.AssistantUserLoc], optional): 用户位置信息对象,默认为None. 默认为 None. Returns: AssistantStreamManager: 返回的流管理器对象 Raises: HTTPError: 如果HTTP响应状态码不为200,则抛出HTTPError异常 """ response = self._stream( assistant_id=assistant_id, thread_id=thread_id, thread=thread, model=model, response_format=response_format, instructions=instructions, thought_instructions=thought_instructions, chat_instructions=chat_instructions, model_parameters=model_parameters, tools=tools, metadata=metadata, tool_output=tool_output, user_info=user_info, user_loc=user_loc ) self._http_client.check_response_header(response) return AssistantStreamManager( response=response, event_handler=event_handler or AssistantEventHandler() ) def _iterate_events(self, events): """ 根据给定的事件列表,生成对应的事件处理结果 Args: events (list): 事件列表,每个元素为一个包含 'event' 和 'data' 属性的字典对象 Returns: generator: 返回一个生成器,每次迭代返回一个处理结果对象,可能是 StreamRunStatus 或 StreamRunMessage """ for event in events: try: event_class = event.event if event_class == "ping": # TODO(chengmo): record ping event, add timeout func continue data = event.data if len(data) == 0: data = event.raw data = json.loads(data) if event_class == "status": result = thread_type.StreamRunStatus(**data) elif event_class == "message": result = thread_type.StreamRunMessage(**data) except Exception as e: print(e) yield result @assistent_tool_trace def submit_tool_outputs(self, run_id: str, thread_id: str, tool_outputs: Optional[list[thread_type.ToolOutput]]) -> thread_type.RunResult: """ 向服务端提交工具输出 Args: run_id (str): 运行ID thread_id (str): 线程ID tool_outputs (Optional[list[thread_type.ToolOutput]]): 工具输出列表,可选 Returns: thread_type.RunResult: 运行结果 """ headers = self._http_client.auth_header() url = self._http_client.service_url( "/v2/threads/runs/submit_tool_outputs") req = thread_type.AssistantSubmitToolOutputsRequest( thread_id=thread_id, run_id=run_id, tool_outputs=tool_outputs ) response = self._http_client.session.post( url=url, headers=headers, json=req.model_dump(), timeout=None ) self._http_client.check_response_header(response) data = response.json() request_id = self._http_client.response_request_id(response) self._http_client.check_assistant_response(request_id, data) resp = thread_type.RunResult(**data) return resp @assistent_tool_trace def cancel(self, run_id: str, thread_id: str, sync: bool = False) -> thread_type.RunResult: """ 取消指定线程的运行 Args: run_id (str): 运行的ID thread_id (str): 线程的ID sync (bool, optional): 是否同步执行. 默认为False. Returns: thread_type.RunResult: 取消运行的结果 """ headers = self._http_client.auth_header() url = self._http_client.service_url("/v2/threads/runs/cancel") req = thread_type.AssistantRunCancelRequest( run_id=run_id, thread_id=thread_id, sync = sync ) response = self._http_client.session.post( url=url, headers=headers, json=req.model_dump(), timeout=None ) self._http_client.check_response_header(response) data = response.json() request_id = self._http_client.response_request_id(response) self._http_client.check_assistant_response(request_id, data) resp = thread_type.RunResult(**data) return resp @assistent_tool_trace def list(self, thread_id: str, limit: int = 20, order: str = 'desc', after: str = "", before: str = "") -> thread_type.RunListResponse: """ 列出对应thread的历史run记录 Args: thread_id (str): 线程ID limit (int, optional): 列表数量限制,默认为20 order (str, optional): 排序方式,'asc'为升序,'desc'为降序,默认为'desc' after (str, optional): 返回在指定时间之后的运行列表,默认为空字符串 before (str, optional): 返回在指定时间之前的运行列表,默认为空字符串 Returns: thread_type.RunListResponse: 列出对应thread的历史run记录 Raises: 无 """ headers = self._http_client.auth_header() url = self._http_client.service_url("/v2/threads/runs/list") req = thread_type.AssistantRunListRequest( thread_id=thread_id, limit=limit, order=order, after=after, before=before ) response = self._http_client.session.post( url=url, headers=headers, json=req.model_dump(), timeout=None ) self._http_client.check_response_header(response) data = response.json() request_id = self._http_client.response_request_id(response) self._http_client.check_assistant_response(request_id, data) resp = thread_type.RunListResponse(**data) return resp @assistent_tool_trace def query(self, thread_id: str, run_id: str) -> thread_type.RunResult: """ 根据thread_id和run_id,查询run的详情 Args: thread_id (str): 线程ID。 run_id (str): 运行ID。 Returns: thread_type.RunResult: 查询到的运行结果。 """ headers = self._http_client.auth_header() url = self._http_client.service_url("/v2/threads/runs/query") req = thread_type.AssistantRunQueryRequest( thread_id=thread_id, run_id=run_id ) response = self._http_client.session.post( url=url, headers=headers, json=req.model_dump(), timeout=None ) self._http_client.check_response_header(response) data = response.json() request_id = self._http_client.response_request_id(response) self._http_client.check_assistant_response(request_id, data) resp = thread_type.RunResult(**data) return resp ================================================ FILE: python/core/assistant/threads/runs/steps.py ================================================ # Copyright (c) 2024 Baidu, Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import os import json from typing import Optional from appbuilder.core.assistant.type import thread_type from appbuilder.core.assistant.type import assistant_type from appbuilder.core._client import AssistantHTTPClient from appbuilder.utils.sse_util import SSEClient from appbuilder.utils.trace.tracer_wrapper import assistent_tool_trace class Steps(): def __init__(self) -> None: self._http_client = AssistantHTTPClient() @assistent_tool_trace def list(self, thread_id: str, run_id: str, limit: int = 20, order: str = 'desc', after: str = "", before: str = "") -> thread_type.RunStepListResponse: """ 根据thread_id和run_id,列出对应run的历史step记录 Args: thread_id (str): 线程ID run_id (str): 运行ID limit (int, optional): 步骤数量限制,默认为20 order (str, optional): 排序方式,'asc'表示升序,'desc'表示降序,默认为'desc' after (str, optional): 过滤出时间戳晚于此值的步骤,默认为空 before (str, optional): 过滤出时间戳早于此值的步骤,默认为空 Returns: thread_type.RunStepListResponse: 线程运行步骤列表的响应对象 """ headers = self._http_client.auth_header() url = self._http_client.service_url("/v2/threads/runs/steps/list") req = thread_type.AssistantRunStepListRequest( thread_id=thread_id, run_id=run_id, limit=limit, order=order, after=after, before=before ) response = self._http_client.session.post( url=url, headers=headers, json=req.model_dump(), timeout=None ) self._http_client.check_response_header(response) data = response.json() request_id = self._http_client.response_request_id(response) self._http_client.check_assistant_response(request_id, data) resp = thread_type.RunStepListResponse(**data) return resp @assistent_tool_trace def query(self, thread_id: str, run_id: str, step_id: str) -> thread_type.RunStepResult: """ 根据thread_id,run_id和step_id,查询对应step的信息 Args: thread_id (str): 线程ID run_id (str): 运行ID step_id (str): 步骤ID Returns: thread_type.RunStepResult: 步骤运行结果 """ headers = self._http_client.auth_header() url = self._http_client.service_url("/v2/threads/runs/steps/query") req = thread_type.AssistantRunStepQueryRequest( thread_id=thread_id, run_id=run_id, step_id=step_id ) response = self._http_client.session.post( url=url, headers=headers, json=req.model_dump(), timeout=None ) self._http_client.check_response_header(response) data = response.json() request_id = self._http_client.response_request_id(response) self._http_client.check_assistant_response(request_id, data) resp = thread_type.RunStepResult(**data) return resp ================================================ FILE: python/core/assistant/threads/runs/stream_helper.py ================================================ # Copyright (c) 2024 Baidu, Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import os import json from typing import Optional, Iterator, Union from appbuilder.core.assistant.type import thread_type from appbuilder.utils.sse_util import SSEClient from appbuilder.utils.logger_util import logger class StreamRunContext(object): """ StreamRunContext类用于管理和维护流式运行时的上下文信息。 这个类提供了存储和获取当前流事件、工具调用、运行ID、运行步骤ID、线程ID和助手ID等属性的功能。 通过创建StreamRunContext的实例,可以方便地跟踪和处理流式运行时的各种状态和数据。 Attributes: current_event: 当前流事件的对象。 current_tool_calls: 当前工具调用的相关信息。 current_run_id: 当前运行的唯一标识符。 current_run_step_id: 当前运行步骤的唯一标识符。 current_thread_id: 当前线程的唯一标识符。 current_assistant_id: 当前助手的唯一标识符。 Note: 这个类通常作为其他流式处理类(如StreamProcessor、StreamHandler等)的组成部分, 用于在流式处理过程中传递和共享上下文信息。 """ def __init__(self) -> None: # 当前事件 self._current_event = None # 当前工具调用 self._current_tool_calls = None # 当前运行ID self._current_run_id = None # 当前运行步骤ID self._current_run_step_id = None # 当前线程ID self._current_thread_id = None # 当前助手ID self._current_assistant_id = None @property def current_event(self) -> Union[thread_type.StreamRunStatus, thread_type.StreamRunMessage, None]: """ 获取当前事件。 Args: 无 Returns: Union[thread_type.StreamRunStatus, thread_type.StreamRunMessage, None]: 当前事件,可能为StreamRunStatus类型(表示流运行状态)、StreamRunMessage类型(表示流运行消息)或None。 """ return self._current_event def set_current_event(self, event): """ 设置当前事件 Args: event (thread_type.StreamRunStatus or thread_type.StreamRunMessage): 需要设置的事件对象 Returns: None Raises: 无 """ if isinstance(event, thread_type.StreamRunStatus) or \ isinstance(event, thread_type.StreamRunMessage): self._current_event = event else: self._current_event = None @property def current_tool_calls(self) -> Union[list[thread_type.ToolCall], None]: """ 获取当前工具调用列表。 Args: 无 Returns: Union[list[thread_type.ToolCall], None]: 如果存在当前工具调用列表,则返回该列表;否则返回None。 """ return self._current_tool_calls def set_current_tool_calls(self, tool_calls): """ 设置当前工具调用列表。 Args: tool_calls (list of thread_type.ToolCall): 工具调用列表。 Returns: None Raises: AssertionError: 如果 tool_calls 不是 ToolCall 对象的列表。 """ if isinstance(tool_calls, list) and len(tool_calls) > 0: for call in tool_calls: assert isinstance(call, thread_type.ToolCall), \ "current_tool_calls should be a list of ToolCall object." self._current_tool_calls = tool_calls else: self._current_tool_calls = None @property def current_run_id(self) -> Union[str, None]: """ 获取当前运行的ID。 Args: 无参数。 Returns: str 或 None: 返回当前运行的ID,如果没有当前运行的ID,则返回None。 """ return self._current_run_id def set_current_run_id(self, run_id): """ 设置当前运行ID。 Args: run_id (str): 运行ID字符串。 Returns: None Raises: 无 注意事项: 如果传入的run_id不是字符串类型或长度为0,则不设置当前运行ID,将其设置为None。 """ if isinstance(run_id, str) and len(run_id) > 0: self._current_run_id = run_id else: self._current_run_id = None @property def current_run_step_id(self) -> Union[str, None]: """ 获取当前运行的步骤ID。 Args: 无参数。 Returns: Union[str, None]: 当前运行的步骤ID,如果没有运行任何步骤则返回None。 """ return self._current_run_step_id def set_current_run_step_id(self, run_step_id): """ 设置当前运行步骤的ID。 Args: run_step_id (str): 需要设置的运行步骤ID。 Returns: None Raises: 无 Note: 如果传入的run_step_id是一个非空字符串,则将其设置为当前运行步骤的ID; 否则,将当前运行步骤的ID设置为None。 """ if isinstance(run_step_id, str) and len(run_step_id) > 0: self._current_run_step_id = run_step_id else: self._current_run_step_id = None @property def current_thread_id(self) -> Union[str, None]: """ 获取当前线程的ID。 Args: 无参数。 Returns: Union[str, None]: 当前线程的ID,如果当前没有线程ID则返回None。 """ return self._current_thread_id def set_current_thread_id(self, thread_id): """ 设置当前线程的ID。 Args: thread_id (str): 要设置的线程ID。 Returns: None Raises: 无 Note: 如果thread_id不是字符串类型或者长度为0,则不会设置当前线程的ID,并将其设置为None。 """ if isinstance(thread_id, str) and len(thread_id) > 0: self._current_thread_id = thread_id else: self._current_thread_id = None @property def current_assistant_id(self) -> Union[str, None]: """ 获取当前助手ID。 Args: 无 Returns: Union[str, None]: 返回当前助手ID的字符串,如果未设置则返回None。 """ return self._current_assistant_id def set_current_assistant_id(self, assistant_id): """ 设置当前助手ID。 Args: assistant_id (str): 需要设置的助手ID。 Returns: None Raises: 无 Note: 如果输入的assistant_id是有效的字符串且长度大于0,则将其设置为当前助手ID;否则,将当前助手ID设置为None。 """ if isinstance(assistant_id, str) and len(assistant_id) > 0: self._current_assistant_id = assistant_id else: self._current_assistant_id = None def reset_step_context(self): """ 重置步骤上下文。 Args: 无 Returns: 无 """ self._current_tool_calls = None self._current_run_step_id = None self._current_event = None class AssistantEventHandler(): """ AssistantEventHandler类用于处理Assistant流式返回的相关事件。 这个类作为Assistant流式事件的处理中心,负责接收和处理来自Assistant的各种事件, 如用户交互、数据更新、状态变化等。通过实现不同的事件处理方法, 可以定义Assistant在不同事件下的行为逻辑。 Assistant事件处理程序通常与具体的Assistant实例相关联,用于管理和控制Assistant的运行流程, 以及与其他系统组件的交互。 该类包含多个方法,每个方法对应一种特定事件的处理逻辑。 当相应的事件发生时,Assistant或相关系统会调用这些方法,以执行预定义的操作。 通过继承AssistantEventHandler类并重写其方法,可以实现自定义的Assistant流式事件处理逻辑, 从而满足特定的业务需求。 """ def _init(self, response): self._response = response self._sse_client = SSEClient(response) self._event_stream = self._sse_client.events() self._iterator = self.__stream__() self.stream_run_context = StreamRunContext() def __stream__(self) -> Iterator[Union[ thread_type.StreamRunStatus, thread_type.StreamRunMessage, str]]: """ 获取流数据的迭代器,用于从事件流中读取并处理事件数据。 Args: 无参数。 Returns: 返回一个迭代器,每次迭代返回一个Union[StreamRunStatus, StreamRunMessage, str]类型的值。 StreamRunStatus类型表示流运行状态,StreamRunMessage类型表示流运行消息,str类型表示异常信息。 Raises: 流式运行过程中的任何异常都会在此抛出 """ try: for event in self._event_stream: self.stream_run_context.reset_step_context() process_res = self.__stream_event_process__(event) yield process_res except Exception as e: logger.info(e) def __stream_event_process__(self, event) -> Union[ thread_type.StreamRunStatus, thread_type.StreamRunMessage, dict]: """ 处理从stream收到的event Args: event (thread_type.StreamEvent): 从stream收到的event对象 Returns: Union[thread_type.StreamRunStatus, thread_type.StreamRunMessage, dict]: 根据event的类型,返回相应的StreamRunStatus、StreamRunMessage对象或原始数据字典 """ event_type = event.event raw_data = event.data if len(raw_data) == 0: raw_data = event.raw if event_type == 'ping': self.__timeout_process__(event) elif event_type == 'message': data = json.loads(raw_data) stream_run_message = thread_type.StreamRunMessage(**data) self.stream_run_context.set_current_event(stream_run_message) self.messages(stream_run_message) return stream_run_message elif event_type == 'status': data = json.loads(raw_data) stream_run_status = thread_type.StreamRunStatus(**data) self.stream_run_context.set_current_event(stream_run_status) # stream内置的handler,用于设置stream_context,不建议用户重载 context_func_map = { "tool_calls": self._before_tool_calls, "run_begin": self._before_run_begin, "tool_step_begin": self._before_tool_step, "tool_step_end": self._before_tool_step, } if stream_run_status.event_type in context_func_map: context_func = context_func_map[stream_run_status.event_type] context_func(stream_run_status) # 用户可以自定义的handler type_handler_func_map = { "run_begin": self.run_begin, "run_end": self.run_end, "tool_step_begin": self.tool_step_begin, "tool_step_end": self.tool_step_end, "run_cancelling": self.run_cancelling, "tool_calls": self.tool_calls, "message_creation": self.message_creation, "tool_submitted_output": self.tool_submitted_output } if stream_run_status.event_type in type_handler_func_map: status_handler_func = type_handler_func_map[stream_run_status.event_type] status_handler_func(stream_run_status) else: logger.warning( f"Unknown status: {stream_run_status.event_type}, " f"data: {stream_run_status}" ) return stream_run_status return raw_data def __timeout_process__(self, event): # TODO(chengmo): record ping event, add timeout func pass def __next__(self) -> Optional[str]: return self._iterator.__next__() def __iter__(self): for item in self._iterator: yield item def until_done(self): """ 直到迭代器结束为止,持续迭代。 Args: 无 Returns: 无 Raises: 无 """ for _ in self._iterator: ... def _before_run_begin(self, stream_run_status): self.stream_run_context.set_current_run_id( stream_run_status.details.run_object.id) self.stream_run_context.set_current_assistant_id( stream_run_status.details.run_object.assistant_id) self.stream_run_context.set_current_thread_id( stream_run_status.details.run_object.thread_id) def _before_tool_calls(self, stream_run_status): self.stream_run_context.set_current_tool_calls( stream_run_status.details.tool_calls) def _before_tool_step(self, stream_run_status): self.stream_run_context.set_current_run_step_id( stream_run_status.details.run_step_object.id) def messages(self, messages_event: thread_type.StreamRunMessage): """ 当触发 messages 打印事件时回调此函数。 Args: messages_event (thread_type.StreamRunMessage): 包含消息内容的事件对象 Returns: None Note: 用户可以重载此函数,实现自定义的消息处理逻辑。 """ pass def tool_calls(self, status_event: thread_type.StreamRunStatus): """ 当触发 tool_calls 事件时回调此函数。 Args: status_event (thread_type.StreamRunStatus): 工具调用状态事件对象 Returns: None Note: 用户可以重载此函数,实现自定义的工具调用处理逻辑。 """ pass def tool_submitted_output(self, status_event: thread_type.StreamRunStatus): """ 当触发 tool_submitted_output 事件时回调此函数。 Args: status_event (thread_type.StreamRunStatus): 工具提交输出状态事件对象 Returns: None Note: 用户可以重载此函数,实现自定义的工具输出处理逻辑。 """ pass def message_creation(self, status_event: thread_type.StreamRunStatus): """ 当触发 message_creation 事件时回调此函数。 Args: status_event (thread_type.StreamRunStatus): 消息创建状态事件对象 Returns: None Note: 用户可以重载此函数,实现自定义的消息创建处理逻辑。 """ pass def run_begin(self, status_event: thread_type.StreamRunStatus): """ 当触发 run_begin 事件时回调此函数。 Args: status_event (thread_type.StreamRunStatus): 运行开始状态事件对象 Returns: None Note: 用户可以重载此函数,实现自定义的运行开始处理逻辑。 """ pass def run_end(self, status_event: thread_type.StreamRunStatus): """ 当触发 run_end 事件时回调此函数。 Args: status_event (thread_type.StreamRunStatus): 运行结束状态事件对象 Returns: None Note: 用户可以重载此函数,实现自定义的运行结束处理逻辑。 """ pass def tool_step_begin(self, status_event: thread_type.StreamRunStatus): """ 当触发 tool_step_begin 事件时回调此函数。 Args: status_event (thread_type.StreamRunStatus): 工具步骤开始状态事件对象 Returns: None Note: 用户可以重载此函数,实现自定义的工具步骤开始处理逻辑。 """ pass def tool_step_end(self, status_event: thread_type.StreamRunStatus): """ 当触发 tool_step_end 事件时回调此函数。 Args: status_event (thread_type.StreamRunStatus): 工具步骤结束状态事件对象 Returns: None Note: 用户可以重载此函数,实现自定义的工具步骤结束处理逻辑。 """ pass def run_cancelling(self, status_event: thread_type.StreamRunStatus): """ 当触发 run_cancelling 事件时回调此函数。 Args: status_event (thread_type.StreamRunStatus): 运行取消状态事件对象 Returns: None Note: 用户可以重载此函数,实现自定义的运行取消处理逻辑。 """ pass class AssistantStreamManager(AssistantEventHandler): def __init__( self, response, event_handler: AssistantEventHandler, ) -> None: self._response = response self._event_handler = event_handler self._event_handler._init(self._response) def __enter__(self) -> AssistantEventHandler: return self._event_handler def __exit__(self, exc_type, exc_value, traceback) -> None: pass ================================================ FILE: python/core/assistant/threads/threads.py ================================================ # Copyright (c) 2024 Baidu, Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import os from typing import Optional from appbuilder.core.assistant.type import thread_type from appbuilder.core.assistant.threads.messages import Messages from appbuilder.core.assistant.threads.runs import Runs from appbuilder.core._client import AssistantHTTPClient from appbuilder.utils.trace.tracer_wrapper import assistent_tool_trace class Threads(): def __init__(self) -> None: self._http_client = AssistantHTTPClient() @property def messages(self) -> Messages: """ 获取消息实例 Args: 无 Returns: Messages: 返回Messages实例 """ return Messages() @property def runs(self) -> Runs: """ 返回Runs对象。 Args: 无 Returns: Runs: 一个Runs对象实例。 """ return Runs() @assistent_tool_trace def create(self, messages: Optional[list[thread_type.AssistantMessage]] = []) -> thread_type.ThreadCreateResponse: """ 创建一个新的对话线程。 Args: messages: 要发送给助手的消息列表。如果不传入此参数,则会创建一个空对话线程。 Returns: 一个ThreadCreateResponse对象,包含新创建的线程的相关信息。 Raises: ValueError: 如果传入的messages参数不是列表类型。 """ headers = self._http_client.auth_header() url = self._http_client.service_url("/v2/threads") if not isinstance(messages, list): raise ValueError("Threads().create() messages must be a list, but got: {}".format(messages)) req = thread_type.ThreadCreateRequest( messages=messages) response =self._http_client.session.post( url = url, headers=headers, json=req.model_dump(), timeout=None ) self._http_client.check_response_header(response) data = response.json() request_id = self._http_client.response_request_id(response) self._http_client.check_assistant_response(request_id, data) response = thread_type.ThreadCreateResponse(**data) return response @assistent_tool_trace def query(self, thread_id:str)->thread_type.ThreadQueryResponse: """ 查询对话线程信息。 Args: thread_id: 要查询的对话线程ID。 Returns: 一个ThreadQueryResponse对象,包含对话线程的相关信息。 Raises: ValueError: 如果传入的thread_id参数不是字符串类型。 """ headers = self._http_client.auth_header() url = self._http_client.service_url("/v2/threads/query") req = thread_type.ThreadQueryRequest( thread_id=thread_id) response =self._http_client.session.post( url = url, headers=headers, json=req.model_dump(), timeout=None ) self._http_client.check_response_header(response) data = response.json() request_id = self._http_client.response_request_id(response) self._http_client.check_assistant_response(request_id, data) response = thread_type.ThreadQueryResponse(**data) return response @assistent_tool_trace def delete(self, thread_id:str)->thread_type.ThreadDeleteResponse: """ 删除对话线程。 Args: thread_id: 要删除的对话线程ID。 Returns: 一个ThreadDeleteResponse对象,包含对话线程的相关信息。 Raises: ValueError: 如果传入的thread_id参数不是字符串类型。 """ headers = self._http_client.auth_header() url = self._http_client.service_url("/v2/threads/delete") req = thread_type.ThreadDeleteRequest( thread_id=thread_id) response =self._http_client.session.post( url = url, headers=headers, json=req.model_dump(), timeout=None ) self._http_client.check_response_header(response) data = response.json() request_id = self._http_client.response_request_id(response) self._http_client.check_assistant_response(request_id, data) response = thread_type.ThreadDeleteResponse(**data) return response @assistent_tool_trace def update(self, thread_id:str , metadata:Optional[dict] ={} )->thread_type.ThreadUpdateResponse: """ 更新线程信息 Args: thread_id (str): 线程ID metadata (Optional[dict], optional): 线程元数据. 默认为空字典. Returns: thread_type.ThreadUpdateResponse: 线程更新响应 Raises: TypeError: 如果metadata不是字典类型 ValueError: 如果metadata的键超过64个字符或值超过512个字符 """ if not isinstance(metadata, dict): raise TypeError("Threads().update() metadata must be a dict, but got: {}".format(type(metadata))) for key,value in metadata.items(): if len(key)>64: raise ValueError("Threads().update() metadata key must be less than 64, but got: {}".format(len(key))) if len(value)>512: raise ValueError("Threads().update() metadata value must be less than 512, but got: {}".format(len(value))) headers = self._http_client.auth_header() url = self._http_client.service_url("/v2/threads/update") req = thread_type.ThreadUpdateRequest( thread_id=thread_id) response =self._http_client.session.post( url = url, headers=headers, json=req.model_dump(), timeout=None ) self._http_client.check_response_header(response) data = response.json() request_id = self._http_client.response_request_id(response) self._http_client.check_assistant_response(request_id, data) response = thread_type.ThreadUpdateResponse(**data) return response ================================================ FILE: python/core/assistant/type/__init__.py ================================================ # Copyright (c) 2024 Baidu, Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from .public_type import ( AssistantFunctionCall, AssistantExample, AssistantFunctionJsonSchema, AssistantFunction, AssistantTool, ResponseFormat, AssistantText, AssistantContent, AssistantChatParameters, AssistantThoughtParameters, AssistantModelParameters, AssistantUserInfo, AssistantUserLoc, ) from .assistant_type import ( # AssitantFileInfo, # AssistantAnnotation, AssistantFilesCreateResponse, AssistantCreateRequest, AssistantCreateResponse, AuditStatus, AssistantFilesListData, AssistantFilesListResponse, AssistantFilesQueryResponse, AssistantFilesDeleteResponse, AssistantUpdateRequest, AssistantUpdateResponse, AssistantListRole, AssistantListRequest, AssistantListResponse, AssistantQueryRequest, AssistantQueryResponse, AssistantDeleteRequest, AssistantDeleteResponse, AssistantFilesRequest, AssistantFilesResponse, AssistantMountedFilesListRequest, AssistantMountedFilesListResponse, AssistantFilesDeleteRequest, AssistantFilesContentResponse ) from .thread_type import ( AssistantMessageRole, AssistantMessage, AssistantMessageCreateRequest, AssistantMessageCreateResponse, AssistantThread, ThreadCreateResponse, ThreadCreateRequest, AssistantThread, RunActionInfo, FunctionCall, ToolCall, SubmitToolOutput, RequiredAction, LastError, FinalAnswerMessage, FinalAnswer, RunResult, RunMessageCreation, ToolInfo, RunStepDetail, RunStepResult, StreamRunDetail, StreamRunStatus, StreamRunMessage, ToolOutput, AssistantRunRequest, AssistantSubmitToolOutputsRequest, AssistantRunCancelRequest, AssistantMessageListRole, AssistantMessageListRequest, AssistantMessageListResponse, AssistantMessageListResponseData, AssistantMessageQueryRequest, AssistantMessageQueryResponse, AssistantMessageUpdateRequest, AssistantMessageUpdateResponse, AssistantMessageFilesRequest, AssistantMessageFilesResponse, AssistantContentFilesData, ThreadQueryRequest, ThreadQueryResponse, ThreadDeleteRequest, ThreadDeleteResponse, ThreadUpdateResponse, AssistantThread ) ================================================ FILE: python/core/assistant/type/assistant_type.py ================================================ # Copyright (c) 2024 Baidu, Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from pydantic import BaseModel from pydantic import Field from typing import Optional from enum import Enum from appbuilder.core.assistant.type import ( AssistantTool, ResponseFormat ) # AssistantFilesCreateResponse类,用于描述创建助理文件后的响应信息 class AssistantFilesCreateResponse(BaseModel): id: str = "" # 文件ID bytes: int = 0 # 文件大小(字节) object: str = "" # 文件对象标识 purpose: str = "" # 文件用途 create_at: int = 0 # 文件创建时间戳 filename: str = "" # 文件名 classification_id: str = "" # 文件分类ID class AuditStatus(int,Enum): AUDITING = -1, # 审核中 NOT_AUDITED = 0, # 未审核 APPROVED = 1, # 审核通过 REJECTED = 2, # 审核不通过 NEEDS_FURTHER_AUDIT = 3, # 需要进一步审核 AUDIT_FAILED_SERVICE_EXCEPTION = 4, # 审核失败(服务异常) AUDIT_FAILED_TIMEOUT = 5, # 审核失败(审核超时) class AssistantFilesListData(BaseModel): id: str = "" # 文件ID bytes: int = 0 # 文件大小(字节) object: str = "" # 文件对象标识 purpose: str = "" # 文件用途 censored :AuditStatus = Field() # 审核状态 create_at: int = 0 # 文件创建时间戳 filename: str = "" # 文件名 classification_id: str = "" # 文件分类ID file_type: str = "" # 文件类型 class AssistantFilesListResponse(BaseModel): object :str = "list" data: list[AssistantFilesListData] = [] class AssistantFilesQueryResponse(BaseModel): id: str = "" # 文件ID bytes: int = 0 # 文件大小(字节) object: str = "" # 文件对象标识 purpose: str = "" # 文件用途 censored :AuditStatus = Field() # 审核状态 create_at: int = 0 # 文件创建时间戳 filename: str = "" # 文件名 classification_id: str = "" # 文件分类ID file_type: str = "" # 文件类型 class AssistantFilesDeleteResponse(BaseModel): id: str = "" # 文件ID object: str = "" # 文件对象标识 deleted: bool = False # 是否删除成功 # AssistantCreateRequest类,用于描述创建助理的请求参数 class AssistantCreateRequest(BaseModel): model: str = Field(default="ERNIE-4.0T-8K") # 使用的模型 name: str = Field(default="", min_length=1, max_length=128, pattern="^[\u4e00-\u9fa50-9a-zA-Z_-]+$") # 助理名称 description: str = Field(default="", max_length=512) # 助理描述 response_format: ResponseFormat = Field(default=ResponseFormat.TEXT) # 响应格式 instructions: str = Field(default="你是百度制作的AI助手", max_length=4096) # 助理的通用指令 thought_instructions: str = Field(default="", max_length=4096) # 助理的思维指令 chat_instructions: str = Field(default="", max_length=4096) # 助理的聊天指令 tools: list[AssistantTool] = Field(default=[], max_length=10) # 助理使用的工具列表 file_ids: list[str] = Field(default=[], max_length=10) # 关联文件的ID列表 metadata: dict = Field(default={}, max_length=16) # 元数据 # AssistantCreateResponse类,用于描述创建助理后的响应信息 class AssistantCreateResponse(BaseModel): id: Optional[str] = "" # 助理ID object: Optional[str] = "" # 助理对象标识 name: Optional[str] = "" # 助理名称 description: Optional[str] = "" # 助理描述 instructions: Optional[str] # 助理的通用指令 tools: Optional[list[AssistantTool]] = Field(default=[]) # 助理使用的工具列表 created_at: Optional[int] = 0 # 助理创建时间戳 thought_instructions: Optional[str] = "" # 助理的思维指令 chat_instructions: Optional[str] = "" # 助理的聊天指令 response_format: Optional[ResponseFormat] = Field(default=ResponseFormat.TEXT) # 响应格式 file_ids: Optional[list[str]] = Field(default=[]) # 关联文件的ID列表 metadata: Optional[dict] = Field(default={}, max_length=16) # 元数据 class AssistantUpdateRequest(BaseModel): assistant_id: Optional[str] = "" # 助理ID model: str = Field(default="ERNIE-4.0T-8K") # 使用的模型 name: str = Field(default="", min_length=1, max_length=128, pattern="^[\u4e00-\u9fa50-9a-zA-Z_-]+$") # 助理名称 description: str = Field(default="", max_length=512) # 助理描述 response_format: ResponseFormat = Field(default=ResponseFormat.TEXT) # 响应格式 instructions: str = Field(default="你是百度制作的AI助手", max_length=4096) # 助理的通用指令 thought_instructions: str = Field(default="", max_length=4096) # 助理的思维指令 chat_instructions: str = Field(default="", max_length=4096) # 助理的聊天指令 tools: list[AssistantTool] = Field(default=[], max_length=10) # 助理使用的工具列表 file_ids: list[str] = Field(default=[], max_length=10) # 关联文件的ID列表 metadata: dict = Field(default={}, max_length=16) # 元数据 class AssistantUpdateResponse(BaseModel): id: Optional[str] = "" # 助理ID model: Optional[str] = "" # 助理对象标识 name: Optional[str] = "" # 助理名称 description: Optional[str] = "" # 助理描述 response_format: Optional[ResponseFormat] = Field(default=ResponseFormat.TEXT) # 响应格式 instructions: Optional[str] # 助理的通用指令 created_at: Optional[int] = 0 # 助理创建时间戳 thought_instructions: Optional[str] = "" # 助理的思维指令 chat_instructions: Optional[str] = "" # 助理的聊天指令 tools: Optional[list[AssistantTool]] = Field(default=[]) # 助理使用的工具列表 file_ids: Optional[list[str]] = Field(default=[]) # 关联文件的ID列表 metadata: Optional[dict] = Field(default={}, max_length=16) # 元数据 class AssistantListRole(str, Enum): DESC = 'desc' ASC = 'asc' class AssistantListRequest(BaseModel): limit: Optional[int] = Field(default=20) # 列举结果数量上限 order: Optional[AssistantListRole] = Field(default= AssistantListRole.DESC) # 排序字段 after: Optional[str] = Field(default="") # 查询指定assistant_id之后创建的Assistant before: Optional[str] = Field(default="") # 查询指定assistant_id之前创建的Assistant class AssistantListResponse(BaseModel): object: str = "list" # 结构类型,返回值固定为 list data: Optional[list[AssistantCreateResponse]] = Field(default=[]) # Assistant对象列表 first_id: Optional[str] = "" # 返回的列表中第一条assistant的id last_id: Optional[str] = "" # 返回的列表中最后一条assistant的id has_more: bool = False # 是否还有更多的数据 class AssistantQueryRequest(BaseModel): assistant_id: Optional[str] = "" # 助理ID class AssistantQueryResponse(BaseModel): id: Optional[str] = "" # 助理ID object: Optional[str] = "" # 助理对象标识 name: Optional[str] = "" # 助理名称 description: Optional[str] = "" # 助理描述 instructions: Optional[str] # 助理的通用指令 tools: Optional[list[AssistantTool]] = Field(default=[]) # 助理使用的工具列表 created_at: Optional[int] = 0 # 助理创建时间戳 thought_instructions: Optional[str] = "" # 助理的思维指令 chat_instructions: Optional[str] = "" # 助理的聊天指令 response_format: Optional[ResponseFormat] = Field(default=ResponseFormat.TEXT) # 响应格式 file_ids: Optional[list[str]] = Field(default=[]) # 关联文件的ID列表 metadata: Optional[dict] = Field(default={}, max_length=16) # 元数据 class AssistantDeleteRequest(BaseModel): assistant_id: Optional[str] = "" # 助理ID class AssistantDeleteResponse(BaseModel): id: Optional[str] = "" # 助理ID object: Optional[str] = "" # 助理对象标识 deleted: bool = False # 删除状态 class AssistantFilesRequest(BaseModel): assistant_id: Optional[str] = "" # 助理ID file_id: Optional[str] = "" # File对象的id class AssistantFilesResponse(BaseModel): id: Optional[str] = "" # File对象的id,值等于入参 object: Optional[str] = "" # 助理对象标识 created_at: Optional[int] = 0 # 助理创建时间戳 assistant_id: Optional[str] = "" # Assistant对象的id,值等于入参 class AssistantMountedFilesListRequest(BaseModel): assistant_id: Optional[str] = "" # Assistant对象的id limit: Optional[int] = Field(default=20) # 列举结果数量上限 order: AssistantListRole = Field(default= AssistantListRole.DESC) # 排序字段 after: Optional[str] = Field(default="") # 查询指定file_id之后创建的File before: Optional[str] = Field(default="") # 查询指定file_id之前创建的File class AssistantMountedFilesListResponse(BaseModel): object: str = "list" # 结构类型,返回值固定为 list data: Optional[list[AssistantFilesResponse]] = Field(default=[]) # file对象列表 first_id: Optional[str] = "" # 返回的列表中第一条assistant的id last_id: Optional[str] = "" # 返回的列表中最后一条assistant的id has_more: bool = False # 是否还有更多的数据 class AssistantFilesDeleteRequest(BaseModel): assistant_id: Optional[str] = "" # 助理ID file_id: Optional[str] = "" # File对象的id class AssistantFilesContentResponse(BaseModel): content_type:Optional[str] = "" # 文件类型 content :Optional[bytes] =b"" # 二进制流数据 ================================================ FILE: python/core/assistant/type/public_type.py ================================================ # Copyright (c) 2024 Baidu, Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from pydantic import BaseModel from enum import Enum from typing import Union from typing import Optional class AssistantFunctionCall(BaseModel): """ 表示助理功能调用的模型。 Attributes: name (str): 函数调用的名称。 arguments (str): 函数调用的参数列表。 """ name: str arguments: str class AssistantExample(BaseModel): """ 表示助理功能示例的模型。 Attributes: role (str): 示例的角色,默认为 "user"。 content (str): 示例的内容。 function_call (AssistantFunctionCall): 函数调用的实例。 """ role: str = "user" content: str function_call: AssistantFunctionCall class AssistantFunctionJsonSchema(BaseModel): """ 表示助理功能的JSON Schema的模型。 Attributes: type (str): Schema的类型,默认为 'object'。 properties (Union[dict, None]): JSON对象的属性,默认为None。 required (Union[list[str], None]): 必需的属性列表,默认为None。 """ type: str = "object" properties: Union[dict, None] = None required: Union[list[str], None] = None class AssistantFunction(BaseModel): """ 表示助理功能的模型。 Attributes: name (str): 功能的名称。 description (str): 功能的描述。 parameters (Union[AssistantFunctionJsonSchema, None]): 功能的参数Schema,默认为None。 responses (Union[AssistantFunctionJsonSchema, None]): 功能的响应Schema,默认为None。 examples (Union[list[list[AssistantExample]], None]): 功能的示例列表,默认为None。 """ name: str description: str parameters: Union[AssistantFunctionJsonSchema, None] = None responses: Union[AssistantFunctionJsonSchema, None] = None examples: Union[list[list[AssistantExample]], None] = None class AssistantTool(BaseModel): """ 表示助理工具的模型。 Attributes: type (str): 工具的类型,默认为 'function'。 function (AssistantFunction): 功能的实例。 """ type: str = "function" function: AssistantFunction = None class ResponseFormat(str, Enum): """ 表示响应格式的枚举类型。 Values: TEXT: 文本格式。 JSON_OBJECT: JSON对象格式。 """ TEXT = "text" JSON_OBJECT = "json_object" class AssistantText(BaseModel): """ 表示助理文本内容的模型。 Attributes: value (str): 文本的值。 annotations (Optional[list[str]]): 文本的注解列表,默认为None。 """ value: str = "" annotations: Optional[list[str]] = None class AssistantContent(BaseModel): """ 表示助理内容的模型。 Attributes: type (str): 内容类型,默认为 "text"。 text (Optional[AssistantText]): 文本内容的实例,默认为None。 """ type: str = "text" text: Optional[AssistantText] = None class AssistantChatParameters(BaseModel): """ 表示助理聊天参数的模型。 Attributes: temperature (Optional[float]): 采样温度,较高的数值会使输出更随机。取值范围严格大于0,小于等于1,默认为0.8。 top_p (Optional[float]): top_p,核采样方法的概率阈值,影响输出文本的多样性,较高的数值会使输出的文本更加多样性。取值范围大于等于0,小于等于1,默认为0.8。 penalty_score (Optional[float]): 惩罚分数,减少重复生成的现象,值越大表示惩罚越大。取值范围大于等于1,小于等于2,默认为1.0。 """ temperature: Optional[float] = 0.8 top_p: Optional[float] = 0.8 penalty_score: Optional[float] = 1.0 class AssistantThoughtParameters(BaseModel): """ 表示助理思考参数的模型。 Attributes: temperature (Optional[float]): 采样温度,较高的数值会使输出更随机。取值范围严格大于0,小于等于1,默认为0.01。 top_p (Optional[float]): top_p,核采样方法的概率阈值,影响输出文本的多样性,较高的数值会使输出的文本更加多样性。取值范围大于等于0,小于等于1,默认为0。 penalty_score (Optional[float]): 惩罚分数,减少重复生成的现象,值越大表示惩罚越大取值范围大于等于1,小于等于2,默认为1.0。 """ temperature: Optional[float] = 0.01 top_p: Optional[float] = 0 penalty_score: Optional[float] = 1.0 class AssistantModelParameters(BaseModel): """ 表示助理模型的参数的模型。 Attributes: chat_parameters (Optional[AssistantChatParameters]): 聊天参数的实例,默认为None。 thought_parameters (Optional[AssistantThoughtParameters]): 思考参数的实例,默认为None。 """ chat_parameters: Optional[AssistantChatParameters] = AssistantChatParameters() thought_parameters: Optional[AssistantThoughtParameters] = ( AssistantThoughtParameters() ) class AssistantUserInfo(BaseModel): """ 表示用户信息。 Attributes: id (Optional[str]): 用户ID,默认为None。 name (Optional[str]): 用户名称,默认为None。 nickname (Optional[str]): 用户昵称,默认为None。 watermark (Optional[str]): 用户水印,默认为None。 intro (Optional[str]): 用户简介,默认为None。 baidu_id (Optional[str]): 用户百度ID,默认为None。 """ id: Optional[str] = None name: Optional[str] = None nickname: Optional[str] = None watermark: Optional[str] = None intro: Optional[str] = None baidu_id: Optional[str] = None class AssistantUserLoc(BaseModel): """ 表示用户位置信息。 Attributes: loc (Optional[str]): 用户当前的地理位置信息,使用json格式描述 uip (Optional[str]): 用户的ipv4地址 uipv6 (Optional[str]): 用户的ipv6地址 """ loc: Optional[str] = None uip: Optional[str] = None uipv6: Optional[str] = None ================================================ FILE: python/core/assistant/type/thread_type.py ================================================ # Copyright (c) 2024 Baidu, Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from pydantic import BaseModel from pydantic import Field from enum import Enum from typing import Union from typing import Optional from appbuilder.core.assistant.type import ( AssistantTool, AssistantContent, ResponseFormat, AssistantModelParameters, AssistantUserInfo, AssistantUserLoc ) class AssistantMessageRole(str, Enum): USER = 'user' ASSISTANT = 'assistant' class AssistantMessage(BaseModel): content: str role: AssistantMessageRole = Field( default=AssistantMessageRole.USER) file_ids: Optional[list[str]] = Field(default=[], max_length=10) class AssistantMessageCreateRequest(BaseModel): thread_id: str role: AssistantMessageRole = Field( default=AssistantMessageRole.USER) content: str file_ids: Optional[list[str]] = Field(default=[], max_length=10) class AssistantMessageCreateResponse(BaseModel): id: str = "" object: str = "" role: AssistantMessageRole = Field( default=AssistantMessageRole.USER) content: Optional[list[AssistantContent]] = [] created_at: int = 0 thread_id: str = "" assistant_id: Optional[str] = "" run_id: Optional[str] = "" file_ids: Optional[list[str]] = [] class AssistantMessageListRole(str, Enum): DESC = 'desc' ASC = 'asc' class AssistantMessageListRequest(BaseModel): thread_id: str limit: int = -20 order: AssistantMessageListRole = Field( default=AssistantMessageListRole.DESC) after: str = "" before: str = "" class AssistantMessageListResponseData(BaseModel): id: str = "" object: str = "" role: AssistantMessageRole = Field() content: Optional[list[AssistantContent]] = [] created_at: int = 0 thread_id: str = "" assistant_id: Optional[str] = "" run_id: Optional[str] = "" file_ids: Optional[list[str]] = [] class AssistantMessageListResponse(BaseModel): object: str = "" data: list[AssistantMessageListResponseData] = [] first_id: Optional[str] = "" last_id: Optional[str] = "" has_more: bool = False class AssistantMessageQueryRequest(BaseModel): thread_id: str message_id: str class AssistantMessageQueryResponse(BaseModel): id: str = "" object: str = "" role: AssistantMessageRole = Field() content: Optional[list[AssistantContent]] = [] created_at: int = 0 thread_id: str = "" assistant_id: Optional[str] = "" run_id: Optional[str] = "" file_ids: Optional[list[str]] = [] class AssistantMessageUpdateRequest(BaseModel): thread_id: str message_id: str content: Optional[str] file_ids: Optional[list[str]] = [] class AssistantMessageUpdateResponse(BaseModel): id: str = "" object: str = "" role: AssistantMessageRole = Field(default=AssistantMessageRole.USER) content: Optional[list[AssistantContent]] = [] created_at: int = 0 thread_id: str = "" assistant_id: Optional[str] = "" run_id: Optional[str] = "" file_ids: Optional[list[str]] = [] class AssistantMessageFilesRequest(BaseModel): thread_id: str message_id: str limit: int = -20 order : AssistantMessageListRole = Field( default=AssistantMessageListRole.DESC) after: str = "" before: str = "" class AssistantContentFilesData(BaseModel): id: str = "" object: str = "" created_at: int = 0 message_id: str = "" class AssistantMessageFilesResponse(BaseModel): object: str = "" data: list[AssistantContentFilesData] = [] first_id: Optional[str] = "" last_id: Optional[str] = "" has_more: bool = False class AssistantThread(BaseModel): messages: Optional[list[AssistantMessage]] = [] metadata: Optional[dict] = Field(default={}, max_length=16) class ThreadCreateResponse(BaseModel): id: str = "" object: str = "" created_at: int = 0 metadata: dict = {} class ThreadCreateRequest(BaseModel): messages: list[AssistantMessage] class ThreadQueryRequest(BaseModel): thread_id: str class ThreadQueryResponse(BaseModel): id: str = "" object: str = "" created_at: int = 0 metadata: dict = {} class ThreadDeleteRequest(BaseModel): thread_id: str class ThreadDeleteResponse(BaseModel): id: str = "" object: str = "" deleted: bool = False class ThreadUpdateRequest(BaseModel): thread_id: str metadata: Optional[dict] = Field(default={}, max_length=16) class ThreadUpdateResponse(BaseModel): id: str = "" object: str = "" created_at: Optional[int] = 0 metadata: Optional[dict] = {} class AssistantThread(BaseModel): messages: list[AssistantMessage] = [] class RunActionInfo(BaseModel): toolName: str = "" actionName: str = "" actionContent: str = "" class FunctionCall(BaseModel): name: str = "" arguments: str = "" output: str = "" class ToolCall(BaseModel): id: str = "" type: str = 'function' function: Union[FunctionCall, None] = None class SubmitToolOutput(BaseModel): tool_calls: Union[list[ToolCall], None] = None class RequiredAction(BaseModel): type: str = "" submit_tool_outputs: Union[SubmitToolOutput, None] = None class LastError(BaseModel): type: Optional[str] = "" message: Optional[str] = "" class FinalAnswerMessage(BaseModel): message_id: Optional[str] = "" content: Optional[list[AssistantContent]] = [] class FinalAnswer(BaseModel): type: Optional[str] = "message" message: Optional[FinalAnswerMessage] = None class RunResult(BaseModel): id: str = "" object: str = "" assistant_id: str = "" thread_id: str = "" model: str = "" instructions: str = "" thought_instructions: str = "" chat_instructions: str = "" tools: Optional[list[AssistantTool]] = None file_ids: Optional[list[str]] = None status: str = "" required_action: Optional[RequiredAction] = None last_error: Optional[LastError] = None final_answer: Optional[FinalAnswer] = None created_at: int = 0 started_at: int = 0 expired_at: int = 0 cancelled_at: int = 0 failed_at: int = 0 completed_at: int = 0 class RunMessageCreation(BaseModel): message_id: str = "" class ToolInfo(BaseModel): type: str = "" name: str = "" arguments: str = "" output: str = "" class RunStepDetail(BaseModel): type: str = "" message_creation: Union[RunMessageCreation, None] = None action_info: Union[RunActionInfo, None] = None tool_calls: Union[list[ToolCall], None] = None tool_info: Union[list[ToolInfo], None] = None class RunStepResult(BaseModel): id: Optional[str] = "" object: Optional[str] = "" assistant_id: Optional[str] = "" thread_id: Optional[str] = "" run_id: Optional[str] = "" status: Optional[str] = "" created_at: Optional[int] = 0 started_at: Optional[int] = 0 expired_at: Optional[int] = 0 cancelled_at: Optional[int] = 0 failed_at: Optional[int] = 0 completed_at: Optional[int] = 0 last_error: Union[LastError, str, None] = None type: Optional[str] = 'null' step_datail: Union[RunStepDetail, None] = None class StreamRunDetail(BaseModel): type: str = "" message_creation: Union[RunMessageCreation, None] = None run_object: Union[RunResult, None] = None run_step_object: Union[RunStepResult, None] = None tool_calls: Union[list[ToolCall], None] = None error_info: Union[LastError, None] = None class StreamRunStatus(BaseModel): event: str = "status" status: str = "" send_id: int = 0 message: str = "" event_type: str = "" details: Optional[StreamRunDetail] = None class StreamRunMessage(BaseModel): event: str = "message" status: str = "" send_id: int = 0 is_end: int = 0 message_id: str = "" message_index: str = "" content: Optional[list[AssistantContent]] = None class ToolOutput(BaseModel): tool_call_id: str = "" output: str = "" run_id: str = "" class AssistantRunModel(str,Enum): ERNIE_4_0_8K = "ERNIE-4.0T-8K" ERNIE_3_5_8K = "DeepSeek-V3.1" class AssistantRunRequest(BaseModel): thread_id: Optional[str] = Field(default="") model: Optional[AssistantRunModel] = Field(default=None) assistant_id: Optional[str] = Field(default="") metadata: Optional[dict] = Field(default={}, max_length=16) response_format: ResponseFormat = Field(default=ResponseFormat.TEXT) instructions: Optional[str] = Field(default= None, max_length=4096) thought_instructions: Optional[str] = Field(default=None, max_length=4096) chat_instructions: Optional[str] = Field(default=None, max_length=4096) stream: Optional[bool] = False model_parameters: Optional[AssistantModelParameters] = AssistantModelParameters() class Config: extra = "forbid" protected_namespaces = () thread: Optional[AssistantThread] = None tools: Optional[list[AssistantTool]] = [] tool_output: Optional[ToolOutput] = None user_info: Optional[AssistantUserInfo] = None user_loc: Optional[AssistantUserLoc] = None class AssistantSubmitToolOutputsRequest(BaseModel): thread_id: str = Field(default="", min_length=1) run_id: str = Field(default="", min_length=1) tool_outputs: Optional[list[ToolOutput]] = Field(default=[], min_length=1) class AssistantRunCancelRequest(BaseModel): thread_id: str = Field(default="", min_length=1) run_id: str = Field(default="", min_length=1) sync:bool = False class RunListOrderEnum(str, Enum): DESC = "desc" ASC = "asc" class AssistantRunListRequest(BaseModel): thread_id: str = Field(default="", min_length=1) limit: int = Field(default=20) order: RunListOrderEnum = Field(default=RunListOrderEnum.DESC) after: str = Field(default="") before: str = Field(default="") class RunListResponse(BaseModel): object: Optional[str] = Field(default="list") first_id: Optional[str] = Field(default="") last_id: Optional[str] = Field(default="") has_more: Optional[bool] = Field(default=False) data: Optional[list[RunResult]] = Field(default=[]) class AssistantRunQueryRequest(BaseModel): thread_id: str = Field(default="", min_length=1) run_id: str = Field(default="", min_length=1) class AssistantRunStepListRequest(BaseModel): thread_id: str = Field(default="", min_length=1) run_id: str = Field(default="", min_length=1) limit: int = Field(default=20) order: RunListOrderEnum = Field(default=RunListOrderEnum.DESC) after: str = Field(default="") before: str = Field(default="") class RunStepListResponse(BaseModel): object: Optional[str] = Field(default="list") first_id: Optional[str] = Field(default="") last_id: Optional[str] = Field(default="") has_more: Optional[bool] = Field(default=False) data: Optional[list[RunStepResult]] = Field(default=[]) class AssistantRunStepQueryRequest(BaseModel): thread_id: str = Field(default="", min_length=1) run_id: str = Field(default="", min_length=1) step_id: str = Field(default="", min_length=1) ================================================ FILE: python/core/component.py ================================================ # Copyright (c) 2023 Baidu, Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Component模块包括组件基类,用户自定义组件需要继承Component类,并至少实现run方法""" import json from enum import Enum from pydantic import BaseModel from pydantic import Field, field_validator from typing import ( Dict, List, Optional, Any, Generator, Union, AsyncGenerator) from appbuilder.core.utils import ttl_lru_cache from appbuilder.core._client import HTTPClient, AsyncHTTPClient from appbuilder.core.message import Message class ComponentArguments(BaseModel): """ ComponentArguments define Component meta fields Attributes: name (str): component name. tool_desc (dict): component description. """ name: str = "" tool_desc: Dict[str, Any] = {} def extract_values_to_dict(self): r"""extract ComponentArguments fields to dict""" inputs = {} for name, info in self.model_fields.items(): value = getattr(self, name) # 获取 display_name 元数据 if not info.json_schema_extra: continue variable_name = info.json_schema_extra.get('variable_name') if not variable_name: inputs[name] = value continue # 使用 Enum 成员的实际值 if isinstance(value, Message): inputs[variable_name] = str(value.content) elif isinstance(value, Enum): inputs[variable_name] = str(value.value) else: inputs[variable_name] = str(value) return inputs class Text(BaseModel, extra='allow'): info: str = Field(default="", description="具体文本内容") class Code(BaseModel, extra='allow'): code: str = Field(default="", description="代码片段") class Files(BaseModel, extra='allow'): filename: str = Field(default="", description="文件名") url: str = Field(default="", description="文件url") file_id: str = Field(default="", description="文件ID") class Urls(BaseModel, extra='allow'): url: str = Field(default="", description="链接地址") class OralText(BaseModel, extra='allow'): info: str = Field(default="", description="口语化文本内容") class ReasoningContent(BaseModel, extra="allow"): info: str = Field(default="", description="思考过程") class VideoDetail(BaseModel): url: Optional[str] = Field(None, description="视频链接") height: Optional[str] = Field(None, description="视频高度") width: Optional[str] = Field(None, description="视频宽度") size: Optional[str] = Field(None, description="视频大小,单位Bytes") duration: Optional[str] = Field(None, description="视频长度,单位秒") hover_pic: Optional[str] = Field(None, description="视频封面图") class ImageDetail(BaseModel): url: Optional[str] = Field(None, description="图片链接") height: Optional[str] = Field(None, description="图片高度") width: Optional[str] = Field(None, description="图片宽度") class References(BaseModel, extra='allow'): type: Optional[str] = Field(default="", description="类型") source: Optional[str] = Field(default="", description="来源") doc_id: Optional[str] = Field(default=None, description="文档id") content: Optional[str] = Field(default="", description="内容") extra: Optional[dict] = Field(default={}, description="其他信息") title: Optional[str] = Field("", description="网页标题") url: Optional[str] = Field("", description="网页地址") web_anchor: Optional[str] = Field("", description="网站锚文本或网站标题") icon: Optional[str] = Field(None, description="站点图标") date: Optional[str] = Field(None, description="网页日期") type: Optional[str] = Field( None, description="检索资源类型" ) id: Optional[Union[int, str]] = Field( None, description="引用编号1、2、3" ) image: Optional[ImageDetail] = Field(None, description="图片详情") video: Optional[VideoDetail] = Field(None, description="视频详情") class Image(BaseModel, extra='allow'): filename: str = Field(default="", description="图片名称") url: str = Field(default="", description="图片url") base64: Optional[str] = Field(default="", description="图片base64数据") mime_type: Optional[str] = Field( default="jpeg", description="图片类型,如image/jpeg, 可选,默认jpeg") class Chart(BaseModel, extra='allow'): type: str = Field(default="", description="图表类型") data: str = Field(default="", description="图表数据, json_str格式") class Audio(BaseModel, extra='allow'): filename: str = Field(default="", description="音频名称") url: str = Field(default="", description="音频url") base64: Optional[str] = Field(default="", description="音频base64数据") mime_type: Optional[str] = Field( default="", description="音频类型,如mp3/wav, 可选,暂无默认值") class PlanStep(BaseModel, extra='allow'): name: str = Field(default="", description="step名") arguments: dict = Field(default={}, description="step参数") thought: str = Field(default="", description="step思考结果") class Task(BaseModel, extra='allow'): id: str = Field(default="", description="task id") name: str = Field(default="", description="task名") description: str = Field(default="", description="task描述") requires: list[str] = Field(default=[], description="依赖的task列表") tool: str = Field(default="", description="工具名") parameters: dict = Field(default={}, description="参数列表") status: str = Field(default="", description="task状态") class Plan(BaseModel, extra='allow'): goal: str = Field(default="", description="计划目标") thought: str = Field(default="", description="计划思考结果") tasks: list[Task] = Field(default=[], description="任务列表") # deprecated parameters, delete when dte agent update detail: str = Field(default="", description="计划详情") steps: list[PlanStep] = Field(default=[], description="步骤列表") class FunctionCall(BaseModel, extra='allow'): thought: str = Field(default="", description="思考结果") name: str = Field(default="", description="工具名") arguments: dict = Field(default={}, description="参数列表") class Json(BaseModel, extra='allow'): data: str = Field(default="", description="json数据") class Browser(BaseModel, extra='allow'): class Computer(BaseModel, extra='allow'): vnc_url: str = Field(default="", description="vnc url") computer_id: str = Field(default="", description="该vnc容器的computer_id") class Result(BaseModel, extra='allow'): is_error: bool = Field(default=False, description="是否错误") answer: str = Field( default="", description="is_error=False为最终的总结结果, is_error=True为错误信息") class Screenshot(BaseModel, extra='allow'): browser_url: str = Field(default="", description="截图时的浏览器当前URL") url: str = Field( default="", description="图片URL (url, filename与data, mime_type二选一)") filename: str = Field(default="", description="图像文件名") mime_type: str = Field( default="image/jpeg", description="图片类型,如image/jpeg, image/png,可选,默认为image/jpeg") data: str = Field( default="", description="图片base64串 (url, filename与data, mime_type二选一)") file_id: str = Field(default="", description="图片文件ID") class Thought(BaseModel, extra='allow'): next_goal: str = Field(default="", description="下一个目标") query: str = Field(default="", description="浏览器查询内容") computer: Computer = Field(default=Computer(), description="浏览器计算资源") result: Result = Field(default=Result(), description="浏览器执行结果") screenshot: Screenshot = Field(default=Screenshot(), description="浏览器截图结果") thought: Thought = Field(default=Thought(), description="浏览器思考结果") action: Union[list, list[dict], None] = Field( default=None, description="浏览器执行动作") class Progress(BaseModel, extra='allow'): progress: float = Field(default=0.0, description="进度, 数值在0-1之间") step: str = Field(default="", description="状态枚举值") next_step_name: str = Field(default="", description="下一个step名") message: str = Field(default="", description="附加说明信息") class Content(BaseModel): name: str = Field(default="", description="介绍当前yield内容的阶段名, 使用name的必要条件,是同一组件会输出不同type的content,并且需要加以区分,方便前端渲染与用户展示") visible_scope: str = Field(default="all", description="为了界面展示明确的说明字段,三种取值:llm、user、all。llm为思考模型可见,类似function calling结果中submit的执行结果,user为终端用户可见,all包含上述两者") raw_data: dict = Field(default={}, description="raw_data是原始数据,可以是任何格式,比如json、html等,具体由开发者决定,用户上游请求结果透传,内部系统返回的信息,例如API节点收到的resp,大模型节点的MB resp") usage: dict = Field(default={}, description="大模型的token用量, ") metrics: dict = Field(default={}, description="耗时、性能、内存等trace及debug所需信息") type: str = Field(default="text", description="代表event 类型,包括 text、code、files、urls、oral_text、references、image、chart、audio、browser、plan、function_call、json、progress该字段的取值决定了下面text字段的内容结构") text: Union[Text, Code, Files, Urls, OralText, References, Image, Chart, Audio, Plan, Json, FunctionCall, Browser, Progress, ReasoningContent] = Field(default=Text, description="代表当前 event 元素的内容,每一种 event 对应的 text 结构固定") @field_validator('text', mode='before') def set_text(cls, v, values, **kwargs): if values.data['type'] == 'text': return Text(**v) elif values.data['type'] == 'code': return Code(**v) elif values.data['type'] == 'files': return Files(**v) elif values.data['type'] == 'urls': return Urls(**v) elif values.data['type'] == 'oral_text': return OralText(**v) elif values.data['type'] == 'references': return References(**v) elif values.data['type'] == 'image': return Image(**v) elif values.data['type'] == 'chart': return Chart(**v) elif values.data['type'] == 'audio': return Audio(**v) elif values.data['type'] == 'plan': return Plan(**v) elif values.data['type'] == 'function_call': return FunctionCall(**v) elif values.data['type'] == 'json': return Json(**v) elif values.data['type'] == 'browser': return Browser(**v) elif values.data['type'] == 'progress': return Progress(**v) elif values.data['type'] == "reasoning_content": return ReasoningContent(**v) else: raise ValueError(f"Invalid value for 'type': {values['type']}") class ComponentOutput(BaseModel): role: str = Field(default="tool", description="role是区分当前消息来源的重要字段,对于绝大多数组件而言,都是填写tool,标明role所在的消息来源为组件。部分思考及问答组件,role需要填写为assistant") content: list[Content] = Field(default=[], description="content是当前组件返回内容的主要payload,List[Content],每个Content Dict 包括了当前输出的一个元素") class Component: """ Component基类, 其它实现的Component子类需要继承该基类,并至少实现run方法. Args: meta (ComponentArguments): component meta information. secret_key (str): user authentication token. gateway (str): backend gateway server address. lazy_certification (bool): lazy certification flag. """ manifests = [] def __init__( self, meta: Optional[ComponentArguments] = ComponentArguments(), secret_key: Optional[str] = None, gateway: str = "", lazy_certification: bool = False, is_aysnc: bool = False, **kwargs ): r"""Component初始化方法. 参数: meta (obj: `ComponentArguments`, 可选) : component元信息. secret_key(str,可选): 用户鉴权token, 默认从环境变量中获取: os.getenv("APPBUILDER_TOKEN", ""). gateway(str, 可选): 后端网关服务地址,默认从环境变量中获取: os.getenv("GATEWAY_URL", "") lazy_certification (bool, 可选): 延迟认证,为True时在第一次运行时认证. Defaults to False. 返回: 无 """ self.meta = meta self.secret_key = secret_key self.gateway = gateway self._http_client = None self.lazy_certification = lazy_certification self.is_async = is_aysnc if not self.lazy_certification: self.set_secret_key_and_gateway(self.secret_key, self.gateway) def set_secret_key_and_gateway(self, secret_key: Optional[str] = None, gateway: str = ""): """ 设置密钥和网关地址。 Args: secret_key (Optional[str], optional): 密钥,默认为None。如果未指定,则使用实例当前的密钥。 gateway (str, optional): 网关地址,默认为空字符串。如果未指定,则使用实例当前的网关地址。 Returns: None """ self.secret_key = secret_key self.gateway = gateway # 因为子类可能重载init方法,导致没有is_async属性,所以此处需要判断一下 try: self.is_async except AttributeError: # 目前async仅在AppBuilderClient中使用,所以没有async属性的组件都可以设置为False self.is_async = False if self.is_async: self._http_client = AsyncHTTPClient(self.secret_key, self.gateway) else: self._http_client = HTTPClient(self.secret_key, self.gateway) def set_model_info(self, model_name: str, model_url: str): """为llm component设置模型,其它component不生效""" pass @property def http_client(self): """ 获取 HTTP 客户端实例。 Args: 无 Returns: HTTPClient: HTTP 客户端实例。 """ if self._http_client is None: if self.is_async: self._http_client = AsyncHTTPClient( self.secret_key, self.gateway) else: self._http_client = HTTPClient(self.secret_key, self.gateway) return self._http_client def __call__(self, *inputs, **kwargs): r"""implement __call__ method""" return self.run(*inputs, **kwargs) def tool_eval(self, *input, **kwargs) -> Generator: """ 对给定的输入执行工具的FunctionCall。 Args: *input: 一个可变数量的参数,代表输入数据。 **kwargs: 关键字参数,可以包含任意数量的键值对,用于传递额外的参数。 Returns: Generator[dict, ComponentOutput]: 生成器,生成字典和ComponentOutput类型的对象。 Raises: NotImplementedError: 如果子类没有实现此方法,则抛出此异常。 """ raise NotImplementedError def run(self, *inputs, **kwargs) -> Message: """ run method,待子类重写实现 Args: inputs: list of arguments kwargs: keyword arguments """ raise NotImplementedError def batch(self, *args, **kwargs) -> List[Message]: """ 批量处理输入并返回结果列表。 Args: *args: 可变数量的输入参数,每个参数将依次被处理。 **kwargs: 关键字参数,这些参数将被传递给每个输入的处理函数。 Returns: List[Message]: 包含处理结果的列表,每个元素对应一个输入参数的处理结果。 """ results = [self.run(inp, **kwargs) for inp in args] return results def non_stream_tool_eval(self, *args, **kwargs) -> Union[ComponentOutput, dict]: """ 对工具评估结果进行非流式处理。 Args: *args: 可变参数,具体参数依赖于调用的工具评估函数。 **kwargs: 关键字参数,具体参数依赖于调用的工具评估函数。 Returns: Union[ComponentOutput, dict]: 返回包含评估结果的 ComponentOutput 对象或字典。 如果评估结果为空,则返回包含评估结果的字典。 """ result = ComponentOutput() result_content = [] for iter_result in self.tool_eval(*args, **kwargs): result.role = iter_result.role result_content += iter_result.content result.content = result_content return result async def atool_eval(self, *args, **kwargs) -> AsyncGenerator: r""" atool_eval method,待子类重写实现 Args: args: list of arguments kwargs: keyword arguments """ return None async def arun(self, *args, **kwargs) -> Optional[Message]: r""" arun method,待子类重写实现 Args: args: list of arguments kwargs: keyword arguments """ return None async def abatch(self, *args, **kwargs) -> List[Message]: r""" abatch method,待子类重写实现 Args: args: list of arguments kwargs: keyword arguments """ return None def _trace(self, **data) -> None: r"""pass""" pass def _debug(self, **data) -> None: r"""pass""" pass def tool_desc(self) -> List[str]: r""" tool_desc method,待子类重写实现 Args: None Returns: list of strings """ return [json.dumps(manifest, ensure_ascii=False) for manifest in self.manifests] def tool_name(self) -> List[str]: r""" tool_name method,待子类重写实现 Args: None Returns: list of strings """ return [manifest["name"] for manifest in self.manifests] def create_langchain_tool(self, tool_name="", **kwargs): r""" create_langchain_tool method,将AB-SDK的Tool转换为LangChain的StructuredTool Args: tool_name: string, optional, default is empty string kwargs: keyword arguments Returns: StructuredTool """ try: from langchain_core.tools import StructuredTool except ImportError: raise ImportError( "Please install langchain to use create_langchain_tool.") # NOTE(chengmo): 可以支持LangChain的组件,必须要求具备mainfest if self.manifests == []: raise ValueError( "Compnent {} No manifests found. Cannot convert it into LangChain Tool".format(type(self))) langchain_tool_json_schema = {} # NOTE(chengmo): 虽然现阶段,组件的mainfest列表中最多只有一个元素,但是需要兼容后期可能的多Tool的情况 if len(self.manifests) > 1: if tool_name == "": raise ValueError( "Multiple tools found, please use 'tool_name' specify which one to use.") for manifest in self.manifests: if manifest["name"] == tool_name: langchain_tool_json_schema = manifest break if langchain_tool_json_schema == {}: raise ValueError( "Tool {} not found in mainfest.".format(tool_name)) else: langchain_tool_json_schema = self.manifests[0] # NOTE(chengmo): 当前AB-SDK的Tool有两种情况 # 1、存在tool_eval方法,则直接调用tool_eval方法,并设置stream=True, 汇总结果,封装成Message返回 # 2、不存在tool_eval方法,则调用run方法,并设置 stream=False, 封装成Message返回 has_tool_eval = self._has_implemented_tool_eval() langchain_tool_func = None if has_tool_eval: langchain_tool_func = self._langchain_tool_eval_implement else: langchain_tool_func = self._langchain_run_implement # NOTE(chengmo): name 及 description 都从mainfest中获取 langchain_tool_name = langchain_tool_json_schema["name"] langchain_tool_description = langchain_tool_json_schema["description"] # NOTE(chengmo): 从mainfest中获取参数的json_schema,并转换成Pydantic的BaseModel from appbuilder.utils.json_schema_to_model import json_schema_to_pydantic_model try: import copy schema = copy.deepcopy(langchain_tool_json_schema["parameters"]) schema["title"] = langchain_tool_name langchain_tool_model = json_schema_to_pydantic_model( schema, name_override=langchain_tool_name) except Exception as e: raise RuntimeError( "Failed to generate Pydantic model for tool schema: {}".format(e)) return StructuredTool.from_function( func=langchain_tool_func, name=langchain_tool_name, description=langchain_tool_description, args_schema=langchain_tool_model, return_direct=False ) def _has_implemented_tool_eval(self): has_tool_eval = False try: # 调用self.tool_eval方法,如果抛出NotImplementedError异常,则说明没有实现tool_eval方法 self.tool_eval(**{'name': "", "streaming": False}) except NotImplementedError: has_tool_eval = False else: has_tool_eval = True return has_tool_eval def _langchain_run_implement(self, **kwargs): # NOTE(chengmo): 调用run方法,并设置 stream=False, 封装成Message返回 kwargs["stream"] = False return self.run(**kwargs) def _langchain_tool_eval_implement(self, **kwargs): # NOTE(chengmo): 调用tool_eval方法,并设置 stream=True, 封装成Message返回 kwargs["stream"] = True kwargs["streaming"] = True res = self.tool_eval(**kwargs) final_result = "" # TODO(chengmo): 在组件标准化管理前,复用DTE对流式组件的处理逻辑 for step in res: if isinstance(step, str): final_result += step else: final_result += step.get("text", "") return final_result @classmethod def create_output(cls, type, text, role="tool", name="", visible_scope="all", raw_data={}, usage={}, metrics={}): """create_text_output Args: type (str): 类型,包括"text", "code", "files", "urls", "oral_text", "references", "image", "chart", "audio", "plan", "function_call" text (str|dict): text字段,可输入str或dict role (str, optional): 当前消息来源. Defaults to "tool". name (str, optional): 当前yield内容的step name. Defaults to "". visible_scope (str, optional): 界面展示明确的说明字段. Defaults to "all". raw_data (dict, optional): 内部信息,由开发者请求透传. Defaults to {}. usage (dict, optional): 大模型的token用量. Defaults to {}. metrics (dict, optional): 耗时、性能、内存等trace及debug所需信息. Defaults to {}. Returns: ComponentOutput: 组件输出 """ if isinstance(text, str): if type == "text": text = {"info": text} elif type == "code": text = {"code": text} elif type == "urls": text = {"url": text} elif type == "oral_text": text = {"info": text} elif type == "json": text = {"data": text} elif type == "reasoning_content": text = {"info": text} else: raise ValueError( "Only when type=text/code/urls/oral_text/reasoning_content, string text is allowed! Please give dict text") elif isinstance(text, dict): if type == "text": key_list = ["info"] elif type == "code": key_list = ["code"] elif type == "oral_text": key_list = ["info"] elif type == "urls": key_list = ["url"] elif type == "files": key_list = ["filename", "url"] elif type == "references": key_list = [] elif type == "image": key_list = ["filename", "url"] elif type == "chart": key_list = ["type", "data"] elif type == "audio": key_list = ["filename", "url"] elif type == "plan": # add follow key_list when dte_agent update key_list = [] # ["goal", "thought", "tasks", "detail", "steps"] elif type == "function_call": key_list = ["thought", "name", "arguments"] elif type == "json": key_list = ["data"] elif type == "browser": key_list = ["query"] elif type == "progress": key_list = [] elif type == "reasoning_content": key_list = ["info"] else: raise ValueError("Unknown type: {}".format(type)) assert all( key in text for key in key_list), "all keys:{} must be included in the text field".format(key_list) else: raise ValueError("text must be str or dict") assert role in [ "tool", "assistant"], "role must be 'tool' or 'assistant'" result = { "role": role, "content": [{ "type": type, "name": name, "text": text, "visible_scope": visible_scope, "raw_data": raw_data, "usage": usage, "metrics": metrics }] } return ComponentOutput(**result) ================================================ FILE: python/core/components/__init__.py ================================================ # Copyright (c) 2023 Baidu, Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. ================================================ FILE: python/core/components/animal_recognize/README.md ================================================ # 动物识别 (AnimalRecognition) ## 简介 动物识别 (AnimalRecognition) 支持对于输入的一张图片(可正常解码),输出动物识别结果。 ### 功能介绍 * 识别动物名称 识别近八千种动物,接口返回动物名称、置信度信息,支持自定义返回结果数, 并可获取识别结果对应的百科信息; ### 应用场景 * 拍照识图 根据拍摄照片,识别图片中动物的名称,可配合其它识图能力对识别的结果进一步细化,提升用户体验,广泛应用于拍照识图类APP中。 ## 基本用法 我们选取一张可爱的大熊猫照片,使用动物识别组件进行识别。 ![大熊猫](https://bj.bcebos.com/v1/appbuilder/animal_recognize_test.png?authorization=bce-auth-v1%2FALTAKGa8m4qCUasgoljdEDAzLm%2F2024-01-24T12%3A19%3A16Z%2F-1%2Fhost%2F411bad53034fa8f9c6edbe5c4909d76ecf6fad6862cf937c03f8c5260d51c6ae ) 下面是动物识别的代码示例: ```python import os import appbuilder import requests # 请前往千帆AppBuilder官网创建密钥,流程详见:https://cloud.baidu.com/doc/AppBuilder/s/Olq6grrt6#1%E3%80%81%E5%88%9B%E5%BB%BA%E5%AF%86%E9%92%A5 os.environ["APPBUILDER_TOKEN"] = '...' # 从BOS读取样例图片 image_url = "https://bj.bcebos.com/v1/appbuilder/animal_recognize_test.png?" \ "authorization=bce-auth-v1%2FALTAKGa8m4qCUasgoljdEDAzLm%2F2024-01-24T" \ "12%3A19%3A16Z%2F-1%2Fhost%2F411bad53034fa8f9c6edbe5c4909d76ecf6fad68" \ "62cf937c03f8c5260d51c6ae" raw_image = requests.get(image_url).content # 创建动物识别组件实例 animal_recognition = appbuilder.AnimalRecognition() # 执行识别操作并获取结果 out = animal_recognition.run(appbuilder.Message(content={"raw_image": raw_image})) print(out.content) ``` ## 参数说明 ### 鉴权说明 使用组件之前,请首先申请并设置鉴权参数,可参考[组件使用流程](https://cloud.baidu.com/doc/AppBuilder/s/Olq6grrt6#1%E3%80%81%E5%88%9B%E5%BB%BA%E5%AF%86%E9%92%A5)。 ```python # 设置环境中的TOKEN,以下示例略 os.environ["APPBUILDER_TOKEN"] = "bce-YOURTOKEN" ``` ### 初始化参数 无 ### 调用参数 | 参数名称 | 参数类型 | 是否必须 | 描述 | 示例值 | |---------|---------|------|-----------------------------|------------------------------------------------| | message | obj:`Message` | 是 | 输入的消息,用于模型的主要输入内容。这是一个必需的参数 | | | +content | Dict | 是 | 消息内容 | {"raw_image": ...., "url": "http://xxx.png"} | | ++raw_image | Bytes | 是 | 输入的图片数据,图片数据需要base64编码 | - | | ++url | String | 否 | 图像下载链接 | - | |timeout| Float | 否 | HTTP超时时间,单位:秒 |1|| | retry | Integer | 否 | HTTP重试次数 | 3 | ### 响应参数 | 参数名称 | 参数类型 | 描述 | 示例值 | |--------|---------|------|---------------------------------------| | message | obj:`Message` | 动物识别输出内容 | - | | +content | Dict | 返回结果 | "result": [{"name":"国宝大熊猫","score":"0.975161"}] | | ++name | String | 动物名称 | "国宝大熊猫" | | ++score | String | 置信度 | "0.975161" | ### 响应示例 ```json { "result":[ { "name":"国宝大熊猫", "score":"0.975161" }, { "name":"秦岭四宝", "score":"0.0161979" }, { "name":"团团圆圆", "score":"0.00239265" }, { "name":"圆仔", "score":"0.00192277" }, { "name":"棕色大熊猫", "score":"0.00130296" }, { "name":"小熊猫", "score":"0.000275865" } ] } ``` ## 高级用法 目前该模块仅提供基础的动物识别功能。 ## 更新记录和贡献 * 动物识别能力 (2024-01) ================================================ FILE: python/core/components/animal_recognize/__init__.py ================================================ ================================================ FILE: python/core/components/animal_recognize/component.py ================================================ # Copyright (c) 2023 Baidu, Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """animal recognize component.""" import base64 import json from appbuilder.core.component import Component from appbuilder.core.components.animal_recognize.model import * from appbuilder.core.message import Message from appbuilder.core._client import HTTPClient from appbuilder.core._exception import AppBuilderServerException from typing import Generator, Union from appbuilder.utils.trace.tracer_wrapper import components_run_trace, components_run_stream_trace TOP_NUM = 1 BAIKE_NUM = 0 class AnimalRecognition(Component): r""" 用于识别一张图片,即对于输入的一张图片(可正常解码,且长宽比较合适),输出动物识别结果。 Examples: .. code-block:: python import appbuilder # 请前往千帆AppBuilder官网创建密钥,流程详见:https://cloud.baidu.com/doc/AppBuilder/s/Olq6grrt6#1%E3%80%81%E5%88%9B%E5%BB%BA%E5%AF%86%E9%92%A5 os.environ["APPBUILDER_TOKEN"] = '...' animal_recognition = appbuilder.AnimalRecognition() with open("./animal_recognition_test.png", "rb") as f: out = self.component.run(appbuilder.Message(content={"raw_image": f.read()})) print(out.content) """ name = "animal_rec" version = "v1" manifests = [ { "name": "animal_rec", "description": "用于识别图片中动物类别,可识别近八千种动物", "parameters": { "type": "object", "properties": { "img_name": { "type": "string", "description": "待识别图片的文件名" }, "img_url": { "type": "string", "description": "待识别图片的url" } }, "anyOf": [ { "required": [ "img_name" ] }, { "required": [ "img_url" ] } ] } } ] @HTTPClient.check_param @components_run_trace def run(self, message: Message, timeout: float = None, retry: int = 0) -> Message: """ 根据输入消息运行动物识别功能 Args: message (Message): 输入的消息对象,其中应包含需要识别的图像数据或URL timeout (float, optional): 超时时间,单位为秒。默认为None,表示无超时限制。Defaults to None. retry (int, optional): 重试次数。默认为0,表示不重试。Defaults to 0. Returns: Message: 识别结果的消息对象 """ inp = AnimalRecognitionInMsg(**message.content) req = AnimalRecognitionRequest() if inp.raw_image: req.image = base64.b64encode(inp.raw_image) if inp.url: req.url = inp.url req.top_num = 6 req.baike_num = 0 result = self._recognize(req, timeout, retry) result_dict = proto.Message.to_dict(result) out = AnimalRecognitionOutMsg(**result_dict) return Message(content=out.model_dump()) def _recognize( self, request: AnimalRecognitionRequest, timeout: float = None, retry: int = 0, request_id: str = None, ) -> AnimalRecognitionResponse: r"""调用底层接口进行动物识别 参数: request (obj: `AnimalRecognitionRequest`) : 动物识别输入参数 返回: response (obj: `AnimalRecognitionResponse`): 动物识别返回结果 """ if not request.image and not request.url: raise ValueError("request format error, one of image or url must be set") data = AnimalRecognitionRequest.to_dict(request) if self.http_client.retry.total != retry: self.http_client.retry.total = retry headers = self.http_client.auth_header(request_id) headers['content-type'] = 'application/x-www-form-urlencoded' url = self.http_client.service_url("/v1/bce/aip/image-classify/v1/animal") response = self.http_client.session.post(url, headers=headers, data=data, timeout=timeout) self.http_client.check_response_header(response) data = response.json() self.http_client.check_response_json(data) request_id = self.http_client.response_request_id(response) self.__class__._check_service_error(request_id, data) animalRes = AnimalRecognitionResponse.from_json(json.dumps(data)) animalRes.request_id = request_id return animalRes @components_run_stream_trace def tool_eval( self, name: str, streaming: bool, origin_query: str, **kwargs, ) -> Union[Generator[str, None, None], str]: """ 用于工具的执行,通过调用底层接口进行动物识别。 Args: name (str): 工具名。 streaming (bool): 是否流式返回。 origin_query (str): 用户原始query。 **kwargs: 工具调用的额外关键字参数。 Returns: Union[Generator[str, None, None], str]: 动物识别结果,包括识别出的动物类别和相应的置信度信息。 """ traceid = kwargs.get("traceid") img_name = kwargs.get("img_name", "") img_url = kwargs.get("img_url", "") file_urls = kwargs.get("file_urls", {}) rec_res = self._recognize_w_post_process(img_name, img_url, file_urls, request_id=traceid) if streaming: yield rec_res else: return rec_res def _recognize_w_post_process(self, img_name, img_url, file_urls, request_id=None) -> str: r"""调底层接口对图片或图片url进行动物识别,并返回类别及其置信度 参数: img_name (str): 图片文件名 img_url (str): 图片url file_urls (dict): 文件名与对应文件url的映射 返回: str: 动物识别结果,包括识别出的动物类别和相应的置信度信息 """ req = AnimalRecognitionRequest() if img_name in file_urls: req.url = file_urls[img_name] if img_url: if img_url in file_urls: img_url = file_urls[img_url] req.url = img_url req.top_num = TOP_NUM req.baike_num = BAIKE_NUM result = self._recognize(req, request_id=request_id) result_dict = proto.Message.to_dict(result) rec_res = "模型识别结果为:\n" for rec_info in result_dict['result']: rec_res += "类别: {} 置信度: {}\n".format(rec_info['name'], rec_info['score']) return rec_res @staticmethod def _check_service_error(request_id: str, data: dict): r"""个性化服务response参数检查 参数: request_id (str) : 请求ID data (dict) : 动物识别body返回 返回: 无 """ if "error_code" in data or "error_msg" in data: raise AppBuilderServerException( request_id=request_id, service_err_code=data.get("error_code"), service_err_message=data.get("error_msg") ) ================================================ FILE: python/core/components/animal_recognize/model.py ================================================ # Copyright (c) 2023 Baidu, Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """animal recognize client.""" import proto from typing import List from pydantic import BaseModel class AnimalRecognitionRequest(proto.Message): r"""动物识别请求体参数. 属性: image (str): 可选。图像内容的base64编码。 url (str): 可选。图像的URL地址,经过base64编码。 图像大小必须小于4MB,图像的最短边长大于15像素,最长边长大于4096像素。 top_num (int): 返回预测得分top结果数,默认为6 baike_num (int): 控制返回结果是否带有百科信息,默认为0,不返回 必须设置image或url属性之一,如果两者都设置了,将使用image属性。 """ image: str = proto.Field( proto.STRING, number=1, ) url: str = proto.Field( proto.STRING, number=2, ) top_num: int = proto.Field( proto.INT32, number=3, ) baike_num: int = proto.Field( proto.INT64, number=4, ) class AnimalRecognitionResponse(proto.Message): """动物识别响应消息。 属性: request_id (str): 请求ID。 log_id (int): 用于问题识别的唯一日志ID。 result (List[AnimalRecognitionRes]): 动物识别结果列表。 """ request_id: str = proto.Field( proto.STRING, number=1, ) log_id: int = proto.Field( proto.INT64, number=2, ) result: 'AnimalRecognitionRes' = proto.RepeatedField( proto.MESSAGE, number=3, message='AnimalRecognitionRes', ) class AnimalRecognitionRes(proto.Message): """动物识别结果详情。 属性: name (str): 请求ID。 score (int): 用于问题识别的唯一日志ID。 baike_info (AnimalBaikeInfo): 动物识别百科信息。 """ name: str = proto.Field( proto.STRING, number=1, ) score: str = proto.Field( proto.STRING, number=2, ) baike_info: 'AnimalBaikeInfo' = proto.RepeatedField( proto.MESSAGE, number=3, message="AnimalBaikeInfo", ) class AnimalBaikeInfo(proto.Message): """物体识别百科信息。 属性: baike_url (str): 与识别结果对应的百度百科页面的URL。 image_url (str): 与识别结果相关联的图像的URL。 description (str): 百度百科提供的识别结果的描述。 """ baike_url: str = proto.Field( proto.STRING, number=1, ) image_url: str = proto.Field( proto.STRING, number=2, ) description: str = proto.Field( proto.STRING, number=3, ) class AnimalRecognitionInMsg(BaseModel): """ 动物识别输入消息 属性: raw_image(bytes): 图像原始内容 url(str): 图像下载链接 """ raw_image: bytes = b'' url: str = "" class AnimalRes(BaseModel): """动物识别对象信息 属性: name (str): 动物名称,示例:蒙古马 score (str): 置信度,示例:0.5321 """ name: str score: str class AnimalRecognitionOutMsg(BaseModel): r"""识别结果列表""" result: List[AnimalRes] # 结果列表 ================================================ FILE: python/core/components/asr/README.md ================================================ # 短语音识别-极速版 (Automatic Speech Recognition) ## 简介 短语音识别 (Automatic Speech Recognition) 可以将音频流实时识别为文字,并返回每句话的开始和结束时间,适用于手机语音输入、语音搜索、人机对话等语音交互场景。 ### 功能介绍 通过极速API接口,将语音识别为文字,毫秒级响应,快速返回识别结果。 ### 特色优势 采用领先国际的流式端到端建模方法SMLTA,近场普通话语音识别准确率可达98%;采用最新识别解码技术,识别速度提升5倍以上,极速返回识别结果;专有GPU服务集群、提供企业级的稳定服务,弹性灵活的高并发承载及高可靠性保障。 ### 应用场景 语音输入、语音搜索、人机对话等。 ## 基本用法 下面是短语音识别的代码示例: ```python import os import requests import appbuilder # 设置环境变量和初始化 # 请前往千帆AppBuilder官网创建密钥,流程详见:https://cloud.baidu.com/doc/AppBuilder/s/Olq6grrt6#1%E3%80%81%E5%88%9B%E5%BB%BA%E5%AF%86%E9%92%A5 os.environ["APPBUILDER_TOKEN"] = "..." asr = appbuilder.ASR() audio_file_url = "https://bj.bcebos.com/v1/appbuilder/asr_test.pcm?authorization=bce-auth-v1" \ "%2FALTAKGa8m4qCUasgoljdEDAzLm%2F2024-01-11T10%3A56%3A41Z%2F-1%2Fhost" \ "%2Fa6c4d2ca8a3f0259f4cae8ae3fa98a9f75afde1a063eaec04847c99ab7d1e411" audio_data = requests.get(audio_file_url).content content_data = {"audio_format": "pcm", "raw_audio": audio_data, "rate": 16000} msg = appbuilder.Message(content_data) out = asr.run(msg) print(out.content) # {'result': ['北京科技馆。']} ``` ## 参数说明 ### 鉴权配置 使用组件之前,请首先申请并设置鉴权参数,可参考[组件使用流程](https://cloud.baidu.com/doc/AppBuilder/s/Olq6grrt6#1%E3%80%81%E5%88%9B%E5%BB%BA%E5%AF%86%E9%92%A5)。 ```python # 设置环境中的TOKEN,以下示例略 os.environ["APPBUILDER_TOKEN"] = "bce-YOURTOKEN" ``` ### 初始化参数 无 ### 调用参数 |参数名称 |参数类型 |是否必须 |描述 | 示例值 | |--------|--------|--------|----|--------| |message |String |是 |输入的消息,用于模型的主要输入内容。这是一个必需的参数,语音时长最长为60S| Message(content={"raw_audio": b"..."}) | |audio_format|String|是 |定义语言文件的格式,包括"pcm"、"wav"、"amr",默认值为"pcm"| pcm | |rate|Integer|是 |定义录音采样率,固定值16000| 16000 | |timeout| Float | 否 | HTTP超时时间,单位:秒 |1|| |retry|Integer|是 |HTTP重试次数| 3 | ### 响应参数 |参数名称 | 参数类型 |描述 |示例值| |--------|--------------|----|------| |result | List[String] |返回结果|["北京科技馆。"]| ### 响应示例 ```json {"result": ["北京科技馆。"]} ``` ### 错误码 | 错误码 |描述| |---|---| | 0 |success| | 2000 |data empty| ## 高级用法 目前该模块仅提供基础的语音识别功能。 ## 更新记录和贡献 * 短语音识别能力 (2023-12) ================================================ FILE: python/core/components/asr/__init__.py ================================================ # Copyright (c) 2023 Baidu, Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. ================================================ FILE: python/core/components/asr/component.py ================================================ # Copyright (c) 2023 Baidu, Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. r"""ASR component. """ import os import uuid import json import requests import tempfile from urllib.parse import urlparse from appbuilder.core.component import Component from appbuilder.core.message import Message from appbuilder.core._exception import AppBuilderServerException, InvalidRequestArgumentError from appbuilder.core._client import HTTPClient from appbuilder.core.components.asr.model import ShortSpeechRecognitionRequest, ShortSpeechRecognitionResponse, \ ASRInMsg, ASROutMsg from appbuilder.utils.trace.tracer_wrapper import components_run_trace, components_run_stream_trace DEFAULT_AUDIO_MAX_DURATION = 55 * 1000 # 55s # 参考短语音极速版API(https://ai.baidu.com/ai-doc/SPEECH/Jlbxdezuf) DEFAULT_FRAME_RATE = 16000 class ASR(Component): r""" ASR组件,即对于输入的语音文件,输出语音识别结果 Examples: .. code-block:: python import appbuilder asr = appbuilder.ASR() os.environ["APPBUILDER_TOKEN"] = '...' with open("xxxx.pcm", "rb") as f: audio_data = f.read() content_data = {"audio_format": "pcm", "raw_audio": audio_data, "rate": 16000} msg = appbuilder.Message(content_data) out = asr.run(msg) print(out.content) # eg: {"result": ["北京科技馆。"]} """ name = "asr" version = "v1" manifests = [ { "name": "asr", "description": "对于输入的语音文件进行识别,输出语音识别结果。", "parameters": { "type": "object", "properties": { "file_url": { "type": "string", "description": "输入语音文件的url,根据url获取到语音文件" }, "file_name": { "type": "string", "description": "待识别语音文件名,用于生成获取语音的url" }, "file_type": { "type": "string", "description": "语音文件类型,支持pcm/wav/amr/m4a", "enum": ["pcm", "wav", "amr", "m4a"] } }, "anyOf": [ { "required": [ "file_url" ] }, { "required": [ "file_name" ] } ] } } ] @HTTPClient.check_param @components_run_trace def run(self, message: Message, audio_format: str = "pcm", rate: int = 16000, timeout: float = None, retry: int = 0, **kwargs) -> Message: r""" 执行语音识别操作,并返回识别结果。 Args: message (Message): 输入消息对象,包含待识别的音频数据。该参数为必需项,格式如:Message(content={"raw_audio": b"..."})。 audio_format (str, optional): 音频文件格式,支持pcm/wav/amr/m4a,不区分大小写,推荐使用pcm格式。默认为"pcm"。 rate (int, optional): 音频采样率,固定为16000。默认为16000。 timeout (float, optional): HTTP请求超时时间。默认为None。 retry (int, optional): HTTP请求重试次数。默认为0。 Returns: Message: 语音识别结果,格式如:Message(content={"result": ["识别结果"]})。 """ inp = ASRInMsg(**message.content) request = ShortSpeechRecognitionRequest() request.format = audio_format request.rate = rate request.cuid = str(uuid.uuid4()) request.dev_pid = "80001" request.speech = inp.raw_audio traceid = kwargs.get("traceid", "") response = self._recognize(request, timeout, retry, request_id=traceid) out = ASROutMsg(result=list(response.result)) return Message(content=out.model_dump()) def _recognize( self, request: ShortSpeechRecognitionRequest, timeout: float = None, retry: int = 0, request_id: str = None, ) -> ShortSpeechRecognitionResponse: """ 使用给定的输入并返回语音识别的结果。 参数: request (obj:`ShortSpeechRecognitionRequest`): 输入请求,这是一个必需的参数。 timeout (float, 可选): 请求的超时时间。 retry (int, 可选): 请求的重试次数。 返回: obj:`ShortSpeechRecognitionResponse`: 接口返回的输出消息。 """ ContentType = "audio/" + request.format + ";rate=" + str(request.rate) headers = self.http_client.auth_header(request_id) headers['content-type'] = ContentType params = { 'dev_pid': request.dev_pid, 'cuid': request.cuid } if retry != self.http_client.retry.total: self.http_client.retry.total = retry response = self.http_client.session.post(self.http_client.service_url("/v1/bce/aip_speech/asrpro"), params=params, headers=headers, data=request.speech, timeout=timeout) self.http_client.check_response_header(response) data = response.json() self.http_client.check_response_json(data) request_id = self.http_client.response_request_id(response) self.__class__._check_service_error(request_id, data) response = ShortSpeechRecognitionResponse.from_json(payload=json.dumps(data)) response.request_id = request_id return response @staticmethod def _check_service_error(request_id: str, data: dict): r"""个性化服务response参数检查 参数: request (dict) : 短语音识别body返回 返回: 无 """ if "err_no" in data and "err_msg" in data: if data["err_no"] != 0: raise AppBuilderServerException( request_id=request_id, service_err_code=data["err_no"], service_err_message=data["err_msg"] ) @components_run_stream_trace def tool_eval(self, name: str, streaming: bool, **kwargs): """ 评估给定文件名或文件URL的语音识别结果。 Args: name (str): 函数调用名称。 streaming (bool): 是否以流的方式返回结果。 **kwargs: 关键字参数,用于指定文件名、文件URL等参数。 Returns: 如果streaming为True,则通过生成器逐个返回包含识别结果的消息对象; 如果streaming为False,则返回包含识别结果的JSON字符串。 Raises: InvalidRequestArgumentError: 如果未设置文件名或文件URL不存在,则抛出此异常。 """ file_url = kwargs.get("file_url", None) if not file_url: file_urls = kwargs.get("file_urls", {}) file_path = kwargs.get("file_name", None) if not file_path: raise InvalidRequestArgumentError("request format error, file name is not set") file_name = os.path.basename(file_path) file_url = file_urls.get(file_name, None) if not file_url: raise InvalidRequestArgumentError( f"request format error, file {file_url} url does not exist" ) _, file_type = os.path.splitext(os.path.basename(urlparse(file_url).path)) file_type = file_type.strip('.') audio_file = tempfile.NamedTemporaryFile("wb", suffix=file_type) audio_file.write(requests.get(file_url).content) raw_audios = _convert(audio_file.name, file_type) text = "" for raw_audio in raw_audios: content_data = {"audio_format": file_type, "raw_audio": raw_audio, "rate": DEFAULT_FRAME_RATE} msg = Message(content_data) out = self.run(msg) text += "".join(out.content["result"]) results = {"识别结果": text} audio_file.close() res = json.dumps(results, ensure_ascii=False, indent=4) if streaming: yield { "type": "text", "text": res, "visible_scope": 'llm', } yield { "type": "text", "text": "", "visible_scope": 'user', } else: return res def _convert(path, file_type): from pydub import AudioSegment if file_type.lower() == "mp3": audio = AudioSegment.from_mp3(path) elif file_type.lower() == "wav": audio = AudioSegment.from_wav(path) # 如果是pcm格式,则直接读取并返回 elif file_type.lower() == "pcm": with open(path, "rb") as f: return [f.read()] else: # pydub自动检测音频类型 audio = AudioSegment.from_wav(path) # 如果取样率为16000且时长小于60s,则直接读取音频并返回 if (audio.frame_rate == DEFAULT_FRAME_RATE and audio.frame_count() * 1000 / audio.frame_rate < DEFAULT_AUDIO_MAX_DURATION): with open(path, "rb") as f: return [f.read()] audio = audio.set_frame_rate(DEFAULT_FRAME_RATE) total_milliseconds = int(audio.frame_count() * 1000 / audio.frame_rate) start = 0 raw_audios = [] while start < total_milliseconds: end = start + DEFAULT_AUDIO_MAX_DURATION if start + DEFAULT_AUDIO_MAX_DURATION > total_milliseconds: end = total_milliseconds audio_seg = audio[start:end] audio_seg_file = tempfile.NamedTemporaryFile("wb", suffix="wav") try: audio_seg.export(audio_seg_file.name, format="wav") with open(audio_seg_file.name, "rb") as f: raw_audios.append(f.read()) finally: audio_seg_file.close() start = end return raw_audios ================================================ FILE: python/core/components/asr/model.py ================================================ # Copyright (c) 2023 Baidu, Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. r"""ASR model.py. """ from typing import MutableSequence, List import proto from pydantic import BaseModel class ShortSpeechRecognitionRequest(proto.Message): r"""短语音识别的请求体 参数: format(str): 语音文件的格式,pcm/wav/amr/m4a。不区分大小写。推荐pcm文件。 rate(int): 采样率,16000,固定值。 cuid(str): 用户唯一标识,用来区分用户,计算UV值。建议填写能区分用户的机器 MAC 地址或 IMEI 码,长度为60字符以内。 dev_pid(int): 80001(极速版输入法模型) speech(int): 本地语音文件的的二进制语音数据。 """ format: str = proto.Field( proto.STRING, number=1, ) rate: int = proto.Field( proto.INT64, number=2, ) cuid: str = proto.Field( proto.STRING, number=3, ) dev_pid: str = proto.Field( proto.STRING, number=4, ) speech: bytes = proto.Field( proto.BYTES, number=5, ) class ShortSpeechRecognitionResponse(proto.Message): r"""短语音识别结果返回体. 参数: request_id(str): 网关层的请求ID. err_no(int): 算子层的错误码. err_msg(str): 算子层的错误信息. corpus_no(str): sn(str): 语音数据唯一标识,系统内部产生。如果反馈及debug请提供sn。 result(MutableSequence[str]): 识别结果数组,返回1个最优候选结果。utf-8 编码。 """ request_id: str = proto.Field( proto.STRING, number=1, ) err_no: int = proto.Field( proto.INT32, number=2, ) err_msg: str = proto.Field( proto.STRING, number=3, ) corpus_no: str = proto.Field( proto.STRING, number=4, ) sn: str = proto.Field( proto.STRING, number=5, ) result: MutableSequence[str] = proto.RepeatedField( proto.STRING, number=6 ) class ASRInMsg(BaseModel): """ ASR输入message. 参数: raw_audio(bytes): 原始的语音文件字节数组. """ raw_audio: bytes class ASROutMsg(BaseModel): """ ASR输出message. 参数: result(List[str]): 输出识别后的文本结果. """ result: List[str] ================================================ FILE: python/core/components/dish_recognize/README.md ================================================ # 菜品识别(DishRecognition) ## 简介 菜品识别组件(DishRecognition)可以识别超过9千种菜品,可准确识别图片中的菜品名称、卡路里,适用于多种客户识别菜品的业务场景中。 ### 功能介绍 识别超过9千种菜品,适用于识别只含有单个菜品的图片,接口返回菜品的名称、卡路里等综合信息 ### 特色优势 识别精度高,响应速度快 ### 应用场景 1. 餐饮健康:根据拍摄照片,识别图片中菜品名称,获取菜品参考卡路里含量和百科信息,可结合识别结果进一步提供饮食推荐、健康管理方案等相关功能,增强用户体验,广泛应用于餐饮娱乐类和健康管理类APP中 2. 智能结算:根据拍摄照片,识别图片中菜品名称和位置,提高结算效率,减少人工录入成本,广泛应用于餐饮行业中 ## 基本用法 通过如下示例代码可以快速开始使用菜品识别组件: 示例图片为: ![菜品识别示例图片](https://bj.bcebos.com/v1/appbuilder/dish_recognize_test.jpg?authorization=bce-auth-v1%2FALTAKGa8m4qCUasgoljdEDAzLm%2F2024-01-11T10%3A58%3A25Z%2F-1%2Fhost%2F7b8fc08b2be5adfaeaa4e3a0bb0d1a1281b10da3d6b798e116cce3e37feb3438) ```python import os import requests import appbuilder # 请前往千帆AppBuilder官网创建密钥,流程详见:https://cloud.baidu.com/doc/AppBuilder/s/Olq6grrt6#1%E3%80%81%E5%88%9B%E5%BB%BA%E5%AF%86%E9%92%A5 os.environ["APPBUILDER_TOKEN"] = '...' dish_recognition = appbuilder.DishRecognition() image_url = "https://bj.bcebos.com/v1/appbuilder/dish_recognize_test.jpg?" \ "authorization=bce-auth-v1%2FALTAKGa8m4qCUasgoljdEDAzLm%2F2024-01-11T" \ "10%3A58%3A25Z%2F-1%2Fhost%2F7b8fc08b2be5adfaeaa4e3a0bb0d1a1281b10da" \ "3d6b798e116cce3e37feb3438" raw_image = requests.get(image_url).content resp = dish_recognition(appbuilder.Message({"raw_image": raw_image})) # 输出{'result': [{'name': '剁椒鱼头', 'calorie': '127'}]} print(resp.content) ``` ## 参数说明 ### 鉴权说明 使用组件之前,请首先申请并设置鉴权参数,可参考[组件使用流程](https://cloud.baidu.com/doc/AppBuilder/s/Olq6grrt6#1%E3%80%81%E5%88%9B%E5%BB%BA%E5%AF%86%E9%92%A5)。 ```python # 设置环境中的TOKEN,以下示例略 os.environ["APPBUILDER_TOKEN"] = "bce-YOURTOKEN" ``` ### 初始化参数 无 ### 调用参数 |参数名称 |参数类型 |是否必须 |描述 | 示例值 | |--------|--------|--------|----|--------| |message |obj:`Message` |是 |待识别的图片字节流数据或url| Message(content={"raw_image": b"..."}) 或Message(content={"url": "..."}) | |timeout| Float | 否 | HTTP超时时间,单位:秒 |1|| |retry|Integer|否 |HTTP重试次数| 3 | ### 响应参数 |参数名称 |参数类型 |描述 |示例值| |--------|--------|----|------| |result |List[Object] |返回结果|[{"name": "剁椒鱼头", "calorie": "127"}]| |result[0].name |String |菜品名称|剁椒鱼头| |result[0].calorie |String |菜品卡路里含量|127| ### 响应示例 ```json {"result": [{"name": "剁椒鱼头", "calorie": "127"}]} ``` ## 更新记录和贡献 * 菜品识别 (2024-01) ================================================ FILE: python/core/components/dish_recognize/__init__.py ================================================ # Copyright (c) 2023 Baidu, Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. ================================================ FILE: python/core/components/dish_recognize/component.py ================================================ # Copyright (c) 2023 Baidu, Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # -*- coding: utf-8 -*- """ 菜品识别组件. """ import base64 from appbuilder.core.message import Message from appbuilder.core.component import Component from appbuilder.core._client import HTTPClient from appbuilder.core._exception import AppBuilderServerException from appbuilder.core.components.dish_recognize.model import * from appbuilder.utils.trace.tracer_wrapper import components_run_trace, components_run_stream_trace class DishRecognition(Component): """ 菜品识别组件,适用于识别只含有单个菜品的图片,返回识别的菜品名称和卡路里信息 Examples: .. code-block:: python import appbuilder # 请前往千帆AppBuilder官网创建密钥,流程详见:https://cloud.baidu.com/doc/AppBuilder/s/Olq6grrt6#1%E3%80%81%E5%88%9B%E5%BB%BA%E5%AF%86%E9%92%A5 os.environ["APPBUILDER_TOKEN"] = '...' dish_recognition = appbuilder.DishRecognition() with open("xxxx.jpg", "rb") as f: resp = dish_recognition(appbuilder.Message({"raw_image": f.read()})) # 输出示例 {'result': [{'name': '剁椒鱼头', 'calorie': '127'}]} print(resp.content) """ @HTTPClient.check_param @components_run_trace def run(self, message: Message, timeout: float = None, retry: int = 0) -> Message: """ 根据输入图片进行菜品识别。 Args: message (Message): 输入待识别图片,支持传图片二进制流和图片URL。 timeout (float, optional): 请求超时时间,默认为 None。 retry (int, optional): 重试次数,默认为 0。 Returns: Message: 包含菜品识别结果的输出消息。例如,Message(content={'result': [{'name': '剁椒鱼头', 'calorie': '127'}]}) """ inp = DishRecognitionInMsg(**message.content) req = DishRecognitionRequest() if inp.raw_image: req.image = base64.b64encode(inp.raw_image) if inp.url: req.url = inp.url result = self._recognize(req, timeout=timeout, retry=retry) result_dict = proto.Message.to_dict(result) out = DishRecognitionOutMsg(**result_dict) return Message(content=out.model_dump()) def _recognize(self, request: DishRecognitionRequest, timeout: float = None, retry: int = 0) -> DishRecognitionResponse: """ 发起食物识别请求并返回识别结果。 :param request: 包含执行识别所需信息的 DishRecognitionRequest 对象。 :param timeout: 请求超时时间(秒),默认为 None。 :param retry: 请求失败时的重试次数,默认为 0。 :return: 包含食物识别结果的响应对象。 """ if not request.image and not request.url: raise ValueError("request format error, one of image or url must be set") if not request.top_num: request.top_num = 1 if not request.filter_threshold: request.filter_threshold = 0.95 request_data = DishRecognitionRequest.to_dict(request) if retry != self.http_client.retry.total: self.http_client.retry.total = retry headers = self.http_client.auth_header() headers['content-type'] = 'application/x-www-form-urlencoded' url = self.http_client.service_url("/v1/bce/aip/image-classify/v2/dish") response = self.http_client.session.post(url, headers=headers, data=request_data, timeout=timeout) self.http_client.check_response_header(response) data = response.json() self.http_client.check_response_json(data) request_id = self.http_client.response_request_id(response) if "error_code" in data and "error_msg" in data: raise AppBuilderServerException(request_id=request_id, service_err_code=data["error_code"], service_err_message=data["error_msg"]) return DishRecognitionResponse(data) ================================================ FILE: python/core/components/dish_recognize/model.py ================================================ # Copyright (c) 2023 Baidu, Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # -*- coding: utf-8 -*- """ 菜品识别model """ import proto import pydantic from typing import Optional, List class DishRecognitionRequest(proto.Message): """ 菜品识别请求的请求体。 Attributes: image (str): 表示图像数据的 Base64 编码字符串。 url (str): 图像的 URL,用于识别。 top_num (int): 要返回的顶部结果的数量。 filter_threshold (float): 过滤识别结果的置信度阈值。 baike_num (int): 要返回的百科结果的数量。 Note: 'image' 或 'url' 字段至少传一个,两个都传默认使用 'image'。 """ image: str = proto.Field( proto.STRING, number=1, ) url: str = proto.Field( proto.STRING, number=2, ) top_num: int = proto.Field( proto.INT32, number=3, ) filter_threshold: float = proto.Field( proto.FLOAT, number=4, ) baike_num: int = proto.Field( proto.INT32, number=5, ) class DishRecognitionResponse(proto.Message): """ 表示菜品识别返回的响应结果。 Attributes: log_id (str): 识别请求的唯一标识符。 request_id (str): 识别请求的唯一标识符。 result_num (int): 返回的识别结果数量。 result (List[DishRecognitionRes]): 识别结果列表。 """ log_id: str = proto.Field( proto.INT64, number=1, ) request_id: str = proto.Field( proto.STRING, number=2, ) result_num: int = proto.Field( proto.INT32, number=3, ) result: "DishRecognitionRes" = proto.RepeatedField( proto.MESSAGE, number=4, message='DishRecognitionRes', ) class DishRecognitionRes(proto.Message): """ 表示菜品识别结果。 Attributes: name (str): 识别的菜品名称。 calorie (str): 识别的菜品热量信息。 has_calorie (bool): 指示识别菜品是否返回了热量信息。 probability (str): 识别置信度分数。 baike_info (DishBaikeInfo): 与被识别菜品相关的百度百科信息。 """ name: str = proto.Field( proto.STRING, number=1, ) calorie: str = proto.Field( proto.STRING, number=2, ) has_calorie: bool = proto.Field( proto.BOOL, number=3, ) probability: str = proto.Field( proto.STRING, number=4, ) baike_info: "DishBaikeInfo" = proto.Field( proto.MESSAGE, number=5, message='DishBaikeInfo', ) class DishBaikeInfo(proto.Message): """ 与被识别菜品相关的百度百科信息。 Attributes: baike_url (str): 识别菜品的百度百科页面URL。 image_url (str): 百度百科中与被识别菜品相关的图像URL。 description (str): 百度百科中关于被识别菜品的描述或信息。 """ baike_url: str = proto.Field( proto.STRING, number=1, ) image_url: str = proto.Field( proto.STRING, number=2, ) description: str = proto.Field( proto.STRING, number=3, ) class DishRecognitionInMsg(pydantic.BaseModel): """ 菜品识别的输入消息模型。 :param raw_image: 图像的字节数组,包含要识别的菜品图像的原始数据。 此字段是可选的,可以为 None。 :param url: 图像的可下载URL。如果提供,则将从此URL下载图像进行识别。 此字段也是可选的,可以为 None。 注意:raw_image 和 url 至少传一个,不能同时为 None,两个都传默认使用 raw_image。 """ raw_image: bytes = None url: str = None class DishRecognitionResult(pydantic.BaseModel): """ 表示菜品识别结果。 Attributes: name (str): 识别到的菜品名称。 calorie (Optional[str]): 菜品的卡路里信息。如果未返回卡路里信息,默认为 None。 """ name: str calorie: Optional[str] = None class DishRecognitionOutMsg(pydantic.BaseModel): """ 表示菜品识别组件返回的结构。 Attributes: result (List[DishRecognitionResult]): 包含菜品识别结果的列表。 """ result: List[DishRecognitionResult] ================================================ FILE: python/core/components/doc_crop_enhance/README.md ================================================ # 文档矫正增强 (DocCropEnhance) ## 简介 文档矫正增强 (DocCropEnhance) 可对图片中的文件、卡证、票据等内容进行四角点检测定位,提取主体内容并对其进行矫正,同时可选图片增强效果进一步提升图片清晰度,达到主体检测矫正并增强的目的,提升图片整体质量 ### 功能介绍 * 文档矫正增强 支持对文档中的文件、卡证等内容进行主体检测与矫正,同时可开启增强功能 ### 特色优势 * 技术领先 模型针对图片倾斜、弯曲等情况进行专项优化,鲁棒性强,在处理图像的同时,可完整保留原有文档内容 * 能力丰富 提供文档图片矫正、增强、去手写等多项能力,全方位提升图像质量,适用于采集质量把控、文字识别效果提升等多应用场景 ### 应用场景 旨在改善文档图像质量,提升可读性和可处理性,广泛应用于图像处理和分析、归档和数字化等领域 ## 基本用法 下面是文档矫正增强代码示例: 示例图片为 ![示例图片](https://bj.bcebos.com/v1/appbuilder/doc_enhance_test.png?authorization=bce-auth-v1%2FALTAKGa8m4qCUasgoljdEDAzLm%2F2024-01-24T12%3A51%3A09Z%2F-1%2Fhost%2F2020d2433da471b40dafa933d557a1ebe8abf28df78010f865e45dfcd6dc3951) ```python import os import appbuilder import requests # 请前往千帆AppBuilder官网创建密钥,流程详见:https://cloud.baidu.com/doc/AppBuilder/s/Olq6grrt6#1%E3%80%81%E5%88%9B%E5%BB%BA%E5%AF%86%E9%92%A5 os.environ["APPBUILDER_TOKEN"] = '...' # 从BOS读取样例图片 image_url = "https://bj.bcebos.com/v1/appbuilder/doc_enhance_test.png?" \ "authorization=bce-auth-v1%2FALTAKGa8m4qCUasgoljdEDAzLm%2F2024-01" \ "-24T12%3A51%3A09Z%2F-1%2Fhost%2F2020d2433da471b40dafa933d557a1e" \ "be8abf28df78010f865e45dfcd6dc3951" raw_image = requests.get(image_url).content # 创建文档矫正增强组件实例 doc_crop_enhance = appbuilder.DocCropEnhance() # 执行操作并获取结果 out = doc_crop_enhance.run(appbuilder.Message(content={"raw_image": raw_image}),enhance_type=3) print(out.content) # {"image_processed": "...", 'points': [{'y': 1371, 'x': 0}, {'x': 0, 'y': 0}, {'x': 997, 'y': 0}, {'x': 994, 'y': 1371}]} ``` ## 参数说明 ### 鉴权说明 使用组件之前,请首先申请并设置鉴权参数,可参考[组件使用流程](https://cloud.baidu.com/doc/AppBuilder/s/Olq6grrt6#1%E3%80%81%E5%88%9B%E5%BB%BA%E5%AF%86%E9%92%A5)。 ```python # 设置环境中的TOKEN,以下示例略 os.environ["APPBUILDER_TOKEN"] = "bce-YOURTOKEN" ``` ### 初始化参数 无 ### 调用参数 | 参数名称 | 参数类型 | 是否必须 | 描述 | 示例值 | |--------------|---------|------|-----------------------------------------------------------------------------------------------------------------------------|------------------------------------------------| | message | String | 是 | 输入的消息,用于模型的主要输入内容。这是一个必需的参数 | Message(content={"raw_image": b"待识别的图片字节流数据"}) | | enhance_type | Integer | 否 | 选择是否开启图像增强功能,如开启可选择增强效果,可选值如下:enhance_type =0:默认值,不开启增强功能,enhance_type = 1:去阴影,enhance_type = 2:增强并锐化,enhance_type = 3:黑白滤镜 | 0 | |timeout| Float | 否 | HTTP超时时间,单位:秒 |1|| | retry | Integer | 否 | HTTP重试次数 | 3 | ### 响应参数 | 参数名称 | 参数类型 | 描述 | 示例值 | |-----------------|---------|-------------------------------------------|-----------------------------------------------------------------------------------------| | image_processed | String | 返回处理后的图片,base64编码 | "..." | | points | Array[] | 检测到的图片内主体在原图中的四角点坐标 | [{ "x": 0, "y": 1371 },{ "x": 0, "y": 0 },{ "x": 997, "y": 0 },{ "x": 994, "y": 1371 }] | ### 响应示例 ```json { "image_processed": "...", "points": [ { "x": 0, "y": 1371 }, { "x": 0, "y": 0 }, { "x": 997, "y": 0 }, { "x": 994, "y": 1371 } ] } ``` ## 高级用法 目前该模块仅提供基础的文档矫正增强功能。 ## 更新记录和贡献 * 文档矫正增强能力 (2024-01) ================================================ FILE: python/core/components/doc_crop_enhance/__init__.py ================================================ ================================================ FILE: python/core/components/doc_crop_enhance/component.py ================================================ # Copyright (c) 2023 Baidu, Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """doc_crop_enhance component.""" import base64 import json from appbuilder.core.component import Component from appbuilder.core._client import HTTPClient from appbuilder.core.components.doc_crop_enhance.model import * from appbuilder.core.message import Message from appbuilder.core._exception import * from appbuilder.utils.trace.tracer_wrapper import components_run_trace, components_run_stream_trace enhance_type_set = [0, 1, 2, 3] class DocCropEnhance(Component): r""" 对图片中的文件、卡证、票据等内容进行四角点检测定位,提取主体内容并对其进行矫正,同时可选图片增强效果进一步提升图片清晰度, 达到主体检测矫正并增强的目的,提升图片整体质量 Examples: .. code-block:: python import appbuilder # 请前往千帆AppBuilder官网创建密钥,流程详见:https://cloud.baidu.com/doc/AppBuilder/s/Olq6grrt6#1%E3%80%81%E5%88%9B%E5%BB%BA%E5%AF%86%E9%92%A5 os.environ["APPBUILDER_TOKEN"] = '...' doc_crop_enhance = appbuilder.DocCropEnhance() with open("./doc_enhance_test.png", "rb") as f: out = self.component.run(appbuilder.Message(content={"raw_image": f.read()})) print(out.content) """ @HTTPClient.check_param @components_run_trace def run(self, message: Message, enhance_type: int = 0, timeout: float = None, retry: int = 0) -> Message: r""" 文档矫正增强 Args: message (Message): 输入图片或图片url下载地址用于执行操作。举例: Message(content={"raw_image": b"...", "enhance_type": 3})或 Message(content={"url": "https://image/download/url"})。 enhance_type (int, 可选): 选择是否开启图像增强功能,如开启可选择增强效果,可选值如下: - 0:默认值,不开启增强功能 - 1:去阴影 - 2:增强并锐化 - 3:黑白滤镜。 timeout (float, 可选): HTTP超时时间 retry (int, 可选): HTTP重试次数 Returns: Message: 识别结果。举例: Message(name=msg, content={'image_processed': '...', 'points': [{'x': 220, 'y': 705}, {'x': 240, 'y': 0}, {'x': 885, 'y': 2}, {'x': 980, 'y': 759}]}, mtype=dict) """ inp = DocCropEnhanceInMsg(**message.content) req = DocCropEnhanceRequest() if inp.raw_image: req.image = base64.b64encode(inp.raw_image) if inp.url: req.url = inp.url req.scan_type = 3 if enhance_type not in enhance_type_set: raise InvalidRequestArgumentError(f"mismatched argument enhance_type, expected enhance_type in {enhance_type_set}") req.enhance_type = enhance_type result = self._recognize(req, timeout, retry) result_dict = proto.Message.to_dict(result) out = DocCropEnhanceOutMsg(**result_dict) return Message(content=out.model_dump()) def _recognize(self, request: DocCropEnhanceRequest, timeout: float = None, retry: int = 0) -> DocCropEnhanceResponse: r"""文档矫正增强调用 参数: request (obj: `DocCropEnhanceRequest`) : 文档矫正增强输入参数 返回: response (obj: `DocCropEnhanceResponse`): 文档矫正增强返回结果 """ if not request.image and not request.url: raise ValueError("request argument error, one of image or url must be set") req = json.dumps(DocCropEnhanceRequest.to_dict(request)) if self.http_client.retry.total != retry: self.http_client.retry.total = retry headers = self.http_client.auth_header() headers['content-type'] = 'application/json' url = self.http_client.service_url("/v1/bce/aip/ocr/v1/doc_crop_enhance") response = self.http_client.session.post(url, headers=headers, data=req, timeout=timeout) self.http_client.check_response_header(response) data = response.json() self.http_client.check_response_json(data) request_id = self.http_client.response_request_id(response) self.__class__._check_service_error(request_id, data) res = DocCropEnhanceResponse.from_json(json.dumps(data)) res.request_id = request_id return res @staticmethod def _check_service_error(request_id: str, data: dict): r"""个性化服务response参数检查 参数: request (dict) : 文档矫正增强body返回 返回: 无 """ if "error_code" in data or "error_msg" in data: raise AppBuilderServerException( request_id=request_id, service_err_code=data.get("error_code"), service_err_message=data.get("error_msg") ) ================================================ FILE: python/core/components/doc_crop_enhance/model.py ================================================ # Copyright (c) 2023 Baidu, Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """doc_crop_enhance model.""" import proto from typing import List, Dict from pydantic import BaseModel class DocCropEnhanceRequest(proto.Message): r"""文档矫正增强请求体参数. 属性: image (str): 可选。图像内容的base64编码。 url (str): 可选。图像的URL地址,经过base64编码。 图像大小必须小于4MB,图像的最短边长大于15像素,最长边长大于4096像素。 scan_type (int): 可选。选择是否对图片内主体内容进行四角点增强或矫正。 - scan_type = 1:只做检测,不对主体进行矫正,返回主体四角点坐标,可用作前端页面展示 - scan_type = 2:只做矫正,需传入主体四角点坐标,使用传入的坐标值对主体进行扣取及矫正 - scan_type = 3:默认值,检测并矫正,返回主体在原图中的四角点坐标以及矫正后的图像 enhance_type (int): 可选。选择是否开启图像增强功能,如开启可选择增强效果,可选值如下: - enhance_type = 0:默认值,不开启增强功能 - enhance_type = 1:去阴影 - enhance_type = 2:增强并锐化 - enhance_type = 3:黑白滤镜。 必须设置image或url属性之一,如果两者都设置了,将使用image属性。 """ image: str = proto.Field( proto.STRING, number=1, ) url: str = proto.Field( proto.STRING, number=2, ) scan_type: int = proto.Field( proto.INT32, number=3, ) enhance_type: int = proto.Field( proto.INT32, number=4, ) class DocCropEnhanceResponse(proto.Message): """文档矫正增强识别响应消息。 属性: request_id (str): 请求ID。 log_id (int): 用于问题识别的唯一日志ID。 image_processed (str): 返回处理后的图片,base64编码,如请求参数 scan_type = 1 & enhance_type =0,则返回原图。 points (List[DocLocation]): 检测到的图片内主体在原图中的四角点坐标,scan_type = 2 时不返回此参数。 """ request_id: str = proto.Field( proto.STRING, number=1, ) log_id: int = proto.Field( proto.INT64, number=2, ) image_processed: str = proto.Field( proto.STRING, number=3, ) points: 'DocLocation' = proto.RepeatedField( proto.MESSAGE, number=4, message='DocLocation', ) class DocLocation(proto.Message): """图片四角点坐标。 属性: x (int): x坐标。 y (int): y坐标。 """ x: int = proto.Field( proto.INT64, number=1, ) y: int = proto.Field( proto.INT64, number=2, ) class DocCropEnhanceInMsg(BaseModel): """ 文档矫正增强识别输入消息 属性: raw_image(bytes): 图像原始内容 url(str): 图像下载链接 enhance_type(int): 可选参数 选择是否开启图像增强功能,如开启可选择增强效果,可选值如下: - enhance_type = 0:默认值,不开启增强功能 - enhance_type = 1:去阴影 - enhance_type = 2:增强并锐化 - enhance_type = 3:黑白滤镜 """ raw_image: bytes = b'' url: str = "" class DocCropEnhanceOutMsg(BaseModel): """ 文档矫正增强识别响应体 属性: image_processed(str): 处理后的图片,base64编码 points(List[Dict[str, int]]): 检测主体在原图中的四角点坐标 """ image_processed: str points: List[Dict[str, int]] ================================================ FILE: python/core/components/doc_format_converter/README.md ================================================ # 文档格式转换 (DocFormatConverter) ## 简介 文档格式转换:识别文档内文字及版面布局,可将多种类型的版式文档转换为流式文档。 ### 功能介绍 支持识别图片中文档版面布局,提取文字内容,并转换为保留原文档版式的Word/Excel,方便二次编辑和复制。 ### 特色优势 1、多种格式互转:支持多种格式相互转换,覆盖全面; 2、图像预处理:支持对文件朝向检测、印章/水印去除后等预处理,提升格式转换效果。 ### 应用场景 文档电子化:标题/正文/表格/配图等版式信息精准识别与还原,快速录入文档内容,实现纸质档案电子化。 ## 基本用法 ```python import os import requests import appbuilder # 请前往千帆AppBuilder官网创建密钥,流程详见:https://cloud.baidu.com/doc/AppBuilder/s/Olq6grrt6#1%E3%80%81%E5%88%9B%E5%BB%BA%E5%AF%86%E9%92%A5 os.environ["APPBUILDER_TOKEN"] = '...' doc_format_converter = appbuilder.DocFormatConverter() image_url = "https://ai-cape-strategy-data.bj.bcebos.com/document-restructure/1EF33F9307451C9413D5D1160.jpg" resp = doc_format_converter(appbuilder.Message({"file_path": image_url})) # 输出{"word_url":"", "excel_url":""} print(resp.content) ``` ## 参数说明 ### 鉴权说明 使用组件之前,请首先申请并设置鉴权参数,可参考[组件使用流程](https://cloud.baidu.com/doc/AppBuilder/s/Olq6grrt6#1%E3%80%81%E5%88%9B%E5%BB%BA%E5%AF%86%E9%92%A5)。 ```python # 设置环境中的TOKEN,以下示例略 os.environ["APPBUILDER_TOKEN"] = "bce-YOURTOKEN" ``` ### 初始化参数 无 ### 调用参数 | 参数名称 |参数类型 |是否必须 | 描述 | 示例值 | |------------|--------|--------|-------------|------| | file_path |String |是 | 需要转换的文件的本地存储路径或远程URL,支持图片, URL长度不超过1024字节,图片base64编码后大小不超过4M,最短边至少15px,最长边最大4096px,支持jpg/jpeg/png/bmp格式 | "./test.png" | ### 响应参数 | 参数名称 |参数类型 | 描述 | 示例值 | |-------------|--------|------|-------------------------| | word_url |Message | 还原后的word文件的下载地址,文件识别失败时返回空 | "http://bos.bce.cn/dsfkjc.docx"| | excel_url |Message | 还原后的Excel文件的下载地址(源文件中含表格时才会输出),若文档中没有表格则返回"" | "http://bos.bce.cn/dsfkjc.xlsx"| ### 常见错误信息 | 错误信息 | 描述 | |-------------------------|-------------| |IAM Certification failed |IAM鉴权失败| |Check file failed!|文件检查错误,请检查文件大小以及URL是否符合要求 | ## 更新记录和贡献 * 文档格式转换 (2024-04) ================================================ FILE: python/core/components/doc_format_converter/__init__.py ================================================ # Copyright (c) 2024 Baidu, Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. ================================================ FILE: python/core/components/doc_format_converter/component.py ================================================ # Copyright (c) 2024 Baidu, Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # -*- coding: utf-8 -*- """ 文档格式转换 """ import os import json import base64 from typing import Dict, Any import time import requests from appbuilder.core._exception import AppBuilderServerException, InvalidRequestArgumentError from appbuilder.core.component import Component, Message from appbuilder.core._client import HTTPClient from appbuilder.core.components.doc_format_converter.model import DocFormatConverterInMessage, \ DocFormatConverterOutMessage, \ DocFormatConverterSubmitRequest, DocFormatConverterSubmitResponse, \ DocFormatConverterQueryRequest, DocFormatConverterQueryResponse from appbuilder.utils.trace.tracer_wrapper import components_run_trace, components_run_stream_trace class DocFormatConverter(Component): r""" 可识别图片/PDF文档版面布局,提取文字内容,并转换为保留原文档版式的Word、Excel文档,方便二次编辑和复制, 可支持含表格、印章、水印、手写等内容的文档。满足文档格式转换、企业档案电子化等信息管理需求。 Examples: .. code-block:: python import appbuilder # 请前往千帆AppBuilder官网创建密钥 os.environ["APPBUILDER_TOKEN"] = '...' table_ocr = appbuilder.DocFormatConverter() out = self.component.run(appbuilder.Message(content={"file_path": ""})) print(out.content) """ name = "doc_converter" version = "v1" manifests = [ { "name": "doc_format_converter", "description": "提供文档格式转换功能,包含图片转word、图片转excel、PDF转word、PDF转excel", "parameters": { "type": "object", "properties": { "file_name": { "type": "string", "description": "待转换文件的文件名称", }, "file_url": { "type": "string", "description": "待转换文件的URL地址", }, "page_num": { "anyOf": [ {"type": "string"}, {"type": "integer"} ], "description": "待转换PDF文档的页码, 从1开始, 如果不传则默认转换全部页码", } }, "anyOf": [ {"required": ["file_name"]}, {"required": ["file_url"]} ] } } ] @HTTPClient.check_param @components_run_trace def run(self, message: Message, timeout: float = None, retry: int = 0, request_id: str = None) -> Message: """ 将PDF、JPG、PNG、BMP等格式文件转换为Word、Excel格式,并返回转换后的文件URL。 Args: message (Message): 包含待转换文件路径和页码信息的消息对象。 timeout (float, optional): 请求超时时间,单位为秒。默认为None,表示不设置超时时间。 retry (int, optional): 请求重试次数。默认为0,表示不重试。 Returns: Message: 包含转换后文件URL的消息对象。 Raises: AppBuilderServerException: 文档格式转换服务发生错误时抛出。 """ doc_message = DocFormatConverterInMessage(**message.content) submit_request = DocFormatConverterSubmitRequest() if doc_message.file_path.startswith(('http://', 'https://')): # TODO 根据URL判断文件类型Refactor if(".pdf" in doc_message.file_path): submit_request.pdf_file = base64.b64encode(requests.get(doc_message.file_path).content) if doc_message.page_num: submit_request.pdf_file_num = doc_message.page_num else: submit_request.url = doc_message.file_path else: if doc_message.file_path.endswith('.pdf'): with open(doc_message.file_path, 'rb') as f: submit_request.pdf_file = base64.b64encode(f.read()) if doc_message.page_num: submit_request.pdf_file_num = doc_message.page_num else: with open(doc_message.file_path, 'rb') as f: submit_request.image = base64.b64encode(f.read()) docConverterSubmitResponse = self.submitDocFormatConverterTask(submit_request, request_id=request_id) taskId = docConverterSubmitResponse.result.task_id TASK_PROGRESS_COMPLETED = 3 TASK_PROGRESS_FAILED = 4 if taskId: task_request_time = 1 while True: request = DocFormatConverterQueryRequest() request.task_id = taskId docConverterQueryResponse = self.queryDocFormatConverterTask(request, request_id=request_id) if docConverterQueryResponse.result.ret_code is not None: task_progress = docConverterQueryResponse.result.ret_code if task_progress == TASK_PROGRESS_COMPLETED: break elif task_progress == TASK_PROGRESS_FAILED: raise AppBuilderServerException(f'doc convert task progress failed: {docConverterQueryResponse.error_msg}') # TODO 文档格式转换查询间隔Refactor if task_request_time <= 3: time.sleep(3) else: time.sleep(task_request_time) task_request_time += 1 word_url = docConverterQueryResponse.result.result_data.word excel_url = docConverterQueryResponse.result.result_data.excel out = DocFormatConverterOutMessage(word_url=word_url, excel_url=excel_url) return Message(content=out.model_dump()) else: raise AppBuilderServerException(f'service error when doc convert:{docConverterSubmitResponse.error_msg}') @HTTPClient.check_param def submitDocFormatConverterTask( self, request: DocFormatConverterSubmitRequest, timeout: float = None, retry: int = 0, request_id: str = None, ) -> DocFormatConverterSubmitResponse: """ 提交任务 :param request: 请求参数 :type request: DocFormatConverterSubmitRequest :return: 返回结果 :rtype: DocFormatConverterSubmitResponse """ url = self.http_client.service_url("/v1/bce/aip/text_mind/v1/doc_convert/request",'/api') data = json.loads(DocFormatConverterSubmitRequest.to_json(request, preserving_proto_field_name=True)) headers = self.http_client.auth_header(request_id) headers['Content-Type'] = 'application/x-www-form-urlencoded' if retry != self.http_client.retry.total: self.http_client.retry.total = retry response = self.http_client.session.post(url, data=data, headers=headers, timeout=timeout) self.http_client.check_response_header(response) data = response.json() self.http_client.check_response_json(data) response = DocFormatConverterSubmitResponse.from_json(payload=json.dumps(data)) return response @HTTPClient.check_param def queryDocFormatConverterTask( self, request: DocFormatConverterQueryRequest, timeout: float = None, retry: int = 0, request_id: str = None ) -> DocFormatConverterQueryResponse: """ 查询任务 :param request: 请求参数 :type request: DoFormatcConverterQueryRequest :return: 返回结果 :rtype: DocFormatConverterSubmitResponse """ url = self.http_client.service_url("/v1/bce/aip/text_mind/v1/doc_convert/get_request_result",'/api') data = { "task_id": request.task_id } data = json.loads(DocFormatConverterQueryRequest.to_json(request, preserving_proto_field_name=True)) headers = self.http_client.auth_header(request_id) headers['content-type'] = "application/x-www-form-urlencoded" if retry != self.http_client.retry.total: self.http_client.retry.total = retry response = self.http_client.session.post(url, data=data, headers=headers, timeout=timeout) self.http_client.check_response_header(response) data = response.json() self.http_client.check_response_json(data) response = DocFormatConverterQueryResponse.from_json(payload=json.dumps(data)) return response @components_run_stream_trace def tool_eval(self, streaming: bool, origin_query: str, **kwargs,): """ 评估工具函数。 Args: streaming (bool): 是否流式输出。如果为True,则逐个生成文件URL;如果为False,则直接返回结果内容。 origin_query (str): 原始查询字符串。 **kwargs: 其他关键字参数,包括但不限于: traceid (str): 请求的跟踪ID,用于日志追踪。 file_url (str): 文件的URL地址。如果为空,则从file_urls和file_name中获取。 file_urls (dict): 包含多个文件路径与URL的映射关系的字典。 file_name (str): 文件名。如果file_url为空,则从file_urls和file_name中获取file_url。 page_num (Union[int, str]): 需要处理的页面编号,如果为字符串,必须为纯数字。 Returns: 如果streaming为True,则逐个生成包含文件URL的字典;如果streaming为False,则直接返回结果内容。 Raises: InvalidRequestArgumentError: 如果请求格式错误,如page_num不是整数、file_url为空且无法从file_urls和file_name中获取file_url等。 AppBuilderServerException: 如果服务执行过程中出现异常。 """ traceid = kwargs.get("traceid") file_url = kwargs.get("file_url", None) page_num = kwargs.get("page_num", '') if page_num: if isinstance(page_num, int) or (isinstance(page_num, str) and page_num.isdigit()): page_num = str(page_num) else: raise InvalidRequestArgumentError("request format error, page_num must be a integer") if not file_url or not (file_url.startswith("http") or file_url.startswith("https")): file_urls = kwargs.get("file_urls", {}) file_path = kwargs.get("file_name", file_url) if not file_path: raise InvalidRequestArgumentError("request format error, file name is not set") file_name = os.path.basename(file_path) file_url = file_urls.get(file_name, None) if not file_url: raise InvalidRequestArgumentError("request format error, file url is not set") try: result = self.run(Message({"file_path": file_url, "page_num": page_num}), request_id=traceid) except AppBuilderServerException: raise except Exception as e: raise AppBuilderServerException(f'service error when doc convert:{e}') if streaming: yield { "type": "files", "text": [result.content['word_url'], result.content['excel_url']] } else: return result.content ================================================ FILE: python/core/components/doc_format_converter/model.py ================================================ # Copyright (c) 2024 Baidu, Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """doc converter model.""" import proto from datetime import date, datetime from typing import List, Dict from pydantic import BaseModel class DocFormatConverterInMessage(BaseModel): """ 文档格式转换输入message 属性: file_path: 文件路径 pdf_file_num(str): 需要转换的PDF文件的对应页码, 从1开始 """ file_path: str = None page_num: str = None class DocFormatConverterOutMessage(BaseModel): """ 文档格式转换输出message 属性: word_url(str): 转换后的word路径 excel_url(str): 转换后的excel路径 """ word_url: str excel_url: str class DocFormatConverterSubmitRequest(proto.Message): """ 文档格式转换提交请求类。 用于构建和提交文档格式转换任务所需的参数。 """ image: bytes = proto.Field( proto.STRING, number=1, optional=True, ) url: str = proto.Field( proto.STRING, number=2, optional=True, ) pdf_file: str = proto.Field( proto.STRING, number=3, optional=True, ) pdf_file_num: str = proto.Field( proto.STRING, number=4, optional=True, ) class DocFormatConverterSubmitResponse(proto.Message): """文档格式转换提交响应类""" class Result(proto.Message): """Result""" task_id: str = proto.Field(proto.STRING, number=1) success: bool = proto.Field(proto.BOOL, number=1) log_id: int = proto.Field(proto.UINT64, number=2) error_code: int = proto.Field(proto.INT32, number=3) code: int = proto.Field(proto.INT32, number=4) error_msg: str = proto.Field(proto.STRING, number=5) message: str = proto.Field(proto.STRING, number=6) result: Result = proto.Field(proto.MESSAGE, number=7, message=Result) class DocFormatConverterQueryRequest(proto.Message): """ 文档格式转换查询请求类。 用于查询文档格式转换任务所需的参数 """ task_id = proto.Field( proto.STRING, number=1, ) class DocFormatConverterQueryResponse(proto.Message): """文档格式转换查询响应类""" class Result(proto.Message): """Result""" class ResultData(proto.Message): """ResultData""" word: str = proto.Field(proto.STRING, number=1) excel: str = proto.Field(proto.STRING, number=2) task_id: str = proto.Field(proto.STRING, number=1) ret_code: int = proto.Field(proto.INT32, number=2) ret_msg: str = proto.Field(proto.STRING, number=3) percent: int = proto.Field(proto.INT32, number=4) result_data: ResultData = proto.Field(proto.MESSAGE, number=5, message=ResultData) create_time: datetime = proto.Field(proto.STRING, number=6) start_time: datetime = proto.Field(proto.STRING, number=7) end_time: datetime = proto.Field(proto.STRING, number=8) success: bool = proto.Field(proto.BOOL, number=1) log_id: int = proto.Field(proto.INT64, number=2) result: Result = proto.Field(proto.MESSAGE, number=3, message=Result) code: int = proto.Field(proto.INT64, number=4) message: str = proto.Field(proto.STRING, number=5) ================================================ FILE: python/core/components/doc_parser/README.md ================================================ # 文档解析(DocParser) ## 简介 文档解析组件(DocParser)可以用于文档内容解析,支持PDF、JPG、DOC、TXT、XLS、PPT等16种文档格式的内容解析。 ### 功能介绍 文档解析组件(DocParser)支持从文档中解析出文档字符内容、版式信息、位置坐标、表格结构、阅读顺序、标题段落层级树等内容 ### 特色优势 DocParser支持解析以下几种类型的文档: * 版式文档:「pdf」、「jpg」、「jpeg」、「png」、「bmp」、「tif」、「tiff」、「ofd」 * 流式文档:「doc」、「docx」、「txt」、「xls」、「xlsx」、「wps」、「ppt」、「pptx」 支持解析的文档内容包括: * 文档的版式分析,识别文档中的标题、正文、页眉页脚、表格等 * 文档内的文字内容、位置坐标 * 表格结构和内容 * 构建文档标题段落层级树 * 构建文档阅读顺序 * 支持以上类型文档转成pdf格式 ### 应用场景 * 文档内容解析 * 文档版式解析 * 文档格式转化 ## 基本用法 以下是使用DocParser快速开始的一个示例: ```python from appbuilder import DocParser from appbuilder.core.message import Message import os import requests # 请前往千帆AppBuilder官网创建密钥,流程详见:https://cloud.baidu.com/doc/AppBuilder/s/Olq6grrt6#1%E3%80%81%E5%88%9B%E5%BB%BA%E5%AF%86%E9%92%A5 os.environ["APPBUILDER_TOKEN"] = "..." # 进行文档内容解析 file_url = "https://agi-dev-platform-bos.bj.bcebos.com/ut_appbuilder/test.pdf?authorization=bce-auth-v1/e464e6f951124fdbb2410c590ef9ed2f/2024-01-25T12%3A56%3A15Z/-1/host/b54178fea9be115eafa2a8589aeadfcfaeba20d726f434f871741d4a6cb0c70d" file_data = requests.get(file_url).content file_path = "./test.pdf" # 待解析的文件路径 with open(file_path, "wb") as f: f.write(file_data) msg = Message(file_path) parser = DocParser() parse_result = parser(msg) print(parse_result.content) ``` ## 参数说明 ### 鉴权说明 使用组件之前,请首先申请并设置鉴权参数,可参考[组件使用流程](https://cloud.baidu.com/doc/AppBuilder/s/Olq6grrt6#1%E3%80%81%E5%88%9B%E5%BB%BA%E5%AF%86%E9%92%A5)。 ```python # 设置环境中的TOKEN,以下示例略 os.environ["APPBUILDER_TOKEN"] = "bce-YOURTOKEN" ``` ### 初始化参数 无 ### 调用参数 | 参数名称 |参数类型 |是否必须 | 描述 | 示例值 | |------------|--------|--------|-------------|------| | message |String |是 | 需要解析的文档的存储路径 | "./test.pdf" | | return_raw |bool|否 | 指定是否返回原始的解析结果结构,默认为 False。 | True | ### 响应参数 | 参数名称 |参数类型 | 描述 | 示例值 | |-------------|--------|------|-------------------------| | parseResult |Message | 解析结果 | ParseResult对象,包含文档解析的内容 | ### 响应示例 ```python class ParseResult(BaseModel): """ 解析结果整体结构 """ para_node_tree: Optional[List[ParaNode]] = [] # 标题段落层级树,当ParserConfig.return_para_node_tree为True时有内容 page_contents: Optional[List[PageContent]] = [] # 页面的解析内容,详细内容参考base.py中的PageContent类 pdf_data: Optional[str] = "" # pdf格式数据, 当ParserConfig.convert_file_to_pdf为True时有内容 raw: Optional[Dict] = {} # 云端服务的原始解析结果 ``` ## 高级用法 DocParser支持自定义文档解析的配置和对解析结果进行二次处理,以下是一个示例: ```python from appbuilder import DocParser from appbuilder.core.message import Message import os import requests # 设置环境变量 os.environ["APPBUILDER_TOKEN"] = "..." # 先进行文档内容解析 file_url = "https://agi-dev-platform-bos.bj.bcebos.com/ut_appbuilder/test.pdf?authorization=bce-auth-v1/e464e6f951124fdbb2410c590ef9ed2f/2024-01-25T12%3A56%3A15Z/-1/host/b54178fea9be115eafa2a8589aeadfcfaeba20d726f434f871741d4a6cb0c70d" file_data = requests.get(file_url).content file_path = "./test.pdf" # 待解析的文件路径 with open(file_path, "wb") as f: f.write(file_data) msg = Message(file_path) parser = DocParser() config = parser.config config.convert_file_to_pdf = True # 指定将当前文件转换成pdf格式 config.page_filter = [0, 2] # 只解析第1页和第3页,注意:页码从0开始 parse_result = parser(msg) file_content = parse_result.content pdf_data = file_content.pdf_data # 获取原始文件转化成pdf之后的数据 page_content = file_content.page_content[1] # 获取第3页的解析结果 page_table = page_content.tables[0] # 第3页中第一个表格的解析结果(如有),表格的解析内容的结构详见上一章详细说明部分关于表格结果的说明 cells = page_table.cells # 表格的单元格信息 cell_text = cells[0] # 表格第一个单元格的文本内容 matrix = page_table.cell_matrix # 表格的单元格矩阵,用来描述单元格的空间位置信息 ... 自定义处理表格内容 ... ``` ### 高级用法参数详细说明 在base.py中定义了DocParser配置和结果结构,下面做一些详细的说明和解释: ### DocParser配置 ```python class ParserConfig(BaseModel): """ DocParser解析配置 """ convert_file_to_pdf: bool = Field(alias="need_pdffile_data", default=False) # 是否需要将当前文件转换成pdf格式 page_filter: List[int] = Field(alias="page_filter", default=None) # 指定解析的页码,默认传None,代表全部解析 return_para_node_tree: bool = Field(alias="return_para_nodes", default=True) # 是否需要返回标题段落层级树 erase_watermark: bool = Field(alias="erase_watermark", default=False) # 解析的过程中是否需要去除水印的干扰 ``` ### DocParser解析结果 ```python class ParseResult(BaseModel): """ 解析结果整体结构 """ para_node_tree: Optional[List[ParaNode]] = [] # 标题段落层级树,当ParserConfig.return_para_node_tree为True时有内容 page_contents: Optional[List[PageContent]] = [] # 页面的解析内容,详细内容参考base.py中的PageContent类 pdf_data: Optional[str] = "" # pdf格式数据, 当ParserConfig.convert_file_to_pdf为True时有内容 raw: Optional[Dict] = {} # 云端服务的原始解析结果 class ParaNode(BaseModel): """ 文档内容层级树结构 """ node_id: int # 标题段落层级树的节点id text: str # 节点文本 para_type: str # 节点类型,包括:title、text、table parent: Optional[int] # 父节点id,文本的父节点是标题,标题的父节点是更高一级的标题 children: List[int] # 子节点id列表,标题节点才会有子节点 position: List[Position] # 节点位置信息,包括:页码和在对应页面的位置坐标 table: Optional[Table] = None # 节点类型为table时,包含表格解析结果 class PageContent(BaseModel): """ 单页文档内容结构 """ page_num: int # 页码 page_width: int # 页面宽度 page_height: int # 页面高度 page_angle: int # 页面旋转角度 page_type: str # 页面类型 page_layouts: List[Layout] # 页面版式信息 titles: Optional[List[Layout]] = [] # 页面标题信息 tables: Optional[List[Table]] = [] # 页面表格信息 class Layout(BaseModel): """ layout结构 """ type: str # 布局类型 text: str # 布局文本 box: List[int] # 布局位置信息,包括:左上角x、y坐标和宽高 node_id: int # 布局在标题层级树中的节点id class Table(BaseModel): """ 表格结构 """ box: List[int] # 表格位置信息,包括:左上角x、y坐标和宽高 cells: List[Layout] = Field(alias="children") # 表格单元格信息,列表形式 matrix: List[List[int]] # 表格单元格矩阵,用来描述单元格的空间位置信息 node_id: int # 表格在标题层级树中的节点id ``` 表格解析结构说明, 以下图为例: ![表格](https://bj.bcebos.com/v1/appbuilder-sdk-components/table.png?authorization=bce-auth-v1%2FALTAKGa8m4qCUasgoljdEDAzLm%2F2024-05-30T03%3A09%3A32Z%2F-1%2Fhost%2Fb36695708e047713b5fe17b49733228aecdaf46322a5cec8d4e7bd0989032197) ```python # cells中一共有26个元素,matrix中的每一个元素代表单元格在cells中的索引 cells = [{"box": [90, 376, 21, 10], "type": "cell", "text": "序号", "node_id": 1}, ...] matrix = [ [0, 1, 2, 3], [4, 5, 6, 7], [8, 9, 10, 11], [12, 13, 14, 15], [16, 17, 18, 19], [20, 21, 22, 23], [24, 24, 25, 26] ] ``` ## 更新记录和贡献 * 文档解析能力 (2023-12) ================================================ FILE: python/core/components/doc_parser/__init__.py ================================================ # Copyright (c) 2023 Baidu, Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. ================================================ FILE: python/core/components/doc_parser/base.py ================================================ # Copyright (c) 2023 Baidu, Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # -*- coding: utf-8 -*- """ 文档解析 """ from typing import List, Optional, Dict from pydantic import BaseModel, Field # 定义Parser解析结果的结构 class Position(BaseModel): """ position结构 """ page_num: int = Field(alias="pageno") box: List[int] class Layout(BaseModel): """ layout结构 """ type: str text: str box: List[int] node_id: int class Table(BaseModel): """ 表格结构 """ box: List[int] cells: List[Layout] = Field(alias="children") matrix: List[List[int]] node_id: int class ParaNode(BaseModel): """ 文档内容层级树结构 """ node_id: int text: str para_type: str parent: Optional[int] children: List[int] position: List[Position] table: Optional[Table] = None class PageContent(BaseModel): """ 单页文档内容结构 """ page_num: int page_width: int page_height: int page_angle: int page_type: str page_layouts: List[Layout] titles: Optional[List[Layout]] = [] tables: Optional[List[Table]] = [] class ParseResult(BaseModel): """ 解析结果整体结构 """ para_node_tree: Optional[List[ParaNode]] = [] page_contents: Optional[List[PageContent]] = [] pdf_data: Optional[str] = "" raw: Optional[Dict] = {} class ParserConfig(BaseModel): """ DocParser解析配置 """ convert_file_to_pdf: bool = Field(alias="need_pdffile_data", default=False) page_filter: List[int] = Field(alias="page_filter", default=None) return_para_node_tree: bool = Field(alias="return_para_nodes", default=True) erase_watermark: bool = Field(alias="erase_watermark", default=False) # 文档内容切分结构 class DocSegment(BaseModel): """ 自定义文档内容切分的结构 """ content: Optional[str] = "" title: Optional[List[str]] = [] ================================================ FILE: python/core/components/doc_parser/component.py ================================================ # Copyright (c) 2023 Baidu, Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # -*- coding: utf-8 -*- """ 文档解析 """ import os import json import base64 from typing import Dict, Any import tempfile from urllib.parse import urlparse import requests from appbuilder.core._exception import AppBuilderServerException, InvalidRequestArgumentError from appbuilder.core.component import Component, Message from appbuilder.utils.logger_util import logger from appbuilder.core._client import HTTPClient from appbuilder.core.components.doc_parser.base import ParserConfig, ParseResult from appbuilder.utils.trace.tracer_wrapper import ( components_run_trace, components_run_stream_trace ) class DocParser(Component): """ 文档解析组件,用于对文档的内容进行解析。 Examples: .. code-block:: python import appbuilder os.environ["APPBUILDER_TOKEN"] = '...' file_path = "./test.pdf" # 待解析的文件路径 msg = Message(file_path) parser = appbuilder.DocParser() parse_result = parser(msg) """ name: str = "doc_parser" tool_desc: Dict[str, Any] = {"description": "parse document content"} base_url: str = "/v1/bce/xmind/parser" config: ParserConfig = ParserConfig() manifests = [ { "name": "doc_parser", "description": "提供文档解析功能,支持PDF、Word、Excel、PPT等文档的解析", "parameters": { "type": "object", "properties": { "file_names": { "type": "array", "description": "用户上传的文档的文件名,包含文件后缀,用于判断文件类型" } }, "required": ["file_names"] } } ] def set_config(self, config: ParserConfig): """ 设置解析配置 Args: config (ParserConfig): 解析配置对象 Returns: None """ self.config = config def make_parse_result(self, response: Dict): """ 将解析结果的内容转化成ParseResult的结构 Args: response (Dict): 解析后的响应字典,包含文件内容、目录等信息 Returns: Dict: 转换后的ParseResult结构,包含段落节点树、页面内容和PDF数据 """ para_nodes = ( response["para_nodes"] if response["para_nodes"] is not None else [] ) catalog = response["catalog"] if response["catalog"] is not None else [] pdf_data = response["pdf_data"] title_node_ids = [title["node_id"] for title in catalog] if catalog else [] page_contents = [] for content in response["file_content"]: page_content = { "page_num": content["page_num"], "page_width": int(content["page_size"]["width"]), "page_height": int(content["page_size"]["height"]), "page_angle": int(content["page_angle"]), "page_type": content["page_content"]["type"], "page_layouts": [], "page_titles": [], "page_tables": [], } for layout_item in content["page_content"]["layout"]: if layout_item["node_id"] in title_node_ids: continue if layout_item["type"] == "table": page_content["page_tables"].append(layout_item) if para_nodes: para_nodes[layout_item["node_id"]]["table"] = layout_item table_row = [] for i in range(len(layout_item["matrix"])): cell_index = layout_item["matrix"][i] row_markdown = ( "|" + "|".join( [ layout_item["children"][index]["text"] for index in set(cell_index) ] ) + "|" ) if i != len(layout_item["matrix"]) - 1: row_markdown += "\n" table_row.append(row_markdown) para_nodes[layout_item["node_id"]]["text"] = "".join(table_row) else: page_content["page_layouts"].append(layout_item) page_contents.append(page_content) for title in catalog: page_num = title["position"][0]["pageno"] page_contents[page_num]["page_titles"].append( { "text": title["text"], "type": title["level"], "box": title["position"][0]["box"], "node_id": title["node_id"], } ) parse_result = { "para_node_tree": para_nodes, "page_contents": page_contents, "pdf_data": pdf_data, } # parse_result = ParseResult.parse_obj(parse_result) return parse_result @HTTPClient.check_param @components_run_trace def run(self, input_message: Message, return_raw=False) -> Message: """ 对传入的文件进行解析 Args: input_message (Message[str]): 输入为文件的路径 return_raw (bool, optional): 是否返回云端服务的原始结果。默认为False。 Returns: Message[ParseResult]: 文件的解析结果。 Raises: ValueError: 如果传入的文件路径不是字符串类型。 AppBuilderServerException: 如果文件解析过程中出现异常,将抛出该异常。 """ file_path = input_message.content if not isinstance(file_path, str): raise ValueError("file_path should be str type") with open(file_path, "rb") as f: param = self.config.dict(by_alias=True) param["data"] = base64.b64encode(f.read()).decode() param["name"] = os.path.basename(file_path) payload = json.dumps({"file_list": [param]}) headers = self.http_client.auth_header() headers["Content-Type"] = "application/json" response = self.http_client.session.post( url=self.http_client.service_url(self.base_url), headers=headers, data=payload, ) self.http_client.check_response_header(response) self.http_client.check_response_json(response.json()) request_id = self.http_client.response_request_id(response) response = response.json() if response["error_code"] != 0: logger.error( "doc parser service log_id {} err {}".format( response["log_id"], response["error_msg"] ) ) raise AppBuilderServerException( request_id=request_id, service_err_code=response["error_code"], service_err_message=response["error_msg"], ) parse_result = self.make_parse_result(response["result"]["result_list"][0]) if return_raw: parse_result["raw"] = response parse_result = ParseResult.parse_obj(parse_result) return Message(parse_result) @components_run_stream_trace def tool_eval(self, streaming: bool = False, **kwargs): """ tool eval """ return_raw = kwargs.get("return_raw", False) file_names = kwargs.get("file_names", []) if not file_names: raise ValueError("缺少file_names参数") file_name = file_names[0] file_urls = kwargs.get("file_urls", {}) if len(file_urls) == 0: raise ValueError("file_urls is empty") file_url = file_name if file_name.startswith("http") else file_urls.get(file_name, "") with tempfile.TemporaryDirectory() as tmp_dir: local_filename = os.path.join(tmp_dir, os.path.basename(urlparse(file_url).path)) # 下载文件 with requests.get(file_url, stream=True) as r: r.raise_for_status() with open(local_filename, 'wb') as f: for chunk in r.iter_content(chunk_size=8192): if chunk: f.write(chunk) input_message = Message(content=local_filename) parse_result = self.run(input_message, return_raw) result = json.dumps(parse_result.content.model_dump(), ensure_ascii=False) if streaming: yield result else: return result ================================================ FILE: python/core/components/doc_splitter/README.md ================================================ # 文档切分(DocSplitter) ## 简介 文档切分组件(DocSplitter)可以用于对文档进行段落切分。 ### 功能介绍 对解析后的文档,支持将文档划分为多个段落,便于后续处理和分析。 目前支持的文档切分类型splitter_type如下: * split_by_chunk:按照最大段落大小,对文档进行切分 * split_by_title:按照文档的title标识层级进行段落切分 ### 特色优势 组件对文档分隔段落,准确高效,且有多种可选策略,代码简单可快速上手,是后续大模型使用文档信息的基础。 ### 应用场景 对解析后的各类型文档进行分段,用于后续任务的输入。 ## 基本用法 --- 参考tests目录下的[test_doc_splitter.py](https://github.com/baidubce/app-builder/blob/master/appbuilder/tests/test_doc_splitter.py),可快速搭建自己的文档切分用例。 以下是DocSplitter快速开始的一个示例。 #### DocSplitter示例: ```python import os import requests from appbuilder import DocParser from appbuilder import DocSplitter from appbuilder.core.message import Message # 请前往千帆AppBuilder官网创建密钥,流程详见:https://cloud.baidu.com/doc/AppBuilder/s/Olq6grrt6#1%E3%80%81%E5%88%9B%E5%BB%BA%E5%AF%86%E9%92%A5 os.environ["APPBUILDER_TOKEN"] = "..." # 先解析 file_url = "https://agi-dev-platform-bos.bj.bcebos.com/ut_appbuilder/test.pdf?authorization=bce-auth-v1/e464e6f951124fdbb2410c590ef9ed2f/2024-01-25T12%3A56%3A15Z/-1/host/b54178fea9be115eafa2a8589aeadfcfaeba20d726f434f871741d4a6cb0c70d" file_data = requests.get(file_url).content file_path = "./test.pdf" with open(file_path, "wb") as f: f.write(file_data) msg = Message(file_path) parser = DocParser() parse_result = parser(msg, return_raw=True) # 基于parser的结果切分段落 splitter = DocSplitter(splitter_type="split_by_chunk") res_paras = splitter(parse_result) # 打印结果 print(res_paras.content) ``` ## 参数说明 ### 鉴权说明 使用组件之前,请首先申请并设置鉴权参数,可参考[组件使用流程](https://cloud.baidu.com/doc/AppBuilder/s/Olq6grrt6#1%E3%80%81%E5%88%9B%E5%BB%BA%E5%AF%86%E9%92%A5)。 ```python # 设置环境中的TOKEN,以下示例略 os.environ["APPBUILDER_TOKEN"] = "bce-YOURTOKEN" ``` ### 初始化参数 `splitter_type`(str): 切分器的类型,支持`split_by_chunk`和`split_by_title`两种方式,必选参数 ### 调用参数 * `message`(Message): 上游`docparser`的文档解析结果 * 备注: 文档解析时,`parser(msg, return_raw=True)`函数的参数`return_raw`必须为`True` |参数名称 |参数类型 |是否必须 |描述 | 示例值 | |--------|--------|--------|----|--------| |splitter_type |String |是 |文本提取器类型, 目前支持`split_by_chunk`, `split_by_title`| DocSplitter(splitter_type="split_by_chunk") | ### 响应参数 |参数名称 | 参数类型 |描述 | 示例值 | |--------|------|----|----------------| |res_paras |Message |返回结果| [{段落1}, {段落2}] | ### 响应示例 ``` Message(name=msg, content={'paragraphs': [{'text': '第十节其他重要事项'}]}) ``` ### 错误码 无 ## DocSplitter高级用法 #### 示例: ```python import os import requests from appbuilder import DocParser from appbuilder import DocSplitter from appbuilder.core.message import Message # 请前往千帆AppBuilder官网创建密钥,流程详见:https://cloud.baidu.com/doc/AppBuilder/s/Olq6grrt6#1%E3%80%81%E5%88%9B%E5%BB%BA%E5%AF%86%E9%92%A5 os.environ["APPBUILDER_TOKEN"] = "..." # 先解析 file_url = "https://agi-dev-platform-bos.bj.bcebos.com/ut_appbuilder/test.pdf?authorization=bce-auth-v1/e464e6f951124fdbb2410c590ef9ed2f/2024-01-25T12%3A56%3A15Z/-1/host/b54178fea9be115eafa2a8589aeadfcfaeba20d726f434f871741d4a6cb0c70d" file_data = requests.get(file_url).content file_path = "./test.pdf" with open(file_path, "wb") as f: f.write(file_data) msg = Message(file_path) parser = DocParser() parse_result = parser(msg, return_raw=True) # 基于parser的结果切分段落 doc_splitter = DocSplitter(splitter_type="split_by_chunk", separators=["。", "!", "?", ".", "!", "?", "……", "|\n"], max_segment_length=800, overlap=0) res_paras = doc_splitter(parse_result) # 打印结果 print(res_paras.content) ``` ## 参数说明: ### 鉴权配置 使用组件之前,请首先申请并设置鉴权参数,可参考[组件使用流程](https://cloud.baidu.com/doc/AppBuilder/s/Olq6grrt6#1%E3%80%81%E5%88%9B%E5%BB%BA%E5%AF%86%E9%92%A5)。 ```python # 设置环境中的TOKEN,以下示例略 os.environ["APPBUILDER_TOKEN"] = "bce-YOURTOKEN" ``` ### 调用参数 * `message`(Message): 上游`docparser`的文档解析结果 * 备注: 文档解析时,`parser(msg, return_raw=True)`函数的参数`return_raw`必须为`True` * 备注: `splitter_type`为`split_by_title`时,`max_segment_length`, `separators`, `overlap`, `join_symbol`参数不起作用 |参数名称 | 参数类型 | 是否必须 |描述 | 示例值 | |--------|---------|------|----|-------| |splitter_type | String | 是 |文本提取器类型, 目前支持`split_by_chunk`, `split_by_title`| DocSplitter(splitter_type="split_by_chunk") | |max_segment_length| Integer | 否 |切分时段落的最大长度| 800 | |separators| List | 否 |固定字数时,段落最后截断的分隔符| ["。", "!", "?", ".", "!", "?", "……", "|\n"] | |overlap| Integer | 否 |分隔的段落间重叠的内容字数| 200 | |join_symbol| String | 否 |组成固定字数段落时,文本块段落间的链接符| 空字符 | ### 响应参数 |参数名称 | 参数类型 |描述 | 示例值 | |--------|------|----|----------------| |res_paras |Message |返回结果| [{段落1}, {段落2}] | ### 响应示例 ``` Message(name=msg, content={'paragraphs': [{'text': '第十节其他重要事项'}]}) ``` ## 更新记录和贡献 * 文档分隔 (2023-12) ================================================ FILE: python/core/components/doc_splitter/__init__.py ================================================ ================================================ FILE: python/core/components/doc_splitter/component.py ================================================ # Copyright (c) 2023 Baidu, Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # -*- coding: utf-8 -*- """ 对文档进行段落切分 """ import os from typing import Dict, Any from appbuilder.core._exception import AppBuilderServerException from appbuilder.core.components.doc_parser.base import ParseResult from appbuilder.core.component import Component, Message, ComponentArguments from appbuilder.core.components.doc_parser.base import DocSegment from appbuilder.utils.trace.tracer_wrapper import components_run_trace, components_run_stream_trace class DocSplitter(Component): """ 文档段落切分组件 Attributes: name (str): 组件名称。 meta (ComponentArguments): 组件元数据。 """ name: str = "doc_to_parapraphs" meta: ComponentArguments = ComponentArguments(tool_desc={ "description": "split data to segments in doc", }) def __init__(self, splitter_type, max_segment_length=800, overlap=200, separators=["。", "!", "?", ".", "!", "?", "……", "|\n"], join_symbol="", **kwargs): """ 文档段落切分实例化 Args: splitter_type (str): 切分器的类型,目前支持split_by_chunk和split_by_title,为split_by_title时,后续参数无效 max_segment_length (int, optional): 切分后每个段落的最大长度,默认为800。 overlap (int, optional): 每个段落和其前后相邻块,首尾重叠两部分的长度,默认为200。 separators (list, optional): 段落按照最大字符数切分时,字符数超限时,边界用分隔符截断,默认为["。", "!", "?", ".", "!", "?", "……"]。 join_symbol (str, optional): 文本块拼接时,作为连接符的字符,默认为""。 **kwargs (Any, optional): 关键字参数。 Returns: 无 """ self.splitter_type = splitter_type self.max_segment_length = max_segment_length self.overlap = overlap self.separators = separators self.join_symbol = join_symbol super(DocSplitter, self). __init__(meta=self.meta, **kwargs) @components_run_trace def run(self, message: Message): """ 运行函数,根据splitter_type将文档分割成多个部分 Args: message (Message): 包含文档内容的消息对象 Returns: list: 分割后的文档列表 Raises: ValueError: 如果message.content不是ParseResult类型,抛出异常 ValueError: 如果splitter_type为空,抛出异常 ValueError: 如果ParseResult不包含原始值,抛出异常 ValueError: 如果splitter_type不是split_by_chunk或split_by_title,抛出异常 """ parse_result = message.content if not isinstance(parse_result, ParseResult): raise ValueError("message.content type must be a ParseResult") if not self.splitter_type: raise ValueError("splitter_type must be a value") if not parse_result.raw: raise ValueError("The exceptional purpose:Z to determine whether the ParseResult contains a raw value.\n" "The current value: maybe the value of return_raw is False.\n" "The expected value: the value of return_raw is True.") if self.splitter_type == "split_by_chunk": xmind_output = parse_result.raw # 文档原始的解析结果,作为输入,按照块最大长度,分隔文档 chunk_splitter = ChunkSplitter(self.max_segment_length, self.overlap, self.separators, self.join_symbol) result = chunk_splitter(message) return result elif self.splitter_type == "split_by_title": # 文档原始的解析结果,作为输入,按照标题叶子层级,分隔文档 title_splitter = TitleSplitter() result = title_splitter(message) return result else: raise ValueError("splitter_type must be split_by_chunk or split_by_title") class ChunkSplitter(Component): """ 文档按照块大小切分段落 Examples: 原始文档: 贷款资金不得用于从事股本权益性投资,不得用于购买股票、有价证券、期货、理财产品等金融产品。 不得用于从事房地产经营,不得用于借贷牟取非法收入。不得用于个人或其控制的企业生产经营。 不得套取现金。不得用于其他违反国家法律、政策规定的领域,不得用于监管机构禁止银行贷款进入的领域。 切分结果: ["贷款资金不得用于从事股本权益性投资,不得用于购买股票、有价证券、期货、理财产品等金融产品。不得用于从事房地产经营, 不得用于借贷牟取非法收入。不得用于个", "不得用于个人或其控制的企业生产经营。不得套取现金。不得用于其他违反国家法律、政策规定的领域, 不得用于监管机构禁止银行贷款进入的领域。"] """ name: str = "doc_to_chunk" meta: ComponentArguments = ComponentArguments(tool_desc={ "description": "split data to chunks with max size in doc", }) def __init__(self, max_segment_length=800, overlap=200, separators=["。", "!", "?", ".", "!", "?", "……", "|\n"], join_symbol="", **kwargs): """ 文档段落切分实例化 Args: max_segment_length (int, optional): 切分后每个段落的最大长度,默认为800。 overlap (int, optional): 每个段落和其前后相邻块,首尾重叠两部分的长度,默认为200。 separators (list of str, optional): 按照段落最大字符数切分超限时,边界用分隔符截断,默认为["。", "!", "?", ".", "!", "?", "……", "|\n"]。 join_symbol (str, optional): 文本块拼接时,作为连接符的字符,默认为""。 **kwargs (Any, optional): 关键字参数。 Returns: None """ self.base_url = kwargs.get( "base_url", "/rpc/2.0/cloud_hub/v1/ai_engine/copilot_engine/v1/api/doc_search_tools/xmind_paragraph_splitter") kwargs.pop("base_url", "") self.max_segment_length = max_segment_length self.overlap = overlap self.separators = separators self.join_symbol = join_symbol super(ChunkSplitter, self). __init__(meta=self.meta, **kwargs) @components_run_trace def run(self, message: Message): """ 对输入的解析文档结果,按照最大段落块大小、结尾分隔符等,处理为多个段落结果 Args: message (obj:Message): 上游docparser的文档解析结果 Returns: obj:Message: 文档分隔后的段落结果 Raises: ValueError: 如果 message.content 的类型不是 ParseResult,则抛出 ValueError 异常 Examples: .. code-block:: python import os from appbuilder import DocParser from appbuilder.core.components.doc_splitter.component import DocSplitter, ChunkSplitter from appbuilder.core.message import Message # 请前往千帆AppBuilder官网创建密钥,流程详见:https://cloud.baidu.com/doc/AppBuilder/s/Olq6grrt6#1%E3%80%81%E5%88%9B%E5%BB%BA%E5%AF%86%E9%92%A5 os.environ["APPBUILDER_TOKEN"] = "..." # 先解析 msg = Message("./test.pdf") parser = DocParser() parse_result = parser(msg, return_raw=True) # 基于parser的结果切分段落 splitter = ChunkSplitter() res_paras = splitter(parse_result) # 打印结果 print(res_paras.content) """ paser_res = message.content if not isinstance(paser_res, ParseResult): raise ValueError("message.content type must be a ParseResult") headers = self.http_client.auth_header() headers["Content-Type"] = "application/json" chunk_splitter_remote_params = {"xmind_res": paser_res.raw, "max_segment_length": self.max_segment_length, "overlap": self.overlap, "separators": self.separators, "join_symbol": self.join_symbol} response = self.http_client.session.post(url=self.http_client.service_url(prefix=self.base_url, sub_path=""), headers=headers, json=chunk_splitter_remote_params, stream=False) self.http_client.check_response_header(response) self.http_client.check_response_json(response.json()) doc_chunk_splitter_res = response.json() return Message(doc_chunk_splitter_res["result"]) class TitleSplitter(Component): """ 文档按照标题层级切分段落 Examples: 原始文档: 一、简介 叠贷业务是指借款人家庭为满足购房、购车、装修、教育、医疗、旅游、日常消费等符合国家法律法规规定的消费用途。 二、申请条件 (一)基本条件 1、年满18周岁的自然人,具有完全民事行为能力,能提供有效身份证明或居留证明; 2、有稳定职业和收入,有偿还贷款本息的能力; (二)抵押房产所有人的要求 1、抵押房产的所有人应为借款人本人 2、抵押房产如有共同所有人,借款人必须为之一,且其他共同所有人必须同意以该房产办理最高额抵押登记,并提供同意抵押的合法有效的书面文件。 切分结果: ["一、简介 叠贷业务是指借款人家庭为满足购房、购车、装修、教育、医疗、旅游、日常消费等符合国家法律法规规定的消费用途。", "二、申请条件 (一)基本条件 1、年满18周岁的自然人,具有完全民事行为能力,能提供有效身份证明或居留证明; 2、有稳定职业和收入, 有偿还贷款本息的能力;", "二、申请条件 (二)抵押房产所有人的要求 1、抵押房产的所有人应为借款人本人。 2、抵押房产如有共同所有人,借款人必须为之一, 且其他共同所有人必须同意以该房产办理最高额抵押登记,并提供同意抵押的合法有效的书面文件。"】 """ name: str = "doc_to_title_level" tool_desc: Dict[str, Any] = {"description": "split document content by titles"} def _get_title(self, nodes, parent_id, titles): """ 获取段落各层级的标题 参数: nodes: 文档的节点树 parent_id: 当前节点的父节点 titles: 当前节点的标题, 递归过程中,记录各层级的标题 返回: titles: 当前节点的标题 """ def inner_get_titles(nodes, parent_id, titles): if parent_id: titles.append(nodes[parent_id].text) inner_get_titles(nodes, nodes[parent_id].parent, titles) inner_get_titles(nodes, parent_id, titles) return titles[::-1] # 按照标题层级进行切分 @components_run_trace def run(self, input_message: Message) -> Message: """ 对输入的解析文档结果,按照各标题层级,处理为多个段落结果 Args: input_message (obj:Message): 上游docparser的文档解析结果 Returns: obj:Message: 文档分隔后的段落结果 Raises: ValueError: 如果message.content的类型不是ParseResult,则抛出异常 Examples: .. code-block:: python import os from appbuilder.core.components.doc_parser.doc_parser import DocParser from appbuilder.core.components.doc_splitter.doc_splitter import DocSplitter, TitleSplitter from appbuilder.core.message import Message # 请前往千帆AppBuilder官网创建密钥,流程详见:https://cloud.baidu.com/doc/AppBuilder/s/Olq6grrt6#1%E3%80%81%E5%88%9B%E5%BB%BA%E5%AF%86%E9%92%A5 os.environ["APPBUILDER_TOKEN"] = "..." # 先解析 msg = Message("./title_splitter.docx") parser = DocParser() parse_result = parser(msg, return_raw=True) # 基于parser的结果切分段落 splitter = TitleSplitter() res_paras = splitter(parse_result) # 打印结果 print(res_paras.content) """ parse_result = input_message.content if not isinstance(parse_result, ParseResult): raise ValueError("message.content type must be a ParseResult") para_node_tree = parse_result.para_node_tree doc_segments = [] paragraphs = [] segment = DocSegment() for i in range(1, len(para_node_tree)): node = para_node_tree[i] # 去掉页眉页脚 if node.para_type == "head_tail": continue if node.para_type[:5] != "title": segment.content += " " + node.text # 下一个node是title或当前node是最后一个node,代表当前的标题层级segment结束 if i < len(para_node_tree) - 1 and para_node_tree[i + 1].para_type[:5] == "title" or i == len( para_node_tree) - 1: segment.title = self._get_title(para_node_tree, node.parent, []) doc_segments.append(segment) paragraphs_text = " ".join(segment.title) + " " + segment.content paragraphs.append({"text": paragraphs_text, "node_id": i}) segment = DocSegment() if segment.content: segment.title = self._get_title(para_node_tree, node.parent, []) doc_segments.append(segment) paragraphs_text = " ".join(segment.title) + " " + segment.content paragraphs.append({"text": paragraphs_text, "node_id": i}) return Message({"doc_segments": doc_segments, "paragraphs": paragraphs}) ================================================ FILE: python/core/components/document_understanding/README.md ================================================ # 长文档内容理解(DocumentUnderstanding) ## 简介 长文档内容理解组件(DocumentUnderstanding)支持对图片以及文档内容进行理解,并基于图片以及文档内容对用户的提问进行回答, 包括但不限于文档内容问答、总结摘要、内容分析。 ### 功能介绍 根据用户上传的文档(支持txt、docx、pdf、xlsx、png、jpg、jpeg等多种格式)、query、指令生成大模型答案 ### 特色优势 处理长上下文的大模型内容理解任务 ### 应用场景 长上下文的文档问答 ## 基本用法 ### 快速开始 ```python import os import appbuilder # 请前往千帆AppBuilder官网创建密钥,流程详见:https://cloud.baidu.com/doc/AppBuilder/s/Olq6grrt6#1%E3%80%81%E5%88%9B%E5%BB%BA%E5%AF%86%E9%92%A5 APPBUILDER_TOKEN = "YOUR-TOKEN" os.environ["APPBUILDER_TOKEN"] = APPBUILDER_TOKEN du = appbuilder.DocumentUnderstanding() query = appbuilder.Message("这篇文档讲了什么") instruction = "请根据文档内容回答问题,用一句话简短概括" addition_instruction = "用一句话简短概括" ##用户增强指令,可选填,该内容会进一步增强大模型的指令跟随能力,将你最需要增强效果的指令填于此,内容可以与上述的"instruction"基础指令有重复,注意:该字段内容过多会一定程度影响大模型内容严谨度,请注意控制该字段的指令字数 app_id = "YOUR-APP-ID" ##你需要在系统上自己的账号下(https://qianfan.cloud.baidu.com/appbuilder)创建任意空Agent,并获取该Agent的app_id(即界面上的应用ID,在首页->个人空间->应用 里面即会显示应用ID),这里任意空Agent就可以,无需任何配置信息,这个agent的作用只是为了获取app_id信息 file_path = "YOUR-FILE-PATH" ##填写你的本地待分析文件路径 stream = False ##是否开启流式输出功能 response_ = du.run(query, file_path, instruction=instruction, addition_instruction=addition_instruction, app_id=app_id, stream=stream) for result in response_: print(result) ##打印输出的大模型答案 ``` ## 参数说明 ### 鉴权说明 使用组件之前,请首先申请并设置鉴权参数,可参考[组件使用流程](https://cloud.baidu.com/doc/AppBuilder/s/Olq6grrt6#1%E3%80%81%E5%88%9B%E5%BB%BA%E5%AF%86%E9%92%A5)。 ```python # 设置环境中的TOKEN,以下示例略 import os os.environ['APPBUILDER_TOKEN'] = 'bce-YOURTOKEN' ``` ### 初始化参数 | 参数名称 | 参数类型 | 是否必须 | 描述 | 示例值 | | ------- | ------- | -------- | -------- | -------- | | `secret_key` | str | 否 | 用户鉴权token,默认从环境变量中获取: `os.getenv("APPBUILDER_TOKEN", "")` | bce-v3/XXX | | `gateway` | str | 否 | 后端网关服务地址,默认从环境变量中获取: `os.getenv("GATEWAY_URL", "")` | https://appbuilder.baidu.com | | `lazy_certification` | bool | 否 | 延迟认证,为True时在第一次运行时认证。默认为False。 | False | ### 调用参数 | 参数名称 | 参数类型 | 是否必须 | 描述 | 示例值 | |------------------------|------|------|--------------------------------------------------------------------------|-----------------------------| | `message` | obj | 是 | 输入消息,用户输入query。 | Message(content=input_data) | | `file_path` | str | 是 | 用户需要分析的文档 | "test.pdf" | | `app_id` | str | 是 | 你需要在系统上自己的账号下(https://qianfan.cloud.baidu.com/appbuilder)创建任意空Agent,并获取该Agent的app_id(即界面上的应用ID,在首页->个人空间->应用 里面即会显示应用ID),这里任意空Agent就可以,无需任何配置信息,这个agent的作用只是为了获取app_id信息 | "YOUR-APP-ID" | | `instruction` | str | 否 | 用户指令 | "你的回答要严谨客观,且答案一定要分点阐述" | | `addition_instruction` | str | 否 | 用户增强指令,可选填,该内容会进一步增强大模型的指令跟随能力,将你最需要增强效果的指令填于此,注意:该字段内容过多会一定程度影响大模型内容严谨度 | "你的答案需要分点阐述" | ### 响应参数 | 参数名称 | 参数类型 | 描述 | 示例值 | | ------- |------| -------- | -------- | | `result` | str | 模型运行后的输出结果 | "" | ### 响应示例-流式输出 ``` data: {"type": "text", "text": "文件解析完成, 耗时13485.63ms\n\n"} request_id: f99a7230-649f-4170-ade7-62d8368a18e6 data: {"type": "text", "text": "**Human", "event_status": "running"} request_id: f99a7230-649f-4170-ade7-62d8368a18e6 data: {"type": "text", "text": "-Timescale Adaptation in an Open-Ended Task Space** 文档详细介绍了DeepMind团队开发的自适应代理(Adaptive Agent,简称", "event_status": "running"} request_id: f99a7230-649f-4170-ade7-62d8368a18e6 data: {"type": "text", "text": "AdA)在开放任务空间中的快速适应能力。", "event_status": "running"} request_id: f99a7230-649f-4170-ade7-62d8368a18e6 data: {"type": "text", "text": "", "event_status": "done"} request_id: f99a7230-649f-4170-ade7-62d8368a18e6 ``` ### 响应示例-非流式输出 ``` {'code': 0, 'message': '', 'result': {'text': '文件解析完成, 耗时14572.57ms\n\n**Human-Timescale Adaptation in an Open-Ended Task Space** 文档详细介绍了DeepMind团队开发的自适应代理(Adaptive Agent,简称AdA)在开放任务空间中的快速适应能力。以下是文档的主要内容和贡献点:\n\n1. **引言**:\n - 强调了快速适应能力对于人工智能的重要性,特别是在现实世界中的应用和与人类互动的场景中。\n - 提出了通过元强化学习(meta-RL)和自动课程学习(auto-curriculum learning)等方法,训练能够在未见过的环境中快速适应的代理。\n\n2. **自适应代理(AdA)**:\n - 介绍了AdA的设计和训练方法,包括其在开放任务空间中的适应行为、记忆架构、以及如何通过自动课程学习来优化训练过程。\n - 展示了AdA能够在几分钟内解决复杂的3D任务,且不需要进一步的代理训练,显示了其快速适应的能力。\n\n3. **实验与结果**:\n - 在多个方面评估了AdA的性能,包括其在单代理和多代理设置下的适应能力、不同架构和课程学习方法的影响、以及模型大小和记忆长度对性能的影响。\n - 通过与人类玩家的比较,证明了AdA在适应速度上与人类相当。\n\n4. **相关工作**:\n - 回顾了与本工作相关的领域,包括程序化环境生成、开放任务学习、适应性和强化学习中的Transformer应用等。\n\n5. **结论**:\n - 总结了AdA的贡献,强调了其在开放任务空间中快速适应的能力,以及通过元强化学习和自动课程学习等方法训练大型模型的可能性。\n\n6. **作者和贡献**:\n - 列出了主要贡献者和部分贡献者,以及项目的赞助商和认可。\n\n**主要贡献点**:\n- 提出了AdA,一个能够在开放任务空间中快速适应的代理,其适应速度与人类相当。\n- 通过元强化学习和自动课程学习等方法,训练了大型Transformer模型,展示了其在开放任务空间中的快速适应能力。\n- 分析了不同架构、课程学习方法、模型大小和记忆长度对AdA性能的影响,提供了详细的实验结果和比较。\n- 通过与人类玩家的比较,证明了AdA在适应速度上的优势。'}, 'request_id': '687642b0-b877-49ed-9ad9-65d76de0ea58'} ``` ## 高级用法 ## 更新记录和贡献 ### 2024.10. 15 #### [Added] - 第一版 ================================================ FILE: python/core/components/document_understanding/__init__.py ================================================ ================================================ FILE: python/core/components/document_understanding/base.py ================================================ """ Copyright (c) 2023 Baidu, Inc. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. """ from pydantic import Field from appbuilder.core.message import Message from appbuilder.core.component import ComponentArguments class DocumentUnderstandingArgs(ComponentArguments): '''长文档问答配置''' message: Message = Field(..., variable_name="query", description="用户输入query") file_path: str = Field(..., variable_name="file_path", description="用户上传的文件路径") instruction: str = Field(default="", variable_name='instruction', description='用户指令') addition_instruction: str = Field(default="", variable_name='addition_instruction', description='用户增强指令') ================================================ FILE: python/core/components/document_understanding/component.py ================================================ """ Copyright (c) 2023 Baidu, Inc. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. """ import os import requests import json from typing import Optional from appbuilder.core.components.document_understanding.base import DocumentUnderstandingArgs from appbuilder.core.message import Message from appbuilder.core.component import Component import base64 import uuid class DocumentUnderstanding(Component): """ DocumentUnderstanding """ name = "document_understanding" version = "v1" meta = DocumentUnderstandingArgs manifests = [{ "name": "document_understanding", "description": "该工具支持对图片以及文档内容进行理解,并基于图片以及文档内容对用户的提问进行回答,包括但不限于文档内容问答、" "总结摘要、内容分析。", "parameters": { "type": "object", "properties": { "query": { "type": "string", "description": "用户输入的query" }, "file_path": { "type": "string", "description": "用户上传的文档的文件路径" }, "instruction": { "type": "string", "description": "用户指令" }, "addition_instruction": { "type": "string", "description": "用户增强指令" }, "app_id": { "type": "string", "description": "系统应用ID" }, }, "required": ["query", "file_path", "instruction", "addition_instruction", "app_id"] } }] def __init__( self, secret_key: Optional[str] = None, gateway: str = "", lazy_certification: bool = False, instruction: Optional[Message] = None, addition_instruction: Optional[Message] = None, file_path: Optional[str] = None, app_id: Optional[str] = None, **kwargs ): """初始化DocumentUnderstanding组件。 Args: secret_key (str, 可选): 用户鉴权token, 默认从环境变量中获取: os.getenv("APPBUILDER_TOKEN", ""). gateway (str, 可选): 后端网关服务地址,默认从环境变量中获取: os.getenv("GATEWAY_URL", "") lazy_certification (bool, 可选): 延迟认证,为True时在第一次运行时认证. Defaults to False. Returns: None """ super().__init__(DocumentUnderstandingArgs, secret_key=secret_key, gateway=gateway, lazy_certification=lazy_certification) self.instruction = instruction, self.addition_instruction = addition_instruction self.file_path = file_path self.app_id = app_id def get_addition_instruction(self, addition_instruction: str): """拼接addition_instruction""" return ",指令:" + addition_instruction def get_conversation_id(self, app_id: str): url = "https://qianfan.baidubce.com/v2/app/conversation" payload = json.dumps({ "app_id": app_id }) headers = { 'Content-Type': 'application/json', 'X-Appbuilder-Authorization': f"Bearer {os.getenv('APPBUILDER_TOKEN', '')}" } response = self.http_client.session.post(url, headers=headers, data=payload) self.http_client.check_response_header(response) response = requests.request("POST", url, headers=headers, data=payload) return json.loads(response.text).get("conversation_id", None) def get_file_id(self, conversation_id: str, app_id: str, file_path: str): url = "https://qianfan.baidubce.com/v2/app/conversation/file/upload" payload = { 'app_id': app_id, 'conversation_id': conversation_id } files = [ ('file', (os.path.basename(file_path), open(file_path, 'rb'), 'application/{}'.format(file_path.split(".")[-1]))) ] headers = { 'X-Appbuilder-Authorization': f"Bearer {os.getenv('APPBUILDER_TOKEN', '')}" } response = requests.request("POST", url, headers=headers, data=payload, files=files) return json.loads(response.text).get("id", None) def run(self, message: Message, file_path, instruction="", addition_instruction="", app_id="", stream=False, timeout=None): ''' run方法,用于执行长文档理解任务 Args: message: 用户输入query file_path: 用户输入的文件路径 instruction: 用户输入的人设指令 addition_instruction: 用户输入的增强版指令(如有) app_id: 用户输入的app_id Returns: result (Message): 模型运行后的输出消息。 ''' file_name = file_path.split("/")[-1] file_type = file_name.split(".")[-1].lower() request_id = str(uuid.uuid4()) support_file_type = ["pdf", "docx", "xlsx", "png", "jpg", "jpeg", "txt"] if file_type not in support_file_type: raise Exception(f"不支持解析{file_type}类型的文件,当前仅支持解析以下几种文件类型:{support_file_type}") payload = json.dumps({ "stream": stream, "batch": False, "arguments": { "query": message.content, "file_ids":[self.get_file_id(self.get_conversation_id(app_id=app_id), app_id, file_path)], "files": [], "file_urls": {}, "instruction": instruction, "addition_instruction": self.get_addition_instruction(addition_instruction), } }) headers = self.http_client.auth_header() headers['Content-Type'] = 'application/json' headers['Authorization'] = f"Bearer {os.getenv('APPBUILDER_TOKEN', '')}" headers['X-Appbuilder-Request-Id'] = request_id url = self.http_client.service_url_v2("/components/document_understanding/version/preview") response = self.http_client.session.post(url, headers=headers, data=payload, timeout=timeout, stream=stream) self.http_client.check_response_header(response) if response.status_code == 200: if stream: # 处理流式响应,逐行生成数据 for line in response.iter_lines(): if line: decoded_line = line.decode('utf-8') decoded_line = f"{decoded_line} request_id: {request_id}" yield decoded_line # 使用yield逐行输出结果 else: result = response.json() result["request_id"] = request_id if result["code"] == 0: yield result else: raise Exception(f"服务请求失败: {result['message']}") else: response.raise_for_status() def tool_eval(self, message: Message, file_path: str, stream: bool = False, **kwargs): """用于function call """ instruction = kwargs.get("instruction", "") addition_instruction = kwargs.get("addition_instruction", "") app_id = kwargs.get("app_id", "") result = self.run(message, file_path, instruction=instruction, addition_instruction=addition_instruction, app_id=app_id, stream=stream) return result ================================================ FILE: python/core/components/embeddings/README.md ================================================ # 向量计算(Embedding) ## 简介 向量计算组件(Embedding)支持将文本转化为用数值表示的向量形式,用于文本检索、信息推荐、知识挖掘等场景。嵌入(Embedding)是一种在机器学习和自然语言处理中常用的技术,主要用于将大量高维数据(如单词、图像等)转换为更低维的向量表示。这些向量表示捕获了原始数据的关键特征和关系。 ### 功能介绍 1. 维度降低:将高维数据(如词汇表中的单词)映射到低维空间,使得数据处理更高效。 2. 特征学习:学习数据的内在特征,使得具有相似含义的元素在嵌入空间中彼此接近。 3. 关系映射:在嵌入空间中,数据点的距离和方向可以表示元素之间的关系。 ### 特色优势 Embedding-V1,是基于百度文心大模型技术的文本表示模型,在Embedding模块中,我们使用Embedding-V1作为默认模型。 ### 应用场景 1. 文本检索 2. 信息推荐 3. 知识挖掘 ## 基本用法 当前支持的embedding底座模型暂时只包括: - embedding-v1 ### 下面是使用单条字符串测试的代码示例 请注意,您必须确保字符串的token长度小于384 ```python import os import appbuilder # 请前往千帆AppBuilder官网创建密钥,流程详见:https://cloud.baidu.com/doc/AppBuilder/s/Olq6grrt6#1%E3%80%81%E5%88%9B%E5%BB%BA%E5%AF%86%E9%92%A5 os.environ["APPBUILDER_TOKEN"] = '...' embedding = appbuilder.Embedding() out = embedding("hello world!") # 得到一个长度为384的float数组 print(out.content) ``` ### 下面是使用多条字符串测试的代码示例 ```python import os import appbuilder # 请前往千帆AppBuilder官网创建密钥,流程详见:https://cloud.baidu.com/doc/AppBuilder/s/Olq6grrt6#1%E3%80%81%E5%88%9B%E5%BB%BA%E5%AF%86%E9%92%A5 os.environ["APPBUILDER_TOKEN"] = '...' embedding = appbuilder.Embedding() outs = embedding.batch(["hello", "world"]) # 得到一个长度为 2 x 384的float 二维数组 print(out.content) ``` ### 下面是使用上游的Message作为输入的代码示例 ```python import os import appbuilder # 请前往千帆AppBuilder官网创建密钥,流程详见:https://cloud.baidu.com/doc/AppBuilder/s/Olq6grrt6#1%E3%80%81%E5%88%9B%E5%BB%BA%E5%AF%86%E9%92%A5 os.environ["APPBUILDER_TOKEN"] = '...' from appbuilder import Message embedding = appbuilder.Embedding() query = Message("你好,世界!") out = embedding(query) # 得到一个长度为384的float数组 print(out.content) ``` ### 下面是批量运行的代码示例 ```python import os import appbuilder # 请前往千帆AppBuilder官网创建密钥,流程详见:https://cloud.baidu.com/doc/AppBuilder/s/Olq6grrt6#1%E3%80%81%E5%88%9B%E5%BB%BA%E5%AF%86%E9%92%A5 os.environ["APPBUILDER_TOKEN"] = '...' from appbuilder import Message embedding = appbuilder.Embedding() query = Message([ "你好", "世界" ]) outs = embedding.batch(query) # 得到一个长度为 2 x 384的float 二维数组 print(outs.content) ``` ## 参数说明 ### 鉴权说明 使用组件之前,请首先申请并设置鉴权参数,可参考[组件使用流程](https://cloud.baidu.com/doc/AppBuilder/s/Olq6grrt6#1%E3%80%81%E5%88%9B%E5%BB%BA%E5%AF%86%E9%92%A5)。 ```python # 设置环境中的TOKEN,以下示例略 os.environ["APPBUILDER_TOKEN"] = "bce-YOURTOKEN" ``` ### 初始化参数 | 参数名称 | 参数类型 | 是否必须 | 描述 | 示例值 | | -------- | -------- | -------- | ------------------------------------------------------------ | ---------------- | | model | 字符串 | 可选 | 指定底座模型的类型。当前仅支持 embedding-v1 作为可选值。若不指定,默认值为 embedding-v1。 | embedding-v1 | ### 调用参数 #### 单条 | 参数名称 | 参数类型 | 是否必须 | 描述 | 示例值 | | -------- | -------- | -------- | ------------------------------------------------------------ | ---------------- | | text | 字符串 | 必须 | 一个类型为 string 的句子,用于输入。该句子的长度不能超过384个字符,通常为用户的输入。 | "您好,我需要帮助。" | #### 批量 | 参数名称 | 参数类型 | 是否必须 | 描述 | 示例值 | | -------- | --------------- | -------- | ---------------------------------------------------------------- | ------------------------------------ | | texts | 字符串列表 | 必须 | 一个类型为 List[string] 的句子数组。数组中的每个元素都是一个句子,且每个句子的长度不能超过384个字符。通常这些句子为和用户输入相关的文本候选集。 | ["您好,我需要帮助。", "请问有什么可以帮您?"] | ### 响应示例 #### 单条 ``` [0.1, 0.2, 0.3, ....] ``` #### 批量 ``` [ [0.1, 0.2, ...], ..., [0.1, 0.2, ...], ] ``` ### 错误码 无 ## 更新记录和贡献 * embedding-v1 (2023-12) ================================================ FILE: python/core/components/embeddings/__init__.py ================================================ """ init """ from .component import Embedding from .base import EmbeddingBaseComponent ================================================ FILE: python/core/components/embeddings/base.py ================================================ # Copyright (c) 2023 Baidu, Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from abc import abstractmethod from typing import List, Union from appbuilder.core.component import Component from appbuilder.core.message import Message from appbuilder.core.component import ComponentArguments class EmbeddingBaseComponent(Component): """ EmbeddingBaseComponent """ name: str version: str meta: ComponentArguments base_url: str = "" model_type: str = "embeddings" @abstractmethod def run(self, text: Union[Message[str], str]) -> Message[List[float]]: """ Args: message: str Returns: embeddings: List[float] """ async def arun(self, text: Union[Message[str], str]) -> Message[List[float]]: """ Args: message: str Returns: embeddings: List[float] """ # embedding don't need be async, just return it return self.run(text) @abstractmethod def batch(self, texts: Union[Message[List[str]], List[str]]) -> Message[List[List[float]]]: """ Args: message: List[str] Returns: embeddings: List[List[float]] """ def abatch(self, texts: Union[Message[List[str]], List[str]]) -> Message[List[List[float]]]: """ Args: message: List[str] Returns: embeddings: List[List[float]] """ # embedding don't need be async, just return it return self.batch(texts) class EmbeddingArgs(ComponentArguments): """ ernie bot embedding配置 Attributes: text (Union[Message[str], str]): 输入文本 """ text: Union[Message[str], str] ================================================ FILE: python/core/components/embeddings/component.py ================================================ # Copyright (c) 2023 Baidu, Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """ ernie bot embedding """ from typing import Union, List from appbuilder.core.message import Message from appbuilder.core.components.embeddings.base import EmbeddingBaseComponent from appbuilder.core._exception import AppBuilderServerException, ModelNotSupportedException from appbuilder.utils.trace.tracer_wrapper import components_run_trace, components_run_stream_trace from .base import EmbeddingArgs class Embedding(EmbeddingBaseComponent): """ Embedding Embedding-V1是基于百度文心大模型技术的文本表示模型,将文本转化为用数值表示的向量形式,用于文本检索、信息推荐、知识挖掘等场景。 Attributes: model: str = "Embedding-V1" Examples: .. code-block:: python import appbuilder from appbuilder import Message os.environ["APPBUILDER_TOKEN"] = '...' embedding = appbuilder.Embedding() embedding_single = embedding(Message("hello world!")) embedding_batch = embedding.batch(Message(["hello", "world"])) """ name: str = "embedding" version: str = "v1" meta = EmbeddingArgs accepted_models = ["Embedding-V1"] base_urls = { 'Embedding-V1' : "/v1/bce/wenxinworkshop/ai_custom/v1/embeddings/embedding-v1" } def __init__(self, model="Embedding-V1", **kwargs ): """Embedding""" if model not in self.accepted_models: raise ModelNotSupportedException(f"Model {model} not supported, only support {self.accepted_models}") if model in self.base_urls: self.base_url = self.base_urls[model] else: raise ModelNotSupportedException(f"Model {model} is not yet supported, only support {self.base_urls.keys()}") super().__init__(self.meta) def _check_response_json(self, data: dict): """ check_response_json for embedding """ self.http_client.check_response_json(data) if "error_code" in data and "error_msg" in data: raise AppBuilderServerException( service_err_code=data['error_code'], service_err_message=data['error_msg'], ) def _request(self, payload: dict) -> dict: """ request to gateway """ headers = self.http_client.auth_header() headers["Content-Type"] = "application/json" resp = self.http_client.session.post( url=self.http_client.service_url(self.base_url), headers=headers, json=payload, ) self.http_client.check_response_header(resp) self._check_response_json(resp.json()) return resp.json() def _batchify(self, texts: List[str], batch_size: int = 16) -> List[List[str]]: """ batchify input text list """ if batch_size > 16: raise ValueError(f"The max Embedding batch_size is 16, but got {batch_size}") return [ texts[i : i + batch_size] for i in range(0, len(texts), batch_size) ] def _batch(self, texts: List[str]) -> Message[List[List[float]]]: """ batch run implement """ batches = self._batchify(texts) results = [] for batch in batches: result = self._request({"input": batch}) results.extend(result['data']) results = Message([result['embedding'] for result in results]) return results @components_run_trace def run(self, text: Union[Message[str], str]) -> Message[List[float]]: """ 处理给定的文本或消息对象,并返回包含处理结果的消息对象。 Args: text (Union[Message[str], str]): 待处理的文本或消息对象。 Returns: Message[List[float]]: 处理后的结果,封装在消息对象中。结果是一个浮点数列表。 """ _text = text if isinstance(text, str) else text.content return Message(self._batch([_text]).content[0]) def batch(self, texts: Union[Message[List[str]], List[str]]) -> Message[List[List[float]]]: """ 批量处理文本数据。 Args: texts (Union[Message[List[str]], List[str]]): 待处理的文本数据,可以是 Message 类型,包含多个文本列表,也可以是普通列表类型,包含多个文本。 Returns: Message[List[List[float]]]: 处理后的结果,为 Message 类型,包含一个二维浮点数列表,每个子列表对应输入文本列表中一个文本的处理结果。 """ _texts = texts if isinstance(texts, list) else texts.content return self._batch(_texts) ================================================ FILE: python/core/components/extract_table/README.md ================================================ # 表格抽取组件(ExtractTableFromDoc) ## 简介 表格抽取组件(ExtractTableFromDoc)是用于文档表格处理的组件,从文档中抽取表格。支持对文档表格大小进行限制,限制后自动进行拆分、跨页合并等处理;支持合并表格上文,提取的表格为Markdown格式。 ### 功能介绍 从文档中抽取表格。支持对文档表格大小进行限制,限制后自动进行拆分、跨页合并等处理;支持合并表格上文,设置表格上文数量,提取的表格为Markdown格式。 ### 特色优势 组件抽取表格,准确高效,代码简单可快速上手;且不依赖本地计算资源。 ### 适用场景 文档表格解析与处理,用于后续任务的输入。 ## 基本用法 下面是一个基本用法的样例 ```python import os import json import requests from appbuilder.utils.logger_util import logger from appbuilder import Message, ExtractTableFromDoc, DocParser # 请前往千帆AppBuilder官网创建密钥,流程详见:https://cloud.baidu.com/doc/AppBuilder/s/Olq6grrt6#1%E3%80%81%E5%88%9B%E5%BB%BA%E5%AF%86%E9%92%A5 os.environ["APPBUILDER_TOKEN"] = "..." # 进行文档内容解析 file_url = "https://agi-dev-platform-bos.bj.bcebos.com/ut_appbuilder/test.pdf?authorization=bce-auth-v1/e464e6f951124fdbb2410c590ef9ed2f/2024-01-25T12%3A56%3A15Z/-1/host/b54178fea9be115eafa2a8589aeadfcfaeba20d726f434f871741d4a6cb0c70d" file_data = requests.get(file_url).content file_path = "./test.pdf" # 待解析的文件路径 with open(file_path, "wb") as f: f.write(file_data) msg = Message(file_path) parser = DocParser() # ExtractTableFromDoc输入为文档原始解析结果,此处需要带上原始结果,return_raw=True. doc = parser(msg, return_raw=True).content.raw # 抽取文档中的表格 parser = ExtractTableFromDoc() result = parser.run(Message(doc)) logger.info("Tables: {}".format( json.dumps(result.content, ensure_ascii=False)) ) ``` ## 参数说明 ### 鉴权说明 使用组件之前,请首先申请并设置鉴权参数,可参考[组件使用流程](https://cloud.baidu.com/doc/AppBuilder/s/Olq6grrt6#1%E3%80%81%E5%88%9B%E5%BB%BA%E5%AF%86%E9%92%A5)。 ```python # 设置环境中的TOKEN,以下示例略 os.environ["APPBUILDER_TOKEN"] = "bce-YOURTOKEN" ``` ### 初始化参数 无 ### 调用参数 |参数名称 |参数类型 |是否必须 |描述 |示例值| |--------|--------|--------|----|------| |message | Dict |是 | 输入的消息,用于模型的主要输入内容,必须为Docparser解析后的结果raw,需要设置return_raw=True。这是一个必需的参数。| `Message(parser(msg, return_raw=True).content.raw)` | |table_max_size |int |否 |单个表格的长度的最大值(包含上文),按字符数即len(table_str)统计,默认为800。如果表格超长,则会被拆分成多个子表格,拆分的最小粒度为表格的行。若单行就超长,则会强制按table_max_size截断。截断时会优先截断上文,尽量保留表格内容。 | 800 | |doc_node_num_before_table |int |否 |表格前附加的上文DocParser Node的数量,默认为1。范围:1~10。 | 1 | ### 响应参数 |参数名称 |参数类型 |描述 |示例值| |--------|--------|----|------| | - | List | 解析出来的文档表格,如果元素长度为1,则对应原文档中格式化后的长度不超过`table_max_size`的表格;如果元素长度>1,则是对应原文档中一个大表格,该表格被拆分成的多个子表格,以满足设置大小。 | 见响应示例 | ### 错误码 |错误码|描述| |------|---| ### 响应示例 ```json [[{"para": "table1"}], [{"para": "table2-part1"}, {"para": "table2-part2"}]] ``` ## 更新记录和贡献 * 表格抽取能力 (2023-12) ================================================ FILE: python/core/components/extract_table/__init__.py ================================================ # Copyright (c) 2023 Baidu, Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """__init__""" ================================================ FILE: python/core/components/extract_table/component.py ================================================ # Copyright (c) 2023 Baidu, Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # -*- coding: utf-8 -*- """ 文档表格转换 """ import os import json from appbuilder.core.component import Component, Message, ComponentArguments from appbuilder.utils.trace.tracer_wrapper import components_run_trace, components_run_stream_trace class ExtractTableFromDoc(Component): """ 文档表格抽取 Examples: .. code-block:: python import os import json from appbuilder.utils.logger_util import logger from appbuilder import Message, ExtractTableFromDoc, DocParser # 请前往千帆AppBuilder官网创建密钥,流程详见:https://cloud.baidu.com/doc/AppBuilder/s/Olq6grrt6#1%E3%80%81%E5%88%9B%E5%BB%BA%E5%AF%86%E9%92%A5 os.environ["APPBUILDER_TOKEN"] = "..." # 测试文档解析器使用默认配置,xxx为待解析的文档路径。 msg = Message("xxx") parser = DocParser() # ExtractTableFromDoc输入为文档原始解析结果,此处需要带上原始结果,return_raw=True. doc = parser(msg, return_raw=True).content.raw # 抽取文档中的表格 parser = ExtractTableFromDoc() result = parser.run(Message(doc)) logger.info("Tables: {}".format( json.dumps(result.content, ensure_ascii=False))) """ name: str = "extract_table_from_doc" #TODO: 隐藏base_url,@tangwei12统一修改 base_url = "/rpc/2.0/cloud_hub/v1/ai_engine/copilot_engine/v1/api/doc_search_tools/doc_table_to_markdown_parser" meta: ComponentArguments = ComponentArguments(tool_desc={ "description": "Extract table from doc, table format is markdown", }) def _input_check(self, message: Message, table_max_size, doc_node_num_before_table): """ para_check """ if table_max_size < 30: raise ValueError("table_max_size mismached, expected table_max_size >= 30, got {}".format(table_max_size)) if doc_node_num_before_table < 1 or doc_node_num_before_table > 10: raise ValueError("doc_node_num_before_table mismatched, expected [1, 10], got {}".format(doc_node_num_before_table)) obj = message.content.get("result", {}).get("result_list", []) if len(obj) < 1: raise ValueError("Input check failed, expected raw_doc_parser output.") def _post_process(self, resp): """ pass """ resp = resp["result"] data = [] for table in resp.get("mdtables", []): tmp = [] for sub_table in table: # print(sub_table["para"]) sub_table = sub_table.get("para", "").split("表:\n|") if len(sub_table) < 2: context = sub_table[0] tmp.append({"para": context[:self.table_max_size]}) else: context, table_str = sub_table table_str = "|" + table_str remain_len = self.table_max_size - len(table_str) if remain_len < 1: table_str = table_str[:self.table_max_size] else: table_str = context[-remain_len:] + table_str tmp.append({"para": table_str}) data.append(tmp) return data @components_run_trace def run(self, message: Message, table_max_size: int = 800, doc_node_num_before_table: int = 1): """ 将文档原始解析结果,请求云端进行表格抽取,返回表格列表。 Args: message (Message): 文档原始解析结果。 table_max_size (int): 单个表格的长度的最大值(包含上文),按字符数即len(table_str)统计,默认为800。如果表格超长,则会被拆\ 分成多个子表格,拆分的最小粒度为表格的行。若单行就超长,则会强制按table_max_size截断。截断时会优先截断上文,尽量保留表格内容。 doc_node_num_before_table (int): 表格前附加的上文DocParser Node的数量,默认为1。范围:1~10。 Returns: Message: 返回解析后的消息实体对象 Message.content (list): 解析出来的文档表格,list(二维)。解析出来的文档表格,如果元素长度为1,则对应原文档中格式化后的\ 长度不超过`table_max_size`的表格;如果元素长度>1,则是对应原文档中一个大表格,该表格被拆分成的多个子表格,以满足设置\ 大小。输出结果数据结构样例:`[[{table1}], [{table2-part1}, {table2-part2}]]` Raises: ValueError: 当输入参数不为文档原始解析结果时,或值不合法时,抛出异常。 """ self._input_check(message, table_max_size, doc_node_num_before_table) self.table_max_size = table_max_size params = { "xmind_res": message.content, "single_table_size": self.table_max_size, "field_before_table_cnt": doc_node_num_before_table } url = self.http_client.service_url(sub_path="", prefix=self.base_url) headers = self.http_client.auth_header() headers["Content-Type"] = "application/json" resp = self.http_client.session.post(url=url, data=json.dumps(params), headers=headers) self.http_client.check_response_header(resp) resp = resp.json() self.http_client.check_response_json(resp) resp = self._post_process(resp) return Message(resp) ================================================ FILE: python/core/components/gbi/__init__.py ================================================ # Copyright (c) 2023 Baidu, Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. ================================================ FILE: python/core/components/gbi/basic.py ================================================ #!/usr/bin/env python 3 # -*- coding: utf-8 -*- # Copyright (c) 2023 Baidu, Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. r"""GBI nl2sql component. """ from pydantic import BaseModel, Field from typing import Dict, List class NL2SqlResult(BaseModel): """ gbi_nl2sql 返回的结果 """ llm_result: str = Field(..., description="大模型返回的结果") sql: str = Field(..., description="从大模型中抽取的 sql 语句") class SessionRecord(BaseModel): """ gbi session record """ query: str = Field(..., description="用户的问题") answer: NL2SqlResult = Field(..., description="nl2sql 返回的结果") class ColumnItem(BaseModel): """ 列信息 """ ori_value: str = Field(..., description="query 中的 词语, 比如: 北京去年收入, " "分词后: 北京, 去年, 收入, ori_value 是分词中某一个,比如: ori_value = 北京") column_name: str = Field(..., description="对应数据库中的列名称, 比如: city") column_value: str = Field(..., description="对应数据库中的列值, 比如: 北京市") table_name: str = Field(..., description="该列所在表的名字") is_like: bool = Field(default=False, description="与 ori_value 的匹配是包含 还是 等于,包含: True; 等于: False") SUPPORTED_MODEL_NAME = { "ERNIE-Bot 4.0", "ERNIE-Bot", "ERNIE-Bot-turbo" } ================================================ FILE: python/core/components/gbi/nl2sql/README.md ================================================ # GBI 问表 ## 简介 GBI 问表,根据提供的 mysql 表的 schema 信息,生成对应问题的 sql 语句。 ### 功能介绍 GBI 问表,根据提供的 mysql 表的 schema 信息,生成对应问题的 sql 语句。 ### 特色优势 直接生成 sql 语句,无需人工编写。 ### 应用场景 1. 业务人员需要根据问题生成 sql 语句,但是不熟悉 sql 语法。 2. 业务人员需要根据问题生成 sql 语句,但是不熟悉表的名称。 ## 基本用法 这里是一个示例,展示如何基于 mysql 表的 schema, 根据问题生成 sql 语句。 ```python import logging import os import appbuilder from appbuilder.core.message import Message from appbuilder.core.components.gbi.basic import SessionRecord # 请前往千帆AppBuilder官网创建密钥,流程详见:https://cloud.baidu.com/doc/AppBuilder/s/Olq6grrt6#1%E3%80%81%E5%88%9B%E5%BB%BA%E5%AF%86%E9%92%A5 os.environ["APPBUILDER_TOKEN"] = "..." SUPER_MARKET_SCHEMA = """ CREATE TABLE `supper_market_info` ( `订单编号` varchar(32) DEFAULT NULL, `订单日期` date DEFAULT NULL, `邮寄方式` varchar(32) DEFAULT NULL, `地区` varchar(32) DEFAULT NULL, `省份` varchar(32) DEFAULT NULL, `客户类型` varchar(32) DEFAULT NULL, `客户名称` varchar(32) DEFAULT NULL, `商品类别` varchar(32) DEFAULT NULL, `制造商` varchar(32) DEFAULT NULL, `商品名称` varchar(32) DEFAULT NULL, `数量` int(11) DEFAULT NULL, `销售额` int(11) DEFAULT NULL, `利润` int(11) DEFAULT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 """ table_schemas = [SUPER_MARKET_SCHEMA] gbi_nl2sql = appbuilder.NL2Sql(model_name="ERNIE-Bot 4.0", table_schemas=table_schemas) query = "列出超市中的所有数据" nl2sql_result_message = gbi_nl2sql(Message({"query": query})) print(f"sql: {nl2sql_result_message.content.sql}") print(f"llm result: {nl2sql_result_message.content.llm_result}") ``` ## 参数说明 ### 初始化参数 - model_name: 支持的模型名字 ERNIE-Bot 4.0, ERNIE-Bot, ERNIE-Bot-turbo, DeepSeek-V3.1 - table_schemas: 表的 schema,例如: ``` CREATE TABLE `supper_market_info` ( `订单编号` varchar(32) DEFAULT NULL, `订单日期` date DEFAULT NULL, `邮寄方式` varchar(32) DEFAULT NULL, `地区` varchar(32) DEFAULT NULL, `省份` varchar(32) DEFAULT NULL, `客户类型` varchar(32) DEFAULT NULL, `客户名称` varchar(32) DEFAULT NULL, `商品类别` varchar(32) DEFAULT NULL, `制造商` varchar(32) DEFAULT NULL, `商品名称` varchar(32) DEFAULT NULL, `数量` int(11) DEFAULT NULL, `销售额` int(11) DEFAULT NULL, `利润` int(11) DEFAULT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 ``` - knowledge: 用于提供一些知识, 比如 {"毛利率": "(销售收入 - 销售成本) / 销售收入"} - prompt_template: prompt 模版, 必须包含的格式如下: ***你的描述 {schema} ***你的描述 {column_instrument} ***你的描述 {kg} ***你的描述 当前时间:{date} ***你的描述 {history_instrument} ***你的描述 当前问题:{query} 回答: ### 调用参数 - message: message.content 是 字典,包含: query, session, column_constraint 三个key * query: 用户的问题 * session: gbi session 的历史 列表, 参考 SessionRecord * column_constraint: 列选约束 参考 ColumnItem 具体定义 #### SessionRecord 初始化参数 - query: 用户的问题 - answer: gbi_nl2sql 返回的结果 NL2SqlResult #### ColumnItem 初始化参数如下 - ori_value: query 中的 词语, 比如: "北京去年收入", 分词后: "北京, 去年, 收入", ori_value 是分词中某一个,比如: ori_value = "北京" - column_name: 对应数据库中的列名称, city - column_value: 对应数据库中的列值, 北京市 - table_name: 该列所属的表名称 - is_like: 与 ori_value 的匹配是包含 还是 等于,包含: True; 等于: False ### 返回值 - NL2SqlResult 的 message #### NL2SqlResult 初始化参数如下 - llm_result: 大模型返回的结果 - sql: 从 llm_result 中抽取的 sql 语句 ## 高级用法 ### 设置 session ```python session = list() session.append(SessionRecord(query=query, answer=nl2sql_result_message.content)) ``` 再次问表 ```python nl2sql_result_message2 = gbi_nl2sql(Message({"query": "查看商品类别是水果的所有数据", "session": session})) print(f"sql: {nl2sql_result_message2.content.sql}") print(f"llm result: {nl2sql_result_message2.content.llm_result}") ``` sql: SELECT * FROM supper_market_info WHERE 商品类别 = '水果'; ----------------- llm result: ```sql SELECT * FROM supper_market_info WHERE 商品类别 = '水果'; ``` ### 增加列选优化 实际上数据中 "商品类别" 存储的是 "新鲜水果", 那么就可以通过列选的限制来优化 sql. ```python from appbuilder.core.components.gbi.basic import ColumnItem column_constraint = [ColumnItem(ori_value="水果", column_name="商品类别", column_value="新鲜水果", table_name="超市营收明细表", is_like=False)] nl2sql_result_message2 = gbi_nl2sql(Message({"query": "查看商品类别是水果的所有数据", "column_constraint": column_constraint})) print(f"sql: {nl2sql_result_message2.content.sql}") print(f"llm result: {nl2sql_result_message2.content.llm_result}") ``` sql: SELECT * FROM supper_market_info WHERE 商品类别='新鲜水果' ----------------- llm result: ```sql SELECT * FROM supper_market_info WHERE 商品类别='新鲜水果' ``` 从上面我们看到,商品类别不在是 "水果" 而是 修订为 "新鲜水果" ### 增加知识优化 当计算某些特殊知识的时候,大模型是不知道的,所以需要告诉大模型具体的知识,比如: 利润率的计算方式: 利润/销售额 可以将该知识注入。具体示例如下: ```python # 注入知识 gbi_nl2sql.knowledge["利润率"] = "计算方式: 利润/销售额" ``` ```python query3 = "列出商品类别是日用品的利润率" msg3 = Message(query3) nl2sql_result_message3 = gbi_nl2sql(Message({"query": "列出商品类别是日用品的利润率"})) print(f"sql: {nl2sql_result_message3.content.sql}") print(f"llm result: {nl2sql_result_message3.content.llm_result}") ``` sql: SELECT 商品类别, SUM(利润)/SUM(销售额) AS 利润率 FROM supper_market_info WHERE 商品类别 = '日用品' GROUP BY 商品类别 ----------------- llm result: ```sql SELECT 商品类别, SUM(利润)/SUM(销售额) AS 利润率 FROM supper_market_info WHERE 商品类别 = '日用品' GROUP BY 商品类别 ``` ## 调整 prompt 模版 有时候,我们希望定义自己的prompt, 但是必须遵循对应的 prompt 模版的格式。 问表的 prompt template 必须包含: 1. {schema} - 表的 schema 信息 2. {instrument} - 列选限制的信息 3. {kg} - 知识 4. {date} - 时间 5. {history_prompt} - 历史 6. {query} - 当前问题 参考下面的示例 ```python NL2SQL_PROMPT_TEMPLATE = """ MySql 表 Schema 如下: {schema} 请根据用户当前问题,联系历史信息,仅编写1个sql,其中 sql 语句需要使用```sql ```这种 markdown 形式给出。 请参考列选信息: {instrument} 请参考知识: {kg} 当前时间:{date} 历史信息如下: {history_prompt} 当前问题:"{query}" 回答: """ ``` ```python gbi_nl2sql5 = appbuilder.NL2Sql(model_name="ERNIE-Bot 4.0", table_schemas=table_schemas, prompt_template=NL2SQL_PROMPT_TEMPLATE) nl2sql_result_message5 = gbi_nl2sql5(Message({"query": "查看商品类别是水果的所有数据"})) print(f"sql: {nl2sql_result_message5.content.sql}") print(f"llm result: {nl2sql_result_message5.content.llm_result}") ``` sql: SELECT * FROM supper_market_info WHERE 商品类别 = '水果' ----------------- llm result: ```sql SELECT * FROM supper_market_info WHERE 商品类别 = '水果' ``` ================================================ FILE: python/core/components/gbi/nl2sql/__init__.py ================================================ # Copyright (c) 2023 Baidu, Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. ================================================ FILE: python/core/components/gbi/nl2sql/base.py ================================================ # Copyright (c) 2023 Baidu, Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from typing import List from pydantic import Field from appbuilder.core.component import ComponentArguments from appbuilder.core.components.gbi.basic import SessionRecord from appbuilder.core.components.gbi.basic import ColumnItem class NL2SqlArgs(ComponentArguments): """ nl2sql 的参数 Attributes: query: 用户的 query 输入 session: gbi session 的历史 列表 column_constraint: 列选的限制条件 """ query: str = Field(..., description="用户的 query 输入") session: List[SessionRecord] = Field(default=list(), description="gbi session 的历史 列表") column_constraint: List[ColumnItem] = Field(default=list(), description="列选的限制条件") ================================================ FILE: python/core/components/gbi/nl2sql/component.py ================================================ # Copyright (c) 2023 Baidu, Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. r"""GBI nl2sql component. """ from typing import Dict, List from pydantic import ValidationError from appbuilder.core.component import Component from appbuilder.core.message import Message from appbuilder.core.components.gbi.basic import SessionRecord from appbuilder.core.components.gbi.basic import ColumnItem from appbuilder.core.components.gbi.basic import NL2SqlResult from appbuilder.core.components.gbi.basic import SUPPORTED_MODEL_NAME from appbuilder.utils.trace.tracer_wrapper import components_run_trace, components_run_stream_trace from .base import NL2SqlArgs class NL2Sql(Component): """ gib nl2sql """ meta = NL2SqlArgs def __init__(self, model_name: str, table_schemas: List[str], knowledge: Dict = None, prompt_template: str = "", **kwargs ): """ 创建 gbi nl2sql 对象 Args: model_name: 支持的模型名字 ERNIE-Bot 4.0, ERNIE-Bot, ERNIE-Bot-turbo, DeepSeek-V3.1 table_schemas: 表的 schema 列表,例如: ``` CREATE TABLE `mytable` ( `d_year` COMMENT '年度,2019,2020..2022..', `industry` COMMENT '行业', `project_name` COMMENT '项目名称', `customer_name` COMMENT '客户名称') ```" knowledge: 用于提供一些知识, 比如 {"毛利率": "毛收入-毛成本/毛成本"} prompt_template: prompt 模版, 必须包含的格式如下: ***你的描述 {schema} ***你的描述 {column_instrument} ***你的描述 {kg} ***你的描述 当前时间:{date} ***你的描述 {history_instrument} ***你的描述 当前问题:{query} 回答: """ super().__init__(meta=NL2SqlArgs) if model_name not in SUPPORTED_MODEL_NAME: raise ValueError(f"model_name mismatchhed, expected in {SUPPORTED_MODEL_NAME}, got {model_name}") self.model_name = model_name self.server_sub_path = "/v1/ai_engine/gbi/v1/gbi_nl2sql" self.table_schemas = table_schemas self.knowledge = knowledge or dict() self.prompt_template = prompt_template @components_run_trace def run(self, message: Message, timeout: float = 60, retry: int = 0) -> Message[NL2SqlResult]: """ 执行自然语言转SQL操作。 Args: message (Message): 包含用户问题和会话历史的消息对象。 - message.content 是一个字典,包含以下关键字: 1. query: 用户问题 2. session: 会话历史列表,参考 SessionRecord 3. column_constraint: 列选约束,参考 ColumnItem 具体定义 timeout (float): 超时时间,默认为60秒。 retry (int): 重试次数,默认为0次。 Returns: Message[NL2SqlResult]: 转换结果以Message对象形式返回,其中content属性包含NL2SqlResult对象。 """ try: inputs = self.meta(**message.content) except ValidationError as e: raise ValueError(e) response = self._run_nl2sql(query=inputs.query, session=inputs.session, table_schemas=self.table_schemas, column_constraint=inputs.column_constraint, knowledge=self.knowledge, prompt_template=self.prompt_template, model_name=self.model_name, timeout=timeout, retry=retry) rsp_data = response.json() nl2sql_result = NL2SqlResult(llm_result=rsp_data["llm_result"], sql=rsp_data["sql"]) return Message(content=nl2sql_result) def _run_nl2sql(self, query: str, session: List[SessionRecord], table_schemas: List[str], knowledge: Dict[str, str], prompt_template: str, column_constraint: List[ColumnItem], model_name: str, timeout: float = None, retry: int = 0): """ 运行 Args: query: query session: gbi session 的历史 列表 table_schemas: 表的 schema 列表 knowledge: 知识 prompt_template: prompt 模版 column_constraint: 列的限制 model_name: 模型名字 timeout: 超时时间 retry: Returns: """ headers = self.http_client.auth_header() headers["Content-Type"] = "application/json" if retry != self.http_client.retry.total: self.http_client.retry.total = retry payload = {"query": query, "table_schemas": table_schemas, "session": [session_record.dict() for session_record in session], "column_constraint": [column_item.dict() for column_item in column_constraint], "model_name": model_name, "knowledge": knowledge, "prompt_template": prompt_template} server_url = self.http_client.service_url(prefix="", sub_path=self.server_sub_path) response = self.http_client.session.post(url=server_url, headers=headers, json=payload, timeout=timeout) self.http_client.check_response_header(response) data = response.json() self.http_client.check_response_json(data) request_id = self.http_client.response_request_id(response) response.request_id = request_id return response ================================================ FILE: python/core/components/gbi/select_table/README.md ================================================ # GBI 选表 ## 简介 GBI 选表:根据提供的多个 MySql 表名 以及 表名对应的描述信息,通过 query 选择一个或多个最合适的表来回答该 query。 一般的适用场景是,当有数据库有多个表的时候,但是实际只有1个表能回答该 query,那么,通过该能力将该表选择出来,用于后面的 问表 环节。 ### 功能介绍 GBI 选表,根据提供的多个 MySql 表名 以及 表名对应的描述信息,通过 query 选择一个或多个最合适的表来回答该 query。 一般的适用场景是,当有数据库有多个表的时候,但是实际只有1个表能回答该 query,那么,通过该能力将该表选择出来,用于后面的 问表 环节。 ### 特色优势 可直接通过上传Excel进行数据问答 ### 应用场景 1. 营销数据分析 2. 表格问答 ## 基本用法 下面是根据提供的表的描述信息以及 query 选择对应的表的示例。 ```python import logging import os import appbuilder from appbuilder.core.message import Message from appbuilder.core.components.gbi.basic import SessionRecord # 请前往千帆AppBuilder官网创建密钥,流程详见:https://cloud.baidu.com/doc/AppBuilder/s/Olq6grrt6#1%E3%80%81%E5%88%9B%E5%BB%BA%E5%AF%86%E9%92%A5 os.environ["APPBUILDER_TOKEN"] = "..." # 表的描述信息, key: 表名; value: 是表的描述 table_descriptions = { "supper_market_info": "超市营收明细表,包含超市各种信息等", "product_sales_info": "产品销售表" } # 生成问表对象 select_table = appbuilder.SelectTable(model_name="ERNIE-Bot 4.0", table_descriptions=table_descriptions) select_table_result_message = select_table(Message({"query": "列出超市中的所有数据"})) print(f"选的表是: {select_table_result_message.content}") ``` 选的表是: ['supper_market_info'] ## 参数说明 ### 初始化参数 - model_name: 支持的模型名字 ERNIE-Bot 4.0, ERNIE-Bot, ERNIE-Bot-turbo, DeepSeek-V3.1 - table_descriptions: 表的描述是个字典,key: 是表的名字, value: 是表的描述,例如: ``` { "supper_market_info": "超市营收明细表,包含超市各种信息等", "product_sales_info": "产品销售表" } ``` - prompt_template: prompt 模版, 必须包含如下: 1. {num} - 表的数量, 注意 {num} 有两个地方出现 2. {table_desc} - 表的描述 3. {query} - query 参考下面的示例: ``` 你是一个专业的业务人员,下面有{num}张表,具体表名如下: {table_desc} 请根据问题帮我选择上述1-{num}种的其中相关表并返回,可以为多表,也可以为单表, 返回多张表请用“,”隔开 返回格式请参考如下示例: 问题:有多少个审核通过的投运单? 回答: ```DWD_MAT_OPERATION``` 请严格参考示例只不要返回无关内容,直接给出最终答案后面的内容,分析步骤不要输出 问题:{query} 回答: ``` ### 调用参数 - message: message.content 是用户的问题,包含的key: query, session * query: 用户提出的问题 * session: SessionRecord 列表 #### SessionRecord 初始化参数 - query: 用户的问题 - answer: gbi_nl2sql 返回的结果 NL2SqlResult ### 返回值 识别的表名的列表例如: `["table_name"]` ## 调整 prompt 模版 有时候,我们希望定义自己的prompt, 选表支持 prompt 模版的定制化,但是必须遵循对应的 prompt 模版的格式。 ### 选表 prompt 调整 选表的 prompt template, 必须包含 1. {num} - 表的数量, 注意 {num} 有两个地方出现 2. {table_desc} - 表的描述 3. {query} - query, 参考下面的示例: ```python SELECT_TABLE_PROMPT_TEMPLATE = """ 你是一个专业的业务人员,下面有{num}张表,具体表名如下: {table_desc} 请根据问题帮我选择上述1-{num}种的其中相关表并返回,可以为多表,也可以为单表, 返回多张表请用“,”隔开 返回格式请参考如下示例: 问题:有多少个审核通过的投运单? 回答: ```DWD_MAT_OPERATION``` 请严格参考示例只不要返回无关内容,直接给出最终答案后面的内容,分析步骤不要输出 问题:{query} 回答: """ ``` ```python select_table4 = appbuilder.SelectTable(model_name="ERNIE-Bot 4.0", table_descriptions=table_descriptions, prompt_template=SELECT_TABLE_PROMPT_TEMPLATE) select_table_result_message4 = select_table4(Message({"query": "列出超市中的所有数据"})) print(f"选的表是: {select_table_result_message4.content}") ``` 选的表是: ['supper_market_info'] ================================================ FILE: python/core/components/gbi/select_table/__init__.py ================================================ # Copyright (c) 2023 Baidu, Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. ================================================ FILE: python/core/components/gbi/select_table/base.py ================================================ # Copyright (c) 2023 Baidu, Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from typing import List from pydantic import Field from appbuilder.core.component import ComponentArguments from appbuilder.core.components.gbi.basic import SessionRecord class SelectTableArgs(ComponentArguments): """ 选表的参数 """ query: str = Field(..., description="用户的 query 输入") session: List[SessionRecord] = Field(default=list(), description="gbi session 的历史 列表") ================================================ FILE: python/core/components/gbi/select_table/component.py ================================================ # Copyright (c) 2023 Baidu, Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. r"""GBI nl2sql component. """ from typing import Dict, List from pydantic import ValidationError from appbuilder.core.component import Component from appbuilder.core.message import Message from appbuilder.core.components.gbi.basic import SessionRecord from appbuilder.core.components.gbi.basic import SUPPORTED_MODEL_NAME from appbuilder.utils.trace.tracer_wrapper import components_run_trace, components_run_stream_trace from .base import SelectTableArgs class SelectTable(Component): """ gbi 选表 """ def __init__(self, model_name: str, table_descriptions: Dict[str, str], prompt_template: str = "", **kwargs ): """ 创建 GBI 选表对象 Args: model_name: 支持的模型名字 ERNIE-Bot 4.0, ERNIE-Bot, ERNIE-Bot-turbo, DeepSeek-V3.1 table_descriptions: 表的描述是个字典,key: 是表的名字, value: 是表的描述,例如: { "超市营收明细表": "超市营收明细表,包含超市各种信息等", "product_sales_info": "产品销售表" } prompt_template: rompt 模版, 必须包含如下: 1. {num} - 表的数量, 注意 {num} 有两个地方出现 2. {table_desc} - 表的描述 3. {query} - query 参考下面的示例: ``` 你是一个专业的业务人员,下面有{num}张表,具体表名如下: {table_desc} 请根据问题帮我选择上述1-{num}种的其中相关表并返回,可以为多表,也可以为单表, 返回多张表请用“,”隔开 返回格式请参考如下示例: 问题:有多少个审核通过的投运单? 回答: ```DWD_MAT_OPERATION``` 请严格参考示例只不要返回无关内容,直接给出最终答案后面的内容,分析步骤不要输出 问题:{query} 回答: ``` """ super().__init__(meta=SelectTableArgs) if model_name not in SUPPORTED_MODEL_NAME: raise ValueError( f"model_name mismatchhed, expected in {SUPPORTED_MODEL_NAME}, got {model_name}" ) self.model_name = model_name self.server_sub_path = "/v1/ai_engine/gbi/v1/gbi_select_table" self.table_descriptions = table_descriptions self.prompt_template = prompt_template @components_run_trace def run(self, message: Message, timeout: int = 60, retry: int = 0) -> Message[List[str]]: """ 执行查询操作,返回识别的表名列表。 Args: message (Message): 包含查询信息的消息对象。 - message.content 字典包含以下 key: 1. query (str): 用户的问题输入。 2. session (list, optional): 对话历史,默认为空列表。 timeout (int, optional): 超时时间,默认为 60 秒。 retry (int, optional): 重试次数,默认为 0。 Returns: Message[List[str]]: 包含识别出的表名列表的 Message 对象。 Raises: ValueError: 如果输入的 message.content 不符合期望的格式,将抛出 ValueError 异常。 """ try: inputs = self.meta(**message.content) except ValidationError as e: raise ValueError(e) response = self._run_select_table(query=inputs.query, session=inputs.session, prompt_template=self.prompt_template, table_descriptions=self.table_descriptions, model_name=self.model_name, timeout=timeout, retry=retry) rsp_data = response.json() return Message(content=rsp_data) def _run_select_table(self, query: str, session: List[SessionRecord], prompt_template, table_descriptions: Dict[str, str], model_name: str, timeout: float = None, retry: int = 0): """ 使用给定的输入并返回语音识别的结果。 参数: request (obj:`ShortSpeechRecognitionRequest`): 输入请求,这是一个必需的参数。 timeout (float, 可选): 请求的超时时间。 retry (int, 可选): 请求的重试次数。 返回: obj:`ShortSpeechRecognitionResponse`: 接口返回的输出消息。 """ headers = self.http_client.auth_header() headers["Content_Type"] = "application/json" if retry != self.http_client.retry.total: self.http_client.retry.total = retry payload = {"query": query, "table_descriptions": table_descriptions, "session": [session_record.dict() for session_record in session], "model_name": model_name, "prompt_template": prompt_template} server_url = self.http_client.service_url(sub_path=self.server_sub_path) response = self.http_client.session.post(url=server_url, headers=headers, json=payload, timeout=timeout) self.http_client.check_response_header(response) data = response.json() self.http_client.check_response_json(data) request_id = self.http_client.response_request_id(response) response.request_id = request_id return response ================================================ FILE: python/core/components/general_ocr/README.md ================================================ # 通用文字识别-高精度版(GeneralOCR) ## 简介 通用文字识别组件(GeneralOCR)支持多场景、多语种、高精度的文字识别服务,对图片全部文字内容进行检测识别。 ### 功能介绍 覆盖多种通用场景、20+种语言的高精度整图文字检测和识别服务,包括各类印刷和手写文档、网络图片、表格、印章、数字、二维码等; ### 特色优势 * 准确率高 多项ICDAR指标居世界第一,识别准确率高 ### 应用场景 支持多场景、多语种、高精度的文字识别服务,可用于纸质文档电子化、办公文档/报表识别、图像内容审核等场景 ## 基本用法 以下是一个简单的例子来演示如何开始使用GeneralOCR组件: 示例图片为![示例图片](https://bj.bcebos.com/v1/appbuilder/general_ocr_test.png?authorization=bce-auth-v1%2FALTAKGa8m4qCUasgoljdEDAzLm%2F2024-01-11T10%3A59%3A17Z%2F-1%2Fhost%2F081bf7bcccbda5207c82a4de074628b04ae857a27513734d765495f89ffa5f73) ```python import os import appbuilder import requests # 请前往千帆AppBuilder官网创建密钥,流程详见:https://cloud.baidu.com/doc/AppBuilder/s/Olq6grrt6#1%E3%80%81%E5%88%9B%E5%BB%BA%E5%AF%86%E9%92%A5 os.environ["APPBUILDER_TOKEN"] = '...' # 从BOS读取样例图片 image_url = "https://bj.bcebos.com/v1/appbuilder/general_ocr_test.png?"\ "authorization=bce-auth-v1%2FALTAKGa8m4qCUasgoljdEDAzLm%2F2024-01-"\ "11T10%3A59%3A17Z%2F-1%2Fhost%2F081bf7bcccbda5207c82a4de074628b04ae"\ "857a27513734d765495f89ffa5f73" raw_image = requests.get(image_url).content image_base64 = base64.b64encode(raw_image) general_ocr = appbuilder.GeneralOCR() out = general_ocr.run(appbuilder.Message(content={"image_base64": image_base64})) print(out.content) ``` ## 参数说明 ### 鉴权说明 使用组件之前,请首先申请并设置鉴权参数,可参考[组件使用流程](https://cloud.baidu.com/doc/AppBuilder/s/Olq6grrt6#1%E3%80%81%E5%88%9B%E5%BB%BA%E5%AF%86%E9%92%A5)。 ```python # 设置环境中的TOKEN,以下示例略 os.environ["APPBUILDER_TOKEN"] = "bce-YOURTOKEN" ``` ### 初始化参数 无 ### 调用参数 | 参数名称 | 参数类型 | 是否必须 | 描述 | 示例值 | |---------|---------|------|-----------------------------|------------------------------------------------| | message | Message | 是 | 输入的消息,用于模型的主要输入内容。这是一个必需的参数 | Message(content={"image_base64": "待识别的图片base64数据", "image_url": ...}), 优先级image_base64 > image_url > pdf_base64 > pdf_url | | +image_base64 | String | 否 | 待识别的图片base64数据, 要求base64编码和urlencode后大小不超过10M,最短边至少15px,最长边最大8192px,支持jpg/jpeg/png/bmp格式 | 略 | | +image_url | String | 否 | 待识别的图片url, 要求base64编码和urlencode后大小不超过10M,最短边至少15px,最长边最大8192px,支持jpg/jpeg/png/bmp格式 | "https://bj.bcebos.com/agi-dev-platform-sdk-test/1.png" | | +pdf_base64 | String | 否 | 待识别的pdf文件base64数据,base64编码后进行urlencode,要求base64编码和urlencode后大小不超过10M,最短边至少15px,最长边最大8192px,支持jpg/jpeg/png/bmp格式 | 略 | | +pdf_url | String | 否 | 待识别的pdf文件url,base64编码后进行urlencode,要求base64编码和urlencode后大小不超过10M,最短边至少15px,最长边最大8192px,支持jpg/jpeg/png/bmp格式 | "https://bj.bcebos.com/agi-dev-platform-sdk-test/8、质量流量计.pdf" | | +pdf_file_num | String | 否 | 需要识别的PDF文件的对应页码,当 pdf_file 参数有效时,识别传入页码的对应页面内容,若不传入,则默认识别第 1 页 | "1" | | +detect_direction | String | 否 | 是否检测图像朝向,默认不检测,即:false。朝向是指输入图像是正常方向、逆时针旋转90/180/270度。可选值包括: true-检测朝向, false:不检测朝向 | "false" | | +multidirectional_recognize | String | 否 | 是否开启行级别的多方向文字识别,可选值包括: true-识别, false-不识别.若图内有不同方向的文字时,建议将此参数设置为“true” | "true" | |timeout| Float | 否 | HTTP超时时间,单位:秒 |1|| | retry | Integer | 否 | HTTP重试次数 | 3 | ### 响应参数 | 参数名称 | 参数类型 | 描述 | 示例值 | |--------------|---------|---------|---------------------------------------------------| | words_result | Array[] | 返回结果 | [{"words":"一站式企业级大模型平台,提供先进的生成式AI生产及应用全流程开发工具链"}] | | + words | String | 识别结果字符串 | "百度智能云千帆大模型平台" | ### 响应示例 ```json { "words_result":[ { "words":"一站式企业级大模型平台,提供先进的生成式AI生产及应用全流程开发工具链" }, { "words":"百度智能云千帆大模型平台" }, { "words":"文心大模型4.0已正式发布,个人和企业客户可通过百度智能云千帆大模型平台接入使用" }, { "words":"立即使用" }, { "words":"在线体验" }, { "words":"使用文档" }, { "words":"定价说明" }, { "words":"千帆社区" }, { "words":"常见概念、使用指导" }, { "words":"定价、计费方式、计量说明" }, { "words":"大模型开发学习、交流社区" } ] } ``` ## 高级用法 目前该模块仅提供基础通用文字识别功能。 ## 更新记录和贡献 * 通用文字识别能力 (2023-12) * 增加Pdf格式输入,增加detect_direction和multidirectional_recognize入参 ================================================ FILE: python/core/components/general_ocr/__init__.py ================================================ # Copyright (c) 2023 Baidu, Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. ================================================ FILE: python/core/components/general_ocr/component.py ================================================ # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. r"""general ocr component.""" import base64 import json import os.path import requests from appbuilder.core import utils from appbuilder.core._client import HTTPClient from appbuilder.core._exception import AppBuilderServerException, InvalidRequestArgumentError from appbuilder.core.component import Component from appbuilder.core.components.general_ocr.model import * from appbuilder.core.message import Message from appbuilder.utils.trace.tracer_wrapper import components_run_trace, components_run_stream_trace class GeneralOCR(Component): r""" 提供通用文字识别能力,在通用文字识别的基础上,提供更高精度的识别服务,支持更多语种识别(丹麦语、荷兰语、马来语、 瑞典语、印尼语、波兰语、罗马尼亚语、土耳其语、希腊语、匈牙利语、泰语、越语、阿拉伯语、印地语及部分中国少数民族语言), 并将字库从1w+扩展到2w+,能识别所有常用字和大部分生僻字。 Examples: .. code-block:: python import appbuilder # 请前往千帆AppBuilder官网创建密钥,流程详见:https://cloud.baidu.com/doc/AppBuilder/s/Olq6grrt6#1%E3%80%81%E5%88%9B%E5%BB%BA%E5%AF%86%E9%92%A5 os.environ["APPBUILDER_TOKEN"] = '...' general_ocr = appbuilder.GeneralOCR() with open("./general_ocr_test.png", "rb") as f: out = general_ocr.run(appbuilder.Message(content={"raw_image": f.read()})) print(out.content) """ name = "general_ocr" version = "v1" manifests = [ { "name": "general_ocr", "description": "提供更高精度的通用文字识别能力,能够识别图片中的文字,不支持html后缀文件的输入", "parameters": { "type": "object", "properties": { "img_url": { "type": "string", "description": "待识别图片的url,根据该url能够获取图片" }, "img_name": { "type": "string", "description": "待识别图片的文件名,用于生成图片url" }, "language_type": { "type": "string", "description": "识别语言类型,'CHN_ENG'为中英文混合,'ENG'为英文, 'JAP'为日语,'KOR'为韩语,'FRE'为法语,'SPA'为西班牙语,'POR'为葡萄牙语," "'GER'为德语,'ITA'为意大利语,'RUS'为俄语,'DAN'为丹麦语,'DUT'为荷兰语,'MAL'为马来语,'SWE'为瑞典语,'IND'为印尼语,'POL'为波兰语,'ROM'为罗马尼亚语," "'TUR'为土耳其语,'GRE'为希腊语,'HUN'为匈牙利语,'THA'为泰语,'VIE'为越南语,'ARA'为阿拉伯语,'HIN'为印地语,默认为'CHN_ENG'", "enum": ['CHN_ENG', 'ENG', 'JAP', 'KOR', 'FRE', 'SPA', 'POR', 'GER', 'ITA', 'RUS', 'DAN', 'DUT', 'MAL', 'SWE', 'IND', 'POL', 'ROM', 'TUR', 'GRE', 'HUN', 'THA', 'VIE', 'ARA', 'HIN'], }, }, "anyOf": [ { "required": [ "img_url" ] }, { "required": [ "img_name" ] } ] } } ] @HTTPClient.check_param @components_run_trace def run(self, message: Message, timeout: float = None, retry: int = 0, language_type: str = 'CHN_ENG') -> Message: """ 在通用文字识别的基础上,提供更高精度的识别服务,支持更多语种识别 Args: message (Message): 包含识别任务的输入信息的消息对象。 timeout (float, optional): 超时时间,单位秒。默认为None,表示不设置超时。 retry (int, optional): 重试次数。默认为0,表示不重试。 language_type (str, optional): 识别语言类型,可选值为'CHN_ENG'(中英文)和'CHN'(中文)。默认为'CHN_ENG'。 Returns: Message: 包含识别结果的消息对象。 """ inp = GeneralOCRInMsg(**message.content) request = GeneralOCRRequest() if inp.image_base64: request.image = (inp.image_base64) elif inp.image_url: request.url = inp.image_url elif inp.pdf_base64: request.pdf_file = inp.pdf_base64 elif inp.pdf_url: raw_pdf = requests.get(inp.pdf_url).content pdf_base64 = base64.b64encode(raw_pdf) request.pdf_file = pdf_base64 request.pdf_file_num = inp.pdf_file_num request.detect_direction = inp.detect_direction request.multidirectional_recognize = inp.multidirectional_recognize request.language_type = language_type result = self._recognize(request, timeout, retry) result_dict = proto.Message.to_dict(result) out = GeneralOCROutMsg(**result_dict) return Message(content=out.model_dump()) def _recognize( self, request: GeneralOCRRequest, timeout: float = None, retry: int = 0, request_id: str = None, ) -> GeneralOCRResponse: r"""调用底层接口进行通用文字识别 参数: request (obj: `GeneralOCRRequest`) : 通用文字识别输入参数 返回: response (obj: `GeneralOCRResponse`): 通用文字识别返回结果 """ if not request.image and not request.url and not request.pdf_file and not request.ofd_file: raise ValueError( "request format error, one of image or url or must pdf_file or ofd_file be set") data = GeneralOCRRequest.to_dict(request) if self.http_client.retry.total != retry: self.http_client.retry.total = retry headers = self.http_client.auth_header(request_id) headers['content-type'] = 'application/x-www-form-urlencoded' url = self.http_client.service_url("/v1/bce/aip/ocr/v1/accurate_basic") response = self.http_client.session.post( url, headers=headers, data=data, timeout=timeout) self.http_client.check_response_header(response) data = response.json() self.http_client.check_response_json(data) request_id = self.http_client.response_request_id(response) self.__class__._check_service_error(request_id, data) ocr_response = GeneralOCRResponse.from_json(payload=json.dumps(data)) ocr_response.request_id = request_id return ocr_response @staticmethod def _check_service_error(request_id: str, data: dict): r"""个性化服务response参数检查 参数: request (dict) : 通用文字识别body返回 返回: 无 """ if "error_code" in data or "error_msg" in data: raise AppBuilderServerException( request_id=request_id, service_err_code=data.get("error_code"), service_err_message=data.get("error_msg") ) @components_run_stream_trace def tool_eval(self, name: str, streaming: bool, **kwargs): r""" 根据给定的参数执行OCR识别功能。 Args: name (str): 函数名称,此处未使用,但为保持一致性保留。 streaming (bool): 是否以流式方式返回结果。如果为True,则逐个返回结果,否则返回全部结果。 kwargs: 关键字参数,支持以下参数: traceid (str): 请求的唯一标识符,用于追踪请求和响应。 img_url (str): 待识别图片的URL。 file_urls (dict): 包含文件名和对应URL的字典。如果提供了img_url,则忽略此参数。 img_name (str): 待识别图片的文件名,与file_urls配合使用。 Returns: 如果streaming为False,则返回包含识别结果的JSON字符串。 如果streaming为True,则逐个返回包含识别结果的字典。 Raises: InvalidRequestArgumentError: 如果请求格式错误(例如未设置文件名或指定文件名对应的URL不存在),则抛出此异常。 """ traceid = kwargs.get("traceid") img_url = kwargs.get("img_url", None) language_type = kwargs.get("language_type", 'CHN_ENG') if not img_url: file_urls = kwargs.get("file_urls", {}) img_path = kwargs.get("img_name", None) if not img_path: raise InvalidRequestArgumentError( "request format error, file name is not set") img_name = os.path.basename(img_path) img_url = file_urls.get(img_name, None) if not img_url: raise InvalidRequestArgumentError( f"request format error, file {img_name} url does not exist") req = GeneralOCRRequest(url=img_url) req.detect_direction = "true" req.language_type = language_type result = proto.Message.to_dict(self._recognize(req, request_id=traceid)) results = { "识别结果": " \n".join(item["words"] for item in result["words_result"]) } res = json.dumps(results, ensure_ascii=False, indent=4) if streaming: yield { "type": "text", "text": res, "visible_scope": 'llm', } yield { "type": "text", "text": "", "visible_scope": 'user', } else: return res ================================================ FILE: python/core/components/general_ocr/model.py ================================================ # Copyright (c) 2023 Baidu, Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """general ocr model.""" import proto from typing import List from pydantic import BaseModel # PB definition class GeneralOCRRequest(proto.Message): """通用ocr识别请求体 属性: image (str): 可选。图像内容的base64编码。 url (str): 可选。图像的URL地址,经过base64编码。 图像大小必须小于4MB,图像的最短边长大于15像素,最长边长大于4096像素。 pdf_file (str): 可选。PDF文件内容的base64编码。 pdf_file_num (str): 可选。PDF文件的页数。 ofd_file (str): 可选。OFD(Open Format Document)文件内容的base64编码。 ofd_file_num (str): 可选。OFD文件的页数。 language_type (str): 可选。文本使用的语言类型。默认为"CHN_ENG"。 可能的取值包括: - "auto_detect": 自动检测语言并识别。 - "CHN_ENG": 中英文混合。 - "ENG": 英文。 - "JAP": 日文。 - "KOR": 韩文。 - "FRE": 法文。 - "SPA": 西班牙文。 - "POR": 葡萄牙文。 - "GER": 德文。 - "ITA": 意大利文。 - "RUS": 俄文。 - "DAN": 丹麦文。 - "DUT": 荷兰文。 - "MAL": 马来文。 - "SWE": 瑞典文。 - "IND": 印度尼西亚文。 - "POL": 波兰文。 - "ROM": 罗马尼亚文。 - "TUR": 土耳其文。 - "GRE": 希腊文。 - "HUN": 匈牙利文。 - "THA": 泰文。 - "VIE": 越南文。 - "ARA": 阿拉伯文。 - "HIN": 印地文。 detect_direction (str): 可选。是否检测文本方向。默认为"false"。 可能的取值包括: - "true": 检测文本方向。 - "false": 不检测文本方向。 paragraph (str): 可选。是否输出段落信息。默认为"false"。 可能的取值包括: - "true": 输出段落信息。 - "false": 不输出段落信息。 probability (str): 可选。是否输出置信度。默认为"false"。 可能的取值包括: - "true": 返回识别结果中每行的置信度。 - "false": 不返回置信度。 """ image: str = proto.Field( proto.STRING, number=1, ) url: str = proto.Field( proto.STRING, number=2, ) pdf_file: str = proto.Field( proto.STRING, number=3, ) pdf_file_num: str = proto.Field( proto.STRING, number=4, optional=True, ) ofd_file: str = proto.Field( proto.STRING, number=5, ) ofd_file_num: str = proto.Field( proto.STRING, number=6, ) language_type: str = proto.Field( proto.STRING, number=7, ) detect_direction: str = proto.Field( proto.STRING, number=8, ) paragraph: str = proto.Field( proto.STRING, number=9, ) probability: str = proto.Field( proto.STRING, number=10, ) multidirectional_recognize: str = proto.Field( proto.STRING, number=11, ) class GeneralOCRResponse(proto.Message): """通用ocr识别结果 属性: log_id (int): 必填。用于问题跟踪的唯一日志ID。 direction (int): 可选。当detect_direction=true时的图像方向。 - -1: 未定义。 - 0: 正常。 - 1: 逆时针旋转90度。 - 2: 逆时针旋转180度。 - 3: 逆时针旋转270度。 words_result_num (int): 必填。识别结果的数量。 words_result (List[Dict[str, Any]]): 必填。识别结果的数组。 - words (str): 识别出的文本。 - probability (Dict[str, float]): 识别结果中每行的置信度值。 包括平均值、方差和最小置信度值。 当probability=true时返回。 paragraphs_result (List[Dict[str, Any]]): 可选。段落检测结果。当paragraph=true时返回。 - words_result_idx (List[int]): 包含在段落中的行索引。 paragraphs_result_num (int): 可选。段落检测结果的数量。当paragraph=true时返回。 pdf_file_size (int): 可选。输入PDF文件的总页数。当pdf_file参数有效时返回。 ofd_file_size (str): 可选。输入OFD文件的总页数。当ofd_file参数有效时返回。 """ request_id: str = proto.Field( proto.STRING, number=1, ) log_id: int = proto.Field( proto.UINT64, number=2, ) direction: int = proto.Field( proto.INT32, number=3, ) words_result_num: int = proto.Field( proto.UINT32, number=4, ) words_result: 'WordResult' = proto.RepeatedField( proto.MESSAGE, number=5, message='WordResult' ) paragraphs_result: 'ParagraphResult' = proto.RepeatedField( proto.MESSAGE, number=6, message='ParagraphResult' ) paragraphs_result_num: int = proto.Field( proto.UINT32, number=7, ) pdf_file_size: int = proto.Field( proto.UINT32, number=8, ) ofd_file_size: str = proto.Field( proto.STRING, number=9, ) class WordResult(proto.Message): """ 识别结果列表. 属性: - words (str): 识别出的文本。 - probability (Dict[str, float]): 识别结果中每行的置信度值。 包括平均值、方差和最小置信度值。 当probability=true时返回。 """ words: str = proto.Field( proto.STRING, number=1, ) probability: 'Probability' = proto.Field( proto.MESSAGE, number=2, message='Probability' ) class Probability(proto.Message): """置信度 属性: - average (float): 每行的平均置信度 - variance (float): 每行置信度的方差 - minimum (float):每行的最小置信度 """ average: float = proto.Field( proto.FLOAT, number=1, ) variance: float = proto.Field( proto.FLOAT, number=2, ) min: float = proto.Field( proto.FLOAT, number=3, ) class ParagraphResult(proto.Message): """ 段落检测结果,当paragraph=true时将返回该字段。 """ words_result_idx: int = proto.Field( proto.INT32, number=1, ) class GeneralOCRInMsg(BaseModel): """ 通用文字识别输入消息 属性: raw_image(bytes): 图像原始内容 url(str): 图像下载链接 """ image_base64: str = "" # 原始图片base64数据 image_url: str = "" # 图片可下载链接 pdf_base64: str = "" #pdf base64数据 pdf_url: str = "" #pdf 可下载链接 pdf_file_num: str = "1" #需要识别的PDF文件的对应页码 detect_direction: str = "false" #是否检测图像朝向 multidirectional_recognize: str = "true" #是否开启行级别的多方向文字识别 class Words(BaseModel): """ 识别文字 属性: words(str):识别文字结果 """ words: str class GeneralOCROutMsg(BaseModel): """ 识别文字结果列表 属性: words_result([]array):识别文字结果列表 """ words_result: List['Words'] ================================================ FILE: python/core/components/handwrite_ocr/README.md ================================================ # 手写文字识别 (HandwriteOCR) ## 简介 手写文字识别 (HandwriteOCR),图片中的手写中文、手写数字进行检测和识别,针对不规则的手写字体进行专项优化,识别准确率可达90%以上。 ### 功能介绍 检测识别图片中的手写中文、手写数字,针对不规则的手写字体进行专项优化 ### 特色优势 识别准确率可达90%以上 ### 应用场景 手写文字识别 ## 基本用法 下面是手写文字识别的代码示例: 示例图片为 ![示例图片](https://bj.bcebos.com/v1/appbuilder/test_handwrite_ocr.jpg?authorization=bce-auth-v1%2FALTAKGa8m4qCUasgoljdEDAzLm%2F2024-01-23T11%3A58%3A09Z%2F-1%2Fhost%2F677f93445fb65157bee11cd492ce213d5c56e7a41827e45ce7e32b083d195c8b) ```python import os import requests import appbuilder # 请前往千帆AppBuilder官网创建密钥,流程详见:https://cloud.baidu.com/doc/AppBuilder/s/Olq6grrt6#1%E3%80%81%E5%88%9B%E5%BB%BA%E5%AF%86%E9%92%A5 os.environ["APPBUILDER_TOKEN"] = "..." image_url="https://bj.bcebos.com/v1/appbuilder/test_handwrite_ocr.jpg?authorization=bce-auth-v1%2FALTAKGa8m4qCUasgoljdEDAzLm%2F2024-01-23T11%3A58%3A09Z%2F-1%2Fhost%2F677f93445fb65157bee11cd492ce213d5c56e7a41827e45ce7e32b083d195c8b" # 从BOS存储读取样例文件 raw_image = requests.get(image_url).content inp = appbuilder.Message(content={"raw_image": raw_image}) # inp = Message(content={"url": image_url}) # 运行手写文字识别 handwrite_ocr = appbuilder.HandwriteOCR() out = handwrite_ocr.run(inp) # 打印识别结果 print(out.content) ``` ## 参数说明 ### 鉴权说明 使用组件之前,请首先申请并设置鉴权参数,可参考[组件使用流程](https://cloud.baidu.com/doc/AppBuilder/s/Olq6grrt6#1%E3%80%81%E5%88%9B%E5%BB%BA%E5%AF%86%E9%92%A5)。 ```python import os os.environ["APPBUILDER_TOKEN"] = "..." ``` ### 初始化参数 无 ### 调用参数 | 参数名称 | 参数类型 | 是否必须 | 描述 |示例值| |------------|--------|------|-----------------------------|---| | message | String | 是 | 输入的消息,用于模型的主要输入内容。这是一个必需的参数 || | +content | Dict | 是 | 消息内容 || | +raw_image | String | 否 | 原始图片字节流 || | +url | String | 否 | 图片下载链接地址 || |timeout| Float | 否 | HTTP超时时间,单位:秒 |1|| |retry|Integer| 否 | HTTP重试次数 |3|| ### 响应参数 | 参数名称 | 参数类型 | 描述 | 示例值 | |-----------|----------|--|-----------------------------------------------------------------| | contents | List | 文本内容块 | | | +text | String | 文本字符串 | | | +Position | Dict | 文本位置信息 | | | ++left | Interger | 表示定位位置的长方形左上顶点的水平坐标 | | | ++top | Interger | 表示定位位置的长方形左上顶点的垂直坐标| | | ++width | Interger | 表示定位位置的长方形的宽度 | | | ++height | Interger | 表示定位位置的长方形的高度 | | | direction | Interger | 图像旋转角度 | 图像旋转角度,0(正向),- 1(逆时针90度),- 2(逆时针180度),- 3(逆时针270度)| ### 响应示例 ```json { "contents": [{ "text": "我们家住的小区里有很多银杏树。", "position": { "left": 390, "top": 46, "width": 1801, "height": 161 } }, { "text": "它们笔直笔直的,就像一位正在站岗的", "position": { "left": 131, "top": 263, "width": 2083, "height": 170 } }, { "text": "卫兵。它枝繁叶茂,长的非常好,它的叶子", "position": { "left": 154, "top": 483, "width": 2023, "height": 161 } }, { "text": "有些小的像一把把小扇子,大的也像扇子。", "position": { "left": 151, "top": 699, "width": 2167, "height": 168 } }, { "text": "但是中间有一个缺口,就像被淘汽的小", "position": { "left": 148, "top": 929, "width": 2123, "height": 177 } }, { "text": "朋友用剪刀剪掉了一样。", "position": { "left": 161, "top": 1165, "width": 1340, "height": 217 } } ], "direction": 0 } ``` ## 高级用法 目前该模块仅提供基础的手写体识别。 ## 更新记录和贡献 * 手写文字识别 (2024-01) * 手写文字识别 (2024-02) ================================================ FILE: python/core/components/handwrite_ocr/__init__.py ================================================ # Copyright (c) 2023 Baidu, Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. ================================================ FILE: python/core/components/handwrite_ocr/component.py ================================================ # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. r"""手写文字识别组件""" import base64 from appbuilder.core._exception import AppBuilderServerException, InvalidRequestArgumentError from appbuilder.core.component import Component from appbuilder.core.components.handwrite_ocr.model import * from appbuilder.core.message import Message from appbuilder.core._client import HTTPClient from appbuilder.core import utils from appbuilder.utils.trace.tracer_wrapper import components_run_trace, components_run_stream_trace class HandwriteOCR(Component): r""" 手写文字识别组件 Examples: .. code-block:: python import os import appbuilder os.environ["GATEWAY_URL"] = "..." os.environ["APPBUILDER_TOKEN"] = "..." # 从BOS存储读取样例文件 image_url="https://bj.bcebos.com/v1/appbuilder/test_handwrite_ocr.jpg?authorization=bce-auth-v1%2FALTAKGa8m4qCUasgoljdEDAzLm%2F2024-01-23T11%3A58%3A09Z%2F-1%2Fhost%2F677f93445fb65157bee11cd492ce213d5c56e7a41827e45ce7e32b083d195c8b" # 输入参数为一张图片 inp = appbuilder.Message(content={"url": image_url}) # 进行植物识别 handwrite_ocr = HandwriteOCR() out = handwrite_ocr.run(inp) # 打印识别结果 print(out.content) """ name = "handwriting_ocr" version = "v1" manifests = [ { "name": "handwriting_ocr", "description": "需要对图片中手写体文字进行识别时,使用该工具,不支持PDF文件,如果用户没有提供图片文件,应引导用户提供图片,而不是尝试使用该工具", "parameters": { "type": "object", "properties": { "file_names": { "type": "array", "items": { "type": "string" }, "description": "待识别文件的文件名" } }, "required": ["file_names"] } } ] @HTTPClient.check_param @components_run_trace def run(self, message: Message, timeout: float = None, retry: int = 0) -> Message: r""" 输入图片并识别其中的文字 Args: message (Message): 输入图片或图片url下载地址用于执行识别操作.例如: Message(content={"raw_image": b"..."}) 或 Message(content={"url": "https://image/download/url"}). timeout (float, optional): HTTP超时时间. 默认为None. retry (int, optional): HTTP重试次数. 默认为0. Returns: Message: 手写体模型识别结果. """ inp = HandwriteOCRInMsg(**message.content) request = HandwriteOCRRequest() if inp.url: request.url = inp.url if inp.raw_image: request.image = base64.b64encode(inp.raw_image) request.recognize_granularity = "big" request.probability = "false" request.detect_direction = "true" request.detect_alteration = "true" response = self._recognize(request, timeout, retry) out = HandwriteOCROutMsg() out.direction = response.direction [out.contents.append( Content(text=w.words, position=Position( left=w.location.left, top=w.location.top, width=w.location.width, height=w.location.height ))) for w in response.words_result] return Message(content=out.model_dump()) @components_run_stream_trace def tool_eval(self, name: str, streaming: bool, **kwargs): r""" 对指定文件或URL进行手写识别。 Args: name (str): 任务名称。 streaming (bool): 是否以流式形式返回结果。 kwargs: 其他参数,包括: traceid (str, optional): 请求的traceid,用于标识请求的唯一性。默认为None。 file_names (List[str], optional): 待识别的文件名列表。默认为None,此时会从kwargs中获取'files'参数。 file_urls (Dict[str, str], optional): 文件名与URL的映射字典。默认为空字典。 Returns: 如果streaming为True,则以生成器形式返回识别结果,否则直接返回结果字符串。 Raises: InvalidRequestArgumentError: 如果请求格式错误,例如指定的文件名对应的URL不存在。 """ traceid = kwargs.get("traceid") result = "" file_names = kwargs.get("file_names", None) if not file_names: file_names = kwargs.get("files") file_urls = kwargs.get("file_urls", {}) for file_name in file_names: if utils.is_url(file_name): file_url = file_name else: file_url = file_urls.get(file_name, None) if file_url is None: raise InvalidRequestArgumentError(f"request format error, file {file_name} url does not exist") req = HandwriteOCRRequest() req.url = file_url req.recognize_granularity = "big" req.probability = "false" req.detect_direction = "true" req.detect_alteration = "true" response = self._recognize(req, request_id=traceid) text = "".join([w.words for w in response.words_result]) result += f"{file_name}的手写识别结果是:{text} " if streaming: yield { "type": "text", "text": result, "visible_scope": 'llm', } yield { "type": "text", "text": "", "visible_scope": "user", } else: return result def _recognize( self, request: HandwriteOCRRequest, timeout: float = None, retry: int = 0, request_id: str = None, ) -> HandwriteOCRResponse: r"""调用底层接口进行通用文字识别 参数: request (obj: `HandwriteOCRRequest`) : 通用文字识别输入参数 返回: response (obj: `HandwriteOCRResponse`): 通用文字识别返回结果 """ if not request.image and not request.url: raise ValueError("request format error, one of image or url must be set") data = HandwriteOCRRequest.to_dict(request) if self.http_client.retry.total != retry: self.http_client.retry.total = retry headers = self.http_client.auth_header(request_id) headers['content-type'] = 'application/x-www-form-urlencoded' url = self.http_client.service_url("/v1/bce/aip/ocr/v1/handwriting") response = self.http_client.session.post(url, headers=headers, data=data, timeout=timeout) self.http_client.check_response_header(response) data = response.json() self.http_client.check_response_json(data) request_id = self.http_client.response_request_id(response) self.__class__._check_service_error(request_id, data) ocr_response = HandwriteOCRResponse(data) ocr_response.request_id = request_id return ocr_response @staticmethod def _check_service_error(request_id: str, data: dict): r"""个性化服务response参数检查 参数: request (dict) : 通用文字识别body返回 返回: 无 """ if "error_code" in data or "error_msg" in data: raise AppBuilderServerException( request_id=request_id, service_err_code=data.get("error_code"), service_err_message=data.get("error_msg") ) ================================================ FILE: python/core/components/handwrite_ocr/model.py ================================================ # Copyright (c) 2023 Baidu, Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """手写文字识别数据类""" import proto from typing import List, Optional from pydantic import BaseModel class HandwriteOCRRequest(proto.Message): """ 手写文字识别组件请求参数 属性: image (str): 可选。图像内容的base64编码。 url (str): 可选。图像的URL地址,经过base64编码。 图像大小必须小于4MB,图像的最短边长大于15像素,最长边长大于4096像素。 pdf_file (str): 可选。PDF文件内容的base64编码。 pdf_file_num (str): 可选。PDF文件的页数。 ofd_file (str): 可选。OFD(Open Format Document)文件内容的base64编码。 ofd_file_num (str): 可选。OFD文件的页数。 recognize_granularity(str): 可选,识别粒度: 可能的取值包括: - "big": 不定位单字符位置 - "small": 定位单字符位置。 probability (str): 可选。是否输出置信度。默认为"false"。 可能的取值包括: - "true": 返回识别结果中每行的置信度。 - "false": 不返回置信度。 detect_direction (str): 可选。是否检测文本方向。默认为"false"。 可能的取值包括: - "true": 检测文本方向。 - "false": 不检测文本方向。 detect_alteration(str): 可选,是否检测涂改痕迹,适用于手写作文场景,默认不检测 可选值包括: - "true":检测,涂改痕迹部分用“☰”返回; - "false":不检测 """ image: str = proto.Field( proto.STRING, number=1, ) url: str = proto.Field( proto.STRING, number=2, ) pdf_file: str = proto.Field( proto.STRING, number=3, ) pdf_file_num: str = proto.Field( proto.STRING, number=4, ) ofd_file: str = proto.Field( proto.STRING, number=5, ) ofd_file_num: str = proto.Field( proto.STRING, number=6, ) recognize_granularity: str = proto.Field( proto.STRING, number=7, ) probability: str = proto.Field( proto.STRING, number=8, ) detect_direction: str = proto.Field( proto.STRING, number=9, ) detect_alteration: str = proto.Field( proto.STRING, number=10, ) class HandwriteLocation(proto.Message): """ 手写体位置信息. 属性: left (int): 表示定位位置的长方形左上顶点的水平坐标 top (int): 表示定位位置的长方形左上顶点的垂直坐标 width (int): 表示定位位置的长方形的宽度 height (int): 表示定位位置的长方形的高度 """ left: int = proto.Field( proto.INT32, number=1, ) top: int = proto.Field( proto.INT32, number=2, ) width: int = proto.Field( proto.INT32, number=3, ) height: int = proto.Field( proto.INT32, number=4, ) class HandwriteWordResult(proto.Message): """ 手写文字识别结果列表 属性: words (str): 识别出的文本 location (Location): 文本位置信息 """ words: str = proto.Field( proto.STRING, number=1, ) location = proto.Field( HandwriteLocation, number=2, ) class HandwriteProbability(proto.Message): """手写体置信度 属性: average (float): 每行的平均置信度 variance (float): 每行置信度的方差 min (float):每行的最小置信度 """ average: float = proto.Field( proto.FLOAT, number=1, ) variance: float = proto.Field( proto.FLOAT, number=2, ) min: float = proto.Field( proto.FLOAT, number=3, ) class HandwriteOCRResponse(proto.Message): """手写文字识别结果 属性: request_id(str): 请求ID log_id (int): 用于问题跟踪的唯一日志ID words_result_num (int): 必填。识别结果的数量 words_result (List[WordResult]): 识别结果的数组 probability(Probability):当probability=true 时返回该字段,表示识别结果中每一行的置信度值 direction (int): 当detect_direction=true返回改字段,1(未定义)、 0(正向)、1(逆时针90度)、2(逆时针180度)、3(逆时针270度) pdf_file_size (str): 输入PDF文件的总页数。当pdf_file参数有效时返回 """ request_id: str = proto.Field( proto.STRING, number=1, ) log_id: int = proto.Field( proto.UINT64, number=2, ) words_result_num: int = proto.Field( proto.UINT32, number=3, ) words_result = proto.RepeatedField( HandwriteWordResult, number=4, ) probability = proto.Field( HandwriteProbability, number=5 ) direction: int = proto.Field( proto.INT32, number=6, ) pdf_file_size: str = proto.Field( proto.STRING, number=7, ) class HandwriteOCRInMsg(BaseModel): """ 手写体文字识别输入消息 属性: raw_image(bytes): 图像原始内容 url(str): 图像下载链接 """ raw_image: bytes = b'' # 原始图片byte数组 url: str = "" # 图片可下载链接 class Position(BaseModel): """位置信息 属性: left (int): 表示定位位置的长方形左上顶点的水平坐标 top (int): 表示定位位置的长方形左上顶点的垂直坐标 width (int): 表示定位位置的长方形的宽度 height (int): 表示定位位置的长方形的高度 """ left: int top: int width: int height: int class Content(BaseModel): """ 识别文字 属性: content(str):文字内容 position(Position): 文字内容的位置信息 """ text: str position: Optional[Position] = None class HandwriteOCROutMsg(BaseModel): """ 识别文字结果列表 属性: contents(list[Content]): 手写体文字识别结果列表 direction(int): 图像旋转角度,0(正向),- 1(逆时针90度),- 2(逆时针180度),- 3(逆时针270度) """ contents: List[Content] = list() direction: int = 0 ================================================ FILE: python/core/components/image_understand/README.md ================================================ # 图像内容理解 (ImageUnderstand) ## 简介 图像内容理解 (ImageUnderstand),输出理解图片后的文本信息 ### 功能介绍 支持输入图片和提问信息,可对输入图片进行理解,输出对图片的一句话描述 ### 特色优势 同时,支持客户自主选择,是否调用大模型对输出文本进行润色,目前支持百度文心大模型调用。 ### 应用场景 图像内容理解 ## 基本用法 下面是图像内容理解的代码示例: 示例图片为:![示例图片](https://bj.bcebos.com/v1/appbuilder/test_image_understand.jpeg?authorization=bce-auth-v1%2FALTAKGa8m4qCUasgoljdEDAzLm%2F2024-01-24T09%3A41%3A01Z%2F-1%2Fhost%2Fe8665506e30e0edaec4f1cc84a2507c4cb3fdb9b769de3a5bfe25c372b7e56e6) ```python import os import appbuilder import requests # 请前往千帆AppBuilder官网创建密钥,流程详见:https://cloud.baidu.com/doc/AppBuilder/s/Olq6grrt6#1%E3%80%81%E5%88%9B%E5%BB%BA%E5%AF%86%E9%92%A5 os.environ["APPBUILDER_TOKEN"] = "..." # 从BOS存储读取样例文件 image_url = "https://bj.bcebos.com/v1/appbuilder/test_image_understand.jpeg?authorization=bce-auth-v1%2FALTAKGa8m4qCUasgoljdEDAzLm%2F2024-01-24T09%3A41%3A01Z%2F-1%2Fhost%2Fe8665506e30e0edaec4f1cc84a2507c4cb3fdb9b769de3a5bfe25c372b7e56e6" raw_image = requests.get(image_url).content # 输入参数为一张图片 inp = appbuilder.Message(content={"raw_image": raw_image, "question": "图片里内容是什么?"}) # 进行图像内容理解 image_understand = appbuilder.ImageUnderstand() out = image_understand.run(inp) # 打印识别结果 print(out.content) ``` ## 参数说明 ### 鉴权说明 使用组件之前,请首先申请并设置鉴权参数,可参考[组件使用流程](https://cloud.baidu.com/doc/AppBuilder/s/Olq6grrt6#1%E3%80%81%E5%88%9B%E5%BB%BA%E5%AF%86%E9%92%A5)。 ```python import os os.environ["APPBUILDER_TOKEN"] = "..." ``` ### 初始化参数 无 ### 调用参数 | 参数名称 | 参数类型 | 是否必须 | 描述 | 示例值 | |------------|--------|------|-----------------------------------|-----| | message | obj:`Message` | 是 | 输入的消息,用于模型的主要输入内容。这是一个必需的参数 | | | +content | Dict | 是 | 消息内容 | | | ++raw_image | String | 否 | 原始图片字节流 | | | ++url | String | 否 | 图片下载链接地址 | | | ++question | String | 是 | 问题字符串,长度小于100 | | | ++language | String | 否 | 描述内容的所使用的语言,默认是zh-CN(中文),可选en(英文) | | |timeout| Float | 否 | HTTP超时时间,单位:秒 |1|| |retry| Integer | 否 | HTTP重试次数 |3|| ### 响应参数 | 参数名称 | 参数类型 | 描述 | 示例值 | |-----------|------|--------|-------------------------------------------------| | message | obj:`Message` | 图像理解输出内容 | - | | +content | Dict | 输出内容 | "description": "用户上传的图像,经过前期模型分析存在以下信息..., 整个图像内容可以表述为...,回答如下..." | | ++description | String | 图像内容理解结果 | "用户上传的图像,经过前期模型分析存在以下信息...,回答如下问题:图片里内容是什么?" | ### 响应示例 ```json output.content = { "description": "用户上传的图像,经过前期模型分析存在以下信息:;;整个图像内容可以表述为:...,回答如下问题:图片里内容是什么?, 注意不要复述提供的资料内容" } ``` ### 错误码 |错误码|描述| |------|---| ## 高级用法 目前该模块仅提供基础的图像内容理解。 ## 更新记录和贡献 * 图像内容理解 (2024-01) ================================================ FILE: python/core/components/image_understand/__init__.py ================================================ # Copyright (c) 2023 Baidu, Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. ================================================ FILE: python/core/components/image_understand/component.py ================================================ # Copyright (c) 2023 Baidu, Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. r"""图像内容理解""" import base64 import time from appbuilder.core.component import Component from appbuilder.core.message import Message from appbuilder.core._client import HTTPClient from appbuilder.core._exception import AppBuilderServerException from appbuilder.core.components.image_understand.model import * from typing import Generator, Union from appbuilder.utils.trace.tracer_wrapper import components_run_trace, components_run_stream_trace class ImageUnderstand(Component): r""" 图像内容理解组件,即对于输入的一张图片(可正常解码,且长宽比适宜)与问题,输出对图片的描述 Examples: .. code-block:: python import os import appbuilder os.environ["GATEWAY_URL"] = "..." os.environ["APPBUILDER_TOKEN"] = "..." # 从BOS存储读取样例文件 image_url = "https://bj.bcebos.com/v1/appbuilder/test_image_understand.jpeg?authorization=bce-auth-v1%2FALTAKGa8m4qCUasgoljdEDAzLm%2F2024-01-24T09%3A41%3A01Z%2F-1%2Fhost%2Fe8665506e30e0edaec4f1cc84a2507c4cb3fdb9b769de3a5bfe25c372b7e56e6" # 输入参数为一张图片 inp = Message(content={"url": image_url, "question": "图片里内容是什么?"}) # 进行图像内容理解 image_understand = ImageUnderstand() out = image_understand.run(inp) # 打印识别结果 print(out.content) """ name = "image_understanding" version = "v1" manifests = [ { "name": "image_understanding", "description": "可对输入图片进行理解,可输出图片描述、OCR 及图像识别结果", "parameters": { "type": "object", "properties": { "img_name": { "type": "string", "description": "待识别图片的文件名" }, "img_url": { "type": "string", "description": "待识别图片的url" } }, "anyOf": [ { "required": [ "img_name" ] }, { "required": [ "img_url" ] } ] } } ] @HTTPClient.check_param @components_run_trace def run(self, message: Message, timeout: float = None, retry: int = 0) -> Message: """ 执行图像内容理解 Args: message (Message): 输入图片或图片url下载地址用于执行识别操作. 举例: Message(content={"raw_image": b"...", "question": "图片主要内容是什么?"}) 或 Message(content={"url": "https://image/download/url", "question": "图片主要内容是什么?"}). timeout (float, optional): HTTP超时时间. 默认为 None. retry (int, optional): HTTP重试次数. 默认为 0. Returns: Message: 模型识别结果. """ inp = ImageUnderstandInMsg(**message.content) request = ImageUnderstandRequest() # 兼容新参数,确保输出结果一致 request.subject_detect = False request.llm_switch = False if inp.raw_image: request.image = base64.b64encode(inp.raw_image) if inp.url: request.url = inp.url if inp.question == "": raise ValueError("request format error, question is empty") if len(inp.question) > 100: raise ValueError(f"request format error, expected len(question)>100, got {len(inp.question)}") if inp.language != "zh-CN" and inp.language != "en": raise ValueError(f"request format error, expected language in ['zh-CN', 'en'], got {inp.language}") request.question = inp.question request.output_CHN = True if inp.language == "en": request.output_CHN = False response = self.__recognize(request, timeout, retry) out = ImageUnderstandOutMsg(description=response.result.description_to_llm) return Message(content=out.model_dump()) def __recognize( self, request: ImageUnderstandRequest, timeout: float = None, retry: int = 0, request_id: str = None, ) -> ImageUnderstandResponse: r"""调用底层接口进行图像内容理解 参数: request (obj: `ImageUnderstandRequest`) : 图像内容理解输入 返回: response (obj: `ImageUnderstandResponse`): 图像内容理解输出 """ if not request.image and not request.url: raise ValueError("request format error, one of image or url must be set") if retry != self.http_client.retry.total: self.http_client.retry.total = retry data = ImageUnderstandRequest.to_dict(request) headers = self.http_client.auth_header(request_id) headers['Content-Type'] = 'application/json' url = self.http_client.service_url("/v1/bce/aip/image-classify/v1/image-understanding/request") response = self.http_client.session.post(url, json=data, timeout=timeout, headers=headers) self.http_client.check_response_header(response) data = response.json() self.http_client.check_response_json(data) request_id = self.http_client.response_request_id(response) self.__class__.__check_create_task_service_error(request_id, data) task = ImageUnderstandTask(data, request_id=request_id) task_id = task.result.get("task_id", "") if task_id == "": raise AppBuilderServerException(request_id=request_id, service_err_message="empty task_id") url = self.http_client.service_url("/v1/bce/aip/image-classify/v1/image-understanding/get-result") while True: response = self.http_client.session.post(url, json={"task_id": task_id}, timeout=timeout, headers=headers) self.http_client.check_response_header(response) data = response.json() self.http_client.check_response_json(data) request_id = self.http_client.response_request_id(response) self.__class__.__check_service_error(request_id, data.get("result", {})) # 处理成功 response = ImageUnderstandResponse(data) if response.result.ret_code == 0: return ImageUnderstandResponse(data) # 还在处理中 if response.result.ret_code == 1: # 避免触发限流(>1QPS),等待1.1秒 time.sleep(1.1) @components_run_stream_trace def tool_eval( self, name: str, streaming: bool, origin_query: str = '图片内容有哪些', **kwargs, ) -> Union[Generator[str, None, None], str]: """ 用于工具的执行,调用底层接口进行图像内容理解 Args: name (str): 工具名 streaming (bool): 是否流式返回 origin_query (str): 用户原始query **kwargs: 工具调用的额外关键字参数 Returns: Union[Generator[str, None, None], str]: 图片内容理解结果 """ if origin_query is None or not origin_query.strip(): origin_query = '图片内容有哪些' traceid = kwargs.get("traceid") img_name = kwargs.get("img_name", "") img_url = kwargs.get("img_url", "") file_urls = kwargs.get("file_urls", {}) rec_res = self._recognize_w_post_process( img_name, img_url, file_urls, question=origin_query, request_id=traceid ) if streaming: yield { "type": "text", "text": rec_res, "visible_scope": 'llm', } yield { "type": "text", "text": "", "visible_scope": 'user', } else: return rec_res def _recognize_w_post_process( self, img_name, img_url, file_urls, question="图片内容有哪些", request_id=None, ) -> str: r""" 参数: img_name (str): 图片文件名 img_url (bool): 图片url question (str): 询问有关图片内容的问题 file_urls (dict): 文件名与对应文件url的映射 返回: str: 图片内容理解结果 """ req = ImageUnderstandRequest() # 兼容新参数,确保输出结果一致 req.subject_detect = False req.llm_switch = False req.question = question if img_name in file_urls: req.url = file_urls[img_name] if img_url: if img_url in file_urls: img_url = file_urls[img_url] req.url = img_url response = self.__recognize(req, request_id=request_id) description_to_llm = response.result.description_to_llm description_processed = description_to_llm.rsplit("。", 2)[0] return description_processed @staticmethod def __check_service_error(request_id: str, data: dict): r"""个性化服务response参数检查 参数: request (dict) : 图像内容理解body返回 返回: 无 """ ret_code = data.get("ret_code", 0) if ret_code != 0 and ret_code != 1: raise AppBuilderServerException( request_id=request_id, service_err_code=data.get("ret_code", ""), service_err_message=data.get("ret_msg", "") ) @staticmethod def __check_create_task_service_error(request_id: str, data: dict): r"""个性化服务response参数检查 参数: request_id (str) : 任务请求ID data (dict): 响应数据 返回: 无 """ if "error_code" in data and "error_msg" in data: raise AppBuilderServerException( request_id=request_id, service_err_code=data.get("error_code", ""), service_err_message=data.get("error_msg", "") ) ================================================ FILE: python/core/components/image_understand/model.py ================================================ # Copyright (c) 2023 Baidu, Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Landmark recognition model.""" from typing import MutableMapping, List import proto from pydantic import BaseModel class ImageUnderstandRequest(proto.Message): r"""地标识别请求参数 属性: image (str, 可选): 图像base64编码结果. url (str, 可选): 图像下载链接,base64编码后结果小于4MB, 短边大于15px,长边小于4096px. question(str): 针对图片的问题信息,限制在100个字符之内 """ image: str = proto.Field( proto.STRING, number=1, ) url: str = proto.Field( proto.STRING, number=2, ) question: str = proto.Field( proto.STRING, number=3, ) output_CHN: bool = proto.Field( proto.BOOL, number=4 ) subject_detect: bool = proto.Field( proto.BOOL, number=5 ) llm_switch: bool = proto.Field( proto.BOOL, number=6 ) class ImageUnderstandTask(proto.Message): r"""地标识别返回结果 属性: log_id (int): 随机日志ID request_id(str): 服务链路追踪ID. result (MutableMapping[str, str]): {"task_id":"task-123"} """ request_id: str = proto.Field( proto.STRING, number=1, ) log_id: int = proto.Field( proto.INT64, number=2 ) result: MutableMapping[str, str] = proto.MapField( proto.STRING, proto.STRING, number=3, ) class ImageUnderstandLocation(proto.Message): """位置信息 属性: left (int): 表示定位位置的长方形左上顶点的水平坐标 top (int): 表示定位位置的长方形左上顶点的垂直坐标 width (int): 表示定位位置的长方形的宽度 height (int): 表示定位位置的长方形的高度 """ top: int = proto.Field( proto.INT32, number=1 ) left: int = proto.Field( proto.INT32, number=2 ) width: int = proto.Field( proto.INT32, number=3 ) height: int = proto.Field( proto.INT32, number=4 ) class ImageUnderstandSubject(proto.Message): """主题信息 属性: name (str): 主题名字 location (ImageUnderstandLocation): 主题位置 """ name: str = proto.Field( proto.STRING, number=1 ) location = proto.Field( ImageUnderstandLocation, number=2 ) class ImageUnderstandOCR(proto.Message): """主题信息 属性: word (str): 文本识别结果 rect (ImageUnderstandLocation): 位置信息 """ word: str = proto.Field( proto.STRING, number=1 ) rect = proto.Field( ImageUnderstandLocation, number=2 ) prob = proto.Field( proto.FLOAT, number=3 ) class ImageUnderstandResult(proto.Message): """主题信息 属性: task_id (str): 任务id ret_code (int): 返回错误码 ret_msg(str):错误信息 description(str):描述信息 description_to_llm(str):描述信息 subject_result(ImageUnderstandSubject):主题结果 ocr_result(ImageUnderstandOCR):ocr识别结果 classify_result(str):分类结果 """ task_id: str = proto.Field( proto.STRING, number=1 ) ret_code: int = proto.Field( proto.INT32, number=2 ) ret_msg: str = proto.Field( proto.STRING, number=3 ) description: str = proto.Field( proto.STRING, number=4 ) description_to_llm: str = proto.Field( proto.STRING, number=5, ) subject_result = proto.RepeatedField( ImageUnderstandSubject, number=6 ) ocr_result = proto.RepeatedField( ImageUnderstandOCR, number=7, ) classify_result = proto.RepeatedField( proto.STRING, number=8 ) class ImageUnderstandResponse(proto.Message): """主题信息 属性: request_id (str): 请求id log_id (int): 日志ID result(ImageUnderstandResult):图像理解结果 """ request_id: str = proto.Field( proto.STRING, number=1, ) log_id: int = proto.Field( proto.INT64, number=2 ) result = proto.Field( ImageUnderstandResult, number=3 ) class ImageUnderstandInMsg(BaseModel): """ 图像理解输入消息 属性: raw_image(bytes): 图像原始内容 url(str): 图像下载链接 """ raw_image: bytes = b'' url: str = "" question: str = "" language: str = "zh-CN" class ImageUnderstandOutMsg(BaseModel): """ 图像理解输出结果 属性: description(str): 输出描述信息 """ description: str = "" ================================================ FILE: python/core/components/landmark_recognize/README.md ================================================ # 地标识别(LandmarkRecognition) ## 简介 地标识别组件(LandmarkRecognition)可以识别12万中外著名地标、热门景点,可返回地标名称。 ### 功能介绍 识别中外著名地标、热门景点,可返回地标名称 ### 特色优势 可以识别12万中外著名地标、热门景点 ### 应用场景 地点识别 ## 基本用法 下面是地标识别的代码示例: 示例图片为:![示例图片](https://bj.bcebos.com/v1/appbuilder/landmark_test.jpeg?authorization=bce-auth-v1%2FALTAKGa8m4qCUasgoljdEDAzLm%2F2024-01-11T10%3A59%3A56Z%2F-1%2Fhost%2Fc249a068c6f321b91da0d0fd629b26ded58dcac2b6a3674f32378f5eb8df1ed0) ```python import os import requests import appbuilder # 请前往千帆AppBuilder官网创建密钥,流程详见:https://cloud.baidu.com/doc/AppBuilder/s/Olq6grrt6#1%E3%80%81%E5%88%9B%E5%BB%BA%E5%AF%86%E9%92%A5 os.environ["APPBUILDER_TOKEN"] = '...' # 从BOS存储读取样例文件 image_url = "https://bj.bcebos.com/v1/appbuilder/landmark_test.jpeg?" \ "authorization=bce-auth-v1%2FALTAKGa8m4qCUasgoljdEDAzLm%2F2024-01-" \ "11T10%3A59%3A56Z%2F-1%2Fhost%2Fc249a068c6f321b91" \ "da0d0fd629b26ded58dcac2b6a3674f32378f5eb8df1ed0" raw_image = requests.get(image_url).content # 输入参数为一张图片 inp = appbuilder.Message(content={"raw_image": raw_image}) # 进行地标识别 landmark_recognize = appbuilder.LandmarkRecognition() out = landmark_recognize.run(inp) # 打印识别结果 print(out.content) # eg: {"landmark": "尼罗河"} ``` ## 参数说明 ### 鉴权说明 使用组件之前,请首先申请并设置鉴权参数,可参考[组件使用流程](https://cloud.baidu.com/doc/AppBuilder/s/Olq6grrt6#1%E3%80%81%E5%88%9B%E5%BB%BA%E5%AF%86%E9%92%A5)。 ```python import os os.environ["APPBUILDER_TOKEN"] = "..." ``` ### 初始化参数 无 ### 调用参数 | 参数名称 | 参数类型 | 是否必须 | 描述 |示例值| |------------|--------|------|-----------------------------|---| | message | String | 是 | 输入的消息,用于模型的主要输入内容。这是一个必需的参数 || | +content | Dict | 是 | 消息内容 || | +raw_image | String | 否 | 原始图片字节流 || | +url | String | 否 | 图片下载链接地址 || |timeout| Float | 否 | HTTP超时时间,单位:秒 |1|| |retry|Integer| 否 | HTTP重试次数 |3|| ### 响应参数 | 参数名称 | 参数类型 | 描述 | 示例值 | |----------|------|------|--------| | landmark | str | 地标名字 | 比如:尼罗河 | ### 响应示例 ```json {"landmark": "尼罗河"} ``` ### 错误码 |错误码|描述| |------|---| ## 高级用法 目前该模块仅提供基础的地标识别。 ## 更新记录和贡献 * 地标识别 (2024-01) ================================================ FILE: python/core/components/landmark_recognize/__init__.py ================================================ # Copyright (c) 2023 Baidu, Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. ================================================ FILE: python/core/components/landmark_recognize/component.py ================================================ # Copyright (c) 2023 Baidu, Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. r"""landmark recognize component.""" import base64 from appbuilder.core.component import Component from appbuilder.core.message import Message from appbuilder.core._client import HTTPClient from appbuilder.core._exception import AppBuilderServerException from appbuilder.core.components.landmark_recognize.model import * from appbuilder.utils.trace.tracer_wrapper import components_run_trace, components_run_stream_trace class LandmarkRecognition(Component): r""" 识别地标组件,即对于输入的一张图片(可正常解码,且长宽比适宜),输出图片中的地标识别结果 Examples: .. code-block:: python import appbuilder os.environ["APPBUILDER_TOKEN"] = '...' landmark_recognize = appbuilder.LandmarkRecognition() with open("xxxx.jpg", "rb") as f: inp = appbuilder.Message(content={"raw_image": f.read()}) out = landmark_recognize.run(inp) # 打印识别结果 print(out.content) # eg: {"landmark": "狮身人面相"} """ @HTTPClient.check_param @components_run_trace def run(self, message: Message, timeout: float = None, retry: int = 0) -> Message: """ 执行地标识别任务 Args: message (Message): 输入消息对象,包含待识别的图片或图片URL。 例如:Message(content={"raw_image": b"..."}) 或 Message(content={"url": "https://image/download/url"})。 timeout (float, optional): HTTP请求的超时时间。默认为None。 retry (int, optional): HTTP请求的重试次数。默认为0。 Returns: Message: 地标识别结果的消息对象。 例如:Message(content={"landmark": b"狮身人面像"}) """ inp = LandmarkRecognitionInMsg(**message.content) request = LandmarkRecognitionRequest() if inp.raw_image: request.image = base64.b64encode(inp.raw_image) if inp.url: request.url = inp.url response = self.__recognize(request, timeout, retry) out = LandmarkRecognitionOutMsg(landmark=response.result.get("landmark", "")) return Message(content=out.model_dump()) def __recognize(self, request: LandmarkRecognitionRequest, timeout: float = None, retry: int = 0) -> LandmarkRecognitionResponse: r"""调用底层接口进行地标识别 参数: request (obj: `LandmarkRecognitionRequest`) : 地标识别输入参数 返回: response (obj: `LandmarkRecognitionResponse`): 地标识别返回结果 """ if not request.image and not request.url: raise ValueError("request format error, one of image or url must be set") data = LandmarkRecognitionRequest.to_dict(request) if retry != self.http_client.retry.total: self.http_client.retry.total = retry headers = self.http_client.auth_header() headers['content-type'] = 'application/x-www-form-urlencoded' url = self.http_client.service_url("/v1/bce/aip/image-classify/v1/landmark") response = self.http_client.session.post(url, data=data, timeout=timeout, headers=headers) self.http_client.check_response_header(response) data = response.json() self.http_client.check_response_json(data) request_id = self.http_client.response_request_id(response) self.__class__.__check_service_error(request_id, data) return LandmarkRecognitionResponse(data, request_id=request_id) @staticmethod def __check_service_error(request_id: str, data: dict): r"""个性化服务response参数检查 参数: request (dict) : 地标识别body返回 返回: 无 """ if "error_code" in data or "error_msg" in data: raise AppBuilderServerException( request_id=request_id, service_err_code=data.get("error_code"), service_err_message=data.get("error_msg") ) ================================================ FILE: python/core/components/landmark_recognize/model.py ================================================ # Copyright (c) 2023 Baidu, Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Landmark recognition model.""" from typing import MutableMapping import proto from pydantic import BaseModel class LandmarkRecognitionRequest(proto.Message): r"""地标识别请求参数 属性: image (str, 可选): 图像base64编码结果. url (str, 可选): 图像下载链接,base64编码后结果小于4MB, 短边大于15px,长边小于4096px. """ image: str = proto.Field( proto.STRING, number=1, optional=True, ) url: str = proto.Field( proto.STRING, number=2, optional=True, ) class LandmarkRecognitionResponse(proto.Message): r"""地标识别返回结果 属性: log_id (int): 随机日志ID result (MutableMapping[str, str]): 地标识别结果, eg: {"landmark": "狮身人面像"}. request_id(str): 服务链路追踪ID. """ log_id: int = proto.Field( proto.INT64, number=1 ) result: MutableMapping[str, str] = proto.MapField( proto.STRING, proto.STRING, number=2, ) request_id: str = proto.Field( proto.STRING, number=3, ) class LandmarkRecognitionInMsg(BaseModel): """ 地标识别输入消息 属性: raw_image(bytes): 图像原始内容 url(str): 图像下载链接 """ raw_image: bytes = b'' url: str = "" class LandmarkRecognitionOutMsg(BaseModel): """ 地标识别输出消息 属性: landmark(str): 地标识别结果 """ landmark: str ================================================ FILE: python/core/components/llms/__init__.py ================================================ # Copyright (c) 2023 Baidu, Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. ================================================ FILE: python/core/components/llms/base.py ================================================ # Copyright (c) 2023 Baidu, Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import itertools import json import os import uuid from enum import Enum import logging import requests import copy import collections.abc from appbuilder.core.constants import GATEWAY_URL, GATEWAY_INNER_URL from pydantic import BaseModel, Field, ValidationError, HttpUrl, validator from pydantic.types import confloat from appbuilder.core.component import Component from appbuilder.core.message import Message, _T from appbuilder.utils.logger_util import logger from typing import Dict, List, Optional, Any from appbuilder.core.component import ComponentArguments from appbuilder.core.utils import ModelInfo, ttl_lru_cache from appbuilder.utils.sse_util import SSEClient from appbuilder.core._exception import AppBuilderServerException, ModelNotSupportedException class LLMMessage(Message): content: Optional[_T] = {} extra: Optional[Dict] = {} token_usage: Optional[Dict] = {} def __str__(self): return f"Message(name={self.name}, content={self.content}, " \ f"mtype={self.mtype}, extra={self.extra}, token_usage={self.token_usage})" def __deepcopy__(self, memo): new_instance = self.__class__() memo[id(self)] = new_instance for k, v in self.__dict__.items(): if k == "content" and isinstance(v, collections.abc.Iterator): pass else: setattr(new_instance, k, copy.deepcopy(v, memo)) return new_instance class CompletionRequest(object): r"""ShortSpeechRecognitionRequest.""" params = None response_mode = "blocking" def __init__(self, params: Dict[str, Any] = None, response_mode: str = None, **kwargs): r""" __init__ the client state. """ self.params = params self.response_mode = response_mode class ModelArgsConfig(BaseModel): stream: bool = Field(default=False, description="是否流式响应。默认为 False。") temperature: float = Field(default=1e-10,gt=0.0, le=1.0 ,description="模型的温度参数,范围从 0.0 到 1.0。") top_p: float= Field(default=1e-10, ge=0.0, le=1.0, description="模型的top_p参数,范围从 0.0 到 1.0。") max_output_tokens: int = Field(default=1024, ge=2, description="最大输出token数。") disable_search: bool = Field(default=True, description="是否禁用搜索。默认为 True") response_format: str = Field(default="text", description="响应格式,可选项有text、json_object") stop: list[str] = Field(default=[], description="停止词列表。", max_length=4) class CompletionResponse(object): r"""ShortSpeechRecognitionResponse.""" error_no = 0 error_msg = "" result = None log_id = "" extra = None token_usage = {} def __init__(self, response, stream: bool = False): """初始化客户端状态。""" self.error_no = 0 self.error_msg = "" self.log_id = response.headers.get("X-Appbuilder-Request-Id", None) self.extra = {} self.token_usage = {} if stream: # 流式数据处理 def stream_data(): sse_client = SSEClient(response) for event in sse_client.events(): if not event: continue answer = self.parse_stream_data(event) if answer is not None: yield answer self.result = stream_data() else: # 非流式数据的处理 if response.status_code != 200: self.error_no = response.status_code self.error_msg = "error" self.result = response.text raise AppBuilderServerException(self.log_id, self.error_no, self.result) else: data = response.json() if data.get("code") and "message" in data: raise AppBuilderServerException(self.log_id, data["code"], data["message"]) if "code" in data and "message" in data and "requestId" in data: raise AppBuilderServerException(self.log_id, data["code"], data["message"]) if "code" in data and "message" in data and "status" in data: raise AppBuilderServerException(self.log_id, data["code"], data["message"]) self.result = data.get("answer", None) trace_log_list = data.get("trace_log", None) if trace_log_list is not None: for trace_log in trace_log_list: key = trace_log["tool"] result_list = trace_log["result"] result_list = ResultProcessor.process(key, result_list) self.extra[key] = result_list self.token_usage = data.get("usage", {}) def parse_stream_data(self, event): """解析流式数据块并提取answer字段""" parsed_str = event.data raw_str = event.raw if parsed_str: try: data = json.loads(parsed_str) if data.get("code") and "message" in data: raise AppBuilderServerException(self.log_id, data["code"], data["message"]) if "code" in data and "message" in data and "requestId" in data: raise AppBuilderServerException(self.log_id, data["code"], data["message"]) if "code" in data and "message" in data and "status" in data: raise AppBuilderServerException(self.log_id, data["code"], data["message"]) return data except json.JSONDecodeError: # 处理可能的解析错误 logging.error("failed to parse: " + parsed_str) raise AppBuilderServerException("unknown", "unknown", parsed_str) else: try: data = json.loads(raw_str) if "code" in data and "message" in data: raise AppBuilderServerException(self.log_id, data["code"], data["message"]) return data except json.JSONDecodeError: # 处理解析错误 logging.error("failed to parse: " + raw_str) raise AppBuilderServerException("unknown", "unknown", raw_str) def get_stream_data(self): """获取处理过的流式数据的迭代器""" return self.result def to_message(self): """将响应结果转换为Message对象。 Returns: Message: Message对象。 """ message = LLMMessage() message.id = self.log_id message.content = self.result message.extra = self.extra message.token_usage = self.token_usage return self.message_iterable_wrapper(message) def message_iterable_wrapper(self, message): """ 对模型输出的 Message 对象进行包装。 当 Message 是流式数据时,数据被迭代完后,将重新更新 content 为 blocking 的字符串。 """ class IterableWrapper: def __init__(self, stream_content): self._content = stream_content self._concat = "" self._token_usage = {} def __iter__(self): return self def __next__(self): try: result_json = next(self._content) char = result_json.get("answer", "") result_list = result_json.get("result") key = result_json.get("tool") if result_list is not None: result_list = ResultProcessor.process(key, result_list) message.extra = {key: result_list} # Update the original extra else: message.extra = {} if "usage" in result_json: self._token_usage = result_json.get("usage") message.token_usage = self._token_usage self._concat += char return char except StopIteration: message.content = self._concat # Update the original content raise from collections.abc import Generator if isinstance(message.content, Generator): # Replace the original content with the custom iterable message.content = IterableWrapper(message.content) return message class ResultProcessor: @staticmethod def process(key, result_list): if key == 'search_baidu': rename_fields = { 'id': 'url', 'mock_id': 'ref_id', 'content': 'content', 'title': 'title', 'icon': 'icon', 'site_name': 'site_name', } renamed_list = [] for result in result_list: renamed_list.append({rename_fields[k]: v for k, v in result.items() if k in rename_fields}) return renamed_list elif key == 'search_db': return result_list else: raise TypeError(f"illegal argument key, expected key in {'search_baidu','search_db'}, got {key}") class CompletionBaseComponent(Component): name: str version: str base_url: str = "/rpc/2.0/cloud_hub/v1/ai_engine/copilot_engine" model_name: str = "" model_url: str = "" model_type: str = "chat" excluded_models: List[str] = ["DeepSeek-V3.1", "ChatLaw"] model_info: ModelInfo = None model_config: Dict[str, Any] = { "model": { "provider": "baidu", "name": "ERNIE-Bot", "completion_params": { "temperature": 1e-10, "top_p": 0, } } } def __init__( self, meta: ComponentArguments, model: str = None, secret_key: Optional[str] = None, gateway: str = "", lazy_certification: bool = False, **kwargs ): """ Args: meta (ComponentArguments): 组件参数信息 model (str, optional): 模型名称. Defaults to None. secret_key (Optional[str], optional): 可选的密钥. Defaults to None. gateway (str, optional): 网关地址. Defaults to "". lazy_certification (bool, optional): 延迟认证,为True时在第一次运行时认证. Defaults to False. **kwargs: 其他关键字参数 """ super(CompletionBaseComponent, self).__init__( meta=meta, secret_key=secret_key, gateway=gateway, lazy_certification=lazy_certification) self.model_name = model self.version = self.version if not lazy_certification: self._check_model_and_get_model_url(self.model_name, self.model_type) @ttl_lru_cache(seconds_to_live=1 * 60 * 60) # 1h def set_secret_key_and_gateway(self, secret_key: Optional[str] = None, gateway: str = ""): super(CompletionBaseComponent, self).set_secret_key_and_gateway( secret_key=secret_key, gateway=gateway) # 不用重新获取列表 if os.environ.get("PRIVATE_AB", "OFF") == "OFF": self.__class__.model_info = ModelInfo(client=self.http_client) def set_model_info(self, model_name: str, model_url: str): """为llm component设置模型信息""" self.model_name = model_name self.model_url = model_url @ttl_lru_cache(seconds_to_live=1 * 60 * 60) # 1h def _check_model_and_get_model_url(self, model, model_type): if model and model in self.excluded_models: raise ModelNotSupportedException(f"unsupport model, epected model in {self.excluded_models}, got {model}") if not model: raise ValueError("illegal argument, model_name can't be empty") if self.__class__.model_info is None: self.set_secret_key_and_gateway() m_type = self.model_info.get_model_type(model) if m_type != model_type: raise ModelNotSupportedException( f"unsupport model_type for model {model}, expected model_type in {model_type}, got {m_type}") model_url = self.model_info.get_model_url(model) return model_url def gene_request(self, query, inputs, response_mode, message_id, model_config): """"send request""" data = { "query": query, "inputs": inputs, "response_mode": response_mode, "user": message_id, "model_config": model_config } request = CompletionRequest(data, response_mode) return request def gene_response(self, response, stream: bool = False): """generate response""" response = CompletionResponse(response, stream) return response def run(self, *args, **kwargs): """ Run the model with given input and return the result. Args: **kwargs: Keyword arguments for both StyleWritingComponent and common component inputs. Returns: obj:`Message`: Output message after running model. """ timeout = kwargs.get('timeout') retry = kwargs.get('retry', 0) request_id = kwargs.get('request_id') specific_params = {k: v for k, v in kwargs.items() if k in self.meta.model_fields} model_config_params = {k: v for k, v in kwargs.items() if k in ModelArgsConfig.model_fields} # 不在timeout、retry、request_id、specific_params、model_config_params中的参数 other_params = {k: v for k, v in kwargs.items() if k not in [ 'timeout', 'retry', 'request_id' ] + list(specific_params.keys()) + list(model_config_params.keys()) } try: specific_inputs = self.meta(**specific_params) model_config_inputs = ModelArgsConfig(**model_config_params) except ValidationError as e: raise ValueError(e) query, inputs, response_mode, user_id = self.get_compeliton_params(specific_inputs, model_config_inputs) model_config = self.get_model_config(model_config_inputs, other_params) request = self.gene_request(query, inputs, response_mode, user_id, model_config) response = self.completion( version=self.version, base_url=self.base_url, request=request, timeout=timeout, retry=retry, request_id=request_id ) if response.error_no != 0: raise AppBuilderServerException(service_err_code=response.error_no, service_err_message=response.error_msg) return response.to_message() def get_compeliton_params(self, specific_inputs, model_config_inputs): """获取模型请求参数""" inputs = specific_inputs.extract_values_to_dict() query = inputs["query"] user_id = str(uuid.uuid4()) if model_config_inputs.stream: response_mode = "streaming" else: response_mode = "blocking" return query, inputs, response_mode, user_id def get_model_config(self, model_config_inputs: ModelArgsConfig, other_params: dict = {}): """获取模型配置信息""" self.model_config["model"]["name"] = self.model_name # 不需要进行地址替换 if os.environ.get("PRIVATE_AB", "false") == "false": model_url = self._check_model_and_get_model_url(self.model_name, self.model_type) if model_url: self.model_config["model"]["url"] = model_url elif os.environ.get("PRIVATE_AB", "false") == "true": if self.model_url: self.model_config["model"]["url"] = self.model_url self.model_config["model"]["completion_params"]["temperature"] = model_config_inputs.temperature self.model_config["model"]["completion_params"]["top_p"] = model_config_inputs.top_p self.model_config["model"]["completion_params"]["max_output_tokens"] = model_config_inputs.max_output_tokens self.model_config["model"]["completion_params"]["disable_search"] = model_config_inputs.disable_search self.model_config["model"]["completion_params"]["response_format"] = model_config_inputs.response_format self.model_config["model"]["completion_params"]["stop"] = model_config_inputs.stop if len(other_params) > 0: logger.info("Some paramters are not expected by the model configuration, we assume they will be used in llm completion api") for k, v in other_params.items(): self.model_config["model"]["completion_params"][k] = v logger.info("Add parameter: {}, value: {} in completion_params.".format(k, v)) return self.model_config def completion( self, version, base_url, request: CompletionRequest, timeout: float = None, retry: int = 0, request_id: str = None, ) -> CompletionResponse: r"""Send a byte array of an audio file to obtain the result of speech recognition.""" headers = self.http_client.auth_header(request_id) headers["Content-Type"] = "application/json" completion_url = "/" + self.version + "/api/llm/" + self.name stream = True if request.response_mode == "streaming" else False url = self.http_client.service_url(completion_url, self.base_url) response = self.http_client.session.post(url, json=request.params, headers=headers, timeout=timeout, stream=stream) return self.gene_response(response, stream) @staticmethod def check_service_error(data: dict): r"""check service internal error. :param: data: dict, service return body data. :rtype: . """ if "err_no" in data and "err_msg" in data: if data["err_no"] != 0: raise AppBuilderServerException(service_err_code=data["err_no"], service_err_message=data["err_msg"]) ================================================ FILE: python/core/components/llms/dialog_summary/README.md ================================================ # 会话小结(DialogSummary) ## 简介 会话小结(DialogSummary)基于生成式大模型对一段用户与坐席的对话生成总结,结果按{"诉求": "", "回应": "", "解决情况": ""}格式输出。适用于运营商、金融、汽车等多种场景的对话总结。 ### 功能介绍 基于生成式大模型对一段用户与坐席的对话生成总结。 ### 特色优势 基于生成式大模型对一段用户与坐席的对话生成总结,结果按{"诉求": "", "回应": "", "解决情况": ""}格式输出。 ### 应用场景 适用于运营商、金融、汽车等多种场景的对话总结。 ## 基本用法 为了快速开始使用会话小结组件,您可以参考以下步骤: ```python import appbuilder import os # 请前往千帆AppBuilder官网创建密钥,流程详见:https://cloud.baidu.com/doc/AppBuilder/s/Olq6grrt6#1%E3%80%81%E5%88%9B%E5%BB%BA%E5%AF%86%E9%92%A5 os.environ["APPBUILDER_TOKEN"] = "bce-YOURTOKEN" dialog_summary = appbuilder.DialogSummary("DeepSeek-V3.1") text = "用户:喂我想查一下我的话费\n坐席:好的女士您话费余的话还有87.49元钱\n用户:好的知道了谢谢\n坐席:嗯不客气祝您生活愉快再见" answer = dialog_summary(appbuilder.Message(text)) print(answer) ``` ## 参数说明 ### 鉴权配置 使用组件之前,请首先申请并设置鉴权参数,可参考[组件使用流程](https://cloud.baidu.com/doc/AppBuilder/s/Olq6grrt6#1%E3%80%81%E5%88%9B%E5%BB%BA%E5%AF%86%E9%92%A5)。 ```python # 设置环境中的TOKEN,以下示例略 os.environ["APPBUILDER_TOKEN"] = "bce-YOURTOKEN" ``` ### 初始化参数 - `model` (str|None): 模型名称,用于指定要使用的千帆模型。 ### 调用参数 ### 调用参数 |参数名称 |参数类型 | 是否必须 | 描述 | 示例值 | |--------|--------|---|-----------------------------------------------------------------------------|---------------| |message |Message | 是 | 输入消息,包含用户提出的问题。 | Message("你好") | |stream|bool| 否 | 是否以流式形式返回响应 | False | |temperature|float| 否 | 模型配置的温度参数,用于调整模型的生成概率。取值范围为 0.0 到 1.0,其中较低的值使生成更确定性,较高的值使生成更多样性。默认值为 1e-10。 | 0.0001 | ### 响应参数 |参数名称 |参数类型 |描述 |示例值| |--------|--------|----|------| |result |Message |返回结果|对象,包含模型运行后的输出消息。| ### 响应示例 ```json {"result": ["您话费余的话还有87.49元钱"]} ``` ### 错误码 无 ## 高级用法 暂无 ## 示例和案例研究 目前暂无具体的实际应用案例。 ## API文档 暂无 ## 更新记录和贡献 * 会话小结更新Readme (2023-12) ================================================ FILE: python/core/components/llms/dialog_summary/__init__.py ================================================ """DialogSummary""" from .component import DialogSummary ================================================ FILE: python/core/components/llms/dialog_summary/base.py ================================================ # Copyright (c) 2023 Baidu, Inc. All Rights Reserved. # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from pydantic import Field from appbuilder.core.message import Message from appbuilder.core.component import ComponentArguments class DialogSummaryArgs(ComponentArguments): """ 会话小结生成配置 Attributes: message (Message): 输入对话文本,用于生成小结 """ message: Message = Field(..., variable_name='query', description='输入对话文本,用于生成小结') ================================================ FILE: python/core/components/llms/dialog_summary/component.py ================================================ # Copyright (c) 2023 Baidu, Inc. All Rights Reserved. # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from typing import Optional from appbuilder.core.message import Message from appbuilder.core.components.llms.base import CompletionBaseComponent from appbuilder.utils.trace.tracer_wrapper import components_run_trace, components_run_stream_trace from .base import DialogSummaryArgs class DialogSummary(CompletionBaseComponent): r""" 会话小结大模型组件, 基于生成式大模型对一段用户与坐席的对话生成总结,结果按{"诉求": "", "回应": "", "解决情况": ""}格式输出。 Examples: .. code-block:: python import app import os # 请前往千帆AppBuilder官网创建密钥,流程详见:https://cloud.baidu.com/doc/AppBuilder/s/Olq6grrt6#1%E3%80%81%E5%88%9B%E5%BB%BA%E5%AF%86%E9%92%A5 os.environ["APPBUILDER_TOKEN"] = '...' dialog_summary = appbuilder.DialogSummary("DeepSeek-V3.1") text = "用户:喂我想查一下我的话费\n坐席:好的女士您话费余的话还有87.49元钱\n用户:好的知道了谢谢\n坐席:嗯不客气祝您生活愉快再见" answer = dialog_summary(appbuilder.Message(text)) print(answer) """ name = "dialog_summary" version = "v1" meta = DialogSummaryArgs manifests = [ { "name": "dialog_summary", "description": "基于输入的对话,用大模型对该段对话生成总结, 结果按{\"诉求\": \"\", \"回应\": \"\", \"解决情况\": \"\"}格式输出。", "parameters": { "type": "object", "properties": { "query": { "type": "string", "description": "输入的对话,用于大模型根据该对话生成总结。" } }, "required": [ "query" ] } } ] def __init__( self, model=None, secret_key: Optional[str] = None, gateway: str = "", lazy_certification: bool = False, **kwargs ): """初始化DialogSummary模型。 Args: model (str|None): 模型名称,用于指定要使用的千帆模型。 secret_key (str, 可选): 用户鉴权token, 默认从环境变量中获取: os.getenv("APPBUILDER_TOKEN", ""). gateway (str, 可选): 后端网关服务地址,默认从环境变量中获取: os.getenv("GATEWAY_URL", "") lazy_certification (bool, 可选): 延迟认证,为True时在第一次运行时认证. Defaults to False. Returns: None """ super().__init__( DialogSummaryArgs, model=model, secret_key=secret_key, gateway=gateway, lazy_certification=lazy_certification) @components_run_trace def run(self, message, stream=False, temperature=1e-10, top_p=0): """ 使用给定的输入运行模型并返回结果。 Args: message (obj:`Message`): 输入消息,用于模型的主要输入内容。这是一个必需的参数。 stream (bool, optional): 指定是否以流式形式返回响应。默认为 False。 temperature (float, optional): 模型配置的温度参数,用于调整模型的生成概率。 取值范围为 0.0 到 1.0,其中较低的值使生成更确定性,较高的值使生成更多样性。 默认值为 1e-10。 top_p (float, optional): 影响输出文本的多样性,取值越大,生成文本的多样性越强。 取值范围为 0.0 到 1.0,其中较低的值使生成更确定性,较高的值使生成更多样性。 默认值为 0。 Returns: obj:`Message`: 模型运行后的输出消息。 """ return super().run(message=message, stream=stream, temperature=temperature, top_p=top_p) @components_run_stream_trace def tool_eval(self, name: str, streaming: bool = False, **kwargs): """ tool_eval for function call """ traceid = kwargs.get("traceid") query = kwargs.get("query", None) if not query: raise ValueError("param `query` is required") msg = Message(query) model_configs = kwargs.get('model_configs', {}) temperature = model_configs.get("temperature", 1e-10) top_p = model_configs.get("top_p", 0.0) message = super().run(message=msg, stream=False, temperature=temperature, top_p=top_p, request_id=traceid) if streaming: yield str(message.content) else: return str(message.content) ================================================ FILE: python/core/components/llms/hallucination_detection/README.md ================================================ # 幻觉检测(Hallucination Detection) ## 简介 幻觉检测(Hallucination Detection)针对问答场景,检测答案中是否存在幻觉。 ### 功能介绍 幻觉检测(Hallucination Detection)针对问答场景,检测答案中是否存在幻觉。 ### 特色优势 无。 ### 应用场景 问答场景,比如RAG问答。 ## 基本用法 下面是幻觉检测的代码示例: ```python import os import appbuilder # 请前往千帆AppBuilder官网创建密钥,流程详见:https://cloud.baidu.com/doc/AppBuilder/s/Olq6grrt6#1%E3%80%81%E5%88%9B%E5%BB%BA%E5%AF%86%E9%92%A5 os.environ['APPBUILDER_TOKEN'] = '...' query = '澳门新麻蒲烤肉店每天开门吗?' context = \ '''澳门美食: 澳门新麻蒲韩国烤肉店 在澳门一年四季之中除了火锅,烤肉也相当受欢迎。提到韩烧,有一间令我印象最深刻,就是号称韩国第一的烤肉店-新麻蒲韩国烤肉店,光是韩国的分店便多达四百多间,海外分店更是遍布世界各地,2016年便落户澳门筷子基区,在原本已经食肆林立的地方一起百花齐放!店内的装修跟韩国分店还完度几乎没差,让食客彷如置身于韩国的感觉,还要大赞其抽风系统不俗,离开时身上都不会沾上烤肉味耶! 时间:周一至周日 下午5:00 - 上午3:00 电话:+853 2823 4012 地址:澳门筷子基船澳街海擎天第三座地下O号铺96号 必食推介: 护心肉二人套餐 来新麻蒲必试的有两样东西,现在差不多每间烤肉店都有炉边烤蛋,但大家知道吗?原来新麻蒲就是炉边烤蛋的开创者,既然是始祖,这已经是个非吃不可的理由!还有一款必试的就是护心肉,即是猪的横隔膜与肝中间的部分,每头猪也只有200克这种肉,非常珍贵,其味道吃起来有种独特的肉香味,跟牛护心肉一样精彩! 秘制猪皮 很多怕胖的女生看到猪皮就怕怕,但其实猪皮含有大量胶原蛋白,营养价值很高呢!这里红通通的猪皮还经过韩国秘制酱汁处理过,会有一点点辣味。烤猪皮的时候也需特别注意火侯,这样吃起来才会有外脆内Q的口感!''' answer = '澳门新麻蒲烤肉店并不是每天开门。' #! 该组件推荐使用DeepSeek-V3.1模型。 hallucination_detection = appbuilder.HallucinationDetection('DeepSeek-V3.1') inputs = {'query': query, 'context': context, 'answer': answer} msg = appbuilder.Message(inputs) result = hallucination_detection.run(msg) print(result) ``` ## 参数说明 ### 鉴权说明 使用组件之前,请首先申请并设置鉴权参数,可参考[组件使用流程](https://cloud.baidu.com/doc/AppBuilder/s/Olq6grrt6#1%E3%80%81%E5%88%9B%E5%BB%BA%E5%AF%86%E9%92%A5)。 ```python # 设置环境中的TOKEN,以下示例略 os.environ["APPBUILDER_TOKEN"] = "bce-YOURTOKEN" ``` ### 初始化参数 | 参数名称 | 参数类型 | 是否必须 | 描述 | 示例值 | | ------- | ------- | -------- | -------- | -------- | | `model` | str | 是 | 模型名称,用于指定要使用的千帆模型。推荐使用DeepSeek-V3.1模型。 | DeepSeek-V3.1 | | `secret_key` | str | 否 | 用户鉴权token,默认从环境变量中获取: `os.getenv("APPBUILDER_TOKEN", "")` | bce-v3/XXX | | `gateway` | str | 否 | 后端网关服务地址,默认从环境变量中获取: `os.getenv("GATEWAY_URL", "")` | https://appbuilder.baidu.com | | `lazy_certification` | bool | 否 | 延迟认证,为True时在第一次运行时认证。默认为False。 | False | ### 调用参数 | 参数名称 | 参数类型 | 是否必须 | 描述 | 示例值 | | ------- | ------- | -------- | -------- | -------- | | `message` | obj | 是 | 输入信息,用于传入用户查询query、根据query得到的检索结果context和基于context生成的query的答案answer。 | Message(content={'query': '...', 'context': '...', 'answer': '...'}) | | `stream` | bool | 否 | 指定是否以流式形式返回响应。默认为 False。 | False | | `temperature` | float | 否 | 模型配置的温度参数,用于调整模型的生成概率。取值范围为 0.0 到 1.0,其中较低的值使生成更确定性,较高的值使生成更多样性。默认值为 1e-10。 | 0.1 | | `top_p` | float | 否 | 影响输出文本的多样性,取值越大,生成文本的多样性越强。取值范围为 0.0 到 1.0,其中较低的值使生成更确定性,较高的值使生成更多样性。默认值为 0.0。 | 0.0 | ### 响应参数 | 参数名称 | 参数类型 | 描述 | 示例值 | | ------- | ------- | -------- | -------- | | `result` | obj | 模型运行后的输出结果(可通过result.content获取结果核心内容) | Message(content='...') | ### 响应示例 ``` Message(name=msg, content=存在幻觉, mtype=dict, extra={}, token_usage={'prompt_tokens': 748, 'completion_tokens': 2, 'total_tokens': 750}) ``` ### 错误码 |错误码|描述| | ------ | ------ | ## 高级用法 可用于RAG问答的答案检测。 ## 更新记录和贡献 ### 2024.5.22 #### [Added] - 增加幻觉检测组件。 - 增加幻觉检测组件单元测试。 ================================================ FILE: python/core/components/llms/hallucination_detection/__init__.py ================================================ from .component import HallucinationDetection ================================================ FILE: python/core/components/llms/hallucination_detection/base.py ================================================ # Copyright (c) 2023 Baidu, Inc. All Rights Reserved. # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from pydantic import Field from appbuilder.core.component import ComponentArguments class HallucinationDetectionArgs(ComponentArguments): """ 幻觉检测配置 Attributes: query: str 用户查询。 context: str 根据query得到的检索结果。 answer: str 基于context生成的query的答案。 """ query: str = Field(..., valiable_name='query', description='用户查询。') context: str = Field(..., valiable_name='context', description='根据query得到的检索结果。') answer: str = Field(..., valiable_name='answer', description='基于context生成的query的答案。') ================================================ FILE: python/core/components/llms/hallucination_detection/component.py ================================================ # Copyright (c) 2023 Baidu, Inc. All Rights Reserved. # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from pydantic import BaseModel, Field from typing import Optional from appbuilder.core.components.llms.base import CompletionBaseComponent, ModelArgsConfig from appbuilder.core.message import Message from appbuilder.core._exception import AppBuilderServerException from appbuilder.utils.trace.tracer_wrapper import components_run_trace, components_run_stream_trace from .base import HallucinationDetectionArgs class HallucinationDetection(CompletionBaseComponent): """ 幻觉检测。输入,判断answer中是否存在幻觉。 *注:该组件推荐使用DeepSeek-V3.1模型。* Examples: .. code-block:: python import os import appbuilder # 请前往千帆AppBuilder官网创建密钥,流程详见:https://cloud.baidu.com/doc/AppBuilder/s/Olq6grrt6#1%E3%80%81%E5%88%9B%E5%BB%BA%E5%AF%86%E9%92%A5 os.environ['APPBUILDER_TOKEN'] = '...' hallucination_detection = appbuilder.HallucinationDetection() query = '' context = \ '''澳门美食: 澳门新麻蒲韩国烤肉店 在澳门一年四季之中除了火锅,烤肉也相当受欢迎。提到韩烧,有一间令我印象最深刻,就是号称韩国第一的烤肉店-新麻蒲韩国烤肉店,光是韩国的分店便多达四百多间,海外分店更是遍布世界各地,2016年便落户澳门筷子基区,在原本已经食肆林立的地方一起百花齐放!店内的装修跟韩国分店还完度几乎没差,让食客彷如置身于韩国的感觉,还要大赞其抽风系统不俗,离开时身上都不会沾上烤肉味耶! 时间:周一至周日 下午5:00 - 上午3:00 电话:+853 2823 4012 地址:澳门筷子基船澳街海擎天第三座地下O号铺96号 必食推介: 护心肉二人套餐 来新麻蒲必试的有两样东西,现在差不多每间烤肉店都有炉边烤蛋,但大家知道吗?原来新麻蒲就是炉边烤蛋的开创者,既然是始祖,这已经是个非吃不可的理由!还有一款必试的就是护心肉,即是猪的横隔膜与肝中间的部分,每头猪也只有200克这种肉,非常珍贵,其味道吃起来有种独特的肉香味,跟牛护心肉一样精彩! 秘制猪皮 很多怕胖的女生看到猪皮就怕怕,但其实猪皮含有大量胶原蛋白,营养价值很高呢!这里红通通的猪皮还经过韩国秘制酱汁处理过,会有一点点辣味。烤猪皮的时候也需特别注意火侯,这样吃起来才会有外脆内Q的口感!''' answer = '澳门新麻蒲烤肉店并不是每天开门。' inputs = {'query': query, 'context': context, 'answer': answer} msg = appbuilder.Message(inputs) result = hallucination_detection.run(msg) print(result) """ name = 'hallucination_detection' version = 'v1' meta = HallucinationDetectionArgs manifests = [ { "name": "hallucination_detection", "description": "输入用户查询query、检索结果context以及根据检索结果context生成的用户查询query的回答answer,判断answer" \ "中是否存在幻觉。", "parameters": { "type": "object", "properties": { "query": { "type": "string", "description": "用户查询。" }, "context": { "type": "string", "description": "检索结果。" }, "answer": { "type": "string", "description": "根据检索结果context生成的用户查询query的回答answer。" } }, "required": [ "query", "context", "answer" ] } } ] def __init__( self, model=None, secret_key: Optional[str] = None, gateway: str = "", lazy_certification: bool = False, **kwargs ): """初始化幻觉检测组件。 Args: model (str|None): 模型名称,用于指定要使用的千帆模型。推荐使用DeepSeek-V3.1模型。 secret_key (str, 可选): 用户鉴权token, 默认从环境变量中获取: os.getenv("APPBUILDER_TOKEN", ""). gateway (str, 可选): 后端网关服务地址,默认从环境变量中获取: os.getenv("GATEWAY_URL", "") lazy_certification (bool, 可选): 延迟认证,为True时在第一次运行时认证. Defaults to False. Returns: None """ super().__init__(HallucinationDetectionArgs, model=model, secret_key=secret_key, gateway=gateway, lazy_certification=lazy_certification) def completion(self, version, base_url, request, timeout: float = None, retry: int = 0): """ Send a byte array of an audio file to obtain the result of speech recognition. Args: version (str): API version. base_url (str): Base URL of the API. request (Request): Request object containing audio file and other parameters. timeout (float, optional): Timeout for the request. Defaults to None. retry (int, optional): Number of retries for the request. Defaults to 0. Returns: Response: Processed response object. """ headers = self.http_client.auth_header() headers["Content-Type"] = "application/json" stream = True if request.response_mode == "streaming" else False url = self.http_client.service_url("/app/hallucination_detection", self.base_url) response = self.http_client.session.post(url, json=request.params, headers=headers, timeout=timeout, stream=stream) return self.gene_response(response, stream) @components_run_trace def run(self, message, stream=False, temperature=1e-10, top_p=0.0): """ 使用给定的输入运行模型并返回结果。 Args: message (Message): 输入消息,包含 query、context 和 answer。是必需的参数。 stream (bool, 可选): 是否以流式形式返回响应。默认为 False。 temperature (float, 可选): 模型配置的温度参数,用于调整模型的生成概率。 取值范围为 0.0 到 1.0,较低的值使生成更确定性,较高的值使生成更多样性。默认值为 1e-10。 top_p (float, 可选): 影响输出文本的多样性,取值越大,生成文本的多样性越强。 取值范围为 0.0 到 1.0,较低的值使生成更确定性,较高的值使生成更多样性。默认值为 0。 Returns: result (Message): 模型运行后的输出消息。 Raises: AssertionError: 如果输入的 message 中缺少 query、context 或 answer。 AppBuilderServerException: 如果请求执行失败,将抛出异常,包含服务错误码和错误信息。 """ inputs = message.content query = inputs.pop('query', None) assert query, 'You must input query and query should not be empty' assert 'context' in inputs and inputs['context'], 'You must input context and context should not be empty' assert 'answer' in inputs and inputs['answer'], 'You must input answer and answer should not be empty' response_mode = "streaming" if stream else "blocking" user_id = message.id model_config_inputs = ModelArgsConfig(**{"stream": stream, "temperature": temperature, "top_p": top_p}) model_config = self.get_model_config(model_config_inputs) request = self.gene_request(query, inputs, response_mode, user_id, model_config) response = self.completion(self.version, self.base_url, request) if response.error_no != 0: raise AppBuilderServerException(service_err_code=response.error_no, service_err_message=response.error_msg) result = response.to_message() return result @components_run_stream_trace def tool_eval(self, name: str, stream: bool = False, **kwargs): """ 调用函数进行工具评估。 Args: name (str): 函数名,当前方法未使用此参数,预留接口。 stream (bool, optional): 是否以流的方式返回结果,默认为False。如果为True,则逐个返回结果;如果为False,则一次性返回所有结果。 **kwargs: 关键字参数,包含评估所需的输入参数。 - query (str): 查询语句。 - context (str): 上下文信息。 - answer (str): 参考答案。 - model_configs (dict, optional): 模型配置信息,默认为空字典。包含以下字段: - temperature (float, optional): 温度参数,用于控制生成文本的随机性,默认为1e-10。 - top_p (float, optional): 截断概率,用于控制生成文本的质量,默认为0.0。 Returns: 如果stream为False,返回包含所有评估结果的列表;如果stream为True,逐个返回评估结果。 Raises: ValueError: 如果缺少query、context或answer参数,将引发此异常。 """ query = kwargs.get('query', None) context = kwargs.get('context', None) answer = kwargs.get('answer', None) if not query or not context or not answer: raise ValueError('param `query` and `context` and `answer` are required') msg = Message({'query': query, 'context': context, 'answer': answer}) model_configs = kwargs.get('model_configs', {}) temperature = model_configs.get('temperature', 1e-10) top_p = model_configs.get('top_p', 0.0) message = self.run(message=msg, stream=stream, temperature=temperature, top_p=top_p) if stream: for data in message.content: yield data else: return message.content ================================================ FILE: python/core/components/llms/is_complex_query/README.md ================================================ # 复杂Query判定(IsComplexQuery) ## 简介 复杂Query判定组件(IsComplexQuery)可以根据输入的提问进行初步的分类,区分简单问题和复杂问题,以便后续运用不同的处理流程处理。可应用于知识问答场景。 ### 功能介绍 在知识问答领域中存在很多复杂问题需要处理,这些复杂问题通常需要进行问题分解并采用分治的方法处理。复杂Query判定组件尝试定义复杂问题和简单问题的概念,对用户的问题进行初步的分类,方便下游使用不同类型的流程来处理当前的简单问题/复杂问题。 ### 特色优势 复杂Query判定组件通过对问题进行有效分类,系统可以更快速地将简单问题导向快速回答流程,而将复杂问题导向更深入的分析流程。这种判定能力可以提高整个问答系统的效率和准确性。 ### 应用场景 广泛应用于知识问答场景 ## 基本用法 下面是复杂Query判定的代码示例: ```python import os import appbuilder # 请前往千帆AppBuilder官网创建密钥,流程详见:https://cloud.baidu.com/doc/AppBuilder/s/Olq6grrt6#1%E3%80%81%E5%88%9B%E5%BB%BA%E5%AF%86%E9%92%A5 os.environ["APPBUILDER_TOKEN"] = "..." is_complex_query = appbuilder.IsComplexQuery(model="DeepSeek-V3.1") msg = "吸塑包装盒在工业化生产和物流运输中分别有什么重要性?" msg = appbuilder.Message(msg) answer = is_complex_query(msg) print("Answer: \n{}".format(answer.content)) ``` ## 参数说明 ### 鉴权说明 使用组件之前,请首先申请并设置鉴权参数,可参考[组件使用流程](https://cloud.baidu.com/doc/AppBuilder/s/Olq6grrt6#1%E3%80%81%E5%88%9B%E5%BB%BA%E5%AF%86%E9%92%A5)。 ```python # 设置环境中的TOKEN,以下示例略 os.environ["APPBUILDER_TOKEN"] = "bce-YOURTOKEN" ``` ### 初始化参数 |参数名称 |参数类型 |是否必须 |描述 |示例值| |--------|--------|--------|----|------| |model |str |是 |模型名称,用于指定要使用的千帆模型|DeepSeek-V3.1| ### 调用参数 |参数名称 |参数类型 |是否必须 |描述 |示例值| |--------|--------|--------|----|------| |message |obj:`Message`|是 |输入消息,用于模型的主要输入内容。这是一个必需的参数| | |stream|bool|否 |指定是否以流式形式返回响应。默认为 False|False| |temperature|float|否 |模型配置的温度参数,用于调整模型的生成概率。取值范围为 0.0 到 1.0,其中较低的值使生成更确定性,较高的值使生成更多样性。默认值为 1e-10|1e-10| ### 响应参数 |参数名称 |参数类型 |描述 |示例值| |--------|--------|----|------| |Message |obj:`Message` |输出消息,包含模型运行后的输出| | ### 响应示例 ```text 分析:这个问题涉及到吸塑包装盒在工业化生产和物流运输中的重要性。回答这个问题需要从多个角度来考虑,比如生产方面、运输方面、环保方面等。这需要对吸塑包装盒有深入的了解,并且需要考虑到生产、运输等各个环节。因此,这是一个复杂问题。 类型:复杂问题 ``` ### 错误码 无 ## 高级用法 你可以通过自定义调整参数来获得想要的结果,例如: ```python # 流式返回, 调整模型temperature参数 answer = is_complex_query(msg, stream=True, temperature=0.5) ``` ## 更新记录和贡献 * 复杂Query判定 (2024-01) ================================================ FILE: python/core/components/llms/is_complex_query/__init__.py ================================================ from .component import IsComplexQuery ================================================ FILE: python/core/components/llms/is_complex_query/base.py ================================================ # Copyright (c) 2023 Baidu, Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from pydantic import Field from appbuilder.core.message import Message from appbuilder.core.component import ComponentArguments class IsComplexQueryMeta(ComponentArguments): """ IsComplexQueryMeta Attributes: message (Message): 输入消息,用于模型的输入,一般为问题。 """ message: Message = Field(..., variable_name="query", description="输入消息,用于模型的输入,一般为问题。") ================================================ FILE: python/core/components/llms/is_complex_query/component.py ================================================ # Copyright (c) 2023 Baidu, Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """ is complex query """ from pydantic import Field from typing import Optional from appbuilder.core.message import Message from appbuilder.core.component import ComponentArguments from appbuilder.core.components.llms.base import CompletionBaseComponent from appbuilder.utils.trace.tracer_wrapper import components_run_trace, components_run_stream_trace from .base import IsComplexQueryMeta class IsComplexQuery(CompletionBaseComponent): r""" 基于输入的问题, 对问题进行初步的分类,方便下游使用不同类型的流程来处理当前的简单问题/复杂问题。广泛用于知识问答场景。 Examples: .. code-block:: python import os import appbuilder # 请前往千帆AppBuilder官网创建密钥,流程详见:https://cloud.baidu.com/doc/AppBuilder/s/Olq6grrt6#1%E3%80%81%E5%88%9B%E5%BB%BA%E5%AF%86%E9%92%A5 os.environ["APPBUILDER_TOKEN"] = "..." is_complex_query = appbuilder.IsComplexQuery(model="DeepSeek-V3.1") msg = "吸塑包装盒在工业化生产和物流运输中分别有什么重要性?" msg = appbuilder.Message(msg) answer = is_complex_query(msg) print("Answer: \n{}".format(answer.content)) """ name = "is_complex_query" version = "v1" meta = IsComplexQueryMeta manifests = [ { "name": "is_complex_query", "description": "基于输入的问题, 对问题进行初步的分类,方便下游使用不同类型的流程来处理当前的简单问题/复杂问题。", "parameters": { "type": "object", "properties": { "query": { "type": "string", "description": "输入的问题,用于大模型根据该问题进行初步的分类。" } }, "required": [ "query" ] } } ] def __init__( self, model=None, secret_key: Optional[str] = None, gateway: str = "", lazy_certification: bool = False, **kwargs ): """初始化IsComplexQueryMeta任务。 Args: model (str|None): 模型名称,用于指定要使用的千帆模型。 secret_key (str, 可选): 用户鉴权token, 默认从环境变量中获取: os.getenv("APPBUILDER_TOKEN", ""). gateway (str, 可选): 后端网关服务地址,默认从环境变量中获取: os.getenv("GATEWAY_URL", "") lazy_certification (bool, 可选): 延迟认证,为True时在第一次运行时认证. Defaults to False. Returns: None """ super().__init__( IsComplexQueryMeta, model=model, secret_key=secret_key, gateway=gateway, lazy_certification=lazy_certification) @components_run_trace def run(self, message, stream=False, temperature=1e-10, top_p=0): """ 给定输入(message)到模型运行,同时指定运行参数,并返回结果。 Args: message (obj:`Message`): 输入消息,用于模型的主要输入内容。这是一个必需的参数。 stream (bool, optional): 指定是否以流式形式返回响应。默认为 False。 temperature (float, optional): 模型配置的温度参数,用于调整模型的生成概率。取值范围为 0.0 到 1.0,其中较低的值使生成更确定性,较高的值使生成更多样性。默认值为 1e-10。 top_p (float, optional): 影响输出文本的多样性,取值越大,生成文本的多样性越强。取值范围为 0.0 到 1.0,其中较低的值使生成更确定性,较高的值使生成更多样性。默认值为 0。 Returns: obj:`Message`: 模型运行后的输出消息。 """ return super().run(message=message, stream=stream, temperature=temperature, top_p=top_p) @components_run_stream_trace def tool_eval(self, name: str, streaming: bool = False, **kwargs): """ tool_eval for function call """ traceid = kwargs.get("traceid") query = kwargs.get("query", None) if not query: raise ValueError("param `query` is required") msg = Message(query) model_configs = kwargs.get('model_configs', {}) temperature = model_configs.get("temperature", 1e-10) top_p = model_configs.get("top_p", 0.0) message = super().run(message=msg, stream=False, temperature=temperature, top_p=top_p, request_id=traceid) if streaming: yield str(message.content) else: return str(message.content) ================================================ FILE: python/core/components/llms/mrc/README.md ================================================ # 阅读理解问答(MRC) ## 简介 阅读理解问答(MRC)组件是基于生成式大模型的阅读理解问答系统。该组件支持拒答、澄清、重点强调、友好性提升、溯源等多种功能,可用于回答用户提出的问题。 ### 功能介绍 MRC(阅读理解问答模块)是一项先进的自然语言处理功能,旨在使机器能够理解、分析文本内容,并基于这些内容回答相关问题。 本模块基于大语言模型,提供对文本内容的深入理解和精确回答能力。 ### 特色优势 我们的MRC模块,基于百度自研的先进语言模型文新一言,提供了一系列强大的阅读理解问答功能。在保持文本理解和问题回答的高精度的同时, 我们特别强调了答案的质量和交互体验。以下是我们MRC模块的几个主要功能特色: - 1.多版本模型支持:我们的MRC模块包括不同版本的文新一言大模型,Erniebot 4.0、DeepSeek-V3.1等,每个版本都针对特定的应用场景进行了优化。 用户可以根据自己的需求选择最适合的模型版本,以获得最佳的性能。 - 2.答案格式的多样性: - 拒答功能:当问题超出模型知识范围或不具体时,模型可以选择不回答,避免提供误导性信息。 - 澄清功能:对于模棱两可或含糊的问题,模型可以请求更多信息或对问题进行澄清,以确保答案的准确性。 - 重点内容强调:模型可以识别并强调答案中的关键信息,使答案更清晰、更易于理解。 - 友好度提升:模型可以以更自然、更亲切礼貌的方式呈现答案,且必要时对答案进行分点论述,改善用户体验。 - 答案溯源:模型能提供答案的来源信息,增强答案的可信度和透明度。 - 3.灵活的功能开关:每项功能都配备了开关,用户可以根据不同的应用场景和需求,灵活地启用或关闭某些功能。这种可定制性确保了MRC模块能够在各种环境下提供最优化的表现。 ### 应用场景 我们的MRC模块,凭借文心大模型强大的文本理解能力,以及多功能性,已在多个领域展现出显著的价值。 - 政务服务:在政务领域,MRC模块可以帮助构建智能问答系统,为公民提供关于政策、法规和服务程序的即时信息。它可以通过理解复杂的政府文件和公文,准确回答与政策相关的查询,极大地提高政府服务的效率和透明度。 - 法律咨询:法律领域充满了专业术语和复杂的概念。我们的MRC模块能够深入理解法律文献和案例,为法律专业人士和普通民众提供准确的法律咨询。无论是寻找相关法条还是理解特定法律案例,MRC模块都能提供快速、可靠的帮助。 - 医疗健康:在医疗健康领域,准确的信息至关重要。MRC模块能够解析医学文献、病例报告和临床试验数据,为医生和研究人员提供支持,帮助他们在诊断、治疗和研究中做出更明智的决策。此外,它也能在患者咨询中发挥作用,为患者提供关于疾病、治疗方案和药物的详细信息。 - 教育和研究:MRC模块可以作为学习和研究的强大工具,帮助学生和研究人员快速找到他们需要的信息。无论是解答学术问题,还是提供详细的背景资料,MRC模块都能提供卓越的支持。 - 企业客户服务:企业可以利用MRC模块构建高效的客服系统,提供24/7的咨询服务。从产品详情到服务流程的解释,MRC模块都能提供准确、及时的答案,提升客户满意度并减轻人工客服的压力。 - 金融咨询:在金融领域,MRC模块可以帮助用户理解复杂的金融产品、市场趋势和投资策略。通过提供准确的数据解读和市场分析,MRC模块能够辅助投资者和金融专业人士做出更明智的决策。 除上述场景以外,还可应用于其他更多生产生活的场景中。 ## 基本用法 ### 快速开启 ```python import appbuilder import os # 请前往千帆AppBuilder官网创建密钥,流程详见:https://cloud.baidu.com/doc/AppBuilder/s/Olq6grrt6#1%E3%80%81%E5%88%9B%E5%BB%BA%E5%AF%86%E9%92%A5 os.environ["APPBUILDER_TOKEN"] = "..." # 创建MRC对象 mrc_component = appbuilder.MRC(model="DeepSeek-V3.1") # 初始化参数 msg = "残疾人怎么办相关证件" msg = appbuilder.Message(msg) context_list = appbuilder.Message(["""如何办理残疾人通行证一、残疾人通行证办理条件: 1、持有中华人民共和国残疾人证,下肢残疾或者听力残疾; 2、持有准驾车型为C1(听力残疾)、C2(左下肢残疾、听力残疾)""", """3、本人拥有本市登记核发的非营运小型载客汽车,车辆须在检验有效期内,并有有效交强险凭证, C5车辆加装操纵辅助装置后已办理变更手续。二、办理地点:北京市朝阳区左家庄北里35号: 北京市无障碍环境建设促进中心"""]) # 模拟运行MRC基本组件 result = mrc_component.run(msg, context_list) # 输出运行结果 print(result) ``` ## 参数说明 ### 鉴权说明 使用组件之前,请首先申请并设置鉴权参数,可参考[组件使用流程](https://cloud.baidu.com/doc/AppBuilder/s/Olq6grrt6#1%E3%80%81%E5%88%9B%E5%BB%BA%E5%AF%86%E9%92%A5)。 ```python # 设置环境中的TOKEN,以下示例略 import os os.environ["APPBUILDER_TOKEN"] = "bce-YOURTOKEN" ``` ### 初始化参数 - `model`: 模型名称,用于指定要使用的千帆模型。 ### 调用参数 |参数名称 |参数类型 | 是否必须 |描述 | 示例值 | |--------|--------|---|----|------------------------------------------| |msg |Message | 是 |输入消息,包含用户提出的问题。| Message("你好") | |context_list|Message| 是 |用户输入的问题对应的段落文本列表。| Message(["""context1""","""context2"""]) | |reject|bool| 否 |拒绝开关,如果为 True,则启用该能力。默认为 False。当输入的问题在context_list中没有找到答案时,开关开启时,模型会用特定话术("当前文档库找不到对应的答案,我可以尝试用我的常识来回答你。")做回复的开头,并后接自有知识做回复内容。| eg.示例值 | |clarify|bool| 否 |澄清开关,如果为 True,则启用该能力。默认为 False。 当输入的问题比较模糊、或者主体指代不清晰,且context_list中包含有可以回答该模糊问题的多种潜在备选答案时,开启该开关,大模型会以特定的话术做澄清反问,引导用户继续补充问题发问。举例子,query:发电机的续航时间? Answer: 根据搜索结果得到了xx和xx两种型号的发电机,您的问题具体涉及到哪一个?请补充关键信息,作为完整的问题重新发问。| eg.示例值 | |highlight|bool| 否 |重点强调开关,如果为 True,则启用该能力。默认为 False。开启该功能时,回复结果中会高亮显示关键部分的内容。| 加粗的部分是**重点内容** | |friendly|bool| 否 |友好性提升开关,如果为 True,则启用该能力。默认为 False。开关开启时,部分回复的开头会加礼貌用语。且如果回答涉及到大段的信息,会倾向于以<总-分>或者<总-分-总>的形式做分点论述,使得答案的格式更规整,可读性更强。| eg.示例值 | |cite|bool| 否 |溯源开关,如果为 True,则启用该能力。默认为 False。开关开启时,回复内容后会接形如(^[1]^)的标记来表示回答内容在原文(context_list)中的来源索引。例如:按照当地公安机关出入境管理部门规定的其他材料办理^[2]^。| eg.示例值 | |temperature|float| 否 |模型配置的温度参数,用于调整模型的生成概率。取值范围为 0.0 到 1.0,其中较低的值使生成更确定性,较高的值使生成更多样性。默认值为 1e-10。| 0.0001 | ### 响应参数 |参数名称 |参数类型 |描述 |示例值| |--------|--------|----|------| |result |Message |返回结果|对象,包含模型运行后的输出消息。| ### 响应示例 ```json {"result": "极氪007的售价区间为20.99~29.99万元。"} ``` ### 错误码 无 ## 高级用法 该组件的高级用法包括定制化的输入处理、输出处理,以及更复杂的调用场景。用户可以根据具体需求扩展组件功能,实现个性化的问答系统。 包括如下功能: 1、拒答 2、澄清反问 3、重点强调 4、友好度提升 5、溯源 ### 代码样例 ```python import appbuilder import os # 设置环境变量 os.environ["APPBUILDER_TOKEN"] = '...' # 创建MRC对象 mrc_component = appbuilder.MRC(model="DeepSeek-V3.1") # 初始化参数 msg = "残疾人怎么办相关证件" msg = appbuilder.Message(msg) context_list = appbuilder.Message(["""如何办理残疾人通行证一、残疾人通行证办理条件: 1、持有中华人民共和国残疾人证,下肢残疾或者听力残疾; 2、持有准驾车型为C1(听力残疾)、C2(左下肢残疾、听力残疾)""", """3、本人拥有本市登记核发的非营运小型载客汽车,车辆须在检验有效期内,并有有效交强险凭证, C5车辆加装操纵辅助装置后已办理变更手续。二、办理地点:北京市朝阳区左家庄北里35号: 北京市无障碍环境建设促进中心"""]) # 模拟运行MRC组件,开启拒答、澄清追问、重点强调、友好性提升和溯源能力五个功能 result = mrc_component.run(msg, context_list, reject=True, clarify=True, highlight=True, friendly=True, cite=True) # 输出运行结果 print(result) ``` ## 更新记录和贡献 * 阅读理解问答 (2023-12) ================================================ FILE: python/core/components/llms/mrc/__init__.py ================================================ from .component import MRC ================================================ FILE: python/core/components/llms/mrc/base.py ================================================ # Copyright (c) 2023 Baidu, Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from appbuilder.core.message import Message from appbuilder.core.component import ComponentArguments from pydantic import Field class MrcArgs(ComponentArguments): """ 阅读理解问答配置 Attributes: message: Message 用户输入的查询内容,例如'千帆平台都有哪些大模型?' context_list: list 用户输入的检索片段列表,例如['content1', 'content2', 'content3',...],也可以为空,即[] reject: bool 控制大模型拒答能力的开关,为true即为开启拒答功能,为false即为关闭拒答功能 clarify: bool 控制大模型澄清能力的开关,为true即为开启澄清反问功能,为false即为关闭澄清反问功能 highlight: bool 控制大模型重点强调能力的开关,为true即为开启重点强调功能,为false即为关闭重点强调功能 friendly: bool 控制大模型友好对提升难过能力的开关,为true即为开启友好度提升功能,为false即为关闭重点强调功能 cite: bool 控制大模型溯源能力的开关,为true即为开启溯源功能,为false即为关闭溯源功能 """ message: Message = Field(..., variable_name="query", description="输入用户query,例如'千帆平台都有哪些大模型?'") context_list: list = Field(..., variable_name="context_list", description="用户输入检索片段list," "例如[content1, content2, content3,...],也可以为空, 即[]") reject: bool = Field(..., variable_name="reject", description="控制大模型拒答能力的开关,为true即为开启拒答功能,为false即为关闭拒答功能") clarify: bool = Field(..., variable_name="clarify", description="控制大模型澄清能力的开关,为true即为开启澄清反问功能,为false即为关闭澄清反问功能") highlight: bool = Field(..., variable_name="highlight", description="控制大模型重点强调能力的开关,为true即为开启重点强调功能,为false即为关闭重点强调功能") friendly: bool = Field(..., variable_name="friendly", description="控制大模型友好对提升难过能力的开关," "为true即为开启友好度提升功能,为false即为关闭友好度提升功能") cite: bool = Field(..., variable_name="cite", description="控制大模型溯源能力的开关,为true即为开启溯源功能,为false即为关闭溯源功能") ================================================ FILE: python/core/components/llms/mrc/component.py ================================================ # Copyright (c) 2023 Baidu, Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from appbuilder.core._exception import AppBuilderServerException from appbuilder.core.components.llms.base import CompletionBaseComponent, ModelArgsConfig from appbuilder.core.message import Message from appbuilder.core.component import ComponentArguments from pydantic import Field from typing import Optional from appbuilder.utils.trace.tracer_wrapper import components_run_trace, components_run_stream_trace from .base import MrcArgs class MRC(CompletionBaseComponent): """ 阅读理解问答组件,基于大模型进行阅读理解问答,支持拒答、澄清、重点强调、友好性提升、溯源等多种功能,可用于回答用户提出的问题。 Examples: .. code-block:: python import appbuilder import os # 设置环境变量 os.environ["APPBUILDER_TOKEN"] = '...' # 创建MRC对象 mrc_component = appbuilder.MRC() #初始化参数 msg = "残疾人怎么办相关证件" msg = appbuilder.Message(msg) context_list = appbuilder.Message(["如何办理残疾人通行证一、残疾人通行证办理条件: 1、持有中华人民共和国残疾人证,下肢残疾或者听力残疾;2、持有准驾车型为C1(听力残疾)、 C2(左下肢残疾、听力残疾", "3、本人拥有本市登记核发的非营运小型载客汽车,车辆须在检验有效期内, 并有有效交强险凭证,C5车辆加装操纵辅助装置后已办理变更手续。二、办理地点:北京市朝阳区左家庄北里35号: 北京市无障碍环境建设促进中心"]) # 模拟运行MRC组件,开启拒答、澄清追问、重点强调、友好性提升和溯源能力五个功能 result = mrc_component.run(msg, context_list, reject=True, clarify=True, highlight=True, friendly=True, cite=True) # 输出运行结果 print(result) """ name = "mrc" version = "v1" meta: MrcArgs manifests = [ { "name": "mrc", "description": "对于输入的问题,基于大模型进行阅读理解问答,支持拒答、澄清、重点强调、友好性提升、溯源等多种功能,可用于回答用户提出的问题", "parameters": { "type": "object", "properties": { "query": { "type": "string", "description": "输入用户query,例如'千帆平台都有哪些大模型?'" }, "context_list": { "type": "list", "description": "用户输入检索片段list,例如[content1, content2, content3,...],也可以为空, 即[]" }, "reject": { "type": "bool", "description": "控制大模型拒答能力的开关,为true即为开启拒答功能,为false即为关闭拒答功能" }, "clarify": { "type": "bool", "description": "控制大模型澄清能力的开关,为true即为开启澄清反问功能,为false即为关闭澄清反问功能" }, "highlight": { "type": "bool", "description": "控制大模型重点强调能力的开关,为true即为开启重点强调功能,为false即为关闭重点强调功能" }, "friendly": { "type": "bool", "description": "控制大模型友好对提升难过能力的开关,为true即为开启友好度提升功能,为false即为关闭友好度提升功能" }, "cite": { "type": "bool", "description": "控制大模型溯源能力的开关,为true即为开启溯源功能,为false即为关闭溯源功能。" } }, "required": [ "query", "context_list" ] } } ] def __init__( self, model=None, secret_key: Optional[str] = None, gateway: str = "", lazy_certification: bool = False, **kwargs ): """初始化MRC(阅读理解问答)模型。 Args: model (str|None): 模型名称,用于指定要使用的千帆模型。 secret_key (str, 可选): 用户鉴权token, 默认从环境变量中获取: os.getenv("APPBUILDER_TOKEN", ""). gateway (str, 可选): 后端网关服务地址,默认从环境变量中获取: os.getenv("GATEWAY_URL", "") lazy_certification (bool, 可选): 延迟认证,为True时在第一次运行时认证. Defaults to False. Returns: None """ super().__init__( MrcArgs, model=model, secret_key=secret_key, gateway=gateway, lazy_certification=lazy_certification) def __get_instruction_set(self): """ return: json格式的instruction_set """ return {"reject": "如果答案不在搜索结果中得到,则在答案开头说明:" "“当前文档库找不到对应的答案,我可以尝试用我的常识来回答你”," "并基于你的常识给出答案。", "clarify": "当问题比较模糊,而检索结果包含多种可能的答案时,反向提问用户想问的具体内容," "让用户补充关键信息后以完整的query重新发问。", "highlight": "可以对答案中的核心部分进行markdown加粗(**加粗内容**)。", "friendly": "答案尽量用礼貌用语开头,涉及到条目列举的内容需要在前面加序号并做分点描述," "必要时可在每一点前面做小标题的汇总,并可以用总-分-总的形式展示分点式答案内容,使得答案内容可读性更强。", "cite": "使用引用标记来标注回答内容参考的搜索结果序号,例如^[1]^ (引用单个搜索结果),^[1][2]^(引用多个搜索结果)," "其中方括号中的数字是搜索结果序号。引用标记只能出现在句尾标点符号前。"} @components_run_trace def run(self, message, context_list, reject=False, clarify=False, highlight=False, friendly=False, cite=False, stream=False, temperature=1e-10, top_p=0): """ 运行阅读理解问答模型并返回结果。 Args: message (obj:`Message`): 输入消息,包含用户提出的问题。这是一个必需的参数。 context_list (obj:`Message`): 用户输入的问题对应的段落文本列表。这是一个必需的参数。 reject (bool, 可选): 拒答开关,如果为 True,则启用拒答能力。默认为 False。 clarify (bool, 可选): 澄清开关,如果为 True,则启用澄清能力。默认为 False。 highlight (bool, 可选): 重点强调开关,如果为 True,则启用重点强调能力。默认为 False。 friendly (bool, 可选): 友好性提升开关,如果为 True,则启用友好性提升能力。默认为 False。 cite (bool, 可选): 溯源开关,如果为 True,则启用溯源能力。默认为 False。 stream (bool, 可选): 指定是否以流式形式返回响应。默认为 False。 temperature (float, 可选): 模型配置的温度参数,用于调整模型的生成概率。取值范围为 0.0 到 1.0,其中较低的值使生成更确定性,较高的值使生成更多样性。默认值为 1e-10。 top_p (float, 可选): 影响输出文本的多样性,取值越大,生成文本的多样性越强。取值范围为 0.0 到 1.0,其中较低的值使生成更确定性,较高的值使生成更多样性。默认值为 0。 Returns: obj:`Message`: 模型运行后的输出消息。 """ instruction_set = self.__get_instruction_set() context_list = context_list.content inputs = { "query": message.content, "context_out": "\n\n".join(f"[{i + 1}] {s}" for i, s in enumerate(context_list)), "reject": instruction_set["reject"] if reject else None, "clarify": instruction_set["clarify"] if clarify else None, "highlight": instruction_set["highlight"] if highlight else None, "friendly": instruction_set["friendly"] if friendly else None, "cite": instruction_set["cite"] if cite else None, } model_config_inputs = ModelArgsConfig(**{"stream": stream, "temperature": temperature, "top_p": top_p}) model_config = self.get_model_config(model_config_inputs) query = inputs["query"] response_mode = "streaming" if stream else "blocking" user_id = message.id request = self.gene_request(query, inputs, response_mode, user_id, model_config) response = self.completion(self.version, self.base_url, request) if response.error_no != 0: raise AppBuilderServerException(service_err_code=response.error_no, service_err_message=response.error_msg) return response.to_message() @components_run_stream_trace def tool_eval(self, name: str, streaming: bool = False, **kwargs): """ tool_eval for function call """ traceid = kwargs.get("traceid") query = kwargs.get("query", None) context_list = kwargs.get("context_list", None) reject = kwargs.get("reject", False) clarify = kwargs.get("clarify", False) highlight = kwargs.get("highlight", False) friendly = kwargs.get("friendly", False) cite = kwargs.get("cite", False) if not query or not context_list: raise ValueError("param `query` and `context_list` are required") msg = Message(query) context_list_msg = Message(context_list) model_configs = kwargs.get('model_configs', {}) temperature = model_configs.get("temperature", 1e-10) top_p = model_configs.get("top_p", 0.0) message = super().run(message=msg, context_list=context_list_msg, reject=reject, clarify=clarify, highlight=highlight, friendly=friendly, cite=cite, stream=False, temperature=temperature, top_p=top_p, request_id=traceid) if streaming: yield str(message.content) else: return str(message.content) ================================================ FILE: python/core/components/llms/nl2pandas/README.md ================================================ # 自然语言转pandas (nl2pandas) ## 简介 自然语言转pandas (nl2pandas)这个组件通过理解对表格信息的提问,生成对应语义的可执行Python代码,主要使用Pandas库。它可以用于基于表格的查询,问答等多种场景。 ### 功能介绍 自然语言转pandas (nl2pandas)根据用户的输入的表格信息和查询query,利用大语言模型的理解和生成能力,自动生成符合查询语义的一行或多行pandas代码。 ### 特色优势 自然语言转pandas (nl2pandas),基于百度自研的大语言模型文心一言,提供内置的自然语言转pandas代码的能力,无需更多的prompt描述,即可生成对应的查询代码。 ### 应用场景 自然语言转pandas (nl2pandas)可用对结构化表格数据的自然语言查询场景,问答场景等。 ## 基本用法 这里是一个简单示例,展示如何使用自然语言转Pandas组件: ```python import os import appbuilder # 请前往千帆AppBuilder官网创建密钥,流程详见:https://cloud.baidu.com/doc/AppBuilder/s/Olq6grrt6#1%E3%80%81%E5%88%9B%E5%BB%BA%E5%AF%86%E9%92%A5 os.environ["APPBUILDER_TOKEN"] = "..." #定义表格信息 假设有一个小学学校表格,包含学校名、所属地区、创办时间、类别、学生人数、教职工人数、教学班数量等列。列名后给出示例(例如清华附小是学校名的示例),以及列值类型(字符串类型、数字值类型),最后给出列名的解释。列之间使用换行符分隔。 table_info = '''表格列信息如下:\n学校名 : 清华附小 , 字符串类型,代表小学学校的名称\n所属地区 : 西城区 , 字符串类型,表示该小学学校所在的位置\n创办时间 : 1998 , 数字值类型,表示该小学学校的创办时间\n类别 : 公立小学 , 字符串类型,表示该小学学校所在的类别\n学生人数 : 2000 , 数字值类型,表示该小学学校的学生数量\n教职工人数 : 140 , 数字值类型,表示该小学学校的教职工数量\n教学班数量 : 122 , 数字值类型,表示该小学学校的教学班数量''' #定义查询问题 query = "海淀区有哪些学校" query = appbuilder.Message(query) #定义并运行Nl2pandas实例,得到结果 nl2pandas = appbuilder.Nl2pandasComponent(model="DeepSeek-V3.1") answer = nl2pandas(query, table_info = table_info) ``` ## 参数说明 ### 鉴权配置 使用组件之前,请首先申请并设置鉴权参数,可参考[组件使用流程](https://cloud.baidu.com/doc/AppBuilder/s/Olq6grrt6#1%E3%80%81%E5%88%9B%E5%BB%BA%E5%AF%86%E9%92%A5)。 ```python # 设置环境中的TOKEN,以下示例略 os.environ["APPBUILDER_TOKEN"] = "bce-YOURTOKEN" ``` ### 初始化参数 - `model`: 模型名称,用于指定要使用的千帆模型。 ### 调用参数 |参数名称 |参数类型 |是否必须 |描述 |示例值| |--------|--------|--------|----|------| |query |Message | 是 | 查询语句,一般是针对表格信息的提问 |例如'海淀区的小学有哪些'。建议长度是50字以内。 | |table_info |str | 是 | 表格信息,是表格列名以及对应列名的举例和释义 |例如:’表格列信息如下:\n学校名 : 清华附小 , 字符串类型,代表小学学校的名称\n所属地区 : 西城区 , 字符串类型,表示该小学学校所在的位置\n创办时间 : 1998 , 数字值类型,表示该小学学校的创办时间\n类别 : 公立小学 , 字符串类型,表示该小学学校所在的类别\n学生人数 : 2000 , 数字值类型,表示该小学学校的学生数量\n教职工人数 : 140 , 数字值类型,表示该小学学校的教职工数量\n教学班数量 : 122 , 数字值类型,表示该小学学校的教学班数量‘ | |stream |bool | 否 |指定是否以流式形式返回响应。默认为 False。 |False | |temperature |float | 否 |模型配置的温度参数,用于调整模型的生成概率。取值范围为 0.0 到 1.0,其中较低的值使生成更确定性,较高的值使生成更多样性。默认值为 1e-10。 |0.7 | ### 响应参数 |参数名称 |参数类型 |描述 |示例值| |--------|--------|----|------| |result |Message |返回结果|Message(content="df.loc[df['所属地区'] == "海淀区","学校名"]")| ## 高级用法 多个表格查询或跨表查询场景。 ## 更新记录和贡献 - 初始版本发布(2023-10) ================================================ FILE: python/core/components/llms/nl2pandas/__init__.py ================================================ """text to pandas""" from .component import Nl2pandasComponent ================================================ FILE: python/core/components/llms/nl2pandas/base.py ================================================ # Copyright (c) 2023 Baidu, Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from appbuilder.core.message import Message from pydantic import Field from appbuilder.core.component import ComponentArguments class Nl2pandasArgs(ComponentArguments): """ 自然语言转pandas代码 参数配置 Attributes: message: Message = Field(...) table_info: str = Field(...) """ message: Message = Field(..., variable_name="query", description="输入问题,一般是针对表格信息的提问,例如'海淀区的小学有哪些'") table_info: str = Field(..., variable_name="table_info", description="表格信息,一般是表格列名以及对应列名的举例和释义,例如'表格列信息如下:\n学校名 : 清华附小 , 字符串类型,代表小学学校的名称") ================================================ FILE: python/core/components/llms/nl2pandas/component.py ================================================ # Copyright (c) 2023 Baidu, Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from appbuilder.core.components.llms.base import CompletionBaseComponent from appbuilder.core.message import Message from pydantic import BaseModel, Field from typing import Optional from appbuilder.utils.trace.tracer_wrapper import components_run_trace, components_run_stream_trace from .base import Nl2pandasArgs class Nl2pandasComponent(CompletionBaseComponent): """ 自然语言转pandas大模型组件, 基于生成式大模型对query进行理解并生成对应语义的可执行python代码(主要使用pandas),可用于基于表格的查询、问答等多种场景。 Examples: .. code-block:: python import appbuilder os.environ["APPBUILDER_TOKEN"] = '...' table_info = '''表格列信息如下: 学校名 : 清华附小 , 字符串类型,代表小学学校的名称 所属地区 : 西城区 , 字符串类型,表示该小学学校所在的位置 创办时间 : 1998 , 数字值类型,表示该小学学校的创办时间 类别 : 公立小学 , 字符串类型,表示该小学学校所在的类别 学生人数 : 2000 , 数字值类型,表示该小学学校的学生数量 教职工人数 : 140 , 数字值类型,表示该小学学校的教职工数量 教学班数量 : 122 , 数字值类型,表示该小学学校的教学班数量 ''' query = "海淀区有哪些学校" query = appbuilder.Message(query) nl2pandas = appbuilder.Nl2pandasComponent(model="DeepSeek-V3.1") answer = nl2pandas(query, table_info = table_info) """ name = "nl2pandas" version = "v1" meta = Nl2pandasArgs manifests = [ { "name": "nl2pandas", "description": "输入用户查询query,基于生成式大模型对query进行理解并生成对应语义的可执行python代码(主要使用pandas),可用于基于表格的查询、问答等多种场景", "parameters": { "type": "object", "properties": { "query": { "text": "string", "description": "输入问题,一般是针对表格信息的提问,例如'海淀区的小学有哪些'" }, "table_info": { "text": "string", "description": "表格信息,一般是表格列名以及对应列名的举例和释义,例如'表格列信息如下:\n学校名 : 清华附小 , 字符串类型,代表小学学校的名称" } }, "required": [ "query", "table_info" ] } } ] def __init__( self, model=None, secret_key: Optional[str] = None, gateway: str = "", lazy_certification: bool = False, **kwargs ): """初始化Nl2pandasComponent模型。 Args: model (str|None): 模型名称,用于指定要使用的千帆模型。 secret_key (str, 可选): 用户鉴权token, 默认从环境变量中获取: os.getenv("APPBUILDER_TOKEN", ""). gateway (str, 可选): 后端网关服务地址,默认从环境变量中获取: os.getenv("GATEWAY_URL", "") lazy_certification (bool, 可选): 延迟认证,为True时在第一次运行时认证. Defaults to False. Returns: None """ super().__init__( Nl2pandasArgs, model=model, secret_key=secret_key, gateway=gateway, lazy_certification=lazy_certification) @components_run_trace def run(self, message, table_info=None, stream=False, temperature=1e-10, top_p=0): """ 使用给定的输入运行模型并返回结果。 Args: message (obj:`Message`): 输入问题,通常是针对表格信息的提问,如'海淀区的小学有哪些'。这是一个必需的参数。 table_info (obj:`Message`, optional): 表格信息,包括表格列名、对应列名的示例和释义。默认值为 None,但这是一个必需的参数。 stream (bool, optional): 指定是否以流式形式返回响应。默认为 False。 temperature (float, optional): 模型配置的温度参数,用于调整模型的生成概率。取值范围为 0.0 到 1.0,较低的值使生成更确定性,较高的值使生成更多样性。默认值为 1e-10。 top_p (float, optional): 影响输出文本的多样性,取值越大,生成文本的多样性越强。取值范围为 0.0 到 1.0,较低的值使生成更确定性,较高的值使生成更多样性。默认值为 0。 Returns: obj:`Message`: 模型运行后的输出消息。 """ return super().run(message=message, table_info=table_info, stream=stream, temperature=temperature, top_p=top_p) @components_run_stream_trace def tool_eval(self, name: str, streaming: bool = False, **kwargs): """ tool_eval for function call """ traceid = kwargs.get("traceid") query = kwargs.get("query", None) table_info = kwargs.get("table_info", None) if not query or not table_info: raise ValueError("param `query` and 'table_info' are required") msg = Message(query) model_configs = kwargs.get('model_configs', {}) temperature = model_configs.get("temperature", 1e-10) top_p = model_configs.get("top_p", 0.0) message = super().run(message=msg, table_info=table_info, stream=False, temperature=temperature, top_p=top_p, request_id=traceid) if streaming: yield str(message.content) else: return str(message.content) ================================================ FILE: python/core/components/llms/oral_query_generation/README.md ================================================ # 口语化Query生成(Oral Query Generation) ## 简介 口语化Query生成组件(Oral Query Generation)可以基于输入文本生成与文档内容相关的Query。 ### 功能介绍 基于输入文本生成与文档内容相关的Query。 ### 特色优势 生成的query划分为问题和短语两种类型,可分别用于不同场景。 ### 应用场景 可用于推荐问题生成、标签生成、文档索引增强等。 ## 基本用法 ### 快速开始 ```python import os import appbuilder # 请前往千帆AppBuilder官网创建密钥,流程详见:https://cloud.baidu.com/doc/AppBuilder/s/Olq6grrt6#1%E3%80%81%E5%88%9B%E5%BB%BA%E5%AF%86%E9%92%A5 os.environ["APPBUILDER_TOKEN"] = "..." text = ('文档标题:在OPPO Reno5上使用视频超级防抖\n' '文档摘要:OPPO Reno5上的视频超级防抖,视频超级防抖3.0,多代视频防抖算法积累,这一代依旧超级防抖超级稳。 开启视频超级' '防抖 开启路径:打开「相机 > 视频 > 点击屏幕上方的“超级防抖”标识」 后置视频同时支持超级防抖和超级防抖Pro功能,开启超级' '防抖后手机屏幕将出现超级防抖Pro开关,点击即可开启或关闭。 除此之外,前置视频同样加持防抖算法,边走边拍也能稳定聚焦脸部' ',实时视频分享您的生活。') #! 该组件推荐使用DeepSeek-V3.1模型。 oral_query_generation = appbuilder.OralQueryGeneration(model='DeepSeek-V3.1') result = oral_query_generation(appbuilder.Message(text), query_type='全部', output_format='str') print(result) ``` ## 参数说明 ### 鉴权说明 使用组件之前,请首先申请并设置鉴权参数,可参考[组件使用流程](https://cloud.baidu.com/doc/AppBuilder/s/Olq6grrt6#1%E3%80%81%E5%88%9B%E5%BB%BA%E5%AF%86%E9%92%A5)。 ```python # 设置环境中的TOKEN,以下示例略 os.environ["APPBUILDER_TOKEN"] = "bce-YOURTOKEN" ``` ### 初始化参数 | 参数名称 | 参数类型 | 是否必须 | 描述 | 示例值 | | ------- | ------- | -------- | -------- | -------- | | `model` | str | 是 | 模型名称,用于指定要使用的千帆模型。推荐使用DeepSeek-V3.1模型。 | DeepSeek-V3.1 | | `secret_key` | str | 否 | 用户鉴权token,默认从环境变量中获取: `os.getenv("APPBUILDER_TOKEN", "")` | bce-v3/XXX | | `gateway` | str | 否 | 后端网关服务地址,默认从环境变量中获取: `os.getenv("GATEWAY_URL", "")` | https://appbuilder.baidu.com | | `lazy_certification` | bool | 否 | 延迟认证,为True时在第一次运行时认证。默认为False。 | False | ### 调用参数 | 参数名称 | 参数类型 | 是否必须 | 描述 | 示例值 | | ------- | ------- | -------- | -------- | -------- | | `message` | obj | 是 | 输入消息,用于模型的主要输入内容。 | Message(content='...') | | `query_type` | str | 否 | 待生成的query类型,包括问题、短语和全部(问题+短语)。默认为全部。 | 全部 | | `output_format` | str | 否 | 输出格式,包括json和str。默认为str。 | str | | `stream` | bool | 否 | 指定是否以流式形式返回响应。默认为 False。 | False | | `temperature` | float | 否 | 模型配置的温度参数,用于调整模型的生成概率。取值范围为 0.0 到 1.0,其中较低的值使生成更确定性,较高的值使生成更多样性。默认值为 1e-10。 | 0.1 | | `top_p` | float | 否 | 影响输出文本的多样性,取值越大,生成文本的多样性越强。取值范围为 0.0 到 1.0,其中较低的值使生成更确定性,较高的值使生成更多样性。默认值为 0.0。 | 0.0 | ### 响应参数 | 参数名称 | 参数类型 | 描述 | 示例值 | | ------- | ------- | -------- | -------- | | `result` | obj | 模型运行后的输出结果 | Message(content='...') | ### 响应示例 ``` Message(name=msg, content=1. OPPO Reno5上有什么特殊的功能? 2. 视频超级防抖是什么? 3. 视频超级防抖有什么作用? 4. 如何在OPPO Reno5上开启视频超级防抖? 5. 视频超级防抖Pro是什么? 6. 开启视频超级防抖后,屏幕上会出现什么? 7. 前置视频有防抖算法吗? 8. OPPO Reno5上的视频超级防抖 9. 视频超级防抖3.0 10. 多代视频防抖算法积累的作用 11. 开启视频超级防抖的方法 12. 视频超级防抖Pro的功能 13. 开启视频超级防抖后,屏幕上会出现的东西 14. 前置视频防抖算法的作用, mtype=dict, extra={}) ``` ## 高级用法 ## 更新记录和贡献 ### 2024.5.22 #### [Updated] - 升级能力,主要升级内容如下: - 生成的query要求能够使用输入文本进行回答。 - 生成的query划分为问题和短语类型。 - 生成的query数量不再限制为10个。 - 在调用组件时,支持输出问题、短语或全部(问题 + 短语);支持输出格式为json或者str(兼容之前版本的输出格式)。 ### 2024.1.24 #### [Updated] - 更新README。 ### 2023.12.07 #### [Added] - 增加口语化Query生成组件。 - 增加口语化Query生成组件单元测试。 ================================================ FILE: python/core/components/llms/oral_query_generation/__init__.py ================================================ from .component import OralQueryGeneration ================================================ FILE: python/core/components/llms/oral_query_generation/base.py ================================================ # Copyright (c) 2023 Baidu, Inc. All Rights Reserved. # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from pydantic import Field from enum import Enum from appbuilder.core.component import ComponentArguments class QueryTypeChoices(Enum): questions = '问题' phrases = '短语' questions_and_phrases = '全部' def to_chinese(self): """ 将QueryTypeChoices枚举类中的值转换为中文描述。 Args: 无参数 Returns: 返回一个字典,键是QueryTypeChoices枚举类的成员,值为对应的中文描述字符串。 """ descriptions = { QueryTypeChoices.questions: '问题', QueryTypeChoices.phrases: '短语', QueryTypeChoices.questions_and_phrases: '全部' } return descriptions[self] class OutputFormatChoices(Enum): json_format = 'json' str_format = 'str' def to_chinese(self): """ 将OutputFormatChoices枚举类中的值转换为中文描述。 Args: 无参数 Returns: 返回一个字典,键是OutputFormatChoices枚举类的成员,值为对应的中文描述字符串。 """ descriptions = { OutputFormatChoices.json_format: 'json', OutputFormatChoices.str_format: 'str' } return descriptions[self] class OralQueryGenerationArgs(ComponentArguments): """口语化Query生成配置 """ text: str = Field(..., valiable_name='text', description='输入文本,用于生成Query') query_type: QueryTypeChoices = Field(..., variable_name='query_type', description='待生成的query类型,可选值为问题、短语和全部(问题+短语)。') output_format: QueryTypeChoices = Field(..., variable_name='output_format', description='输出格式,可选值为json、str。') ================================================ FILE: python/core/components/llms/oral_query_generation/component.py ================================================ # Copyright (c) 2023 Baidu, Inc. All Rights Reserved. # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import json import re from typing import Optional from appbuilder.core.components.llms.base import CompletionBaseComponent, ModelArgsConfig from appbuilder.core.message import Message from appbuilder.core._exception import AppBuilderServerException from appbuilder.utils.trace.tracer_wrapper import components_run_trace, components_run_stream_trace from .base import OralQueryGenerationArgs class OralQueryGeneration(CompletionBaseComponent): r""" 口语化Query生成,可用于问答场景下对文档增强索引。 *注:该组件推荐使用DeepSeek-V3.1模型。* Examples: .. code-block:: python import os import appbuilder os.environ["APPBUILDER_TOKEN"] = '...' text = ('文档标题:在OPPO Reno5上使用视频超级防抖\n' '文档摘要:OPPO Reno5上的视频超级防抖,视频超级防抖3.0,多代视频防抖算法积累,这一代依旧超级防抖超级稳。 开启视频超级' '防抖 开启路径:打开「相机 > 视频 > 点击屏幕上方的“超级防抖”标识」 后置视频同时支持超级防抖和超级防抖Pro功能,开启超级' '防抖后手机屏幕将出现超级防抖Pro开关,点击即可开启或关闭。 除此之外,前置视频同样加持防抖算法,边走边拍也能稳定聚焦脸部' ',实时视频分享您的生活。') oral_query_generation = appbuilder.OralQueryGeneration(model='DeepSeek-V3.1') answer = oral_query_generation(appbuilder.Message(text), query_type='全部', output_format='str') print(answer.content) """ name = 'query_generation' version = 'v1' meta = OralQueryGenerationArgs manifests = [ { "name": "query_generation", "description": "输入文本、待生成的query类型和输出格式,生成query,并按照要求的格式进行输出。", "parameters": { "type": "object", "properties": { "text": { "type": "string", "description": "输入文本,组件会根据该输入文本生成query。" }, "query_type": { "type": "string", "description": "待生成的query类型,可选问题、短语以及全部(问题 + 短语)。" }, "output_format": { "type": "string", "description": "输出格式,可选json或str,str格式与老版本输出格式相同。" } }, "required": [ "text" ] } } ] def __init__( self, model=None, secret_key: Optional[str] = None, gateway: str = "", lazy_certification: bool = False, **kwargs ): """初始化口语化Query生成模型。 Args: model (str|None): 模型名称,用于指定要使用的千帆模型。推荐使用DeepSeek-V3.1模型。 secret_key (str, 可选): 用户鉴权token, 默认从环境变量中获取: os.getenv("APPBUILDER_TOKEN", ""). gateway (str, 可选): 后端网关服务地址,默认从环境变量中获取: os.getenv("GATEWAY_URL", "") lazy_certification (bool, 可选): 延迟认证,为True时在第一次运行时认证. Defaults to False. Returns: None """ super().__init__( OralQueryGenerationArgs, model=model, secret_key=secret_key, gateway=gateway, lazy_certification=lazy_certification) def regenerate_output(self, model_output, output_format): """ 兼容老版本的输出格式 """ if not isinstance(model_output, str): return model_output match_obj = re.search(r'```json\n(.+)\n```', model_output, flags=re.DOTALL) regenerated_output = None if match_obj: regenerated_output = json.loads(match_obj.group(1)) else: dict_json_match_obj = re.search(r'\{(.|\n)+\}', model_output) dict_json_text = dict_json_match_obj.group(0) if dict_json_match_obj else None regenerated_output = json.loads(dict_json_text) if dict_json_text is not None else model_output if output_format == 'json' or not isinstance(regenerated_output, dict): return json.dumps(regenerated_output, ensure_ascii=False, indent=4) queries = [] for key in ['问题', '短语']: queries += regenerated_output.pop(key, []) for value in regenerated_output.values(): queries += value regenerated_output = '\n'.join([f'{index}. {query}' for index, query in enumerate(queries, 1)]) return regenerated_output def completion(self, version, base_url, request, timeout: float = None, retry: int = 0): r"""Send a byte array of an audio file to obtain the result of speech recognition.""" headers = self.http_client.auth_header() headers["Content-Type"] = "application/json" stream = True if request.response_mode == "streaming" else False url = self.http_client.service_url("/app/query_generation", self.base_url) response = self.http_client.session.post(url, json=request.params, headers=headers, timeout=timeout, stream=stream) return self.gene_response(response, stream) @components_run_trace def run(self, message, query_type='全部', output_format='str', stream=False, temperature=1e-10, top_p=0.0): """ 使用给定的输入运行模型并返回结果。 Args: message (Message): 输入消息,包含query、context和answer等信息。这是一个必需的参数。 query_type (str, 可选): 待生成的query类型,包括问题、短语和全部(问题+短语)。默认为全部。 output_format (str, 可选): 输出格式,包括json和str,当stream为True时,只能以json形式输出。默认为str。 stream (bool, 可选): 指定是否以流式形式返回响应。默认为 False。 temperature (float, 可选): 模型配置的温度参数,用于调整模型的生成概率。 取值范围为 0.0 到 1.0,其中较低的值使生成更确定性,较高的值使生成更多样性。默认值为 1e-10。 top_p (float, 可选): 影响输出文本的多样性,取值越大,生成文本的多样性越强。 取值范围为 0.0 到 1.0,其中较低的值使生成更确定性,较高的值使生成更多样性。默认值为 0。 Returns: result (Message): 模型运行后的输出消息。 """ text = message.content assert text, 'Input text should be a valid string' inputs = { 'text': text, 'query_type': query_type } response_mode = "streaming" if stream else "blocking" user_id = message.id model_config_inputs = ModelArgsConfig(**{"stream": stream, "temperature": temperature, "top_p": top_p}) model_config = self.get_model_config(model_config_inputs) request = self.gene_request('', inputs, response_mode, user_id, model_config) response = self.completion(self.version, self.base_url, request) if response.error_no != 0: raise AppBuilderServerException(service_err_code=response.error_no, service_err_message=response.error_msg) result = response.to_message() result.content = self.regenerate_output(result.content, output_format) return result @components_run_stream_trace def tool_eval(self, name: str, streaming: bool = False, **kwargs): """ 调用函数进行工具评估。 Args: name (str): 评估工具的名称。 stream (bool, optional): 是否以流的形式返回结果。默认为False。 **kwargs: 关键字参数,可以包含以下参数: text (str): 需要评估的文本。 query_type (str, optional): 查询类型,默认为'全部'。 output_format (str, optional): 输出格式,默认为'str'。 model_configs (dict, optional): 模型配置,默认为空字典。 Returns: 如果stream为False,则返回评估结果列表; 如果stream为True,则逐个返回评估结果。 Raises: ValueError: 如果未提供text参数,则抛出ValueError异常。 """ text = kwargs.get('text', None) query_type = kwargs.get('query_type', '全部') output_format = kwargs.get('output_format', 'str') if not text: raise ValueError('param `text` is required') msg = Message(text) model_configs = kwargs.get('model_configs', {}) temperature = model_configs.get('temperature', 1e-10) top_p = model_configs.get('top_p', 0.0) message = self.run(message=msg, query_type=query_type, output_format=output_format, stream=streaming, temperature=temperature, top_p=top_p) if streaming: for data in message.content: yield data else: return message.content ================================================ FILE: python/core/components/llms/playground/README.md ================================================ # 空应用(Playground) ## 简介 Playground空应用(Playground)是一款灵活的组件,允许用户自定义prompt模板并执行。 ### 功能介绍 Playground空应用(Playground)是一款灵活的组件,允许用户自定义prompt模板并执行。它适用于各种场景,特别是在需要自定义输入模板和使用预训练模型进行交互的情况下。 ### 特色优势 灵活可自定义,用户可自由定义提示词,来跟大模型进行交互。 ### 应用场景 在需要灵活定义提示词的场景,并且其他提供的开箱即用的组件无法满足的情况下使用。 ## 基本用法 要开始使用 Playground,你需要设置prompt模板和模型名称。以下是一个基本示例: ```python import os import appbuilder # 请前往千帆AppBuilder官网创建密钥,流程详见:https://cloud.baidu.com/doc/AppBuilder/s/Olq6grrt6#1%E3%80%81%E5%88%9B%E5%BB%BA%E5%AF%86%E9%92%A5 os.environ["APPBUILDER_TOKEN"] = "..." play = appbuilder.Playground( prompt_template="你好,{name},我是{bot_name},{bot_name}是一个{bot_type},我可以{bot_function},你可以问我{bot_question}。", model="DeepSeek-V3.1" ) play(appbuilder.Message({"name": "小明", "bot_name": "小红", "bot_type": "聊天机器人", "bot_function": "聊天", "bot_question": "你好吗?"}), stream=False) ``` ## 参数说明 ### 初始化参数 | 参数名称 | 类型 | 说明 | |----------------|------------|----------------------------------| | prompt_template | str | 输入模板,用于指定prompt格式。 | | model | str \| None | 模型名称,用于指定要使用的千帆模型。 | ### 调用参数 | 参数名称 | 类型 | 说明 | 默认值 | |-----------|---------------|----------------------------|------| | message | obj:`Message` | 输入消息,必需参数。 | 无 | | stream | bool | 是否以流式形式返回响应。 | False | | temperature | float | 模型配置的温度参数。 | 1e-10 | | max_output_tokens | int | 指定生成的文本的最大长度,默认最大输出token数为1024, 最小为2, 最大输出token与选择的模型有关 | 1024 | |disable_search| bool | 是否关闭搜索功能,默认关闭 | True | |response_format| str | 指定返回的响应格式,可选值有:`text`, `json_object`| text | |stop| str | 生成停止标识,当模型生成结果以stop中某个元素结尾时,停止文本生成。每个元素长度不超过20字符,最多4个元素. | [] | ### 响应参数 | 类型 | 说明 | |----------------|--------------------| | obj:`Message` | 模型运行后的输出消息。 | ### 响应示例 ```json {"result": "北京科技馆。"} ``` ### 错误码 |错误码|描述| |------|---| ## 高级用法 此部分可根据实际应用场景提供更复杂的示例和用法说明。 ## 示例和案例研究 目前暂无具体案例,将在未来更新。 ## API文档 无 ## 更新记录和贡献 - 2024年01月24日 更新Readme格式,调整请求参数样式,新增特色优势 - 2024年08月01日 更新playground组件的入参,并且前向兼容,支持未来的大模型对话参数 ================================================ FILE: python/core/components/llms/playground/__init__.py ================================================ """text to pandas""" from .component import Playground ================================================ FILE: python/core/components/llms/playground/base.py ================================================ # Copyright (c) 2023 Baidu, Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from pydantic import Field from appbuilder.core.component import ComponentArguments from appbuilder.core.message import Message class PlaygroundArgs(ComponentArguments): """ 空模板参数配置 Attributes: message (Message): 输入消息,用于模型的主要输入内容 """ message: Message = Field(..., json_schema_extra={ "variable_name": "query", "description": "输入消息,用于模型的主要输入内容"} ) ================================================ FILE: python/core/components/llms/playground/component.py ================================================ # Copyright (c) 2023 Baidu, Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from typing import Optional import re from appbuilder.core.components.llms.base import CompletionBaseComponent from appbuilder.core.message import Message from appbuilder.utils.trace.tracer_wrapper import components_run_trace from .base import PlaygroundArgs class Playground(CompletionBaseComponent): """ 空模板, 支持用户自定义prompt模板,并进行执行 Examples: .. code-block:: python import os import appbuilder os.environ["APPBUILDER_TOKEN"] = "..." play = appbuilder.Playground(prompt_template="你好,{name},我是{bot_name},{bot_name}是一个{bot_type},我可以{bot_function},你可以问我{bot_question}。", model="DeepSeek-V3.1") play(appbuilder.Message({"name": "小明", "bot_name": "小红", "bot_type": "聊天机器人", "bot_function": "聊天", "bot_question": "你好吗?"}), stream=False) """ name = "playground" version = "v1" meta = PlaygroundArgs prompt_template = "" variable_names = {} def __init__( self, prompt_template=None, model=None, secret_key: Optional[str] = None, gateway: str = "", lazy_certification: bool = False, **kwargs ): """初始化空模板配置模型。 Args: prompt_template (str): 输入模板,用于指定prompt格式 model (str|None): 模型名称,用于指定要使用的千帆模型。 secret_key (str, 可选): 用户鉴权token, 默认从环境变量中获取: os.getenv("APPBUILDER_TOKEN", ""). gateway (str, 可选): 后端网关服务地址,默认从环境变量中获取: os.getenv("GATEWAY_URL", "") lazy_certification (bool, 可选): 延迟认证,为True时在第一次运行时认证. Defaults to False. Returns: None """ super().__init__( PlaygroundArgs, model=model, secret_key=secret_key, gateway=gateway, lazy_certification=lazy_certification) if prompt_template is None: prompt_template = "{query}" self.prompt_template = prompt_template self.variable_names = self.__parse__(prompt_template) @components_run_trace def run(self, message, stream=False, temperature=1e-10, top_p=0.0, max_output_tokens=1024, disable_search=True, response_format='text', stop=[], **kwargs): """ 使用给定的输入运行模型并返回结果。 Args: message (obj:`Message`): 输入消息,用于模型的主要输入内容。这是一个必需的参数。 stream (bool, 可选): 指定是否以流式形式返回响应。默认为 False。 temperature (float, 可选): 模型配置的温度参数,用于调整模型的生成概率。 取值范围为 0.0 到 1.0,其中较低的值使生成更确定性,较高的值使生成更多样性。默认值为 1e-10。 top_p (float, 可选): 影响输出文本的多样性,取值越大,生成文本的多样性越强。 取值范围为 0.0 到 1.0,其中较低的值使生成更确定性,较高的值使生成更多样性。默认值为 0。 max_output_tokens (int, 可选): 指定生成的文本的最大长度,默认最大输出token数为1024, 最小为2, 最大输出token与选择的模型有关。 disable_search (bool, 可选): 是否强制关闭实时搜索功能,默认为 True,表示关闭。 response_format (str, 可选): 指定返回的消息格式,默认为 'text',以文本模式返回。 可选 'json_object',以 json 格式返回,但可能存在不满足效果的情况。 stop (list[str], 可选): 生成停止标识,当模型生成结果以 stop 中某个元素结尾时,停止文本生成。 每个元素长度不超过 20 字符,最多 4 个元素。 Returns: obj:`Message`: 模型运行后的输出消息。 """ inputs = {} if isinstance(message.content, str): if len(self.variable_names) == 1: inputs[self.variable_names[0]] = message.content if isinstance(message.content, dict): inputs.update(message.content) for key in self.variable_names: if key not in inputs: raise ValueError( f"Missing input variable {key} in message {message.content}") prompt = self.prompt_template.format(**inputs) query_message = Message(prompt) return super().run(message=query_message, stream=stream, temperature=temperature, top_p=top_p, max_output_tokens=max_output_tokens, disable_search=disable_search, response_format=response_format, stop=stop, **kwargs) def __parse__(self, prompt_template): last_end = 0 results = [] for match in re.finditer(r"{([a-zA-Z_]\w*)}", prompt_template): field_name = match.group(1) start, end = match.span() literal_text = prompt_template[last_end:start] last_end = end results.append((literal_text, field_name, '', None)) remaining_literal_text = prompt_template[last_end:] if remaining_literal_text: results.append((remaining_literal_text, None, None, None)) input_variables = [v for _, v, _, _ in results if v is not None] return input_variables ================================================ FILE: python/core/components/llms/qa_pair_mining/README.md ================================================ # 问答对挖掘(QAPairMining) ## 简介 问答对挖掘(QAPairMining)可以基于输入文本内容,快速生成多个问题及对应答案,极大提高信息提炼的效率和准确性。广泛用于在线客服、智能问答等领域。 ### 功能介绍 基于输入文本内容,快速生成多个问题及对应答案;可与文档解析、分段联用,快速生成文档的问答对。 ### 特色优势 问答对挖掘组件快速基于输入文本生成的问题和答案,准确率高;可快速依据文档生成FAQ,减少人工成本。 ### 适用场景 适用于在线客服、智能问答等场景 ## 基本用法 ### 快速开始 ```python import os import appbuilder # 请前往千帆AppBuilder官网创建密钥,流程详见:https://cloud.baidu.com/doc/AppBuilder/s/Olq6grrt6#1%E3%80%81%E5%88%9B%E5%BB%BA%E5%AF%86%E9%92%A5 os.environ["APPBUILDER_TOKEN"] = "..." qa_mining = appbuilder.QAPairMining(model="DeepSeek-V3.1") # 输入文本(对此文本挖掘问答对) msg = '2017年,工商银行根据外部宏观环境变化,及时调整业务策略,优化资产负债结构,' + \ '保持存贷款业务协调发展,提升资产负债配置效率。' + \ '2018年3月末,工商银行总资产264,937.81亿元,比上年末增加4,067.38亿元.' msg = appbuilder.Message(msg) answer = qa_mining(msg) print(">>> Output: {}".format(answer.content)) ``` ## 参数说明 ### 鉴权说明 使用组件之前,请首先申请并设置鉴权参数,可参考[组件使用流程](https://cloud.baidu.com/doc/AppBuilder/s/Olq6grrt6#1%E3%80%81%E5%88%9B%E5%BB%BA%E5%AF%86%E9%92%A5)。 ```python # 设置环境中的TOKEN,以下示例略 os.environ["APPBUILDER_TOKEN"] = "bce-YOURTOKEN" ``` ### 初始化参数 无 ### 调用参数 |参数名称 |参数类型 |是否必须 |描述 |示例值| |--------|--------|--------|----|------| | message | String |是 |输入消息,用于模型的主要输入内容。这是一个必需的参数。| `Message("2017年,工商银行根据...")` | | stream |bool|否 |指定是否以流式形式返回响应。默认为 False。| False | | temperature |float|否 |模型配置的温度参数,用于调整模型的生成概率。取值范围为 0.0 到 1.0,其中较低的值使生成更确定性,较高的值使生成更多样性。默认值为 1e-10。 | 1e-10 | ### 响应参数 |参数名称 |参数类型 |描述 |示例值| |--------|--------|----|------| | result | String | 输出消息,包含模型运行后的输出内容。| 见响应示例 | ### 响应示例 ```text 问题:2017年,工商银行是如何应对外部宏观环境变化的? 答案:工商银行根据外部宏观环境变化,及时调整业务策略,优化资产负债结构,保持存贷款业务协调发展,提升资产负债配置效率。 问题:2018年3月末,工商银行总资产是多少? 答案:264,937.81亿元。 ``` ### 错误码 |错误码|描述| |------|---| ## 高级用法 基于一篇文档,快速生成多个问题及对应答案,极大提高信息提炼的效率和准确性。 主要流程如下: 1. 读取本地文档,文档解析分段,获取段落; 2. 段落作为问答对挖掘的输入,挖掘问答对。 ### 代码样例 ```python import os import requests from appbuilder.utils.logger_util import logger from appbuilder import Message, DocParser, DocSplitter, QAPairMining # 请前往千帆AppBuilder官网创建密钥,流程详见:https://cloud.baidu.com/doc/AppBuilder/s/Olq6grrt6#1%E3%80%81%E5%88%9B%E5%BB%BA%E5%AF%86%E9%92%A5 # os.environ["APPBUILDER_TOKEN"] = "..." # 进行文档内容解析 file_url = "https://agi-dev-platform-bos.bj.bcebos.com/ut_appbuilder/test.pdf?authorization=bce-auth-v1/e464e6f951124fdbb2410c590ef9ed2f/2024-01-25T12%3A56%3A15Z/-1/host/b54178fea9be115eafa2a8589aeadfcfaeba20d726f434f871741d4a6cb0c70d" file_data = requests.get(file_url).content file_path = "./test.pdf" # 待解析的文件路径 with open(file_path, "wb") as f: f.write(file_data) # 解析文档 msg = Message(file_path) parser = DocParser() parse_result = parser.run(msg, return_raw=True) # 对文档进行分段落,split_by_chunk需要return_raw=True splitter = DocSplitter( splitter_type="split_by_chunk", overlap=0) split_result = splitter(parse_result) # 每个段落抽取问答对,并返回结果 for doc_segment in split_result.content["paragraphs"]: qa_mining = QAPairMining(model="DeepSeek-V3.1") text = doc_segment.get("text", "") if text == "": logger.error("Text is null. break") break logger.info("Input: \n{}".format(text)) answer = qa_mining(Message(text)) logger.info("Output: \n{}".format(answer.content)) break # 样例代码只跑1个段落 ``` ## 更新记录和贡献 * 问答对挖掘能力 (2023-12) ================================================ FILE: python/core/components/llms/qa_pair_mining/__init__.py ================================================ from .component import QAPairMining ================================================ FILE: python/core/components/llms/qa_pair_mining/base.py ================================================ # Copyright (c) 2023 Baidu, Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from pydantic import Field from appbuilder.core.message import Message from appbuilder.core.component import ComponentArguments class QAPairMiningMeta(ComponentArguments): """ QAPairMiningMeta Attributes: message (Message): 输入消息,用于模型的输入,一般为文档段落。 """ message: Message = Field(..., variable_name="query", description="输入消息,用于模型的输入,一般为文档段落。") ================================================ FILE: python/core/components/llms/qa_pair_mining/component.py ================================================ # Copyright (c) 2023 Baidu, Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from pydantic import Field from typing import Optional from appbuilder.core.message import Message from appbuilder.core.component import ComponentArguments from appbuilder.core.components.llms.base import CompletionBaseComponent from appbuilder.utils.trace.tracer_wrapper import components_run_trace, components_run_stream_trace from .base import QAPairMiningMeta class QAPairMining(CompletionBaseComponent): """ 基于输入文本内容,快速生成多个问题及对应答案,极大提高信息提炼的效率和准确性.广泛用于在线客服、智能问答等领域。 Examples: .. code-block:: python import os import appbuilder os.environ["APPBUILDER_TOKEN"] = "..." qa_mining = appbuilder.QAPairMining(model="DeepSeek-V3.1") # 输入文本(对此文本挖掘问答对) msg = '2017年,工商银行根据外部宏观环境变化,及时调整业务策略,优化资产负债结构,' + \ '保持存贷款业务协调发展,提升资产负债配置效率。' + \ '2018年3月末,工商银行总资产264,937.81亿元,比上年末增加4,067.38亿元。' msg = appbuilder.Message(msg) answer = qa_mining(msg) print(">>> Output: {}".format(answer.content)) """ name = "qa_pair_mining" version = "v1" meta = QAPairMiningMeta manifests = [ { "name": "qa_pair_mining", "description": "基于输入文本内容,快速生成多个问题及对应答案,极大提高信息提炼的效率和准确性。广泛用于在线客服、智能问答等领域。", "parameters": { "type": "object", "properties": { "query": { "type": "string", "description": "输入消息,用于模型的输入,一般为文档段落。" } }, "required": [ "query" ] } } ] def __init__( self, model=None, secret_key: Optional[str] = None, gateway: str = "", lazy_certification: bool = False, **kwargs ): """初始化QAPairMining(问答对挖掘)模型。 Args: model (str|None): 模型名称,用于指定要使用的千帆模型。 secret_key (str, 可选): 用户鉴权token, 默认从环境变量中获取: os.getenv("APPBUILDER_TOKEN", ""). gateway (str, 可选): 后端网关服务地址,默认从环境变量中获取: os.getenv("GATEWAY_URL", "") lazy_certification (bool, 可选): 延迟认证,为True时在第一次运行时认证. Defaults to False. Returns: None """ super().__init__( QAPairMiningMeta, model=model, secret_key=secret_key, gateway=gateway, lazy_certification=lazy_certification) @components_run_trace def run(self, message, stream=False, temperature=1e-10, top_p=0.0): """ 给定输入(message)到模型运行,同时指定运行参数,并返回结果。 Args: message (obj:`Message`): 输入消息,用于模型的主要输入内容。这是一个必需的参数。 stream (bool, optional): 指定是否以流式形式返回响应。默认为 False。 temperature (float, optional): 模型配置的温度参数,用于调整模型的生成概率。取值范围为 0.0 到 1.0,其中较低的值使生成更确定性,较高的值使生成更多样性。默认值为 1e-10。 top_p (float, optional): 影响输出文本的多样性,取值越大,生成文本的多样性越强。取值范围为 0.0 到 1.0,其中较低的值使生成更确定性,较高的值使生成更多样性。默认值为 0。 Returns: obj:`Message`: 模型运行后的输出消息。 """ return super().run(message=message, stream=stream, temperature=temperature, top_p=top_p) @components_run_stream_trace def tool_eval(self, name: str, streaming: bool = False, **kwargs): """ tool_eval for function call """ traceid = kwargs.get("traceid") query = kwargs.get("query", None) if not query: raise ValueError("param `query` is required") msg = Message(query) model_configs = kwargs.get('model_configs', {}) temperature = model_configs.get("temperature", 1e-10) top_p = model_configs.get("top_p", 0.0) message = super().run(message=msg, stream=False, temperature=temperature, top_p=top_p, request_id=traceid) if streaming: yield str(message.content) else: return str(message.content) ================================================ FILE: python/core/components/llms/query_decomposition/README.md ================================================ # 复杂Query分解(QueryDecomposition) ## 简介 复杂Query分解(QueryDecomposition)可以将已经确定为复杂问题的原始问题拆解为一个个简单问题。广泛应用在知识问答场景。 ### 功能介绍 在知识问答领域中存在很多复杂问题需要处理,这些复杂问题通常需要进行问题分解并采用分治的方法处理。复杂Query分解组件尝试对已经判定为复杂问题的原始问题进行拆解,把复杂问题拆解为一个个简单问题。 ### 特色优势 复杂Query分解组件可以将复杂问题分解为不同层级的简单问题。这有助于更系统地分析和解决问题,提高答案的全面性。 ### 应用场景 广泛应用于知识问答场景 ## 基本用法 下面是复杂Query分解的代码示例: ```python import os import appbuilder # 请前往千帆AppBuilder官网创建密钥,流程详见:https://cloud.baidu.com/doc/AppBuilder/s/Olq6grrt6#1%E3%80%81%E5%88%9B%E5%BB%BA%E5%AF%86%E9%92%A5 os.environ["APPBUILDER_TOKEN"] = "..." query_decomposition = appbuilder.QueryDecomposition(model="DeepSeek-V3.1") msg = "吸塑包装盒在工业化生产和物流运输中分别有什么重要性?" msg = appbuilder.Message(msg) answer = query_decomposition(msg) print("Answer: \n{}".format(answer.content)) ``` ## 参数说明 ### 鉴权说明 使用组件之前,请首先申请并设置鉴权参数,可参考[组件使用流程](https://cloud.baidu.com/doc/AppBuilder/s/Olq6grrt6#1%E3%80%81%E5%88%9B%E5%BB%BA%E5%AF%86%E9%92%A5)。 ```python # 设置环境中的TOKEN,以下示例略 os.environ["APPBUILDER_TOKEN"] = "bce-YOURTOKEN" ``` ### 初始化参数 |参数名称 |参数类型 |是否必须 |描述 |示例值| |--------|--------|--------|----|------| |model |str |是 |模型名称,用于指定要使用的千帆模型|DeepSeek-V3.1| ### 调用参数 |参数名称 |参数类型 |是否必须 |描述 |示例值| |--------|--------|--------|----|------| |message |obj:`Message`|是 |输入消息,用于模型的主要输入内容。这是一个必需的参数| | |stream|bool|否 |指定是否以流式形式返回响应。默认为 False|False| |temperature|float|否 |模型配置的温度参数,用于调整模型的生成概率。取值范围为 0.0 到 1.0,其中较低的值使生成更确定性,较高的值使生成更多样性。默认值为 1e-10|1e-10| ### 响应参数 |参数名称 |参数类型 |描述 |示例值| |--------|--------|----|------| |Message |obj:`Message` |输出消息,包含模型运行后的输出| | ### 响应示例 ```text 1. 吸塑包装盒在工业化生产中有什么重要性? 2. 吸塑包装盒在物流运输中有什么重要性? ``` ### 错误码 无 ## 高级用法 你可以通过自定义调整参数来获得想要的结果,例如: ```python # 流式返回, 调整模型temperature参数 answer = query_decomposition(msg, stream=True, temperature=0.5) ``` ## 更新记录和贡献 * 复杂Query分解 (2024-01) ================================================ FILE: python/core/components/llms/query_decomposition/__init__.py ================================================ from .component import QueryDecomposition ================================================ FILE: python/core/components/llms/query_decomposition/base.py ================================================ # Copyright (c) 2023 Baidu, Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from pydantic import Field from appbuilder.core.message import Message from appbuilder.core.component import ComponentArguments class QueryDecompositionMeta(ComponentArguments): """ QueryDecomposition Attributes: message (Message): 输入消息,用于模型的主要输入内容。 """ message: Message = Field(..., variable_name="query", description="输入消息,用于模型的输入,一般为问题。") ================================================ FILE: python/core/components/llms/query_decomposition/component.py ================================================ # Copyright (c) 2023 Baidu, Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """ query decomposition """ from pydantic import Field from typing import Optional from appbuilder.core.message import Message from appbuilder.core.component import ComponentArguments from appbuilder.core.components.llms.base import CompletionBaseComponent from appbuilder.utils.trace.tracer_wrapper import components_run_trace, components_run_stream_trace from .base import QueryDecompositionMeta class QueryDecomposition(CompletionBaseComponent): r""" 尝试对已经判定为复杂问题的原始问题进行拆解,把复杂问题拆解为一个个简单问题。广泛用于知识问答场景。 Examples: .. code-block:: python import os import appbuilder # 请前往千帆AppBuilder官网创建密钥,流程详见:https://cloud.baidu.com/doc/AppBuilder/s/Olq6grrt6#1%E3%80%81%E5%88%9B%E5%BB%BA%E5%AF%86%E9%92%A5 os.environ["APPBUILDER_TOKEN"] = "..." query_decomposition = appbuilder.QueryDecomposition(model="DeepSeek-V3.1") msg = "吸塑包装盒在工业化生产和物流运输中分别有什么重要性?" msg = appbuilder.Message(msg) answer = query_decomposition(msg) print("Answer: \n{}".format(answer.content)) """ name = "query_decomposition" version = "v1" meta = QueryDecompositionMeta manifests = [ { "name": "query_decomposition", "description": "尝试对已经判定为复杂问题的原始问题进行拆解,把复杂问题拆解为一个个简单问题。广泛用于知识问答场景。", "parameters": { "type": "object", "properties": { "query": { "type": "string", "description": "输入消息,用于模型的输入,一般为问题。" } }, "required": [ "query" ] } } ] def __init__( self, model=None, secret_key: Optional[str] = None, gateway: str = "", lazy_certification: bool = False, **kwargs ): """初始化QueryDecompositionMeta任务。 Args: model (str|None): 模型名称,用于指定要使用的千帆模型。 secret_key (str, 可选): 用户鉴权token, 默认从环境变量中获取: os.getenv("APPBUILDER_TOKEN", ""). gateway (str, 可选): 后端网关服务地址,默认从环境变量中获取: os.getenv("GATEWAY_URL", "") lazy_certification (bool, 可选): 延迟认证,为True时在第一次运行时认证. Defaults to False. Returns: None """ super().__init__( QueryDecompositionMeta, model=model, secret_key=secret_key, gateway=gateway, lazy_certification=lazy_certification) @components_run_trace def run(self, message, stream=False, temperature=1e-10, top_p=0.0): """ 给定输入(message)到模型运行,同时指定运行参数,并返回结果。 Args: message (obj:`Message`): 输入消息,用于模型的主要输入内容。这是一个必需的参数。 stream (bool, optional): 指定是否以流式形式返回响应。默认为 False。 temperature (float, optional): 模型配置的温度参数,用于调整模型的生成概率。取值范围为 0.0 到 1.0,其中较低的值使生成更确定性,较高的值使生成更多样性。默认值为 1e-10。 top_p (float, optional): 影响输出文本的多样性,取值越大,生成文本的多样性越强。取值范围为 0.0 到 1.0,其中较低的值使生成更确定性,较高的值使生成更多样性。默认值为 0。 Returns: obj:`Message`: 模型运行后的输出消息。 """ return super().run(message=message, stream=stream, temperature=temperature, top_p=top_p) @components_run_stream_trace def tool_eval(self, name: str, streaming: bool = False, **kwargs): """ tool_eval for function call """ traceid = kwargs.get("traceid") query = kwargs.get("query", None) if not query: raise ValueError("param `query` is required") msg = Message(query) model_configs = kwargs.get('model_configs', {}) temperature = model_configs.get("temperature", 1e-10) top_p = model_configs.get("top_p", 0.0) message = super().run(message=msg, stream=False, temperature=temperature, top_p=top_p, request_id=traceid) if streaming: yield str(message.content) else: return str(message.content) ================================================ FILE: python/core/components/llms/query_rewrite/README.md ================================================ # 多轮改写 (QueryRewrite) ## 简介 多轮改写组件 (QueryRewrite) 是一个用于处理多轮对话和查询改写的组件。它主要用于理解和优化用户与机器人的交互过程,进行指代消解及省略补全。该组件支持不同的改写类型,可根据对话历史生成更准确的用户查询。 ### 功能介绍 多轮改写组件 (QueryRewrite) 据用户和机器人的聊天记录,改写用户当前query,利用大语言模型的理解及生成能力,进行指代消解及省略补全。 ### 特色优势 多轮改写组件 (QueryRewrite) ,基于百度自研的大语言模型文心一言,无需更多的prompt描述,即可根据对话历史生成更准确的用户查询。 ### 应用场景 多轮改写组件 (QueryRewrite) 可用于智能问答、对话式搜索等场景。 ## 基本用法 以下是一个简单的例子,展示如何快速开始使用 QueryRewrite 组件: ```python import os import appbuilder # 请前往千帆AppBuilder官网创建密钥,流程详见:https://cloud.baidu.com/doc/AppBuilder/s/Olq6grrt6#1%E3%80%81%E5%88%9B%E5%BB%BA%E5%AF%86%E9%92%A5 os.environ["APPBUILDER_TOKEN"] = '...' # 初始化并使用 QueryRewrite 组件 query_rewrite = appbuilder.QueryRewrite(model="DeepSeek-V3.1") answer = query_rewrite(appbuilder.Message(['我应该怎么办理护照?', '您可以查询官网或人工咨询', '我需要准备哪些材料?', '身份证、免冠照片一张以及填写完整的《中国公民因私出国(境)申请表》', '在哪里办']), rewrite_type="带机器人回复") print(answer) ``` ## 参数说明 ### 鉴权配置 使用组件之前,请首先申请并设置鉴权参数,可参考[组件使用流程](https://cloud.baidu.com/doc/AppBuilder/s/Olq6grrt6#1%E3%80%81%E5%88%9B%E5%BB%BA%E5%AF%86%E9%92%A5)。 ```python # 设置环境中的TOKEN,以下示例略 os.environ["APPBUILDER_TOKEN"] = "bce-YOURTOKEN" ``` ### 初始化参数 - `model`: 模型名称,用于指定要使用的千帆模型。 ### 调用参数 |参数名称 |参数类型 |是否必须 |描述 |示例值| |--------|--------|--------|----|------| |message |Message |是 |需要改写的文本,用于模型的主要输入内容,这是一个必需的参数。 |Message(content=['我应该怎么办理护照?', '您可以查询官网或人工咨询','我需要准备哪些材料?', '身份证、免冠照片一张以及填写完整的《中国公民因私出国(境)申请表》', '在哪里办']) | |rewrite_type |str |否 |改写类型选项,可选值为 '带机器人回复'(改写时参考user查询历史和assistant回复历史),'仅用户查询'(改写时参考user查询历史)。 默认是"带机器人回复" |"带机器人回复" | |stream |bool | 否 |指定是否以流式形式返回响应。默认为 False。 |False | |temperature |float | 否 |模型配置的温度参数,用于调整模型的生成概率。取值范围为 0.0 到 1.0,其中较低的值使生成更确定性,较高的值使生成更多样性。默认值为 1e-10。 |1e-10 | ### 响应参数 |参数名称 |参数类型 |描述 |示例值| |--------|--------|----|------| |result |Message |返回结果|Message(content="身份证在哪办")| ### 响应示例 ``` Message(name=msg, content="身份证在哪办", mtype=dict, extra={}) ``` ## 示例和案例研究 实际应用中,QueryRewrite 可用于多种场景,如信息检索、智能对话等。 ## 更新记录和贡献 当前版本:v2 (2023-12) ================================================ FILE: python/core/components/llms/query_rewrite/__init__.py ================================================ """query_rewrite""" from .component import QueryRewrite ================================================ FILE: python/core/components/llms/query_rewrite/base.py ================================================ # Copyright (c) 2023 Baidu, Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from appbuilder.core.message import Message from appbuilder.core.component import ComponentArguments from pydantic import Field from enum import Enum class RewriteTypeChoices(Enum): """ 多轮改写类型选择 """ user_assistant_user = "带机器人回复" user_user = "仅用户查询" def to_chinese(self): """ 将RewriteTypeChoices枚举类中的值转换为中文描述。 Args: 无参数 Returns: 返回一个字典,键是RewriteTypeChoices枚举类的成员,值为对应的中文描述字符串。 """ descriptions = { RewriteTypeChoices.user_assistant_user: "带机器人回复", RewriteTypeChoices.user_user: "仅用户查询", } return descriptions[self] class QueryRewriteArgs(ComponentArguments): """ 多轮改写配置 Attributes: message: Message = Field(...) rewrite_type: RewriteTypeChoices = Field(...) """ message: Message = Field(..., variable_name="query", description="输入消息,用于模型的主要输入内容,例如'['我应该怎么办理护照?', '您可以查询官网或人工咨询', \ '我需要准备哪些材料?', '身份证、免冠照片一张以及填写完整的《中国公民因私出国(境)申请表》', '在哪里办']'") rewrite_type: RewriteTypeChoices = Field(..., variable_name="rewrite_type", description="改写类型选项,可选值为 '带机器人回复'(改写时参考user查询历史和assistant回复历史),\ '仅用户查询'(改写时参考user查询历史)。 默认是'带机器人回复'. ") ================================================ FILE: python/core/components/llms/query_rewrite/component.py ================================================ # Copyright (c) 2023 Baidu, Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """ 多轮改写 """ from appbuilder.core.components.llms.base import CompletionBaseComponent from appbuilder.core.message import Message from appbuilder.core.component import ComponentArguments from pydantic import BaseModel, Field from typing import Optional from appbuilder.utils.trace.tracer_wrapper import components_run_trace, components_run_stream_trace from .base import QueryRewriteArgs class QueryRewrite(CompletionBaseComponent): """ 多轮改写大模型组件, 基于生成式大模型进行多轮对话query改写的组件。它主要用于理解和优化用户与机器人的交互过程,进行指代消解及省略补全。该组件支持不同的改写类型,可根据对话历史生成更准确的用户查询。 Examples: .. code-block:: python import appbuilder os.environ["APPBUILDER_TOKEN"] = '...' query_rewrite = appbuilder.QueryRewrite(model="DeepSeek-V3.1") answer = query_rewrite(appbuilder.Message(['我应该怎么办理护照?', '您可以查询官网或人工咨询', '我需要准备哪些材料?', '身份证、免冠照片一张以及填写完整的《中国公民因私出国(境)申请表》', '在哪里办']), rewrite_type="带机器人回复") """ name = "query_rewrite" version = "v1" meta = QueryRewriteArgs manifests = [ { "name": "query_rewrite", "description": "多轮改写大模型组件, 基于生成式大模型进行多轮对话query改写的组件。它主要用于理解和优化用户与机器人" "的交互过程,进行指代消解及省略补全。该组件支持不同的改写类型,可根据对话历史生成更准确的用户查询。", "parameters": { "type": "object", "properties": { "query": { "type": "string", "description": "输入消息,用于模型的主要输入内容" }, "rewrite_type": { "type": "string", "enum": [ "带机器人回复", "仅用户查询" ] } }, "required": [ "query" ] } } ] def __init__( self, model=None, secret_key: Optional[str] = None, gateway: str = "", lazy_certification: bool = False, **kwargs ): """QueryRewrite模型。 Args: model (str|None): 模型名称,用于指定要使用的千帆模型。 secret_key (str, 可选): 用户鉴权token, 默认从环境变量中获取: os.getenv("APPBUILDER_TOKEN", ""). gateway (str, 可选): 后端网关服务地址,默认从环境变量中获取: os.getenv("GATEWAY_URL", "") lazy_certification (bool, 可选): 延迟认证,为True时在第一次运行时认证. Defaults to False. Returns: None """ super().__init__( QueryRewriteArgs, model=model, secret_key=secret_key, gateway=gateway, lazy_certification=lazy_certification) @components_run_trace def run(self, message, rewrite_type="带机器人回复", stream=False, temperature=1e-10, top_p=0): """ 使用给定的输入运行模型并返回结果。 Args: message (obj:`Message`): 输入消息,用于模型的主要输入内容。这是一个必需的参数。 rewrite_type (str, 可选): 改写类型选项,可选值为 '带机器人回复'(改写时参考user查询历史和assistant回复历史), '仅用户查询'(改写时参考user查询历史)。默认为"带机器人回复"。 stream (bool, 可选): 指定是否以流式形式返回响应。默认为 False。 temperature (float, 可选): 模型配置的温度参数,用于调整模型的生成概率。 取值范围为 0.0 到 1.0,其中较低的值使生成更确定性,较高的值使生成更多样性。 默认值为 1e-10。 top_p (float, 可选): 影响输出文本的多样性,取值越大,生成文本的多样性越强。 取值范围为 0.0 到 1.0,其中较低的值使生成更确定性,较高的值使生成更多样性。 默认值为 0。 Returns: obj:`Message`: 模型运行后的输出消息。 Raises: ValueError: 如果输入消息为空或不符合要求,将抛出 ValueError 异常。 """ if message is None: raise ValueError("input message is required") sum_len = sum(len(item) for item in message.content) if len(message.content) > 10 or len(message.content) % 2 == 0: raise ValueError(f"illegal input,expected len(message.content) in {1,3,5,9}, got {len(message.content)}") if sum_len > 4000: raise ValueError(f"illegal input, expected length <= 4000, got {sum_len}") if rewrite_type == "带机器人回复": converted_input = ''.join([f"{'User:' if i % 2 == 0 else 'Assistant:'}\ {message.content[i]}\n" for i in range(len(message.content))]) else: converted_input = ''.join([f"User1: {message.content[i]}\n" for i in range(0, len(message.content), 2)]) message.content = converted_input return super().run(message=message, rewrite_type=rewrite_type, stream=stream, temperature=temperature, top_p=top_p) @components_run_stream_trace def tool_eval(self, name: str, streaming: bool = False, **kwargs): """ tool_eval for function call """ traceid = kwargs.get("traceid") rewrite_type = kwargs.get("rewrite_type", "带机器人回复") query = kwargs.get("query", None) if not query: raise ValueError("param `query` is required") msg = Message(query) model_configs = kwargs.get('model_configs', {}) temperature = model_configs.get("temperature", 1e-10) top_p = model_configs.get("top_p", 0.0) message = super().run(message=msg, rewrite_type=rewrite_type, stream=False, temperature=temperature, top_p=top_p, trace_id=traceid) if streaming: yield str(message.content) else: return str(message.content) ================================================ FILE: python/core/components/llms/similar_question/README.md ================================================ # 相似问生成(SimilarQuestion) ## 简介 相似问生成组件(SimilarQuestion)可以用于基于输入的问题,挖掘出与该问题相关的类似问题。广泛用于客服、问答等场景。 ### 功能介绍 基于输入的问题,挖掘出与该问题相关的类似问题。 ### 特色优势 相似问生成组件,可一次生成多个相似问题,准确率可达90%以上。 ### 应用场景 应用于客服、问答等场景 ## 基本用法 ### 快速开始 ```python import os import appbuilder # 请前往千帆AppBuilder官网创建密钥,流程详见:https://cloud.baidu.com/doc/AppBuilder/s/Olq6grrt6#1%E3%80%81%E5%88%9B%E5%BB%BA%E5%AF%86%E9%92%A5 os.environ["APPBUILDER_TOKEN"] = "..." similar_question = appbuilder.SimilarQuestion(model="DeepSeek-V3.1") msg = "我想吃冰淇淋,哪里的冰淇淋比较好吃?" msg = appbuilder.Message(msg) answer = similar_question(msg) print("Answer: \n{}".format(answer.content)) ``` ## 参数说明 ### 初始化参数 无 ### 调用参数 |参数名称 |参数类型 |是否必须 |描述 |示例值| |--------|--------|--------|----|------| | message | String |是 |输入消息,用于模型的主要输入内容。这是一个必需的参数。| `Message("我想吃冰淇淋,哪里的冰淇淋比较好吃?")` | | stream |bool|否 |指定是否以流式形式返回响应。默认为 False。| False | | temperature |float|否 |模型配置的温度参数,用于调整模型的生成概率。取值范围为 0.0 到 1.0,其中较低的值使生成更确定性,较高的值使生成更多样性。默认值为 1e-10。 | 1e-10 | ### 响应参数 |参数名称 |参数类型 |描述 |示例值| |--------|--------|----|------| | result | String | 返回结果 | "1. 哪里能品尝到美味的冰淇淋?\n2. 哪..." | ### 响应示例 ```text 1. 哪里能品尝到美味的冰淇淋? 2. 哪里能买到好吃的冰淇淋? 3. 哪里能品尝到正宗的冰淇淋? 4. 哪里能品尝到最新鲜的冰淇淋? 5. 哪里能买到口感最好的冰淇淋? 6. 哪里能品尝到最经典的冰淇淋? ``` ### 错误码 |错误码|描述| |------|---| ## 高级用法 ### 特殊场景示例 你可以根据特定的场景调整参数来获得更精确的结果,例如: ```python # 流式返回, 调整模型temperature参数 answer = similar_question(msg, stream=True, temperature=0.5) ``` ## 示例和案例研究 ### 示例 - **场景:** 用户提出问题 - **输入:** "我想吃冰淇淋,哪里的冰淇淋比较好吃?" - **输出:** 1. 请问哪里的冰淇淋最美味? 2. 在哪些地方可以品尝到最好的冰淇淋? ..... ## 更新记录和贡献 * 相似问生成能力 (2023-12) ================================================ FILE: python/core/components/llms/similar_question/__init__.py ================================================ from .component import SimilarQuestion ================================================ FILE: python/core/components/llms/similar_question/base.py ================================================ # Copyright (c) 2023 Baidu, Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from pydantic import Field from appbuilder.core.message import Message from appbuilder.core.component import ComponentArguments class SimilarQuestionMeta(ComponentArguments): """ SimilarQuestionMeta Attributes: message (Message): 输入消息,用于模型的输入,一般为问题。 """ message: Message = Field(..., variable_name="query", description="输入消息,用于模型的输入,一般为问题。") ================================================ FILE: python/core/components/llms/similar_question/component.py ================================================ # Copyright (c) 2023 Baidu, Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """ similar question """ from typing import Optional from appbuilder.core.message import Message from appbuilder.core.components.llms.base import CompletionBaseComponent from appbuilder.utils.trace.tracer_wrapper import components_run_trace, components_run_stream_trace from .base import SimilarQuestionMeta class SimilarQuestion(CompletionBaseComponent): r""" 基于输入的问题, 挖掘出与该问题相关的类似问题。广泛用于客服、问答等场景。 Examples: .. code-block:: python import os import appbuilder os.environ["APPBUILDER_TOKEN"] = "..." qa_mining = appbuilder.SimilarQuestion(model="DeepSeek-V3.1") msg = "我想吃冰淇淋,哪里的冰淇淋比较好吃?" msg = appbuilder.Message(msg) answer = qa_mining(msg) print("Answer: \n{}".format(answer.content)) """ name = "similar_question" version = "v1" meta = SimilarQuestionMeta manifests = [ { "name": "similar_question", "description": "基于输入的问题,挖掘出与该问题相关的类似问题。", "parameters": { "type": "object", "properties": { "query": { "type": "string", "description": "输入的问题,用于大模型根据该问题输出相关的类似问题。" } }, "required": [ "query" ] } } ] def __init__( self, model=None, secret_key: Optional[str] = None, gateway: str = "", lazy_certification: bool = False, **kwargs ): """初始化SimilarQuestionMeta任务。 Args: model (str|None): 模型名称,用于指定要使用的千帆模型。 secret_key (str, 可选): 用户鉴权token, 默认从环境变量中获取: os.getenv("APPBUILDER_TOKEN", ""). gateway (str, 可选): 后端网关服务地址,默认从环境变量中获取: os.getenv("GATEWAY_URL", "") lazy_certification (bool, 可选): 延迟认证,为True时在第一次运行时认证. Defaults to False. Returns: None """ super().__init__( SimilarQuestionMeta, model=model, secret_key=secret_key, gateway=gateway, lazy_certification=lazy_certification) @components_run_trace def run(self, message, stream=False, temperature=1e-10, top_p=0.0, request_id=None): """ 给定输入(message)到模型运行,同时指定运行参数,并返回结果。 Args: message (obj:`Message`): 输入消息,用于模型的主要输入内容。这是一个必需的参数。 stream (bool, 可选): 指定是否以流式形式返回响应。默认为 False。 temperature (float, 可选): 模型配置的温度参数,用于调整模型的生成概率。取值范围为 0.0 到 1.0,其中较低的值使生成更确定性,较高的值使生成更多样性。默认值为 1e-10。 top_p(float, 可选): 影响输出文本的多样性,取值越大,生成文本的多样性越强。取值范围为 0.0 到 1.0,其中较低的值使生成更确定性,较高的值使生成更多样性。默认值为 0。 Returns: obj:`Message`: 模型运行后的输出消息。 """ return super().run(message=message, stream=stream, temperature=temperature, top_p=top_p, request_id=request_id) @components_run_stream_trace def tool_eval(self, name: str, streaming: bool = False, **kwargs): """ 执行函数调用的评估工具。 Args: name (str): 函数名。 streaming (bool, optional): 是否以流式方式输出结果。默认为False。 **kwargs: 其他关键字参数,包括: traceid (str, optional): 请求的追踪ID。 query (str): 输入的查询字符串。 model_configs (dict, optional): 模型配置字典,包括: temperature (float, optional): 温度参数,用于控制输出结果的多样性。默认为1e-10。 top_p (float, optional): 截断概率,用于控制生成文本的质量。默认为0.0。 Returns: 如果streaming为False,则返回评估结果的字符串表示。 如果streaming为True,则生成评估结果的字符串表示的迭代器。 Raises: ValueError: 如果未提供query参数,则抛出此异常。 """ traceid = kwargs.get("traceid") query = kwargs.get("query", None) if not query: raise ValueError("param `query` is required") msg = Message(query) model_configs = kwargs.get('model_configs', {}) temperature = model_configs.get("temperature", 1e-10) top_p = model_configs.get("top_p", 0.0) message = super().run(message=msg, stream=False, temperature=temperature, top_p=top_p, request_id=traceid) if streaming: yield str(message.content) else: return str(message.content) ================================================ FILE: python/core/components/llms/style_rewrite/README.md ================================================ # 风格转写 (StyleRewrite) ## 简介 风格转写组件(StyleRewrite) 可以基于生成式大模型对文本的风格进行改写。支持多种文本风格,包括营销、客服、直播、激励及教学话术。 ### 功能介绍 文本风格转写能够将一段文本转换成不同的风格(营销、客服、直播、激励及教学话术),同时保持原文的基本意义不变。基于大模型的文本理解与生成能力,根据用户指定的风格重新组织语言和表达方式。它不仅能识别和模仿不同的写作风格,还能在转换过程中保持文本的连贯性和逻辑性。 ### 特色优势 - 准确性与流畅性: 在转写时保持原文意义的准确传达,同时确保文本流畅自然。 - 风格多样性: 能够覆盖广泛的文本风格,满足不同场合的需求。 - 提高效率: 节省人工重新编写文本的时间。 ### 应用场景 不同的文本风格可以应用到以下不同的场景中: - 营销风格:该风格的转写能力可以根据商品的描述生成一段营销文案,生动地为用户介绍商品特点。 - 客服风格:针对客户关心的产品问题,用礼貌易懂的口语化文本进行回复,提升客户服务体验。 - 直播风格:在线直播平台的主播或内容创作者可以使用文本风格转写技术来优化其直播脚本,使其更吸引特定的观众群体。 - 激励风格:在激励演讲、团队管理或个人发展领域,文本风格转写可以帮助创建更有动力和启发性的内容。起到鼓舞人心的作用。 - 教学风格:可以帮助教师或教材作者生成互动感强、并且引人入胜的教学材料。 ## 基本用法 以下是一个简单的例子,展示如何快速开始使用 StyleRewrite 组件: ```python import os import appbuilder # 请前往千帆AppBuilder官网创建密钥,流程详见:https://cloud.baidu.com/doc/AppBuilder/s/Olq6grrt6#1%E3%80%81%E5%88%9B%E5%BB%BA%E5%AF%86%E9%92%A5 os.environ["APPBUILDER_TOKEN"] = "..." # 初始化并使用 StyleRewrite 组件 style_rewrite = appbuilder.StyleRewrite(model="DeepSeek-V3.1") answer = style_rewrite(appbuilder.Message("文心大模型发布新版"), style="激励话术") ``` ## 参数说明 ### 鉴权说明 使用组件之前,请首先申请并设置鉴权参数,可参考[组件使用流程](https://cloud.baidu.com/doc/AppBuilder/s/Olq6grrt6#1%E3%80%81%E5%88%9B%E5%BB%BA%E5%AF%86%E9%92%A5)。 ```python # 设置环境中的TOKEN,以下示例略 os.environ["APPBUILDER_TOKEN"] = "bce-YOURTOKEN" ``` ### 初始化参数 无 ### 调用参数 |参数名称 |参数类型 |是否必须 |描述 |示例值| |--------|--------|--------|----|------| |message |String |是 |需要改写的文本|文心大模型发布新版| |style|String|否 |想要转换的文本风格,默认为"营销话术",目前支持营销、客服、直播、激励及教学五种话术。|激励话术| |stream|bool|否 |指定是否以流式形式返回响应,默认为 False。|True| |temperature|float|否 |模型配置的温度参数,默认为 1e-10|1e-10| ### 响应参数 |参数名称 |参数类型 |描述 |示例值| |--------|--------|----|------| |result |String |返回结果|"文心NLP大模型平台再添新功绩!近日,文心NLP大模型平台成功发布新版,这标志着我们在这个领域又取得了新的里程碑。新版的文心NLP大模型平台在技术、功能和易用性等方面都有了显著的提升,为用户提供了更好的使用体验。"| ### 响应示例 ```json {"result": "文心NLP大模型平台再添新功绩!近日,文心NLP大模型平台成功发布新版,这标志着我们在这个领域又取得了新的里程碑。新版的文心NLP大模型平台在技术、功能和易用性等方面都有了显著的提升,为用户提供了更好的使用体验。"} ``` ### 错误码 |错误码|描述| |------|---| ## 高级用法 目前该模块仅提供基础的文本风格转写功能。 ## 更新记录和贡献 * 当前版本:v1 ================================================ FILE: python/core/components/llms/style_rewrite/__init__.py ================================================ """StyleRewrite""" from .component import StyleRewrite ================================================ FILE: python/core/components/llms/style_rewrite/base.py ================================================ # Copyright (c) 2023 Baidu, Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from appbuilder.core.message import Message from appbuilder.core.component import ComponentArguments from pydantic import Field from enum import Enum class StyleChoices(Enum): """ StyleChoices枚举类,包含了五种风格: Attributes: YINGXIAO : 营销话术 JIAOXUE : 教学话术 JILI : 激励话术 KEFU : 客服话术 ZHIBO : 直播话术 """ YINGXIAO = "营销话术" JIAOXUE = "教学话术" JILI = "激励话术" KEFU = "客服话术" ZHIBO = "直播话术" def to_chinese(self): """ 将StyleChoices枚举类中的值转换为中文描述。 Args: 无参数 Returns: 返回一个字典,键是StyleChoices枚举类的成员,值为对应的中文描述字符串。 """ descriptions = { StyleChoices.YINGXIAO: "营销话术", StyleChoices.JIAOXUE: "教学话术", StyleChoices.JILI: "激励话术", StyleChoices.KEFU: "客服话术", StyleChoices.ZHIBO: "直播话术" } return descriptions[self] class StyleRewriteArgs(ComponentArguments): """ 文本风格转写配置 Attributes: message: Message style: StyleChoices """ message: Message = Field(..., variable_name="query", description="需要改写的文本,该字段为必须字段。") style: StyleChoices = Field(..., variable_name="style", description="想要转换的文本风格,目前有营销、客服、直播、激励及教学五种话术可选") ================================================ FILE: python/core/components/llms/style_rewrite/component.py ================================================ # Copyright (c) 2023 Baidu, Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from appbuilder.core.components.llms.base import CompletionBaseComponent from appbuilder.core.message import Message from typing import Optional from appbuilder.utils.trace.tracer_wrapper import components_run_trace, components_run_stream_trace from .base import StyleRewriteArgs class StyleRewrite(CompletionBaseComponent): """ 文本风格转写大模型组件, 基于生成式大模型对文本的风格进行改写,支持有营销、客服、直播、激励及教学五种话术。 Examples: .. code-block:: python import os import appbuilder os.environ["APPBUILDER_TOKEN"] = '...' style_rewrite = appbuilder.StyleRewrite(model="DeepSeek-V3.1") answer = style_rewrite(appbuilder.Message("文心大模型发布新版本"), style="激励话术") """ name = "style_rewrite" version = "v1" meta = StyleRewriteArgs manifests = [ { "name": "style_rewrite", "description": "能够将一段文本转换成不同的风格(营销、客服、直播、激励及教学话术),同时保持原文的基本意义不变。", "parameters": { "type": "object", "properties": { "query": { "type": "string", "description": "需要改写的文本。" }, "style": { "type": "string", "description": "想要转换的文本风格,目前有营销、客服、直播、激励及教学五种话术可选. 默认是营销话术。", "enum": ["营销话术", "客服话术", "直播话术", "激励话术", "教学话术"] } }, "required": [ "query" ] } } ] def __init__( self, model=None, secret_key: Optional[str] = None, gateway: str = "", lazy_certification: bool = False, **kwargs ): """初始化StyleRewrite模型。 Args: model (str|None): 模型名称,用于指定要使用的千帆模型。 secret_key (str, 可选): 用户鉴权token, 默认从环境变量中获取: os.getenv("APPBUILDER_TOKEN", ""). gateway (str, 可选): 后端网关服务地址,默认从环境变量中获取: os.getenv("GATEWAY_URL", "") lazy_certification (bool, 可选): 延迟认证,为True时在第一次运行时认证. Defaults to False. Returns: None """ super().__init__( StyleRewriteArgs, model=model, secret_key=secret_key, gateway=gateway, lazy_certification=lazy_certification) @components_run_trace def run(self, message, style="营销话术", stream=False, temperature=1e-10, top_p=0.0, request_id=None): """ 使用给定的输入运行模型并返回结果。 Args: message (obj:`Message`): 输入消息,用于模型的主要输入内容。这是一个必需的参数。 style (str, optional): 想要转换的文本风格,目前有营销、客服、直播、激励及教学五种话术可选。默认为"营销话术"。 stream (bool, optional): 指定是否以流式形式返回响应。默认为 False。 temperature (float, optional): 模型配置的温度参数,用于调整模型的生成概率。取值范围为 0.0 到 1.0,其中较低的值使生成更确定性,较高的值使生成更多样性。默认值为 1e-10。 top_p (float, optional): 影响输出文本的多样性,取值越大,生成文本的多样性越强。取值范围为 0.0 到 1.0,其中较低的值使生成更确定性,较高的值使生成更多样性。默认值为 0。 Returns: obj:`Message`: 模型运行后的输出消息。 """ return super().run(message=message, style=style, stream=stream, temperature=temperature, top_p=top_p, request_id=request_id) @components_run_stream_trace def tool_eval(self, name: str, streaming: bool = False, **kwargs): """ 执行工具评估函数 Args: name (str): 函数名称,本函数不使用该参数,但保留以符合某些框架的要求。 streaming (bool, optional): 是否以流的形式返回结果。默认为 False,即一次性返回结果。如果设置为 True,则以生成器形式逐个返回结果。 **kwargs: 其他参数,包含但不限于: traceid (str): 请求的跟踪ID,用于日志记录和跟踪。 query (str): 待评估的文本。 style (str, optional): 评估风格,可选值为 ['营销话术', '客服话术', '直播话术', '激励话术', '教学话术']。默认为 '营销话术'。 model_configs (dict, optional): 模型配置参数,可选的键包括: temperature (float, optional): 温度参数,用于控制生成文本的随机性。默认为 1e-10。 top_p (float, optional): top_p 采样参数,用于控制生成文本的多样性。默认为 0.0。 Returns: 如果 streaming 为 False,则直接返回评估结果字符串。 如果 streaming 为 True,则以生成器形式逐个返回评估结果字符串。 Raises: ValueError: 如果缺少参数 'query'。 """ traceid = kwargs.get("traceid") query = kwargs.get("query", None) if not query: raise ValueError("param `query` is required") msg = Message(query) style = kwargs.get("style", "营销话术") if style not in ["营销话术", "客服话术", "直播话术", "激励话术", "教学话术"]: style = "营销话术" model_configs = kwargs.get('model_configs', {}) temperature = model_configs.get("temperature", 1e-10) top_p = model_configs.get("top_p", 0.0) message = super().run(message=msg, style=style, stream=False, temperature=temperature, top_p=top_p, request_id=traceid) if streaming: yield str(message.content) else: return str(message.content) ================================================ FILE: python/core/components/llms/style_writing/README.md ================================================ # 风格写作(StyleWriting) ## 简介 风格写作组件(StyleWriting)是一款基于生成式大模型进行文本创作的工具,支持多种风格,包括B站、小红书等,适用于编写文案、广告等多种场景。 ### 功能介绍 风格写作组件(StyleWriting)根据用户的输入内容和风格要求,利用大语言模型的生成能力,自动生成符合特定风格的文案。 ### 特色优势 风格写作组件(StyleWriting),基于百度自研的大语言模型文新一言,提供内置的风格生成能力,无需更多的prompt描述,即可生成对应风格的文案。 ### 应用场景 风格写作组件(StyleWriting)可用于特定平台的文案生成分发营销场景。 ## 基本用法 为了快速开始使用风格写作组件,您可以参考以下步骤: ```python import appbuilder import os # 请前往千帆AppBuilder官网创建密钥,流程详见:https://cloud.baidu.com/doc/AppBuilder/s/Olq6grrt6#1%E3%80%81%E5%88%9B%E5%BB%BA%E5%AF%86%E9%92%A5 os.environ["APPBUILDER_TOKEN"] = "..." model = "DeepSeek-V3.1" style_writing = appbuilder.StyleWriting(model) query = "帮我写一篇关于人体工学椅的文案" style = "小红书" length = 100 msg = appbuilder.Message(query) answer = style_writing(message=msg, style_query=style, length=length) print(answer) ``` ## 参数说明 ### 鉴权说明 使用组件之前,请首先申请并设置鉴权参数,可参考[组件使用流程](https://cloud.baidu.com/doc/AppBuilder/s/Olq6grrt6#1%E3%80%81%E5%88%9B%E5%BB%BA%E5%AF%86%E9%92%A5)。 ```python # 设置环境中的TOKEN,以下示例略 os.environ["APPBUILDER_TOKEN"] = "bce-YOURTOKEN" ``` ### 初始化参数 - `model`: 模型名称,用于指定要使用的千帆模型。 ### 调用参数 |参数名称 |参数类型 |是否必须 |描述 |示例值| |--------|--------|--------|----|------| |message |Message |是 |输入的消息,用于模型的主要输入内容,这是一个必需的参数。 |Message(content="帮我生成一个介绍保温杯的话术") | |style_query |str |否 |定义生成文案的格式,包括"通用"、"B站"、"小红书",默认为"通用" |"通用" | |length |int |否 |定义生成文案的长度,可选 '短' (100), '中' (300), '长' (600), 默认100 |100 | |stream |bool | 否 |指定是否以流式形式返回响应。默认为 False。 |False | |temperature |float | 否 |模型配置的温度参数,用于调整模型的生成概率。取值范围为 0.0 到 1.0,其中较低的值使生成更确定性,较高的值使生成更多样性。默认值为 1e-10。 |0.7 | ### 响应参数 |参数名称 |参数类型 |描述 |示例值| |--------|--------|----|------| |result |Message |返回结果|Message(content="大家好,我给你们介绍一款家里和办公室都要备上的保温杯。...")| ### 响应示例 ``` Message(name=msg, content=大家好,我给你们介绍一款家里和办公室都要备上的保温杯。我平常上班的时候都会装上一杯热开水,但用普通保温杯装上一会就凉了,所以我赶紧在网上淘了一个好货。它是双层设计,内层是不锈钢材质,外层是玻璃材质,非常贴心,冷热都能装。装上热水,保温效果非常出色,到晚上还是热的。这个保温杯的外观也非常漂亮,采用优质不锈钢材质,耐磨、易清洗。同时,它还非常轻便,可以轻松放入口袋、背包中。有了这个保温杯后,我再也不用担心喝水问题了。无论是在家里、办公室还是户外活动,它都能随时随地为你提供热水。而且,它还非常安全、健康,采用了优质的保温材料和先进的生产工艺。无论男女老少都可以使用这款保温杯哦。快来购买吧。", mtype=dict, extra={}) ``` ## 高级用法 使用风格写作组件进行更复杂的文本创作,例如调整不同的风格和长度参数来适应特定的写作场景。 ## 更新记录和贡献 - 初始版本发布(2023-10) ================================================ FILE: python/core/components/llms/style_writing/__init__.py ================================================ """ Copyright (c) 2023 Baidu, Inc. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. """ from .component import StyleWriting ================================================ FILE: python/core/components/llms/style_writing/base.py ================================================ # Copyright (c) 2023 Baidu, Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from appbuilder.core.message import Message from appbuilder.core.component import ComponentArguments from pydantic import Field from enum import Enum class StyleQueryChoices(Enum): """ StyleQueryChoices是一个枚举类型,包含三个选项: Attributes: BILIBILI ("B站") XIAOHONGSHU ("小红书") GENERAL ("通用") """ BILIBILI = "B站" XIAOHONGSHU = "小红书" GENERAL = "通用" def to_chinese(self): """ 将StyleQueryChoices枚举类中的值转换为中文描述。 Args: 无参数 Returns: 返回一个字典,键是StyleQueryChoices枚举类的成员,值为对应的中文描述字符串。 """ descriptions = { StyleQueryChoices.BILIBILI: "B站", StyleQueryChoices.XIAOHONGSHU: "小红书", StyleQueryChoices.GENERAL: "通用", } return descriptions[self] class LengthChoices(Enum): SHORT = 100 # 短 MEDIUM = 300 # 中 LONG = 600 # 长 def to_chinese(self): """ 将LengthChoices枚举对象转换为中文描述。 Args: 无参数 Returns: str: 转换后的中文描述,包括"短"、"中"和"长"。 """ descriptions = { LengthChoices.SHORT: "短", LengthChoices.MEDIUM: "中", LengthChoices.LONG: "长", } return descriptions[self] class StyleWritingArgs(ComponentArguments): """ 风格写作配置 Attributes: message: Message = Field(...) style_query: StyleQueryChoices = Field(...) length: LengthChoices = Field(...) """ message: Message = Field(..., variable_name="query", description="输入消息,用于模型的主要输入内容,例如'帮我生成一个介绍保温杯的话术'") style_query: StyleQueryChoices = Field(..., variable_name="style_query", description="风格查询选项,可选值为 'B站', '小红书', '通用'。") length: LengthChoices = Field(..., variable_name="length", description="输出长度,可选值为 '短' (100), '中' (300), '长' (600)。") ================================================ FILE: python/core/components/llms/style_writing/component.py ================================================ # Copyright (c) 2023 Baidu, Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from appbuilder.core.components.llms.base import CompletionBaseComponent from appbuilder.core.message import Message from appbuilder.core.component import ComponentArguments from appbuilder.utils.trace.tracer_wrapper import components_run_trace, components_run_stream_trace from pydantic import Field from typing import Optional from .base import StyleQueryChoices, LengthChoices class StyleWritingArgs(ComponentArguments): """ 风格写作配置 Attributes: message: Message = Field(...) style_query: StyleQueryChoices = Field(...) length: LengthChoices = Field(...) """ message: Message = Field(..., variable_name="query", description="输入消息,用于模型的主要输入内容,例如'帮我生成一个介绍保温杯的话术'") style_query: StyleQueryChoices = Field(..., variable_name="style_query", description="风格查询选项,可选值为 'B站', '小红书', '通用'。") length: LengthChoices = Field(..., variable_name="length", description="输出长度,可选值为 '短' (100), '中' (300), '长' (600)。") class StyleWriting(CompletionBaseComponent): """ 风格写作大模型组件, 基于生成式大模型进行风格写作,支持B站、小红书等多种风格,可用于文案、广告等多种场景。 Examples: .. code-block:: python import os import appbuilder # 请前往千帆AppBuilder官网创建密钥,流程详见:https://cloud.baidu.com/doc/AppBuilder/s/Olq6grrt6#1%E3%80%81%E5%88%9B%E5%BB%BA%E5%AF%86%E9%92%A5 os.environ["APPBUILDER_TOKEN"] = '...' style_writing = appbuilder.StyleWriting(model="DeepSeek-V3.1") answer = style_writing(appbuilder.Message("帮我写一篇关于人体工学椅的文案"), style_query="小红书", length=100) """ name = "style_writing" version = "v1" meta = StyleWritingArgs manifests = [ { "name": "style_writing", "description": "根据用户输入的文案要求和文案风格,生成符合特定风格的产品介绍或宣传文案。目前支持生成小红书风格、B站风格或通用风格的文案。", "parameters": { "type": "object", "properties": { "query": { "type": "string", "description": "用于描述生成文案的主题和要求。" }, "style": { "type": "string", "description": "用于定义文案生成的风格,包括通用、B站、小红书,默认为通用。", "enum": ["通用", "B站", "小红书"] }, "length": { "type": "integer", "description": "用于定义输出内容的长度。有效的选项包括 100(短)、300(中)、600(长),默认值为 100。", "enum": [100, 300, 600] } }, "required": [ "query" ] } } ] def __init__( self, model=None, secret_key: Optional[str] = None, gateway: str = "", lazy_certification: bool = False, **kwargs ): """初始化StyleWriting模型。 Args: model (str|None): 模型名称,用于指定要使用的千帆模型。 secret_key (str, 可选): 用户鉴权token, 默认从环境变量中获取: os.getenv("APPBUILDER_TOKEN", ""). gateway (str, 可选): 后端网关服务地址,默认从环境变量中获取: os.getenv("GATEWAY_URL", "") lazy_certification (bool, 可选): 延迟认证,为True时在第一次运行时认证. Defaults to False. Returns: None """ super().__init__( StyleWritingArgs, model=model, secret_key=secret_key, gateway=gateway, lazy_certification=lazy_certification) @components_run_trace def run(self, message, style_query="通用", length=100, stream=False, temperature=1e-10, top_p=0, request_id=None): """ 使用给定的输入运行模型并返回结果。 Args: message (obj:`Message`): 输入消息,用于模型的主要输入内容。这是一个必需的参数。 style_query (str): 风格查询选项,用于指定写作风格。有效的选项包括 'B站', '小红书', '通用'。默认值为 '通用'。 length (int): 输出内容的长度。有效的选项包括 100(短),300(中),600(长)。默认值为 100。 stream (bool, optional): 指定是否以流式形式返回响应。默认为 False。 temperature (float, optional): 模型配置的温度参数,用于调整模型的生成概率。取值范围为 0.0 到 1.0,其中较低的值使生成更确定性,较高的值使生成更多样性。默认值为 1e-10。 top_p (float, optional): 影响输出文本的多样性,取值越大,生成文本的多样性越强。取值范围为 0.0 到 1.0,其中较低的值使生成更确定性,较高的值使生成更多样性。默认值为 0。 request_id (str, optional): 请求ID,用于跟踪和识别请求。 Returns: obj:`Message`: 模型运行后的输出消息。 """ return super().run(message=message, style_query=style_query, length=length, stream=stream, temperature=temperature, top_p=top_p, request_id=request_id) @components_run_stream_trace def tool_eval(self, name: str, streaming: bool = False, **kwargs): """ 对指定的工具进行函数调用评估。 Args: name (str): 工具名称。 streaming (bool, optional): 是否以流的方式返回结果。默认为False。 **kwargs: 其他参数。 Returns: str 或 generator: 如果 streaming 为 False,则返回评估结果字符串;如果 streaming 为 True,则返回一个生成器,每次迭代返回评估结果字符串的一部分。 Raises: ValueError: 如果未提供必要的参数 'query'。 """ traceid = kwargs.get("traceid") query = kwargs.get("query", None) if not query: raise ValueError("param `query` is required") msg = Message(query) style = kwargs.get("style", "通用") if style not in ["通用", "B站", "小红书"]: style = "通用" length = kwargs.get("length", 100) try: length = int(length) if length not in [100, 300, 600]: length = 100 except: length = 100 model_configs = kwargs.get('model_configs', {}) temperature = model_configs.get("temperature", 1e-10) top_p = model_configs.get("top_p", 0.0) message = super().run(message=msg, style_query=style, length=length, stream=False, temperature=temperature, top_p=top_p, request_id=traceid) if streaming: yield str(message.content) else: return str(message.content) ================================================ FILE: python/core/components/llms/tag_extraction/README.md ================================================ # 标签抽取(TagExtraction) ## 简介 标签抽取组件(TagExtraction)是一款高效的标签抽取组件,基于生成式大模型,专门用于从文本中提取关键标签。它适用于各种文本分析场景,如内容分类、关键词提取等。 ### 功能介绍 标签抽取组件(TagExtraction)专门设计用于从各类文本中高效地提取关键标签。此组件利用先进的生成式大模型,可以准确识别和提取文本中的重要信息,如关键词、短语或主题。它不仅能快速分析大量文本数据,还能精准识别文本的核心内容,支持用户快速了解文本的主要信息和结构 ### 特色优势 - 高效准确:基于先进的生成式大模型,提供高效且准确的标签提取功能。 - 适用广泛:能够处理不同类型和格式的文本数据,适用于多种文本分析场景。 - 格式友好:输出格式采用规范化编号输出,后处理时方便快捷。 ### 应用场景 标签抽取组件可以广泛应用于多种场景: - 内容分类:快速为文章或文档分类,提高信息管理和检索效率。 - 关键词提取:从文本中提取关键词,帮助用户快速了解文本主题和内容。 - 数据分析:在大数据分析中,可以用于预处理,提取有价值的信息。 - 搜索引擎优化:帮助网站或博客提取有效标签,改善其在搜索引擎中的可见度。 ## 基本用法 要开始使用 `TagExtraction`,首先需要设置环境变量 `APPBUILDER_TOKEN`,然后创建 `TagExtraction` 实例并传递文本消息。 ```python import os import appbuilder # 请前往千帆AppBuilder官网创建密钥,流程详见:https://cloud.baidu.com/doc/AppBuilder/s/Olq6grrt6#1%E3%80%81%E5%88%9B%E5%BB%BA%E5%AF%86%E9%92%A5 os.environ["APPBUILDER_TOKEN"] = '...' tag_extraction = appbuilder.TagExtraction(model="DeepSeek-V3.1") result = tag_extraction(appbuilder.Message("从这段文本中抽取关键标签")) ``` 这个例子展示了如何实例化 `TagExtraction` 组件并使用一个文本消息进行标签抽取。 ## 参数说明 ### 鉴权说明 使用组件之前,请首先申请并设置鉴权参数,可参考[组件使用流程](https://cloud.baidu.com/doc/AppBuilder/s/Olq6grrt6#1%E3%80%81%E5%88%9B%E5%BB%BA%E5%AF%86%E9%92%A5)。 ```python # 设置环境中的TOKEN,以下示例略 os.environ["APPBUILDER_TOKEN"] = "bce-YOURTOKEN" ``` ### 初始化参数 无 ### 调用参数 |参数名称 |参数类型 |是否必须 |描述 |示例值| |--------|--------|--------|----|------| |message |String |是 |需要抽取标签的文本|从这段文本中抽取关键标签| |stream|bool|否 |指定是否以流式形式返回响应,默认为 False。|True| |temperature|float|否 |模型配置的温度参数,用于调整模型的生成概率。取值范围为 0.0 到 1.0,其中较低的值使生成更确定性,较高的值使生成更多样性。默认值为 1e-10。|1e-10| ### 响应参数 |参数名称 |参数类型 |描述 |示例值| |--------|--------|----|------| |result |Message |返回结果|对象,包含模型运行后的输出消息。| ### 响应示例 ```json {"result": "1.5G 2.云计算 3.人工智能 4.数字经济 5.数据中心 6.新型基础设施 7.政策优化 8.产业发展 9.国家重视 10.快速增长"} ``` ## 高级用法 高级用法可以包括自定义模型参数或使用不同的模型源。例如,可以通过指定不同的 `model` 来使用特定于域的模型进行标签抽取。 ```python tag_extraction = appbuilder.TagExtraction(model="custom-model") result = tag_extraction(appbuilder.Message("自定义模型抽取的标签")) ``` ## 示例和案例研究 在实际应用中,`TagExtraction` 可以用于新闻文章、社交媒体帖子或其他任何文本内容的关键标签提取,帮助内容创建者或营销分析师快速了解主要主题和趋势。 ================================================ FILE: python/core/components/llms/tag_extraction/__init__.py ================================================ from .component import TagExtraction ================================================ FILE: python/core/components/llms/tag_extraction/base.py ================================================ # Copyright (c) 2023 Baidu, Inc. All Rights Reserved. # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from appbuilder.core.message import Message from appbuilder.core.component import ComponentArguments from pydantic import Field class TagExtractionArgs(ComponentArguments): """ 标签抽取配置 Attributes: message (Message): 输入消息,用于模型的主要输入内容 """ message: Message = Field(..., variable_name="query", description="""输入消息,用于模型的主要输入内容,例如'本实用新型公开了一种可利用热能的太阳能光伏光热一体化组件, 包括太阳能电池,还包括有吸热板,太阳能电池粘附在吸热板顶面,吸热板内嵌入有热电材料制成的内芯,吸热板底面设置有蛇形管。 本实用新型结构紧凑,安装方便,能充分利用太阳能电池散发的热能,具有较高的热能利用率。'""") ================================================ FILE: python/core/components/llms/tag_extraction/component.py ================================================ # Copyright (c) 2023 Baidu, Inc. All Rights Reserved. # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from appbuilder.core.components.llms.base import CompletionBaseComponent from appbuilder.core.message import Message from appbuilder.core.component import ComponentArguments from pydantic import BaseModel, Field from typing import Optional from appbuilder.utils.trace.tracer_wrapper import components_run_trace, components_run_stream_trace from .base import TagExtractionArgs class TagExtraction(CompletionBaseComponent): """ 标签抽取组件,基于生成式大模型进行关键标签的抽取。 Examples: .. code-block:: python import appbuilder # 请前往千帆AppBuilder官网创建密钥,流程详见:https://cloud.baidu.com/doc/AppBuilder/s/Olq6grrt6#1%E3%80%81%E5%88%9B%E5%BB%BA%E5%AF%86%E9%92%A5 os.environ["APPBUILDER_TOKEN"] = '...' tag_extraction = appbuilder.TagExtraction(model="DeepSeek-V3.1") answer = tag_extraction(appbuilder.Message("从这段文本中抽取关键标签")) """ name = "tag_extraction" version = "v1" meta = TagExtractionArgs manifests = [ { "name": "tag_extraction", "description": "标签抽取组件,基于生成式大模型进行关键标签的抽取。", "parameters": { "type": "object", "properties": { "query": { "type": "string", "description": "输入消息,用于模型的主要输入内容" } }, "required": [ "query" ] } } ] def __init__( self, model=None, secret_key: Optional[str] = None, gateway: str = "", lazy_certification: bool = False, **kwargs ): """初始化TagExtraction模型。 Args: model (str|None): 模型名称,用于指定要使用的千帆模型。 secret_key (str, 可选): 用户鉴权token, 默认从环境变量中获取: os.getenv("APPBUILDER_TOKEN", ""). gateway (str, 可选): 后端网关服务地址,默认从环境变量中获取: os.getenv("GATEWAY_URL", "") lazy_certification (bool, 可选): 延迟认证,为True时在第一次运行时认证. Defaults to False. Returns: None """ super().__init__( TagExtractionArgs, model=model, secret_key=secret_key, gateway=gateway, lazy_certification=lazy_certification) @components_run_trace def run(self, message, stream=False, temperature=1e-10, top_p=0.0): """ 使用给定的输入运行模型并返回结果。 Args: message (obj:`Message`, 必选): 输入消息,用于模型的主要输入内容。 stream (bool, 可选): 指定是否以流式形式返回响应。默认为 False。 temperature (float, 可选): 模型配置的温度参数,用于调整模型的生成概率。 取值范围为 0.0 到 1.0,其中较低的值使生成更确定性,较高的值使生成更多样性。 默认值为 1e-10。 top_p (float, 可选): 影响输出文本的多样性,取值越大,生成文本的多样性越强。 取值范围为 0.0 到 1.0,其中较低的值使生成更确定性,较高的值使生成更多样性。 默认值为 0。 Returns: obj:`Message`: 模型运行后的输出消息。 """ return super().run(message=message, stream=stream, temperature=temperature, top_p=top_p) @components_run_stream_trace def tool_eval(self, name: str, streaming: bool = False, **kwargs): """ tool_eval for function call """ traceid = kwargs.get("traceid") query = kwargs.get("query", None) if not query: raise ValueError("param `query` is required") msg = Message(query) model_configs = kwargs.get('model_configs', {}) temperature = model_configs.get("temperature", 1e-10) top_p = model_configs.get("top_p", 0.0) message = super().run(message=msg, stream=False, temperature=temperature, top_p=top_p, request_id=traceid) if streaming: yield str(message.content) else: return str(message.content) ================================================ FILE: python/core/components/matching/README.md ================================================ # 语义匹配(Matching) ## 简介 语义匹配组件(Matching)可以计算query与文本列表之间的相似度关系,并根据其进行排序。 ### 功能介绍 根据query与文本列表之间的相似度关系,并根据其进行排序。 ### 特色优势 基于百度文心大模型技术的文本表示模型,学习数据的内在特征,使得排序效果相较于bm25等排序算法,可以更好地处理相似问和同义、近义句子之间的偏序关系。 ### 应用场景 1. 语义排序 ## 基本用法 ### 下面是基于query和文本之间的相似度进行匹配排序的代码示例 ```python import os import appbuilder # 请前往千帆AppBuilder官网创建密钥,流程详见:https://cloud.baidu.com/doc/AppBuilder/s/Olq6grrt6#1%E3%80%81%E5%88%9B%E5%BB%BA%E5%AF%86%E9%92%A5 os.environ["APPBUILDER_TOKEN"] = '...' # 初始化所需要的组件 embedding = appbuilder.Embedding() matching = appbuilder.Matching(embedding) # 定义query和文本列表 query = appbuilder.Message("你好") contexts = appbuilder.Message(["世界", "你好"]) contexts_matched = matching(query, contexts) print(contexts_matched.content) ``` ``` ['你好', '世界'] ``` ## 参数说明 ### 鉴权说明 使用组件之前,请首先申请并设置鉴权参数,可参考[组件使用流程](https://cloud.baidu.com/doc/AppBuilder/s/Olq6grrt6#1%E3%80%81%E5%88%9B%E5%BB%BA%E5%AF%86%E9%92%A5)。 ```python # 设置环境中的TOKEN,以下示例略 os.environ["APPBUILDER_TOKEN"] = "bce-YOURTOKEN" ``` ### 初始化参数 | 参数名称 | 参数类型 | 是否必须 | 描述 | 示例值 | | ---------- | ----------- | -------- | ------------------------------------------------------------- | --------------- | | embedding | Embedding | 可选 | 一个类型为Embedding的Component,用于初始化 Matching 的向量计算功能。底座模型当前仅支持 embedding-v1 作为可选值。若不指定,默认值为 embedding-v1 。 | appbuilder.Embedding() | ### 调用参数 | 参数名称 | 参数类型 | 是否必须 | 描述 | 示例值 | | --------- | ----------- | -------- | ------------------------------------------------------------ | ---------------------------------- | | query | 字符串 | 必须 | 一个类型为 string 的句子,用于输入。该句子的长度不能超过384个字符,通常为用户输入的问题。 | "如何提高工作效率?" | | contexts | 字符串列表 | 必须 | 一个类型为 List[string] 的句子数组。数组中的每个元素都是一个句子,且每个句子的长度不能超过384个字符。这些句子通常为与问题相关的文本候选集。 | ["时间管理技巧", "提高专注力的方法"] | | return_score | 布尔 | 可选 | 默认为False, 仅返回排序后的字符串列表;当设置为True时,返回匹配分数和字符串的二元组列表 | ### 响应示例 默认为排完序后的字符串列表 ``` ["时间管理技巧", "提高专注力的方法"] ``` 当设置`return_score = True`时,二元组的第一个值为相似度分数,第二个值为字符串 ``` [(0.9999999852985002, '你好'), (0.18920520439845268, '世界')] ``` ### 错误码 无 ## 更新记录和贡献 * 语义匹配 (2023-12) ================================================ FILE: python/core/components/matching/__init__.py ================================================ # Copyright (c) 2023 Baidu, Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """ init """ from .component import Matching ================================================ FILE: python/core/components/matching/base.py ================================================ """ base """ # Copyright (c) 2023 Baidu, Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from abc import abstractmethod from typing import List, Union from appbuilder.core.message import Message from appbuilder.core.component import Component from appbuilder.core.component import ComponentArguments class MatchingArgs(ComponentArguments): """Matching Args""" query: Union[str, Message[str]] contexts: Union[List[str], Message[List[str]]] class MatchingBaseComponent(Component): """ MatchingBaseComponent """ name: str version: str meta: MatchingArgs @abstractmethod def run( self, query: Union[Message[str], str], contexts: Union[Message[List[str]], List[str]], ) -> Message[List[str]]: """ Args: query: Union[Message[str], str] contexts: Union[Message[List[str]], List[str]] Returns: Message[List[str]]: contexts which has been Matched """ ================================================ FILE: python/core/components/matching/component.py ================================================ # Copyright (c) 2023 Baidu, Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from typing import List, Union import numpy as np from appbuilder.core.message import Message from appbuilder.core.components.embeddings import EmbeddingBaseComponent from appbuilder.utils.trace.tracer_wrapper import components_run_trace, components_run_stream_trace from .base import MatchingBaseComponent, MatchingArgs class Matching(MatchingBaseComponent): """ Matching 基于Embedding类型的文本表示模型,输入query和文本列表,对其进行排序或者相似度计算 Examples: .. code-block:: python import appbuilder os.environ["APPBUILDER_TOKEN"] = '...' # 初始化所需要的组件 embedding = appbuilder.Embedding() matching = appbuilder.Matching(embedding) # 定义输入query和文本列表 query = appbuilder.Message("你好") contexts = appbuilder.Message(["世界", "你好"]) # 根据query,对文本列表做相似度排序 contexts_matched = matching(query, contexts) print(contexts_matched.content) # ['你好', '世界'] """ name: str = "Matching" version: str = "v1" meta: MatchingArgs = MatchingArgs def __init__( self, embedding_component: EmbeddingBaseComponent, **kwargs ): """ EmbeddingBaseComponent: 用于计算文本的embedding """ self.embedding_component = embedding_component super().__init__(self.meta) @components_run_trace def run( self, query: Union[Message[str], str], contexts: Union[Message[List[str]], List[str]], return_score: bool=False, ) -> Message[List[str]]: """ 根据给定的查询和上下文,返回匹配的上下文列表。 Args: query (Union[Message[str], str]): 查询字符串或Message对象,包含查询字符串。 contexts (Union[Message[List[str]], List[str]]): 上下文字符串列表或Message对象,包含上下文字符串列表。 return_score (bool, optional): 是否返回匹配得分。默认为False。 Returns: Message[List[str]]: 匹配的上下文列表。如果return_score为True,则返回包含得分和上下文的元组列表;否则仅返回上下文列表。 """ query_embedding = self.embedding_component(query) contexts_embedding = self.embedding_component.batch(contexts) sematic = self.semantics(query_embedding, contexts_embedding) combined = list(zip(sematic.content, contexts.content)) sorted_combined = sorted(combined, reverse=True) if return_score: return Message([(item[0], item[1]) for item in sorted_combined]) else: return Message([item[1] for item in sorted_combined]) def _cosine_similarity(self, X, Y): """ Args: X: 长度为 1 x n 的矩阵 Y: 长度为 m x n 的矩阵 Returns: 长度为 m x 1 的矩阵,每个元素表示 X 与 Y的对应行m 的余弦相似度 """ X_norm = X / np.linalg.norm(X) Y_norm = Y / np.linalg.norm(Y, axis=1, keepdims=True) similarity = np.dot(Y_norm, X_norm.T) return similarity def semantics( self, query_embedding: Union[Message[List[float]], List[float]], context_embeddings: Union[Message[List[List[float]]], List[List[float]]], ) -> Message[List[float]]: """ 计算query和context的相似度 Args: query_embedding (Union[Message[List[float]], List[float]]): query的embedding,长度为n的数组 context_embeddings (Union[Message[List[List[float]]], List[List[float]]]): context的embedding,长度为m x n的矩阵,其中m表示候选context的数量 Returns: Message[List[float]]: query和所有候选context的相似度列表 """ _query_embedding = query_embedding.content if isinstance(query_embedding, Message) else query_embedding _context_embeddings = context_embeddings.content if isinstance(context_embeddings, Message) else context_embeddings similarity_matrix = self._cosine_similarity([_query_embedding], _context_embeddings) similarity_matrix = similarity_matrix.flatten().tolist() return Message(similarity_matrix) ================================================ FILE: python/core/components/mix_card_ocr/README.md ================================================ # 身份证混贴识别(MixCardOCR) ## 简介 身份证混贴识别(MixCardOCR),身份证混贴识别支持自动检测与识别身份证正反面在同一张图片上的场景,一次识别图片中身份证正反面所有字段。 ### 功能介绍 支持对二代居民身份证正反面所有8个字段进行结构化识别,包括姓名、性别、民族、出生日期、住址、身份证号、签发机关、有效期限,识别准确率超过99%;同时支持身份证正面头像检测,并返回头像切片的base64编码及位置信息。 ### 特色优势 同时,支持对用户上传的身份证图片进行图像风险和质量检测,可识别图片是否为复印件或临时身份证,是否被翻拍或编辑,是否存在正反颠倒、模糊、欠曝、过曝等质量问题。 ### 应用场景 身份证混贴识别支持自动检测与识别身份证正反面在同一张图片上的场景,一次识别图片中身份证正反面所有字段。 ## 基本用法 下面是身份证混贴识别的代码示例: 示例图片为:![示例图片](https://bj.bcebos.com/v1/appbuilder/test_mix_card_ocr.jpeg?authorization=bce-auth-v1%2FALTAKGa8m4qCUasgoljdEDAzLm%2F2024-01-24T06%3A18%3A11Z%2F-1%2Fhost%2F695b8041c1ded194b9e80dbe1865e4393da5a3515e90d72d81ef18296bd29598) ```python import os import requests import appbuilder # 请前往千帆AppBuilder官网创建密钥,流程详见:https://cloud.baidu.com/doc/AppBuilder/s/Olq6grrt6#1%E3%80%81%E5%88%9B%E5%BB%BA%E5%AF%86%E9%92%A5 os.environ["APPBUILDER_TOKEN"] = "..." image_url= "https://bj.bcebos.com/v1/appbuilder/test_mix_card_ocr.jpeg?authorization=bce-auth-v1%2FALTAKGa8m4qCUasgoljdEDAzLm%2F2024-01-24T06%3A18%3A11Z%2F-1%2Fhost%2F695b8041c1ded194b9e80dbe1865e4393da5a3515e90d72d81ef18296bd29598" # 从BOS存储读取样例文件 raw_image = requests.get(image_url).content inp = appbuilder.Message(content={"raw_image": raw_image}) # inp = Message(content={"url": image_url}) # 运行身份证混贴识别OCR mix_card_ocr = appbuilder.MixCardOCR() out = mix_card_ocr.run(inp) # 打印识别结果 print(out.content) # {'front': {'fields': [{'key': '出生', 'value': '19920225', 'position': {'left': 620, 'top': 218, 'width': 239, 'height': 30}}, {'key': '性别', 'value': '女', 'position': {'left': 616, 'top': 164, 'width': 25, 'height': 30}}, {'key': '民族', 'value': '汉', 'position': {'left': 766, 'top': 164, 'width': 29, 'height': 30}}, {'key': '姓名', 'value': '姚佳', 'position': {'left': 621, 'top': 102, 'width': 84, 'height': 35}}, {'key': '公民身份号码', 'value': '110103199202250229', 'position': {'left': 733, 'top': 417, 'width': 399, 'height': 36}}, {'key': '住址', 'value': '北京市海淀区仙秀园555号', 'position': {'left': 618, 'top': 277, 'width': 253, 'height': 67}}], 'position': {'left': 483, 'top': 42, 'width': 737, 'height': 464}}, 'back': {'fields': [{'key': '签发日期', 'value': '20150413', 'position': {'left': 789, 'top': 946, 'width': 139, 'height': 34}}, {'key': '签发机关', 'value': '北京市公安局海淀分局', 'position': {'left': 787, 'top': 883, 'width': 275, 'height': 35}}, {'key': '失效日期', 'value': '20350413', 'position': {'left': 946, 'top': 945, 'width': 144, 'height': 34}}], 'position': {'left': 473, 'top': 537, 'width': 749, 'height': 480}}, 'direction': 0} ``` ## 参数说明 ### 鉴权说明 使用组件之前,请首先申请并设置鉴权参数,可参考[组件使用流程](https://cloud.baidu.com/doc/AppBuilder/s/Olq6grrt6#1%E3%80%81%E5%88%9B%E5%BB%BA%E5%AF%86%E9%92%A5)。 ```python import os os.environ["APPBUILDER_TOKEN"] = "..." ``` ### 初始化参数 无 ### 调用参数 | 参数名称 | 参数类型 | 是否必须 | 描述 |示例值| |------------|--------|------|-----------------------------|---| | message | String | 是 | 输入的消息,用于模型的主要输入内容。这是一个必需的参数 || | +content | Dict | 是 | 消息内容 || | +raw_image | String | 否 | 原始图片字节流 || | +url | String | 否 | 图片下载链接地址 || |timeout| Float | 否 | HTTP超时时间,单位:秒 |1|| |retry|Integer| 否 | HTTP重试次数 |3|| ### 响应参数 | 参数名称 | 参数类型 | 描述 | 示例值 | |------------|--------|---------------------|----------------------------------------------------| | front | object | 身份证正面信息 | | | +fields | list | 字段信息 | | | ++key | str | 字段名 | | | ++value | str | 字段值 | | | ++position | object | 字段坐标,结构同下position | | | +position | object | 身份证正面坐标 | | | ++left | int | 表示定位位置的长方形左上顶点的水平坐标 | | | ++top | int | 表示定位位置的长方形左上顶点的垂直坐标 | | | ++width | int | 表示定位位置的长方形的宽度 | | | ++height | int | 表示定位位置的长方形的高度 | | | back | object | 身份证反面信息,结构同front | | | direction | int | 图像旋转角度 | 图像旋转角度,0(正向),- 1(逆时针90度),- 2(逆时针180度),- 3(逆时针270度) | ### 响应示例 ```json { "front": { "fields": [{ "key": "出生", "value": "19920225", "position": { "left": 620, "top": 218, "width": 239, "height": 30 } }, { "key": "性别", "value": "女", "position": { "left": 616, "top": 164, "width": 25, "height": 30 } }, { "key": "民族", "value": "汉", "position": { "left": 766, "top": 164, "width": 29, "height": 30 } }, { "key": "姓名", "value": "姚佳", "position": { "left": 621, "top": 102, "width": 84, "height": 35 } }, { "key": "公民身份号码", "value": "110103199202250229", "position": { "left": 733, "top": 417, "width": 399, "height": 36 } }, { "key": "住址", "value": "北京市海淀区仙秀园555号", "position": { "left": 618, "top": 277, "width": 253, "height": 67 } } ], "position": { "left": 483, "top": 42, "width": 737, "height": 464 } }, "back": { "fields": [{ "key": "签发日期", "value": "20150413", "position": { "left": 789, "top": 946, "width": 139, "height": 34 } }, { "key": "签发机关", "value": "北京市公安局海淀分局", "position": { "left": 787, "top": 883, "width": 275, "height": 35 } }, { "key": "失效日期", "value": "20350413", "position": { "left": 946, "top": 945, "width": 144, "height": 34 } } ], "position": { "left": 473, "top": 537, "width": 749, "height": 480 } }, "direction": 0 } ``` ### 错误码 |错误码|描述| |------|---| ## 高级用法 目前该模块仅提供基础的身份证混贴识别。 ## 更新记录和贡献 * 身份证混贴识别 (2024-01) ================================================ FILE: python/core/components/mix_card_ocr/__init__.py ================================================ # Copyright (c) 2023 Baidu, Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. ================================================ FILE: python/core/components/mix_card_ocr/component.py ================================================ # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. r"""身份证混贴识别组件""" import base64 import json from appbuilder.core import utils from appbuilder.core._client import HTTPClient from appbuilder.core._exception import AppBuilderServerException, InvalidRequestArgumentError from appbuilder.core.component import Component from appbuilder.core.components.mix_card_ocr.model import * from appbuilder.core.message import Message from appbuilder.utils.trace.tracer_wrapper import components_run_trace, components_run_stream_trace class MixCardOCR(Component): r""" 身份证混贴识别组件 Examples: .. code-block:: python import os import requests import appbuilder os.environ["GATEWAY_URL"] = "..." os.environ["APPBUILDER_TOKEN"] = "..." # 从BOS存储读取样例文件 image_url="https://bj.bcebos.com/v1/appbuilder/test_mix_card_ocr.jpeg?authorization=bce-auth-v1%2FALTAKGa8m4qCUasgoljdEDAzLm%2F2024-01-24T06%3A18%3A11Z%2F-1%2Fhost%2F695b8041c1ded194b9e80dbe1865e4393da5a3515e90d72d81ef18296bd29598" raw_image = requests.get(image_url).content # 输入参数为一张图片 inp = appbuilder.Message(content={"raw_image": raw_image}) # 进行识别 mix_card_ocr = MixCardOCR() out = mix_card_ocr.run(inp) # 打印识别结果 print(out.content) """ name = "mixcard_ocr" version = "v1" manifests = [ { "name": "mixcard_ocr", "description": "当身份证正反面在同一张图片上,需要识别图片中身份证正反面所有字段时,使用该工具", "parameters": { "type": "object", "properties": { "file_names": { "type": "array", "items": { "type": "string" }, "description": "待识别文件的文件名" } }, "required": ["file_names"] } } ] @HTTPClient.check_param @components_run_trace def run(self, message: Message, timeout: float = None, retry: int = 0) -> Message: """ 执行身份证识别操作 Args: message (Message): 包含待识别图片或图片下载URL的Message对象. 示例: Message(content={"raw_image": b"..."}) 或 Message(content={"url": "https://image/download/url"}). timeout (float, 可选): HTTP请求的超时时间,默认为None. retry (int, 可选): HTTP请求的重试次数,默认为0. Returns: Message: 包含身份证识别结果的Message对象. """ inp = MixCardOCRInMsg(**message.content) request = MixCardOCRRequest() if inp.url: request.url = inp.url if inp.raw_image: request.image = base64.b64encode(inp.raw_image) request.detect_risk = "false" request.detect_quality = "false" request.detect_photo = "false" request.detect_card = "false" response = self._recognize(request, timeout, retry) out = MixCardOCROutMsg() for res in response.words_result: card_type = res.card_info.card_type if card_type != "idcard_back" and card_type != "idcard_front": continue ref = out.front if card_type == "idcard_back": ref = out.back loc = res.card_info.card_location ref.position = MixCardPosition(left=loc.left, top=loc.top, width=loc.width, height=loc.height) for key, val in res.card_result.items(): position = MixCardPosition(left=val.location.left, top=val.location.top, width=val.location.width, height=val.location.height) ref.fields.append(MixCardField(key=key, value=val.words, position=position)) out.direction = response.direction return Message(content=out.model_dump()) def _recognize(self, request: MixCardOCRRequest, timeout: float = None, retry: int = 0, request_id: str = None) -> MixCardOCRResponse: r"""调用底层身份证混贴识别 参数: request (obj: `GeneralOCRRequest`) : 通用文字识别输入参数 返回: response (obj: `GeneralOCRResponse`): 通用文字识别返回结果 """ if not request.image and not request.url: raise ValueError("request format error, one of image or url must be set") data = MixCardOCRRequest.to_dict(request) if self.http_client.retry.total != retry: self.http_client.retry.total = retry headers = self.http_client.auth_header(request_id) headers['content-type'] = 'application/x-www-form-urlencoded' url = self.http_client.service_url("/v1/bce/aip/ocr/v1/multi_idcard") response = self.http_client.session.post(url, headers=headers, data=data, timeout=timeout) self.http_client.check_response_header(response) data = response.json() self.http_client.check_response_json(data) request_id = self.http_client.response_request_id(response) self.__class__._check_service_error(request_id, data) response = MixCardOCRResponse(data) response.request_id = request_id return response @staticmethod def _check_service_error(request_id: str, data: dict): r"""个性化服务response参数检查 参数: request (dict) : 通用文字识别body返回 返回: 无 """ if "error_code" in data or "error_msg" in data: raise AppBuilderServerException( request_id=request_id, service_err_code=data.get("error_code"), service_err_message=data.get("error_msg") ) @components_run_stream_trace def tool_eval(self, name: str, streaming: bool, **kwargs): """ 对指定文件进行OCR识别。 Args: name (str): API名称。 streaming (bool): 是否流式输出。如果为True,则逐个返回识别结果;如果为False,则一次性返回所有识别结果。 **kwargs: 其他参数。 Returns: 如果streaming为False,则返回包含所有识别结果的JSON字符串。 如果streaming为True,则逐个返回包含识别结果的字典,每个字典包含以下字段: type (str): 消息类型,固定为"text"。 text (str): 识别结果的JSON字符串。 visible_scope (str): 消息可见范围,可以是"llm"或"user"。 Raises: InvalidRequestArgumentError: 如果请求格式错误,即文件URL不存在时抛出。 """ result = {} traceid = kwargs.get("traceid") file_names = kwargs.get("file_names", None) if not file_names: file_names = kwargs.get("files") file_urls = kwargs.get("file_urls", {}) for file_name in file_names: if utils.is_url(file_name): file_url = file_name else: file_url = file_urls.get(file_name, None) if file_url is None: raise InvalidRequestArgumentError(f"request format error, file {file_name} url does not exist") request = MixCardOCRRequest() request.url = file_url request.detect_risk = "false" request.detect_quality = "false" request.detect_photo = "false" request.detect_card = "false" response = self._recognize(request, request_id=traceid) out = MixCardOCROutMsg() for res in response.words_result: card_type = res.card_info.card_type if card_type != "idcard_back" and card_type != "idcard_front": continue ref = out.front if card_type == "idcard_back": ref = out.back for key, val in res.card_result.items(): ref.fields.append(MixCardField(key=key, value=val.words, position=None)) out.direction = response.direction result[file_name] = out.dict() result = json.dumps(result, ensure_ascii=False) if streaming: yield { "type": "text", "text": result, "visible_scope": 'llm', } yield { "type": "text", "text": "", "visible_scope": "user", } else: return result ================================================ FILE: python/core/components/mix_card_ocr/model.py ================================================ # Copyright (c) 2023 Baidu, Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """身份证混贴数据类""" import proto from typing import List, Optional from pydantic import BaseModel class MixCardOCRRequest(proto.Message): """ 身份证混贴识别 属性: image (str): 可选。图像内容的base64编码 url (str): 可选,图像的URL地址,经过base64编码 图像大小必须小于4MB,图像的最短边长大于15像素,最长边长大于4096像素 detect_risk(str): 是否检测风险(身份证复印件、临时身份证、身份证翻拍、修改过的身份证)类型,可选值是"true"或“false” detect_quality(str): 是否开启身份证质量类型(边框/四角不完整、头像或关键字段被遮挡/马赛克)检测功能,可选值是"true"或“false” detect_photo(str): 是否检测头像内容,默认不检测,可选值是"true"或“false” detect_card(str): 是否检测身份证并进行裁剪,"true"或“false” """ image: str = proto.Field( proto.STRING, number=1, ) url: str = proto.Field( proto.STRING, number=2, ) detect_risk: str = proto.Field( proto.STRING, number=3, ) detect_quality: str = proto.Field( proto.STRING, number=4, ) detect_photo: str = proto.Field( proto.STRING, number=5, ) detect_card: str = proto.Field( proto.STRING, number=6, ) class MixCardOCRLocation(proto.Message): """ 位置信息. 属性: left (int): 表示定位位置的长方形左上顶点的水平坐标 top (int): 表示定位位置的长方形左上顶点的垂直坐标 width (int): 表示定位位置的长方形的宽度 height (int): 表示定位位置的长方形的高度 """ left: int = proto.Field( proto.INT32, number=1, ) top: int = proto.Field( proto.INT32, number=2, ) width: int = proto.Field( proto.INT32, number=3, ) height: int = proto.Field( proto.INT32, number=4, ) class MixCardOCRInfo(proto.Message): """ 身份证混贴手识别结果 属性: card_location (MixCardLocation): 身份证的位置信息(坐标0点为左上角) card_type(str): idcard_front(头像面)、idcard_back(国徽面) image_status (str): normal-识别正常、 non_idcard-上传的图片中不包含身份证 、blurred-身份证模糊 other_type_card-其他类型证照 、over_exposure-身份证关键字段反光或过曝 、over_dark-身份证欠曝(亮度过低) unknown-未知状态 """ card_location = proto.Field( MixCardOCRLocation, number=1, ) card_type: str = proto.Field( proto.STRING, number=2, ) image_status: str = proto.Field( proto.STRING, number=3 ) direction: int = proto.Field( proto.INT32, number=4 ) idcard_number_type: int = proto.Field( proto.INT32, number=5 ) class MixCardOCRResult(proto.Message): """身份证混贴别结果 属性: words (str): 文本信息 location(MixCardOCRLocation): 位置信息 """ words: str = proto.Field( proto.STRING, number=1 ) location = proto.Field( MixCardOCRLocation, number=2 ) class MixOCRCardInfoResult(proto.Message): """身份证混贴信息 属性: card_result (Map[str,MixCardOCRResult]): 身份证字段信息 card_info(MixCardOCRInfo): 身份证信息 """ card_result = proto.MapField( proto.STRING, MixCardOCRResult, number=1 ) card_info = proto.Field( MixCardOCRInfo, number=2 ) class MixCardOCRResponse(proto.Message): """身份证混贴识别结果 属性: request_id(str): 请求ID log_id (int): 用于问题跟踪的唯一日志ID words_result (List[MixOCRCardInfoResult]): 识别结果列表 direction (int): 当detect_direction=true返回改字段,1(未定义)、 0(正向)、1(逆时针90度)、2(逆时针180度)、3(逆时针270度) pdf_file_size (str): 输入PDF文件的总页数。当pdf_file参数有效时返回 """ request_id: str = proto.Field( proto.STRING, number=1, ) log_id: int = proto.Field( proto.UINT64, number=2, ) words_result = proto.RepeatedField( MixOCRCardInfoResult, number=3, ) direction: int = proto.Field( proto.INT32, number=4, ) class MixCardOCRInMsg(BaseModel): """ 手写体文字识别输入消息 属性: raw_image(bytes): 图像原始内容 url(str): 图像下载链接 """ raw_image: bytes = b'' # 原始图片byte数组 url: str = "" # 图片可下载链接 class MixCardPosition(BaseModel): """位置信息 属性: left (int): 表示定位位置的长方形左上顶点的水平坐标 top (int): 表示定位位置的长方形左上顶点的垂直坐标 width (int): 表示定位位置的长方形的宽度 height (int): 表示定位位置的长方形的高度 """ left: int top: int width: int height: int class MixCardField(BaseModel): """ 字段信息 属性: key(str): 字段名 value (str): 字段值 position(MixCardPosition): 字段位置信息 """ key: str value: str position: Optional[MixCardPosition] = None class MixCardContent(BaseModel): """正/反识别结果 属性: fields(List[MixCardField]):字段列表 position(MixCardPosition): 正/反面在图像中的位置信息 """ fields: List[MixCardField] = list() position: MixCardPosition = None class MixCardOCROutMsg(BaseModel): """身份证混贴识别结果 属性: front(MixCardField): 人像面信息 back(MixCardField): 国徽面信息 direction(int): 图像旋转角度,0(正向),- 1(逆时针90度),- 2(逆时针180度),- 3(逆时针270度) """ front: MixCardContent = MixCardContent() back: MixCardContent = MixCardContent() direction: int = 0 ================================================ FILE: python/core/components/object_recognize/README.md ================================================ # 通用物体和场景识别-高级版(ObjectRecognition) ## 简介 通用物体和场景识别组件(ObjectRecognition)可以识别超过10万类常见物体和场景,接口返回大类及细分类的名称。广泛适用于图像或视频内容分析、拍照识图等业务场景。 ### 功能介绍 * 识别物体或场景名称 识别动物、植物、商品、建筑、风景、动漫、食材、公众人物等10万个常见物体及场景,接口返回大类及细分类的名称结果; ### 特色优势 * 可识别超过10万类常见物体和场景,接口返回大类及细分类的名称,并支持获取识别结果对应的百科信息; ### 应用场景 可以识别超过10万类常见物体和场景,广泛适用于图像或视频内容分析、拍照识图等业务场景 ## 基本用法 示例图片为: ![示例图片](https://bj.bcebos.com/v1/appbuilder/object_recognize_test.png?authorization=bce-auth-v1%2FALTAKGa8m4qCUasgoljdEDAzLm%2F2024-01-11T11%3A00%3A19Z%2F-1%2Fhost%2F2c31bf29205f61e58df661dc80af31a1dc1ba1de0a8f072bc5a87102bd32f9e3) ```python import os import appbuilder import requests # 请前往千帆AppBuilder官网创建密钥,流程详见:https://cloud.baidu.com/doc/AppBuilder/s/Olq6grrt6#1%E3%80%81%E5%88%9B%E5%BB%BA%E5%AF%86%E9%92%A5 os.environ["APPBUILDER_TOKEN"] = '...' # 从BOS读取样例图片 image_url = "https://bj.bcebos.com/v1/appbuilder/object_recognize_test.png?"\ "authorization=bce-auth-v1%2FALTAKGa8m4qCUasgoljdEDAzLm%2F2024-01-"\ "11T11%3A00%3A19Z%2F-1%2Fhost%2F2c31bf29205f61e58df661dc80af31a1dc"\ "1ba1de0a8f072bc5a87102bd32f9e3" raw_image = requests.get(image_url).content # 创建物体识别组件实例 object_recognition = appbuilder.ObjectRecognition() # 执行识别操作并获取结果 out = object_recognition.run(appbuilder.Message(content={"raw_image": raw_image})) print(out.content) # {'result': [{'keyword': '苹果', 'score': 0.961247, 'root': '植物-蔷薇科'}, {'keyword': '姬娜果', 'score': 0.740838, 'root': '植物-其它'}, {'keyword': '梨子', 'score': 0.392218, 'root': '商品-水果'}, {'keyword': '车厘子', 'score': 0.193986, 'root': '植物-其它'}, {'keyword': '石榴', 'score': 0.000239, 'root': '植物-千屈菜科'}]} ``` ## 参数说明 ### 鉴权说明 使用组件之前,请首先申请并设置鉴权参数,可参考[组件使用流程](https://cloud.baidu.com/doc/AppBuilder/s/Olq6grrt6#1%E3%80%81%E5%88%9B%E5%BB%BA%E5%AF%86%E9%92%A5)。 ```python # 设置环境中的TOKEN,以下示例略 os.environ["APPBUILDER_TOKEN"] = "bce-YOURTOKEN" ``` ### 初始化参数 无 ### 调用参数 (以表格形式展示) | 参数名称 | 参数类型 | 是否必须 | 描述 | 示例值 | |---------|---------|------|-----------------------------|------------------------------------------------| | message | String | 是 | 输入的消息,用于模型的主要输入内容。这是一个必需的参数 | Message(content={"raw_image": b"待识别的图片字节流数据"}) | |timeout| Float | 否 | HTTP超时时间,单位:秒 |1|| | retry | Integer | 否 | HTTP重试次数 | 3 | ### 响应参数 | 参数名称 | 参数类型 | 描述 | 示例值 | |----------|---------|-------------|-----------------------------------------------------| | result | Array[] | 返回结果 | [{"keyword":"苹果","score":0.961247,"root":"植物-蔷薇科"}] | | +keyword | String | 图片中的物体或场景名称 | "苹果" | | +score | Float | 置信度 | 0.961247 | | +root | String | 识别结果的上层标签 | "植物-蔷薇科" | ### 响应示例 ```json { "result":[ { "keyword":"苹果", "score":0.961247, "root":"植物-蔷薇科" }, { "keyword":"姬娜果", "score":0.740838, "root":"植物-其它" }, { "keyword":"梨子", "score":0.392218, "root":"商品-水果" }, { "keyword":"车厘子", "score":0.193986, "root":"植物-其它" }, { "keyword":"石榴", "score":0.000239, "root":"植物-千屈菜科" } ] } ``` ### 错误码 | 错误码 | 描述 | |-----|----| ## 高级用法 目前该模块仅提供基础通用物体与场景识别功能。 ## 更新记录和贡献 * 通用物体及场景识别 (2023-12-08) ================================================ FILE: python/core/components/object_recognize/__init__.py ================================================ # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. ================================================ FILE: python/core/components/object_recognize/component.py ================================================ # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """object recognize component.""" import base64 import json import os from appbuilder.core import utils from appbuilder.core._client import HTTPClient from appbuilder.core.component import Component from appbuilder.core.message import Message from appbuilder.core._exception import AppBuilderServerException, InvalidRequestArgumentError from appbuilder.core.components.object_recognize.model import * from appbuilder.utils.trace.tracer_wrapper import components_run_trace, components_run_stream_trace class ObjectRecognition(Component): r""" 提供通用物体及场景识别能力,即对于输入的一张图片(可正常解码,且长宽比适宜),输出图片中的多 个物体及场景标签。 Examples: .. code-block:: python import appbuilder # 请前往千帆AppBuilder官网创建密钥,流程详见:https://cloud.baidu.com/doc/AppBuilder/s/Olq6grrt6#1%E3%80%81%E5%88%9B%E5%BB%BA%E5%AF%86%E9%92%A5 os.environ["APPBUILDER_TOKEN"] = '...' object_recognition = appbuilder.ObjectRecognition() with open("./object_recognition_test.jepg", "rb") as f: out = self.component.run(appbuilder.Message(content={"raw_image": f.read()})) print(out.content) """ name = "object_recognition" version = "v1" manifests = [ { "name": "object_recognition", "description": "提供通用物体及场景识别能力,即对于输入的一张图片,输出图片中的多个物体及场景标签。", "parameters": { "type": "object", "properties": { "img_url": { "type": "string", "description": "待识别图片的url,根据该url能够获取图片" }, "img_name": { "type": "string", "description": "待识别图片的文件名,用于生成图片url" } }, "anyOf": [ { "required": [ "img_url" ] }, { "required": [ "img_name" ] } ] } } ] @HTTPClient.check_param @components_run_trace def run(self, message: Message, timeout: float = None, retry: int = 0) -> Message: """ 通用物体识别 Args: message (Message): 输入图片或图片url下载地址用于执行识别操作。 例如: Message(content={"raw_image": b"..."}) 或 Message(content={"url": "https://image/download/url"})。 timeout (float, optional): HTTP超时时间,默认为None。 retry (int, optional): HTTP重试次数,默认为0。 Returns: Message: 模型识别结果。 例如: Message(content={"result":[{"keyword":"苹果", "score":0.94553,"root":"植物-蔷薇科"},{"keyword":"姬娜果","score":0.730442,"root":"植物-其它"}, {"keyword":"红富士","score":0.505194,"root":"植物-其它"}]}) """ inp = ObjectRecognitionInMsg(**message.content) req = ObjectRecognitionRequest() if inp.raw_image: req.image = base64.b64encode(inp.raw_image) if inp.url: req.url = inp.url result = self._recognize(req, timeout, retry) result_dict = proto.Message.to_dict(result) out = ObjectRecognitionOutMsg(**result_dict) return Message(content=out.model_dump()) def _recognize(self, request: ObjectRecognitionRequest, timeout: float = None, retry: int = 0, request_id: str = None) -> ObjectRecognitionResponse: r"""调用底层接口进行通用物体与场景识别 参数: request (obj: `ObjectRecognitionRequest`) : 通用物体与场景识别输入参数 返回: response (obj: `ObjectRecognitionResponse`): 通用物体与场景识别返回结果 """ if not request.image and not request.url: raise ValueError("request format error, one of image or url must be set") data = ObjectRecognitionRequest.to_dict(request) if self.http_client.retry.total != retry: self.http_client.retry.total = retry headers = self.http_client.auth_header(request_id) headers['content-type'] = 'application/x-www-form-urlencoded' url = self.http_client.service_url("/v1/bce/aip/image-classify/v2/advanced_general") response = self.http_client.session.post(url, headers=headers, data=data, timeout=timeout) self.http_client.check_response_header(response) data = response.json() self.http_client.check_response_json(data) request_id = self.http_client.response_request_id(response) self.__class__._check_service_error(request_id,data) object_response = ObjectRecognitionResponse.from_json(payload=json.dumps(data)) object_response.request_id = request_id return object_response @staticmethod def _check_service_error(request_id: str, data: dict): r"""个性化服务response参数检查 参数: request (dict) : 通用物体与场景识别body返回 返回: 无 """ if "error_code" in data or "error_msg" in data: raise AppBuilderServerException( request_id=request_id, service_err_code=data.get("error_code"), service_err_message=data.get("error_msg") ) @components_run_stream_trace def tool_eval(self, name: str, streaming: bool, **kwargs): """ 评估并识别传入图像中的物体或场景。 Args: name (str): 调用此方法的对象名称。 streaming (bool): 是否以流式方式返回结果。如果是True,则以生成器形式返回结果;如果是False,则直接返回字符串形式的识别结果。 **kwargs: 任意关键字参数,支持以下参数: traceid (str, optional): 请求的追踪ID,用于追踪请求处理流程。默认为None。 img_url (str, optional): 待识别图像的URL地址。默认为None,如果未指定,则尝试从file_urls和img_name参数中获取图像路径。 file_urls (dict, optional): 包含文件名和对应URL的字典。默认为空字典。 img_name (str, optional): 待识别图像的文件名。如果img_url未指定,则根据img_name从file_urls中获取图像的URL。默认为None。 score_threshold (float, optional): 置信度阈值,低于此阈值的识别结果将被忽略。默认为0.5。 Returns: 如果streaming为True,则返回一个生成器,生成器中的元素为包含识别结果的字典,字典包含以下键: type (str): 结果类型,固定为"text"。 text (str): 识别结果的JSON字符串表示。 visible_scope (str): 结果的可见范围,'llm'表示仅对LLM可见,'user'表示对用户可见。 如果streaming为False,则直接返回识别结果的JSON字符串表示。 Raises: InvalidRequestArgumentError: 如果请求格式错误(如未设置文件名或文件URL不存在),则抛出此异常。 """ traceid = kwargs.get("traceid") img_url = kwargs.get("img_url", None) if not img_url: file_urls = kwargs.get("file_urls", {}) img_path = kwargs.get("img_name", None) if not img_path: raise InvalidRequestArgumentError("request format error, file name is not set") img_name = os.path.basename(img_path) img_url = file_urls.get(img_name, None) if not img_url: raise InvalidRequestArgumentError(f"request format error, file {img_name} url does not exist") score_threshold = kwargs.get("score_threshold", 0.5) req = ObjectRecognitionRequest(url=img_url) result = proto.Message.to_dict(self._recognize(req, request_id=traceid)) results = [] for item in result["result"]: if item["score"] < score_threshold and len(results) > 0: continue res = { "物体或场景名称": item["keyword"], "置信度": item["score"], "所属类别": item["root"], } results.append(res) res = json.dumps(results, ensure_ascii=False, indent=4) if streaming: yield { "type": "text", "text": res, "visible_scope": 'llm', } yield { "type": "text", "text": "", "visible_scope": 'user', } else: return res ================================================ FILE: python/core/components/object_recognize/model.py ================================================ # Copyright (c) 2023 Baidu, Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """object recognize client.""" import proto from typing import List from pydantic import BaseModel # PB Definition class ObjectRecognitionRequest(proto.Message): r"""通用物体与场景识别请求体. 属性: image (str): 可选。图像内容的base64编码。 url (str): 可选。图像的URL地址,经过base64编码。 图像大小必须小于4MB,图像的最短边长大于15像素,最长边长大于4096像素。 必须设置image或url属性之一,如果两者都设置了,将使用image属性。 """ image: str = proto.Field( proto.STRING, number=1, ) url: str = proto.Field( proto.STRING, number=2, ) baike_num: int = proto.Field( proto.INT64, number=3, ) class ObjectRecognitionResponse(proto.Message): """通用物体与场景识别响应消息。 属性: request_id (str): 请求ID。 log_id (int): 用于问题识别的唯一日志ID。 result_num (int): 结果数量,即结果数组中的元素数量。最多返回5个结果。 result (List[ObjectResult]): 物体识别结果列表。 """ request_id: str = proto.Field( proto.STRING, number=1, ) log_id: int = proto.Field( proto.INT64, number=2, ) result_num: int = proto.Field( proto.UINT32, number=3, ) result: 'ObjectResult' = proto.RepeatedField( proto.MESSAGE, number=4, message="ObjectResult", ) class ObjectResult(proto.Message): """物体识别信息. 属性: keyword (str): 图像中物体或场景的名称。 score (float): 置信度得分,范围从0到1。 root (str): 识别结果中的顶级标签。一些标签,如硬币、动漫、烟草等,可能没有顶级标签。 baike_info (List[BaikeInfo]): 与识别结果对应的百科信息列表。 """ keyword: str = proto.Field( proto.STRING, number=1, ) score: float = proto.Field( proto.FLOAT, number=2, ) root: str = proto.Field( proto.STRING, number=3, ) baike_info: 'BaikeInfo' = proto.RepeatedField( proto.MESSAGE, number=4, message="BaikeInfo", ) class BaikeInfo(proto.Message): """物体识别百科信息。 属性: baike_url (str): 与识别结果对应的百度百科页面的URL。 image_url (str): 与识别结果相关联的图像的URL。 description (str): 百度百科提供的识别结果的描述。 """ baike_url: str = proto.Field( proto.STRING, number=1, ) image_url: str = proto.Field( proto.STRING, number=2, ) description: str = proto.Field( proto.STRING, number=3, ) class ObjectRecognitionInMsg(BaseModel): """ 通用物体与场景识别输入消息 属性: raw_image(bytes): 图像原始内容 url(str): 图像下载链接 """ raw_image: bytes = b'' url: str = "" class Object(BaseModel): """物体识别输入消息。 属性: keyword(bytes): 原始二进制图像数据。 score(float): 置信度得分,范围从0到1。 root(str): 识别结果中的顶级标签。 """ keyword: str score: float root: str class ObjectRecognitionOutMsg(BaseModel): r"""识别结果列表""" result: List[Object] # 结果列表 ================================================ FILE: python/core/components/plant_recognize/README.md ================================================ # 植物识别(PlantRecognition) ## 简介 植物识别(PlantRecognition),即对于输入的一张图片(可正常解码,且长宽比较合适),输出植物识别结果。 ### 功能介绍 可识别超过2万种常见植物和近8千种花卉,接口返回植物的名称,并支持获取识别结果对应的百科信息 ### 特色优势 还可使用EasyDL定制训练平台,定制识别植物种类 ### 应用场景 适用于拍照识图、幼教科普、图像内容分析等场景 ## 基本用法 下面是植物识别的代码示例: 示例图片为 ![示例图片](https://bj.bcebos.com/v1/appbuilder/palnt_recognize_test.jpg?authorization=bce-auth-v1%2FALTAKGa8m4qCUasgoljdEDAzLm%2F2024-01-23T09%3A51%3A03Z%2F-1%2Fhost%2Faa2217067f78f0236c8262cdd89a4b4f4b2188d971ca547c53d01742af4a2cbe) ```python import os import requests import appbuilder # 请前往千帆AppBuilder官网创建密钥,流程详见:https://cloud.baidu.com/doc/AppBuilder/s/Olq6grrt6#1%E3%80%81%E5%88%9B%E5%BB%BA%E5%AF%86%E9%92%A5 os.environ["APPBUILDER_TOKEN"] = "..." image_url = "https://bj.bcebos.com/v1/appbuilder/palnt_recognize_test.jpg?authorization=bce-auth-v1%2FALTAKGa8m4qCUasgoljdEDAzLm%2F2024-01-23T09%3A51%3A03Z%2F-1%2Fhost%2Faa2217067f78f0236c8262cdd89a4b4f4b2188d971ca547c53d01742af4a2cbe" # 从BOS存储读取样例文件 raw_image = requests.get(image_url).content inp = appbuilder.Message(content={"raw_image": raw_image}) # inp = Message(content={"url": image_url}) # 运行植物识别 plant_recognize = appbuilder.PlantRecognition() out = plant_recognize.run(inp) # 打印识别结果 print(out.content) # {'plant_score_list': [{'name': '榕树', 'score': 0.4230029582977295}, {'name': '榆树', 'score': 0.1273619383573532}, {'name': '美国榆', 'score': 0.12065108865499496}, {'name': '白蜡树', 'score': 0.11650644987821579}, {'name': '雨树', 'score': 0.045340824872255325}]} ``` ## 参数说明 ### 鉴权说明 使用组件之前,请首先申请并设置鉴权参数,可参考[组件使用流程](https://cloud.baidu.com/doc/AppBuilder/s/Olq6grrt6#1%E3%80%81%E5%88%9B%E5%BB%BA%E5%AF%86%E9%92%A5)。 ```python import os os.environ["APPBUILDER_TOKEN"] = "..." ``` ### 初始化参数 无 ### 调用参数 | 参数名称 | 参数类型 | 是否必须 | 描述 |示例值| |------------|--------|------|-----------------------------|---| | message | String | 是 | 输入的消息,用于模型的主要输入内容。这是一个必需的参数 || | +content | Dict | 是 | 消息内容 || | +raw_image | String | 否 | 原始图片字节流 || | +url | String | 否 | 图片下载链接地址 || |timeout| Float | 否 | HTTP超时时间,单位:秒 |1|| |retry|Integer| 否 | HTTP重试次数 |3|| ### 响应参数 | 参数名称 | 参数类型 | 描述 | 示例值 | |------------------|--------|--------|--------------------------------------------------| | plant_score_list | List | 植物识别列表 | | | name | String | 植物名 | | | score | Float | 植物识别打分 | | ### 响应示例 ```json { "plant_score_list": [ { "name": "榕树", "score": 0.4230029582977295 }, { "name": "榆树", "score": 0.1273619383573532 }, { "name": "美国榆", "score": 0.1206519496 }, { "name": "白蜡树", "score": 0.11650644987821579 }, { "name": "雨树", "score": 0.045340824872255325 } ] } ``` ### 错误码 |错误码|描述| |------|---| ## 高级用法 目前该模块仅提供基础的植物识别。 ## 更新记录和贡献 * 植物识别 (2024-01) ================================================ FILE: python/core/components/plant_recognize/__init__.py ================================================ # Copyright (c) 2023 Baidu, Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. ================================================ FILE: python/core/components/plant_recognize/component.py ================================================ # Copyright (c) 2023 Baidu, Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. r"""植物识别组件""" import base64 from appbuilder.core.component import Component from appbuilder.core.message import Message from appbuilder.core._client import HTTPClient from appbuilder.core._exception import AppBuilderServerException from appbuilder.core.components.plant_recognize.model import * from typing import Generator, Union from appbuilder.utils.trace.tracer_wrapper import components_run_trace, components_run_stream_trace from .model import TOP_NUM, BAIKE_NUM class PlantRecognition(Component): r""" 植物识别组件,即对于输入的一张图片(可正常解码,且长宽比适宜),输出图片中的植物识别结果 Examples: .. code-block:: python import os import requests import appbuilder # 请前往千帆AppBuilder官网创建密钥,流程详见:https://cloud.baidu.com/doc/AppBuilder/s/Olq6grrt6#1%E3%80%81%E5%88%9B%E5%BB%BA%E5%AF%86%E9%92%A5 os.environ["GATEWAY_URL"] = "..." os.environ["APPBUILDER_TOKEN"] = "..." image_url = "https://bj.bcebos.com/v1/appbuilder/palnt_recognize_test.jpg?authorization=bce-auth-v1%2FALTAKGa8m4qCUasgoljdEDAzLm%2F2024-01-23T09%3A51%3A03Z%2F-1%2Fhost%2Faa2217067f78f0236c8262cdd89a4b4f4b2188d971ca547c53d01742af4a2cbe" # 从BOS存储读取样例文件 raw_image = requests.get(image_url).content inp = appbuilder.Message(content={"raw_image": raw_image}) # inp = Message(content={"url": image_url}) # 运行植物识别 plant_recognize = appbuilder.PlantRecognition() out = plant_recognize.run(inp) # 打印识别结果 print(out.content) """ name = "plant_rec" version = "v1" manifests = [ { "name": "plant_rec", "description": "用于识别图片中植物类别", "parameters": { "type": "object", "properties": { "img_name": { "type": "string", "description": "待识别图片的文件名" }, "img_url": { "type": "string", "description": "待识别图片的url" } }, "anyOf": [ { "required": [ "img_name" ] }, { "required": [ "img_url" ] } ] } } ] @HTTPClient.check_param @components_run_trace def run(self, message: Message, timeout: float = None, retry: int = 0) -> Message: """ 输入图片并识别其中的植物 Args: message (Message): 输入图片或图片url下载地址用于执行识别操作. 举例: Message(content={"raw_image": b"..."}) 或 Message(content={"url": "https://image/download/uel"}). timeout (float, optional): HTTP超时时间,默认为None retry (int, optional): HTTP重试次数,默认为0 Returns: Message: 模型识别结果 """ inp = PlantRecognitionInMsg(**message.content) request = PlantRecognitionRequest() if inp.url: request.url = inp.url if inp.raw_image: request.image = base64.b64encode(inp.raw_image) request.top_num = 5 request.baike_num = 0 response = self.__recognize(request, timeout, retry) plant_score_list = [] [plant_score_list.append(PlantScore(name=plant.name, score=plant.score)) for plant in response.result] out = PlantRecognitionOutMsg(plant_score_list=plant_score_list) return Message(content=out.model_dump()) def __recognize( self, request: PlantRecognitionRequest, timeout: float = None, retry: int = 0, request_id: str = None, ) -> PlantRecognitionResponse: r"""调用底层接口植物识别 参数: request (obj: `PlantRecognitionRequest`) : 植物识别输入参数 返回: response (obj: `PlantRecognitionResponse`): 植物识别返回结果 """ if not request.image and not request.url: raise ValueError("request format error, one of image or url must be set") data = PlantRecognitionRequest.to_dict(request) if retry != self.http_client.retry.total: self.http_client.retry.total = retry headers = self.http_client.auth_header(request_id) headers['content-type'] = 'application/x-www-form-urlencoded' url = self.http_client.service_url("/v1/bce/aip/image-classify/v1/plant") response = self.http_client.session.post(url, data=data, timeout=timeout, headers=headers) self.http_client.check_response_header(response) data = response.json() self.http_client.check_response_json(data) request_id = self.http_client.response_request_id(response) self.__class__.__check_service_error(request_id, data) return PlantRecognitionResponse(data, request_id=request_id) @components_run_stream_trace def tool_eval( self, name: str, streaming: bool, origin_query: str, **kwargs, ) -> Union[Generator[str, None, None], str]: """ 用于工具的执行,通过调用底层接口进行植物识别 Args: name (str): 工具名 streaming (bool): 是否流式返回 origin_query (str): 用户原始query **kwargs: 工具调用的额外关键字参数 Returns: Union[Generator[str, None, None], str]: 植物识别结果,包括识别出的植物类别和相应的置信度信息 """ traceid = kwargs.get("traceid") img_name = kwargs.get("img_name", "") img_url = kwargs.get("img_url", "") file_urls = kwargs.get("file_urls", {}) rec_res = self._recognize_w_post_process(img_name, img_url, file_urls, request_id=traceid) if streaming: yield rec_res else: return rec_res def _recognize_w_post_process(self, img_name, img_url, file_urls, request_id=None): r"""调底层接口对图片或图片url进行植物识别,并返回类别及其置信度 参数: img_name (str): 图片文件名 img_url (str): 图片url file_urls (dict): 文件名与对应文件url的映射 返回: str: 植物识别结果,包括识别出的动物类别和相应的置信度信息 """ req = PlantRecognitionRequest() if img_name in file_urls: req.url = file_urls[img_name] if img_url: if img_url in file_urls: img_url = file_urls[img_url] req.url = img_url req.top_num = TOP_NUM req.baike_num = BAIKE_NUM result = self.__recognize(req, request_id=request_id) result_dict = proto.Message.to_dict(result) rec_res = "模型识别结果为:\n" for rec_info in result_dict['result']: rec_res += "类别: {} 置信度: {}\n".format(rec_info['name'], rec_info['score']) return rec_res @staticmethod def __check_service_error(request_id: str, data: dict): r"""个性化服务response参数检查 参数: request (dict) : 地标识别body返回 返回: 无 """ if "error_code" in data or "error_msg" in data: raise AppBuilderServerException( request_id=request_id, service_err_code=data.get("error_code"), service_err_message=data.get("error_msg") ) ================================================ FILE: python/core/components/plant_recognize/model.py ================================================ # Copyright (c) 2023 Baidu, Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """植物识别数据类""" from typing import List import proto from pydantic import BaseModel TOP_NUM = 1 BAIKE_NUM = 0 class PlantBaikeInfo(proto.Message): """ 植物百度百科信息 属性: baike_url (str): 百度百科页面URL image_url (str): 百度百科中的图像URL description (str): 百度百科中的描述信息 """ baike_url: str = proto.Field( proto.STRING, number=1, ) image_url: str = proto.Field( proto.STRING, number=2, ) description: str = proto.Field( proto.STRING, number=3, ) class Plant(proto.Message): """ 植物识别结果 属性: name(str): 植物名称 score(float): 置信度 baike_info (List[PlantBaikeInfo]): 植物百科信息 """ name: str = proto.Field( proto.STRING, number=1, ) score: float = proto.Field( proto.FLOAT, number=2, ) baike_info = proto.RepeatedField( PlantBaikeInfo, number=3, ) class PlantRecognitionRequest(proto.Message): r"""植物识别请求参数 属性: image (str, 可选): 图像base64编码结果,支持jpg/png/bmp格式 url (str, 可选): 图像下载链接,base64编码后结果小于4MB, 短边大于15px,长边小于4096px 如果image存在,url字段则自动失效 top_num(int,可选): 返回得分较高的结果 baike_num(int,可选): 返回百科信息的个数 """ image: str = proto.Field( proto.STRING, number=1, ) url: str = proto.Field( proto.STRING, number=2, ) top_num: int = proto.Field( proto.INT64, number=3, ) baike_num: int = proto.Field( proto.INT64, number=4, ) class PlantRecognitionResponse(proto.Message): r"""植物识别返回结果 属性: log_id (int): 随机日志ID request_id(str): 请求链路ID result (List[Plant]): 识别植物列表信息 """ log_id: int = proto.Field( proto.INT64, number=1, ) request_id: str = proto.Field( proto.STRING, number=2, ) result = proto.RepeatedField( Plant, number=3, ) class PlantRecognitionInMsg(BaseModel): """ 植物识别输入消息 属性: raw_image(bytes): 图像原始内容 url(str): 图像下载链接 """ raw_image: bytes = b'' url: str = "" class PlantScore(BaseModel): """ 植物识别输出消息 属性: name(str): 植物名 score(float): 识别分数 """ name: str score: float class PlantRecognitionOutMsg(BaseModel): """ 植物识别输出消息 属性: PlantScores(List[PlantScore]): 植物识别结果列表 """ plant_score_list: List[PlantScore] ================================================ FILE: python/core/components/ppt_generation_from_file/README.md ================================================ # 文件生成PPT(PPTGenerationFromFile) ## 简介 文件生成PPT组件(PPTGenerationFromFile)可以根据上传的文件(支持**中英文**)生成PPT。 ### 功能介绍 根据上传的文件(支持**中英文**)生成PPT。 ### 特色优势 可根据文件(支持**中英文**)生成高质量PPT。 ### 应用场景 PPT生成。 ## 基本用法 ### 快速开始 ```python import os import appbuilder # 请前往千帆AppBuilder官网创建密钥,流程详见:https://cloud.baidu.com/doc/AppBuilder/s/Olq6grrt6#1%E3%80%81%E5%88%9B%E5%BB%BA%E5%AF%86%E9%92%A5 os.environ['APPBUILDER_TOKEN'] = '...' ppt_generator = appbuilder.PPTGenerationFromFile() user_input = { 'file_url':'http://image.yoojober.com/users/chatppt/temp/2024-06/6672a92c87e6f.doc', 'user_name':'百度千帆AppBuilder' } result = ppt_generator(appbuilder.Message(user_input)) print(result.content) ``` ## 参数说明 ### 鉴权说明 使用组件之前,请首先申请并设置鉴权参数,可参考[组件使用流程](https://cloud.baidu.com/doc/AppBuilder/s/Olq6grrt6#1%E3%80%81%E5%88%9B%E5%BB%BA%E5%AF%86%E9%92%A5)。 ```python # 设置环境中的TOKEN,以下示例略 os.environ['APPBUILDER_TOKEN'] = 'bce-YOURTOKEN' ``` ### 初始化参数 | 参数名称 | 参数类型 | 是否必须 | 描述 | 示例值 | | ------- | ------- | -------- | -------- | -------- | | `secret_key` | str | 否 | 用户鉴权token,默认从环境变量中获取: `os.getenv("APPBUILDER_TOKEN", "")` | bce-v3/XXX | | `gateway` | str | 否 | 后端网关服务地址,默认从环境变量中获取: `os.getenv("GATEWAY_URL", "")` | https://appbuilder.baidu.com | | `lazy_certification` | bool | 否 | 延迟认证,为True时在第一次运行时认证。默认为False。 | False | ### 调用参数 | 参数名称 | 参数类型 | 是否必须 | 描述 | 示例值 | | ------- | ------- | -------- | -------- | -------- | | `message` | obj | 是 | 输入消息,用于模型的主要输入内容。 | Message(content=input_data) | | `poll_request_times` | int | 否 | 轮询请求结果次数。默认为60。 | 60 | | `poll_request_interval` | int | 否 | 轮询请求的间隔时间(秒)。默认为5。 | 5 | 其中message包含的input_data包括以下参数: | 参数名称 | 参数类型 | 是否必须 | 描述 | 示例值 | | ------- | ------- | -------- | -------- | -------- | | `file_url` | str | 是 | 文件链接。 | http://image.yoojober.com/users/chatppt/temp/2024-06/6672a92c87e6f.doc | | `user_name` | str | 否 | 作者名。 | 百度千帆AppBuilder | ### 响应参数 | 参数名称 | 参数类型 | 描述 | 示例值 | | ------- | ------- | -------- | -------- | | `result` | obj | 模型运行后的输出结果,包含PPT下载链接。 | Message(content='...') | ### 响应示例 ``` https://download.yoojober.com/chatppt_business/2024-07/d1a1ab518ebcfbba7908a6734fa11d13.pptx?e=1721964933&token=8_2qFlGEVQZPpFvHdGR6gg2t9A9QZfWT9wwTl92s:9bs8LWV1SQLJNJoJgtd-sLF-CTw= ``` ## 高级用法 ## 更新记录和贡献 ### 2024.8.1 #### [Added] - 增加文件生成PPT组件。 - 增加文件生成PPT组件单元测试。 ================================================ FILE: python/core/components/ppt_generation_from_file/__init__.py ================================================ ================================================ FILE: python/core/components/ppt_generation_from_file/base.py ================================================ """ Copyright (c) 2023 Baidu, Inc. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. """ from pydantic import Field from enum import Enum from appbuilder.core.component import ComponentArguments DEFAULT_AUTHOR = '百度千帆AppBuilder' class PPTGenerationFromFileArgs(ComponentArguments): """论文生成PPT组件配置 """ file_url: str = Field(..., valiable_name='file_url', description='文件链接。') user_name: str = Field(default=None, variable_name='user_name', description='作者。') def convert_params_to_dict(self): """输出参数字典 """ output_dict = {} for k, v in self.model_dump().items(): if k in self.model_fields and \ self.model_fields[k].json_schema_extra and \ v is not None: if isinstance(v, Enum): output_dict[k] = v.value else: output_dict[k] = v return output_dict ================================================ FILE: python/core/components/ppt_generation_from_file/component.py ================================================ # Copyright (c) 2023 Baidu, Inc. All Rights Reserved. # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import traceback import time from typing import Optional from .base import PPTGenerationFromFileArgs, DEFAULT_AUTHOR from appbuilder.core.message import Message from appbuilder.core.component import Component from appbuilder.utils.logger_util import logger class PPTGenerationFromFile(Component): """ 文件生成PPT。 Examples: .. code-block:: python import os import appbuilder os.environ["APPBUILDER_TOKEN"] = '...' ppt_generator = appbuilder.PPTGenerationFromFile() user_input = { 'file_url': 'http://image.yoojober.com/users/chatppt/temp/2024-06/6672aa839a9da.docx' } answer = ppt_generator(appbuilder.Message(user_input)) print(answer.content) """ uniform_prefix = '/api/v1/component/component' ppt_generation_url = '/ppt/text2ppt/apps/ppt-create-file' get_ppt_generation_status_url = '/ppt/text2ppt/apps/ppt-result' get_ppt_download_link_url = '/ppt/text2ppt/apps/ppt-download' name = 'ppt_generation_from_file' version: str meta = PPTGenerationFromFileArgs manifests = [ { "name": "ppt_generation_from_file", "description": "根据上传的文件(非论文)生成PPT。", "parameters": { "type": "object", "properties": { "file_url": { "type": "string", "description": "用户上传的文件的链接。" } }, "required": [ "file_url" ] } } ] def __init__( self, secret_key: Optional[str] = None, gateway: str = "", lazy_certification: bool = False, **kwargs ): """初始化论文生成PPT组件。 Args: secret_key (str, 可选): 用户鉴权token, 默认从环境变量中获取: os.getenv("APPBUILDER_TOKEN", ""). gateway (str, 可选): 后端网关服务地址,默认从环境变量中获取: os.getenv("GATEWAY_URL", "") lazy_certification (bool, 可选): 延迟认证,为True时在第一次运行时认证. Defaults to False. Returns: None """ super().__init__(PPTGenerationFromFileArgs, secret_key=secret_key, gateway=gateway, lazy_certification=lazy_certification) self.x_alternative_authorization = None def ppt_generation(self, post_data: dict, timeout: float = None): """ 创建PPT生成任务 Args: post_data (dict): 包含PPT生成任务所需数据的字典 timeout (float, optional): 请求超时时间,默认为None,表示不设置超时时间。 Returns: str: PPT生成任务的Job ID Raises: Exception: 如果PPT生成任务请求失败,抛出异常 """ url = self.http_client.service_url(self.ppt_generation_url, self.uniform_prefix) headers = self.http_client.auth_header() if self.x_alternative_authorization: headers["X-Alternative-Authorization"] = self.x_alternative_authorization headers['Content-Type'] = 'application/json' response = self.http_client.session.post(url, json=post_data, headers=headers, timeout=timeout) self.http_client.check_response_header(response) resp_data = response.json() if resp_data.get('code', None) != 200 or resp_data.get('msg', None) != 'success': error_msg = f'[ppt_generation] PPT generation request error! response: {resp_data}' logger.error(error_msg) raise Exception(error_msg) job_id = resp_data['data']['id'] return job_id def get_ppt_generation_status(self, job_id: str, request_times: int = 60, request_interval: int = 5, timeout: float = None): """ 轮询查看PPT生成状态 Args: job_id (str): PPT生成任务的唯一标识符 request_times (int, optional): 轮询请求次数,默认为60次。 request_interval (int, optional): 每次轮询请求的间隔时间(秒),默认为5秒。 timeout (float, optional): 请求的超时时间(秒),默认为None,即无超时限制。 Returns: int: PPT生成状态码,1表示正在生成,2表示生成完成,3表示生成失败。 Raises: Exception: 如果PPT生成状态码不为2(生成完成),则抛出异常。 """ url = self.http_client.service_url(self.get_ppt_generation_status_url, self.uniform_prefix) + f'?id={job_id}' headers = self.http_client.auth_header() if self.x_alternative_authorization: headers["X-Alternative-Authorization"] = self.x_alternative_authorization headers['Content-Type'] = 'application/json' status = -1 for _ in range(request_times): response = self.http_client.session.get(url, headers=headers, timeout=timeout) try: self.http_client.check_response_header(response) except: error_msg = f'[get_ppt_generation_status] ERROR!\n{traceback.format_exc()}' logger.error(error_msg) time.sleep(request_interval) continue self.http_client.check_response_header(response) resp_data = response.json() if resp_data.get('code', None) != 200 or resp_data.get('msg', None) != 'success': error_msg = f'[get_ppt_generation_status] Get PPT generation status error! job_id: {job_id}, ' \ f'response: {resp_data}' logger.error(error_msg) raise Exception(error_msg) status = resp_data['data']['status'] if status == 1: # 正在生成 time.sleep(request_interval) elif status == 2: # 生成完成 break elif status == 3: # 生成失败 raise Exception(f'[get_ppt_generation_status] PPT generation Fail! job_id: {job_id}') if status == 1: error_msg = f'[get_ppt_generation_status] PPT generation timeout! job_id: {job_id}' logger.error(error_msg) raise Exception(error_msg) elif status == -1: error_msg = f'[get_ppt_generation_status] Request fail! job_id: {job_id}' logger.error(error_msg) raise Exception(error_msg) return status def get_ppt_download_link(self, job_id: str, timeout: float = None): """ 获取PPT下载链接 Args: job_id (str): 任务ID timeout (float, optional): 请求超时时间,默认为None。 Returns: str: PPT下载链接 Raises: Exception: PPT生成请求错误 """ url = self.http_client.service_url(self.get_ppt_download_link_url, self.uniform_prefix) + f'?id={job_id}' headers = self.http_client.auth_header() if self.x_alternative_authorization: headers["X-Alternative-Authorization"] = self.x_alternative_authorization headers['Content-Type'] = 'application/json' response = self.http_client.session.get(url, headers=headers, timeout=timeout) self.http_client.check_response_header(response) resp_data = response.json() if resp_data.get('code', None) != 200 or resp_data.get('msg', None) != 'success': error_msg = f'[get_ppt_download_link] PPT generation request error! response: {resp_data}' logger.error(error_msg) raise Exception(error_msg) download_link = resp_data['data']['download_url'] return download_link def run(self, message: Message, poll_request_times=60, poll_request_interval=5) -> Message: """使用给定的输入运行模型并返回结果。 Args: message (Message): 输入消息,用于传入请求参数。 poll_request_times (int): 轮询请求结果次数。 poll_request_interval (int): 轮询请求的间隔时间(秒)。 Returns: result (Message): 模型运行后的输出消息。 """ # 参数检查与设置 user_input = message.content for key in ['file_url']: if key not in user_input: raise Exception(f'[PPTGenerationFromFile] Missing key: {key}') if user_input.get('user_name', '') is None or not user_input.get('user_name', '').strip(): user_input['user_name'] = DEFAULT_AUTHOR user_input = self.meta(**{k: v for k, v in user_input.items() if v is not None}) user_input = user_input.convert_params_to_dict() # 创建PPT生成任务 logger.info('Creating a PPT generation task...') job_id = self.ppt_generation(user_input) logger.info('Creating a PPT generation task succeeds.') # 查询PPT生成状态 logger.info('Generating PPT...') status = self.get_ppt_generation_status(job_id, request_times=poll_request_times, request_interval=poll_request_interval) logger.info('PPT generation task completed.') # 获取PPT下载链接 logger.info('Getting PPT download link...') ppt_download_link = self.get_ppt_download_link(job_id) logger.info('Getting PPT download link succeeds.') return Message(ppt_download_link) def tool_eval(self, stream: bool = False, **kwargs): """ 用于执行function call的功能。 Args: stream (bool, optional): 是否以生成器的方式返回结果,默认为False。 **kwargs: 任意关键字参数,目前只支持'file_url'。 Returns: 如果stream为False,则返回一个字符串,表示ppt下载链接。 如果stream为True,则返回一个生成器,生成器产生一个字符串,表示ppt下载链接。 Raises: ValueError: 如果'file_url'为空,则抛出异常。 """ file_url = kwargs.get('file_url', '') if not file_url: raise ValueError('param `file_url` should not be empty.') user_input = { 'file_url': file_url } message = Message(user_input) result = self.run(message, poll_request_times=60, poll_request_interval=5) ppt_download_link = result.content if stream: yield ppt_download_link else: return ppt_download_link ================================================ FILE: python/core/components/ppt_generation_from_instruction/README.md ================================================ # 指令生成PPT(PPTGenerationFromInstruction) ## 简介 指令生成PPT组件(PPTGenerationFromInstruction)可以基于指令或者自定义信息生成PPT。 ### 功能介绍 基于指令或者自定义信息生成PPT。 ### 特色优势 - 可生成高质量PPT。 - 支持传入自定义信息生成PPT。 - 生成PPT复杂度可控。 ### 应用场景 PPT生成。 ## 基本用法 ### 快速开始 ```python import os import appbuilder # 请前往千帆AppBuilder官网创建密钥,流程详见:https://cloud.baidu.com/doc/AppBuilder/s/Olq6grrt6#1%E3%80%81%E5%88%9B%E5%BB%BA%E5%AF%86%E9%92%A5 os.environ['APPBUILDER_TOKEN'] = '...' ppt_generator = appbuilder.PPTGenerationFromInstruction() user_input = { 'text': '生成一个介绍北京的PPT。', 'custom_data': {}, 'complex': 1, 'user_name': '百度千帆AppBuilder' } result = ppt_generator(appbuilder.Message(user_input)) print(result.content) ``` ## 参数说明 ### 鉴权说明 使用组件之前,请首先申请并设置鉴权参数,可参考[组件使用流程](https://cloud.baidu.com/doc/AppBuilder/s/Olq6grrt6#1%E3%80%81%E5%88%9B%E5%BB%BA%E5%AF%86%E9%92%A5)。 ```python # 设置环境中的TOKEN,以下示例略 os.environ['APPBUILDER_TOKEN'] = 'bce-YOURTOKEN' ``` ### 初始化参数 | 参数名称 | 参数类型 | 是否必须 | 描述 | 示例值 | | ------- | ------- | -------- | -------- | -------- | | `secret_key` | str | 否 | 用户鉴权token,默认从环境变量中获取: `os.getenv("APPBUILDER_TOKEN", "")` | bce-v3/XXX | | `gateway` | str | 否 | 后端网关服务地址,默认从环境变量中获取: `os.getenv("GATEWAY_URL", "")` | https://appbuilder.baidu.com | | `lazy_certification` | bool | 否 | 延迟认证,为True时在第一次运行时认证。默认为False。 | False | ### 调用参数 | 参数名称 | 参数类型 | 是否必须 | 描述 | 示例值 | | ------- | ------- | -------- | -------- | -------- | | `message` | obj | 是 | 输入消息,用于模型的主要输入内容。 | Message(content=input_data) | | `poll_request_times` | int | 否 | 轮询请求结果次数。默认为60。 | 60 | | `poll_request_interval` | int | 否 | 轮询请求的间隔时间(秒)。默认为5。 | 5 | 其中message包含的input_data包括以下参数: | 参数名称 | 参数类型 | 是否必须 | 描述 | 示例值 | | ------- | ------- | -------- | -------- | -------- | | `text` | str | 是 | 请求生成PPT的query。可为空字符串"",与custom_data有一个参数不为空即可。 | 请你生成一个介绍北京的PPT。 | | `custom_data` | obj | 是 | 自定义参数,可指定标题、副标题、作者、结构等信息。可为空字典{},与text有一个参数不为空即可。 | `{"title": "标题", "sub_title": "副标题", "author": "作者", "catalogs": [{"catalog": "一级大纲1", "sub_catalog": ["一级大纲1-二级大纲1"]}, {"catalog": "一级大纲2", "sub_catalog": ["一级大纲2-二级大纲1"]}], "contents": [{"catalog_index": 0, "sub_catalog_index": 0, "content": ["一级大纲1-二级大纲1-内容1", "一级大纲1-二级大纲1-内容2"]}, {"catalog_index": 1, "sub_catalog_index": 0, "content": [{"key": "一级大纲2-二级大纲1-小标题1", "value": "一级大纲2-二级大纲1-子内容1"}, {"key": "一级大纲2-二级大纲1-小标题2", "value": "一级大纲2-二级大纲1-子内容2"}, {"key": "一级大纲2-二级大纲1-小标题3", "value": "一级大纲2-二级大纲1-子内容3"}], "picture": ["https://image.yoojober.com/chatppt_business/2024-02/000114cd07b809cb8c6bb22674e814da.png"]}]}` | | `complex` | integer | 否 | PPT复杂度,可选:1、2、3,其中1最简单、3最复杂。 | 1 | | `font_name` | str | 否 | PPT字体,可选:黑体、宋体、仿宋、幼圆、楷体、隶书。 | 黑体 | | `user_name` | str | 否 | 作者名。 | 百度千帆AppBuilder | ### 响应参数 | 参数名称 | 参数类型 | 描述 | 示例值 | | ------- | ------- | -------- | -------- | | `result` | obj | 模型运行后的输出结果,包含PPT下载链接。 | Message(content='...') | ### 响应示例 ``` https://download.yoojober.com/chatppt_business/2024-07/bf2af50285e52261507abdd7385e02c4.pptx?e=1721964536&token=8_2qFlGEVQZPpFvHdGR6gg2t9A9QZfWT9wwTl92s:nikgRM9RbPxzClBvmKrweeKd9Ck= ``` ## 高级用法 ## 更新记录和贡献 ### 2024.8.1 #### [Added] - 增加指令生成PPT组件。 - 增加指令生成PPT组件单元测试。 ================================================ FILE: python/core/components/ppt_generation_from_instruction/__init__.py ================================================ ================================================ FILE: python/core/components/ppt_generation_from_instruction/base.py ================================================ """ Copyright (c) 2023 Baidu, Inc. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. """ from pydantic import Field from enum import Enum from appbuilder.core.component import ComponentArguments DEFAULT_AUTHOR = '百度千帆AppBuilder' class ComplexChoices(Enum): easy = 1 medium = 2 complex = 3 class FontNameChoices(Enum): HeiTi = '黑体' SongTi = '宋体' FangSong = '仿宋' YouYuan = '幼圆' KaiTi = '楷体' LiShu = '隶书' class PPTGenerationFromInstructionArgs(ComponentArguments): """PPT生成组件配置 """ text: str = Field(..., valiable_name='text', description='请求生成PPT的query。') custom_data: dict = Field(..., valiable_name='custom_data', description='自定义参数,可指定标题、副标题等信息。') complex: ComplexChoices = Field(default=None, variable_name='complex', description='生成PPT的复杂度,可选:1、2、3,分别对应简单、中等、复杂。默认是1。') font_name: FontNameChoices = Field(default=None, variable_name='font_name', description='字体,可选:黑体、宋体、仿宋、幼圆、楷体、隶书。') user_name: str = Field(default=None, variable_name='user_name', description='PPT作者名。') def convert_params_to_dict(self): """输出参数字典 """ output_dict = {} for k, v in self.model_dump().items(): if k in self.model_fields and \ self.model_fields[k].json_schema_extra and \ v is not None: if isinstance(v, Enum): output_dict[k] = v.value else: output_dict[k] = v return output_dict ================================================ FILE: python/core/components/ppt_generation_from_instruction/component.py ================================================ # Copyright (c) 2023 Baidu, Inc. All Rights Reserved. # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import traceback import time from typing import Optional from .base import PPTGenerationFromInstructionArgs, DEFAULT_AUTHOR from appbuilder.core.message import Message from appbuilder.core.component import Component from appbuilder.utils.logger_util import logger class PPTGenerationFromInstruction(Component): """ 指令生成PPT,可通过传入对PPT的描述或者自定义参数进行生成。 Examples: .. code-block:: python import os import appbuilder os.environ["APPBUILDER_TOKEN"] = '...' ppt_generator = appbuilder.PPTGenerationFromInstruction() input_data = { 'text': '生成一个介绍北京的PPT。', 'custom_data': {}, 'complex': 3, 'user_name': '百度千帆AppBuilder' } answer = ppt_generator(appbuilder.Message(input_data)) print(answer.content) """ uniform_prefix = '/api/v1/component/component' ppt_generation_url = '/ppt/text2ppt/apps/ppt-create' get_ppt_generation_status_url = '/ppt/text2ppt/apps/ppt-result' get_ppt_download_link_url = '/ppt/text2ppt/apps/ppt-download' name = 'ppt_generation_from_instruction' version: str meta = PPTGenerationFromInstructionArgs manifests = [ { "name": "ppt_generation_from_instruction", "description": "根据输入指令生成PPT。", "parameters": { "type": "object", "properties": { "text": { "type": "string", "description": "用户请求生成PPT的指令。", "example": "生成一个介绍北京的PPT。" } }, "required": [ "text" ] } } ] def __init__( self, secret_key: Optional[str] = None, gateway: str = '', lazy_certification: bool = False, **kwargs ): """初始化PPT生成组件。 Args: secret_key (str, 可选): 用户鉴权token, 默认从环境变量中获取: os.getenv("APPBUILDER_TOKEN", ""). gateway (str, 可选): 后端网关服务地址,默认从环境变量中获取: os.getenv("GATEWAY_URL", "") lazy_certification (bool, 可选): 延迟认证,为True时在第一次运行时认证. Defaults to False. Returns: None """ super().__init__(PPTGenerationFromInstructionArgs, secret_key=secret_key, gateway=gateway, lazy_certification=lazy_certification) self.x_alternative_authorization = None def ppt_generation(self, post_data: dict, timeout: float = None): """ 创建PPT生成任务 Args: post_data (dict): 请求数据 timeout (float, optional): 请求超时时间,默认为None. Returns: str: 任务ID Raises: Exception: PPT生成请求失败 """ url = self.http_client.service_url(self.ppt_generation_url, self.uniform_prefix) headers = self.http_client.auth_header() if self.x_alternative_authorization: headers["X-Alternative-Authorization"] = self.x_alternative_authorization headers['Content-Type'] = 'application/json' response = self.http_client.session.post(url, json=post_data, headers=headers, timeout=timeout) self.http_client.check_response_header(response) resp_data = response.json() if resp_data.get('code', None) != 200 or resp_data.get('msg', None) != 'success': error_msg = f'[ppt_generation] PPT generation request error! response: {resp_data}' logger.error(error_msg) raise Exception(error_msg) job_id = resp_data['data']['id'] return job_id def get_ppt_generation_status(self, job_id: str, request_times: int = 60, request_interval: int = 5, timeout: float = None): """ 轮询查看PPT生成状态 Args: job_id (str): PPT生成任务的唯一标识符 request_times (int, optional): 轮询请求的次数,默认为60次。 request_interval (int, optional): 每次轮询请求之间的间隔时间(秒),默认为5秒。 timeout (float, optional): 请求的超时时间(秒)。如果未设置,则使用http_client的默认超时时间。 Returns: int: PPT生成状态码。 - 1:正在生成 - 2:生成完成 - 3:生成失败 Raises: Exception: PPT生成过程中出现异常时抛出。 """ url = self.http_client.service_url(self.get_ppt_generation_status_url, self.uniform_prefix) + f'?id={job_id}' headers = self.http_client.auth_header() if self.x_alternative_authorization: headers["X-Alternative-Authorization"] = self.x_alternative_authorization headers['Content-Type'] = 'application/json' status = -1 for _ in range(request_times): response = self.http_client.session.get(url, headers=headers, timeout=timeout) try: self.http_client.check_response_header(response) except: error_msg = f'[get_ppt_generation_status] ERROR!\n{traceback.format_exc()}' logger.error(error_msg) time.sleep(request_interval) continue self.http_client.check_response_header(response) resp_data = response.json() if resp_data.get('code', None) != 200 or resp_data.get('msg', None) != 'success': error_msg = f'[get_ppt_generation_status] Get PPT generation status error! job_id: {job_id}, ' \ f'response: {resp_data}' logger.error(error_msg) raise Exception(error_msg) status = resp_data['data']['status'] if status == 1: # 正在生成 time.sleep(request_interval) elif status == 2: # 生成完成 break elif status == 3: # 生成失败 raise Exception(f'[get_ppt_generation_status] PPT generation Fail! job_id: {job_id}') if status == 1: error_msg = f'[get_ppt_generation_status] PPT generation timeout! job_id: {job_id}' logger.error(error_msg) raise Exception(error_msg) elif status == -1: error_msg = f'[get_ppt_generation_status] Request fail! job_id: {job_id}' logger.error(error_msg) raise Exception(error_msg) return status def get_ppt_download_link(self, job_id: str, timeout: float = None): """ 获取PPT下载链接 Args: job_id (str): 作业ID timeout (float, optional): 请求超时时间,默认为None。 Returns: str: PPT下载链接 Raises: Exception: 当PPT生成请求失败时抛出异常 """ url = self.http_client.service_url(self.get_ppt_download_link_url, self.uniform_prefix) + f'?id={job_id}' headers = self.http_client.auth_header() if self.x_alternative_authorization: headers["X-Alternative-Authorization"] = self.x_alternative_authorization headers['Content-Type'] = 'application/json' response = self.http_client.session.get(url, headers=headers, timeout=timeout) self.http_client.check_response_header(response) resp_data = response.json() if resp_data.get('code', None) != 200 or resp_data.get('msg', None) != 'success': error_msg = f'[get_ppt_download_link] PPT generation request error! response: {resp_data}' logger.error(error_msg) raise Exception(error_msg) download_link = resp_data['data']['download_url'] return download_link def run(self, message: Message, poll_request_times=60, poll_request_interval=5) -> Message: """ 使用给定的输入运行模型并返回结果。 Args: message (Message): 输入消息,用于传入请求参数。 poll_request_times (int, optional): 轮询请求结果次数,默认为60。 poll_request_interval (int, optional): 轮询请求的间隔时间(秒),默认为5。 Returns: Message: 模型运行后的输出消息,包含PPT下载链接。 """ # 参数检查与设置 user_input = message.content for key in ['text', 'custom_data']: if key not in user_input: raise Exception(f'[PPTGeneration] Missing key: {key}') if user_input['custom_data']: author = user_input['custom_data'].get('author', '') if author is None or not author.strip(): user_input['custom_data']['author'] = DEFAULT_AUTHOR if user_input.get('user_name', '') is None or not user_input.get('user_name', '').strip(): user_input['user_name'] = DEFAULT_AUTHOR user_input = self.meta(**{k: v for k, v in user_input.items() if v is not None}) user_input = user_input.convert_params_to_dict() # 创建PPT生成任务 logger.info('Creating a PPT generation task...') job_id = self.ppt_generation(user_input) logger.info('Creating a PPT generation task succeeds.') # 查询PPT生成状态 logger.info('Generating PPT...') status = self.get_ppt_generation_status(job_id, request_times=poll_request_times, request_interval=poll_request_interval) logger.info('PPT generation task completed.') # 获取PPT下载链接 logger.info('Getting PPT download link...') ppt_download_link = self.get_ppt_download_link(job_id) logger.info('Getting PPT download link succeeds.') return Message(ppt_download_link) def tool_eval(self, stream: bool = False, **kwargs): """ 评估给定的文本内容。 Args: stream (bool, optional): 是否以生成器形式返回结果,默认为False。如果为True,则逐个生成下载链接;如果为False,则直接返回下载链接。 **kwargs: 关键字参数,可以传递其他参数,但当前只使用 'text' 参数。 Returns: 如果 stream 为 False,则返回一个包含下载链接的字符串;如果 stream 为 True,则逐个生成下载链接。 Raises: ValueError: 如果 'text' 参数为空,则抛出此异常。 """ text = kwargs.get('text', '') if not text: raise ValueError('param `text` should not be empty.') user_input = { 'text': text, 'custom_data': {} } message = Message(user_input) result = self.run(message, poll_request_times=60, poll_request_interval=5) ppt_download_link = result.content if stream: yield ppt_download_link else: return ppt_download_link ================================================ FILE: python/core/components/ppt_generation_from_paper/README.md ================================================ # 论文生成PPT(PPTGenerationFromPaper) ## 简介 论文生成PPT组件(PPTGenerationFromPaper)可以根据上传的论文(支持**中英文**)生成PPT。 ### 功能介绍 根据上传的论文(支持**中英文**)生成PPT。 ### 特色优势 可根据论文(支持**中英文**)生成高质量PPT。 ### 应用场景 PPT生成。 ## 基本用法 ### 快速开始 ```python import os import appbuilder # 请前往千帆AppBuilder官网创建密钥,流程详见:https://cloud.baidu.com/doc/AppBuilder/s/Olq6grrt6#1%E3%80%81%E5%88%9B%E5%BB%BA%E5%AF%86%E9%92%A5 os.environ['APPBUILDER_TOKEN'] = '...' ppt_generator = appbuilder.PPTGenerationFromPaper() user_input = { 'file_key': 'http://image.yoojober.com/users/chatppt/temp/2024-06/6672aa839a9da.docx', 'style': '科技', 'color': '蓝色', 'title': '', 'pleader': '百度千帆AppBuilder', 'advisor': '百度千帆AppBuilder', 'school': '北京大学', 'school_logo': '', 'school_picture': '' } result = ppt_generator(appbuilder.Message(user_input)) print(result.content) ``` ## 参数说明 ### 鉴权说明 使用组件之前,请首先申请并设置鉴权参数,可参考[组件使用流程](https://cloud.baidu.com/doc/AppBuilder/s/Olq6grrt6#1%E3%80%81%E5%88%9B%E5%BB%BA%E5%AF%86%E9%92%A5)。 ```python # 设置环境中的TOKEN,以下示例略 os.environ['APPBUILDER_TOKEN'] = 'bce-YOURTOKEN' ``` ### 初始化参数 | 参数名称 | 参数类型 | 是否必须 | 描述 | 示例值 | | ------- | ------- | -------- | -------- | -------- | | `secret_key` | str | 否 | 用户鉴权token,默认从环境变量中获取: `os.getenv("APPBUILDER_TOKEN", "")` | bce-v3/XXX | | `gateway` | str | 否 | 后端网关服务地址,默认从环境变量中获取: `os.getenv("GATEWAY_URL", "")` | https://appbuilder.baidu.com | | `lazy_certification` | bool | 否 | 延迟认证,为True时在第一次运行时认证。默认为False。 | False | ### 调用参数 | 参数名称 | 参数类型 | 是否必须 | 描述 | 示例值 | | ------- | ------- | -------- | -------- | -------- | | `message` | obj | 是 | 输入消息,用于模型的主要输入内容。 | Message(content=input_data) | | `poll_request_times` | int | 否 | 轮询请求结果次数。默认为60。 | 60 | | `poll_request_interval` | int | 否 | 轮询请求的间隔时间(秒)。默认为5。 | 5 | 其中message包含的input_data包括以下参数: | 参数名称 | 参数类型 | 是否必须 | 描述 | 示例值 | | ------- | ------- | -------- | -------- | -------- | | `file_key` | str | 是 | 论文链接。 | http://image.yoojober.com/users/chatppt/temp/2024-06/6672aa839a9da.docx | | `style` | str | 否 | PPT风格,可选:科技、商务、小清新、可爱卡通、中国风、极简、党政。 | 科技 | | `color` | str | 否 | PPT主色调。可选:紫色、红色、橙色、黄色、绿色、青色、蓝色、粉色。 | 紫色 | | `title` | str | 否 | 自定义标题。优先使用自定义标题,如果为空则使用解析结果中的标题。 | 论文分享 | | `pleader` | str | 否 | 汇报人。 | 百度千帆AppBuilder | | `advisor` | str | 否 | 指导教师。 | 百度千帆AppBuilder | | `school` | str | 否 | 学校名称。 | 北京大学 | | `school_logo` | str | 否 | 学校logo链接。 | | | `school_picture` | str | 否 | 学校图片链接。 | | ### 响应参数 | 参数名称 | 参数类型 | 描述 | 示例值 | | ------- | ------- | -------- | -------- | | `result` | obj | 模型运行后的输出结果,包含PPT下载链接。 | Message(content='...') | ### 响应示例 ``` https://download.yoojober.com/chatppt_business/2024-07/6f472b65ee324d2da7849b6003a896e3.pptx?e=1721964794&token=8_2qFlGEVQZPpFvHdGR6gg2t9A9QZfWT9wwTl92s:nG-hbPN51uPP8FOeTY2jdQcT51w= ``` ## 高级用法 ## 更新记录和贡献 ### 2024.8.1 #### [Added] - 增加论文生成PPT组件。 - 增加论文生成PPT组件单元测试。 ================================================ FILE: python/core/components/ppt_generation_from_paper/__init__.py ================================================ ================================================ FILE: python/core/components/ppt_generation_from_paper/base.py ================================================ """ Copyright (c) 2023 Baidu, Inc. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. """ from pydantic import Field from enum import Enum from appbuilder.core.component import ComponentArguments DEFAULT_AUTHOR = '百度千帆AppBuilder' class StyleChoices(Enum): technology = '科技' business = '商务' fresh = '小清新' cute_cartoon = '可爱卡通' chinese_style = '中国风' minimalist = '极简' party_politics = '党政' class ColorChoices(Enum): purple = '紫色' red = '红色' orange = '橙色' yellow = '黄色' green = '绿色' cyan = '青色' blue = '蓝色' pink = '粉色' class FontNameChoices(Enum): HeiTi = '黑体' SongTi = '宋体' FangSong = '仿宋' YouYuan = '幼圆' KaiTi = '楷体' LiShu = '隶书' class PPTGenerationFromPaperArgs(ComponentArguments): """论文生成PPT组件配置 """ file_key: str = Field(..., valiable_name='file_key', description='论文链接。') style: StyleChoices = Field(default=None, valiable_name='style', description='PPT风格,可选:科技、商务、小清新、可爱卡通、中国风、极简、党政。') color: ColorChoices = Field(default=None, variable_name='color', description='PPT主色调。可选:紫色、红色、橙色、黄色、绿色、青色、蓝色、粉色。') title: str = Field(default=None, variable_name='title', description='自定义标题。优先使用自定义标题,如果为空则使用解析结果中的标题。') pleader: str = Field(default=None, variable_name='pleader', description='汇报人。') advisor: str = Field(default=None, variable_name='advisor', description='指导教师。') school: str = Field(default=None, variable_name='school', description='学校名称。') school_logo: str = Field(default=None, variable_name='school_logo', description='学校logo图片链接。') school_picture: str = Field(default=None, variable_name='school_picture', description='学校图片链接。') def convert_params_to_dict(self): """输出参数字典 """ output_dict = {} for k, v in self.model_dump().items(): if k in self.model_fields and \ self.model_fields[k].json_schema_extra and \ v is not None: if isinstance(v, Enum): output_dict[k] = v.value else: output_dict[k] = v return output_dict ================================================ FILE: python/core/components/ppt_generation_from_paper/component.py ================================================ # Copyright (c) 2023 Baidu, Inc. All Rights Reserved. # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import traceback import time from typing import Optional from .base import PPTGenerationFromPaperArgs, DEFAULT_AUTHOR from appbuilder.core.message import Message from appbuilder.core.component import Component from appbuilder.utils.logger_util import logger class PPTGenerationFromPaper(Component): """ 论文生成PPT。 Examples: .. code-block:: python import os import appbuilder os.environ["APPBUILDER_TOKEN"] = '...' ppt_generator = appbuilder.PPTGenerationFromPaper() user_input = { 'file_key': 'http://image.yoojober.com/users/chatppt/temp/2024-06/6672aa839a9da.docx' } answer = ppt_generator(appbuilder.Message(user_input)) print(answer.content) """ uniform_prefix = '/api/v1/component/component' ppt_generation_url = '/ppt/text2ppt/apps/ppt-create-thesis' get_ppt_generation_status_url = '/ppt/text2ppt/apps/ppt-result' get_ppt_download_link_url = '/ppt/text2ppt/apps/ppt-download' name = 'ppt_generation_from_paper' version: str meta = PPTGenerationFromPaperArgs manifests = [ { "name": "ppt_generation_from_paper", "description": "根据上传的论文生成PPT。", "parameters": { "type": "object", "properties": { "file_key": { "type": "string", "description": "用户上传的论文的链接。" } }, "required": [ "file_key" ] } } ] def __init__( self, secret_key: Optional[str] = None, gateway: str = "", lazy_certification: bool = False, **kwargs ): """初始化论文生成PPT组件。 Args: secret_key (str, 可选): 用户鉴权token, 默认从环境变量中获取: os.getenv("APPBUILDER_TOKEN", ""). gateway (str, 可选): 后端网关服务地址,默认从环境变量中获取: os.getenv("GATEWAY_URL", "") lazy_certification (bool, 可选): 延迟认证,为True时在第一次运行时认证. Defaults to False. Returns: None """ super().__init__(PPTGenerationFromPaperArgs, secret_key=secret_key, gateway=gateway, lazy_certification=lazy_certification) self.x_alternative_authorization = None def ppt_generation(self, post_data: dict, timeout: float = None): """ 创建PPT生成任务 Args: post_data (dict): 发送的POST请求体数据 timeout (float, optional): 请求超时时间,默认为None。 Returns: str: 返回的任务ID Raises: Exception: 如果PPT生成请求失败,抛出异常 """ url = self.http_client.service_url(self.ppt_generation_url, self.uniform_prefix) headers = self.http_client.auth_header() if self.x_alternative_authorization: headers["X-Alternative-Authorization"] = self.x_alternative_authorization headers['Content-Type'] = 'application/json' response = self.http_client.session.post(url, json=post_data, headers=headers, timeout=timeout) self.http_client.check_response_header(response) resp_data = response.json() if resp_data.get('code', None) != 200 or resp_data.get('msg', None) != 'success': error_msg = f'[ppt_generation] PPT generation request error! response: {resp_data}' logger.error(error_msg) raise Exception(error_msg) job_id = resp_data['data']['id'] return job_id def get_ppt_generation_status(self, job_id: str, request_times: int = 60, request_interval: int = 5, timeout: float = None): """ 轮询查看PPT生成状态 Args: job_id (str): 任务ID request_times (int, optional): 请求次数,默认为60次。 request_interval (int, optional): 请求间隔时间,默认为5秒。 timeout (float, optional): 请求超时时间,默认为None,即不设置超时时间。 Returns: int: PPT生成状态码。 - 1: PPT正在生成中 - 2: PPT生成完成 - 3: PPT生成失败 Raises: Exception: PPT生成失败或请求失败时抛出异常。 """ url = self.http_client.service_url(self.get_ppt_generation_status_url, self.uniform_prefix) + f'?id={job_id}' headers = self.http_client.auth_header() if self.x_alternative_authorization: headers["X-Alternative-Authorization"] = self.x_alternative_authorization headers['Content-Type'] = 'application/json' status = -1 for _ in range(request_times): response = self.http_client.session.get(url, headers=headers, timeout=timeout) try: self.http_client.check_response_header(response) except: error_msg = f'[get_ppt_generation_status] ERROR!\n{traceback.format_exc()}' logger.error(error_msg) time.sleep(request_interval) continue self.http_client.check_response_header(response) resp_data = response.json() if resp_data.get('code', None) != 200 or resp_data.get('msg', None) != 'success': error_msg = f'[get_ppt_generation_status] Get PPT generation status error! job_id: {job_id}, ' \ f'response: {resp_data}' logger.error(error_msg) raise Exception(error_msg) status = resp_data['data']['status'] if status == 1: # 正在生成 time.sleep(request_interval) elif status == 2: # 生成完成 break elif status == 3: # 生成失败 raise Exception(f'[get_ppt_generation_status] PPT generation Fail! job_id: {job_id}') if status == 1: error_msg = f'[get_ppt_generation_status] PPT generation timeout! job_id: {job_id}' logger.error(error_msg) raise Exception(error_msg) elif status == -1: error_msg = f'[get_ppt_generation_status] Request fail! job_id: {job_id}' logger.error(error_msg) raise Exception(error_msg) return status def get_ppt_download_link(self, job_id: str, timeout: float = None): """ 获取PPT下载链接 Args: job_id (str): 任务ID timeout (float, optional): 请求超时时间,默认为None. Returns: str: PPT下载链接 Raises: Exception: PPT生成请求失败 """ url = self.http_client.service_url(self.get_ppt_download_link_url, self.uniform_prefix) + f'?id={job_id}' headers = self.http_client.auth_header() if self.x_alternative_authorization: headers["X-Alternative-Authorization"] = self.x_alternative_authorization headers['Content-Type'] = 'application/json' response = self.http_client.session.get(url, headers=headers, timeout=timeout) self.http_client.check_response_header(response) resp_data = response.json() if resp_data.get('code', None) != 200 or resp_data.get('msg', None) != 'success': error_msg = f'[get_ppt_download_link] PPT generation request error! response: {resp_data}' logger.error(error_msg) raise Exception(error_msg) download_link = resp_data['data']['download_url'] return download_link def run(self, message: Message, poll_request_times=60, poll_request_interval=5) -> Message: """ 使用给定的输入运行模型并返回结果。 Args: message (Message): 输入消息,用于传入请求参数。 poll_request_times (int): 轮询请求结果次数,默认为60次。 poll_request_interval (int): 轮询请求的间隔时间(秒),默认为5秒。 Returns: Message: 模型运行后的输出消息,包含PPT下载链接。 Raises: Exception: 当输入参数中缺少必要的键时,抛出异常。 """ # 参数检查与设置 user_input = message.content for key in ['file_key']: if key not in user_input: raise Exception(f'[PPTGenerationFromPaper] Missing key: {key}') if user_input.get('pleader', '') is None or not user_input.get('pleader', '').strip(): user_input['pleader'] = DEFAULT_AUTHOR if user_input.get('advisor', '') is None or not user_input.get('advisor', '').strip(): user_input['advisor'] = DEFAULT_AUTHOR user_input = self.meta(**{k: v for k, v in user_input.items() if v is not None}) user_input = user_input.convert_params_to_dict() # 创建PPT生成任务 logger.info('Creating a PPT generation task...') job_id = self.ppt_generation(user_input) logger.info('Creating a PPT generation task succeeds.') # 查询PPT生成状态 logger.info('Generating PPT...') status = self.get_ppt_generation_status(job_id, request_times=poll_request_times, request_interval=poll_request_interval) logger.info('PPT generation task completed.') # 获取PPT下载链接 logger.info('Getting PPT download link...') ppt_download_link = self.get_ppt_download_link(job_id) logger.info('Getting PPT download link succeeds.') return Message(ppt_download_link) def tool_eval(self, stream: bool = False, **kwargs): """ 使用指定的file_key来评估并获取相应的结果。 Args: stream (bool, optional): 是否以生成器的方式逐项返回结果,默认为False。 **kwargs: 关键字参数,用于传递其他参数,目前仅支持file_key。 Returns: 如果stream为False,则直接返回结果。 如果stream为True,则逐个返回结果。 Raises: ValueError: 如果参数file_key为空,则抛出异常。 """ file_key = kwargs.get('file_key', '') if not file_key: raise ValueError('param `file_key` should not be empty.') user_input = { 'file_key': file_key } message = Message(user_input) result = self.run(message, poll_request_times=60, poll_request_interval=5) ppt_download_link = result.content if stream: yield ppt_download_link else: return ppt_download_link ================================================ FILE: python/core/components/qrcode_ocr/README.md ================================================ # 二维码识别 (QRcodeOCR) ## 简介 二维码识别 (QRcodeOCR) 可对图片中的二维码、条形码进行检测和识别,返回存储的文字信息及其位置信息。 ### 功能介绍 * 二维码识别 检测识别图片中的二维码(包括QR_CODE、DATA_MATRIX、AZTEC、PDF_417 4类),自动返回存储的内容。 * 条形码识别 检测识别图片中的条形码(包括CODE_128、UPC_A、EAN_13、ITF、CODABAR 等9类),自动返回存储的内容。 ### 特色优势 * 支持对图片中的二维码、条形码进行检测和识别,自动返回存储的内容。 ### 应用场景 * 物品信息管理 解析识别各类物品的二维码或条形码信息,应用于商品、药品出入库管理及货物运输管理等场景,轻松一扫即可快速完成对物品信息的读取、登记和存储,简化物品管理流程 ## 基本用法 下面是二维码识别的代码示例: 示例图片为: ![示例图片](https://bj.bcebos.com/v1/appbuilder/qrcode_ocr_test.png?authorization=bce-auth-v1%2FALTAKGa8m4qCUasgoljdEDAzLm%2F2024-01-24T12%3A45%3A13Z%2F-1%2Fhost%2Ffc43d07b41903aeeb5a023131ba6e74ab057ce26d50e966dc31ff083e6a9c41b) ```python import os import appbuilder import requests # 请前往千帆AppBuilder官网创建密钥,流程详见:https://cloud.baidu.com/doc/AppBuilder/s/Olq6grrt6#1%E3%80%81%E5%88%9B%E5%BB%BA%E5%AF%86%E9%92%A5 os.environ["APPBUILDER_TOKEN"] = '...' # 从BOS读取样例图片 image_url = "https://bj.bcebos.com/v1/appbuilder/qrcode_ocr_test.png?" \ "authorization=bce-auth-v1%2FALTAKGa8m4qCUasgoljdEDAzLm%2F2024-" \ "01-24T12%3A45%3A13Z%2F-1%2Fhost%2Ffc43d07b41903aeeb5a023131ba6" \ "e74ab057ce26d50e966dc31ff083e6a9c41b" raw_image = requests.get(image_url).content # 创建二维码识别组件实例 qrcode_ocr = appbuilder.QRcodeOCR() # 执行识别操作并获取结果 out = qrcode_ocr.run(appbuilder.Message(content={"raw_image": raw_image}), location="true") print(out.content) # {'codes_result': [{'type': 'QR_CODE', 'text': ['ocr文字识别'], 'location': {'top': 506, 'left': 1302, 'width': 1972, 'height': 1961}}]} ``` ## 参数说明 ### 鉴权说明 使用组件之前,请首先申请并设置鉴权参数,可参考[组件使用流程](https://cloud.baidu.com/doc/AppBuilder/s/Olq6grrt6#1%E3%80%81%E5%88%9B%E5%BB%BA%E5%AF%86%E9%92%A5)。 ```python # 设置环境中的TOKEN,以下示例略 os.environ["APPBUILDER_TOKEN"] = "bce-YOURTOKEN" ``` ### 初始化参数 无 ### 调用参数 (以表格形式展示) | 参数名称 | 参数类型 | 是否必须 | 描述 | 示例值 | |----------|---------|------|-------------------------------------------------------------------------|------------------------------------------------| | message | String | 是 | 输入的消息,用于模型的主要输入内容。这是一个必需的参数 | Message(content={"raw_image": b"待识别的图片字节流数据"}) | | location | String | 否 | 是否输出二维码/条形码位置信息,false:不返回位置信息,true:默认值,返回图中二维码/条形码的位置信息,包括上边距、左边距、宽度、高度 | "false" | |timeout| Float | 否 | HTTP超时时间,单位:秒 |1|| | retry | Integer | 否 | HTTP重试次数 | 3 | ### 响应参数 | 参数名称 | 参数类型 | 描述 | 示例值 | |--------------|----------|-------------|-------------------------------------------------------------------------------------------------------------------| | codes_result | Array[] | 返回结果 | [{'type': 'QR_CODE', 'text': ['ocr文字识别'], 'location': {'top': 506, 'left': 1302, 'width': 1972, 'height': 1961}}] | | +type | String | 识别码类型条码类型 | 'QR_CODE' | | +text | Array[] | 条形码/二维码识别内容 | ['ocr文字识别'] | | +location | Object{} | 条形码/二维码位置信息 | {'top': 506, 'left': 1302, 'width': 1972, 'height': 1961} | | ++top | Integer | 条形码/二维码的上边距 | 506 | | ++left | Integer | 条形码/二维码的左边距 | 1302 | | ++width | Integer | 条形码/二维码的宽度 | 1972 | | ++height | Integer | 条形码/二维码的高度 | 1961 | ### 响应示例 ```json { "codes_result": [ { "type": "QR_CODE", "text": ["ocr文字识别"], "location": { "top": 506, "left": 1302, "width": 1972, "height": 1961 } } ] } ``` ### 错误码 | 错误码 | 描述 | |-----|----| ## 高级用法 目前该模块仅提供基础的二维码识别功能。 ## 更新记录和贡献 * 二维码识别能力 (2024-01) ================================================ FILE: python/core/components/qrcode_ocr/__init__.py ================================================ ================================================ FILE: python/core/components/qrcode_ocr/component.py ================================================ # Copyright (c) 2023 Baidu, Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """qrcode ocr component.""" import base64 import json from appbuilder.core import utils from appbuilder.core.component import Component from appbuilder.core.components.qrcode_ocr.model import * from appbuilder.core.message import Message from appbuilder.core._client import HTTPClient from appbuilder.core._exception import AppBuilderServerException, InvalidRequestArgumentError from appbuilder.utils.trace.tracer_wrapper import components_run_trace, components_run_stream_trace class QRcodeOCR(Component): r""" 对图片中的二维码、条形码进行检测和识别,返回存储的文字信息及其位置信息。 Examples: .. code-block:: python import appbuilder # 请前往千帆AppBuilder官网创建密钥,流程详见:https://cloud.baidu.com/doc/AppBuilder/s/Olq6grrt6#1%E3%80%81%E5%88%9B%E5%BB%BA%E5%AF%86%E9%92%A5 os.environ["APPBUILDER_TOKEN"] = '...' qrcode_ocr = appbuilder.QRcodeOCR() with open("./qrcode_ocr_test.png", "rb") as f: out = self.component.run(appbuilder.Message(content={"raw_image": f.read(),"location": "true"})) print(out.content) """ name = "qrcode_ocr" version = "v1" manifests = [ { "name": "qrcode_ocr", "description": "需要对图片中的二维码、条形码进行检测和识别,返回存储的文字信息及其位置信息,使用该工具", "parameters": { "type": "object", "properties": { "file_names": { "type": "array", "items": { "type": "string" }, "description": "待识别文件的文件名" }, "location": { "type": "string", "description": "是否输出二维码/条形码位置信息" } }, "required": ["file_names"] } } ] @HTTPClient.check_param @components_run_trace def run(self, message: Message, location: str = "true", timeout: float = None, retry: int = 0) -> Message: """ 执行二维码识别操作。 Args: message (Message): 输入的图片或图片URL下载地址,用于执行识别操作。例如: Message(content={"raw_image": b"...", "location": ""}) 或 Message(content={"url": "https://image/download/url"})。 location (str, 可选): 是否需要返回二维码位置信息,默认为 "true"。 timeout (float, 可选): HTTP请求的超时时间。 retry (int, 可选): HTTP请求的重试次数。 Returns: Message: 识别结果,包含识别到的二维码信息。例如: Message(name=msg, content={'codes_result': [{'type': 'QR_CODE', 'text': ['http://weixin.qq.com/r/cS7M1PHE5qyZrbW393tj'], 'location': {'top': 63, 'left': 950, 'width': 220, 'height': 211}}, ...]}, mtype=dict) Raises: InvalidRequestArgumentError: 如果 location 参数非法,将抛出该异常。 """ inp = QRcodeInMsg(**message.content) req = QRcodeRequest() if inp.raw_image: req.image = base64.b64encode(inp.raw_image) if inp.url: req.url = inp.url if not isinstance(location, str) or location not in ('true', 'false'): raise InvalidRequestArgumentError( f"illegal location, expected location is 'true' or 'false', got {location}") req.location = location result = self._recognize(req, timeout, retry) result_dict = proto.Message.to_dict(result) out = QRcodeOutMsg(**result_dict) return Message(content=out.model_dump()) def _recognize(self, request: QRcodeRequest, timeout: float = None, retry: int = 0, request_id: str = None) -> QRcodeResponse: r"""调用二维码识别底层能力 参数: request (obj: `QRcodeRequest`) : 二维码识别输入参数 返回: response (obj: `QRcodeResponse`): 二维码识别返回结果 """ if not request.image and not request.url: raise ValueError( "request format error, one of image or url must be set") data = QRcodeRequest.to_dict(request) if self.http_client.retry.total != retry: self.http_client.retry.total = retry headers = self.http_client.auth_header(request_id) headers['content-type'] = 'application/x-www-form-urlencoded' headers['Accept'] = 'application/json' url = self.http_client.service_url("/v1/bce/aip/ocr/v1/qrcode") response = self.http_client.session.post( url, headers=headers, data=data, timeout=timeout) self.http_client.check_response_header(response) data = response.json() self.http_client.check_response_json(data) request_id = self.http_client.response_request_id(response) self.__class__._check_service_error(request_id, data) res = QRcodeResponse.from_json(json.dumps(data)) res.request_id = request_id return res @staticmethod def _check_service_error(request_id: str, data: dict): r"""个性化服务response参数检查 参数: request (dict) : 二维码识别body返回 返回: 无 """ if "error_code" in data or "error_msg" in data: raise AppBuilderServerException( request_id=request_id, service_err_code=data.get("error_code"), service_err_message=data.get("error_msg") ) @components_run_stream_trace def tool_eval(self, name: str, streaming: bool, **kwargs): """ 评估工具函数 Args: name (str): 工具名称 streaming (bool): 是否流式输出 **kwargs: 其他关键字参数 Keyword Args: traceid (str): 请求的traceid file_names (List[str]): 文件名列表 locations (str): 是否需要获取位置信息,可选值为'true'或'false',默认为'false' file_urls (Dict[str, str]): 文件名到文件URL的映射 Returns: Union[str, Generator[Dict[str, Any], None, None]]: 如果streaming为True,则返回一个生成器,生成两个字典,分别代表LLM和用户可见的内容; 如果streaming为False,则返回一个JSON字符串,包含评估结果 Raises: InvalidRequestArgumentError: 如果请求格式错误,或者位置信息不合法,则抛出该异常 """ result = {} traceid = kwargs.get("traceid") file_names = kwargs.get("file_names", None) location = kwargs.get("locations", "false") if not file_names: file_names = kwargs.get("files") file_urls = kwargs.get("file_urls", {}) for file_name in file_names: if utils.is_url(file_name): file_url = file_name else: file_url = file_urls.get(file_name, None) if file_url is None: raise InvalidRequestArgumentError( f"request format error, file {file_name} url does not exist") req = QRcodeRequest() req.url = file_url if not isinstance(location, str) or location not in ("true", "false"): raise InvalidRequestArgumentError( f"illegal location, expected location is 'true' or 'false', got {location}" ) req.location = location resp = self._recognize(req, request_id=traceid) result[file_name] = [ item["text"] for item in proto.Message.to_dict(resp).get("codes_result", []) ] result = json.dumps(result, ensure_ascii=False) if streaming: yield { "type": "text", "text": result, "visible_scope": 'llm', } yield { "type": "text", "text": "", "visible_scope": "user", } else: return result ================================================ FILE: python/core/components/qrcode_ocr/model.py ================================================ # Copyright (c) 2023 Baidu, Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """qrcode ocr model.""" import proto from typing import List from pydantic import BaseModel class QRcodeRequest(proto.Message): r"""二维码识别请求体参数. 属性: image (str): 可选。图像内容的base64编码。 url (str): 可选。图像的URL地址,经过base64编码。 图像大小必须小于4MB,图像的最短边长大于15像素,最长边长大于4096像素。 location (str): 可选。是否输出二维码/条形码位置信息 - false:默认值,不返回位置信息; - true:返回图中二维码/条形码的位置信息,包括上边距、左边距、宽度、高度 必须设置image或url属性之一,如果两者都设置了,将使用image属性。 """ image: str = proto.Field( proto.STRING, number=1, ) url: str = proto.Field( proto.STRING, number=2, ) location: str = proto.Field( proto.STRING, number=3, ) class QRcodeResponse(proto.Message): """二维码识别响应消息。 属性: request_id (str): 请求ID。 log_id (int): 用于问题识别的唯一日志ID。 codes_result_num (int):识别结果数,表示codes_result的元素个数 result (List[QRcodeRes]): 定位和识别结果数组。 """ request_id: str = proto.Field( proto.STRING, number=1, ) log_id: int = proto.Field( proto.INT64, number=2, ) codes_result_num: int = proto.Field( proto.INT32, number=3, ) codes_result: 'QRcodeRes' = proto.RepeatedField( proto.MESSAGE, number=4, message='QRcodeRes', ) class QRcodeRes(proto.Message): """二维码识别结果。 属性: type (str): 识别码类型条码类型包括:9种条形码(UPC_A、UPC_E、EAN_13、EAN_8、CODE_39、CODE_93、CODE_128、ITF、CODABAR), 4种二维码(QR_CODE、DATA_MATRIX、AZTEC、PDF_417)。 text (str): 条形码/二维码识别内容,目前仅支持输出中英文结果。 location (QRcodeLocation): 条形码/二维码位置信息,包括上边距、左边距、宽度、高度,当请求参数 location = true 时返回 """ type: str = proto.Field( proto.STRING, number=1, ) text: str = proto.RepeatedField( proto.STRING, number=2, ) location: 'QRcodeLocation' = proto.Field( proto.MESSAGE, number=3, message="QRcodeLocation", ) class QRcodeLocation(proto.Message): """条形码/二维码位置信息。 属性: top (int): 条形码/二维码的上边距。 left (int): 条形码/二维码的左边距。 width (int): 条形码/二维码的宽度。 height (int): 条形码/二维码的高度。 """ top: int = proto.Field( proto.INT32, number=1, ) left: int = proto.Field( proto.INT32, number=2, ) width: int = proto.Field( proto.INT32, number=3, ) height: int = proto.Field( proto.INT32, number=4, ) class QRcodeInMsg(BaseModel): """ 二维码识别输入消息 属性: raw_image(bytes): 图像原始内容 url(str): 图像下载链接 """ raw_image: bytes = b'' url: str = "" class QRcodeOCRLocation(BaseModel): """ 条形码/二维码位置信息 属性: top(int): 条形码/二维码的上边距 left(int): 条形码/二维码的左边距 width(int): 条形码/二维码的宽度 height(int): 条形码/二维码的高度 """ top: int left: int width: int height: int class QRcodeOCRRes(BaseModel): """ 条形码/二维码位置信息 属性: type(int): 识别码类型条码类型 text(List[str]): 条形码/二维码识别内容 location(Object): 条形码/二维码位置信息 """ type: str = "" text: List[str] location: QRcodeOCRLocation = {} class QRcodeOutMsg(BaseModel): r"""识别结果列表""" codes_result: List[QRcodeOCRRes] # 结果列表 ================================================ FILE: python/core/components/rag_with_baidu_search/README.md ================================================ # 百度搜索RAG(deprecate) ## 简介 百度搜索(BaiduSearch),通过百度搜索引擎搜索相关内容。 现推荐使用RagWithBaiduSearchPro | | 旧组件(百度搜索RAG)| 新组件(百度搜索RAG_PRO) |--------------|------------------ |------------------ | 指令 | ☑️ | ☑️ | 拒绝回答开关 | ☑️ | ❌ | 高亮开关 | ☑️ | ❌ | 友好度开关 | ☑️ | ❌ | 澄清开关 | ☑️ | ❌ | 溯源开关 | ☑️ | ☑️ | 流式请求 | ☑️ | ☑️ | temperature | ☑️ | ☑️ | top_p | ☑️ | ☑️ | 检索个数 | ❌ | ☑️ | 检索类型(网页、视频等) | ❌ | ☑️ ### 功能介绍 百度搜索是最大的中文搜索引擎,帮助用户在海量信息中找到最需要的内容。 ### 特色优势 百度搜索凭借先进的中文搜索技术、个性化推荐、全面的信息覆盖、即时的搜索结果和强大的安全防护,为用户提供快速、准确、安全的搜索体验,满足多样化的信息需求。 ### 应用场景 通用搜索领域 ## 基本用法 以下是一个简单的例子来演示如何开始使用百度搜索组件: ```python import appbuilder import os # 请前往千帆AppBuilder官网创建密钥,流程详见:https://cloud.baidu.com/doc/AppBuilder/s/Olq6grrt6#1%E3%80%81%E5%88%9B%E5%BB%BA%E5%AF%86%E9%92%A5 # 设置环境变量 os.environ["APPBUILDER_TOKEN"] = '...' # 创建rag_with_baidusearch对象 rag_with_baidusearch_component = appbuilder.RAGWithBaiduSearch(model="DeepSeek-V3.1") # 运行rag_with_baidusearch基本组件 msg = appbuilder.Message("残疾人怎么办相关证件") result = rag_with_baidusearch_component.run(msg) # 获取reference references = result.extra # 输出运行结果 print(result) ``` ## 参数说明 ### 鉴权说明 使用组件之前,请首先申请并设置鉴权参数,可参考[组件使用流程](https://cloud.baidu.com/doc/AppBuilder/s/Olq6grrt6#1%E3%80%81%E5%88%9B%E5%BB%BA%E5%AF%86%E9%92%A5)。 ```python import os os.environ["APPBUILDER_TOKEN"] = "..." ``` ### 初始化参数 - `model`: 模型名称,用于指定要使用的千帆模型。 - `instruction (obj:Message, 可选)`: 可设定人设,如:你是问答助手,在回答问题前需要加上“很高兴为您解答:” - `reject (bool, 可选)`: 拒绝开关,如果为 True,则启用该能力。默认为 False。当输入的问题在搜索结果中没有找到答案时,开关开启时,模型会用特定话术("当前文档库找不到对应的答案,我可以尝试用我的常识来回答你。")做回复的开头,并后接自有知识做回复内容。 - `clarify (bool, 可选)`: 澄清开关,如果为 True,则启用该能力。默认为 False。 当输入的问题比较模糊、或者主体指代不清晰,且context_list中包含有可以回答该模糊问题的多种潜在备选答案时,开启该开关,大模型会以特定的话术做澄清反问,引导用户继续补充问题发问。举例子,query:发电机的续航时间? Answer: 根据搜索结果得到了xx和xx两种型号的发电机,您的问题具体涉及到哪一个?请补充关键信息,作为完整的问题重新发问。 - `highlight (bool, 可选)`: 重点强调开关,如果为 True,则启用该能力。默认为 False。开启该功能时,回复结果中会高亮显示关键部分的内容。 - `friendly (bool, 可选)`: 友好性提升开关,如果为 True,则启用该能力。默认为 False。开关开启时,部分回复的开头会加礼貌用语。且如果回答涉及到大段的信息,会倾向于以<总-分>或者<总-分-总>的形式做分点论述,使得答案的格式更规整,可读性更强。 - `cite (bool, 可选)`: 溯源开关,如果为 True,则启用该能力。默认为 False。开关开启时,回复内容后会使用引用标记来标注回答内容参考的搜索结果序号,如^[1]^ (引用单个搜索结果),^[1][2]^(引用多个搜索结果)。例如:按照当地公安机关出入境管理部门规定的其他材料办理^[2]^。 ### 调用参数 调用参数中的 instruction, reject, clarify, highlight, friendly 和 cite 会覆盖初始化时的参数。 - `msg (obj:Message)`: 输入消息,包含用户提出的问题。这是一个必需的参数。 - `instruction (obj:Message, 可选)`: 可设定人设,如:你是问答助手,在回答问题前需要加上“很高兴为您解答:” - `reject (bool, 可选)`: 拒绝开关,如果为 True,则启用该能力。默认为 False。当输入的问题在搜索结果中没有找到答案时,开关开启时,模型会用特定话术("当前文档库找不到对应的答案,我可以尝试用我的常识来回答你。")做回复的开头,并后接自有知识做回复内容。 - `clarify (bool, 可选)`: 澄清开关,如果为 True,则启用该能力。默认为 False。 当输入的问题比较模糊、或者主体指代不清晰,且context_list中包含有可以回答该模糊问题的多种潜在备选答案时,开启该开关,大模型会以特定的话术做澄清反问,引导用户继续补充问题发问。举例子,query:发电机的续航时间? Answer: 根据搜索结果得到了xx和xx两种型号的发电机,您的问题具体涉及到哪一个?请补充关键信息,作为完整的问题重新发问。 - `highlight (bool, 可选)`: 重点强调开关,如果为 True,则启用该能力。默认为 False。开启该功能时,回复结果中会高亮显示关键部分的内容。 - `friendly (bool, 可选)`: 友好性提升开关,如果为 True,则启用该能力。默认为 False。开关开启时,部分回复的开头会加礼貌用语。且如果回答涉及到大段的信息,会倾向于以<总-分>或者<总-分-总>的形式做分点论述,使得答案的格式更规整,可读性更强。 - `cite (bool, 可选)`: 溯源开关,如果为 True,则启用该能力。默认为 False。开关开启时,回复内容后会使用引用标记来标注回答内容参考的搜索结果序号,如^[1]^ (引用单个搜索结果),^[1][2]^(引用多个搜索结果)。例如:按照当地公安机关出入境管理部门规定的其他材料办理^[2]^。 - `stream (bool, 可选)`: 指定是否以流式形式返回响应。默认为 False。 - `temperature (float, 可选)`: 模型配置的温度参数,用于调整模型的生成概率。取值范围为 0.0 到 1.0,其中较低的值使生成更确定性,较高的值使生成更多样性。默认值为 1e-10。 - `top_p (float, 可选)`: 模型配置的top_p参数,top_p值越高输出文本越多样,top_p值越低输出文本越稳定。取值范围为 0.0 到 1.0,默认值为 1e-10。 ### 返回值 - 返回一个 `Message` 对象,包含模型运行后的输出消息。 ## 高级用法 该组件的高级用法包括定制化的输入处理、输出处理,以及更复杂的调用场景。用户可以根据具体需求扩展组件功能,实现个性化的问答系统。 包括如下功能: 1、人设 2、拒答 3、澄清反问 4、重点强调 5、友好度提升 6、溯源 ### 代码样例 ```python import appbuilder import os # 设置环境变量 os.environ["APPBUILDER_TOKEN"] = '...' # 创建rag_with_baidusearch对象, 并初始化人设指令 rag_with_baidusearch_component = appbuilder.RAGWithBaiduSearch( model="DeepSeek-V3.1", instruction=appbuilder.Message("你是问答助手,在回答问题前需要加上: 很高兴为您解答")) # 运行rag_with_baidusearch组件,开启拒答、澄清追问、重点强调、友好性提升、溯源能力功能 msg = appbuilder.Message("残疾人怎么办相关证件") result = rag_with_baidusearch_component.run( msg, reject=True, clarify=True, highlight=True, friendly=True, cite=True, temperature=0.5, stream=False) # 输出运行结果 print(result) ``` ### 返回参数说明 返回的message中具体字段说明如下: | 字段 | 字段说明 | |---------------|--------| | name | 名称 | | mtype | 类型 | | content | 内容 | | extra | 引用 | | +search_baidu | 百度搜索结果 | | ++content | 网页内容摘要 | | ++url | 网页链接 | | ++ref_id | 序号 | | ++title | 标题 | | ++icon | 网站图标 | | ++site_name | 网站名 | ### 典型返回样例 ``` Message(name=msg, content=您好,请问您是想询问关于残疾人办理什么证件的问题吗?如果是,我可以为您提供一些信息。 首先,如果您是首次申请办理残疾人证,需要携带身份证、户口簿和三张两寸近期免冠白底彩色照片到县残联办证窗口提出申请。如果您因身体原因无法亲自前往,可以联系村(社区)工作人员代办申请。 其次,如果您是指残疾类型等级证明,您需要携带相关材料到指定医院或医生进行评级,并由医生签名盖章。 最后,如果您是指残疾人享受低保或残疾人贫困证的一级肢体、视力、智力、精神、多重及60周岁以上的一级听力、语言的重度残疾人可以享受重度残疾人生活补助,那么您需要携带身份证、户口本和残疾证申请表到县、市、区级残联进行办理。 希望这些信息对您有所帮助。如果您还有其他问题,欢迎随时提问。^[2]^, mtype=dict, extra={'search_baidu': [{'content': '(一)3张两寸近期免冠白底彩色照片。 (二)身份证、户口簿原件及复印件。 (三)申请智力、精神类残疾人证和未成年人申请残疾人证需同时提供法定监护人的身份证、户口本原件及复印件和监护人的证明材料。监护人证明材料为以下三项中任意一项: (1)能体现双方直系血缘亲属关系的户口簿。 (2)申请人所在村(社区)出具的说明双方关系的证明材料。 (3)其他能够证明其双方关系的合法证件。(法院判决书、结婚证、出生证明等) (四)经常居住地的有效居住证(户籍地不在本市申请人需提供此证件,本市户籍申请人无需提供此证件)。 (五)经常居住地残联要求的其他材料。 残疾证办理事项及流程', 'icon': 'https://ss1.baidu.com/6ONXsjip0QIZ8tyhnq/it/u=1505232404,3530227258&fm=195&app=88&f=JPEG?w=200&h=200', 'url': 'https://www.jingzhou.gov.cn/ztfwnew/shjz/cjrbl/index.shtml', 'ref_id': '1', 'site_name': '荆州市人民政府', 'title': '残疾人证办理服务'}, {'content': '{#}申请{@}. 首次申请办理残疾人证人员,需持申请人居民身份证,户口簿和3张两寸近期免冠白底彩照,到县残联办证窗口(县政务服务中心一楼1号窗口)提出办证申请,填写《中华人民共和国残疾人证申请表》.如因身体原因个人无法出行办证,可联系村(社区)工作人员代办申请.', 'icon': None, 'url': 'https://mp.weixin.qq.com/s?__biz=MzIxMzM5ODY5OQ==&mid=2247485042&idx=1&sn=26a4cad0122d24971d3f5ce598af3564&chksm=97b623b6a0c1aaa02f776c19f567e0b3fabdef3d9f5c957e1f260f286fe5356101fd1ac4e675&scene=27', 'ref_id': '2', 'site_name': '微信公众平台', 'title': '残疾人证如何办理?到哪里评定?你想知道的都在这里'}, {'content': '一、残疾人如何办残疾证 1、户口所在地的县、市、区级残联领取《残疾人证申请表》和《残疾评定表》; 2、身份证或户口本复印件一张; 3、两寸彩色相片2-6张(多带不碍事,各地标准不一); 4、残疾类型等级证明。残疾很明显的可以直接到残联进行评级(像肢体类)审核办理,不明显的必须到指定医院、指定医生进行评级签名并盖章。 一切手续完备,就到县、市、区级残联进行办理,快的话立等可取,慢的话7-15天也差不多了。 二、残疾证有什么用? 1、持有残疾证的残疾人可享受低保或持残疾人贫困证的一级肢体、视力、智力、精神、多重及60周岁以上的一级听力、语言的重度残疾人,可享受重度残疾人生活补助。 2、残疾人托(安)养方面,一级重度残疾人(不含听力、语言、视力残疾)或18至60周岁二级重度残疾人(不含听力、语言、视力残疾),集中托养:低保户、贫困户的对象补助每年补助现金按各地政策规定金额发放。', 'icon': 'https://ss0.baidu.com/6ONWsjip0QIZ8tyhnq/it/u=215799447,688541359&fm=195&app=88&f=JPEG?w=200&h=200', 'url': 'https://mip.66law.cn/laws/1060751.aspx', 'ref_id': '3', 'site_name': '华律网', 'title': '残疾人如何办残疾证-证件办理|华律办事直通车'}]}) ``` ================================================ FILE: python/core/components/rag_with_baidu_search/__init__.py ================================================ # Copyright (c) 2023 Baidu, Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from .component import RAGWithBaiduSearch ================================================ FILE: python/core/components/rag_with_baidu_search/component.py ================================================ # Copyright (c) 2023 Baidu, Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from appbuilder.core.component import ComponentArguments from appbuilder.core.components.llms.base import CompletionBaseComponent, ModelArgsConfig from appbuilder.core._exception import AppBuilderServerException from appbuilder.core.message import Message from pydantic import Field from typing import Optional from appbuilder.utils.trace.tracer_wrapper import components_run_trace from .model import RAGWithBaiduSearchArgs class RAGWithBaiduSearch(CompletionBaseComponent): name = "rag_with_baidu_search" version = "v1" meta: RAGWithBaiduSearchArgs def __init__( self, model, secret_key: Optional[str] = None, gateway: str = "", lazy_certification: bool = False, instruction: Optional[Message] = None, reject: Optional[bool] = False, clarify: Optional[bool] = False, highlight: Optional[bool] = False, friendly: Optional[bool] = False, cite: Optional[bool] = False, **kwargs ): """初始化RAG with BaiduSearch组件 Args: model (str): 模型名称,用于指定要使用的千帆模型。 secret_key (str, 可选): 用户鉴权token, 默认从环境变量中获取: os.getenv("APPBUILDER_TOKEN", ""). gateway (str, 可选): 后端网关服务地址,默认从环境变量中获取: os.getenv("GATEWAY_URL", "") lazy_certification (bool, 可选): 延迟认证,为True时在第一次运行时认证. Defaults to False. instruction (Message, 可选): 人设指令,默认为空 reject (bool, 可选): 是否开启拒绝回答开关,默认为False clarify (bool, 可选): 是否开启澄清开关,默认为False highlight (bool, 可选): 是否开启高亮开关,默认为False friendly (bool, 可选): 是否开启礼貌回答开关,默认为False cite (bool, 可选): 是否开启溯源开关,默认为False Returns: None """ super().__init__( RAGWithBaiduSearchArgs, model=model, secret_key=secret_key, gateway=gateway, lazy_certification=lazy_certification) self.instruction = instruction self.reject = reject self.clarify = clarify self.highlight = highlight self.friendly = friendly self.cite = cite @staticmethod def __get_instruction_set(): """ return: json格式的instruction_set """ return {"reject": "如果答案不在搜索结果中得到,则在答案开头说明:" "“当前文档库找不到对应的答案,我可以尝试用我的常识来回答你”," "并基于你的常识给出答案。", "clarify": "当问题比较模糊,而检索结果包含多种可能的答案时,反向提问用户想问的具体内容," "让用户补充关键信息后以完整的query重新发问。", "highlight": "可以对答案中的核心部分进行markdown加粗(**加粗内容**)。", "friendly": "答案尽量用礼貌用语开头,涉及到条目列举的内容需要在前面加序号并做分点描述," "必要时可在每一点前面做小标题的汇总,并可以用总-分-总的形式展示分点式答案内容,使得答案内容可读性更强。", "cite": "使用引用标记来标注回答内容参考的搜索结果序号,例如^[1]^ (引用单个搜索结果),^[1][2]^(引用多个搜索结果)," "其中方括号中的数字是搜索结果序号。引用标记只能出现在句尾标点符号前。" } def _get_search_input(self, text): """ 获取检索query BaiduSearch接口对query有长度要求,需要utf8编码不超过72字节 """ max_bytes = 72 encoded = text.encode('utf-8') if len(encoded) <= max_bytes: return text while max_bytes > 0: try: return encoded[:max_bytes].decode('utf-8') except UnicodeDecodeError: max_bytes -= 1 return "" @components_run_trace def run( self, message, instruction=None, reject=None, clarify=None, highlight=None, friendly=None, cite=None, stream=False, temperature=1e-10, top_p=1e-10, ): """ 执行模型推理 Args: message (Message): 用户输入的消息对象 instruction (Instruction, optional): 用户提供的指令信息,默认为None。如果未提供,则使用默认的指令信息。 reject (bool, optional): 是否拒绝执行,默认为None。如果未提供,则使用默认设置。 clarify (bool, optional): 是否需要澄清,默认为None。如果未提供,则使用默认设置。 highlight (bool, optional): 是否高亮显示,默认为None。如果未提供,则使用默认设置。 friendly (bool, optional): 是否以友好的方式回答,默认为None。如果未提供,则使用默认设置。 cite (bool, optional): 是否引用原始信息,默认为None。如果未提供,则使用默认设置。 stream (bool, optional): 是否以流式方式返回结果,默认为False。 temperature (float, optional): 温度参数,用于控制生成文本的多样性,默认为1e-10。 top_p (float, optional): 截断概率阈值,用于控制生成文本的多样性,默认为1e-10。 Returns: Message: 推理结果消息对象 Raises: AppBuilderServerException: 如果输入消息内容过长(超过72个字符)或推理结果中存在错误,则抛出异常。 """ instruction_set = self.__get_instruction_set() # query 长度限制不能超过 72 if len(message.content) > 72: raise AppBuilderServerException(service_err_message="query is too long, expected <= 72, got {}".format(len(message.content))) instruction = instruction if instruction is not None else self.instruction reject = reject if reject is not None else self.reject clarify = clarify if clarify is not None else self.clarify highlight = highlight if highlight is not None else self.highlight friendly = friendly if friendly is not None else self.friendly cite = cite if cite is not None else self.cite inputs = { "reject": instruction_set["reject"] if reject else None, "clarify": instruction_set["clarify"] if clarify else None, "highlight": instruction_set["highlight"] if highlight else None, "friendly": instruction_set["friendly"] if friendly else None, "cite": instruction_set["cite"] if cite else None, "instruction": instruction.content if instruction else None, "search_input": self._get_search_input(message.content), } model_config_inputs = ModelArgsConfig(**{"stream": stream, "temperature": temperature, "top_p": top_p}) model_config = self.get_model_config(model_config_inputs) response_mode = "streaming" if stream else "blocking" user_id = message.id request = self.gene_request(message.content, inputs, response_mode, user_id, model_config) response = self.completion(self.version, self.base_url, request) if response.error_no != 0: raise AppBuilderServerException(service_err_code=response.error_no, service_err_message=response.error_msg) return response.to_message() ================================================ FILE: python/core/components/rag_with_baidu_search/model.py ================================================ # Copyright (c) 2023 Baidu, Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from appbuilder.core.component import ComponentArguments from appbuilder.core.message import Message from pydantic import Field class RAGWithBaiduSearchArgs(ComponentArguments): """ RAG with Baidusearch提示词配置 """ message: Message = Field(..., variable_name="message", description="输入用户query,例如'千帆平台都有哪些大模型?'") reject: bool = Field(..., variable_name="reject", description="控制大模型拒答能力的开关,为true即为开启拒答功能,为false即为关闭拒答功能") clarify: bool = Field(..., variable_name="clarify", description="控制大模型澄清能力的开关,为true即为开启澄清反问功能,为false即为关闭澄清反问功能") highlight: bool = Field(..., variable_name="highlight", description="控制大模型重点强调能力的开关,为true即为开启重点强调功能,为false即为关闭重点强调功能") friendly: bool = Field(..., variable_name="friendly", description="控制大模型友好对提升难过能力的开关," "为true即为开启友好度提升功能,为false即为关闭友好度提升功能") cite: bool = Field(..., variable_name="cite", description="控制大模型溯源能力的开关,为true即为开启溯源功能,为false即为关闭溯源功能") instruction: Message = Field(..., variable_name="instruction", description="系统人设") ================================================ FILE: python/core/components/rag_with_baidu_search_pro/README.md ================================================ # 百度搜索RAG_PRO ## 简介 百度搜索RAG_PRO组件旨在解决传统生成模型在生成长文本时可能会受到信息获取不足的问题,核心思想是将百度搜索与LLM相结合,使得生成的文本可以借助检索到的信息进行增强,从而提高生成文本的质量和相关性。 ### 功能介绍 基于百度搜索结果进行RAG检索增强问答。 百度搜索RAG_PRO组件支持配置用户指令,temperature,top_p,以及溯源开关等,为用户提供了更灵活的控制选项。 对比旧版百度搜索RAG,新版百度搜索RAG_PRO在支持配置检索个数和检索类型(网页、视频等)方面进行了升级。 ### 特色优势 百度搜索RAG_PRO组件的综合优势在于通过结合百度搜索的搜索引擎技术和ERNIE模型的语义理解能力,可以更准确地理解用户的搜索意图,并提供与搜索查询相关性更高的搜索结果。 ### 应用场景 通用搜索领域 ## 基本用法 以下是一个简单的例子来演示如何开始使用百度搜索RAG_PRO组件: ```python import appbuilder import os # 请前往千帆AppBuilder官网创建密钥,流程详见:https://cloud.baidu.com/doc/AppBuilder/s/Olq6grrt6#1%E3%80%81%E5%88%9B%E5%BB%BA%E5%AF%86%E9%92%A5 # 设置环境变量 os.environ["APPBUILDER_TOKEN"] = '...' # 创建rag_with_baidusearch_pro对象 rag_with_baidu_search_pro = appbuilder.RagWithBaiduSearchPro(model="DeepSeek-V3.1") # 运行rag_with_baidusearch基本组件 msg = appbuilder.Message("残疾人怎么办相关证件") result = rag_with_baidu_search_pro.run(msg) # 获取reference references = result.extra # 输出运行结果 print(result) ``` ## 参数说明 ### 鉴权说明 使用组件之前,请首先申请并设置鉴权参数,可参考[组件使用流程](https://cloud.baidu.com/doc/AppBuilder/s/Olq6grrt6#1%E3%80%81%E5%88%9B%E5%BB%BA%E5%AF%86%E9%92%A5)。 ```python import os os.environ["APPBUILDER_TOKEN"] = "..." ``` ### 初始化参数 - `model`: 模型名称,用于指定要使用的千帆模型。 - `instruction (obj:Message, 可选)`: 可设定人设,如:你是问答助手,在回答问题前需要加上“很高兴为您解答:” ### 调用参数 调用参数中的 instruction 会覆盖初始化时的参数。 - `msg (obj:Message)`: 输入消息,包含用户提出的问题。这是一个必需的参数。 - `instruction (obj:Message, 可选)`: 可设定人设,如:你是问答助手,在回答问题前需要加上“很高兴为您解答:” - `stream (bool, 可选)`: 指定是否以流式形式返回响应。默认为 False。 - `temperature (float, 可选)`: 模型配置的温度参数,用于调整模型的生成概率。取值范围为 0.0 到 1.0,其中较低的值使生成更确定性,较高的值使生成更多样性。默认值为 1e-10。 - `top_p (float, 可选)`: 模型配置的top_p参数,top_p值越高输出文本越多样,top_p值越低输出文本越稳定。取值范围为 0.0 到 1.0,默认值为 1e-10。 - `search_top_k (int, 可选)`: 指定百度搜索返回的检索个数,最多10,默认为4。 - `hide_corner_markers (bool, 可选)`: 溯源开关,True隐藏来源,False显示来源,默认为True,不显示结果来源。 ### 返回值 - 返回一个 `Message` 对象,包含模型运行后的输出消息。 ## 高级用法 该组件的高级用法包括定制化的输入处理、输出处理,以及更复杂的调用场景。用户可以根据具体需求扩展组件功能,实现个性化的问答系统。 包括如下功能: 1、人设 2、溯源 3、百度搜索检索个数 ### 代码样例 ```python import appbuilder import os # 设置环境变量 os.environ["APPBUILDER_TOKEN"] = '...' # 创建rag_with_baidusearch对象, 并初始化人设指令 rag_with_baidusearch_pro = appbuilder.RagWithBaiduSearchPro( model="DeepSeek-V3.1", instruction=appbuilder.Message("你是问答助手,在回答问题前需要加上: 很高兴为您解答")) # 运行rag_with_baidusearch组件,开启拒答、澄清追问、重点强调、友好性提升、溯源能力功能 msg = appbuilder.Message("残疾人怎么办相关证件") result = rag_with_baidusearch_pro.run( msg, temperature=0.5, stream=False) # 输出运行结果 print(result) ``` ### 返回参数说明 返回的message中具体字段说明如下: | 字段 | 字段说明 | |---------------|--------| | name | 名称 | | mtype | 类型 | | content | 内容 | | extra | 引用 | | +search_baidu | 百度搜索结果 | | ++content | 网页内容摘要 | | ++url | 网页链接 | | ++ref_id | 序号 | | ++title | 标题 | | ++icon | 网站图标 | | ++site_name | 网站名 | ### 典型返回样例 ``` Message(name=msg, content=您好,请问您是想询问关于残疾人办理什么证件的问题吗?如果是,我可以为您提供一些信息。 首先,如果您是首次申请办理残疾人证,需要携带身份证、户口簿和三张两寸近期免冠白底彩色照片到县残联办证窗口提出申请。如果您因身体原因无法亲自前往,可以联系村(社区)工作人员代办申请。 其次,如果您是指残疾类型等级证明,您需要携带相关材料到指定医院或医生进行评级,并由医生签名盖章。 最后,如果您是指残疾人享受低保或残疾人贫困证的一级肢体、视力、智力、精神、多重及60周岁以上的一级听力、语言的重度残疾人可以享受重度残疾人生活补助,那么您需要携带身份证、户口本和残疾证申请表到县、市、区级残联进行办理。 希望这些信息对您有所帮助。如果您还有其他问题,欢迎随时提问。^[2]^, mtype=dict, extra={'search_baidu': [{'content': '(一)3张两寸近期免冠白底彩色照片。 (二)身份证、户口簿原件及复印件。 (三)申请智力、精神类残疾人证和未成年人申请残疾人证需同时提供法定监护人的身份证、户口本原件及复印件和监护人的证明材料。监护人证明材料为以下三项中任意一项: (1)能体现双方直系血缘亲属关系的户口簿。 (2)申请人所在村(社区)出具的说明双方关系的证明材料。 (3)其他能够证明其双方关系的合法证件。(法院判决书、结婚证、出生证明等) (四)经常居住地的有效居住证(户籍地不在本市申请人需提供此证件,本市户籍申请人无需提供此证件)。 (五)经常居住地残联要求的其他材料。 残疾证办理事项及流程', 'icon': 'https://ss1.baidu.com/6ONXsjip0QIZ8tyhnq/it/u=1505232404,3530227258&fm=195&app=88&f=JPEG?w=200&h=200', 'url': 'https://www.jingzhou.gov.cn/ztfwnew/shjz/cjrbl/index.shtml', 'ref_id': '1', 'site_name': '荆州市人民政府', 'title': '残疾人证办理服务'}, {'content': '{#}申请{@}. 首次申请办理残疾人证人员,需持申请人居民身份证,户口簿和3张两寸近期免冠白底彩照,到县残联办证窗口(县政务服务中心一楼1号窗口)提出办证申请,填写《中华人民共和国残疾人证申请表》.如因身体原因个人无法出行办证,可联系村(社区)工作人员代办申请.', 'icon': None, 'url': 'https://mp.weixin.qq.com/s?__biz=MzIxMzM5ODY5OQ==&mid=2247485042&idx=1&sn=26a4cad0122d24971d3f5ce598af3564&chksm=97b623b6a0c1aaa02f776c19f567e0b3fabdef3d9f5c957e1f260f286fe5356101fd1ac4e675&scene=27', 'ref_id': '2', 'site_name': '微信公众平台', 'title': '残疾人证如何办理?到哪里评定?你想知道的都在这里'}, {'content': '一、残疾人如何办残疾证 1、户口所在地的县、市、区级残联领取《残疾人证申请表》和《残疾评定表》; 2、身份证或户口本复印件一张; 3、两寸彩色相片2-6张(多带不碍事,各地标准不一); 4、残疾类型等级证明。残疾很明显的可以直接到残联进行评级(像肢体类)审核办理,不明显的必须到指定医院、指定医生进行评级签名并盖章。 一切手续完备,就到县、市、区级残联进行办理,快的话立等可取,慢的话7-15天也差不多了。 二、残疾证有什么用? 1、持有残疾证的残疾人可享受低保或持残疾人贫困证的一级肢体、视力、智力、精神、多重及60周岁以上的一级听力、语言的重度残疾人,可享受重度残疾人生活补助。 2、残疾人托(安)养方面,一级重度残疾人(不含听力、语言、视力残疾)或18至60周岁二级重度残疾人(不含听力、语言、视力残疾),集中托养:低保户、贫困户的对象补助每年补助现金按各地政策规定金额发放。', 'icon': 'https://ss0.baidu.com/6ONWsjip0QIZ8tyhnq/it/u=215799447,688541359&fm=195&app=88&f=JPEG?w=200&h=200', 'url': 'https://mip.66law.cn/laws/1060751.aspx', 'ref_id': '3', 'site_name': '华律网', 'title': '残疾人如何办残疾证-证件办理|华律办事直通车'}]}) ``` ================================================ FILE: python/core/components/rag_with_baidu_search_pro/__init__.py ================================================ # Copyright (c) 2023 Baidu, Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """ init """ from .component import RagWithBaiduSearchPro ================================================ FILE: python/core/components/rag_with_baidu_search_pro/component.py ================================================ # Copyright (c) 2024 Baidu, Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import json from typing import Optional from pydantic import Field from appbuilder.core.component import Component, ComponentArguments from appbuilder.core.message import Message from appbuilder.core.utils import ModelInfo, ttl_lru_cache from appbuilder.core._exception import AppBuilderServerException from appbuilder.core.components.rag_with_baidu_search_pro.model import ParseRagProResponse from appbuilder.utils.trace.tracer_wrapper import components_run_trace from pydantic import BaseModel, Field, conint, confloat from typing import Optional class RagWithBaiduSearchProRequest(BaseModel): """ RagWithBaiduSearchPro 的请求 Attributes: message (object): 用户的消息 stream (bool): 是否流式处理 instruction (str): 指令 model (Optional[str]): 模型名称 temperature (confloat(ge=0, le=1)): 温度,范围在0到1之间 top_p (confloat(ge=0, le=1)): top_p,范围在0到1之间 search_top_k (conint(ge=1)): search_top_k, """ message: object stream: bool = False instruction: str model: Optional[str] = None temperature: confloat(ge=0, le=1) = Field(1e-10, description="temperature范围在0到1之间") top_p: confloat(ge=0, le=1) = Field(1e-10, description="top_p范围在0到1之间") search_top_k: conint(ge=1) = Field(4, description="search_top_k必须是大于等于1的整数") hide_corner_markers: bool = True class RagWithBaiduSearchProArgs(ComponentArguments): """ RagWithBaiduSearchPro 的参数 Args: query (str): 用户的 query 输入 """ query: str = Field(..., description="用户的 query 输入", max_length=300) class RagWithBaiduSearchPro(Component): """ RagWithBaiduSearchPro 组件 """ name = "rag_with_baidu_search_pro" version = "v1" meta: RagWithBaiduSearchProArgs def __init__( self, model: str, secret_key: Optional[str] = None, gateway: str = "", lazy_certification: bool = False, instruction: Optional[Message] = None, **kwargs ): super().__init__( meta=RagWithBaiduSearchProArgs, secret_key=secret_key, gateway=gateway, lazy_certification=lazy_certification) self.model = model self.instruction = instruction self.server_sub_path = "/v1/ai_engine/copilot_engine/service/v1/baidu_search_rag/general" @ttl_lru_cache(seconds_to_live=1 * 60 * 60) # 1h def set_secret_key_and_gateway(self, secret_key: Optional[str] = None, gateway: str = ""): """ 设置API密钥和网关地址。 Args: secret_key (Optional[str], optional): API密钥,默认为None。如果为None,则不会更新现有的API密钥。 gateway (str, optional): 网关地址,默认为空字符串。如果为空字符串,则不会更新现有的网关地址。 Returns: None """ super(RagWithBaiduSearchPro, self).set_secret_key_and_gateway( secret_key=secret_key, gateway=gateway) self.__class__.model_info = ModelInfo(client=self.http_client) @components_run_trace def run( self, message, stream=False, instruction=None, model=None, temperature=1e-10, top_p=1e-10, search_top_k=4, hide_corner_markers=True ): """ 执行模型推理。 Args: message (Message): 待处理的信息对象。 stream (bool, optional): 是否以流的形式接收响应数据。默认为False。 instruction (Instruction, optional): 指令信息对象。默认为None。 model (str, optional): 模型名称。默认为None,表示使用当前实例的模型。 temperature (float, optional): 温度参数,控制生成文本的随机性。默认为1e-10。 top_p (float, optional): 累积概率阈值,用于控制生成文本的多样性。默认为1e-10。 search_top_k (int, optional): 搜索候选结果的数量。默认为4。 hide_corner_markers (bool, optional): 是否隐藏响应中的边界标记。默认为True。 Returns: Message: 处理后的信息对象。 Raises: AppBuilderServerException: 如果输入信息或指令过长,将抛出此异常。 """ if len(message.content) > 300: raise AppBuilderServerException(service_err_message="query is too long, expected <= 300, got {}" .format(len(message.content))) if instruction is not None and len(instruction.content) > 1024: raise AppBuilderServerException(service_err_message="instruction is too long, expected <= 1024, got {}" .format(len(instruction))) headers = self.http_client.auth_header() headers["Content-Type"] = "application/json" req = RagWithBaiduSearchProRequest( message=[ { "role": "user", "content": message.content } ], stream=stream, instruction=instruction.content if instruction else "", model=self.model, temperature=temperature, top_p=top_p, search_top_k=search_top_k, hide_corner_markers=hide_corner_markers ) server_url = self.http_client.service_url(sub_path=self.server_sub_path) response = self.http_client.session.post(url=server_url, headers=headers, json=req.model_dump(), stream=stream) self.http_client.check_response_header(response) return ParseRagProResponse(response, stream).to_message() ================================================ FILE: python/core/components/rag_with_baidu_search_pro/model.py ================================================ # Copyright (c) 2024 Baidu, Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from appbuilder.core._exception import AppBuilderServerException from appbuilder.utils.sse_util import SSEClient from appbuilder.core.components.llms.base import CompletionResponse class ParseRagProResponse(CompletionResponse): def __init__(self, response, stream: bool = False): """初始化客户端状态。""" super().__init__(response, stream) self.error_no = 0 self.error_msg = "" self.log_id = response.headers.get("X-Appbuilder-Request-Id", None) self.extra = {} self.token_usage = {} if stream: # 流式数据处理 def stream_data(): sse_client = SSEClient(response) for event in sse_client.events(): if not event: continue answer = self.parse_stream_data(event) if answer is not None: yield answer self.result = stream_data() else: # 非流式数据的处理 if response.status_code != 200: self.error_no = response.status_code self.error_msg = "error" self.result = response.text raise AppBuilderServerException(self.log_id, self.error_no, self.result) else: data = response.json() if "code" in data and "message" in data and "requestId" in data: raise AppBuilderServerException(self.log_id, data["code"], data["message"]) if "code" in data and "message" in data and "status" in data: raise AppBuilderServerException(self.log_id, data["code"], data["message"]) res = data["result"] answer_message = res.get("answer_message") self.result = answer_message.get("content") self.token_usage = answer_message.get("token_usage", {}) # 拼装百度搜索的结果 extra = answer_message.get("extra") search_baidu_list = [] for item in extra: search_baidu_list.append({ "content": item.get("content"), "icon": item.get("icon"), "url": item.get("url"), "ref_id": item.get("ref_num"), "site_name": item.get("web_anchor"), "title": item.get("title") }) self.extra = { "search_baidu": search_baidu_list } def message_iterable_wrapper(self, message): """ 对模型输出的 Message 对象进行包装。 当 Message 是流式数据时,数据被迭代完后,将重新更新 content 为 blocking 的字符串。 """ class IterableWrapper: def __init__(self, stream_content): self._content = stream_content self._concat = "" self._token_usage = {} def __iter__(self): return self def __next__(self): try: result_json = next(self._content) res = result_json["result"] answer_message = res.get("answer_message") char = answer_message.get("content", "") extra = answer_message.get("extra") if extra is not None: search_baidu_list = [] for item in extra: search_baidu_list.append({ "content": item.get("content"), "icon": item.get("icon"), "url": item.get("url"), "ref_id": item.get("ref_num"), "site_name": item.get("web_anchor"), "title": item.get("title") }) message.extra = { "search_baidu": search_baidu_list } else: message.extra = {} if "token_usage" in answer_message: self._token_usage = answer_message.get("token_usage") message.token_usage = self._token_usage self._concat += char return char except StopIteration: message.content = self._concat # Update the original content raise from collections.abc import Generator if isinstance(message.content, Generator): # Replace the original content with the custom iterable message.content = IterableWrapper(message.content) return message ================================================ FILE: python/core/components/retriever/README.md ================================================ # 向量检索 ## 简介 Appbuilder提供多种向量数据库作为向量检索的底座,当前主要支持百度向量数据库、百度 ElasticSearch。 ### 功能介绍 `向量检索-VDB`组件(Baidu VDB Retriever)以百度向量数据库作为向量存储和检索的底座。百度向量数据库是一个专注于多维向量数据的存储、检索和分析的企业级分布式数据库服务。基于百度自主研发的向量数据库内核,VectorDB在保证高性能和高可用性的同时,也特别注重易用性和可扩展性。它支持多种索引类型和相似度计算方法,能够满足各类复杂和多样化的数据应用需求。特别值得一提的是,VectorDB能够管理高达数十亿的向量规模,同时保持毫秒级的查询响应时间,非常适合进行大规模的向量检索和分析任务。 `向量检索-BES`组件(Baidu ElasticSearch Retriever)以百度 ElasticSearch作为向量存储和检索的底座。百度 ElasticSearch是一款专为企业级需求设计的分布式搜索和分析服务,它在全面兼容开源ElasticSearch的基础上,提供了更多增强功能。这款服务的核心优势在于其高性能和高可靠性,它为处理结构化和非结构化数据提供了一个低成本且高效的平台。对于关注数据安全的客户来说,百度ElasticSearch提供了先进的权限管理机制,使得您可以根据业务需求自由地配置集群权限。 ================================================ FILE: python/core/components/retriever/__init__.py ================================================ # Copyright (c) 2023 Baidu, Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from .bes import BESVectorStoreIndex from .bes import BESRetriever from .baidu_vdb import BaiduVDBVectorStoreIndex from .baidu_vdb import BaiduVDBRetriever from .baidu_vdb import TableParams ================================================ FILE: python/core/components/retriever/baidu_vdb/README.md ================================================ # 向量检索-VectorDB(BaiduVectorDBRetriever) ## 简介 向量检索-VectorDB(BaiduVectorDBRetriever)基于一款百度向量数据库的内容检索组件,支持根据文本的向量的相似度进行内容检索。 ### 功能介绍 向量检索-VectorDB(BaiduVectorDBRetriever)用于在将文本内容输入到百度向量数据库,根据文本的向量相似度进行高效的内容检索。 ### 特色优势 高效准确:基于百度向量数据库的强大能力,提供高效且准确的内容检索功能。 ### 应用场景 各种内容检索场景 ## 准备工作 在使用向量检索-VectorDB(BaiduVectorDBRetriever)进行内容检索之前,需要到百度向量数据库官网创建相应的实例,[教程](https://cloud.baidu.com/doc/VDB/s/hlrsoazuf)。 ## 基本用法 以下是有关如何开始使用向量检索-VectorDB(BaiduVectorDBRetriever)的代码示例: 补充说明: - `you_vdb_instance_id` 为VectorDB 实例ID,请替换为您的实例ID,在VectorDB控制台界面上可以查看 - `your_api_key` 为您在VectorDB上申请的账户密钥,请替换为您自己的root账户密钥,在VectorDB控制台界面上可以查看 ```python import os import appbuilder # 请前往千帆AppBuilder官网创建密钥,流程详见:https://cloud.baidu.com/doc/AppBuilder/s/Olq6grrt6#1%E3%80%81%E5%88%9B%E5%BB%BA%E5%AF%86%E9%92%A5 os.environ["APPBUILDER_TOKEN"] = '...' segments = appbuilder.Message(["文心一言大模型", "百度在线科技有限公司"]) # 初始化构建索引 vector_index = appbuilder.BaiduVDBVectorStoreIndex.from_params( instance_id=your_instance_id, api_key=your_api_key, drop_exists=True, ) vector_index.add_segments(segments) query = appbuilder.Message("文心一言") retriever = vector_index.as_retriever() res = retriever(query) print(res) ``` ## 参数说明 ### 鉴权说明 使用组件之前,请首先申请并设置鉴权参数,可参考[组件使用流程](https://cloud.baidu.com/doc/AppBuilder/s/Olq6grrt6#1%E3%80%81%E5%88%9B%E5%BB%BA%E5%AF%86%E9%92%A5)。 ```python # 设置环境中的TOKEN,以下示例略 os.environ["APPBUILDER_TOKEN"] = "bce-YOURTOKEN" ``` ### 初始化参数说明: `BaiduVDBVectorStoreIndex()` 实例化参数说明: - instance_id(str,必填):百度向量数据库的实例id,创建实例时获取 - api_key (str,必填):连接向量数据库所需的密码,创建实例时获取 - account (str,非必填):连接向量数据库所需的用户名,默认root - database_name (str,非必填) :向量数据库的名称,默认为AppBuilderDatabase - table_params (TableParams,非必填) :VectorDB table参数,参考链接[VectorDB table params](https://cloud.baidu.com/doc/VDB/s/mlrsob0p6) - embedding (Embedding,非必填) :appbuilder.Embedding类型,若有构造好的Embedding,可以增量插入,否则默认新建embedding ------- `BaiduVDBVectorStoreIndex().from_params()` 构造函数参数说明: - instance_id(str,必填):百度向量数据库的实例id,创建实例时获取 - api_key (str,必填):连接向量数据库所需的密码,创建实例时获取 - account (str,非必填):连接向量数据库所需的用户名,默认root - database_name (str,非必填) :向量数据库的名称,默认为AppBuilderDatabase - table_name (str,非必填) :向量数据库的表名,默认为AppBuilderTable - drop_exists (bool, 非必填) :是否清空数据库历史记录,默认为False ------- ### 调用参数: `BaiduVDBRetriever().run()` 函数参数说明: | 参数名称 | 参数类型 |是否必须 | 描述 | 示例值 | |---------|--------|--------|------------------|---------------| | message | String |是 | 需要检索的内容, 类型为Message,content类型为str, 长度要求(0,512) | "中国2023人均GDP" | | top_k | int |否 | 返回相似度最高的top_k个内容,top_k的数值范围(1,embedding索引数量] | 1 | ### 响应参数 `BaiduVDBRetriever().run()` 函数返回值说明: | 参数名称 | 参数类型 | 描述 | 示例值 | |------|--------|-----|--------------------| | text | string | 检索结果 | "中国2023年人均GDP8.94万元" | | score | float | 相似度 | 0.95 | | meta | dict | 元信息 | "" | ### 响应示例 ```json {"text": "中国2023年人均GDP8.94万元", "score": 0.95, "meta": ""} ``` ## 高级用法: 本组件根据向量的相似度进行检索,支持使用不同的embedding方法和索引方式来优化检索的效果。 ## 更新记录和贡献 * 向量检索能力 (2024-03) ================================================ FILE: python/core/components/retriever/baidu_vdb/__init__.py ================================================ # Copyright (c) 2023 Baidu, Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from .component import BaiduVDBVectorStoreIndex from .component import BaiduVDBRetriever from .component import TableParams ================================================ FILE: python/core/components/retriever/baidu_vdb/component.py ================================================ # Copyright (c) 2023 Baidu, Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # -*- coding: utf-8 -*- """ 基于Baidu VDB的retriever """ import os import time from typing import Dict, Any from appbuilder.core.component import Component, Message from appbuilder.core.components.embeddings.component import Embedding from appbuilder.core.constants import GATEWAY_URL from appbuilder.utils.trace.tracer_wrapper import components_run_trace, components_run_stream_trace from .model import * def _try_import() -> None: try: import pymochow except ImportError: raise ImportError( "pymochow module is not installed. " "Please install it using 'pip install pymochow'." ) class TableParams: """ Baidu VectorDB table params. See the following documentation for details: https://cloud.baidu.com/doc/VDB/s/mlrsob0p6 Args: dimension int: The dimension of vector. replication int: The number of replicas in the table. partition int: The number of partitions in the table. index_type (Optional[str]): HNSW, FLAT... Default value is "HNSW" metric_type (Optional[str]): L2, COSINE, IP. Default value is "L2" drop_exists (Optional[bool]): Delete the existing Table. Default value is False. vector_params (Optional[Dict]): if HNSW set parameters: `M` and `efConstruction`, for example `{'M': 16, efConstruction: 200}` default is HNSW """ def __init__( self, dimension: int, table_name: str = DEFAULT_TABLE_NAME, replication: int = DEFAULT_REPLICA, partition: int = DEFAULT_PARTITION, index_type: str = DEFAULT_INDEX_TYPE, metric_type: str = DEFAULT_METRIC_TYPE, drop_exists: bool = False, vector_params: Dict = None, ): self.dimension = dimension self.table_name = table_name self.replication = replication self.partition = partition self.index_type = index_type self.metric_type = metric_type self.drop_exists = drop_exists self.vector_params = vector_params class BaiduVDBVectorStoreIndex: """ Baidu VDB向量存储检索工具 """ vdb_uri_prefix = b"/api/v1/bce/vdb/instance/" def __init__( self, instance_id: str, api_key: str, account: str = DEFAULT_ACCOUNT, database_name: str = DEFAULT_DATABASE_NAME, table_params: TableParams = TableParams(dimension=384), embedding=None, ): if not isinstance(instance_id, str): raise TypeError( "Parameter `instance_id` must be a string, but got {}".format( type(instance_id))) if not isinstance(api_key, str): raise TypeError( "Parameter `api_key` must be a string, but got {}".format( type(api_key))) if not isinstance(account, str): raise TypeError( "Parameter `account` must be a string, but got {}".format( type(account))) if not isinstance(database_name, str): raise TypeError( "Parameter `database_name` must be a string, but got {}".format( type(database_name))) if not isinstance(table_params, TableParams): raise TypeError( "Parameter `table_params` must be a TableParams, but got {}".format( type(table_params))) if embedding is not None and not isinstance(embedding, Embedding): raise TypeError( "Parameter `embedding` must be a Embedding, but got {}".format( type(embedding))) if embedding is None: embedding = Embedding() self.embedding = embedding self._init_client(instance_id, account, api_key) self._create_database_if_not_exists(database_name) self._create_table(table_params) def _init_client(self, instance_id, account, api_key): """ 创建一个vdb的client """ import pymochow from pymochow.configuration import Configuration from pymochow.auth.bce_credentials import AppBuilderCredentials gateway = os.getenv("GATEWAY_URL") if os.getenv( "GATEWAY_URL") else GATEWAY_URL appbuilder_token = os.getenv("APPBUILDER_TOKEN") uri_prefix = self.vdb_uri_prefix + instance_id.encode('utf-8') config = Configuration( credentials=AppBuilderCredentials( account, api_key, appbuilder_token), endpoint=gateway, uri_prefix=uri_prefix, connection_timeout_in_mills=DEFAULT_TIMEOUT_IN_MILLS, ) self.vdb_client = pymochow.MochowClient(config) def _create_database_if_not_exists(self, database_name: str) -> None: db_list = self.vdb_client.list_databases() if database_name in [db.database_name for db in db_list]: self.database = self.vdb_client.database(database_name) else: self.database = self.vdb_client.create_database(database_name) def _create_table(self, table_params: TableParams) -> None: import pymochow if table_params is None: raise ValueError(VALUE_NONE_ERROR.format("table_params")) try: self.table = self.database.describe_table(table_params.table_name) if table_params.drop_exists: self.database.drop_table(table_params.table_name) # wait db release resource time.sleep(5) self._create_table_in_db(table_params) except pymochow.exception.ServerError: self._create_table_in_db(table_params) def _create_table_in_db( self, table_params: TableParams, ) -> None: from pymochow.model.enum import FieldType from pymochow.model.schema import Field, Schema, SecondaryIndex, VectorIndex from pymochow.model.table import Partition index_type = self._get_index_type(table_params.index_type) metric_type = self._get_metric_type(table_params.metric_type) vector_params = self._get_index_params(index_type, table_params) fields = [] fields.append( Field( FIELD_ID, FieldType.UINT64, primary_key=True, partition_key=True, auto_increment=True, not_null=True, ) ) fields.append(Field(FIELD_METADATA, FieldType.STRING)) fields.append(Field(FIELD_TEXT, FieldType.STRING)) fields.append( Field( FIELD_VECTOR, FieldType.FLOAT_VECTOR, dimension=table_params.dimension, not_null=True, ) ) indexes = [] indexes.append( VectorIndex( index_name=INDEX_VECTOR, index_type=index_type, field=FIELD_VECTOR, metric_type=metric_type, params=vector_params, ) ) schema = Schema(fields=fields, indexes=indexes) self.table = self.database.create_table( table_name=table_params.table_name, replication=table_params.replication, partition=Partition(partition_num=table_params.partition), schema=Schema(fields=fields, indexes=indexes), enable_dynamic_field=True, ) # need wait 10s to wait proxy sync meta time.sleep(10) @staticmethod def _get_index_params(index_type: Any, table_params: TableParams) -> None: from pymochow.model.enum import IndexType from pymochow.model.schema import HNSWParams vector_params = ( {} if table_params.vector_params is None else table_params.vector_params ) if index_type == IndexType.HNSW: return HNSWParams( m=vector_params.get("M", DEFAULT_HNSW_M), efconstruction=vector_params.get( "efConstruction", DEFAULT_HNSW_EF_CONSTRUCTION ), ) return None @staticmethod def _get_index_type(index_type_value: str) -> Any: from pymochow.model.enum import IndexType index_type_value = index_type_value or IndexType.HNSW try: return IndexType(index_type_value) except ValueError: support_index_types = [ d.value for d in IndexType.__members__.values()] raise ValueError( NOT_SUPPORT_INDEX_TYPE_ERROR.format( index_type_value, support_index_types ) ) @staticmethod def _get_metric_type(metric_type_value: str) -> Any: from pymochow.model.enum import MetricType metric_type_value = metric_type_value or MetricType.L2 try: return MetricType(metric_type_value.upper()) except ValueError: support_metric_types = [ d.value for d in MetricType.__members__.values()] raise ValueError( NOT_SUPPORT_METRIC_TYPE_ERROR.format( metric_type_value, support_metric_types ) ) @property def client(self) -> Any: """ 获取客户端对象。 Args: 无参数 Returns: Any: 返回客户端对象,具体类型依赖于vdb_client属性的值。 """ return self.vdb_client def as_retriever(self): """ 将对象转化为retriever Args: 无 Returns: BaiduVDBRetriever: 转化后的retriever对象 """ return BaiduVDBRetriever( embedding=self.embedding, table=self.table, ) def add_segments(self, segments: Message, metadata=""): """ 向bes中插入数据段 Args: segments (Message): 需要插入的数据段。 metadata (str, optional): 元数据,默认为空字符串。 Returns: 无返回值 Raises: ValueError: 如果segments为空,则抛出此异常。 """ from pymochow.model.table import Row segment_vectors = self.embedding.batch(segments) segment_vectors = segment_vectors.content vector_dims = len(segment_vectors[0]) segments = segments.content if len(segments) == 0: raise ValueError("segments is emtpty") rows = [] for segment, vector in zip(segments, segment_vectors): row = Row(text=segment, vector=vector, metadata=metadata) rows.append(row) if len(rows) >= DEFAULT_BATCH_SIZE: self.collection.upsert(rows=rows) rows = [] if len(rows) > 0: self.table.upsert(rows=rows) @classmethod def from_params( cls, instance_id: str, api_key: str, account: str = DEFAULT_ACCOUNT, database_name: str = DEFAULT_DATABASE_NAME, table_name: str = DEFAULT_TABLE_NAME, drop_exists: bool = False, **kwargs, ): """ 从参数中实例化类。 Args: cls (type): 类对象,即当前函数所属的类。 instance_id (str): 实例ID。 api_key (str): API密钥。 account (str, optional): 账户名,默认为'root'。 Defaults to DEFAULT_ACCOUNT. database_name (str, optional): 数据库名,默认为'AppBuilderDatabase'。 Defaults to DEFAULT_DATABASE_NAME. table_name (str, optional): 表名,默认为'AppBuilderTable'。 Defaults to DEFAULT_TABLE_NAME. drop_exists (bool, optional): 是否删除已存在的表,默认为False。 Defaults to False. **kwargs: 其他参数,可选的维度参数dimension默认为384。 Returns: cls: 类实例,包含实例ID、账户名、API密钥、数据库名、表参数等属性。 """ _try_import() dimension = kwargs.get("dimension", 384) if not isinstance(instance_id, str): raise TypeError("instance_id must be a string. but got {}".format( type(instance_id))) if not isinstance(api_key, str): raise TypeError("api_key must be a string. but got {}".format( type(api_key))) if not isinstance(account, str): raise TypeError("account must be a string. but got {}".format( type(account))) if not isinstance(database_name, str): raise TypeError("database_name must be a string. but got {}".format( type(database_name))) if not isinstance(table_name, str): raise TypeError("table_name must be a string. but got {}".format( type(table_name))) if not isinstance(drop_exists, bool): raise TypeError("drop_exists must be a boolean. but got {}".format( type(drop_exists))) table_params = TableParams( dimension=dimension, table_name=table_name, drop_exists=drop_exists, ) return cls( instance_id=instance_id, account=account, api_key=api_key, database_name=database_name, table_params=table_params, ) class BaiduVDBRetriever(Component): """ 向量检索组件,用于检索和query相匹配的内容 Examples: .. code-block:: python import appbuilder os.environ["APPBUILDER_TOKEN"] = '...' segments = appbuilder.Message(["文心一言大模型", "百度在线科技有限公司"]) vector_index = appbuilder.BaiduVDBVectorStoreIndex.from_params( self.instance_id, self.api_key, ) vector_index.add_segments(segments) query = appbuilder.Message("文心一言") time.sleep(5) retriever = vector_index.as_retriever() res = retriever(query) """ name: str = "BaiduVectorDBRetriever" tool_desc: Dict[str, Any] = { "description": "a retriever based on Baidu VectorDB"} def __init__(self, embedding, table, **kwargs ): super().__init__() self.embedding = embedding self.table = table @components_run_trace def run(self, query: Message, top_k: int = 1): """ 根据query进行查询 Args: query (Message[str]): 需要查询的内容,类型为Message,包含要查询的文本。 top_k (int, optional): 查询结果中匹配度最高的top_k个结果,默认为1。 Returns: Message[Dict]: 查询到的结果,包含文本和匹配得分。 Raises: TypeError: 如果query不是Message类型,或者top_k不是整数类型。 ValueError: 如果top_k不是正整数,或者query的内容为空字符串,或者长度超过512个字符。 """ from pymochow.model.table import AnnSearch, HNSWSearchParams from pymochow.model.enum import ReadConsistency if not isinstance(query, Message): raise TypeError("Parameter `query` must be a Message, but got {}" .format(type(query))) if not isinstance(top_k, int): raise TypeError("Parameter `top_k` must be a int, but got {}" .format(type(top_k))) if top_k <= 0: raise ValueError("Parameter `top_k` must be a positive integer, but got {}" .format(top_k)) content = query.content if not isinstance(content, str): raise ValueError("Parameter `query` content is not a string, got: {}" .format(type(content))) if len(content) == 0: raise ValueError("Parameter `query` content is empty") if len(content) > 512: raise ValueError( "Parameter `query` content is too long, max length per batch size is 512") query_embedding = self.embedding(query) anns = AnnSearch( vector_field=FIELD_VECTOR, vector_floats=query_embedding.content, params=HNSWSearchParams(ef=10, limit=top_k), ) res = self.table.search( anns=anns, read_consistency=ReadConsistency.STRONG) rows = res.rows docs = [] if rows is None or len(rows) == 0: return Message(docs) for row in rows: row_data = row.get("row", {}) docs.append({ "text": row_data.get(FIELD_TEXT), "meta": row_data.get(FIELD_METADATA), "score": row.get("score") }) return Message(docs) ================================================ FILE: python/core/components/retriever/baidu_vdb/model.py ================================================ # Copyright (c) 2023 Baidu, Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # -*- coding: utf-8 -*- """ 基于Baidu VDB的retriever """ import os import time from typing import Dict, Any from appbuilder.core.component import Message from appbuilder.core.components.embeddings.component import Embedding from appbuilder.core.constants import GATEWAY_URL DEFAULT_ACCOUNT = "root" DEFAULT_DATABASE_NAME = "AppBuilderDatabase" DEFAULT_TABLE_NAME = "AppBuilderTable" DEFAULT_TIMEOUT_IN_MILLS: int = 30 * 1000 DEFAULT_PARTITION = 1 DEFAULT_REPLICA = 3 DEFAULT_INDEX_TYPE = "HNSW" DEFAULT_METRIC_TYPE = "L2" DEFAULT_HNSW_M = 16 DEFAULT_HNSW_EF_CONSTRUCTION = 200 DEFAULT_HNSW_EF = 10 DEFAULT_BATCH_SIZE = 1000 FIELD_ID: str = "id" FIELD_TEXT: str = "text" FIELD_VECTOR: str = "vector" FIELD_METADATA: str = "metadata" INDEX_VECTOR: str = "vector_idx" VALUE_NONE_ERROR = "Parameter `{}` can not be None." NOT_SUPPORT_INDEX_TYPE_ERROR = ( "Unsupported index type: `{}`, supported index types are {}" ) NOT_SUPPORT_METRIC_TYPE_ERROR = ( "Unsupported metric type: `{}`, supported metric types are {}" ) ================================================ FILE: python/core/components/retriever/bes/README.md ================================================ # 向量检索-BES(BaiduElasticSearchRetriever) ## 简介 向量检索-BES组件(BaiduElasticSearchRetriever)基于一款Baidu ElasticSearch的内容检索组件,支持根据文本的向量的相似度进行内容检索。 ### 功能介绍 向量检索-BES组件(BaiduElasticSearchRetriever)用于在将文本内容输入到Baidu ElasticSearch,根据文本的向量相似度进行高效的内容检索。 ### 特色优势 - 高效准确:基于Baidu ElasticSearch的强大能力,提供高效且准确的内容检索功能。 ### 应用场景 各种内容检索场景 ## 准备工作 在使用BaiduElasticSearchRetriever进行内容检索之前,需要到Baidu ElasticSearch官网创建相应的集群,详情见[教程](https://cloud.baidu.com/doc/BES/s/gke3ocf89)。 注:创建集群时请选择7.10.2版本的ES,否则可能无法使用本组件。 ## 基本用法 以下是有关如何开始使用BESRetriever的代码示例: ```python import os import appbuilder # 请前往千帆AppBuilder官网创建密钥,流程详见:https://cloud.baidu.com/doc/AppBuilder/s/Olq6grrt6#1%E3%80%81%E5%88%9B%E5%BB%BA%E5%AF%86%E9%92%A5 os.environ["APPBUILDER_TOKEN"] = '...' embedding = appbuilder.Embedding() segments = appbuilder.Message(["文心一言大模型", "百度在线科技有限公司"]) # 初始化构建索引 vector_index = appbuilder.BESVectorStoreIndex.from_segments(segments=segments, cluster_id=es_cluster_id, user_name=es_username, password=es_password, embedding=embedding) # 获取当前索引中的全部内容 all_content = vector_index.get_all_segments() print(all_content) # 转化为retriever retriever = vector_index.as_retriever() # 按照query进行检索 query = appbuilder.Message("文心一言") res = retriever(query=query, top_k=1) print(res) # 删除当前索引中的全部内容 vector_index.delete_all_segments() ``` ## 参数说明 ### 鉴权说明 使用组件之前,请首先申请并设置鉴权参数,可参考[组件使用流程](https://cloud.baidu.com/doc/AppBuilder/s/Olq6grrt6#1%E3%80%81%E5%88%9B%E5%BB%BA%E5%AF%86%E9%92%A5)。 ```python # 设置环境中的TOKEN,以下示例略 os.environ["APPBUILDER_TOKEN"] = "bce-YOURTOKEN" ``` ### 初始化参数说明: - segments (Message[List[str]],必填):需要入库的文本段落 - cluster_id (str,必填):ElacticSearch集群的id,创建集群时获取 - user_name (str,必填):连接ES集群所需的用户名,创建集群时获取 - password (str,必填):连接ES集群所需的密码,创建集群时获取 - embedding (obj,非必填):用于将文本转为向量的模型,默认为Embedding ### 调用参数: | 参数名称 | 参数类型 |是否必须 | 描述 | 示例值 | |---------|--------|--------|------------------|---------------| | message | String |是 | 需要检索的内容 | "中国2023人均GDP" | | top_k | int |否 | 返回相似度最高的top_k个内容 | 1 | ### 响应参数 | 参数名称 | 参数类型 | 描述 | 示例值 | |------|--------|-----|--------------------| | text | string | 检索结果 | "中国2023年人均GDP8.94万元" | | score | float | 相似度 | 0.95 | | meta | dict | 元信息 | "" | ### 响应示例 ```json {"text": "中国2023年人均GDP8.94万元", "score": 0.95, "meta": ""} ``` ## 高级用法: 本组件根据向量的相似度进行检索,支持使用不同的embedding方法和索引方式来优化检索的效果。 ## 更新记录和贡献 * 向量检索能力 (2023-12) ================================================ FILE: python/core/components/retriever/bes/__init__.py ================================================ # Copyright (c) 2023 Baidu, Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from .component import BESVectorStoreIndex from .component import BESRetriever ================================================ FILE: python/core/components/retriever/bes/component.py ================================================ # Copyright (c) 2023 Baidu, Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # -*- coding: utf-8 -*- """ 基于baidu ES的retriever """ import importlib import os import uuid import random import string from typing import Dict, Any from appbuilder.core.component import Component, Message from appbuilder.core.components.embeddings.component import Embedding from appbuilder.core.constants import GATEWAY_URL from appbuilder.utils.logger_util import logger from appbuilder import get_default_header from appbuilder.utils.trace.tracer_wrapper import components_run_trace, components_run_stream_trace class BESVectorStoreIndex: """ BES向量存储检索工具 """ base_es_url: str = "/v1/bce/bes/cluster/" def __init__(self, cluster_id, user_name, password, embedding=None, index_name=None, index_type="hnsw", prefix="/rpc/2.0/cloud_hub"): if embedding is None: embedding = Embedding() self.embedding = embedding self.index_name = index_name if index_name else BESVectorStoreIndex.generate_id() self.index_type = index_type self.prefix = prefix self._es = None self._helpers = None self.bes_client = self._create_bes_client(cluster_id, user_name, password) @property def es(self): """ 获取Elasticsearch客户端实例。 Args: 无 Returns: Elasticsearch客户端实例。 """ self._lazy_import_es() return self._es @property def helpers(self): """ 获取帮助器实例。 Args: 无 Returns: _helpers (对象): 帮助器实例。 """ self._lazy_import_es() return self._helpers def _lazy_import_es(self): if self._es is None or self._helpers is None: try: from elasticsearch import Elasticsearch, helpers self._es = Elasticsearch self._helpers = helpers except ImportError: raise ImportError("Elasticsearch module is not installed. " "Please install it using 'pip install elasticsearch==7.11.0'.") @staticmethod def generate_id(length=16): """ 生成随机的ID。 Args: length (int, optional): 生成ID的长度,默认为16。 Returns: str: 生成的随机ID。 """ return ''.join(random.choices(string.ascii_lowercase + string.digits, k=length)) def _create_bes_client(self, cluster_id, user_name, password): """ 创建一个BES客户端。 Args: cluster_id (str): BES集群的ID。 user_name (str): 用于连接BES的用户名。 password (str): 用于连接BES的密码。 Returns: Elasticsearch: 初始化好的BES客户端。 Raises: ConnectionError: 如果无法连接到BES集群,则抛出此异常。 """ secret_key = os.getenv("APPBUILDER_TOKEN") if not secret_key.startswith("Bearer"): secret_key = "Bearer {}".format(secret_key) gateway = os.getenv("GATEWAY_URL") if os.getenv("GATEWAY_URL") else GATEWAY_URL headers = get_default_header() headers["X-Appbuilder-Request-Id"] = str(uuid.uuid4()) headers["X-Appbuilder-Authorization"] = f"{secret_key}" connection_params = { "hosts": [gateway + self.prefix + self.base_es_url + cluster_id], "http_auth": (user_name, password), "headers": headers } bes_client = self.es(**connection_params) try: bes_client.info() except Exception as e: logger.error("connecting to bes error: {}".format(e)) raise ConnectionError(e) return bes_client def as_retriever(self): """ 将当前对象转化为retriever。 Args: 无 Returns: BESRetriever: 转化后的retriever对象 """ return BESRetriever(embedding=self.embedding, index_name=self.index_name, bes_client=self.bes_client, index_type=self.index_type) @staticmethod def create_index_mappings(index_type, vector_dims): """ 创建索引的mapping Args: index_type (str): 索引类型,如"hnsw" vector_dims (int): 向量的维度 Returns: dict: 索引的mapping配置 """ mappings = { 'properties': { "vector": { "type": "bpack_vector", "dims": vector_dims, }, } } if index_type == "hnsw": mappings["properties"]["vector"]["index_type"] = "hnsw" mappings["properties"]["vector"]["space_type"] = "cosine" mappings["properties"]["vector"]["parameters"] = {"m": 4, "ef_construction": 200} return mappings def add_segments(self, segments: Message, metadata=""): """ 向BES中插入数据 Args: segments (Message[str]): 需要插入的内容,包含多个文本段 metadata (str, optional): 元数据,默认为空字符串。 Returns: 无返回值 """ segment_vectors = self.embedding.batch(segments) segment_vectors = segment_vectors.content vector_dims = len(segment_vectors[0]) segments = segments.content documents = [ {"_index": self.index_name, "_source": {"text": segment, "vector": vector, "metadata": metadata, "id": BESVectorStoreIndex.generate_id()}} for segment, vector in zip(segments, segment_vectors)] mappings = BESVectorStoreIndex.create_index_mappings(self.index_type, vector_dims) self.bes_client.indices.create(index=self.index_name, body={"settings": {"index": {"knn": True}}, "mappings": mappings}) self.helpers.bulk(self.bes_client, documents) @classmethod def from_segments(cls, segments, cluster_id, user_name, password, embedding=None, **kwargs): """ 根据段落创建一个bes向量索引。 Args: segments (list): 切分的文本段落列表。 cluster_id (str): bes集群ID。 user_name (str): bes用户名。 password (str): bes用户密码。 embedding (Embedding, optional): 文本段落embedding工具,默认为None,使用默认的Embedding类。 **kwargs: 其他初始化参数。 Returns: BesVectorIndex: bes索引实例。 """ if embedding is None: embedding = Embedding() index_name = kwargs.get("index_name", None) index_type = kwargs.get("index_type", "hnsw") prefix = kwargs.get("prefix", "/rpc/2.0/cloud_hub") vector_index = cls(cluster_id, user_name, password, embedding, index_name, index_type, prefix) vector_index.add_segments(segments) return vector_index def delete_all_segments(self): """ 删除索引中的全部内容。 Args: 无 Returns: 无 """ query = { 'query': { 'match_all': {} } } resp = self.bes_client.delete_by_query(index=self.index_name, body=query) logger.debug("deleted {} documents in index {}".format(resp['deleted'], self.index_name)) def get_all_segments(self): """ 获取索引中的全部内容 """ query = { 'query': { 'match_all': {} } } return self.bes_client.search(index=self.index_name, body=query) class BESRetriever(Component): """ 向量检索组件,用于检索和query相匹配的内容 Examples: .. code-block:: python import appbuilder os.environ["APPBUILDER_TOKEN"] = '...' segments = appbuilder.Message(["文心一言大模型", "百度在线科技有限公司"]) vector_index = appbuilder.BESVectorStoreIndex.from_segments(segments, self.cluster_id, self.username, self.password) query = appbuilder.Message("文心一言") time.sleep(5) retriever = vector_index.as_retriever() res = retriever(query) """ name: str = "BaiduElasticSearchRetriever" tool_desc: Dict[str, Any] = {"description": "a retriever based on Baidu ElasticSearch"} base_es_url: str = "/v1/bce/bes/cluster/" def __init__(self, embedding, index_name, bes_client, index_type="hnsw", **kwargs ): super().__init__() self.embedding = embedding self.index_name = index_name self.bes_client = bes_client self.index_type = index_type @components_run_trace def run(self, query: Message, top_k: int = 1): """ 根据query进行查询 Args: query (Message[str]): 需要查询的内容,以Message对象的形式传递。 top_k (int, optional): 查询结果中匹配度最高的top_k个结果。默认为1。 Returns: obj (Message[Dict]): 查询到的结果,包含文本、元数据以及匹配得分,以Message对象的形式返回。 """ query_embedding = self.embedding(query) vector_query = {"vector": query_embedding.content, "k": top_k} if self.index_type == "linear": vector_query["linear"] = True else: vector_query["ef"] = 10 query_body = { "size": top_k, "query": {"knn": {"vector": vector_query}} } res = self.bes_client.search(index=self.index_name, body=query_body) docs = [] for r in res["hits"]["hits"]: docs.append({"text": r["_source"]["text"], "meta": r["_source"]["metadata"], "score": r["_score"]}) return Message(docs) ================================================ FILE: python/core/components/retriever/reranker/README.md ================================================ # 文本精排(Reranker) ## 简介 文本精排能力,将Query召回到的N个候选文本段落进行精排;保证与Query相关程度越高的文本段落排序越靠前,提升检索效果。 ### 功能介绍 文本精排(Reranker)用于检索排序,输入为Query和Top K个段落,输出为每个段落的排序得分;Query相关程度越高的文本段落排序越靠前,用于提升检索效果。 ### 特色优势 - 高效准确:基于开源模型[ bce-reranker](https://huggingface.co/maidalun1020/bce-reranker-base_v1)的能力,提供高效且准确的内容检索功能。[百度云推理服务Api](https://cloud.baidu.com/doc/WENXINWORKSHOP/s/xlu216rqn) ### 应用场景 检索排序场景 ## 基本用法 以下是有关如何开始使用BESRetriever的代码示例: ```python import os import appbuilder from appbuilder import Message # 请前往千帆AppBuilder官网创建密钥,流程详见:https://cloud.baidu.com/doc/AppBuilder/s/Olq6grrt6#1%E3%80%81%E5%88%9B%E5%BB%BA%E5%AF%86%E9%92%A5 os.environ["APPBUILDER_TOKEN"] = '...' reranker = appbuilder.Reranker() ranked_1 = reranker("你好", ["他也好", "hello?"]) print(ranked_1) # 使用上游的Message作为输入的代码示例 ranked_2 = reranker(appbuilder.Message("你好"), appbuilder.Message(["他也好", "hello?"])) print(ranked_2) ``` ## 参数说明 ### 初始化参数说明: | 参数名称 | 参数类型 |是否必须 | 描述 | 示例值 | |---------|--------|--------|------------------|---------------| | model | str |是 | 指定底座模型的类型。当前仅支持 bce-reranker-base 作为可选值。若不指定,默认值为 bce-reranker-base。 | bce-reranker-base | ### 调用参数: | 参数名称 | 参数类型 | 是否必须 | 描述 | 示例值 | |---------|--------|--------|------------------|---------------| | query | str |是 | 精排Query,长度小于1600。 | "你好" | | texts | List[str] | 是 | 精排输入段落,会对列表里的所有内容排序,最大长度为50. | ["你好", "世界"] | ### 响应参数: | 参数名称 | 参数类型 | 描述 | 示例值 | |---------|--------|------------------|---------------| | +document | str | 输入的段落 | "hello?" | | +relevance_score | float | 精排的相关性分数 | 0.565118 | | +index | int | 输入段落的原始index | -- | ### 响应示例 #### 输入 ```python query="你好", text=["他也好", "hello?"] ``` #### 响应 ```json [ { "document": "hello?", "relevance_score": 0.5651187300682068, "index": 1 }, { "document": "他也好", "relevance_score": 0.47729530930519104, "index": 0 } ] ``` ### 错误码 无 ## 更新记录和贡献 * reranker-base (2024-08) ================================================ FILE: python/core/components/retriever/reranker/__init__.py ================================================ ================================================ FILE: python/core/components/retriever/reranker/component.py ================================================ # -*- coding: utf-8 -*- # Copyright (c) 2024 Baidu, Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """ Reranker 文本精排 """ from typing import Union, List from appbuilder.core.message import Message from appbuilder.core.component import Component, Message from appbuilder.core._exception import AppBuilderServerException, ModelNotSupportedException from appbuilder.utils.trace.tracer_wrapper import components_run_trace from .model import RerankerArgs class Reranker(Component): """ Reranker Examples: .. code-block:: python import os import appbuilder from appbuilder import Message os.environ["APPBUILDER_TOKEN"] = '...' reranker = appbuilder.Reranker() ranked_1 = reranker("你好", ["他也好", "hello?"]) print(ranked_1) """ name: str = "reranker" version: str = "v1" meta = RerankerArgs base_urls = { 'bce-reranker-base' : "/api/v1/component/component/bce_reranker_base" } accepted_models = list(base_urls.keys()) def __init__(self, model="bce-reranker-base", **kwargs ): """Reranker""" if model not in self.accepted_models: raise ModelNotSupportedException(f"Model {model} not supported, only support {self.accepted_models}") if model in self.base_urls: self.base_url = self.base_urls[model] else: raise ModelNotSupportedException(f"Model {model} is not yet supported, only support {self.base_urls.keys()}") super().__init__(self.meta) def _check_response_json(self, data: dict): """ check_response_json """ self.http_client.check_response_json(data) if "error_code" in data and "error_msg" in data: raise AppBuilderServerException( service_err_code=data['error_code'], service_err_message=data['error_msg'], ) def _request(self, payload: dict) -> dict: """ request to gateway """ headers = self.http_client.auth_header() headers["Content-Type"] = "application/json" resp = self.http_client.session.post( url=self.http_client.service_url(self.base_url, "/"), headers=headers, json=payload, ) self.http_client.check_response_header(resp) self._check_response_json(resp.json()) return resp.json() def _batch(self, query, texts: List[str]) -> List[dict]: """ batch run implement """ if len(texts) > 50: raise ValueError(f'Rerank texts max nums must be lower than 50, but got {len(texts)}') for v in texts: if not isinstance(v, str): raise ValueError(f'Rerank texts must be str, but got {v}') params = { "inputs": { "query": query, "texts": texts } } result = self._request(params) result = result["result"] return result @components_run_trace def run(self, query: Union[Message[str], str], texts: Union[Message[List[str]], List[str]]) -> Message[List[dict]]: """ 运行查询,对给定的文本集合进行批量处理,并返回处理后的结果列表。 Args: query (Union[Message[str], str]): 查询条件,可以是字符串或Message对象。 texts (Union[Message[List[str]], List[str]]): 待处理的文本集合,可以是字符串列表或包含字符串列表的Message对象。 Returns: Message[List[dict]]: 处理后的结果列表,每个元素是一个字典,包含处理后的文本信息。 """ _query = query if isinstance(query, str) else query.content _texts = texts if isinstance(texts, List) else texts.content return Message(self._batch(_query, _texts)) ================================================ FILE: python/core/components/retriever/reranker/model.py ================================================ # -*- coding: utf-8 -*- # Copyright (c) 2024 Baidu, Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from typing import Union from appbuilder.core.message import Message from appbuilder.core.component import ComponentArguments, Message class RerankerArgs(ComponentArguments): """ 配置 Attributes: text: Union[Message[str], str] """ text: Union[Message[str], str] ================================================ FILE: python/core/components/table_ocr/README.md ================================================ # 表格文字识别 (TableOCR) ## 简介 表格文字识别 (TableOCR) 可支持识别图片中的表格内容,返回各表格的表头表尾内容、单元格文字内容及其行列位置信息,全面覆盖各类表格样式,包括常规有线表格、无线表格、含合并单元格表格。同时,支持多表格内容识别。 ### 功能介绍 * 简单表格文字识别 支持识别具备完整框线的常规简单表格,结构化输出表头、表尾及每个单元格的文字内容。 * 复杂表格文字识别 可识别无表格框线,但行、列位置明确的表格,支持含合并单元格的复杂表格文字识别。 ### 特色优势 * 支持识别图片中的表格内容,返回各表格的表头表尾内容、单元格文字内容及其行列位置信息,全面覆盖各类表格样式,包括常规有线表格、无线表格、含合并单元格表格。同时,支持单图中多表格内容的识别。 ### 应用场景 * 信息登记表识别 对个人、商品、公示内容等纸质信息登记表进行识别,用于登记信息的结构化整理和统计,大幅度降低人力录入成本,提升信息管理的便捷性 * 财税报表识别 提取识别银行对账单、资产负债表、损益表等财税场景常用表格内容,快速实现表格内容的电子化,用于财税信息统计、存档及核算,大幅度提升信息录入效率 ## 基本用法 下面是表格文字识别的代码示例: 示例图片为 ![示例图片](https://bj.bcebos.com/v1/appbuilder/table_ocr_test.png?authorization=bce-auth-v1%2FALTAKGa8m4qCUasgoljdEDAzLm%2F2024-01-24T12%3A37%3A09Z%2F-1%2Fhost%2Fab528a5a9120d328dc6d18c6064079145ff4698856f477b820147768fc2187d3) ```python import os import appbuilder import requests # 请前往千帆AppBuilder官网创建密钥,流程详见:https://cloud.baidu.com/doc/AppBuilder/s/Olq6grrt6#1%E3%80%81%E5%88%9B%E5%BB%BA%E5%AF%86%E9%92%A5 os.environ["APPBUILDER_TOKEN"] = '...' # 从BOS读取样例图片 image_url = "https://bj.bcebos.com/v1/appbuilder/table_ocr_test.png?" \ "authorization=bce-auth-v1%2FALTAKGa8m4qCUasgoljdEDAzLm%2F2024" \ "-01-24T12%3A37%3A09Z%2F-1%2Fhost%2Fab528a5a9120d328dc6d18c6" \ "064079145ff4698856f477b820147768fc2187d3" raw_image = requests.get(image_url).content # 创建表格文字识别组件实例 table_ocr = appbuilder.TableOCR() # 执行识别操作并获取结果 out = table_ocr.run(appbuilder.Message(content={"raw_image": raw_image})) print(out.content) ``` ## 参数说明 ### 鉴权说明 使用组件之前,请首先申请并设置鉴权参数,可参考[组件使用流程](https://cloud.baidu.com/doc/AppBuilder/s/Olq6grrt6#1%E3%80%81%E5%88%9B%E5%BB%BA%E5%AF%86%E9%92%A5)。 ```python # 设置环境中的TOKEN,以下示例略 os.environ["APPBUILDER_TOKEN"] = "bce-YOURTOKEN" ``` ### 初始化参数 无 ### 调用参数 (以表格形式展示) | 参数名称 | 参数类型 | 是否必须 | 描述 | 示例值 | |---------|---------|------|-----------------------------|------------------------------------------------| | message | String | 是 | 输入的消息,用于模型的主要输入内容。这是一个必需的参数 | Message(content={"raw_image": b"待识别的图片字节流数据"}) | |timeout| Float | 否 | HTTP超时时间,单位:秒 |1|| | retry | Integer | 否 | HTTP重试次数 | 3 | ### 响应参数 | 参数名称 | 参数类型 | 描述 | 示例值 | |------------------|---------|---------------|------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| | tables_result | array[] | 返回结果 | [{"table_location": [],"header": [],"body": [],"footer": []}] | | +table_location | array[] | 单个表格的四角点x,y坐标 | [{ "x": 15, "y": 15 },{ "x": 371, "y": 15 },{ "x": 371, "y": 98 },{ "x": 15, "y": 98 }], | | +header | array[] | 表头信息 | [{'location': [{'x': 325, 'y': 40}, {'x': 528, 'y': 40}, {'x': 528, 'y': 71}, {'x': 325, 'y': 71}], 'words': '财务状况变动表'}, {...}] | | +body | array[] | 单元格信息 | [{"cell_location": [{ "x": 15, "y": 15 },{ "x": 120, "y": 15 },{ "x": 120, "y": 58 },{ "x": 15, "y": 58 }],"row_start": 0,"row_end": 1,"col_start": 0,"col_end": 1,"words": "参数"},{...}] | | +footer | array[] | 表尾信息 | [{'location': [...], 'words': '...'}, {...}] | ### 响应示例 ```json { "tables_result": [ { "table_location": [ { "x": 15, "y": 15 }, { "x": 371, "y": 15 }, { "x": 371, "y": 98 }, { "x": 15, "y": 98 } ], "header": [], "body": [ { "cell_location": [ { "x": 15, "y": 15 }, { "x": 120, "y": 15 }, { "x": 120, "y": 58 }, { "x": 15, "y": 58 } ], "row_start": 0, "row_end": 1, "col_start": 0, "col_end": 1, "words": "参数" }, { "cell_location": [ { "x": 120, "y": 15 }, { "x": 371, "y": 15 }, { "x": 371, "y": 58 }, { "x": 120, "y": 58 } ], "row_start": 0, "row_end": 1, "col_start": 1, "col_end": 2, "words": "值" }, { "cell_location": [ { "x": 15, "y": 58 }, { "x": 120, "y": 58 }, { "x": 120, "y": 98 }, { "x": 15, "y": 98 } ], "row_start": 1, "row_end": 2, "col_start": 0, "col_end": 1, "words": "Content-Type" }, { "cell_location": [ { "x": 120, "y": 58 }, { "x": 371, "y": 58 }, { "x": 371, "y": 98 }, { "x": 120, "y": 98 } ], "row_start": 1, "row_end": 2, "col_start": 1, "col_end": 2, "words": "application/x-www-form-urlencoded" } ], "footer": [] } ] } ``` ### 错误码 | 错误码 | 描述 | |-----|----| ## 高级用法 目前该模块仅提供基础的表格文字识别功能。 ## 更新记录和贡献 * 表格文字识别能力 (2024-01) ================================================ FILE: python/core/components/table_ocr/__init__.py ================================================ ================================================ FILE: python/core/components/table_ocr/component.py ================================================ # Copyright (c) 2023 Baidu, Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """table ocr component.""" import base64 import json from appbuilder.core import utils from appbuilder.core.component import Component from appbuilder.core.components.table_ocr.model import * from appbuilder.core.message import Message from appbuilder.core._client import HTTPClient from appbuilder.core._exception import AppBuilderServerException, InvalidRequestArgumentError from appbuilder.utils.trace.tracer_wrapper import components_run_trace, components_run_stream_trace class TableOCR(Component): r""" 支持识别图片中的表格内容,返回各表格的表头表尾内容、单元格文字内容及其行列位置信息,全面覆盖各类表格样式,包括常规有线表格、 无线表格、含合并单元格表格。同时,支持多表格内容识别。 Examples: .. code-block:: python import appbuilder # 请前往千帆AppBuilder官网创建密钥,流程详见:https://cloud.baidu.com/doc/AppBuilder/s/Olq6grrt6#1%E3%80%81%E5%88%9B%E5%BB%BA%E5%AF%86%E9%92%A5 os.environ["APPBUILDER_TOKEN"] = '...' table_ocr = appbuilder.TableOCR() with open("./table_ocr_test.png", "rb") as f: out = self.component.run(appbuilder.Message(content={"raw_image": f.read()})) print(out.content) """ name = "table_ocr" version = "v1" manifests = [ { "name": "table_ocr", "description": "需要识别图片中的表格内容,使用该工具, 但不支持html后缀文件的识别", "parameters": { "type": "object", "properties": { "file_names": { "type": "array", "items": { "type": "string" }, "description": "待识别图片的文件名" } }, "required": ["file_names"] } } ] @HTTPClient.check_param @components_run_trace def run(self, message: Message, timeout: float = None, retry: int = 0) -> Message: """ 表格文字识别 Args: message (Message): 输入图片或图片url下载地址用于执行识别操作。 举例: Message(content={"raw_image": b"..."}) 或 Message(content={"url": "https://image/download/url"})。 timeout (float, 可选): HTTP超时时间。 retry (int, 可选): HTTP重试次数。 Returns: message (Message): 识别结果。 举例: Message(name=msg, content={'tables_result': [{ 'table_location': [{'x': 15, 'y': 15}, {'x': 371, 'y': 15}, {'x': 371, 'y': 98}, {'x': 15, 'y': 98}], 'header': [], 'body': [{'cell_location': [{'x': 15, 'y': 15}, {'x': 120, 'y': 15}, {'x': 120, 'y': 58}, {'x': 15, 'y': 58}], 'row_start': 0, 'row_end': 1, 'col_start': 0, 'col_end': 1, 'words': '参数'}, {'cell_location': [{'x': 120, 'y': 15}, {'x': 371, 'y': 15}, {'x': 371, 'y': 58}, {'x': 120, 'y': 58}], 'row_start': 0, 'row_end': 1, 'col_start': 1, 'col_end': 2, 'words': '值'}, {'cell_location': [{'x': 15, 'y': 58}, {'x': 120, 'y': 58}, {'x': 120, 'y': 98}, {'x': 15, 'y': 98}], 'row_start': 1, 'row_end': 2, 'col_start': 0, 'col_end': 1, 'words': 'Content-Type'}, {'cell_location': [{'x': 120, 'y': 58}, {'x': 371, 'y': 58}, {'x': 371, 'y': 98}, {'x': 120, 'y': 98}], 'row_start': 1, 'row_end': 2, 'col_start': 1, 'col_end': 2, 'words': 'application/x-www-form-urlencoded'}], 'footer': []}]}, mtype=dict) """ inp = TableOCRInMsg(**message.content) req = TableOCRRequest() if inp.raw_image: req.image = base64.b64encode(inp.raw_image) if inp.url: req.url = inp.url req.cell_contents = "false" result = self._recognize(req, timeout, retry) result_dict = proto.Message.to_dict(result) out = TableOCROutMsg(**result_dict) return Message(content=out.model_dump()) def _recognize(self, request: TableOCRRequest, timeout: float = None, retry: int = 0, request_id: str = None) -> TableOCRResponse: r"""调用底层接口进行表格文字识别 参数: request (obj: `TableOCRRequest`) : 表格文字识别输入参数 返回: response (obj: `TableOCRResponse`): 表格文字识别返回结果 """ if not request.image and not request.url: raise ValueError( "request format error, one of image or url must be set") data = TableOCRRequest.to_dict(request) if self.http_client.retry.total != retry: self.http_client.retry.total = retry headers = self.http_client.auth_header(request_id) headers['content-type'] = 'application/x-www-form-urlencoded' url = self.http_client.service_url("/v1/bce/aip/ocr/v1/table") response = self.http_client.session.post( url, headers=headers, data=data, timeout=timeout) self.http_client.check_response_header(response) data = response.json() self.http_client.check_response_json(data) request_id = self.http_client.response_request_id(response) self.__class__._check_service_error(request_id, data) res = TableOCRResponse.from_json(json.dumps(data)) res.request_id = request_id return res @staticmethod def _check_service_error(request_id: str, data: dict): r"""个性化服务response参数检查 参数: request (dict) : 表格文字识别body返回 返回: 无 """ if "error_code" in data or "error_msg" in data: raise AppBuilderServerException( request_id=request_id, service_err_code=data.get("error_code"), service_err_message=data.get("error_msg") ) def get_table_markdown(self, tables_result): """ 将表格识别结果转换为Markdown格式。 Args: tables_result (list): 表格识别结果列表,每个元素是一个包含表格数据的字典,其中包含表格体(body)等字段。 Returns: list: 包含Markdown格式表格的字符串列表。 """ markdowns = [] for table in tables_result: cells = table["body"] max_row = max(cell['row_end'] for cell in cells) max_col = max(cell['col_end'] for cell in cells) # 初始化表格数组 table_arr = [[''] * max_col for _ in range(max_row)] # 填充表格数据 for cell in cells: row = cell['row_start'] col = cell['col_start'] table_arr[row][col] = cell['words'] markdown_table = "" for row in table_arr: markdown_table += "| " + " | ".join(row) + " |\n" # 生成分隔行 separator = "| " + " | ".join(['---'] * max_col) + " |\n" # 插入分隔行在表头下方 header, body = markdown_table.split('\n', 1) markdown_table = header + '\n' + separator + body markdowns.append(markdown_table) return markdowns @components_run_stream_trace def tool_eval(self, name: str, streaming: bool, **kwargs): """ 对传入文件进行处理,并返回处理结果。 Args: name (str): 工具的名称。 streaming (bool): 是否为流式处理。若为True,则以生成器形式返回结果;若为False,则直接返回结果。 **kwargs: 关键字参数,包含以下参数: traceid (str): 请求的唯一标识符。 file_names (List[str]): 文件名列表,表示需要处理的文件名。 files (List[str]): 同file_names,用于兼容老版本接口。 file_urls (Dict[str, str]): 文件名和对应URL的映射字典。 Returns: 若streaming为True,则以生成器形式返回处理结果,每个元素为包含type和text的字典,type固定为"text",text为处理结果的JSON字符串。 若streaming为False,则直接返回处理结果的JSON字符串。 Raises: InvalidRequestArgumentError: 若传入文件名在file_urls中未找到对应的URL,则抛出此异常。 """ result = {} traceid = kwargs.get("traceid") file_names = kwargs.get("file_names", None) if not file_names: file_names = kwargs.get("files") file_urls = kwargs.get("file_urls", {}) for file_name in file_names: if utils.is_url(file_name): file_url = file_name else: file_url = file_urls.get(file_name, None) if file_url is None: raise InvalidRequestArgumentError( f"request format error, file {file_name} url does not exist" ) req = TableOCRRequest() req.url = file_url req.cell_contents = "false" resp = self._recognize(req, request_id=traceid) tables_result = proto.Message.to_dict(resp)["tables_result"] markdowns = self.get_table_markdown(tables_result) result[file_name] = markdowns result = json.dumps(result, ensure_ascii=False) if streaming: yield { "type": "text", "text": result, "visible_scope": 'llm', } yield { "type": "text", "text": "", "visible_scope": "user", } else: return result ================================================ FILE: python/core/components/table_ocr/model.py ================================================ # Copyright (c) 2023 Baidu, Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """table ocr model.""" import proto from typing import List, Dict from pydantic import BaseModel class TableOCRRequest(proto.Message): r"""表格文字识别请求体参数. 属性: image (str): 可选。图像内容的base64编码。 url (str): 可选。图像的URL地址,经过base64编码。 图像大小必须小于4MB,图像的最短边长大于15像素,最长边长大于4096像素。 cell_contents (str): 是否输出单元格文字位置信息,可选值包括: - false: 默认值,仅输出单元格行列信息及四角点坐标,不输出单元格内文字位置信息 - true: 输出单元格内文字的外接四边形四角点坐标,若文字折行,则分行分别输出 必须设置image或url属性之一,如果两者都设置了,将使用image属性。 """ image: str = proto.Field( proto.STRING, number=1, ) url: str = proto.Field( proto.STRING, number=2, ) cell_contents: str = proto.Field( proto.STRING, number=3, ) class TableOCRResponse(proto.Message): """表格文字识别响应消息 属性: request_id (str): 请求ID。 log_id (int): 用于问题识别的唯一日志ID。 table_num (int): 检测到的表格数量。 result (List[TableRes]): 表格文字识别结果列表。 """ request_id: str = proto.Field( proto.STRING, number=1, ) log_id: int = proto.Field( proto.INT64, number=2, ) table_num: int = proto.Field( proto.INT64, number=3, ) tables_result: 'TableRes' = proto.RepeatedField( proto.MESSAGE, number=4, message='TableRes', ) class TableRes(proto.Message): """表格文字识别结果 属性: table_location (List[Location]): 单个表格的四角点x,y坐标。 header (List[Header]): 表头信息。 body (List[Body]): 单元格信息。 footer (List[Footer]): 表尾信息。 """ table_location: 'Location' = proto.RepeatedField( proto.MESSAGE, number=1, message="Location" ) header: 'Header' = proto.RepeatedField( proto.MESSAGE, number=2, message="Header" ) body: 'Body' = proto.RepeatedField( proto.MESSAGE, number=3, message="Body" ) footer: 'Footer' = proto.RepeatedField( proto.MESSAGE, number=4, message="Footer" ) class Header(proto.Message): """表头信息 属性: location (List[Location]): 表头位置,四角点 x,y 坐标。 words (str): 表头文字内容,按行拆分。 """ location: 'Location' = proto.RepeatedField( proto.MESSAGE, number=1, message="Location" ) words: str = proto.Field( proto.STRING, number=2, ) class Body(proto.Message): """单元格信息 属性: cell_location (List[Location]): 表头位置,四角点 x,y 坐标。 row_start (str): 单元格行起始编号,横线编号从0开始。 row_end (str): 单元格行终止编号。 col_start (str): 单元格列起始编号,竖线编号从0开始。 col_end (str): 单元格列终止编号。 words (str): 单元格文字内容。 contents (str): 单元格内文字内容,分行显示,当请求参数 cell_contents = true 时返回。 """ cell_location: 'Location' = proto.RepeatedField( proto.MESSAGE, number=1, message="Location" ) row_start: int = proto.Field( proto.INT32, number=2, ) row_end: int = proto.Field( proto.INT32, number=3, ) col_start: int = proto.Field( proto.INT32, number=4, ) col_end: int = proto.Field( proto.INT32, number=5, ) words: str = proto.Field( proto.STRING, number=6, ) contents: str = proto.Field( proto.STRING, number=7, ) class Footer(proto.Message): """表尾信息 属性: location (List[Location]): 表头位置,四角点 x,y 坐标。 words (str): 表头文字内容,按行拆分。 """ location: 'Location' = proto.RepeatedField( proto.MESSAGE, number=1, message="Location" ) words: str = proto.Field( proto.STRING, number=2, ) class Location(proto.Message): """四角点坐标。 属性: x (int): x坐标。 y (int): y坐标。 """ x: int = proto.Field( proto.INT64, number=1, ) y: int = proto.Field( proto.INT64, number=2, ) class TableOCRInMsg(BaseModel): """ 表格文字识别输入消息 属性: raw_image(bytes): 图像原始内容 url(str): 图像下载链接 """ raw_image: bytes = b'' url: str = "" class PyHeader(BaseModel): """表头信息 属性: location (List[Dict[str, int]]): 表头位置,四角点 x,y 坐标。 words (str): 表头文字内容,按行拆分。 """ location: List[Dict[str, int]] words: str class PyBody(BaseModel): """单元格信息 属性: cell_location (List[Location]): 表头位置,四角点 x,y 坐标。 row_start (str): 单元格行起始编号,横线编号从0开始。 row_end (str): 单元格行终止编号。 col_start (str): 单元格列起始编号,竖线编号从0开始。 col_end (str): 单元格列终止编号。 words (str): 单元格文字内容。 """ cell_location: List[Dict[str, int]] row_start: int row_end: int col_start: int col_end: int words: str class PyFooter(BaseModel): """表尾信息 属性: location (List[Dict[str, int]]): 表头位置,四角点 x,y 坐标。 words (str): 表头文字内容,按行拆分。 """ location: List[Dict[str, int]] words: str class TableOCRRes(BaseModel): """表格文字识别对象信息 属性: table_location (List[Dict[str, int]]): 单个表格的四角点x,y坐标 header (List[PyHeader]): 表头信息 body (List[PyBody]): 单元格信息 footer (List[PyFooter]): 表尾信息 """ table_location: List[Dict[str, int]] header: List[PyHeader] body: List[PyBody] footer: List[PyFooter] class TableOCROutMsg(BaseModel): r"""识别结果列表""" tables_result: List[TableOCRRes] # 结果列表 ================================================ FILE: python/core/components/text_to_image/README.md ================================================ # 文生图 (Text2Image) ## 简介 文生图(Text2Image)基于文心大模型,可以根据用户输入的文本,自动创作不限定风格的图,为内容创作者提供灵感和高质量配图。 ### 功能介绍 AI一下,文字成画,AI 精准理解中文文本,支持用户自由输入,只需一句话,让文字秒变精美画作,支持自定义丰富的修饰词,可生成不同风格、不同构图、不同流派的图片,满足个性化的图片生成需求。 ### 特色优势 利用知识增强扩散模型,学习过程融入语言、视觉、跨模态等多源知识,生成图像语义一致性更高,基于混合降噪专家网络,全球最大跨模态生成模型,参数规模达到240亿,根据生成阶段选择最优生成“专家”,从图像轮廓渐进优化细节,全面提升生成质量。 ### 应用场景 图片素材、艺术插图、海报制作、故事插图、壁纸制作、电商应用、室内设计、影视制作、游戏原画设计、服务创意启发平台等。 ## 基本用法 下面是文生图的代码示例: ```python import os import appbuilder # 设置环境变量和初始化 # 请前往千帆AppBuilder官网创建密钥,流程详见:https://cloud.baidu.com/doc/AppBuilder/s/Olq6grrt6#1%E3%80%81%E5%88%9B%E5%BB%BA%E5%AF%86%E9%92%A5 os.environ["APPBUILDER_TOKEN"] = "..." text2Image = appbuilder.Text2Image() content_data = {"prompt": "上海的经典风景", "width": 1024, "height": 1024, "image_num": 1} msg = appbuilder.Message(content_data) out = text2Image.run(msg) print(out.content) #{'img_urls': ['...']} ``` 生成的"上海的经典风景"图片如下 ![示例图片](https://bj.bcebos.com/v1/appbuilder-sdk-components/shanghai.png?authorization=bce-auth-v1%2FALTAKGa8m4qCUasgoljdEDAzLm%2F2024-05-30T03%3A08%3A30Z%2F-1%2Fhost%2F64296a40b3f01d39776129e0b4ce732b1784f2f91e3afcf9dd7c1de8c3df6a0a) ## 参数说明 ### 鉴权配置 使用组件之前,请首先申请并设置鉴权参数,可参考[组件使用流程](https://cloud.baidu.com/doc/AppBuilder/s/Olq6grrt6#1%E3%80%81%E5%88%9B%E5%BB%BA%E5%AF%86%E9%92%A5)。 ```python # 设置环境中的TOKEN,以下示例略 os.environ["APPBUILDER_TOKEN"] = "bce-YOURTOKEN" ``` ### 初始化参数 无 ### 调用参数 |参数名称 |参数类型 |是否必须 |描述 | 示例值 | |--------|--------|--------|----|--------| |message |String |是 |输入的消息,输入的消息,用于模型的主要输入内容。这是一个必需的参数| Message(content={"prompt": "上海的经典风景"}) | |width|Integer|是 |图片宽度,支持:512x512、640x360、360x640、1024x1024、1280x720、720x1280、2048x2048、2560x1440、1440x2560。| 1024 | |height|Integer|是 |图片高度,支持:512x512、640x360、360x640、1024x1024、1280x720、720x1280、2048x2048、2560x1440、1440x2560。| 1024 | |image_num|Integer|是 |生成图片数量,默认一张,支持生成 1-8 张。| 1 | |timeout| Float | 否 | HTTP超时时间,单位:秒 |1|| |retry|Integer|是 |HTTP重试次数| 3 | ### 响应参数 |参数名称 |参数类型 |描述 |示例值| |--------|--------|----|------| |result |String |返回结果|["xxx"]| ### 响应示例 ```json {"img_urls": ["xxx"]} ``` ### 错误码 | 错误码 |描述| |---|---| | 282000 |服务器内部错误,请再次请求, 如果持续出现此类错误,请在控制台提交工单联系技术支持团队| | 282004 |请求中包含敏感词、非法参数、字数超限,或上传违规参考图,请检查后重新尝试| | 282003 |缺少必要参数| | 17 |日配额流量超限| | 18 |QPS 超限额| | 216630 |服务器内部错误,请再次请求,如果持续出现此类错误,请通过工单联系技术支持| | 501 |文本黄反拦截| | 201 |模型生图失败| | 216100 |参数不满足格式要求| | 216201 |参考图不满足格式要求| | 4 |错误信息为中文的“请求超限”指所有用户提交的 AI 作画总数超限制| | 13 |错误信息为中文的“QPS 超限”指单个用户使用提交请求接口的 QPS 超限| | 15 |错误信息为中文的“并发超限”指单个用户使用 AI 作画的并发超限| | 17 |错误信息为中文的“用量超限”指单个用户使用 AI 作画的用量超限| ## 高级用法 目前该模块仅提供基础的文生图功能。 ## 更新记录和贡献 * 文生图能力 (2023-12) ================================================ FILE: python/core/components/text_to_image/__init__.py ================================================ # Copyright (c) 2023 Baidu, Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. ================================================ FILE: python/core/components/text_to_image/component.py ================================================ # Copyright (c) 2023 Baidu, Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. r"""Text2Image component. """ import time import math from typing import Optional from appbuilder.core.component import Component from appbuilder.core.message import Message from appbuilder.core._client import HTTPClient from appbuilder.core._exception import AppBuilderServerException, RiskInputException from appbuilder.core.components.text_to_image.model import Text2ImageSubmitRequest, Text2ImageQueryRequest, \ Text2ImageQueryResponse, Text2ImageSubmitResponse, Text2ImageOutMessage, Text2ImageInMessage from appbuilder.utils.trace.tracer_wrapper import components_run_trace, components_run_stream_trace class Text2Image(Component): r""" 文生图组件,即对于输入的文本,输出生成的图片url。 Examples: .. code-block:: python import appbuilder text_to_image = appbuilder.Text2Image() os.environ["APPBUILDER_TOKEN"] = '...' content_data = {"prompt": "上海的经典风景", "width": 1024, "height": 1024, "image_num": 1} msg = appbuilder.Message(content_data) out = text_to_image.run(inp) # 打印生成结果 print(out.content) # eg: {"img_urls": ["xxx"]} """ manifests = [ { "name": "text_to_image", "description": "文生图,该组件只用于图片创作。当用户需要进行场景、人物、海报等内容的绘制时,使用该画图组件。如果用户需要生成图表(柱状图、折线图、雷达图等),则必须使用代码解释器。", "parameters": { "type": "object", "properties": { "query": { "type": "string", "description": "文生图用的query。特别注意,这个字段只能由中文字符组成,不能含有任何英语描述。" } }, "required": [ "query" ] } } ] @HTTPClient.check_param @components_run_trace def run( self, message: Message, width: int = 1024, height: int = 1024, image_num: int = 1, image: Optional[str] = None, url: Optional[str] = None, pdf_file: Optional[str] = None, pdf_file_num: Optional[str] = None, change_degree: Optional[int] = None, text_content: Optional[str] = None, task_time_out: Optional[int]= None, text_check: Optional[int] = 1, request_id: Optional[str] = None ): """ 执行文本到图像的生成任务。 Args: message (Message): 包含任务相关信息的消息对象。 width (int, optional): 生成的图像的宽度,默认为1024。 height (int, optional): 生成的图像的高度,默认为1024。 image_num (int, optional): 生成图像的数量,默认为1。 image (Optional[str], optional): 参考图像的路径或URL,默认为None。 url (Optional[str], optional): 参考图像的URL,默认为None。 pdf_file (Optional[str], optional): 参考PDF文件的路径,默认为None。 pdf_file_num (Optional[str], optional): 参考PDF文件中的页码范围,默认为None。 change_degree (Optional[int], optional): 图像变换的程度,默认为None。 text_content (Optional[str], optional): 需要转换的文本内容,默认为None。 task_time_out (Optional[int], optional): 任务超时时间,默认为None。 text_check (Optional[int], optional): 是否进行文本内容检查,默认为1。 request_id (Optional[str], optional): 请求的唯一标识,默认为None。 Returns: Message: 包含生成图像URL的消息对象。 Raises: HTTPError: 请求失败时抛出异常。 """ headers = self._http_client.auth_header() headers["Content-Type"] = "application/json" api_url = self._http_client.service_url("/v1/bce/aip/ernievilg/v1/txt2imgv2") req = Text2ImageSubmitRequest( prompt=message.content["prompt"], width=width, height=height, image_num=image_num, image=image, url=url, pdf_file=pdf_file, pdf_file_num=pdf_file_num, change_degree=change_degree, text_content=text_content, task_time_out=task_time_out, text_check=text_check ) response = self.http_client.session.post(api_url, json=req.model_dump(), headers=headers, timeout=None) self._http_client.check_response_header(response) data = response.json() resp= Text2ImageSubmitResponse(**data) taskId = resp.data.task_id if taskId is not None: task_request_time = 1 while True: request = Text2ImageQueryRequest(task_id=taskId) text2ImageQueryResponse = self.queryText2ImageData(request, request_id=request_id) if text2ImageQueryResponse.data.task_progress is not None: task_progress = float(text2ImageQueryResponse.data.task_progress) if math.isclose(1.0, task_progress, rel_tol=1e-9, abs_tol=0.0): break # NOTE(chengmo):文生图组件的返回时间在10s以上,查询过于频繁会被限流,导致异常报错 # 此处采用 yangyongzhen老师提供的方案,前三次查询间隔3s,后三次查询间隔逐渐增大 if task_request_time <= 3: time.sleep(3) else: time.sleep(task_request_time) task_request_time += 1 img_urls = self.extract_img_urls(text2ImageQueryResponse) out = Text2ImageOutMessage(img_urls=img_urls) return Message(content=out.model_dump()) @HTTPClient.check_param def submitText2ImageTask( self, request: Text2ImageSubmitRequest, timeout: float = None, retry: int = 0, request_id: str = None, ) -> Text2ImageSubmitResponse: """ 使用给定的输入并返回文生图的任务信息。 Args: request (obj:`Text2ImageSubmitRequest`): 输入请求,这是一个必需的参数。 timeout (float, optional): 请求的超时时间。默认为None。 retry (int, optional): 请求的重试次数。默认为0。 request_id (str, optional): 请求的唯一标识符。默认为None。 Returns: obj:`Text2ImageSubmitResponse`: 接口返回的输出消息。 """ url = self.http_client.service_url("/v1/bce/aip/ernievilg/v1/txt2imgv2") data = request.model_dump() headers = self.http_client.auth_header(request_id) headers['content-type'] = 'application/json' if retry != self.http_client.retry.total: self.http_client.retry.total = retry response = self.http_client.session.post(url, json=data, headers=headers, timeout=timeout) self.http_client.check_response_header(response) data = response.json() self.http_client.check_response_json(data) response = Text2ImageSubmitResponse(**data) return response def queryText2ImageData( self, request: Text2ImageQueryRequest, timeout: float = None, retry: int = 0, request_id: str = None, ) -> Text2ImageQueryResponse: """ 将文本查询请求转换为图像数据。 Args: request (Text2ImageQueryRequest): 输入请求,必填参数。 timeout (float, optional): 请求的超时时间,默认为None。 retry (int, optional): 请求的重试次数,默认为0。 request_id (str, optional): 请求的唯一标识符,默认为None。 Returns: Text2ImageQueryResponse: 接口返回的输出消息。 """ url = self.http_client.service_url("/v1/bce/aip/ernievilg/v1/getImgv2") data = { "task_id": request.task_id } headers = self.http_client.auth_header(request_id) headers['content-type'] = 'application/json' if retry != self.http_client.retry.total: self.http_client.retry.total = retry response = self.http_client.session.post(url, json=data, headers=headers, timeout=timeout) self.http_client.check_response_header(response) data = response.json() self.http_client.check_response_json(data) request_id = self.http_client.response_request_id(response) self.__class__.check_service_error(request_id, data) response = Text2ImageQueryResponse(**data) return response def extract_img_urls(self, response: Text2ImageQueryResponse): """ 从作画生成的返回结果中提取图片url。 Args: response (obj:`Text2ImageQueryResponse`): 作画生成的返回结果。 Returns: List[str]: 从返回体中提取的图片url列表。 """ img_urls = [] if response and response.data and response.data.sub_task_result_list: for sub_task_result in response.data.sub_task_result_list: if sub_task_result and sub_task_result.final_image_list: for final_image in sub_task_result.final_image_list: if final_image and final_image.img_url: img_urls.append(final_image.img_url) return img_urls @staticmethod def check_service_error(request_id: str, data: dict): """ 检查服务错误信息 Args: request_id (str): 请求ID data (dict): 响应数据 Raises: AppBuilderServerException: 如果响应数据中包含错误信息,则抛出异常 Returns: None """ if "error_code" in data or "error_msg" in data: raise AppBuilderServerException( request_id=request_id, service_err_code=data.get("error_code"), service_err_message=data.get("error_msg") ) ================================================ FILE: python/core/components/text_to_image/model.py ================================================ # Copyright (c) 2023 Baidu, Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. r"""Text2Image model.py. """ from typing import MutableSequence, List from typing import Optional, Union import proto from pydantic import BaseModel, Field class Text2ImageSubmitRequest(BaseModel): prompt: str = Field(default='') width: int = Field(default=1024) height: int = Field(default=1024) image_num: int = Field(default=1, ge=1, le=8) image: Optional[str] = Field(default="") url: Optional[str] = Field(default="") pdf_file: Optional[str] = Field(default="") pdf_file_num: Optional[str] = Field(default="") change_degree: Optional[int] = None text_content: Optional[str] = None task_time_out: Optional[int] = None text_check: Optional[int] = None class Text2ImageSubmitErrorDetail(BaseModel): msg: Optional[str] words: Optional[list] class Text2ImageSubmitResponseData(BaseModel): primary_task_id: Optional[int] = None task_id: Optional[str] = None class Text2ImageSubmitResponse(BaseModel): log_id: Optional[int] = None data: Optional[Text2ImageSubmitResponseData] = Text2ImageSubmitResponseData() error_msg: Optional[str] = None error_detail: Optional[list[Text2ImageSubmitErrorDetail]] = None error_code: Optional[int] = None class Text2ImageQueryRequest(BaseModel): task_id: Optional[str] class FinalImage(BaseModel): img_url: Optional[str] = None height: Optional[int] = None width: Optional[int] = None img_approve_conclusion: Optional[str] = None class SubTaskResult(BaseModel): sub_task_status: Optional[str] = None sub_task_progress_detail: Union[int, float, None] = None sub_task_progress: Union[float, int, None] = None sub_task_error_code: Optional[int] = None final_image_list: Optional[list[FinalImage]] = None class Text2ImageQueryResponseData(BaseModel): task_id: Optional[int] = None task_status: Optional[str] = None task_progress_detail: Union[float, int, None] = None task_progress: Union[float, int, None] = None sub_task_result_list: Optional[list[SubTaskResult]] = None class Text2ImageQueryResponse(BaseModel): log_id: Union[str, int, None] = None data: Optional[Text2ImageQueryResponseData] = Text2ImageQueryResponseData() class Text2ImageInMessage(BaseModel): """ 文生图组件输入message. 参数: prompt(str): 生图的文本描述。仅支持中文、日常标点符号。不支持英文,特殊符号,限制 200 字。 """ prompt: str class Text2ImageOutMessage(BaseModel): """ 文生图组件输出message. 参数: img_urls(str): 图片所在 BOS http 地址,默认 1 小时失效。 """ img_urls: List[str] ================================================ FILE: python/core/components/translate/README.md ================================================ # 文本翻译-通用版(Translation) ## 简介 文本翻译组件(Translation)提供多种语言互译的在线文本翻译服务。支持术语定制功能,用户可对翻译结果进行干预,快速提高翻译质量。可广泛应用于移动端、PC网站、智能硬件等不同产品形态中,满足多领域、多场景的翻译需求。 ### 功能介绍 支持200+语种互译,传入待翻译内容,并指定源语言(支持语种自动检测)和目标语言,即可获得翻译结果,并支持术语干预。 支持在【创建应用】-【添加工具组件】时,对以下语言的试用: |名称 | 代码 | 名称 | 代码 | 名称 | 代码 | |------------|--------|------------|--------|------------|--------| | 自动检测 | auto | 中文 | zh | 英语 | en | | 粤语 | yue | 文言文 | wyw | 日语 | jp | | 韩语 | kor | 法语 | fra | 西班牙语 | spa | | 泰语 | th | 阿拉伯语 | ara | 俄语 | ru | | 葡萄牙语 | pt | 德语 | de | 意大利语 | it | | 希腊语 | el | 荷兰语 | nl | 波兰语 | pl | | 保加利亚语 | bul | 爱沙尼亚语 | est | 丹麦语 | dan | | 芬兰语 | fin | 捷克语 | cs | 罗马尼亚语 | rom | | 斯洛文尼亚语 | slo | 瑞典语 | swe | 匈牙利语 | hu | | 繁体中文 | cht | 越南语 | vie | | | ### 特色优势 1. 依托互联网数据资源和自然语言处理技术优势,上线全球首个互联网神经网络翻译系统,日均响应千亿字符请求 2. 2019国际机器翻译评测(WMT19)中,获得中英翻译第一,提供业界领先的机器翻译服务 3. 支持用户上传术语对翻译结果进行干预,优化翻译质量,用户可根据不同产品、不同领域创建多个术语库 4. 翻译请求可实现实时响应,服务稳定性高,在海外也可及时获取翻译结果,保障用户稳定的服务体验 ### 应用场景 1. 教育学习:在外语教学及学习场景中,通过实时句子翻译、单词释义、语音合成等功能,帮助师生沟通、外教课后点评,辅助阅读和写作,全面提升学习效率与质量 2. 手机厂商:应用于手机系统中,实现手机系统取词翻译、对话文本翻译等服务。为手机应用开发者提供便捷的翻译功能 3. 跨境电商:在商业全球化背景下,针对跨国商贸服务中产品名称、详情页等网站基本信息进行翻译,助力企业开拓国际市场 4. 智能硬件:应用于翻译机、学习机、智能手表等硬件系统中,为用户提供文本翻译、词典及语音合成等能力,实现便捷准确的多语种互译功能 ## 基本用法 通过如下示例代码可以快速开始使用文本翻译组件: ```python import os import appbuilder # 请前往千帆AppBuilder官网创建密钥,流程详见:https://cloud.baidu.com/doc/AppBuilder/s/Olq6grrt6#1%E3%80%81%E5%88%9B%E5%BB%BA%E5%AF%86%E9%92%A5 os.environ["APPBUILDER_TOKEN"] = '...' translate = appbuilder.Translation() resp = translate(appbuilder.Message("你好\n中国"), from_lang="zh", to_lang="en") # 输出{'from_lang': 'zh', 'to_lang': 'en', 'trans_result': [{'src': '你好', 'dst': 'hello'}, {'src': '中国', 'dst': 'China'}]} print(resp.content) ``` ## 参数说明 ### 鉴权配置 使用组件之前,请首先申请并设置鉴权参数,可参考[组件使用流程](https://cloud.baidu.com/doc/AppBuilder/s/Olq6grrt6#1%E3%80%81%E5%88%9B%E5%BB%BA%E5%AF%86%E9%92%A5)。 ```python # 设置环境中的TOKEN,以下示例略 os.environ["APPBUILDER_TOKEN"] = "bce-YOURTOKEN" ``` ### 初始化参数说明 无 ### 调用参数说明 |参数名称 |参数类型 |是否必须 |描述 | 示例值 | |--------|--------|--------|----|--------| |message |obj:`Message` |是 |输入的请求翻译文本| Message("你好") | |from_lang|String|否 |翻译的源语言,默认为`auto`,表示自动检测语言。| zh | |to_lang|Integer|否 |需要翻译的目标语言,默认为`en`,表示英语。| en | |timeout| Float | 否 | HTTP超时时间,单位:秒 |1|| |retry|Integer|否 |HTTP重试次数| 3 | ### 响应参数 |参数名称 |参数类型 |描述 |示例值| |--------|--------|----|------| |from_lang |String |翻译源语言| zh| |to_lang |String |翻译目标语言|en| |trans_result |List[Object] |返回结果|[{'src': '你好', 'dst': 'hello'}]| |trans_result[0].src |String |源文本|你好| |trans_result[0].dst |String |目标文本|hello| ### 响应示例 ```json { "from_lang": "zh", "to_lang": "en", "trans_result": [ { "src": "你好", "dst": "hello" } ] } ``` ### 错误码 |错误码|描述| |------|---| ## 更新记录和贡献 * 文本翻译-通用版 (2024-01) ## 语种列表 |名称 |代码 |语种检测| |----|-----|------| | 阿拉伯语 | ara | 是 | | 爱尔兰语 | gle | 是 | | 奥克语 | oci | 是 | | 阿尔巴尼亚语 | alb | 是 | | 阿尔及利亚阿拉伯语 | arq | 否 | | 阿肯语 | aka | 否 | | 阿拉贡语 | arg | 否 | | 阿姆哈拉语 | amh | 是 | | 阿萨姆语 | asm | 是 | | 艾马拉语 | aym | 否 | | 阿塞拜疆语 | aze | 是 | | 阿斯图里亚斯语 | ast | 是 | | 奥塞梯语 | oss | 否 | | 爱沙尼亚语 | est | 是 | | 奥杰布瓦语 | oji | 否 | | 奥里亚语 | ori | 是 | | 奥罗莫语 | orm | 否 | | 波兰语 | pl | 是 | | 波斯语 | per | 是 | | 布列塔尼语 | bre | 是 | | 巴什基尔语 | bak | 否 | | 巴斯克语 | baq | 是 | | 巴西葡萄牙语 | pot | 否 | | 白俄罗斯语 | bel | 是 | | 柏柏尔语 | ber | 是 | | 邦板牙语 | pam | 否 | | 保加利亚语 | bul | 是 | | 北方萨米语 | sme | 否 | | 北索托语 | ped | 否 | | 本巴语 | bem | 否 | | 比林语 | bli | 否 | | 比斯拉马语 | bis | 否 | | 俾路支语 | bal | 否 | | 冰岛语 | ice | 是 | | 波斯尼亚语 | bos | 是 | | 博杰普尔语 | bho | 否 | | 楚瓦什语 | chv | 否 | | 聪加语 | tso | 否 | | 丹麦语 | dan | 是 | | 德语 | de | 是 | | 鞑靼语 | tat | 是 | | 掸语 | sha | 否 | | 德顿语 | tet | 否 | | 迪维希语 | div | 否 | | 低地德语 | log | 是 | | 俄语 | ru | 是 | | 法语 | fra | 是 | | 菲律宾语 | fil | 是 | | 芬兰语 | fin | 是 | | 梵语 | san | 否 | | 弗留利语 | fri | 否 | | 富拉尼语 | ful | 否 | | 法罗语 | fao | 否 | | 盖尔语 | gla | 否 | | 刚果语 | kon | 否 | | 高地索布语 | ups | 否 | | 高棉语 | hkm | 是 | | 格陵兰语 | kal | 否 | | 格鲁吉亚语 | geo | 是 | | 古吉拉特语 | guj | 是 | | 古希腊语 | gra | 否 | | 古英语 | eno | 否 | | 瓜拉尼语 | grn | 否 | | 韩语 | kor | 是 | | 荷兰语 | nl | 是 | | 胡帕语 | hup | 否 | | 哈卡钦语 | hak | 否 | | 海地语 | ht | 否 | | 豪萨语 | hau | 否 | | 黑山语 | mot | 否 | | 吉尔吉斯语 | kir | 否 | | 加利西亚语 | glg | 是 | | 加拿大法语 | frn | 否 | | 加泰罗尼亚语 | cat | 是 | | 捷克语 | cs | 是 | | 卡拜尔语 | kab | 是 | | 卡纳达语 | kan | 是 | | 卡努里语 | kau | 否 | | 卡舒比语 | kah | 否 | | 康瓦尔语 | cor | 否 | | 科萨语 | xho | 是 | | 科西嘉语 | cos | 否 | | 克里克语 | cre | 否 | | 克里米亚鞑靼语 | cri | 否 | | 克林贡语 | kli | 否 | | 克罗地亚语 | hrv | 是 | | 克丘亚语 | que | 否 | | 克什米尔语 | kas | 否 | | 孔卡尼语 | kok | 否 | | 库尔德语 | kur | 是 | | 拉丁语 | lat | 是 | | 老挝语 | lao | 否 | | 罗马尼亚语 | rom | 是 | | 拉特加莱语 | lag | 否 | | 拉脱维亚语 | lav | 是 | | 林堡语 | lim | 否 | | 林加拉语 | lin | 否 | | 卢干达语 | lug | 否 | | 卢森堡语 | ltz | 否 | | 卢森尼亚语 | ruy | 否 | | 卢旺达语 | kin | 是 | | 立陶宛语 | lit | 是 | | 罗曼什语 | roh | 否 | | 罗姆语 | ro | 否 | | 逻辑语 | loj | 否 | | 马来语 | may | 是 | | 缅甸语 | bur | 是 | | 马拉地语 | mar | 否 | | 马拉加斯语 | mg | 是 | | 马拉雅拉姆语 | mal | 是 | | 马其顿语 | mac | 是 | | 马绍尔语 | mah | 否 | | 迈蒂利语 | mai | 是 | | 曼克斯语 | glv | 否 | | 毛里求斯克里奥尔语 | mau | 否 | | 毛利语 | mao | 否 | | 孟加拉语 | ben | 是 | | 马耳他语 | mlt | 是 | | 苗语 | hmn | 否 | | 挪威语 | nor | 是 | | 那不勒斯语 | nea | 否 | | 南恩德贝莱语 | nbl | 否 | | 南非荷兰语 | afr | 是 | | 南索托语 | sot | 否 | | 尼泊尔语 | nep | 是 | | 葡萄牙语 | pt | 是 | | 旁遮普语 | pan | 是 | | 帕皮阿门托语 | pap | 否 | | 普什图语 | pus | 否 | | 齐切瓦语 | nya | 否 | | 契维语 | twi | 否 | | 切罗基语 | chr | 否 | | 日语 | jp | 是 | | 瑞典语 | swe | 是 | | 萨丁尼亚语 | srd | 否 | | 萨摩亚语 | sm | 否 | | 塞尔维亚-克罗地亚语 | sec | 否 | | 塞尔维亚语 | srp | 是 | | 桑海语 | sol | 否 | | 僧伽罗语 | sin | 是 | | 世界语 | epo | 是 | | 书面挪威语 | nob | 是 | | 斯洛伐克语 | sk | 是 | | 斯洛文尼亚语 | slo | 是 | | 斯瓦希里语 | swa | 是 | | 索马里语 | som | 是 | | 塞尔维亚语(西里尔) | src | 否 | | 泰语 | th | 是 | | 土耳其语 | tr | 是 | | 塔吉克语 | tgk | 是 | | 泰米尔语 | tam | 是 | | 他加禄语 | tgl | 是 | | 提格利尼亚语 | tir | 否 | | 泰卢固语 | tel | 是 | | 突尼斯阿拉伯语 | tua | 否 | | 土库曼语 | tuk | 否 | | 乌克兰语 | ukr | 是 | | 瓦隆语 | wln | 是 | | 威尔士语 | wel | 是 | | 文达语 | ven | 否 | | 沃洛夫语 | wol | 否 | | 乌尔都语 | urd | 是 | | 西班牙语 | spa | 是 | | 希伯来语 | heb | 是 | | 希腊语 | el | 是 | | 匈牙利语 | hu | 是 | | 西弗里斯语 | fry | 是 | | 西里西亚语 | sil | 否 | | 希利盖农语 | hil | 否 | | 下索布语 | los | 否 | | 夏威夷语 | haw | 否 | | 新挪威语 | nno | 是 | | 西非书面语 | nqo | 否 | | 信德语 | snd | 否 | | 修纳语 | sna | 否 | | 宿务语 | ceb | 否 | | 叙利亚语 | syr | 否 | | 巽他语 | sun | 否 | | 英语 | en | 是 | | 印地语 | hi | 是 | | 印尼语 | id | 是 | | 意大利语 | it | 是 | | 越南语 | vie | 是 | | 意第绪语 | yid | 否 | | 因特语 | ina | 否 | | 亚齐语 | ach | 否 | | 印古什语 | ing | 否 | | 伊博语 | ibo | 否 | | 伊多语 | ido | 否 | | 约鲁巴语 | yor | 否 | | 亚美尼亚语 | arm | 是 | | 伊努克提图特语 | iku | 否 | | 中文(简体) | zh | 是 | | 中文(繁体) | cht | 是 | | 中文(文言文) | wyw | 是 | | 中文(粤语) | yue | 是 | | 扎扎其语 | zaz | 否 | | 中古法语 | frm | 否 | | 祖鲁语 | zul | 否 | | 爪哇语 | jav | 否 | ================================================ FILE: python/core/components/translate/__init__.py ================================================ # Copyright (c) 2023 Baidu, Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. ================================================ FILE: python/core/components/translate/component.py ================================================ # Copyright (c) 2023 Baidu, Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # -*- coding: utf-8 -*- """ 文本翻译-通用版组件 """ import json from appbuilder.core.message import Message from appbuilder.core.component import Component from appbuilder.core._client import HTTPClient from appbuilder.core._exception import AppBuilderServerException, InvalidRequestArgumentError from appbuilder.core.components.translate.model import * from appbuilder.utils.trace.tracer_wrapper import components_run_trace, components_run_stream_trace class Translation(Component): r""" 文本翻译组件,可支持中、英、日、韩等200+语言互译,100+语种自动检测。 支持语种列表可参照 https://ai.baidu.com/ai-doc/MT/4kqryjku9#%E8%AF%AD%E7%A7%8D%E5%88%97%E8%A1%A8 Examples: .. code-block:: python import appbuilder # 请前往千帆AppBuilder官网创建密钥,流程详见:https://cloud.baidu.com/doc/AppBuilder/s/Olq6grrt6#1%E3%80%81%E5%88%9B%E5%BB%BA%E5%AF%86%E9%92%A5 os.environ["APPBUILDER_TOKEN"] = '...' translate = appbuilder.Translation() resp = translate(appbuilder.Message("你好\n中国"), to_lang="en") # 输出 {'from_lang':'zh', 'to_lang':'en', 'trans_result':[{'src':'你好','dst':'hello'},{'src':'中国','dst':'China'}]} print(resp.content) """ name = "translate" version = "v1" manifests = [ { "name": "translation", "description": "文本翻译通用版工具,会根据指定的目标语言对文本进行翻译,并返回翻译后的文本。", "parameters": { "type": "object", "properties": { "q": { "type": "string", "description": "需要翻译的源文本,文本翻译工具会将该文本翻译成对应的目标语言" }, "to_lang": { "type": "string", "description": "翻译的目标语言类型,'en'表示翻译成英语, 'zh'表示翻译成中文,'yue'表示翻译成粤语,'wyw'表示翻译成文言文," "'jp'表示翻译成日语,'kor'表示翻译成韩语,'fra'表示翻译成法语,'spa'表示翻译成西班牙语,'th'表示翻译成泰语," "'ara'表示翻译成阿拉伯语,'ru'表示翻译成俄语,'pt'表示翻译成葡萄牙语,'de'表示翻译成德语,'it'表示翻译成意大利语," "'el'表示翻译成希腊语,'nl'表示翻译成荷兰语,'pl'表示翻译成波兰语,'bul'表示翻译成保加利亚语,'est'表示翻译成爱沙尼亚语," "'dan'表示翻译成丹麦语, 'fin'表示翻译成芬兰语,'cs'表示翻译成捷克语,'rom'表示翻译成罗马尼亚语,'slo'表示翻译成斯洛文尼亚语," "'swe'表示翻译成瑞典语,'hu'表示翻译成匈牙利语,'cht'表示翻译成繁体中文,'vie'表示翻译成越南语,默认为'en'", "enum": ["en", "zh", "yue", "wyw", "jp", "kor", "fra", "spa", "th", "ara", "ru", "pt", "de", "it", "el", "nl", "pl", "bul", "est", "dan", "fin", "cs", "rom", "slo", "swe", "hu", "cht", "vie"] } }, "required": [ "q" ] } } ] @HTTPClient.check_param @components_run_trace def run(self, message: Message, from_lang: str = "auto", to_lang: str = "en", timeout: float = None, retry: int = 0) -> Message: """ 根据提供的文本以及语种参数执行文本翻译 Args: message (Message): 翻译文本。 from_lang (str): 翻译的源语言。默认为 "auto"。 to_lang (str): 翻译的目标语言。默认为 "en"。 timeout (float, optional): 翻译请求的超时时间。 retry (int, optional): 重试次数。 Returns: Message: 返回的文本翻译结果。 例如,Message(content={'from_lang': 'zh', 'to_lang': 'en', 'trans_result': [{'src': '你好', 'dst': 'hello'}]}) """ req = TranslateRequest() req.q = message.content req.from_lang = from_lang req.to_lang = to_lang result = self._translate(req, timeout=timeout, retry=retry) result_dict = proto.Message.to_dict(result) out = TranslateOutMsg(**result_dict["result"]) return Message(content=out.model_dump()) def _translate(self, request: TranslateRequest, timeout: float = None, retry: int = 0, request_id: str = None) -> TranslateResponse: """ 根据提供的 TranslateRequest 执行文本翻译。 Args: request (TranslateRequest): 翻译请求参数。 timeout (float, optional): 请求超时时间。 retry (int, optional): 重试次数。 Returns: TranslateResponse: 文本翻译结果的响应体。 """ if not request.to_lang or not request.q: raise ValueError("params `to_lang` and `q` must be set") if not request.from_lang: request.from_lang = "auto" request_data = TranslateRequest.to_json(request) if retry != self.http_client.retry.total: self.http_client.retry.total = retry headers = self.http_client.auth_header(request_id) headers['content-type'] = 'application/json;charset=utf-8' url = self.http_client.service_url("/v1/bce/aip/mt/texttrans/v1") response = self.http_client.session.post(url, headers=headers, data=request_data, timeout=timeout) self.http_client.check_response_header(response) data = response.json() request_id = self.http_client.response_request_id(response) self.http_client.check_response_json(data) if "error_code" in data and "error_msg" in data: raise AppBuilderServerException(request_id=request_id, service_err_code=data["error_code"], service_err_message=data["error_msg"]) json_str = json.dumps(data) return TranslateResponse(TranslateResponse.from_json(json_str)) @components_run_stream_trace def tool_eval(self, name: str, streaming: bool, **kwargs): """ 工具函数,用于翻译指定的文本。 Args: name (str): 函数名称,此参数在本函数中未使用。 streaming (bool): 是否流式输出翻译结果。 **kwargs: 关键字参数,可以包含以下参数: - traceid (str, optional): 请求的唯一标识符,默认为None。 - q (str): 待翻译的文本。 - to_lang (str, optional): 目标语言代码,默认为"en"。 Returns: 如果streaming为True,则返回生成器,生成包含翻译结果的字典; 如果streaming为False,则返回包含翻译结果的JSON字符串。 Raises: InvalidRequestArgumentError: 如果未设置参数"q",则抛出此异常。 """ traceid = kwargs.get("traceid") req = TranslateRequest() text = kwargs.get("q", None) if not text: raise InvalidRequestArgumentError("param `q` must be set") req.q = text to_lang = kwargs.get("to_lang", "en") req.to_lang = to_lang results = proto.Message.to_dict(self._translate(req, request_id=traceid))["result"] trans_result = results["trans_result"] res = { "原文本": "\n ".join(item["src"] for item in trans_result), "翻译结果": "\n ".join(item["dst"] for item in trans_result) } res = json.dumps(res, ensure_ascii=False, indent=4) if streaming: yield { "type": "text", "text": res, "visible_scope": 'llm', } yield { "type": "text", "text": "", "visible_scope": 'user', } else: return res ================================================ FILE: python/core/components/translate/model.py ================================================ # Copyright (c) 2023 Baidu, Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # -*- coding: utf-8 -*- """ 文本翻译model """ import proto from typing import List from pydantic import BaseModel class TranslateRequest(proto.Message): """ 文本翻译请求体。 Attributes: from_lang (str): 翻译的源语言。 to_lang (str): 翻译的目标语言。 q (str): 待翻译的文本。 """ from_lang: str = proto.Field( proto.STRING, number=1, json_name="from" ) to_lang: str = proto.Field( proto.STRING, number=2, json_name="to" ) q: str = proto.Field( proto.STRING, number=3, ) class TranslateResponse(proto.Message): """ 文本翻译请求响应体。 Attributes: log_id (int): 文本翻译请求的标识符。 result (TranslateRes): 文本翻译结果。 """ log_id: int = proto.Field( proto.INT64, number=1, ) result: "TranslateRes" = proto.Field( proto.MESSAGE, number=2, message='TranslateRes', ) class TranslateRes(proto.Message): """ 表示翻译请求的结果。 Attributes: from_lang (str): 翻译的源语言。 to_lang (str): 翻译的目标语言。 trans_result (List[TranslateResMeta]): 翻译结果列表。 """ from_lang: str = proto.Field( proto.STRING, number=1, json_name="from" ) to_lang: str = proto.Field( proto.STRING, number=2, json_name="to" ) trans_result: "TranslateResMeta" = proto.RepeatedField( proto.MESSAGE, number=3, message='TranslateResMeta', ) class TranslateResMeta(proto.Message): """ 表示与翻译结果关联的proto结构元数据。 Attributes: dst (str): 翻译后的文本。 src (str): 源文本。 """ dst: str = proto.Field( proto.STRING, number=1, ) src: str = proto.Field( proto.STRING, number=2, ) class TranslateResult(BaseModel): """ 表示与翻译结果关联的pydantic结构元数据。 Attributes: src (str): 源文本。 dst (str): 翻译后的文本。 """ src: str # 源文本 dst: str # 目标文本 class TranslateOutMsg(BaseModel): """ 表示文本翻译输出的pydantic结构消息。 Attributes: from_lang (str): 翻译的源语言。 to_lang (str): 翻译的目标语言。 trans_result (List[TranslateResult]): 一个包含翻译结果的列表。 如果请求参数 `q` 包含 `\n`,则会以分段形式返回翻译结果。 """ from_lang: str to_lang: str trans_result: List[TranslateResult] ================================================ FILE: python/core/components/tree_mind/README.md ================================================ # 树图 (TreeMind) ## 简介 树图(TreeMind)提供智能思维导图制作工具和丰富的模板,支持脑图、逻辑图、树形图、鱼骨图、组织架构图、时间轴、时间线等多种专业格式。 ### 功能介绍 树图(TreeMind)是一款智能思维导图制作工具,它提供了一个用户友好的平台来创建和编辑各种类型的图表。该工具支持多种专业格式,包括脑图、逻辑图、树形图、鱼骨图、组织架构图、时间轴和时间线等,满足不同用户在不同场景下的需求。 ### 特色优势 TreeMind提供丰富的模板,支持多种图表格式,用户可以根据个人需求自由编辑和调整图表。 ### 应用场景 年度总结:用户可以利用TreeMind生成年度总结的思维导图,整理和回顾一年的工作成果和经验教训。 项目管理:在项目管理中,TreeMind可以用来规划项目流程、组织架构和时间线,确保项目按计划进行。 教育和学习:教师和学生可以使用TreeMind来创建课程大纲、学习笔记和复习资料,提高学习效率。 商业策划:商业人士可以利用TreeMind来制定商业策略、市场分析和竞争对手分析等。 会议记录:在会议中,TreeMind可以作为记录工具,帮助整理会议要点和行动计划。 ## 基本用法 下面是文生图的代码示例: ```python import os import appbuilder # 设置环境变量和初始化 # 请前往千帆AppBuilder官网创建密钥,流程详见:https://cloud.baidu.com/doc/AppBuilder/s/Olq6grrt6#1%E3%80%81%E5%88%9B%E5%BB%BA%E5%AF%86%E9%92%A5 os.environ["APPBUILDER_TOKEN"] = "..." treemind = appbuilder.TreeMind() query = "生成一份年度总结的思维导图" msg = appbuilder.Message(query) out = treemind.run(msg) print(out.content) >>> {'result': '思维导图已经为您生成好了,您可以点击'img_link'对应的链接查看,如果您觉得这个思维导图还不够完美,或者您的想法需要更自由地表达,点击'edit_link'对应的链接,对思维导图变形、变色、变内容、甚至可以添加新的元素, 'img_link': 'https://static.shutu.cn/shutu/static/open6e/2024/05/24/dbd67eddec13f3a6a75857b9c6e06d85.jpeg', 'edit_link': 'https://gapi.shutu.cn/ai/edit-mind-url?works_guid=open5ab4af46187ff7c138fcd95de09efe92_bdappbuilder'} ``` 生成的思维导图:
      ![图片url](https://bj.bcebos.com/appbuilder-sdk-components/TreeMind-年终总结思维导图.jpeg) ## 参数说明 ### 鉴权配置 使用组件之前,请首先申请并设置鉴权参数,可参考[组件使用流程](https://cloud.baidu.com/doc/AppBuilder/s/Olq6grrt6#1%E3%80%81%E5%88%9B%E5%BB%BA%E5%AF%86%E9%92%A5)。 ```python # 设置环境中的TOKEN,以下示例略 os.environ["APPBUILDER_TOKEN"] = "bce-YOURTOKEN" ``` ### 初始化参数 无 ### 调用参数 | 参数名称 | 参数类型 | 是否必须 | 描述 | 示例值 | |---------|---------|------|-----------------------------|------------------------------------------------| | message | obj:`Message` | 是 | 输入的消息,用于生成思维导图,这是一个必需的参数 | Message(content={"query": "生成一张年终总结的思维导图"}) | ### 响应参数 | 参数名称 |参数类型 | 描述 | 示例值 | |-------------|--------|------|------| | resp | obj:`Message` | 组件返回结果 | Message(name=msg, content={'result': '生成的思维导图:xxx。思维导图已经为您生成好了,如果您觉得这个思维导图还不够完美,或者您的想法需要更自由地表达,点击编辑按钮,对思维导图变形、变色、变内容、甚至可以添加新的元素,您可以通过这个链接编辑:xxx。', 'img_link': 'xxx', 'edit_link': 'xxx'}, mtype=dict) | ================================================ FILE: python/core/components/tree_mind/__init__.py ================================================ # Copyright (c) 2023 Baidu, Inc. All Rights Reserved. # 版权所有 (c) 2023 百度公司。保留所有权利。 # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. ================================================ FILE: python/core/components/tree_mind/component.py ================================================ # Copyright (c) 2023 Baidu, Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. r"""树图工具""" import json from typing import Dict, List, Optional, Any from appbuilder.core.message import Message from appbuilder.core._client import HTTPClient from appbuilder.core._exception import * from appbuilder.utils.trace.tracer_wrapper import components_run_trace, components_run_stream_trace from appbuilder.core.components.tree_mind.model import TreeMindRequest, TreeMindResponse from appbuilder.core.component import Component class TreeMind(Component): r""" 树图工具,提供智能思维导图制作工具和丰富的模板,支持脑图、逻辑图、树形图、鱼骨图、组织架构图、时间轴、时间线等多种专业格式。 .. code-block:: python import os import requests import appbuilder # 请前往千帆AppBuilder官网创建密钥,流程详见:https://cloud.baidu.com/doc/AppBuilder/s/Olq6grrt6#1%E3%80%81%E5%88%9B%E5%BB%BA%E5%AF%86%E9%92%A5 os.environ["GATEWAY_URL"] = "..." os.environ["APPBUILDER_TOKEN"] = "..." treemind = appbuilder.TreeMind() resp = treemind.run(appbuilder.Message("生成一份年度总结的思维导图"), to_lang="en") print(resp.content) # 输出 {'from_lang':'zh', 'to_lang':'en', 'trans_result':[{'src':'你好','dst':'hello'},{'src':'中国','dst':'China'}]} """ name = "tree_mind" version = "v1" manifests = [ { "name": "tree_mind", "description": "根据用户输入的信息,生成详细智能思维导图、脑图、逻辑图、树形图、鱼骨图、组织架构图、时间轴、时间线等多种专业格式思维导图", "parameters": { "type": "object", "properties": { "query": { "type": "string", "description": "用户想要生成思维导图的内容" }, }, "required": [ "query" ] } } ] def _post(self, query, **kwargs): if query is None or query == "": raise InvalidRequestArgumentError("query is empty!" ) request = TreeMindRequest(query_text=query) headers = self.http_client.auth_header(kwargs.get("traceid")) headers['Content-Type'] = 'application/json' tree_mind_url = self.http_client.service_url("/v1/component/component/query_mind_open") payload = TreeMindRequest.model_dump(request) response = self.http_client.session.post(tree_mind_url, headers=headers, json=payload) self.http_client.check_response_header(response) data = response.text treemind_dict = json.loads(data.split("data:")[-1]) treemind_response = TreeMindResponse(**treemind_dict) jump_link = treemind_response.info.downloadInfo.fileInfo.jumpLink img_link = treemind_response.info.downloadInfo.fileInfo.pic return img_link, jump_link @components_run_stream_trace def tool_eval( self, query, **kwargs, ): r"""调用树图查询接口 Args: query (string): 用户想要生成思维导图的内容 Returns: dict: 返回生成的思维导图的图片链接和跳转链接 """ img_link, jump_link = self._post(query, **kwargs) inst = "你必须遵循指令,输出无需总结,只需要将,“原样输出内容”对应的内容原样输出即可:\n" img_res = f"原样输出内容:![图片url]({img_link})\n" jump_res = f"{query}的思维导图已经为您生成好了,您可以通过这个链接编辑:编辑链接:{jump_link}。" end_talk = "如果您觉得这个思维导图还不够完美,或者您的想法需要更自由地表达,点击编辑按钮,对思维导图变形、变色、变内容、甚至可以添加新的元素,快来试试吧!" result = inst + img_res + jump_res + end_talk urls = [img_link, jump_link] yield { "type": "text", "text": result, "visible_scope": 'llm', } yield { "type": "urls", "text": urls, "visible_scope": 'all', } @HTTPClient.check_param @components_run_trace def run(self, message: Message, **kwargs) -> Message: """运行组件 Args: message (Message): 消息对象 Returns: Message: 返回消息对象 """ query = message.content img_link, jump_link = self._post(query, **kwargs) result = { "result": "思维导图已经为您生成好了,您可以点击'img_link'对应的链接查看,如果您觉得这个思维导图还不够完美,或者您的想法需要更自由地表达,点击'edit_link'对应的链接,对思维导图变形、变色、变内容、甚至可以添加新的元素", "img_link": img_link, "edit_link": jump_link } return Message(content=result) ================================================ FILE: python/core/components/tree_mind/model.py ================================================ # Copyright (c) 2023 Baidu, Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """ 树图model """ import proto from typing import List from pydantic import BaseModel class TreeMindRequest(BaseModel): query_text:str class FileInfo(BaseModel): jumpLink: str jumpText: str pic: str class DownloadInfo(BaseModel): fileInfo: FileInfo endDesc: str class Info(BaseModel): downloadInfo: DownloadInfo class TreeMindResponse(BaseModel): errCode: str errMsg: str time_diff: int info: Info ================================================ FILE: python/core/components/tts/README.md ================================================ # 短文本在线合成(TTS) ## 简介 短文本在线合成组件(TTS)提供高度拟人、流畅自然的语音合成服务,将文本朗读出来,基础音库性价比更高,精品音库听感更逼真。 ### 功能介绍 提供高度拟人、流畅自然的语音合成服务。 ### 特色优势 将文本朗读出来,基础音库性价比更高,精品音库听感更逼真。可实时生成语音输出,几乎没有延迟,更加自然流畅。 ### 应用场景 文本朗读 ## 基本用法 下面是语音合成的代码示例: ```python import os import appbuilder # 请前往千帆AppBuilder官网创建密钥,流程详见:https://cloud.baidu.com/doc/AppBuilder/s/Olq6grrt6#1%E3%80%81%E5%88%9B%E5%BB%BA%E5%AF%86%E9%92%A5 os.environ["APPBUILDER_TOKEN"] = "bce-YOURTOKEN" tts = appbuilder.TTS() cwd = os.getcwd() # 使用baidu-tts模型, 默认返回MP3格式 inp = appbuilder.Message(content={"text": "欢迎使用语音合成"}) out = tts.run(inp) mp3_sample_path = os.path.join(cwd,"sample.mp3") with open(mp3_sample_path, "wb") as f: f.write(out.content["audio_binary"]) print("成功将文本转语音,mp3格式文件已写入:{}".format(mp3_sample_path)) # 使用paddlespeech-tts模型,目前只支持返回WAV格式 wav_sample_path = os.path.join(cwd,"sample.wav") inp = appbuilder.Message(content={"text": "欢迎使用语音合成"}) out = tts.run(inp, model="paddlespeech-tts", audio_type="wav") with open(wav_sample_path, "wb") as f: f.write(out.content["audio_binary"]) print("成功将文本转语音,wav格式文件已写入:{}".format(wav_sample_path)) ``` ## 参数说明 ### 鉴权说明 使用组件之前,请首先申请并设置鉴权参数,可参考[组件使用流程](https://cloud.baidu.com/doc/AppBuilder/s/Olq6grrt6#1%E3%80%81%E5%88%9B%E5%BB%BA%E5%AF%86%E9%92%A5)。 ```python import os os.environ["APPBUILDER_TOKEN"] = "..." ``` ### 初始化参数 无 ### 调用参数 | 参数名称 | 参数类型 | 是否必须 | 描述 | 示例值 | |------------|---------|------|------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|-------------------------------------| | message | String | 是 | 待转成语音的文本 | Message(content={"text": "需合成的文本"}) | | model | String | 否 | 默认是`baidu-tts`模型,可选值:`paddlespeech-tts`、`baidu-tts` | paddlespeech-tts | | speed | Integer | 否 | 语音语速,默认是5中等语速,取值范围在0~15之间,仅当模型为`baidu-tts`参数有效,如果模型为`paddlespeech-tts`,参数自动失效 | 5 | | pitch | Integer | 否 | 语音音调,默认是5中等音调,取值范围在0~15之间,仅当模型为`baidu-tts`参数有效,如果模型为`paddlespeech-tts`,参数自动失效 | 5 | | volume | Integer | 否 | 语音音量,默认是5中等音量,取值范围在0~15之间,,仅当模型为`baidu-tts`参数有效,如果模型为`paddlespeech-tts`,参数自动失效 | 5 | | person | Integer | 否 | 语音人物特征,默认是0(度小美),普通音库可选值包括: 0(度小美)、1(度小宇)、3(度逍遥-基础)、4(度丫丫);精品音库包括:5003(度逍遥-精品)、5118(度小鹿)、106(度博文)、110(度小童)、111(度小萌)、103(度米朵)、5(度小娇);臻品音库包括:4003(度逍遥-情感男声)、4106(度博文-专业男主播)、4115(度小贤-电台男主播)、4119(度小鹿-甜美女声)、4105(度灵儿-清激女声)、4117(度小乔-活泼女声)、4100(度小雯-活力女主播)、4103(度米朵-可爱女声)、4144(度姗姗-娱乐女声)、4278(度小贝-知识女主播)、4143(度清风-配音男声)、4140(度小新-专业女主播)、4129(度小彦-知识男主播)、4149(度星河-广告男声)、4254(度小清-广告女声)、4206(度博文-综艺男声)、4226(南方-电台女主播)。仅当模型为`baidu-tts`参数有效,如果模型为`paddlespeech-tts`,参数自动失效 | 0 | | audio_type | String | 否 | 音频文件格式,如果使用`baidu-tts`模型可选`mp3`, `wav`; 如果使用`paddlespeech-tts`模型非流式返回,参数只能设为`wav`;如果使用`paddlespeech-tts`模型流式返回,参数只能设为`pcm` | wav | | stream | Bool | 否 | 默认是False, 目前`paddlespeech-tts`模型支持流式返回,`baidu-tts`模型不支持流式返回 | False | | retry | Integer | 否 | HTTP重试次数 | 3 | | timeout | Integer | 否 | HTTP超时时间 | 5 | ### 非流式语音响应参数 | 参数名称 | 参数类型 | 描述 | 示例值 | |---------------|--------|--------|---------| | content | Dict | 消息内容 | 无 | | +audio_binary | Bytes | 音频二进制流 | b'语音流' | | +audio_type | String | 音频类型 | wav/mp3 | ### 流式语音响应参数 | 参数名称 | 参数类型 | 描述 | 示例值 | |---------|------------------|----------|-----| | content | Python Generator | 可迭代的二进制流 | 无 | ### 响应示例 ```json { "content": { "audio_binary": "", "audio_type": "mp3" } } ``` ### 错误码 | 错误码 | 描述 | |-----|----| ## 高级用法 ### TTS实时播放语音流 ```python import os import appbuilder import pyaudio # 请前往千帆AppBuilder官网创建密钥,流程详见:https://cloud.baidu.com/doc/AppBuilder/s/Olq6grrt6#1%E3%80%81%E5%88%9B%E5%BB%BA%E5%AF%86%E9%92%A5 os.environ["APPBUILDER_TOKEN"] = "bce-YOURTOKEN" tts = appbuilder.TTS() # 使用paddlespeech-tts模型,目前只支持返回WAV格式 inp = appbuilder.Message(content={"text": """随着科技的迅速发展,教育领域也经历了巨大的变革。科技不仅改变了教学和学习的方式,还扩展了教育的可能性和边界。 从在线课程到交互式学习工具,科技为学生和教师提供了前所未有的资源和机遇。科技使得个性化学习成为可能。通过智能学习系统和适应性学习技术, 教育内容可以根据学生的学习速度和能力进行定制。"""}) # 仅支持model为paddlespeech-tts,audio_type为pcm, stream为True out = tts.run(inp, model="paddlespeech-tts", audio_type="pcm", stream=True) play = pyaudio.PyAudio() stream = play.open(format=play.get_format_from_width(2), channels=1, rate=24000, output=True, frames_per_buffer=2048) # 实时播放语音流 for pcm in out.content: stream.write(pcm) stream.stop_stream() stream.close() ``` ### pcm文件转wav ```python import os import appbuilder import wave # 请前往千帆AppBuilder官网创建密钥,流程详见:https://cloud.baidu.com/doc/AppBuilder/s/Olq6grrt6#1%E3%80%81%E5%88%9B%E5%BB%BA%E5%AF%86%E9%92%A5 os.environ["APPBUILDER_TOKEN"] = "bce-YOURTOKEN" tts = appbuilder.TTS() inp = appbuilder.Message(content={"text": """随着科技的迅速发展,教育领域也经历了巨大的变革。科技不仅改变了教学和学习的方式,还扩展了教育的可能性和边界。 从在线课程到交互式学习工具,科技为学生和教师提供了前所未有的资源和机遇。科技使得个性化学习成为可能。通过智能学习系统和适应性学习技术, 教育内容可以根据学生的学习速度和能力进行定制。"""}) # 仅支持model为paddlespeech-tts,audio_type为pcm, stream为True out = tts.run(inp, model="paddlespeech-tts", audio_type="pcm", stream=True) count = 1 cwd = os.getcwd() for pcm in out.content: wave_sample_path = os.path.join(cwd, "{}.wav".format(count)) wavfile = wave.open(wave_sample_path, 'wb') wavfile.setnchannels(1) wavfile.setsampwidth(2) wavfile.setframerate(24000) wavfile.writeframes(pcm) wavfile.close() print("成功将第{}个pcm语音块转换成wav格式,并将对应文件写入:{}".format(count, wave_sample_path)) count += 1 ``` ## 更新记录和贡献 * 短文本在线合成 (2024-01) * 增加流式能力 (2024-02) ================================================ FILE: python/core/components/tts/__init__.py ================================================ # Copyright (c) 2023 Baidu, Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. ================================================ FILE: python/core/components/tts/component.py ================================================ # Copyright (c) 2023 Baidu, Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. r"""text to speech component.""" import base64 import traceback from typing import Literal from urllib.parse import quote_plus from appbuilder.core.component import Component from appbuilder.core._client import HTTPClient from appbuilder.core.message import Message from appbuilder.core._exception import AppBuilderServerException, InvalidRequestArgumentError from appbuilder.core.components.tts.model import * from appbuilder.utils.trace.tracer_wrapper import components_run_trace, components_run_stream_trace class TTS(Component): r""" 文本转语音组件,即输入一段文本将其转为一段语音 Examples: .. code-block:: python import appbuilder os.environ["APPBUILDER_TOKEN"] = '...' tts = appbuilder.TTS() # 默认使用baidu-tts模型, 默认返回MP3格式 inp = appbuilder.Message(content={"text": "欢迎使用语音合成"}) out = tts.run(inp) with open("sample.mp3", "wb") as f: f.write(out.content["audio_binary"]) # 使用paddlespeech-tts模型,目前只支持返回WAV格式 inp = appbuilder.Message(content={"text": "欢迎使用语音合成"}) out = tts.run(inp, model="paddlespeech-tts", audio_type="wav") with open("sample.wav", "wb") as f: f.write(out.content["audio_binary"]) """ Baidu_TTS = "baidu-tts" PaddleSpeech_TTS = "paddlespeech-tts" def __init__(self, *args, **kwargs): r"""初始化语音识别实例 参数: *args (any, 可选): 位置参数 **kwargs(any, 可选): 关键字参数 返回: 无 """ r""""implement __init__ method""" super().__init__(*args, **kwargs) self.model = "" @HTTPClient.check_param @components_run_trace def run(self, message: Message, model: Literal["baidu-tts", "paddlespeech-tts"] = "baidu-tts", speed: int = 5, pitch: int = 5, volume: int = 5, person: int = 0, audio_type: Literal["mp3", "wav", "pcm"] = "mp3", timeout: float = None, retry: int = 0, stream: bool = False) -> Message: """ 执行文本转语音。 Args: message (Message): 待转为语音的文本。 举例: Message(content={"text": "欢迎使用百度语音"})如果选择baidu-tts模型,text最大文本长度为1024 GBK编码长度,大约为512个中英文字符;如果选择paddlespeech-tts模型, text最大文本长度是510个字符。 model (str, 可选): 默认是`baidu-tts`模型,可设置为`paddlespeech-tts`。 speed (int, 可选): 语音语速,默认是5中等语速,取值范围在0~15之间, 如果选择模型为paddlespeech-tts,参数自动失效。 pitch (int, 可选): 语音音调,默认是5中等音调,取值范围在0~15之间, 如果选择模型为paddlespeech-tts,参数自动失效。 volume (int, 音量): 语音音量,默认是5中等音量,取值范围在0~15之间, 如果选择模型为paddlespeech-tts,参数自动失效。 person (int, 可选): 语音人物特征,默认是0, 可选值包括: 度小宇=1 度小美=0 度逍遥(基础)=3 度丫丫=4 度逍遥(精品)=5003 度小鹿=5118 度博文=106 度小童=110 度小萌=111 度米朵=103 度小娇=5 度逍遥-情感男声=4003 度博文-专业男主播=4106 度小贤-电台男主播=4115 度小鹿-甜美女声=4119 度灵儿-清激女声=4105 度小乔-活泼女声=4117 度小雯-活力女主播=4100 度米朵-可爱女声=4103 度姗姗-娱乐女声=4144 度小贝-知识女主播=4278 度清风-配音男声=4143 度小新-专业女主播=4140 度小彦-知识男主播=4129 度星河-广告男声=4149 度小清-广告女声=4254 度博文-综艺男声=4206 南方-电台女主播=4226, 如果选择模型为paddlespeech-tts,参数自动失效。 audio_type (str, 可选): 音频文件格式,默认是`mp3`, 如果选择`paddlespeech-tts`模型,参数只能设为`wav`。 timeout (float, 可选): HTTP超时时间。 retry (int, 可选): HTTP重试次数。 stream (bool, 可选): 是否以流的形式返回音频数据,默认为False。 Returns: message (Message): 文本转语音结果。举例: Message(content={"audio_binary": b"xxx", "audio_type": "mp3"}) """ if model != self.Baidu_TTS and model != self.PaddleSpeech_TTS: raise InvalidRequestArgumentError( f"unsupported model {model}, expected model in {'baidu-tts', 'paddlespeech-tts'}" ) self.model = model inp = TTSInMsg(**message.content) if len(inp.text) == 0: raise InvalidRequestArgumentError("request format error, text field is empty") if model == self.Baidu_TTS and (stream or audio_type not in ["mp3", "wav"]): raise InvalidRequestArgumentError("Baidu_TTS argument error, expected audio type in {'mp3', 'wav'}") elif model == self.PaddleSpeech_TTS: if stream and audio_type != "pcm": raise InvalidRequestArgumentError("Invalid audio type, expected audio type is {'pcm'}") elif not stream and audio_type != "wav": raise InvalidRequestArgumentError("Invalid audio type, expected audio type is {'wav'}") request = TTSRequest() request.tex = inp.text request.spd = speed request.pit = pitch request.vol = volume request.per = person request.stream = stream if audio_type == "mp3": request.aue = 3 elif audio_type == "wav" or audio_type == "pcm": request.aue = 6 if stream and self.model == self.PaddleSpeech_TTS: return Message(content=self.__synthesis(request=request, stream=True, retry=retry)) else: response = self.__synthesis(request=request, timeout=timeout, retry=retry) out = TTSOutMsg(audio_binary=response.binary, audio_type=audio_type) return Message(content=out.model_dump()) def __synthesis(self, request: TTSRequest, stream: bool = False, timeout: float = None, retry: int = 0 ) -> TTSResponse: r"""调用底层接口进行语音合成 参数: request (obj: `[PaddleTTSRequest, TTSRequest]`) : 语音合成输入参数 返回: response (obj: `TTSResponse`): 语音合成输出参数 """ request.ctp = "1" request.lan = "zh" request.cuid = "1" if self.model == self.Baidu_TTS: request.tex = quote_plus(request.tex) request.validate_baidu_tts() url = self.http_client.service_url("/v1/bce/aip_speech/tts_online") elif self.model == self.PaddleSpeech_TTS: request.tp_project_id = "paddlespeech" request.tp_per_id = "100001" request.validate_paddle_speech_tts() url = self.http_client.service_url("/v1/bce/paddle_speech/text2audio") else: raise ValueError("model '{}' is not supported".format(self.model)) if retry != self.http_client.retry.total: self.http_client.retry.total = retry auth_header = self.http_client.auth_header() if self.model == self.Baidu_TTS: response = self.http_client.session.post(url, data=TTSRequest.to_dict(request), timeout=timeout, headers=auth_header) elif self.model == self.PaddleSpeech_TTS: auth_header = self.http_client.auth_header() auth_header['Content-type'] = "application/json" if not stream: response = self.http_client.session.post(url, json=TTSRequest.to_dict(request), timeout=timeout, headers=auth_header) if stream: response = self.http_client.session.post(url, json=TTSRequest.to_dict(request), timeout=(10, 200), headers=auth_header, stream=True) self.http_client.check_response_header(response) content_type = response.headers.get("Content-Type", "application/json") request_id = self.http_client.response_request_id(response) if content_type.find("application/json") != -1: data = response.json() self.http_client.check_response_json(data) self.__class__.__check_service_error(request_id, data) if not stream: return TTSResponse( binary=response.content, request_id=request_id, aue=request.aue ) else: return _iterate_chunk(request_id, response) @staticmethod def __check_service_error(request_id: str, data: dict): r"""个性化服务response检查 参数: request (dict) : 文本转语音body返回 返回: 无 """ if "err_no" in data or "err_msg" in data or 'sn' in data or 'idx' in data: raise AppBuilderServerException( request_id=request_id, service_err_code=data.get("err_no", 0), service_err_message="{} . {} . {}]". format(data.get("err_msg", ""), data.get("sn", ""), data.get("idx", "")) ) def _iterate_chunk(request_id, response): try: for line in response.iter_lines(): chunk = line.decode('utf-8') if chunk.startswith('data:'): chunk = chunk.replace('data: ', '') yield base64.b64decode(chunk) except Exception as e: raise AppBuilderServerException(request_id=request_id, message=traceback.format_exc()) finally: response.close() ================================================ FILE: python/core/components/tts/model.py ================================================ # Copyright (c) 2023 Baidu, Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. r"""short text to speech model.""" import proto from pydantic import BaseModel class TTSRequest(proto.Message): r"""文本转语音请求参数. 属性: tex (str): 如果选择`baidu-tts`模型,`tex`最大文本长度为1024 GBK编码长度, 如果选择`paddlespeech-tts`模型, `tex`最大文本长度是510个字符. tok (str, 可选): 用户token. cuid (str, 可选): 用户ID. ctp (str, 可选): 用户客户端类型. lan (str): 目前仅支持中英-ZH. spd(int, 可选): 语音语速,默认是5中等语速,取值范围在0~15之间,如果选择模型为paddlespeech-tts,参数自动失效. pit(int, 可选): 语音音调,默认是5中等音调,取值范围在0~15之间,如果选择模型为paddlespeech-tts,参数自动失效. vol(int, 音量): 语音音量,默认是5中等音量,取值范围在0~15之间,如果选择模型为paddlespeech-tts,参数自动失效. per(int, 可选): 语音人物特征,默认是0,可选值包括度小宇=1 度小美=0 度逍遥(基础)=3 度丫丫=4 度逍遥(精品)=5003 度小鹿=5118 度博文=106 度小童=110 度小萌=111 度米朵=103 度小娇=5 度逍遥-情感男声=4003 度博文-专业男主播=4106 度小贤-电台男主播=4115 度小鹿-甜美女声=4119 度灵儿-清激女声=4105 度小乔-活泼女声=4117 度小雯-活力女主播=4100 度米朵-可爱女声=4103 度姗姗-娱乐女声=4144 度小贝-知识女主播=4278 度清风-配音男声=4143 度小新-专业女主播=4140 度小彦-知识男主播=4129 度星河-广告男声=4149 度小清-广告女声=4254 度博文-综艺男声=4206 南方-电台女主播=4226, 如果选择模型为paddlespeech-tts,参数自动失效. aue(int, 可选): 语音格式, 默认是3(mp3) 4(pcm-16k) 5(pcm-8k) 6-wav. tp_project_id(str): paddlespeech-tts项目ID tp_per_id(str): paddlespeech-tts音频ID """ tex: str = proto.Field( proto.STRING, number=1, ) tok: str = proto.Field( proto.STRING, number=2, optional=True, ) cuid: str = proto.Field( proto.STRING, number=3, optional=True, ) ctp: str = proto.Field( proto.STRING, number=4, ) lan: str = proto.Field( proto.STRING, number=5, ) spd: int = proto.Field( proto.INT32, number=6, ) pit: int = proto.Field( proto.INT32, number=7, ) vol: int = proto.Field( proto.INT32, number=8, ) per: int = proto.Field( proto.INT32, number=9, ) aue: int = proto.Field( proto.INT32, number=10, ) tp_project_id: str = proto.Field( proto.STRING, number=11, optional=True, ) tp_per_id: str = proto.Field( proto.STRING, number=12, optional=True, ) stream: bool = proto.Field( proto.BOOL, number=13, optional=True, ) def __validate(self): """检查公共参数""" if len(self.tex) == 0: raise ValueError("tex field must be set") if self.spd < 0 or self.spd > 15: raise ValueError("spd value must in [0,15]") if self.pit < 0 or self.pit > 15: raise ValueError("pit value must in [0,15]") if self.vol < 0 or self.vol > 15: raise ValueError("vol value must in [0,15]") def validate_baidu_tts(self): """检查baidu-tts模型请求参数""" self.__validate() _BAIDU_VALID_PER = {0, 1, 3, 4, 5, 103, 106, 110, 111, 4003, 4106, 4115, 4119, 4105, 4117, 4100, 4103, 4144, 4278, 4143, 4140, 4129, 4149, 4254, 4206, 4226, 5003, 5118} if self.per not in _BAIDU_VALID_PER: raise ValueError( f"per value is illegal, expected in {_BAIDU_VALID_PER}, got {self.per}" ) if self.aue == 0: self.aue = 3 if self.aue not in {3, 4, 5, 6}: raise ValueError(f"aue value is illegal, exepect in {3, 4, 5, 6}, got {self.aue}") def validate_paddle_speech_tts(self): """验证参数是否合法""" self.__validate() if self.aue == 0: self.aue = 6 if self.aue not in {6}: raise ValueError("aue value is illegal, expectd aue value is 6, got{}".format(self.aue)) class TTSResponse(proto.Message): r"""文本转语音返回. 属性: binary (bytes): 语音二进制流. aue (int):语音格式, 3(mp3), 4(pcm-16k), 5(pcm-8k) 6(wav). request_id(str): 请求ID """ binary: bytes = proto.Field( proto.BYTES, number=1 ) aue: int = proto.Field( proto.INT32, number=2, ) request_id: str = proto.Field( proto.STRING, number=3, ) class TTSInMsg(BaseModel): r"""文本转语音输入消息. 属性: text(str): 待转为语音的文本, 如果选择`baidu-tts`模型,最大文本长度为1024 GBK编码长度 如果选择`paddlespeech-tts`模型, 最大文本长度是510个字符. """ text: str class TTSOutMsg(BaseModel): r""" 文本转语音输出消息. 属性: audio_binary(bytes): 语音二进制流. audio_type(AudioType): 语音类型,`mp3`或`wav`. """ audio_binary: bytes audio_type: str ================================================ FILE: python/core/components/v2/__init__.py ================================================ # Copyright (c) 2023 Baidu, Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from .animal_recognize.component import AnimalRecognition from .image_understand.component import ImageUnderstand from .translate.component import Translation from .general_ocr.component import GeneralOCR from .llms.style_rewrite.component import StyleRewrite from .llms.hallucination_detection.component import HallucinationDetection from .qrcode_ocr.component import QRcodeOCR from .handwrite_ocr.component import HandwriteOCR from .mix_card_ocr.component import MixCardOCR from .table_ocr.component import TableOCR from .text_to_image.component import Text2Image from .llms.style_writing.component import StyleWriting from .tree_mind.component import TreeMind from .asr.component import ASR from .object_recognize.component import ObjectRecognition from .llms.similar_question.component import SimilarQuestion from .llms.oral_query_generation.component import OralQueryGeneration from .plant_recognize.component import PlantRecognition from .llms.query_rewrite.component import QueryRewrite from .llms.nl2pandas.component import Nl2pandasComponent from .llms.dialog_summary.component import DialogSummary from .llms.mrc.component import MRC from .llms.is_complex_query.component import IsComplexQuery from .llms.qa_pair_mining.component import QAPairMining from .llms.query_decomposition.component import QueryDecomposition from .llms.tag_extraction.component import TagExtraction __V2_COMPONENTS__ = [ "AnimalRecognition", "ImageUnderstand", "Translation", "GeneralOCR", "StyleRewrite", "HallucinationDetection", "QRcodeOCR", "HandwriteOCR", "MixCardOCR", "TableOCR", "Text2Image", "StyleWriting", "TreeMind", "ASR", "ObjectRecognition", "SimilarQuestion", "OralQueryGeneration", "PlantRecognition", "QueryRewrite", "Nl2pandasComponent", "DialogSummary", "MRC", "IsComplexQuery", "QAPairMining", "QueryDecomposition", "TagExtraction" ] # NOQA ================================================ FILE: python/core/components/v2/animal_recognize/__init__.py ================================================ # Copyright (c) 2023 Baidu, Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. ================================================ FILE: python/core/components/v2/animal_recognize/component.py ================================================ # Copyright (c) 2023 Baidu, Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """animal recognize component.""" import base64 import json from typing import Optional from appbuilder.core.component import Component, ComponentOutput from appbuilder.core.components.animal_recognize.model import * from appbuilder.core.message import Message from appbuilder.core._client import HTTPClient from appbuilder.core._exception import AppBuilderServerException from typing import Generator, Union from appbuilder.utils.trace.tracer_wrapper import components_run_trace, components_run_stream_trace TOP_NUM = 1 BAIKE_NUM = 0 class AnimalRecognition(Component): r""" 用于识别一张图片,即对于输入的一张图片(可正常解码,且长宽比较合适),输出动物识别结果。 Examples: .. code-block:: python import appbuilder # 请前往千帆AppBuilder官网创建密钥,流程详见:https://cloud.baidu.com/doc/AppBuilder/s/Olq6grrt6#1%E3%80%81%E5%88%9B%E5%BB%BA%E5%AF%86%E9%92%A5 os.environ["APPBUILDER_TOKEN"] = '...' animal_recognition = appbuilder.AnimalRecognition() with open("./animal_recognition_test.png", "rb") as f: out = self.component.run(appbuilder.Message(content={"raw_image": f.read()})) print(out.content) """ name = "animal_rec" version = "v1" manifests = [ { "name": "animal_rec", "description": "用于识别图片中动物类别,可识别近八千种动物", "parameters": { "type": "object", "properties": { "img_name": { "type": "string", "description": "待识别图片的文件名" }, "img_url": { "type": "string", "description": "待识别图片的url" } }, "anyOf": [ { "required": [ "img_name" ] }, { "required": [ "img_url" ] } ] } } ] @HTTPClient.check_param @components_run_trace def run(self, message: Message, timeout: float = None, retry: int = 0) -> Message: """ 根据输入消息运行动物识别功能 Args: message (Message): 输入的消息对象,其中应包含需要识别的图像数据或URL timeout (float, optional): 超时时间,单位为秒。默认为None,表示无超时限制。Defaults to None. retry (int, optional): 重试次数。默认为0,表示不重试。Defaults to 0. Returns: Message: 识别结果的消息对象 """ inp = AnimalRecognitionInMsg(**message.content) req = AnimalRecognitionRequest() if inp.raw_image: req.image = base64.b64encode(inp.raw_image) if inp.url: req.url = inp.url req.top_num = 6 req.baike_num = 0 result, _ = self._recognize(req, timeout, retry) result_dict = proto.Message.to_dict(result) out = AnimalRecognitionOutMsg(**result_dict) return Message(content=out.model_dump()) def _recognize( self, request: AnimalRecognitionRequest, timeout: float = None, retry: int = 0, request_id: str = None, ) -> AnimalRecognitionResponse: r"""调用底层接口进行动物识别 参数: request (obj: `AnimalRecognitionRequest`) : 动物识别输入参数 返回: response (obj: `AnimalRecognitionResponse`): 动物识别返回结果 """ if not request.image and not request.url: raise ValueError("request format error, one of image or url must be set") data = AnimalRecognitionRequest.to_dict(request) if self.http_client.retry.total != retry: self.http_client.retry.total = retry headers = self.http_client.auth_header(request_id) headers['content-type'] = 'application/x-www-form-urlencoded' url = self.http_client.service_url("/v1/bce/aip/image-classify/v1/animal") response = self.http_client.session.post(url, headers=headers, data=data, timeout=timeout) self.http_client.check_response_header(response) data = response.json() self.http_client.check_response_json(data) request_id = self.http_client.response_request_id(response) self.__class__._check_service_error(request_id, data) animalRes = AnimalRecognitionResponse.from_json(json.dumps(data)) animalRes.request_id = request_id return animalRes, data @components_run_stream_trace def tool_eval( self, img_name: Optional[str] = "", img_url: Optional[str] = "", **kwargs, ) -> Union[Generator[str, None, None], str]: """ 对图像进行工具评估。 Args: img_name (str): 图像名称。 img_url (str): 图像URL地址。 **kwargs: 其他关键字参数。 Returns: Union[Generator[str, None, None], str]: 返回一个生成器,生成图像识别结果,或者返回图像识别结果的字符串。 """ if not img_name and not img_url: raise ValueError("img_name or img_url is required") traceid = kwargs.get("_sys_traceid", "") file_urls = kwargs.get("_sys_file_urls", {}) yield from self._recognize_w_post_process(img_name, img_url, file_urls, request_id=traceid) def _recognize_w_post_process(self, img_name, img_url, file_urls, request_id=None) -> str: # type: ignore r"""调底层接口对图片或图片url进行动物识别,并返回类别及其置信度 Args: img_name (str): 图片文件名 img_url (str): 图片url file_urls (dict): 文件名与对应文件url的映射 Returns: str: 动物识别结果,包括识别出的动物类别和相应的置信度信息 """ req = AnimalRecognitionRequest() if img_name in file_urls: req.url = file_urls[img_name] if img_url: if img_url in file_urls: img_url = file_urls[img_url] req.url = img_url req.top_num = TOP_NUM req.baike_num = BAIKE_NUM result, raw_data = self._recognize(req, request_id=request_id) result_dict = proto.Message.to_dict(result) rec_res = "模型识别结果为:\n" for rec_info in result_dict['result']: rec_res += "类别: {} 置信度: {}\n".format(rec_info['name'], rec_info['score']) output = self.create_output(type="text", text=rec_res, raw_data=raw_data) yield output @staticmethod def _check_service_error(request_id: str, data: dict): r"""个性化服务response参数检查 参数: request_id (str) : 请求ID data (dict) : 动物识别body返回 返回: 无 """ if "error_code" in data or "error_msg" in data: raise AppBuilderServerException( request_id=request_id, service_err_code=data.get("error_code"), service_err_message=data.get("error_msg") ) ================================================ FILE: python/core/components/v2/asr/__init__.py ================================================ # Copyright (c) 2023 Baidu, Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. ================================================ FILE: python/core/components/v2/asr/component.py ================================================ # Copyright (c) 2023 Baidu, Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. r"""ASR component. """ import os import uuid import json import requests import tempfile from urllib.parse import urlparse from typing import Optional from appbuilder.core.component import Component from appbuilder.core.message import Message from appbuilder.core._exception import AppBuilderServerException, InvalidRequestArgumentError from appbuilder.core._client import HTTPClient from appbuilder.core.components.asr.model import ShortSpeechRecognitionRequest, ShortSpeechRecognitionResponse, \ ASRInMsg, ASROutMsg from appbuilder.utils.trace.tracer_wrapper import components_run_trace, components_run_stream_trace import logging DEFAULT_AUDIO_MAX_DURATION = 55 * 1000 # 55s # 参考短语音极速版API(https://ai.baidu.com/ai-doc/SPEECH/Jlbxdezuf) DEFAULT_FRAME_RATE = 16000 DEV_PID = "80001" class ASR(Component): r""" ASR组件,即对于输入的语音文件,输出语音识别结果 Examples: .. code-block:: python import appbuilder asr = appbuilder.ASR() os.environ["APPBUILDER_TOKEN"] = '...' with open("xxxx.pcm", "rb") as f: audio_data = f.read() content_data = {"audio_format": "pcm", "raw_audio": audio_data, "rate": 16000} msg = appbuilder.Message(content_data) out = asr.run(msg) print(out.content) # eg: {"result": ["北京科技馆。"]} """ name = "asr" version = "v1" manifests = [ { "name": "asr", "description": "对于输入的语音文件进行识别,输出语音识别结果。", "parameters": { "type": "object", "properties": { "file_url": { "type": "string", "description": "输入语音文件的url,根据url获取到语音文件" }, "file_name": { "type": "string", "description": "待识别语音文件名,用于生成获取语音的url" }, "file_type": { "type": "string", "description": "语音文件类型,支持pcm/wav/amr/m4a", "enum": ["pcm", "wav", "amr", "m4a"] } }, "anyOf": [ { "required": [ "file_url" ] }, { "required": [ "file_name" ] } ] } } ] @HTTPClient.check_param @components_run_trace def run(self, message: Message, audio_format: str = "pcm", rate: int = 16000, timeout: float = None, retry: int = 0, **kwargs) -> Message: r""" 执行语音识别操作,并返回识别结果。 Args: message (Message): 输入消息对象,包含待识别的音频数据。该参数为必需项,格式如:Message(content={"raw_audio": b"..."})。 audio_format (str, optional): 音频文件格式,支持pcm/wav/amr/m4a,不区分大小写,推荐使用pcm格式。默认为"pcm"。 rate (int, optional): 音频采样率,固定为16000。默认为16000。 timeout (float, optional): HTTP请求超时时间。默认为None。 retry (int, optional): HTTP请求重试次数。默认为0。 Returns: Message: 语音识别结果,格式如:Message(content={"result": ["识别结果"]})。 """ inp = ASRInMsg(**message.content) request = ShortSpeechRecognitionRequest() request.format = audio_format request.rate = rate request.cuid = str(uuid.uuid4()) request.dev_pid = DEV_PID request.speech = inp.raw_audio traceid = kwargs.get("_sys_traceid", "") response, _ = self._recognize(request, timeout, retry, request_id=traceid) out = ASROutMsg(result=list(response.result)) return Message(content=out.model_dump()) def _recognize( self, request: ShortSpeechRecognitionRequest, timeout: float = None, retry: int = 0, request_id: str = None, ) -> ShortSpeechRecognitionResponse: """ 使用给定的输入并返回语音识别的结果。 参数: request (obj:`ShortSpeechRecognitionRequest`): 输入请求,这是一个必需的参数。 timeout (float, 可选): 请求的超时时间。 retry (int, 可选): 请求的重试次数。 返回: obj:`ShortSpeechRecognitionResponse`: 接口返回的输出消息。 """ ContentType = "audio/" + request.format + ";rate=" + str(request.rate) headers = self.http_client.auth_header(request_id) headers['content-type'] = ContentType params = { 'dev_pid': request.dev_pid, 'cuid': request.cuid } if retry != self.http_client.retry.total: self.http_client.retry.total = retry response = self.http_client.session.post(self.http_client.service_url("/v1/bce/aip_speech/asrpro"), params=params, headers=headers, data=request.speech, timeout=timeout) logging.info('Sending POST request with params: %s, headers: %s, data: %s', params, headers, request.speech) self.http_client.check_response_header(response) data = response.json() self.http_client.check_response_json(data) request_id = self.http_client.response_request_id(response) self.__class__._check_service_error(request_id, data) response = ShortSpeechRecognitionResponse.from_json(payload=json.dumps(data)) response.request_id = request_id return response, data @staticmethod def _check_service_error(request_id: str, data: dict): r"""个性化服务response参数检查 参数: request (dict) : 短语音识别body返回 返回: 无 """ if "err_no" in data and "err_msg" in data: if data["err_no"] != 0: raise AppBuilderServerException( request_id=request_id, service_err_code=data["err_no"], service_err_message=data["err_msg"] ) @components_run_stream_trace def tool_eval(self, file_url: Optional[str] = '', file_name: Optional[str] = '', file_type: Optional[str] = '', **kwargs): """ 执行语音识别操作,并返回识别结果 Args: file_url (str, optional): 文件URL。默认为空字符串。 file_name (str, optional): 文件名。默认为空字符串。 file_type (str, optional): 文件类型。默认为空字符串。 **kwargs: 其他关键字参数。 Returns: Generator: 生成器,用于生成输出对象。 Raises: InvalidRequestArgumentError: 请求格式错误。 """ if not file_url: file_urls = kwargs.get("_sys_file_urls", {}) file_path = file_name if not file_path: raise InvalidRequestArgumentError("request format error, file name is not set") file_name = os.path.basename(file_path) file_url = file_urls.get(file_name, None) if not file_url: raise InvalidRequestArgumentError( f"request format error, file {file_url} url does not exist" ) _, file_type = os.path.splitext(os.path.basename(urlparse(file_url).path)) file_type = file_type.strip('.') audio_file = tempfile.NamedTemporaryFile("wb", suffix=file_type) audio_file.write(requests.get(file_url).content) raw_audios = _convert(audio_file.name, file_type) text = "" for raw_audio in raw_audios: request = ShortSpeechRecognitionRequest() request.format = file_type request.rate = DEFAULT_FRAME_RATE request.cuid = str(uuid.uuid4()) request.dev_pid = DEV_PID request.speech = raw_audio traceid = kwargs.get("_sys_traceid", "") response, raw_data = self._recognize(request, request_id=traceid) text += "".join(list(response.result)) results = {"识别结果": text} audio_file.close() res = json.dumps(results, ensure_ascii=False, indent=4) yield self.create_output(type='text', text=res, raw_data=raw_data, visible_scope="llm") yield self.create_output(type='text', text="", raw_data=raw_data, visible_scope="user") def _convert(path, file_type): from pydub import AudioSegment if file_type.lower() == "mp3": audio = AudioSegment.from_mp3(path) elif file_type.lower() == "wav": audio = AudioSegment.from_wav(path) # 如果是pcm格式,则直接读取并返回 elif file_type.lower() == "pcm": with open(path, "rb") as f: return [f.read()] else: # pydub自动检测音频类型 audio = AudioSegment.from_wav(path) # 如果取样率为16000且时长小于60s,则直接读取音频并返回 if (audio.frame_rate == DEFAULT_FRAME_RATE and audio.frame_count() * 1000 / audio.frame_rate < DEFAULT_AUDIO_MAX_DURATION): with open(path, "rb") as f: return [f.read()] audio = audio.set_frame_rate(DEFAULT_FRAME_RATE) total_milliseconds = int(audio.frame_count() * 1000 / audio.frame_rate) start = 0 raw_audios = [] while start < total_milliseconds: end = start + DEFAULT_AUDIO_MAX_DURATION if start + DEFAULT_AUDIO_MAX_DURATION > total_milliseconds: end = total_milliseconds audio_seg = audio[start:end] audio_seg_file = tempfile.NamedTemporaryFile("wb", suffix="wav") try: audio_seg.export(audio_seg_file.name, format="wav") with open(audio_seg_file.name, "rb") as f: raw_audios.append(f.read()) finally: audio_seg_file.close() start = end return raw_audios ================================================ FILE: python/core/components/v2/general_ocr/__init__.py ================================================ # Copyright (c) 2024 Baidu, Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. ================================================ FILE: python/core/components/v2/general_ocr/component.py ================================================ # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. r"""general ocr component.""" import base64 import json import logging import requests import os.path from typing import Optional from appbuilder.core._client import HTTPClient from appbuilder.core._exception import AppBuilderServerException, InvalidRequestArgumentError from appbuilder.core.component import Component from appbuilder.core.components.general_ocr.model import * from appbuilder.core.message import Message from appbuilder.core.constants import COMPONENT_SUPPORT_FILE_NUMBER from appbuilder.utils.trace.tracer_wrapper import components_run_trace, components_run_stream_trace class GeneralOCR(Component): r""" 提供通用文字识别能力,在通用文字识别的基础上,提供更高精度的识别服务,支持更多语种识别(丹麦语、荷兰语、马来语、 瑞典语、印尼语、波兰语、罗马尼亚语、土耳其语、希腊语、匈牙利语、泰语、越语、阿拉伯语、印地语及部分中国少数民族语言), 并将字库从1w+扩展到2w+,能识别所有常用字和大部分生僻字。 Examples: .. code-block:: python import appbuilder # 请前往千帆AppBuilder官网创建密钥,流程详见:https://cloud.baidu.com/doc/AppBuilder/s/Olq6grrt6#1%E3%80%81%E5%88%9B%E5%BB%BA%E5%AF%86%E9%92%A5 os.environ["APPBUILDER_TOKEN"] = '...' general_ocr = appbuilder.GeneralOCR() with open("./general_ocr_test.png", "rb") as f: out = general_ocr.run(appbuilder.Message(content={"raw_image": f.read()})) print(out.content) """ name = "general_ocr" version = "v1" manifests = [ { "name": "general_ocr", "description": "提供更高精度的通用文字识别能力,能够识别图片中的文字,不支持html后缀文件的输入", "parameters": { "type": "object", "properties": { "img_urls": { "type": "array", "description": "待识别图片的url,根据该url能够获取图片" }, "img_names": { "type": "array", "description": "待识别图片的文件名,用于生成图片url" }, "language_type": { "type": "string", "description": "识别语言类型,'CHN_ENG'为中英文混合,'ENG'为英文, 'JAP'为日语,'KOR'为韩语,'FRE'为法语,'SPA'为西班牙语,'POR'为葡萄牙语," "'GER'为德语,'ITA'为意大利语,'RUS'为俄语,'DAN'为丹麦语,'DUT'为荷兰语,'MAL'为马来语,'SWE'为瑞典语,'IND'为印尼语,'POL'为波兰语,'ROM'为罗马尼亚语," "'TUR'为土耳其语,'GRE'为希腊语,'HUN'为匈牙利语,'THA'为泰语,'VIE'为越南语,'ARA'为阿拉伯语,'HIN'为印地语,默认为'CHN_ENG'", "enum": ['CHN_ENG', 'ENG', 'JAP', 'KOR', 'FRE', 'SPA', 'POR', 'GER', 'ITA', 'RUS', 'DAN', 'DUT', 'MAL', 'SWE', 'IND', 'POL', 'ROM', 'TUR', 'GRE', 'HUN', 'THA', 'VIE', 'ARA', 'HIN'], }, "pdf_urls": { "type": "array", "description": "待识别pdf的url,根据该url能够获取pdf文件" }, "pdf_names": { "type": "array", "description": "待识别pdf的文件名,用于生成pdf url" }, "pdf_file_num": { "type": "object", "description": "需要识别的PDF文件的对应页码,key为pdf_names中的文件名,value为对应的页码,当 pdf_file 参数有效时,识别传入页码的对应页面内容,若不传入,则默认识别第 1 页", "additionalProperties": { "type": "string" }, "default": {} }, "detect_direction": { "type": "string", "description": "是否检测图像朝向,朝向是指输入图像是正常方向、逆时针旋转90/180/270度。可选值包括: true-检测朝向; false-不检测朝向" "默认不检测", "default": "false" }, "multidirectional_recognize": { "type": "string", "description": "是否开启行级别的多方向文字识别,可选值包括: true-识别, false-不识别; 若图内有不同方向的文字时,建议将此参数设置为“true”" "默认开启", "default": "true" } }, "anyOf": [ { "required": [ "img_urls", ] }, { "required": [ "img_names" ] }, { "required": [ "pdf_urls", ] }, { "required": [ "pdf_names", ] } ] } } ] @HTTPClient.check_param @components_run_trace def run(self, message: Message, timeout: float = None, retry: int = 0, language_type: str = 'CHN_ENG') -> Message: """ 在通用文字识别的基础上,提供更高精度的识别服务,支持更多语种识别 Args: message (Message): 包含识别任务的输入信息的消息对象。 timeout (float, optional): 超时时间,单位秒。默认为None,表示不设置超时。 retry (int, optional): 重试次数。默认为0,表示不重试。 language_type (str, optional): 识别语言类型,可选值为'CHN_ENG'(中英文)和'CHN'(中文)。默认为'CHN_ENG'。 Returns: Message: 包含识别结果的消息对象。 """ inp = GeneralOCRInMsg(**message.content) request = GeneralOCRRequest() if inp.image_base64: request.image = (inp.image_base64) elif inp.image_url: request.url = inp.image_url elif inp.pdf_base64: request.pdf_file = inp.pdf_base64 elif inp.pdf_url: raw_pdf = requests.get(inp.pdf_url).content pdf_base64 = base64.b64encode(raw_pdf) request.pdf_file = pdf_base64 request.pdf_file_num = inp.pdf_file_num request.detect_direction = inp.detect_direction request.multidirectional_recognize = inp.multidirectional_recognize request.language_type = language_type result, _ = self._recognize(request, timeout, retry) result_dict = proto.Message.to_dict(result) out = GeneralOCROutMsg(**result_dict) return Message(content=out.model_dump()) def _recognize( self, request: GeneralOCRRequest, timeout: float = None, retry: int = 0, request_id: str = None, ) -> GeneralOCRResponse: r"""调用底层接口进行通用文字识别 参数: request (obj: `GeneralOCRRequest`) : 通用文字识别输入参数 返回: response (obj: `GeneralOCRResponse`): 通用文字识别返回结果 """ if not request.image and not request.url and not request.pdf_file and not request.ofd_file: raise ValueError( "request format error, one of image or url or must pdf_file or ofd_file be set") data = GeneralOCRRequest.to_dict(request) if self.http_client.retry.total != retry: self.http_client.retry.total = retry headers = self.http_client.auth_header(request_id) headers['content-type'] = 'application/x-www-form-urlencoded' url = self.http_client.service_url("/v1/bce/aip/ocr/v1/accurate_basic") response = self.http_client.session.post( url, headers=headers, data=data, timeout=timeout) self.http_client.check_response_header(response) data = response.json() self.http_client.check_response_json(data) request_id = self.http_client.response_request_id(response) self.__class__._check_service_error(request_id, data) ocr_response = GeneralOCRResponse.from_json(payload=json.dumps(data)) ocr_response.request_id = request_id return ocr_response, data @staticmethod def _check_service_error(request_id: str, data: dict): r"""个性化服务response参数检查 参数: request (dict) : 通用文字识别body返回 返回: 无 """ if "error_code" in data or "error_msg" in data: raise AppBuilderServerException( request_id=request_id, service_err_code=data.get("error_code"), service_err_message=data.get("error_msg") ) @components_run_stream_trace def tool_eval( self, img_names: Optional[list] = [], img_urls: Optional[list] = [], pdf_names: Optional[list] = [], pdf_urls: Optional[list] = [], pdf_file_num: Optional[dict] = {}, language_type: Optional[str] = 'CHN_ENG', detect_direction: Optional[str] = "false", multidirectional_recognize: Optional[str] = "true", **kwargs ): """ 对图片或PDF文件中的文字进行识别并返回结果。 Args: img_names (list): 图片文件名列表,用于指定要识别的图片文件。 img_urls (list): 图片URL地址列表,用于指定要识别的图片URL。 pdf_names (list): PDF文件名列表,用于指定要识别的PDF文件。 pdf_urls (list): PDF URL地址列表,用于指定要识别的PDF URL。 pdf_file_num (dict): PDF文件页码字典,key为pdf_names中的文件名,value为对应的页码。 例如:{"document1.pdf": 1, "document2.pdf": 3} 表示识别document1.pdf的第1页, document2.pdf的第3页。如果未指定页码,默认为第1页。 language_type (str): 识别语言类型,可选值为'CHN_ENG'(中英文混合)、'ENG'(英文)、 'JAP'(日语)、'KOR'(韩语)等,默认为'CHN_ENG'。 detect_direction (str): 是否检测图像朝向,可选值为'true'(检测)或'false'(不检测), 朝向是指输入图像是正常方向、逆时针旋转90/180/270度,默认为'false'。 multidirectional_recognize (str): 是否开启行级别的多方向文字识别,可选值为'true'(识别) 或'false'(不识别),若图内有不同方向的文字时,建议将此参数 设置为'true',默认为'true'。 **kwargs: 其他参数,目前支持以下参数: _sys_traceid (str): 系统追踪ID,用于跟踪请求。 _sys_file_urls (dict): 文件URL字典,key为文件名,value为文件URL。 Returns: Generator: 生成器,每次生成一个包含识别结果的Output对象。 对于图片文件,返回格式为:{"图片文件名识别结果": "识别的文字内容"} 对于PDF文件,返回格式为:{"PDF文件名识别结果": "识别的文字内容"} Raises: InvalidRequestArgumentError: 如果请求格式错误或文件URL不存在,将抛出此异常。 Examples: # 识别单个图片 img_names = ["test.jpg"] img_urls = ["http://example.com/test.jpg"] # 识别多个PDF文件的不同页码 pdf_names = ["doc1.pdf", "doc2.pdf"] pdf_urls = ["http://example.com/doc1.pdf", "http://example.com/doc2.pdf"] pdf_file_num = {"doc1.pdf": 1, "doc2.pdf": 3} """ traceid = kwargs.get("_sys_traceid", "") if not img_names and not img_urls and not pdf_names and not pdf_urls: raise InvalidRequestArgumentError(request_id=traceid, message="img_names\img_urls\pdf_names\pdf_urls can not both be empty") sys_file_urls = kwargs.get("_sys_file_urls", {}) support_pdf_type = ["pdf"] support_img_type = ["png", "jpg", "jpeg", "webp", "heic", "tif", "tiff", "dcm", "mha", "nii.gz"] img_map = {} pdf_map = {} unsupported_files = [] unknown_files = [] img_names = [os.path.basename(name) for name in img_names] pdf_names = [os.path.basename(name) for name in pdf_names] for img_name in img_names: if len(img_map) >= COMPONENT_SUPPORT_FILE_NUMBER: break file_type = img_name.split(".")[-1].lower() if img_name in sys_file_urls: if file_type in support_img_type: img_map[img_name] = sys_file_urls.get(img_name, "") else: unsupported_files.append(img_name) else: unknown_files.append(img_name) for pdf_name in pdf_names: if len(img_map) + len(pdf_map) >= 10: break file_type = pdf_name.split(".")[-1].lower() if pdf_name in sys_file_urls: if file_type in support_pdf_type: pdf_map[pdf_name] = {"url": sys_file_urls.get(pdf_name, ""), "page_num": pdf_file_num.get(pdf_name, "1")} else: unsupported_files.append(pdf_name) else: unknown_files.append(pdf_name) for img_url in img_urls: if len(img_map) + len(pdf_map) >= 10: break if img_url in list(sys_file_urls.values()): continue file_name = img_url.split("/")[-1].split("?")[0] file_type = file_name.split(".")[-1].lower() if file_type in support_img_type: img_map[img_url] = img_url else: unsupported_files.append(img_url) for pdf_url in pdf_urls: if len(img_map) + len(pdf_map) >= 10: break if pdf_url in list(sys_file_urls.values()): continue file_name = pdf_url.split("/")[-1].split("?")[0] file_type = file_name.split(".")[-1].lower() if file_type in support_pdf_type: pdf_map[pdf_url] = {"url": pdf_url, "page_num": pdf_file_num.get(file_name, "1")} else: unsupported_files.append(pdf_url) if not img_map and not pdf_map: raise InvalidRequestArgumentError( f"request format error, file url does not exist") if img_map: for img_name, img_url in img_map.items(): try: req = GeneralOCRRequest(url=img_url) req.detect_direction = detect_direction req.language_type = language_type req.multidirectional_recognize = multidirectional_recognize result_response, raw_data = self._recognize(req, request_id=traceid) result = proto.Message.to_dict(result_response) results = { f"{img_name}": " \n".join(item["words"] for item in result["words_result"]) } res = json.dumps(results, ensure_ascii=False) yield self.create_output(type="text", text=res, raw_data=raw_data, visible_scope="llm") yield self.create_output(type="text", text="", raw_data=raw_data, visible_scope="user") except Exception as e: logging.warning(f"{img_name} ocr failed with exception: {e}") continue if pdf_map: for pdf_name, pdf_info in pdf_map.items(): try: pdf_url = pdf_info.get("url", None) pdf_file_num = pdf_info.get("page_num", "1") raw_pdf = requests.get(pdf_url).content pdf_base64 = base64.b64encode(raw_pdf) req = GeneralOCRRequest(pdf_file=pdf_base64, pdf_file_num=pdf_file_num) req.detect_direction = detect_direction req.language_type = language_type req.multidirectional_recognize = multidirectional_recognize result_response, raw_data = self._recognize(req, request_id=traceid) result = proto.Message.to_dict(result_response) results = { f"{pdf_name}": " \n".join(item["words"] for item in result["words_result"]) } res = json.dumps(results, ensure_ascii=False) yield self.create_output(type="text", text=res, raw_data=raw_data, visible_scope="llm") yield self.create_output(type="text", text="", raw_data=raw_data, visible_scope="user") except Exception as e: logging.warning(f"{pdf_name} ocr failed with exception: {e}") continue for file_name in unknown_files: results = { f"{file_name}": "无法获取url,请确认是否上传成功" } res = json.dumps(results, ensure_ascii=False) llm_result = self.create_output( type = "text", visible_scope= "llm", text=res, name="llm_text" ) yield llm_result user_result = self.create_output( type = "text", visible_scope= "user", text="", name="user_text" ) yield user_result for file_name in unsupported_files: results = { f"{file_name}": "不支持的文件类型,请确认是否为图片或者pdf文件" } res = json.dumps(results, ensure_ascii=False) llm_result = self.create_output( type = "text", visible_scope= "llm", text=res, name="llm_text" ) yield llm_result user_result = self.create_output( type = "text", visible_scope= "user", text="", name="user_text" ) yield user_result ================================================ FILE: python/core/components/v2/handwrite_ocr/__init__.py ================================================ # Copyright (c) 2023 Baidu, Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. ================================================ FILE: python/core/components/v2/handwrite_ocr/component.py ================================================ # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. r"""手写文字识别组件""" import base64 import json import logging from typing import Optional from appbuilder.core._exception import AppBuilderServerException, InvalidRequestArgumentError from appbuilder.core.component import Component from appbuilder.core.components.v2.handwrite_ocr.model import * from appbuilder.core.message import Message from appbuilder.core._client import HTTPClient from appbuilder.core import utils from appbuilder.core.constants import COMPONENT_SUPPORT_FILE_NUMBER from appbuilder.utils.trace.tracer_wrapper import components_run_trace, components_run_stream_trace class HandwriteOCR(Component): r""" 手写文字识别组件 Examples: .. code-block:: python import os import appbuilder os.environ["GATEWAY_URL"] = "..." os.environ["APPBUILDER_TOKEN"] = "..." # 从BOS存储读取样例文件 image_url="https://bj.bcebos.com/v1/appbuilder/test_handwrite_ocr.jpg?authorization=bce-auth-v1%2FALTAKGa8m4qCUasgoljdEDAzLm%2F2024-01-23T11%3A58%3A09Z%2F-1%2Fhost%2F677f93445fb65157bee11cd492ce213d5c56e7a41827e45ce7e32b083d195c8b" # 输入参数为一张图片 inp = appbuilder.Message(content={"url": image_url}) # 进行植物识别 handwrite_ocr = HandwriteOCR() out = handwrite_ocr.run(inp) # 打印识别结果 print(out.content) """ name = "handwriting_ocr" version = "v1" manifests = [ { "name": "handwriting_ocr", "description": "需要对图片中手写体文字进行识别时,使用该工具,不支持PDF文件,如果用户没有提供图片文件,应引导用户提供图片,而不是尝试使用该工具", "parameters": { "type": "object", "properties": { "file_names": { "type": "array", "items": { "type": "string" }, "description": "待识别文件的文件名" }, "file_urls": { "type": "array", "items": { "type": "string" }, "description": "待识别文件的url" } }, "anyOf": [ { "required": [ "file_names" ] }, { "required": [ "file_urls" ] } ] } } ] @HTTPClient.check_param @components_run_trace def run(self, message: Message, timeout: float = None, retry: int = 0) -> Message: r""" 输入图片并识别其中的文字 Args: message (Message): 输入图片或图片url下载地址用于执行识别操作.例如: Message(content={"raw_image": b"..."}) 或 Message(content={"url": "https://image/download/url"}). timeout (float, optional): HTTP超时时间. 默认为None. retry (int, optional): HTTP重试次数. 默认为0. Returns: Message: 手写体模型识别结果. """ inp = HandwriteOCRInMsg(**message.content) request = HandwriteOCRRequest() if inp.url: request.url = inp.url if inp.raw_image: request.image = base64.b64encode(inp.raw_image) request.recognize_granularity = "big" request.probability = "false" request.detect_direction = "true" request.detect_alteration = "true" response = self._recognize(request, timeout, retry) out = HandwriteOCROutMsg() out.direction = response.direction [out.contents.append( Content(text=w.words, position=Position( left=w.location.left, top=w.location.top, width=w.location.width, height=w.location.height ))) for w in response.words_result] return Message(content=out.model_dump()) @components_run_stream_trace def tool_eval(self, file_names: Optional[list] = [], file_urls: Optional[list] = [], **kwargs): """ 工具评估函数 Args: file_names (Optional[list]): 待识别文件的文件名列表 **kwargs: 其他参数 Raises: InvalidRequestArgumentError: 请求格式错误,文件url不存在 Yields: Generator[Output]: 生成器,每次迭代产生一个输出对象 """ if not file_names and not file_urls: raise InvalidRequestArgumentError(request_id=traceid, message="file_names and file_urls cannot both be empty") supported_file_type = ["png", "jpg", "jpeg", "webp", "heic", "tif", "tiff", "dcm", "mha", "nii.gz"] traceid = kwargs.get("_sys_traceid", "") sys_file_urls = kwargs.get('_sys_file_urls', {}) available_img_urls = {} unsupported_files = [] unknown_file_name = [] if file_names: for file_name in file_names: if len(available_img_urls) >= COMPONENT_SUPPORT_FILE_NUMBER: break file_type = file_name.split(".")[-1].lower() if file_name in sys_file_urls: if file_type in supported_file_type: available_img_urls[file_name] = sys_file_urls.get(file_name, "") else: #不支持的文件类型 unsupported_files.append(file_name) else: #url未知 unknown_file_name.append(file_name) for img_url in file_urls: if len(available_img_urls) >= COMPONENT_SUPPORT_FILE_NUMBER: break if img_url in list(sys_file_urls.values()): #只考虑用户手动传的file_url continue file_name = img_url.split("/")[-1].split("?")[0] file_type = file_name.split(".")[-1].lower() if file_type in supported_file_type: available_img_urls[img_url] = img_url else: #不支持的文件类型 unsupported_files.append(img_url) for file_name, file_url in available_img_urls.items(): try: req = HandwriteOCRRequest() req.url = file_url req.recognize_granularity = "big" req.probability = "false" req.detect_direction = "true" req.detect_alteration = "true" response = self._recognize(req, request_id=traceid) text = "".join([w.words for w in response.words_result]) results = { file_name: text } res = json.dumps(results, ensure_ascii=False) llm_result = self.create_output( type = "text", visible_scope= "llm", text=res, name="llm_text" ) yield llm_result user_result = self.create_output( type = "text", visible_scope= "user", text="", name="user_text" ) yield user_result except Exception as e: logging.warning(f"{file_name} ocr failed with exception: {e}") continue for file_name in unknown_file_name: results = { file_name: "无法获取url,请确认是否上传成功" } res = json.dumps(results, ensure_ascii=False) llm_result = self.create_output( type = "text", visible_scope= "llm", text=res, name="llm_text" ) yield llm_result user_result = self.create_output( type = "text", visible_scope= "user", text="", name="user_text" ) yield user_result for file_name in unsupported_files: results = { file_name: "不支持的文件类型,请确认是否为图片" } res = json.dumps(results, ensure_ascii=False) llm_result = self.create_output( type = "text", visible_scope= "llm", text=res, name="llm_text" ) yield llm_result user_result = self.create_output( type = "text", visible_scope= "user", text="", name="user_text" ) yield user_result def _recognize( self, request: HandwriteOCRRequest, timeout: float = None, retry: int = 0, request_id: str = None, ) -> HandwriteOCRResponse: r"""调用底层接口进行通用文字识别 参数: request (obj: `HandwriteOCRRequest`) : 通用文字识别输入参数 返回: response (obj: `HandwriteOCRResponse`): 通用文字识别返回结果 """ if not request.image and not request.url: raise ValueError("request format error, one of image or url must be set") data = request.model_dump() if self.http_client.retry.total != retry: self.http_client.retry.total = retry headers = self.http_client.auth_header(request_id) headers['content-type'] = 'application/x-www-form-urlencoded' url = self.http_client.service_url("/v1/bce/aip/ocr/v1/handwriting") response = self.http_client.session.post(url, headers=headers, data=data, timeout=timeout) self.http_client.check_response_header(response) data = response.json() self.http_client.check_response_json(data) request_id = self.http_client.response_request_id(response) self.__class__._check_service_error(request_id, data) ocr_response = HandwriteOCRResponse(**data) ocr_response.request_id = request_id return ocr_response @staticmethod def _check_service_error(request_id: str, data: dict): r"""个性化服务response参数检查 参数: request (dict) : 通用文字识别body返回 返回: 无 """ if "error_code" in data or "error_msg" in data: raise AppBuilderServerException( request_id=request_id, service_err_code=data.get("error_code"), service_err_message=data.get("error_msg") ) ================================================ FILE: python/core/components/v2/handwrite_ocr/model.py ================================================ # Copyright (c) 2023 Baidu, Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """手写文字识别数据类""" import proto from typing import List, Optional from pydantic import BaseModel, Field class HandwriteOCRRequest(BaseModel): """ 手写文字识别组件请求参数 属性: image (str): 可选。图像内容的base64编码。 url (str): 可选。图像的URL地址,经过base64编码。 图像大小必须小于4MB,图像的最短边长大于15像素,最长边长大于4096像素。 pdf_file (str): 可选。PDF文件内容的base64编码。 pdf_file_num (str): 可选。PDF文件的页数。 ofd_file (str): 可选。OFD(Open Format Document)文件内容的base64编码。 ofd_file_num (str): 可选。OFD文件的页数。 recognize_granularity(str): 可选,识别粒度: 可能的取值包括: - "big": 不定位单字符位置 - "small": 定位单字符位置。 probability (str): 可选。是否输出置信度。默认为"false"。 可能的取值包括: - "true": 返回识别结果中每行的置信度。 - "false": 不返回置信度。 detect_direction (str): 可选。是否检测文本方向。默认为"false"。 可能的取值包括: - "true": 检测文本方向。 - "false": 不检测文本方向。 detect_alteration(str): 可选,是否检测涂改痕迹,适用于手写作文场景,默认不检测 可选值包括: - "true":检测,涂改痕迹部分用“☰”返回; - "false":不检测 """ image: str = Field(None, description="图像内容的base64编码") url: str = Field(None, description="图像的URL地址,经过base64编码") pdf_file: str = Field(None, description="PDF文件内容的base64编码") pdf_file_num: str = Field(None, description="PDF文件的页数") ofd_file: str = Field(None, description="OFD(Open Format Document)文件内容的base64编码") ofd_file_num: str = Field(None, description="OFD文件的页数") recognize_granularity: str = Field("small", description="识别粒度") probability: str = Field("false", description="是否输出置信度") detect_direction: str = Field("false", description="是否检测文本方向") detect_alteration: str = Field("false", description="是否检测涂改痕迹") class HandwriteLocation(BaseModel): """ 手写体位置信息. 属性: left (int): 表示定位位置的长方形左上顶点的水平坐标 top (int): 表示定位位置的长方形左上顶点的垂直坐标 width (int): 表示定位位置的长方形的宽度 height (int): 表示定位位置的长方形的高度 """ left: Optional[int] = Field(None, description="表示定位位置的长方形左上顶点的水平坐标") top: Optional[int] = Field(None, description="表示定位位置的长方形左上顶点的垂直坐 标") width: Optional[int] = Field(None, description="表示定位位置的长方形的宽度") height: Optional[int] = Field(None, description="表示定位位置的长方形的高度") class HandwriteWordResult(BaseModel): """ 手写文字识别结果 属性: words (str): 识别出的文本 location (Location): 文本位置信息 """ words: str = Field(None, description="识别出的文本") location: Optional[HandwriteLocation] = Field(None, description="文本位置信息") class HandwriteProbability(BaseModel): """手写体置信度 属性: average (float): 每行的平均置信度 variance (float): 每行置信度的方差 min (float):每行的最小置信度 """ average: Optional[float] = Field(None, description="每行的平均置信度") variance: Optional[float] = Field(None, description="每行置信度的方差") min: Optional[float] = Field(None, description="每行的最小置信度") class HandwriteOCRResponse(BaseModel): """手写文字识别结果 属性: request_id(str): 请求ID log_id (int): 用于问题跟踪的唯一日志ID words_result_num (int): 必填。识别结果的数量 words_result (List[WordResult]): 识别结果的数组 probability(Probability):当probability=true 时返回该字段,表示识别结果中每一行的置信度值 direction (int): 当 detect_direction=true返回改字段,1(未定义)、 0(正向)、1(逆时针90度)、2(逆时针180度)、3(逆时针270度) pdf_file_size (str): 输入PDF文件的总页数。当pdf_file参数有效时返回 """ request_id: str = Field(None, description="请求ID") log_id: int = Field(None, description="用于问题跟踪的唯一日志ID") words_result_num: int = Field(None, description="必填。识别结果的数量") words_result: List[HandwriteWordResult] = Field(None, description="识别结果的数组") probability: Optional[HandwriteProbability] = Field(None, description="当probability=true 时返回该字段,表示识别结果中每一行的置信度值") direction: int = Field(None, description="当detect_direction=true返回改字段,1(未定义)、0(正向)、1(逆时针90度)、2(逆时针180度)、3(逆时针270度)") pdf_file_size: str = Field(None, description="输入PDF文件的总页数。当pdf_file参数有效时返回") class HandwriteOCRInMsg(BaseModel): """ 手写体文字识别输入消息 属性: raw_image(bytes): 图像原始内容 url(str): 图像下载链接 """ raw_image: bytes = b'' # 原始图片byte数组 url: str = "" # 图片可下载链接 class Position(BaseModel): """位置信息 属性: left (int): 表示定位位置的长方形左上顶点的水平坐标 top (int): 表示定位位置的长方形左上顶点的垂直坐标 width (int): 表示定位位置的长方形的宽度 height (int): 表示定位位置的长方形的高度 """ left: int top: int width: int height: int class Content(BaseModel): """ 识别文字 属性: content(str):文字内容 position(Position): 文字内容的位置信息 """ text: str position: Optional[Position] = None class HandwriteOCROutMsg(BaseModel): """ 识别文字结果列表 属性: contents(list[Content]): 手写体文字识别结果列表 direction(int): 图像旋转角度,0(正向),- 1(逆时针90度),- 2(逆时针180度),- 3(逆时针270度) """ contents: List[Content] = list() direction: int = 0 ================================================ FILE: python/core/components/v2/image_understand/__init__.py ================================================ # Copyright (c) 2023 Baidu, Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. ================================================ FILE: python/core/components/v2/image_understand/component.py ================================================ # Copyright (c) 2023 Baidu, Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. r"""图像内容理解""" import base64 import time import json import logging from typing import Optional from appbuilder.core.component import Component, ComponentOutput from appbuilder.core.message import Message from appbuilder.core._client import HTTPClient from appbuilder.core._exception import AppBuilderServerException, NoFileUploadedExecption, InvalidRequestArgumentError from appbuilder.core.components.image_understand.model import * from appbuilder.core.constants import COMPONENT_SUPPORT_FILE_NUMBER from typing import Generator, Union from appbuilder.utils.trace.tracer_wrapper import components_run_trace, components_run_stream_trace class ImageUnderstand(Component): r""" 图像内容理解组件,即对于输入的一张图片(可正常解码,且长宽比适宜)与问题,输出对图片的描述 Examples: .. code-block:: python import os import appbuilder os.environ["GATEWAY_URL"] = "..." os.environ["APPBUILDER_TOKEN"] = "..." # 从BOS存储读取样例文件 image_url = "https://bj.bcebos.com/v1/appbuilder/test_image_understand.jpeg?authorization=bce-auth-v1%2FALTAKGa8m4qCUasgoljdEDAzLm%2F2024-01-24T09%3A41%3A01Z%2F-1%2Fhost%2Fe8665506e30e0edaec4f1cc84a2507c4cb3fdb9b769de3a5bfe25c372b7e56e6" # 输入参数为一张图片 inp = Message(content={"url": image_url, "question": "图片里内容是什么?"}) # 进行图像内容理解 image_understand = ImageUnderstand() out = image_understand.run(inp) # 打印识别结果 print(out.content) """ name = "image_understanding" version = "v1" manifests = [ { "name": "image_understanding", "description": "可对输入图片进行理解,可输出图片描述、OCR 及图像识别结果", "parameters": { "type": "object", "properties": { "img_names": { "type": "array", "description": "待识别图片的文件名" }, "img_urls": { "type": "array", "description": "待识别图片的url" } }, "anyOf": [ { "required": [ "img_names" ] }, { "required": [ "img_urls" ] } ] } } ] @HTTPClient.check_param @components_run_trace def run(self, message: Message, timeout: float = None, retry: int = 0) -> Message: """ 执行图像内容理解 Args: message (Message): 输入图片或图片url下载地址用于执行识别操作. 举例: Message(content={"raw_image": b"...", "question": "图片主要内容是什么?"}) 或 Message(content={"url": "https://image/download/url", "question": "图片主要内容是什么?"}). timeout (float, optional): HTTP超时时间. 默认为 None. retry (int, optional): HTTP重试次数. 默认为 0. Returns: Message: 模型识别结果. """ inp = ImageUnderstandInMsg(**message.content) request = ImageUnderstandRequest() # 兼容新参数,确保输出结果一致 request.subject_detect = False request.llm_switch = False if inp.raw_image: request.image = base64.b64encode(inp.raw_image) if inp.url: request.url = inp.url if inp.question == "": raise ValueError("request format error, question is empty") if len(inp.question) > 100: raise ValueError(f"request format error, expected len(question)>100, got {len(inp.question)}") if inp.language != "zh-CN" and inp.language != "en": raise ValueError(f"request format error, expected language in ['zh-CN', 'en'], got {inp.language}") request.question = inp.question request.output_CHN = True if inp.language == "en": request.output_CHN = False response, _ = self.__recognize(request, timeout, retry) out = ImageUnderstandOutMsg(description=response.result.description_to_llm) return Message(content=out.model_dump()) def __recognize( self, request: ImageUnderstandRequest, timeout: float = None, retry: int = 0, request_id: str = None, ) -> ImageUnderstandResponse: r"""调用底层接口进行图像内容理解 参数: request (obj: `ImageUnderstandRequest`) : 图像内容理解输入 返回: response (obj: `ImageUnderstandResponse`): 图像内容理解输出 """ if not request.image and not request.url: raise ValueError("request format error, one of image or url must be set") if retry != self.http_client.retry.total: self.http_client.retry.total = retry data = ImageUnderstandRequest.to_dict(request) headers = self.http_client.auth_header(request_id) headers['Content-Type'] = 'application/json' url = self.http_client.service_url("/v1/bce/aip/image-classify/v1/image-understanding/request") try: response = self.http_client.session.post(url, json=data, timeout=timeout, headers=headers) response.raise_for_status() data = response.json() self.http_client.check_response_json(data) request_id = self.http_client.response_request_id(response) self.__class__.__check_create_task_service_error(request_id, data) except Exception as e: self.http_client.classify_exception(e) task = ImageUnderstandTask(data, request_id=request_id) task_id = task.result.get("task_id", "") if task_id == "": raise AppBuilderServerException(request_id=request_id, service_err_message="empty task_id") url = self.http_client.service_url("/v1/bce/aip/image-classify/v1/image-understanding/get-result") while True: try: response = self.http_client.session.post(url, json={"task_id": task_id}, timeout=timeout, headers=headers) response.raise_for_status() data = response.json() self.http_client.check_response_json(data) request_id = self.http_client.response_request_id(response) self.__class__.__check_service_error(request_id, data.get("result", {})) except Exception as e: self.http_client.classify_exception(e) # 处理成功 response = ImageUnderstandResponse(data) if response.result.ret_code == 0: return ImageUnderstandResponse(data), data # 还在处理中 if response.result.ret_code == 1: # 避免触发限流(>1QPS),等待1.1秒 time.sleep(1.1) @components_run_stream_trace def tool_eval( self, img_names: Optional[list] = [], img_urls: Optional[list] = [], **kwargs, ) -> Union[Generator[str, None, None], str]: """ 用于工具的执行,调用底层接口进行图像内容理解 Args: img_names (list): 图片文件名 img_urls (list): 图片url **kwargs: 工具调用的额外关键字参数 Returns: Union[Generator[str, None, None], str]: 图片内容理解结果 """ traceid = kwargs.get("_sys_traceid", '') if not img_names and not img_urls: raise InvalidRequestArgumentError(message="img_names and img_urls cannot both be empty", request_id=traceid) supported_file_type = ["png", "jpg", "jpeg", "webp", "heic", "tif", "tiff", "dcm", "mha", "nii.gz"] sys_file_urls = kwargs.get("_sys_file_urls", {}) if not img_urls and not sys_file_urls: raise NoFileUploadedExecption("No file uploaded!") available_img_urls = {} unsupported_files = [] unknown_files = [] if img_names: for img_name in img_names: if len(available_img_urls) >= COMPONENT_SUPPORT_FILE_NUMBER: break file_type = img_name.split(".")[-1].lower() if img_name in sys_file_urls: if file_type in supported_file_type: available_img_urls[img_name] = sys_file_urls.get(img_name, "") else: unsupported_files.append(img_name) else: unknown_files.append(img_name) for img_url in img_urls: if len(available_img_urls) >= COMPONENT_SUPPORT_FILE_NUMBER: break if img_url in list(sys_file_urls.values()): continue file_name = img_url.split("/")[-1].split("?")[0] file_type = file_name.split(".")[-1].lower() if file_type in supported_file_type: available_img_urls[img_url] = img_url else: unsupported_files.append(img_url) for img_name, img_url in available_img_urls.items(): try: rec_res, raw_data = self._recognize_w_post_process(img_name, img_url, available_img_urls, request_id=traceid) rec_res = { img_name: rec_res } res = json.dumps(rec_res, ensure_ascii=False) llm_result = self.create_output(type="text", text=res, name="text_1", raw_data=raw_data, visible_scope='llm') yield llm_result user_result = self.create_output(type="text", text="", name="text_2", raw_data=raw_data, visible_scope='user') yield user_result except Exception as e: logging.warning(f"{img_name} ocr failed with exception: {e}") continue for file in unsupported_files: rec_res = { file: "不支持的文件类型,请确认是否为图片文件" } res = json.dumps(rec_res, ensure_ascii=False) yield self.create_output(type="text", text=res, name="text_1", visible_scope='llm') yield self.create_output(type="text", text=f"", name="text_2", visible_scope='user') for file in unknown_files: rec_res = { file: "无法获取url,请确认是否上传成功" } res = json.dumps(rec_res, ensure_ascii=False) yield self.create_output(type="text", text=res, name="text_1", visible_scope='llm') yield self.create_output(type="text", text=f"", name="text_2", visible_scope='user') def _recognize_w_post_process( self, img_name, img_url, file_urls, question="图片内容有哪些", request_id=None, ) -> str: r""" 参数: img_name (str): 图片文件名 img_url (bool): 图片url question (str): 询问有关图片内容的问题 file_urls (dict): 文件名与对应文件url的映射 返回: str: 图片内容理解结果 """ req = ImageUnderstandRequest() # 兼容新参数,确保输出结果一致 req.subject_detect = False req.llm_switch = False req.question = question if img_name in file_urls: req.url = file_urls[img_name] if img_url: if img_url in file_urls: img_url = file_urls[img_url] req.url = img_url response, raw_data = self.__recognize(req, request_id=request_id) description_to_llm = response.result.description_to_llm description_processed = description_to_llm.rsplit("。", 2)[0] return description_processed, raw_data @staticmethod def __check_service_error(request_id: str, data: dict): r"""个性化服务response参数检查 参数: request (dict) : 图像内容理解body返回 返回: 无 """ ret_code = data.get("ret_code", 0) if ret_code != 0 and ret_code != 1: raise AppBuilderServerException( request_id=request_id, service_err_code=data.get("ret_code", ""), service_err_message=data.get("ret_msg", "") ) @staticmethod def __check_create_task_service_error(request_id: str, data: dict): r"""个性化服务response参数检查 参数: request_id (str) : 任务请求ID data (dict): 响应数据 返回: 无 """ if "error_code" in data and "error_msg" in data: raise AppBuilderServerException( request_id=request_id, service_err_code=data.get("error_code", ""), service_err_message=data.get("error_msg", "") ) ================================================ FILE: python/core/components/v2/llms/__init__.py ================================================ # Copyright (c) 2023 Baidu, Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. ================================================ FILE: python/core/components/v2/llms/dialog_summary/__init__.py ================================================ """DialogSummary""" from .component import DialogSummary ================================================ FILE: python/core/components/v2/llms/dialog_summary/component.py ================================================ # Copyright (c) 2023 Baidu, Inc. All Rights Reserved. # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from typing import Optional from appbuilder.core.message import Message from appbuilder.core.components.llms.base import CompletionBaseComponent from appbuilder.utils.trace.tracer_wrapper import components_run_trace, components_run_stream_trace from appbuilder.core.components.llms.dialog_summary.base import DialogSummaryArgs class DialogSummary(CompletionBaseComponent): r""" 会话小结大模型组件, 基于生成式大模型对一段用户与坐席的对话生成总结,结果按{"诉求": "", "回应": "", "解决情况": ""}格式输出。 Examples: .. code-block:: python import app import os # 请前往千帆AppBuilder官网创建密钥,流程详见:https://cloud.baidu.com/doc/AppBuilder/s/Olq6grrt6#1%E3%80%81%E5%88%9B%E5%BB%BA%E5%AF%86%E9%92%A5 os.environ["APPBUILDER_TOKEN"] = '...' dialog_summary = appbuilder.DialogSummary("DeepSeek-V3.1") text = "用户:喂我想查一下我的话费\n坐席:好的女士您话费余的话还有87.49元钱\n用户:好的知道了谢谢\n坐席:嗯不客气祝您生活愉快再见" answer = dialog_summary(appbuilder.Message(text)) print(answer) """ name = "dialog_summary" version = "v1" meta = DialogSummaryArgs manifests = [ { "name": "dialog_summary", "description": "基于输入的对话,用大模型对该段对话生成总结, 结果按{\"诉求\": \"\", \"回应\": \"\", \"解决情况\": \"\"}格式输出。", "parameters": { "type": "object", "properties": { "query": { "type": "string", "description": "输入的对话,用于大模型根据该对话生成总结。" } }, "required": [ "query" ] } } ] def __init__( self, model: str = "DeepSeek-V3.1", secret_key: Optional[str] = None, gateway: str = "", lazy_certification: bool = True, **kwargs ): """初始化DialogSummary模型。 Args: model (str|None): 模型名称,用于指定要使用的千帆模型。 secret_key (str, 可选): 用户鉴权token, 默认从环境变量中获取: os.getenv("APPBUILDER_TOKEN", ""). gateway (str, 可选): 后端网关服务地址,默认从环境变量中获取: os.getenv("GATEWAY_URL", "") lazy_certification (bool, 可选): 延迟认证,为True时在第一次运行时认证. Defaults to False. Returns: None """ super().__init__( DialogSummaryArgs, model=model, secret_key=secret_key, gateway=gateway, lazy_certification=lazy_certification) @components_run_trace def run(self, message, stream=False, temperature=1e-10, top_p=0): """ 使用给定的输入运行模型并返回结果。 Args: message (obj:`Message`): 输入消息,用于模型的主要输入内容。这是一个必需的参数。 stream (bool, optional): 指定是否以流式形式返回响应。默认为 False。 temperature (float, optional): 模型配置的温度参数,用于调整模型的生成概率。 取值范围为 0.0 到 1.0,其中较低的值使生成更确定性,较高的值使生成更多样性。 默认值为 1e-10。 top_p (float, optional): 影响输出文本的多样性,取值越大,生成文本的多样性越强。 取值范围为 0.0 到 1.0,其中较低的值使生成更确定性,较高的值使生成更多样性。 默认值为 0。 Returns: obj:`Message`: 模型运行后的输出消息。 """ return super().run(message=message, stream=stream, temperature=temperature, top_p=top_p) @components_run_stream_trace def tool_eval(self, query: str, **kwargs): """ tool_eval for function call """ if not query: raise ValueError("param `query` is required") msg = Message(query) model_configs = kwargs.get('model_configs', {}) temperature = model_configs.get("temperature", 1e-10) top_p = model_configs.get("top_p", 0.0) message = super().run(message=msg, stream=True, temperature=temperature, top_p=top_p) for data in message.content: yield self.create_output(type="text", text=data, usage=message.token_usage) ================================================ FILE: python/core/components/v2/llms/hallucination_detection/__init__.py ================================================ from .component import HallucinationDetection ================================================ FILE: python/core/components/v2/llms/hallucination_detection/component.py ================================================ # Copyright (c) 2023 Baidu, Inc. All Rights Reserved. # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from pydantic import BaseModel, Field from typing import Optional from appbuilder.core.components.llms.base import CompletionBaseComponent, ModelArgsConfig from appbuilder.core.message import Message from appbuilder.core._exception import AppBuilderServerException from appbuilder.utils.trace.tracer_wrapper import components_run_trace, components_run_stream_trace from appbuilder.core.components.llms.hallucination_detection.base import HallucinationDetectionArgs class HallucinationDetection(CompletionBaseComponent): """ 幻觉检测。输入,判断answer中是否存在幻觉。 *注:该组件推荐使用DeepSeek-V3.1模型。* Examples: .. code-block:: python import os import appbuilder # 请前往千帆AppBuilder官网创建密钥,流程详见:https://cloud.baidu.com/doc/AppBuilder/s/Olq6grrt6#1%E3%80%81%E5%88%9B%E5%BB%BA%E5%AF%86%E9%92%A5 os.environ['APPBUILDER_TOKEN'] = '...' hallucination_detection = appbuilder.HallucinationDetection() query = '' context = \ '''澳门美食: 澳门新麻蒲韩国烤肉店 在澳门一年四季之中除了火锅,烤肉也相当受欢迎。提到韩烧,有一间令我印象最深刻,就是号称韩国第一的烤肉店-新麻蒲韩国烤肉店,光是韩国的分店便多达四百多间,海外分店更是遍布世界各地,2016年便落户澳门筷子基区,在原本已经食肆林立的地方一起百花齐放!店内的装修跟韩国分店还完度几乎没差,让食客彷如置身于韩国的感觉,还要大赞其抽风系统不俗,离开时身上都不会沾上烤肉味耶! 时间:周一至周日 下午5:00 - 上午3:00 电话:+853 2823 4012 地址:澳门筷子基船澳街海擎天第三座地下O号铺96号 必食推介: 护心肉二人套餐 来新麻蒲必试的有两样东西,现在差不多每间烤肉店都有炉边烤蛋,但大家知道吗?原来新麻蒲就是炉边烤蛋的开创者,既然是始祖,这已经是个非吃不可的理由!还有一款必试的就是护心肉,即是猪的横隔膜与肝中间的部分,每头猪也只有200克这种肉,非常珍贵,其味道吃起来有种独特的肉香味,跟牛护心肉一样精彩! 秘制猪皮 很多怕胖的女生看到猪皮就怕怕,但其实猪皮含有大量胶原蛋白,营养价值很高呢!这里红通通的猪皮还经过韩国秘制酱汁处理过,会有一点点辣味。烤猪皮的时候也需特别注意火侯,这样吃起来才会有外脆内Q的口感!''' answer = '澳门新麻蒲烤肉店并不是每天开门。' inputs = {'query': query, 'context': context, 'answer': answer} msg = appbuilder.Message(inputs) result = hallucination_detection.run(msg) print(result) """ name = 'hallucination_detection' version = 'v1' meta = HallucinationDetectionArgs manifests = [ { "name": "hallucination_detection", "description": "输入用户查询query、检索结果context以及根据检索结果context生成的用户查询query的回答answer,判断answer" \ "中是否存在幻觉。", "parameters": { "type": "object", "properties": { "query": { "type": "string", "description": "用户查询。" }, "context": { "type": "string", "description": "检索结果。" }, "answer": { "type": "string", "description": "根据检索结果context生成的用户查询query的回答answer。" } }, "required": [ "query", "context", "answer" ] } } ] def __init__( self, model="DeepSeek-V3.1", secret_key: Optional[str] = None, gateway: str = "", lazy_certification: bool = True, **kwargs, ): """初始化幻觉检测组件。 Args: model (str|None): 模型名称,用于指定要使用的千帆模型。推荐使用DeepSeek-V3.1模型。 secret_key (str, 可选): 用户鉴权token, 默认从环境变量中获取: os.getenv("APPBUILDER_TOKEN", ""). gateway (str, 可选): 后端网关服务地址,默认从环境变量中获取: os.getenv("GATEWAY_URL", "") lazy_certification (bool, 可选): 延迟认证,为True时在第一次运行时认证. Defaults to False. Returns: None """ super().__init__(HallucinationDetectionArgs, model=model, secret_key=secret_key, gateway=gateway, lazy_certification=lazy_certification) def completion(self, version, base_url, request, timeout: float = None, retry: int = 0): """ Send a byte array of an audio file to obtain the result of speech recognition. Args: version (str): API version. base_url (str): Base URL of the API. request (Request): Request object containing audio file and other parameters. timeout (float, optional): Timeout for the request. Defaults to None. retry (int, optional): Number of retries for the request. Defaults to 0. Returns: Response: Processed response object. """ headers = self.http_client.auth_header() headers["Content-Type"] = "application/json" stream = True if request.response_mode == "streaming" else False url = self.http_client.service_url("/app/hallucination_detection", self.base_url) response = self.http_client.session.post(url, json=request.params, headers=headers, timeout=timeout, stream=stream) return self.gene_response(response, stream) @components_run_trace def run(self, message, stream=False, temperature=1e-10, top_p=0.0): """ 使用给定的输入运行模型并返回结果。 Args: message (Message): 输入消息,包含 query、context 和 answer。是必需的参数。 stream (bool, 可选): 是否以流式形式返回响应。默认为 False。 temperature (float, 可选): 模型配置的温度参数,用于调整模型的生成概率。 取值范围为 0.0 到 1.0,较低的值使生成更确定性,较高的值使生成更多样性。默认值为 1e-10。 top_p (float, 可选): 影响输出文本的多样性,取值越大,生成文本的多样性越强。 取值范围为 0.0 到 1.0,较低的值使生成更确定性,较高的值使生成更多样性。默认值为 0。 Returns: result (Message): 模型运行后的输出消息。 Raises: AssertionError: 如果输入的 message 中缺少 query、context 或 answer。 AppBuilderServerException: 如果请求执行失败,将抛出异常,包含服务错误码和错误信息。 """ inputs = message.content query = inputs.pop('query', None) assert query, 'You must input query and query should not be empty' assert 'context' in inputs and inputs['context'], 'You must input context and context should not be empty' assert 'answer' in inputs and inputs['answer'], 'You must input answer and answer should not be empty' response_mode = "streaming" if stream else "blocking" user_id = message.id model_config_inputs = ModelArgsConfig(**{"stream": stream, "temperature": temperature, "top_p": top_p}) model_config = self.get_model_config(model_config_inputs) request = self.gene_request(query, inputs, response_mode, user_id, model_config) response = self.completion(self.version, self.base_url, request) if response.error_no != 0: raise AppBuilderServerException(service_err_code=response.error_no, service_err_message=response.error_msg) result = response.to_message() return result @components_run_stream_trace def tool_eval(self, query: str, context: str, answer: str, **kwargs): """ 调用函数进行工具评估。 Args: - query (str): 查询语句。 - context (str): 上下文信息。 - answer (str): 参考答案。 **kwargs: 关键字参数,包含评估所需的输入参数。 - model_configs (dict, optional): 模型配置信息,默认为空字典。包含以下字段: - temperature (float, optional): 温度参数,用于控制生成文本的随机性,默认为1e-10。 - top_p (float, optional): 截断概率,用于控制生成文本的质量,默认为0.0。 Returns: ComponentOutput: 组件输出结果,包含评估结果。 Raises: ValueError: 如果缺少query、context或answer参数,将引发此异常。 """ if not query or not context or not answer: raise ValueError('param `query` and `context` and `answer` are required') msg = Message({'query': query, 'context': context, 'answer': answer}) model_configs = kwargs.get('model_configs', {}) temperature = model_configs.get('temperature', 1e-10) top_p = model_configs.get('top_p', 0.0) message = self.run(message=msg, stream=True, temperature=temperature, top_p=top_p) for data in message.content: yield self.create_output(type="text", text=data, usage=message.token_usage, name="text") ================================================ FILE: python/core/components/v2/llms/is_complex_query/__init__.py ================================================ from .component import IsComplexQuery ================================================ FILE: python/core/components/v2/llms/is_complex_query/component.py ================================================ # Copyright (c) 2023 Baidu, Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """ is complex query """ from typing import Optional from appbuilder.core.components.llms.base import CompletionBaseComponent from appbuilder.core.components.llms.is_complex_query.base import IsComplexQueryMeta from appbuilder.core.message import Message from appbuilder.utils.trace.tracer_wrapper import components_run_trace, components_run_stream_trace class IsComplexQuery(CompletionBaseComponent): r""" 基于输入的问题, 对问题进行初步的分类,方便下游使用不同类型的流程来处理当前的简单问题/复杂问题。广泛用于知识问答场景。 Examples: .. code-block:: python import os import appbuilder # 请前往千帆AppBuilder官网创建密钥,流程详见:https://cloud.baidu.com/doc/AppBuilder/s/Olq6grrt6#1%E3%80%81%E5%88%9B%E5%BB%BA%E5%AF%86%E9%92%A5 os.environ["APPBUILDER_TOKEN"] = "..." is_complex_query = appbuilder.IsComplexQuery(model="DeepSeek-V3.1") msg = "吸塑包装盒在工业化生产和物流运输中分别有什么重要性?" msg = appbuilder.Message(msg) answer = is_complex_query(msg) print("Answer: \n{}".format(answer.content)) """ name = "is_complex_query" version = "v1" meta = IsComplexQueryMeta manifests = [ { "name": "is_complex_query", "description": "基于输入的问题, 对问题进行初步的分类,方便下游使用不同类型的流程来处理当前的简单问题/复杂问题。", "parameters": { "type": "object", "properties": { "query": { "type": "string", "description": "输入的问题,用于大模型根据该问题进行初步的分类。" } }, "required": [ "query" ] } } ] def __init__( self, model: str = "DeepSeek-V3.1", secret_key: Optional[str] = None, gateway: str = "", lazy_certification: bool = True, **kwargs ): """初始化IsComplexQueryMeta任务。 Args: model (str|None): 模型名称,用于指定要使用的千帆模型。 secret_key (str, 可选): 用户鉴权token, 默认从环境变量中获取: os.getenv("APPBUILDER_TOKEN", ""). gateway (str, 可选): 后端网关服务地址,默认从环境变量中获取: os.getenv("GATEWAY_URL", "") lazy_certification (bool, 可选): 延迟认证,为True时在第一次运行时认证. Defaults to False. Returns: None """ super().__init__( IsComplexQueryMeta, model=model, secret_key=secret_key, gateway=gateway, lazy_certification=lazy_certification) @components_run_trace def run(self, message, stream=False, temperature=1e-10, top_p=0): """ 给定输入(message)到模型运行,同时指定运行参数,并返回结果。 Args: message (obj:`Message`): 输入消息,用于模型的主要输入内容。这是一个必需的参数。 stream (bool, optional): 指定是否以流式形式返回响应。默认为 False。 temperature (float, optional): 模型配置的温度参数,用于调整模型的生成概率。取值范围为 0.0 到 1.0,其中较低的值使生成更确定性,较高的值使生成更多样性。默认值为 1e-10。 top_p (float, optional): 影响输出文本的多样性,取值越大,生成文本的多样性越强。取值范围为 0.0 到 1.0,其中较低的值使生成更确定性,较高的值使生成更多样性。默认值为 0。 Returns: obj:`Message`: 模型运行后的输出消息。 """ return super().run(message=message, stream=stream, temperature=temperature, top_p=top_p) @components_run_stream_trace def tool_eval(self, query: str, **kwargs): """ tool_eval for function call """ if not query: raise ValueError("param `query` is required") msg = Message(query) model_configs = kwargs.get('model_configs', {}) temperature = model_configs.get("temperature", 1e-10) top_p = model_configs.get("top_p", 0.0) message = super().run(message=msg, stream=False, temperature=temperature, top_p=top_p) yield self.create_output(type="text", text=str(message.content), name="text", usage=message.token_usage) ================================================ FILE: python/core/components/v2/llms/mrc/__init__.py ================================================ from .component import MRC ================================================ FILE: python/core/components/v2/llms/mrc/component.py ================================================ # Copyright (c) 2023 Baidu, Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from typing import Optional from appbuilder.core._exception import AppBuilderServerException from appbuilder.core.components.llms.base import CompletionBaseComponent, ModelArgsConfig from appbuilder.core.components.llms.mrc.base import MrcArgs from appbuilder.core.message import Message from appbuilder.utils.trace.tracer_wrapper import components_run_trace, components_run_stream_trace class MRC(CompletionBaseComponent): """ 阅读理解问答组件,基于大模型进行阅读理解问答,支持拒答、澄清、重点强调、友好性提升、溯源等多种功能,可用于回答用户提出的问题。 Examples: .. code-block:: python import appbuilder import os # 设置环境变量 os.environ["APPBUILDER_TOKEN"] = '...' # 创建MRC对象 mrc_component = appbuilder.MRC() #初始化参数 msg = "残疾人怎么办相关证件" msg = appbuilder.Message(msg) context_list = appbuilder.Message(["如何办理残疾人通行证一、残疾人通行证办理条件: 1、持有中华人民共和国残疾人证,下肢残疾或者听力残疾;2、持有准驾车型为C1(听力残疾)、 C2(左下肢残疾、听力残疾", "3、本人拥有本市登记核发的非营运小型载客汽车,车辆须在检验有效期内, 并有有效交强险凭证,C5车辆加装操纵辅助装置后已办理变更手续。二、办理地点:北京市朝阳区左家庄北里35号: 北京市无障碍环境建设促进中心"]) # 模拟运行MRC组件,开启拒答、澄清追问、重点强调、友好性提升和溯源能力五个功能 result = mrc_component.run(msg, context_list, reject=True, clarify=True, highlight=True, friendly=True, cite=True) # 输出运行结果 print(result) """ name = "mrc" version = "v1" meta: MrcArgs manifests = [ { "name": "mrc", "description": "对于输入的问题,基于大模型进行阅读理解问答,支持拒答、澄清、重点强调、友好性提升、溯源等多种功能,可用于回答用户提出的问题", "parameters": { "type": "object", "properties": { "query": { "type": "string", "description": "输入用户query,例如'千帆平台都有哪些大模型?'" }, "context_list": { "type": "list", "description": "用户输入检索片段list,例如[content1, content2, content3,...],也可以为空, 即[]" }, "reject": { "type": "bool", "description": "控制大模型拒答能力的开关,为true即为开启拒答功能,为false即为关闭拒答功能" }, "clarify": { "type": "bool", "description": "控制大模型澄清能力的开关,为true即为开启澄清反问功能,为false即为关闭澄清反问功能" }, "highlight": { "type": "bool", "description": "控制大模型重点强调能力的开关,为true即为开启重点强调功能,为false即为关闭重点强调功能" }, "friendly": { "type": "bool", "description": "控制大模型友好对提升难过能力的开关,为true即为开启友好度提升功能,为false即为关闭友好度提升功能" }, "cite": { "type": "bool", "description": "控制大模型溯源能力的开关,为true即为开启溯源功能,为false即为关闭溯源功能。" } }, "required": [ "query", "context_list" ] } } ] def __init__( self, model: str = "DeepSeek-V3.1", secret_key: Optional[str] = None, gateway: str = "", lazy_certification: bool = True, **kwargs ): """初始化MRC(阅读理解问答)模型。 Args: model (str|None): 模型名称,用于指定要使用的千帆模型。 secret_key (str, 可选): 用户鉴权token, 默认从环境变量中获取: os.getenv("APPBUILDER_TOKEN", ""). gateway (str, 可选): 后端网关服务地址,默认从环境变量中获取: os.getenv("GATEWAY_URL", "") lazy_certification (bool, 可选): 延迟认证,为True时在第一次运行时认证. Defaults to False. Returns: None """ super().__init__( MrcArgs, model=model, secret_key=secret_key, gateway=gateway, lazy_certification=lazy_certification) def __get_instruction_set(self): """ return: json格式的instruction_set """ return {"reject": "如果答案不在搜索结果中得到,则在答案开头说明:" "“当前文档库找不到对应的答案,我可以尝试用我的常识来回答你”," "并基于你的常识给出答案。", "clarify": "当问题比较模糊,而检索结果包含多种可能的答案时,反向提问用户想问的具体内容," "让用户补充关键信息后以完整的query重新发问。", "highlight": "可以对答案中的核心部分进行markdown加粗(**加粗内容**)。", "friendly": "答案尽量用礼貌用语开头,涉及到条目列举的内容需要在前面加序号并做分点描述," "必要时可在每一点前面做小标题的汇总,并可以用总-分-总的形式展示分点式答案内容,使得答案内容可读性更强。", "cite": "使用引用标记来标注回答内容参考的搜索结果序号,例如^[1]^ (引用单个搜索结果),^[1][2]^(引用多个搜索结果)," "其中方括号中的数字是搜索结果序号。引用标记只能出现在句尾标点符号前。"} @components_run_trace def run(self, message, context_list, reject=False, clarify=False, highlight=False, friendly=False, cite=False, stream=False, temperature=1e-10, top_p=0): """ 运行阅读理解问答模型并返回结果。 Args: message (obj:`Message`): 输入消息,包含用户提出的问题。这是一个必需的参数。 context_list (obj:`Message`): 用户输入的问题对应的段落文本列表。这是一个必需的参数。 reject (bool, 可选): 拒答开关,如果为 True,则启用拒答能力。默认为 False。 clarify (bool, 可选): 澄清开关,如果为 True,则启用澄清能力。默认为 False。 highlight (bool, 可选): 重点强调开关,如果为 True,则启用重点强调能力。默认为 False。 friendly (bool, 可选): 友好性提升开关,如果为 True,则启用友好性提升能力。默认为 False。 cite (bool, 可选): 溯源开关,如果为 True,则启用溯源能力。默认为 False。 stream (bool, 可选): 指定是否以流式形式返回响应。默认为 False。 temperature (float, 可选): 模型配置的温度参数,用于调整模型的生成概率。取值范围为 0.0 到 1.0,其中较低的值使生成更确定性,较高的值使生成更多样性。默认值为 1e-10。 top_p (float, 可选): 影响输出文本的多样性,取值越大,生成文本的多样性越强。取值范围为 0.0 到 1.0,其中较低的值使生成更确定性,较高的值使生成更多样性。默认值为 0。 Returns: obj:`Message`: 模型运行后的输出消息。 """ instruction_set = self.__get_instruction_set() context_list = context_list.content inputs = { "query": message.content, "context_out": "\n\n".join(f"[{i + 1}] {s}" for i, s in enumerate(context_list)), "reject": instruction_set["reject"] if reject else None, "clarify": instruction_set["clarify"] if clarify else None, "highlight": instruction_set["highlight"] if highlight else None, "friendly": instruction_set["friendly"] if friendly else None, "cite": instruction_set["cite"] if cite else None, } model_config_inputs = ModelArgsConfig(**{"stream": stream, "temperature": temperature, "top_p": top_p}) model_config = self.get_model_config(model_config_inputs) query = inputs["query"] response_mode = "streaming" if stream else "blocking" user_id = message.id request = self.gene_request(query, inputs, response_mode, user_id, model_config) response = self.completion(self.version, self.base_url, request) if response.error_no != 0: raise AppBuilderServerException(service_err_code=response.error_no, service_err_message=response.error_msg) return response.to_message() @components_run_stream_trace def tool_eval(self, query: str, context_list: list, reject: bool = False, clarify: bool = False, highlight: bool = False, friendly: bool = False, cite: bool = False, **kwargs): """ tool_eval for function call """ if not query or not context_list: raise ValueError("param `query` and `context_list` are required") msg = Message(query) context_list_msg = Message(context_list) model_configs = kwargs.get('model_configs', {}) temperature = model_configs.get("temperature", 1e-10) top_p = model_configs.get("top_p", 0.0) message = super().run( message=msg, context_list=context_list_msg, reject=reject, clarify=clarify, highlight=highlight, friendly=friendly, cite=cite, stream=False, temperature=temperature, top_p=top_p ) yield self.create_output(type="text", text=str(message.content), name="text", usage=message.token_usage) ================================================ FILE: python/core/components/v2/llms/nl2pandas/__init__.py ================================================ """text to pandas""" from .component import Nl2pandasComponent ================================================ FILE: python/core/components/v2/llms/nl2pandas/component.py ================================================ # Copyright (c) 2023 Baidu, Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from typing import Optional from appbuilder.core.components.llms.base import CompletionBaseComponent from appbuilder.core.components.llms.nl2pandas.base import Nl2pandasArgs from appbuilder.core.message import Message from appbuilder.utils.trace.tracer_wrapper import components_run_trace, components_run_stream_trace class Nl2pandasComponent(CompletionBaseComponent): """ 自然语言转pandas大模型组件, 基于生成式大模型对query进行理解并生成对应语义的可执行python代码(主要使用pandas),可用于基于表格的查询、问答等多种场景。 Examples: .. code-block:: python import appbuilder os.environ["APPBUILDER_TOKEN"] = '...' table_info = '''表格列信息如下: 学校名 : 清华附小 , 字符串类型,代表小学学校的名称 所属地区 : 西城区 , 字符串类型,表示该小学学校所在的位置 创办时间 : 1998 , 数字值类型,表示该小学学校的创办时间 类别 : 公立小学 , 字符串类型,表示该小学学校所在的类别 学生人数 : 2000 , 数字值类型,表示该小学学校的学生数量 教职工人数 : 140 , 数字值类型,表示该小学学校的教职工数量 教学班数量 : 122 , 数字值类型,表示该小学学校的教学班数量 ''' query = "海淀区有哪些学校" query = appbuilder.Message(query) nl2pandas = appbuilder.Nl2pandasComponent(model="DeepSeek-V3.1") answer = nl2pandas(query, table_info = table_info) """ name = "nl2pandas" version = "v1" meta = Nl2pandasArgs manifests = [ { "name": "nl2pandas", "description": "输入用户查询query,基于生成式大模型对query进行理解并生成对应语义的可执行python代码(主要使用pandas),可用于基于表格的查询、问答等多种场景", "parameters": { "type": "object", "properties": { "query": { "type": "string", "description": "输入问题,一般是针对表格信息的提问,例如'海淀区的小学有哪些'" }, "table_info": { "type": "string", "description": "表格信息,一般是表格列名以及对应列名的举例和释义,例如'表格列信息如下:\n学校名 : 清华附小 , 字符串类型,代表小学学校的名称" } }, "required": [ "query", "table_info" ] } } ] def __init__( self, model: str = "DeepSeek-V3.1", secret_key: Optional[str] = None, gateway: str = "", lazy_certification: bool = True, **kwargs ): """初始化Nl2pandasComponent模型。 Args: model (str|None): 模型名称,用于指定要使用的千帆模型。 secret_key (str, 可选): 用户鉴权token, 默认从环境变量中获取: os.getenv("APPBUILDER_TOKEN", ""). gateway (str, 可选): 后端网关服务地址,默认从环境变量中获取: os.getenv("GATEWAY_URL", "") lazy_certification (bool, 可选): 延迟认证,为True时在第一次运行时认证. Defaults to False. Returns: None """ super().__init__( Nl2pandasArgs, model=model, secret_key=secret_key, gateway=gateway, lazy_certification=lazy_certification) @components_run_trace def run(self, message, table_info=None, stream=False, temperature=1e-10, top_p=0): """ 使用给定的输入运行模型并返回结果。 Args: message (obj:`Message`): 输入问题,通常是针对表格信息的提问,如'海淀区的小学有哪些'。这是一个必需的参数。 table_info (obj:`Message`, optional): 表格信息,包括表格列名、对应列名的示例和释义。默认值为 None,但这是一个必需的参数。 stream (bool, optional): 指定是否以流式形式返回响应。默认为 False。 temperature (float, optional): 模型配置的温度参数,用于调整模型的生成概率。取值范围为 0.0 到 1.0,较低的值使生成更确定性,较高的值使生成更多样性。默认值为 1e-10。 top_p (float, optional): 影响输出文本的多样性,取值越大,生成文本的多样性越强。取值范围为 0.0 到 1.0,较低的值使生成更确定性,较高的值使生成更多样性。默认值为 0。 Returns: obj:`Message`: 模型运行后的输出消息。 """ return super().run(message=message, table_info=table_info, stream=stream, temperature=temperature, top_p=top_p) @components_run_stream_trace def tool_eval(self, query: str, table_info: str, **kwargs): """ tool_eval for function call """ if not query or not table_info: raise ValueError("param `query` and 'table_info' are required") msg = Message(query) model_configs = kwargs.get('model_configs', {}) temperature = model_configs.get("temperature", 1e-10) top_p = model_configs.get("top_p", 0.0) message = super().run(message=msg, table_info=table_info, stream=True, temperature=temperature, top_p=top_p) for data in message.content: yield self.create_output(type="text", text=data, name="text", usage=message.token_usage) ================================================ FILE: python/core/components/v2/llms/oral_query_generation/__init__.py ================================================ from .component import OralQueryGeneration ================================================ FILE: python/core/components/v2/llms/oral_query_generation/component.py ================================================ # Copyright (c) 2023 Baidu, Inc. All Rights Reserved. # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import json import re from typing import Optional from appbuilder.core.components.llms.base import CompletionBaseComponent, ModelArgsConfig from appbuilder.core.message import Message from appbuilder.core._exception import AppBuilderServerException from appbuilder.utils.trace.tracer_wrapper import components_run_trace, components_run_stream_trace from appbuilder.core.components.llms.oral_query_generation.base import OralQueryGenerationArgs class OralQueryGeneration(CompletionBaseComponent): r""" 口语化Query生成,可用于问答场景下对文档增强索引。 *注:该组件推荐使用DeepSeek-V3.1模型。* Examples: .. code-block:: python import os import appbuilder os.environ["APPBUILDER_TOKEN"] = '...' text = ('文档标题:在OPPO Reno5上使用视频超级防抖\n' '文档摘要:OPPO Reno5上的视频超级防抖,视频超级防抖3.0,多代视频防抖算法积累,这一代依旧超级防抖超级稳。 开启视频超级' '防抖 开启路径:打开「相机 > 视频 > 点击屏幕上方的“超级防抖”标识」 后置视频同时支持超级防抖和超级防抖Pro功能,开启超级' '防抖后手机屏幕将出现超级防抖Pro开关,点击即可开启或关闭。 除此之外,前置视频同样加持防抖算法,边走边拍也能稳定聚焦脸部' ',实时视频分享您的生活。') oral_query_generation = appbuilder.OralQueryGeneration(model='DeepSeek-V3.1') answer = oral_query_generation(appbuilder.Message(text), query_type='全部', output_format='str') print(answer.content) """ name = 'query_generation' version = 'v1' meta = OralQueryGenerationArgs manifests = [ { "name": "query_generation", "description": "输入文本、待生成的query类型和输出格式,生成query,并按照要求的格式进行输出。", "parameters": { "type": "object", "properties": { "text": { "type": "string", "description": "输入文本,组件会根据该输入文本生成query。" }, "query_type": { "type": "string", "description": "待生成的query类型,可选问题、短语以及全部(问题 + 短语)。" }, "output_format": { "type": "string", "description": "输出格式,可选json或str,str格式与老版本输出格式相同。" } }, "required": [ "text" ] } } ] def __init__( self, model: str="DeepSeek-V3.1", secret_key: Optional[str] = None, gateway: str = "", lazy_certification: bool = True, **kwargs ): """初始化StyleRewrite模型。 Args: model (str|None): 模型名称,用于指定要使用的千帆模型。 secret_key (str, 可选): 用户鉴权token, 默认从环境变量中获取: os.getenv("APPBUILDER_TOKEN", ""). gateway (str, 可选): 后端网关服务地址,默认从环境变量中获取: os.getenv("GATEWAY_URL", "") lazy_certification (bool, 可选): 延迟认证,为True时在第一次运行时认证. Defaults to False. Returns: None """ super().__init__( OralQueryGenerationArgs, model=model, secret_key=secret_key, gateway=gateway, lazy_certification=lazy_certification) def regenerate_output(self, model_output, output_format): """ 兼容老版本的输出格式 """ if not isinstance(model_output, str): return model_output match_obj = re.search(r'```json\n(.+)\n```', model_output, flags=re.DOTALL) regenerated_output = None if match_obj: regenerated_output = json.loads(match_obj.group(1)) else: dict_json_match_obj = re.search(r'\{(.|\n)+\}', model_output) dict_json_text = dict_json_match_obj.group(0) if dict_json_match_obj else None regenerated_output = json.loads(dict_json_text) if dict_json_text is not None else model_output if output_format == 'json' or not isinstance(regenerated_output, dict): return json.dumps(regenerated_output, ensure_ascii=False, indent=4) queries = [] for key in ['问题', '短语']: queries += regenerated_output.pop(key, []) for value in regenerated_output.values(): queries += value regenerated_output = '\n'.join([f'{index}. {query}' for index, query in enumerate(queries, 1)]) return regenerated_output def completion(self, version, base_url, request, timeout: float = None, retry: int = 0): r"""Send a byte array of an audio file to obtain the result of speech recognition.""" headers = self.http_client.auth_header() headers["Content-Type"] = "application/json" stream = True if request.response_mode == "streaming" else False url = self.http_client.service_url("/app/query_generation", self.base_url) response = self.http_client.session.post(url, json=request.params, headers=headers, timeout=timeout, stream=stream) return self.gene_response(response, stream) @components_run_trace def run(self, message, query_type='全部', output_format='str', stream=False, temperature=1e-10, top_p=0.0): """ 使用给定的输入运行模型并返回结果。 Args: message (Message): 输入消息,包含query、context和answer等信息。这是一个必需的参数。 query_type (str, 可选): 待生成的query类型,包括问题、短语和全部(问题+短语)。默认为全部。 output_format (str, 可选): 输出格式,包括json和str,当stream为True时,只能以json形式输出。默认为str。 stream (bool, 可选): 指定是否以流式形式返回响应。默认为 False。 temperature (float, 可选): 模型配置的温度参数,用于调整模型的生成概率。 取值范围为 0.0 到 1.0,其中较低的值使生成更确定性,较高的值使生成更多样性。默认值为 1e-10。 top_p (float, 可选): 影响输出文本的多样性,取值越大,生成文本的多样性越强。 取值范围为 0.0 到 1.0,其中较低的值使生成更确定性,较高的值使生成更多样性。默认值为 0。 Returns: result (Message): 模型运行后的输出消息。 """ text = message.content assert text, 'Input text should be a valid string' inputs = { 'text': text, 'query_type': query_type } response_mode = "streaming" if stream else "blocking" user_id = message.id model_config_inputs = ModelArgsConfig(**{"stream": stream, "temperature": temperature, "top_p": top_p}) model_config = self.get_model_config(model_config_inputs) request = self.gene_request('', inputs, response_mode, user_id, model_config) response = self.completion(self.version, self.base_url, request) if response.error_no != 0: raise AppBuilderServerException(service_err_code=response.error_no, service_err_message=response.error_msg) result = response.to_message() result.content = self.regenerate_output(result.content, output_format) return result @components_run_stream_trace def tool_eval(self, text: str, query_type: str = '全部', output_format: str = 'str', **kwargs): """ 根据给定的文本和查询类型生成输出。 Args: text (str): 要处理的文本。 query_type (str, optional): 查询类型,默认为'全部'。 output_format (str, optional): 输出格式,默认为'str'。 **kwargs: 其他关键字参数,例如模型配置等。 Returns: generator: 生成输出数据的生成器。 """ msg = Message(text) model_configs = kwargs.get('model_configs', {}) temperature = model_configs.get('temperature', 1e-10) top_p = model_configs.get('top_p', 0.0) message = self.run(message=msg, query_type=query_type, output_format=output_format, stream=True, temperature=temperature, top_p=top_p) for data in message.content: yield self.create_output(type="text", text=data, usage=message.token_usage) ================================================ FILE: python/core/components/v2/llms/qa_pair_mining/__init__.py ================================================ from .component import QAPairMining ================================================ FILE: python/core/components/v2/llms/qa_pair_mining/component.py ================================================ # Copyright (c) 2023 Baidu, Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from typing import Optional from appbuilder.core.components.llms.base import CompletionBaseComponent from appbuilder.core.components.llms.qa_pair_mining.base import QAPairMiningMeta from appbuilder.core.message import Message from appbuilder.utils.trace.tracer_wrapper import components_run_trace, components_run_stream_trace class QAPairMining(CompletionBaseComponent): """ 基于输入文本内容,快速生成多个问题及对应答案,极大提高信息提炼的效率和准确性.广泛用于在线客服、智能问答等领域。 Examples: .. code-block:: python import os import appbuilder os.environ["APPBUILDER_TOKEN"] = "..." qa_mining = appbuilder.QAPairMining(model="DeepSeek-V3.1") # 输入文本(对此文本挖掘问答对) msg = '2017年,工商银行根据外部宏观环境变化,及时调整业务策略,优化资产负债结构,' + \ '保持存贷款业务协调发展,提升资产负债配置效率。' + \ '2018年3月末,工商银行总资产264,937.81亿元,比上年末增加4,067.38亿元。' msg = appbuilder.Message(msg) answer = qa_mining(msg) print(">>> Output: {}".format(answer.content)) """ name = "qa_pair_mining" version = "v1" meta = QAPairMiningMeta manifests = [ { "name": "qa_pair_mining", "description": "基于输入文本内容,快速生成多个问题及对应答案,极大提高信息提炼的效率和准确性。广泛用于在线客服、智能问答等领域。", "parameters": { "type": "object", "properties": { "query": { "type": "string", "description": "输入消息,用于模型的输入,一般为文档段落。" } }, "required": [ "query" ] } } ] def __init__( self, model: str = "DeepSeek-V3.1", secret_key: Optional[str] = None, gateway: str = "", lazy_certification: bool = True, **kwargs ): """初始化QAPairMining(问答对挖掘)模型。 Args: model (str|None): 模型名称,用于指定要使用的千帆模型。 secret_key (str, 可选): 用户鉴权token, 默认从环境变量中获取: os.getenv("APPBUILDER_TOKEN", ""). gateway (str, 可选): 后端网关服务地址,默认从环境变量中获取: os.getenv("GATEWAY_URL", "") lazy_certification (bool, 可选): 延迟认证,为True时在第一次运行时认证. Defaults to False. Returns: None """ super().__init__( QAPairMiningMeta, model=model, secret_key=secret_key, gateway=gateway, lazy_certification=lazy_certification) @components_run_trace def run(self, message, stream=False, temperature=1e-10, top_p=0.0): """ 给定输入(message)到模型运行,同时指定运行参数,并返回结果。 Args: message (obj:`Message`): 输入消息,用于模型的主要输入内容。这是一个必需的参数。 stream (bool, optional): 指定是否以流式形式返回响应。默认为 False。 temperature (float, optional): 模型配置的温度参数,用于调整模型的生成概率。取值范围为 0.0 到 1.0,其中较低的值使生成更确定性,较高的值使生成更多样性。默认值为 1e-10。 top_p (float, optional): 影响输出文本的多样性,取值越大,生成文本的多样性越强。取值范围为 0.0 到 1.0,其中较低的值使生成更确定性,较高的值使生成更多样性。默认值为 0。 Returns: obj:`Message`: 模型运行后的输出消息。 """ return super().run(message=message, stream=stream, temperature=temperature, top_p=top_p) @components_run_stream_trace def tool_eval(self, query: str, **kwargs): """ tool_eval for function call """ if not query: raise ValueError("param `query` is required") msg = Message(query) model_configs = kwargs.get('model_configs', {}) temperature = model_configs.get("temperature", 1e-10) top_p = model_configs.get("top_p", 0.0) message = super().run(message=msg, stream=False, temperature=temperature, top_p=top_p) yield self.create_output(type="text", text=str(message.content), name="text", usage=message.token_usage) ================================================ FILE: python/core/components/v2/llms/query_decomposition/__init__.py ================================================ from .component import QueryDecomposition ================================================ FILE: python/core/components/v2/llms/query_decomposition/component.py ================================================ # Copyright (c) 2023 Baidu, Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """ query decomposition """ from typing import Optional from appbuilder.core.components.llms.base import CompletionBaseComponent from appbuilder.core.components.llms.query_decomposition.base import QueryDecompositionMeta from appbuilder.core.message import Message from appbuilder.utils.trace.tracer_wrapper import components_run_trace, components_run_stream_trace class QueryDecomposition(CompletionBaseComponent): r""" 尝试对已经判定为复杂问题的原始问题进行拆解,把复杂问题拆解为一个个简单问题。广泛用于知识问答场景。 Examples: .. code-block:: python import os import appbuilder # 请前往千帆AppBuilder官网创建密钥,流程详见:https://cloud.baidu.com/doc/AppBuilder/s/Olq6grrt6#1%E3%80%81%E5%88%9B%E5%BB%BA%E5%AF%86%E9%92%A5 os.environ["APPBUILDER_TOKEN"] = "..." query_decomposition = appbuilder.QueryDecomposition(model="DeepSeek-V3.1") msg = "吸塑包装盒在工业化生产和物流运输中分别有什么重要性?" msg = appbuilder.Message(msg) answer = query_decomposition(msg) print("Answer: \n{}".format(answer.content)) """ name = "query_decomposition" version = "v1" meta = QueryDecompositionMeta manifests = [ { "name": "query_decomposition", "description": "尝试对已经判定为复杂问题的原始问题进行拆解,把复杂问题拆解为一个个简单问题。广泛用于知识问答场景。", "parameters": { "type": "object", "properties": { "query": { "type": "string", "description": "输入消息,用于模型的输入,一般为问题。" } }, "required": [ "query" ] } } ] def __init__( self, model: str = "DeepSeek-V3.1", secret_key: Optional[str] = None, gateway: str = "", lazy_certification: bool = True, **kwargs ): """初始化QueryDecompositionMeta任务。 Args: model (str|None): 模型名称,用于指定要使用的千帆模型。 secret_key (str, 可选): 用户鉴权token, 默认从环境变量中获取: os.getenv("APPBUILDER_TOKEN", ""). gateway (str, 可选): 后端网关服务地址,默认从环境变量中获取: os.getenv("GATEWAY_URL", "") lazy_certification (bool, 可选): 延迟认证,为True时在第一次运行时认证. Defaults to False. Returns: None """ super().__init__( QueryDecompositionMeta, model=model, secret_key=secret_key, gateway=gateway, lazy_certification=lazy_certification) @components_run_trace def run(self, message, stream=False, temperature=1e-10, top_p=0.0): """ 给定输入(message)到模型运行,同时指定运行参数,并返回结果。 Args: message (obj:`Message`): 输入消息,用于模型的主要输入内容。这是一个必需的参数。 stream (bool, optional): 指定是否以流式形式返回响应。默认为 False。 temperature (float, optional): 模型配置的温度参数,用于调整模型的生成概率。取值范围为 0.0 到 1.0,其中较低的值使生成更确定性,较高的值使生成更多样性。默认值为 1e-10。 top_p (float, optional): 影响输出文本的多样性,取值越大,生成文本的多样性越强。取值范围为 0.0 到 1.0,其中较低的值使生成更确定性,较高的值使生成更多样性。默认值为 0。 Returns: obj:`Message`: 模型运行后的输出消息。 """ return super().run(message=message, stream=stream, temperature=temperature, top_p=top_p) @components_run_stream_trace def tool_eval(self, query: str, **kwargs): """ tool_eval for function call """ if not query: raise ValueError("param `query` is required") msg = Message(query) model_configs = kwargs.get('model_configs', {}) temperature = model_configs.get("temperature", 1e-10) top_p = model_configs.get("top_p", 0.0) message = super().run(message=msg, stream=False, temperature=temperature, top_p=top_p) yield self.create_output(type="text", text=str(message.content), name="text", usage=message.token_usage) ================================================ FILE: python/core/components/v2/llms/query_rewrite/__init__.py ================================================ """query_rewrite""" from .component import QueryRewrite ================================================ FILE: python/core/components/v2/llms/query_rewrite/component.py ================================================ # Copyright (c) 2023 Baidu, Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """ 多轮改写 """ from typing import Optional from appbuilder.core.components.llms.base import CompletionBaseComponent from appbuilder.core.message import Message from appbuilder.utils.trace.tracer_wrapper import components_run_trace, components_run_stream_trace from appbuilder.core.components.llms.query_rewrite.base import QueryRewriteArgs class QueryRewrite(CompletionBaseComponent): """ 多轮改写大模型组件, 基于生成式大模型进行多轮对话query改写的组件。它主要用于理解和优化用户与机器人的交互过程,进行指代消解及省略补全。该组件支持不同的改写类型,可根据对话历史生成更准确的用户查询。 Examples: .. code-block:: python import appbuilder os.environ["APPBUILDER_TOKEN"] = '...' query_rewrite = appbuilder.QueryRewrite(model="DeepSeek-V3.1") answer = query_rewrite(appbuilder.Message(['我应该怎么办理护照?', '您可以查询官网或人工咨询', '我需要准备哪些材料?', '身份证、免冠照片一张以及填写完整的《中国公民因私出国(境)申请表》', '在哪里办']), rewrite_type="带机器人回复") """ name = "query_rewrite" version = "v1" meta = QueryRewriteArgs manifests = [ { "name": "query_rewrite", "description": "多轮改写大模型组件, 基于生成式大模型进行多轮对话query改写的组件。它主要用于理解和优化用户与机器人" "的交互过程,进行指代消解及省略补全。该组件支持不同的改写类型,可根据对话历史生成更准确的用户查询。", "parameters": { "type": "object", "properties": { "query": { "type": "string", "description": "输入消息,用于模型的主要输入内容" }, "rewrite_type": { "type": "string", "enum": [ "带机器人回复", "仅用户查询" ], "description": "改写类型选项,可选值为 '带机器人回复'和 '仅用户查询'。" } }, "required": [ "query" ] } } ] def __init__( self, model: str = "DeepSeek-V3.1", secret_key: Optional[str] = None, gateway: str = "", lazy_certification: bool = True, **kwargs ): """QueryRewrite模型。 Args: model (str|None): 模型名称,用于指定要使用的千帆模型。 secret_key (str, 可选): 用户鉴权token, 默认从环境变量中获取: os.getenv("APPBUILDER_TOKEN", ""). gateway (str, 可选): 后端网关服务地址,默认从环境变量中获取: os.getenv("GATEWAY_URL", "") lazy_certification (bool, 可选): 延迟认证,为True时在第一次运行时认证. Defaults to False. Returns: None """ super().__init__( QueryRewriteArgs, model=model, secret_key=secret_key, gateway=gateway, lazy_certification=lazy_certification) @components_run_trace def run(self, message, rewrite_type="带机器人回复", stream=False, temperature=1e-10, top_p=0): """ 使用给定的输入运行模型并返回结果。 Args: message (obj:`Message`): 输入消息,用于模型的主要输入内容。这是一个必需的参数。 rewrite_type (str, 可选): 改写类型选项,可选值为 '带机器人回复'(改写时参考user查询历史和assistant回复历史), '仅用户查询'(改写时参考user查询历史)。默认为"带机器人回复"。 stream (bool, 可选): 指定是否以流式形式返回响应。默认为 False。 temperature (float, 可选): 模型配置的温度参数,用于调整模型的生成概率。 取值范围为 0.0 到 1.0,其中较低的值使生成更确定性,较高的值使生成更多样性。 默认值为 1e-10。 top_p (float, 可选): 影响输出文本的多样性,取值越大,生成文本的多样性越强。 取值范围为 0.0 到 1.0,其中较低的值使生成更确定性,较高的值使生成更多样性。 默认值为 0。 Returns: obj:`Message`: 模型运行后的输出消息。 Raises: ValueError: 如果输入消息为空或不符合要求,将抛出 ValueError 异常。 """ if message is None: raise ValueError("input message is required") sum_len = sum(len(item) for item in message.content) if len(message.content) > 10 or len(message.content) % 2 == 0: raise ValueError(f"illegal input,expected len(message.content) in {1, 3, 5, 9}, got {len(message.content)}") if sum_len > 4000: raise ValueError(f"illegal input, expected length <= 4000, got {sum_len}") if rewrite_type == "带机器人回复": converted_input = ''.join([f"{'User:' if i % 2 == 0 else 'Assistant:'}\ {message.content[i]}\n" for i in range(len(message.content))]) else: converted_input = ''.join([f"User1: {message.content[i]}\n" for i in range(0, len(message.content), 2)]) message.content = converted_input return super().run(message=message, rewrite_type=rewrite_type, stream=stream, temperature=temperature, top_p=top_p) @components_run_stream_trace def tool_eval(self, query: str, rewrite_type: str = "带机器人回复", **kwargs): """ tool_eval for function call """ if not query: raise ValueError("param `query` is required") msg = Message(query) model_configs = kwargs.get('model_configs', {}) temperature = model_configs.get("temperature", 1e-10) top_p = model_configs.get("top_p", 0.0) message = super().run(message=msg, rewrite_type=rewrite_type, stream=True, temperature=temperature, top_p=top_p) for data in message.content: yield self.create_output(type="text", text=data, usage=message.token_usage) ================================================ FILE: python/core/components/v2/llms/similar_question/__init__.py ================================================ from .component import SimilarQuestion ================================================ FILE: python/core/components/v2/llms/similar_question/component.py ================================================ # Copyright (c) 2024 Baidu, Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """ similar question """ from typing import Optional from appbuilder.core.message import Message from appbuilder.core.components.llms.base import CompletionBaseComponent from appbuilder.utils.trace.tracer_wrapper import components_run_trace, components_run_stream_trace from appbuilder.core.components.llms.similar_question.base import SimilarQuestionMeta class SimilarQuestion(CompletionBaseComponent): r""" 基于输入的问题, 挖掘出与该问题相关的类似问题。广泛用于客服、问答等场景。 Examples: .. code-block:: python import os import appbuilder os.environ["APPBUILDER_TOKEN"] = "..." qa_mining = appbuilder.SimilarQuestion(model="DeepSeek-V3.1") msg = "我想吃冰淇淋,哪里的冰淇淋比较好吃?" msg = appbuilder.Message(msg) answer = qa_mining(msg) print("Answer: \n{}".format(answer.content)) """ name = "similar_question" version = "v1" meta = SimilarQuestionMeta manifests = [ { "name": "similar_question", "description": "基于输入的问题,挖掘出与该问题相关的类似问题。", "parameters": { "type": "object", "properties": { "query": { "type": "string", "description": "输入的问题,用于大模型根据该问题输出相关的类似问题。" } }, "required": [ "query" ] } } ] def __init__( self, model: str="DeepSeek-V3.1", secret_key: Optional[str] = None, gateway: str = "", lazy_certification: bool = True, **kwargs ): """初始化StyleRewrite模型。 Args: model (str|None): 模型名称,用于指定要使用的千帆模型。 secret_key (str, 可选): 用户鉴权token, 默认从环境变量中获取: os.getenv("APPBUILDER_TOKEN", ""). gateway (str, 可选): 后端网关服务地址,默认从环境变量中获取: os.getenv("GATEWAY_URL", "") lazy_certification (bool, 可选): 延迟认证,为True时在第一次运行时认证. Defaults to False. **kwargs: 其他关键字参数. Returns: None """ super().__init__( SimilarQuestionMeta, model=model, secret_key=secret_key, gateway=gateway, lazy_certification=lazy_certification, **kwargs) @components_run_trace def run(self, message, stream=False, temperature=1e-10, top_p=0.0, request_id=None): """ 给定输入(message)到模型运行,同时指定运行参数,并返回结果。 Args: message (obj:`Message`): 输入消息,用于模型的主要输入内容。这是一个必需的参数。 stream (bool, 可选): 指定是否以流式形式返回响应。默认为 False。 temperature (float, 可选): 模型配置的温度参数,用于调整模型的生成概率。取值范围为 0.0 到 1.0,其中较低的值使生成更确定性,较高的值使生成更多样性。默认值为 1e-10。 top_p(float, 可选): 影响输出文本的多样性,取值越大,生成文本的多样性越强。取值范围为 0.0 到 1.0,其中较低的值使生成更确定性,较高的值使生成更多样性。默认值为 0。 Returns: obj:`Message`: 模型运行后的输出消息。 """ return super().run(message=message, stream=stream, temperature=temperature, top_p=top_p, request_id=request_id) @components_run_stream_trace def tool_eval(self, query: str, **kwargs): """ 根据给定的query和可选参数生成并返回文本输出。 Args: query (str): 需要生成文本的输入查询字符串。 **kwargs: 其他可选参数。 Returns: Generator[Output]: 返回一个生成器,生成类型为Output的对象。 """ traceid = kwargs.get("_sys_traceid", "") msg = Message(query) model_configs = kwargs.get('model_configs', {}) temperature = model_configs.get("temperature", 1e-10) top_p = model_configs.get("top_p", 0.0) message = super().run(message=msg, stream=False, temperature=temperature, top_p=top_p, request_id=traceid) yield self.create_output(type="text", text=str(message.content), name="text", usage=message.token_usage) ================================================ FILE: python/core/components/v2/llms/style_rewrite/__init__.py ================================================ """StyleRewrite""" from .component import StyleRewrite ================================================ FILE: python/core/components/v2/llms/style_rewrite/component.py ================================================ # Copyright (c) 2023 Baidu, Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from appbuilder.core.components.llms.base import CompletionBaseComponent from appbuilder.core.message import Message from typing import Optional from appbuilder.utils.trace.tracer_wrapper import components_run_trace, components_run_stream_trace from appbuilder.core.components.llms.style_rewrite.base import StyleRewriteArgs class StyleRewrite(CompletionBaseComponent): """ 文本风格转写大模型组件, 基于生成式大模型对文本的风格进行改写,支持有营销、客服、直播、激励及教学五种话术。 Examples: .. code-block:: python import os import appbuilder os.environ["APPBUILDER_TOKEN"] = '...' style_rewrite = appbuilder.StyleRewrite(model="DeepSeek-V3.1") answer = style_rewrite(appbuilder.Message("文心大模型发布新版本"), style="激励话术") """ name = "style_rewrite" version = "v1" meta = StyleRewriteArgs manifests = [ { "name": "style_rewrite", "description": "能够将一段文本转换成不同的风格(营销、客服、直播、激励及教学话术),同时保持原文的基本意义不变。", "parameters": { "type": "object", "properties": { "query": { "type": "string", "description": "需要改写的文本。" }, "style": { "type": "string", "description": "想要转换的文本风格,目前有营销、客服、直播、激励及教学五种话术可选. 默认是营销话术。", "enum": ["营销话术", "客服话术", "直播话术", "激励话术", "教学话术"] } }, "required": [ "query" ] } } ] def __init__( self, model: str="DeepSeek-V3.1", secret_key: Optional[str] = None, gateway: str = "", lazy_certification: bool = True, **kwargs ): """初始化StyleRewrite模型。 Args: model (str|None): 模型名称,用于指定要使用的千帆模型。 secret_key (str, 可选): 用户鉴权token, 默认从环境变量中获取: os.getenv("APPBUILDER_TOKEN", ""). gateway (str, 可选): 后端网关服务地址,默认从环境变量中获取: os.getenv("GATEWAY_URL", "") lazy_certification (bool, 可选): 延迟认证,为True时在第一次运行时认证. Defaults to False. **kwargs: 其他关键字参数. Returns: None """ super().__init__( StyleRewriteArgs, model=model, secret_key=secret_key, gateway=gateway, lazy_certification=lazy_certification, **kwargs) @components_run_trace def run(self, message, style="营销话术", stream=False, temperature=1e-10, top_p=0.0, request_id=None): """ 使用给定的输入运行模型并返回结果。 Args: message (obj:`Message`): 输入消息,用于模型的主要输入内容。这是一个必需的参数。 style (str, optional): 想要转换的文本风格,目前有营销、客服、直播、激励及教学五种话术可选。默认为"营销话术"。 stream (bool, optional): 指定是否以流式形式返回响应。默认为 False。 temperature (float, optional): 模型配置的温度参数,用于调整模型的生成概率。取值范围为 0.0 到 1.0,其中较低的值使生成更确定性,较高的值使生成更多样性。默认值为 1e-10。 top_p (float, optional): 影响输出文本的多样性,取值越大,生成文本的多样性越强。取值范围为 0.0 到 1.0,其中较低的值使生成更确定性,较高的值使生成更多样性。默认值为 0。 Returns: obj:`Message`: 模型运行后的输出消息。 """ return super().run(message=message, style=style, stream=stream, temperature=temperature, top_p=top_p, request_id=request_id) @components_run_stream_trace def tool_eval(self, query: str, style: str = "营销话术", **kwargs): """ 执行工具评估函数 Args: name (str): 函数名称,本函数不使用该参数,但保留以符合某些框架的要求。 streaming (bool, optional): 是否以流的形式返回结果。默认为 False,即一次性返回结果。如果设置为 True,则以生成器形式逐个返回结果。 **kwargs: 其他参数,包含但不限于: _sys_traceid (str): 请求的跟踪ID,用于日志记录和跟踪。 model_configs (dict, optional): 模型配置参数,可选的键包括: temperature (float, optional): 温度参数,用于控制生成文本的随机性。默认为 1e-10。 top_p (float, optional): top_p 采样参数,用于控制生成文本的多样性。默认为 0.0。 Returns: 如果 streaming 为 False,则直接返回评估结果字符串。 如果 streaming 为 True,则以生成器形式逐个返回评估结果字符串。 Raises: ValueError: 如果缺少参数 'query'。 """ traceid = kwargs.get("_sys_traceid", "") if not query: raise ValueError("param `query` is required") msg = Message(query) if style not in ["营销话术", "客服话术", "直播话术", "激励话术", "教学话术"]: style = "营销话术" model_configs = kwargs.get('model_configs', {}) temperature = model_configs.get("temperature", 1e-10) top_p = model_configs.get("top_p", 0.0) message = super().run(message=msg, style=style, stream=False, temperature=temperature, top_p=top_p, request_id=traceid) yield self.create_output(type="text", text=str(message.content), name="text", usage=message.token_usage) ================================================ FILE: python/core/components/v2/llms/style_writing/__init__.py ================================================ # Copyright (c) 2024 Baidu, Inc. All Rights Reserved. # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from .component import StyleWriting ================================================ FILE: python/core/components/v2/llms/style_writing/component.py ================================================ # Copyright (c) 2023 Baidu, Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from appbuilder.core.components.llms.base import CompletionBaseComponent from appbuilder.core.message import Message from appbuilder.core.component import ComponentArguments from appbuilder.utils.trace.tracer_wrapper import components_run_trace, components_run_stream_trace from pydantic import Field from typing import Optional from appbuilder.core.components.llms.style_writing.base import StyleQueryChoices, LengthChoices, StyleWritingArgs class StyleWritingArgs(ComponentArguments): """ 风格写作配置 Attributes: message: Message = Field(...) style_query: StyleQueryChoices = Field(...) length: LengthChoices = Field(...) """ message: Message = Field(..., variable_name="query", description="输入消息,用于模型的主要输入内容,例如'帮我生成一个介绍保温杯的话术'") style_query: StyleQueryChoices = Field(..., variable_name="style_query", description="风格查询选项,可选值为 'B站', '小红书', '通用'。") length: LengthChoices = Field(..., variable_name="length", description="输出长度,可选值为 '短' (100), '中' (300), '长' (600)。") class StyleWriting(CompletionBaseComponent): """ 风格写作大模型组件, 基于生成式大模型进行风格写作,支持B站、小红书等多种风格,可用于文案、广告等多种场景。 Examples: .. code-block:: python import os import appbuilder # 请前往千帆AppBuilder官网创建密钥,流程详见:https://cloud.baidu.com/doc/AppBuilder/s/Olq6grrt6#1%E3%80%81%E5%88%9B%E5%BB%BA%E5%AF%86%E9%92%A5 os.environ["APPBUILDER_TOKEN"] = '...' style_writing = appbuilder.StyleWriting(model="DeepSeek-V3.1") answer = style_writing(appbuilder.Message("帮我写一篇关于人体工学椅的文案"), style_query="小红书", length=100) """ name = "style_writing" version = "v1" meta = StyleWritingArgs manifests = [ { "name": "style_writing", "description": "根据用户输入的文案要求和文案风格,生成符合特定风格的产品介绍或宣传文案。目前支持生成小红书风格、B站风格或通用风格的文案。", "parameters": { "type": "object", "properties": { "query": { "type": "string", "description": "用于描述生成文案的主题和要求。" }, "style": { "type": "string", "description": "用于定义文案生成的风格,包括通用、B站、小红书,默认为通用。", "enum": ["通用", "B站", "小红书"] }, "length": { "type": "integer", "description": "用于定义输出内容的长度。有效的选项包括 100(短)、300(中)、600(长),默认值为 100。", "enum": [100, 300, 600] } }, "required": [ "query" ] } } ] def __init__( self, model: str="DeepSeek-V3.1", secret_key: Optional[str] = None, gateway: str = "", lazy_certification: bool = True, **kwargs ): """初始化StyleRewrite模型。 Args: model (str|None): 模型名称,用于指定要使用的千帆模型。 secret_key (str, 可选): 用户鉴权token, 默认从环境变量中获取: os.getenv("APPBUILDER_TOKEN", ""). gateway (str, 可选): 后端网关服务地址,默认从环境变量中获取: os.getenv("GATEWAY_URL", "") lazy_certification (bool, 可选): 延迟认证,为True时在第一次运行时认证. Defaults to False. **kwargs: 其他关键字参数. Returns: None """ super().__init__( StyleWritingArgs, model=model, secret_key=secret_key, gateway=gateway, lazy_certification=lazy_certification, **kwargs) @components_run_trace def run(self, message, style_query="通用", length=100, stream=False, temperature=1e-10, top_p=0, request_id=None): """ 使用给定的输入运行模型并返回结果。 Args: message (obj:`Message`): 输入消息,用于模型的主要输入内容。这是一个必需的参数。 style_query (str): 风格查询选项,用于指定写作风格。有效的选项包括 'B站', '小红书', '通用'。默认值为 '通用'。 length (int): 输出内容的长度。有效的选项包括 100(短),300(中),600(长)。默认值为 100。 stream (bool, optional): 指定是否以流式形式返回响应。默认为 False。 temperature (float, optional): 模型配置的温度参数,用于调整模型的生成概率。取值范围为 0.0 到 1.0,其中较低的值使生成更确定性,较高的值使生成更多样性。默认值为 1e-10。 top_p (float, optional): 影响输出文本的多样性,取值越大,生成文本的多样性越强。取值范围为 0.0 到 1.0,其中较低的值使生成更确定性,较高的值使生成更多样性。默认值为 0。 request_id (str, optional): 请求ID,用于跟踪和识别请求。 Returns: obj:`Message`: 模型运行后的输出消息。 """ return super().run(message=message, style_query=style_query, length=length, stream=stream, temperature=temperature, top_p=top_p, request_id=request_id) @components_run_stream_trace def tool_eval(self, query: str, style: str = "通用", length: int = 100, **kwargs): """ 使用指定的模型和参数对输入的查询进行评估,并生成输出。 Args: query (str): 要评估的查询字符串。 style (str, optional): 评估的风格。默认为 "通用"。 length (int, optional): 输出文本的长度。默认为 100。 **kwargs: 关键字参数,可以包含以下可选参数: _sys_traceid (str): 系统跟踪ID。 model_configs (dict): 模型配置字典,可以包含 "temperature" 和 "top_p" 两个键。 Raises: ValueError: 如果查询字符串为空,则引发 ValueError 异常。 Yields: Output: 生成的输出对象,包含文本类型和文本内容。 """ traceid = kwargs.get("_sys_traceid", "") if not query: raise ValueError("param `query` is required") msg = Message(query) try: length = int(length) if length not in [100, 300, 600]: length = 100 except: length = 100 model_configs = kwargs.get('model_configs', {}) temperature = model_configs.get("temperature", 1e-10) top_p = model_configs.get("top_p", 0.0) message = super().run(message=msg, style_query=style, length=length, stream=False, temperature=temperature, top_p=top_p, request_id=traceid) yield self.create_output(type="text", text=str(message.content), usage=message.token_usage) ================================================ FILE: python/core/components/v2/llms/tag_extraction/__init__.py ================================================ from .component import TagExtraction ================================================ FILE: python/core/components/v2/llms/tag_extraction/component.py ================================================ # Copyright (c) 2023 Baidu, Inc. All Rights Reserved. # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 from typing import Optional # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from appbuilder.core.components.llms.base import CompletionBaseComponent from appbuilder.core.components.llms.tag_extraction.base import TagExtractionArgs from appbuilder.core.message import Message from appbuilder.utils.trace.tracer_wrapper import components_run_trace, components_run_stream_trace class TagExtraction(CompletionBaseComponent): """ 标签抽取组件,基于生成式大模型进行关键标签的抽取。 Examples: .. code-block:: python import appbuilder # 请前往千帆AppBuilder官网创建密钥,流程详见:https://cloud.baidu.com/doc/AppBuilder/s/Olq6grrt6#1%E3%80%81%E5%88%9B%E5%BB%BA%E5%AF%86%E9%92%A5 os.environ["APPBUILDER_TOKEN"] = '...' tag_extraction = appbuilder.TagExtraction(model="DeepSeek-V3.1") answer = tag_extraction(appbuilder.Message("从这段文本中抽取关键标签")) """ name = "tag_extraction" version = "v1" meta = TagExtractionArgs manifests = [ { "name": "tag_extraction", "description": "标签抽取组件,基于生成式大模型进行关键标签的抽取。", "parameters": { "type": "object", "properties": { "query": { "type": "string", "description": "输入消息,用于模型的主要输入内容" } }, "required": [ "query" ] } } ] def __init__( self, model: str = "DeepSeek-V3.1", secret_key: Optional[str] = None, gateway: str = "", lazy_certification: bool = True, **kwargs ): """初始化TagExtraction模型。 Args: model (str|None): 模型名称,用于指定要使用的千帆模型。 secret_key (str, 可选): 用户鉴权token, 默认从环境变量中获取: os.getenv("APPBUILDER_TOKEN", ""). gateway (str, 可选): 后端网关服务地址,默认从环境变量中获取: os.getenv("GATEWAY_URL", "") lazy_certification (bool, 可选): 延迟认证,为True时在第一次运行时认证. Defaults to False. Returns: None """ super().__init__( TagExtractionArgs, model=model, secret_key=secret_key, gateway=gateway, lazy_certification=lazy_certification) @components_run_trace def run(self, message, stream=False, temperature=1e-10, top_p=0.0): """ 使用给定的输入运行模型并返回结果。 Args: message (obj:`Message`, 必选): 输入消息,用于模型的主要输入内容。 stream (bool, 可选): 指定是否以流式形式返回响应。默认为 False。 temperature (float, 可选): 模型配置的温度参数,用于调整模型的生成概率。 取值范围为 0.0 到 1.0,其中较低的值使生成更确定性,较高的值使生成更多样性。 默认值为 1e-10。 top_p (float, 可选): 影响输出文本的多样性,取值越大,生成文本的多样性越强。 取值范围为 0.0 到 1.0,其中较低的值使生成更确定性,较高的值使生成更多样性。 默认值为 0。 Returns: obj:`Message`: 模型运行后的输出消息。 """ return super().run(message=message, stream=stream, temperature=temperature, top_p=top_p) @components_run_stream_trace def tool_eval(self, query: str, **kwargs): """ tool_eval for function call """ if not query: raise ValueError("param `query` is required") msg = Message(query) model_configs = kwargs.get('model_configs', {}) temperature = model_configs.get("temperature", 1e-10) top_p = model_configs.get("top_p", 0.0) message = super().run(message=msg, stream=False, temperature=temperature, top_p=top_p) yield self.create_output(type="text", text=str(message.content), usage=message.token_usage) ================================================ FILE: python/core/components/v2/mix_card_ocr/__init__.py ================================================ # Copyright (c) 2023 Baidu, Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. ================================================ FILE: python/core/components/v2/mix_card_ocr/component.py ================================================ # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. r"""身份证混贴识别组件""" import base64 import json from typing import Optional from appbuilder.core import utils from appbuilder.core._client import HTTPClient from appbuilder.core._exception import AppBuilderServerException, InvalidRequestArgumentError from appbuilder.core.component import Component from appbuilder.core.components.v2.mix_card_ocr.model import * from appbuilder.core.message import Message from appbuilder.utils.trace.tracer_wrapper import components_run_trace, components_run_stream_trace class MixCardOCR(Component): r""" 身份证混贴识别组件 Examples: .. code-block:: python import os import requests import appbuilder os.environ["GATEWAY_URL"] = "..." os.environ["APPBUILDER_TOKEN"] = "..." # 从BOS存储读取样例文件 image_url="https://bj.bcebos.com/v1/appbuilder/test_mix_card_ocr.jpeg?authorization=bce-auth-v1%2FALTAKGa8m4qCUasgoljdEDAzLm%2F2024-01-24T06%3A18%3A11Z%2F-1%2Fhost%2F695b8041c1ded194b9e80dbe1865e4393da5a3515e90d72d81ef18296bd29598" raw_image = requests.get(image_url).content # 输入参数为一张图片 inp = appbuilder.Message(content={"raw_image": raw_image}) # 进行识别 mix_card_ocr = MixCardOCR() out = mix_card_ocr.run(inp) # 打印识别结果 print(out.content) """ name = "mixcard_ocr" version = "v1" manifests = [ { "name": "mixcard_ocr", "description": "当身份证正反面在同一张图片上,需要识别图片中身份证正反面所有字段时,使用该工具", "parameters": { "type": "object", "properties": { "file_names": { "type": "array", "items": { "type": "string" }, "description": "待识别文件的文件名" } }, "required": ["file_names"] } } ] @HTTPClient.check_param @components_run_trace def run(self, message: Message, timeout: float = None, retry: int = 0) -> Message: """ 执行身份证识别操作 Args: message (Message): 包含待识别图片或图片下载URL的Message对象. 示例: Message(content={"raw_image": b"..."}) 或 Message(content={"url": "https://image/download/url"}). timeout (float, 可选): HTTP请求的超时时间,默认为None. retry (int, 可选): HTTP请求的重试次数,默认为0. Returns: Message: 包含身份证识别结果的Message对象. """ inp = MixCardOCRInMsg(**message.content) request = MixCardOCRRequest() if inp.url: request.url = inp.url if inp.raw_image: request.image = base64.b64encode(inp.raw_image) request.detect_risk = "false" request.detect_quality = "false" request.detect_photo = "false" request.detect_card = "false" response = self._recognize(request, timeout, retry) out = MixCardOCROutMsg() for res in response.words_result: card_type = res.card_info.card_type if card_type != "idcard_back" and card_type != "idcard_front": continue ref = out.front if card_type == "idcard_back": ref = out.back loc = res.card_info.card_location ref.position = MixCardPosition( left=loc.left, top=loc.top, width=loc.width, height=loc.height) for key, val in res.card_result.items(): position = MixCardPosition(left=val.location.left, top=val.location.top, width=val.location.width, height=val.location.height) ref.fields.append(MixCardField( key=key, value=val.words, position=position)) out.direction = response.direction return Message(content=out.model_dump()) def _recognize(self, request: MixCardOCRRequest, timeout: float = None, retry: int = 0, request_id: str = None) -> MixCardOCRResponse: r"""调用底层身份证混贴识别 参数: request (obj: `GeneralOCRRequest`) : 通用文字识别输入参数 返回: response (obj: `GeneralOCRResponse`): 通用文字识别返回结果 """ if not request.image and not request.url: raise ValueError( "request format error, one of image or url must be set") data = request.model_dump() if self.http_client.retry.total != retry: self.http_client.retry.total = retry headers = self.http_client.auth_header(request_id) headers['content-type'] = 'application/x-www-form-urlencoded' url = self.http_client.service_url("/v1/bce/aip/ocr/v1/multi_idcard") response = self.http_client.session.post( url, headers=headers, data=data, timeout=timeout) self.http_client.check_response_header(response) data = response.json() self.http_client.check_response_json(data) request_id = self.http_client.response_request_id(response) self.__class__._check_service_error(request_id, data) response = MixCardOCRResponse(**data) response.request_id = request_id return response @staticmethod def _check_service_error(request_id: str, data: dict): r"""个性化服务response参数检查 参数: request (dict) : 通用文字识别body返回 返回: 无 """ if "error_code" in data or "error_msg" in data: raise AppBuilderServerException( request_id=request_id, service_err_code=data.get("error_code"), service_err_message=data.get("error_msg") ) @components_run_stream_trace def tool_eval(self, file_names: Optional[list] = [], **kwargs): """ 对指定文件进行OCR识别。 Args: file_names (Optional[List], optional): 要识别的文件名列表。 **kwargs: 其他参数。 Returns: ComponentOutput: 识别结果。 Raises: InvalidRequestArgumentError: 如果请求格式错误,即文件URL不存在时抛出。 """ result = {} traceid = kwargs.get("_sys_traceid", "") sys_file_names = file_names if not sys_file_names: sys_file_names = kwargs.get("_sys_file_names", []) sys_file_urls = kwargs.get("_sys_file_urls", {}) for file_name in sys_file_names: if utils.is_url(file_name): file_url = file_name else: file_url = sys_file_urls.get(file_name, None) if file_url is None: raise InvalidRequestArgumentError( f"request format error, file {file_name} url does not exist") request = MixCardOCRRequest() request.url = file_url request.detect_risk = "false" request.detect_quality = "false" request.detect_photo = "false" request.detect_card = "false" response = self._recognize(request, request_id=traceid) out = MixCardOCROutMsg() for res in response.words_result: card_type = res.card_info.card_type if card_type != "idcard_back" and card_type != "idcard_front": continue ref = out.front if card_type == "idcard_back": ref = out.back for key, val in res.card_result.items(): ref.fields.append(MixCardField( key=key, value=val.words, position=None)) out.direction = response.direction result[file_name] = out.model_dump() result = json.dumps(result, ensure_ascii=False) llm_result = self.create_output( type="text", visible_scope="llm", text={"info": result}, name="llm_text" ) yield llm_result user_result = self.create_output( type="text", visible_scope="user", text="", name="user_text" ) yield user_result ================================================ FILE: python/core/components/v2/mix_card_ocr/model.py ================================================ # Copyright (c) 2023 Baidu, Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """身份证混贴数据类""" import proto from typing import List, Optional from pydantic import BaseModel, Field class MixCardOCRRequest(BaseModel): """ 身份证混贴识别 属性: image (str): 可选。图像内容的base64编码 url (str): 可选,图像的URL地址,经过base64编码 图像大小必须小于4MB,图像的最短边长大于15像素,最长边长大于4096像素 detect_risk(str): 是否检测风险(身份证复印件、临时身份证、身份证翻拍、修改过的身份证)类型,可选值是"true"或“false” detect_quality(str): 是否开启身份证质量类型(边框/四角不完整、头像或关键字段被遮挡/马赛克)检测功能,可选值是"true"或“false” detect_photo(str): 是否检测头像内容,默认不检测,可选值是"true"或“false” detect_card(str): 是否检测身份证并进行裁剪,"true"或“false” """ image: str = Field(default="", description="图像内容的base64编码") url: str = Field(default="", description="图像的URL地址,经过base64编码") detect_risk: str = Field( default="", description="是否检测风险(身份证复印件、临时身份证、身份证翻拍、修改过的身份证)类型,可选值是\"true\"或“false\"") detect_quality: str = Field(default="", description="是否开启身份证质量类型(边框" "四角不完整、头像或关键字段被遮挡/马赛克)检测功能,可选值是\"true\"或“false\"") detect_photo: str = Field( default="", description="是否检测头像内容,默认不检测,可选值是\"true\"或“false\"") detect_card: str = Field( default="", description="是否检测身份证并进行裁剪,\"true\"或“false\"") class MixCardOCRLocation(BaseModel): """ 位置信息. 属性: left (int): 表示定位位置的长方形左上顶点的水平坐标 top (int): 表示定位位置的长方形左上顶点的垂直坐标 width (int): 表示定位位置的长方形的宽度 height (int): 表示定位位置的长方形的高度 """ left: int = Field(default=0, description="表示定位位置的长方形左上顶点的水平坐标") top: int = Field(default=0, description="表示定位位置的长方形左上顶点的垂直坐标") width: int = Field(default=0, description="表示定位位置的长方形的宽度") height: int = Field(default=0, description="表示定位位置的长方形的高度") class MixCardOCRInfo(BaseModel): """ 身份证混贴手识别结果 属性: card_location (MixCardLocation): 身份证的位置信息(坐标0点为左上角) card_type(str): idcard_front(头像面)、idcard_back(国徽面) image_status (str): normal-识别正常、 non_idcard-上传的图片中不包含身份证 、blurred-身份证模糊 other_type_card-其他类型证照 、over_exposure-身份证关键字段反光或过曝 、over_dark-身份证欠曝(亮度过低) unknown-未知状态 """ card_location: Optional[MixCardOCRLocation] = Field( default=None, description="身份证的位置信息(坐标0点为左上角)") card_type: str = Field( default="", description="idcard_front(头像面)、idcard_back(国徽面)") image_status: str = Field( default="", description="normal-识别正常、 non_idcard-上传的图片中不包含身份证 、blurred-身份证模糊") direction: int = Field(default=0, description="身份证正反面,0-正面,1-背面") idcard_number_type: int = Field( default=0, description="身份证号类型,0-普通身份证号码,1-港澳台身份证号码,2-护照号码") class MixCardOCRResult(BaseModel): """身份证混贴别结果 属性: words (str): 文本信息 location(MixCardOCRLocation): 位置信息 """ words: str = Field(default="", description="文本信息") location: Optional[MixCardOCRLocation] = Field( default=None, description="位置信息") class MixOCRCardInfoResult(BaseModel): """身份证混贴信息 属性: card_result (Map[str,MixCardOCRResult]): 身份证字段信息 card_info(MixCardOCRInfo): 身份证信息 """ card_result: Optional[dict[str, MixCardOCRResult]] = Field( default=None, description="身份证字段信息") card_info: Optional[MixCardOCRInfo] = Field( default=None, description="身份证信息") class MixCardOCRResponse(BaseModel): """身份证混贴识别结果 属性: request_id(str): 请求ID log_id (int): 用于问题跟踪的唯一日志ID words_result (List[MixOCRCardInfoResult]): 识别结果列表 direction (int): 当detect_direction=true返回改字段,1(未定义)、 0(正向)、1(逆时针90度)、2(逆时针180度)、3(逆时针270度) pdf_file_size (str): 输入PDF文件的总页数。当pdf_file参数有效时返回 """ request_id: str = Field(default="", description="请求ID") log_id: int = Field(default=0, description="用于问题跟踪的唯一日志ID") words_result: Optional[list[MixOCRCardInfoResult] ] = Field(default=None, description="识别结果列表") direction: int = Field( default=0, description="当detect_direction=true返回改字段,1(未定义)、0(正向)、1(逆时针90度)、2(逆时针180度)、3(逆时针270度)") class MixCardOCRInMsg(BaseModel): """ 手写体文字识别输入消息 属性: raw_image(bytes): 图像原始内容 url(str): 图像下载链接 """ raw_image: bytes = b'' # 原始图片byte数组 url: str = "" # 图片可下载链接 class MixCardPosition(BaseModel): """位置信息 属性: left (int): 表示定位位置的长方形左上顶点的水平坐标 top (int): 表示定位位置的长方形左上顶点的垂直坐标 width (int): 表示定位位置的长方形的宽度 height (int): 表示定位位置的长方形的高度 """ left: int top: int width: int height: int class MixCardField(BaseModel): """ 字段信息 属性: key(str): 字段名 value (str): 字段值 position(MixCardPosition): 字段位置信息 """ key: str value: str position: Optional[MixCardPosition] = None class MixCardContent(BaseModel): """正/反识别结果 属性: fields(List[MixCardField]):字段列表 position(MixCardPosition): 正/反面在图像中的位置信息 """ fields: List[MixCardField] = list() position: MixCardPosition = None class MixCardOCROutMsg(BaseModel): """身份证混贴识别结果 属性: front(MixCardField): 人像面信息 back(MixCardField): 国徽面信息 direction(int): 图像旋转角度,0(正向),- 1(逆时针90度),- 2(逆时针180度),- 3(逆时针270度) """ front: MixCardContent = MixCardContent() back: MixCardContent = MixCardContent() direction: int = 0 ================================================ FILE: python/core/components/v2/object_recognize/__init__.py ================================================ # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. ================================================ FILE: python/core/components/v2/object_recognize/component.py ================================================ # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """object recognize component.""" import base64 import json import os from typing import Optional from appbuilder.core._client import HTTPClient from appbuilder.core.component import Component from appbuilder.core.message import Message from appbuilder.core._exception import AppBuilderServerException, InvalidRequestArgumentError from appbuilder.core.components.object_recognize.model import * from appbuilder.utils.trace.tracer_wrapper import components_run_trace, components_run_stream_trace class ObjectRecognition(Component): r""" 提供通用物体及场景识别能力,即对于输入的一张图片(可正常解码,且长宽比适宜),输出图片中的多 个物体及场景标签。 Examples: .. code-block:: python import appbuilder # 请前往千帆AppBuilder官网创建密钥,流程详见:https://cloud.baidu.com/doc/AppBuilder/s/Olq6grrt6#1%E3%80%81%E5%88%9B%E5%BB%BA%E5%AF%86%E9%92%A5 os.environ["APPBUILDER_TOKEN"] = '...' object_recognition = appbuilder.ObjectRecognition() with open("./object_recognition_test.jepg", "rb") as f: out = self.component.run(appbuilder.Message(content={"raw_image": f.read()})) print(out.content) """ name = "object_recognition" version = "v1" manifests = [ { "name": "object_recognition", "description": "提供通用物体及场景识别能力,即对于输入的一张图片,输出图片中的多个物体及场景标签。", "parameters": { "type": "object", "properties": { "img_url": { "type": "string", "description": "待识别图片的url,根据该url能够获取图片" }, "img_name": { "type": "string", "description": "待识别图片的文件名,用于生成图片url" } }, "anyOf": [ { "required": [ "img_url" ] }, { "required": [ "img_name" ] } ] } } ] @HTTPClient.check_param @components_run_trace def run(self, message: Message, timeout: float = None, retry: int = 0) -> Message: """ 通用物体识别 Args: message (Message): 输入图片或图片url下载地址用于执行识别操作。 例如: Message(content={"raw_image": b"..."}) 或 Message(content={"url": "https://image/download/url"})。 timeout (float, optional): HTTP超时时间,默认为None。 retry (int, optional): HTTP重试次数,默认为0。 Returns: Message: 模型识别结果。 例如: Message(content={"result":[{"keyword":"苹果", "score":0.94553,"root":"植物-蔷薇科"},{"keyword":"姬娜果","score":0.730442,"root":"植物-其它"}, {"keyword":"红富士","score":0.505194,"root":"植物-其它"}]}) """ inp = ObjectRecognitionInMsg(**message.content) req = ObjectRecognitionRequest() if inp.raw_image: req.image = base64.b64encode(inp.raw_image) if inp.url: req.url = inp.url result, _ = self._recognize(req, timeout, retry) result_dict = proto.Message.to_dict(result) out = ObjectRecognitionOutMsg(**result_dict) return Message(content=out.model_dump()) def _recognize(self, request: ObjectRecognitionRequest, timeout: float = None, retry: int = 0, request_id: str = None) -> ObjectRecognitionResponse: r"""调用底层接口进行通用物体与场景识别 参数: request (obj: `ObjectRecognitionRequest`) : 通用物体与场景识别输入参数 返回: response (obj: `ObjectRecognitionResponse`): 通用物体与场景识别返回结果 """ if not request.image and not request.url: raise ValueError("request format error, one of image or url must be set") data = ObjectRecognitionRequest.to_dict(request) if self.http_client.retry.total != retry: self.http_client.retry.total = retry headers = self.http_client.auth_header(request_id) headers['content-type'] = 'application/x-www-form-urlencoded' url = self.http_client.service_url("/v1/bce/aip/image-classify/v2/advanced_general") response = self.http_client.session.post(url, headers=headers, data=data, timeout=timeout) self.http_client.check_response_header(response) data = response.json() self.http_client.check_response_json(data) request_id = self.http_client.response_request_id(response) self.__class__._check_service_error(request_id,data) object_response = ObjectRecognitionResponse.from_json(payload=json.dumps(data)) object_response.request_id = request_id return object_response, data @staticmethod def _check_service_error(request_id: str, data: dict): r"""个性化服务response参数检查 参数: request (dict) : 通用物体与场景识别body返回 返回: 无 """ if "error_code" in data or "error_msg" in data: raise AppBuilderServerException( request_id=request_id, service_err_code=data.get("error_code"), service_err_message=data.get("error_msg") ) @components_run_stream_trace def tool_eval(self, img_url: Optional[str] = '', img_name: Optional[str] = '', **kwargs): """ 对给定的图片进行物体识别,并返回识别结果。 Args: img_url (str, optional): 图片的URL地址。默认为空字符串。 img_name (str, optional): 图片的名称。默认为空字符串。 **kwargs: 其他关键字参数。 Returns: Generator[Output, NoneType, NoneType]: 生成器,包含识别结果的输出对象。 Raises: InvalidRequestArgumentError: 如果请求格式错误,例如文件名未设置或文件URL不存在,则引发此异常。 """ traceid = kwargs.get("_sys_traceid", "") if not img_url: file_urls = kwargs.get("_sys_file_urls", {}) img_path = img_name if not img_path: raise InvalidRequestArgumentError("request format error, file name is not set") img_name = os.path.basename(img_path) img_url = file_urls.get(img_name, None) if not img_url: raise InvalidRequestArgumentError(f"request format error, file {img_name} url does not exist") score_threshold = kwargs.get("score_threshold", 0.5) req = ObjectRecognitionRequest(url=img_url) result, raw_data = self._recognize(req, request_id=traceid) result = proto.Message.to_dict(result) results = [] for item in result["result"]: if item["score"] < score_threshold and len(results) > 0: continue res = { "物体或场景名称": item["keyword"], "置信度": item["score"], "所属类别": item["root"], } results.append(res) res = json.dumps(results, ensure_ascii=False, indent=4) yield self.create_output(type="text", text=res, raw_data=raw_data, visible_scope='llm') yield self.create_output(type="text", text="", raw_data=raw_data, visible_scope='user') ================================================ FILE: python/core/components/v2/plant_recognize/__init__.py ================================================ # Copyright (c) 2023 Baidu, Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. ================================================ FILE: python/core/components/v2/plant_recognize/component.py ================================================ # Copyright (c) 2023 Baidu, Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. r"""植物识别组件""" import base64 from appbuilder.core.component import Component from appbuilder.core.message import Message from appbuilder.core._client import HTTPClient from appbuilder.core._exception import AppBuilderServerException from appbuilder.core.components.plant_recognize.model import * from typing import Generator, Union from appbuilder.utils.trace.tracer_wrapper import components_run_trace, components_run_stream_trace from appbuilder.core.components.plant_recognize.model import TOP_NUM, BAIKE_NUM class PlantRecognition(Component): r""" 植物识别组件,即对于输入的一张图片(可正常解码,且长宽比适宜),输出图片中的植物识别结果 Examples: .. code-block:: python import os import requests import appbuilder # 请前往千帆AppBuilder官网创建密钥,流程详见:https://cloud.baidu.com/doc/AppBuilder/s/Olq6grrt6#1%E3%80%81%E5%88%9B%E5%BB%BA%E5%AF%86%E9%92%A5 os.environ["GATEWAY_URL"] = "..." os.environ["APPBUILDER_TOKEN"] = "..." image_url = "https://bj.bcebos.com/v1/appbuilder/palnt_recognize_test.jpg?authorization=bce-auth-v1%2FALTAKGa8m4qCUasgoljdEDAzLm%2F2024-01-23T09%3A51%3A03Z%2F-1%2Fhost%2Faa2217067f78f0236c8262cdd89a4b4f4b2188d971ca547c53d01742af4a2cbe" # 从BOS存储读取样例文件 raw_image = requests.get(image_url).content inp = appbuilder.Message(content={"raw_image": raw_image}) # inp = Message(content={"url": image_url}) # 运行植物识别 plant_recognize = appbuilder.PlantRecognition() out = plant_recognize.run(inp) # 打印识别结果 print(out.content) """ name = "plant_rec" version = "v1" manifests = [ { "name": "plant_rec", "description": "用于识别图片中植物类别", "parameters": { "type": "object", "properties": { "img_name": { "type": "string", "description": "待识别图片的文件名" }, "img_url": { "type": "string", "description": "待识别图片的url" } }, "anyOf": [ { "required": [ "img_name" ] }, { "required": [ "img_url" ] } ] } } ] @HTTPClient.check_param @components_run_trace def run(self, message: Message, timeout: float = None, retry: int = 0) -> Message: """ 输入图片并识别其中的植物 Args: message (Message): 输入图片或图片url下载地址用于执行识别操作. 举例: Message(content={"raw_image": b"..."}) 或 Message(content={"url": "https://image/download/uel"}). timeout (float, optional): HTTP超时时间,默认为None retry (int, optional): HTTP重试次数,默认为0 Returns: Message: 模型识别结果 """ inp = PlantRecognitionInMsg(**message.content) request = PlantRecognitionRequest() if inp.url: request.url = inp.url if inp.raw_image: request.image = base64.b64encode(inp.raw_image) request.top_num = 5 request.baike_num = 0 response = self.__recognize(request, timeout, retry) plant_score_list = [] [plant_score_list.append(PlantScore(name=plant.name, score=plant.score)) for plant in response.result] out = PlantRecognitionOutMsg(plant_score_list=plant_score_list) return Message(content=out.model_dump()) def __recognize( self, request: PlantRecognitionRequest, timeout: float = None, retry: int = 0, request_id: str = None, ) -> PlantRecognitionResponse: r"""调用底层接口植物识别 参数: request (obj: `PlantRecognitionRequest`) : 植物识别输入参数 返回: response (obj: `PlantRecognitionResponse`): 植物识别返回结果 """ if not request.image and not request.url: raise ValueError("request format error, one of image or url must be set") data = PlantRecognitionRequest.to_dict(request) if retry != self.http_client.retry.total: self.http_client.retry.total = retry headers = self.http_client.auth_header(request_id) headers['content-type'] = 'application/x-www-form-urlencoded' url = self.http_client.service_url("/v1/bce/aip/image-classify/v1/plant") response = self.http_client.session.post(url, data=data, timeout=timeout, headers=headers) self.http_client.check_response_header(response) data = response.json() self.http_client.check_response_json(data) request_id = self.http_client.response_request_id(response) self.__class__.__check_service_error(request_id, data) return PlantRecognitionResponse(data, request_id=request_id) @components_run_stream_trace def tool_eval( self, img_name: str = "", img_url: str = "", **kwargs, ) -> Union[Generator[str, None, None], str]: """ 用于工具的执行,通过调用底层接口进行植物识别 Args: name (str): 工具名 streaming (bool): 是否流式返回 origin_query (str): 用户原始query **kwargs: 工具调用的额外关键字参数 Returns: Union[Generator[str, None, None], str]: 植物识别结果,包括识别出的植物类别和相应的置信度信息 """ traceid = kwargs.get("_sys_traceid", "") file_urls = kwargs.get("_sys_file_urls", {}) rec_res = self._recognize_w_post_process(img_name, img_url, file_urls, request_id=traceid) rec_res = self.create_output( type="text", text=rec_res, ) yield rec_res def _recognize_w_post_process(self, img_name, img_url, file_urls, request_id=None): r"""调底层接口对图片或图片url进行植物识别,并返回类别及其置信度 参数: img_name (str): 图片文件名 img_url (str): 图片url file_urls (dict): 文件名与对应文件url的映射 返回: str: 植物识别结果,包括识别出的动物类别和相应的置信度信息 """ req = PlantRecognitionRequest() if img_name in file_urls: req.url = file_urls[img_name] if img_url: if img_url in file_urls: img_url = file_urls[img_url] req.url = img_url req.top_num = TOP_NUM req.baike_num = BAIKE_NUM result = self.__recognize(req, request_id=request_id) result_dict = proto.Message.to_dict(result) rec_res = "模型识别结果为:\n" for rec_info in result_dict['result']: rec_res += "类别: {} 置信度: {}\n".format(rec_info['name'], rec_info['score']) return rec_res @staticmethod def __check_service_error(request_id: str, data: dict): r"""个性化服务response参数检查 参数: request (dict) : 地标识别body返回 返回: 无 """ if "error_code" in data or "error_msg" in data: raise AppBuilderServerException( request_id=request_id, service_err_code=data.get("error_code"), service_err_message=data.get("error_msg") ) ================================================ FILE: python/core/components/v2/qrcode_ocr/__init__.py ================================================ ================================================ FILE: python/core/components/v2/qrcode_ocr/component.py ================================================ # Copyright (c) 2023 Baidu, Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """qrcode ocr component.""" import base64 import json from typing import Optional from appbuilder.core import utils from appbuilder.core.component import Component from appbuilder.core.components.v2.qrcode_ocr.model import * from appbuilder.core.message import Message from appbuilder.core._client import HTTPClient from appbuilder.core._exception import AppBuilderServerException, InvalidRequestArgumentError from appbuilder.utils.trace.tracer_wrapper import components_run_trace, components_run_stream_trace class QRcodeOCR(Component): r""" 对图片中的二维码、条形码进行检测和识别,返回存储的文字信息及其位置信息。 Examples: .. code-block:: python import appbuilder # 请前往千帆AppBuilder官网创建密钥,流程详见:https://cloud.baidu.com/doc/AppBuilder/s/Olq6grrt6#1%E3%80%81%E5%88%9B%E5%BB%BA%E5%AF%86%E9%92%A5 os.environ["APPBUILDER_TOKEN"] = '...' qrcode_ocr = appbuilder.QRcodeOCR() with open("./qrcode_ocr_test.png", "rb") as f: out = self.component.run(appbuilder.Message(content={"raw_image": f.read(),"location": "true"})) print(out.content) """ name = "qrcode_ocr" version = "v1" manifests = [ { "name": "qrcode_ocr", "description": "需要对图片中的二维码、条形码进行检测和识别,返回存储的文字信息及其位置信息,使用该工具", "parameters": { "type": "object", "properties": { "file_names": { "type": "array", "items": { "type": "string" }, "description": "待识别文件的文件名" }, "location": { "type": "string", "description": "是否输出二维码/条形码位置信息" } }, "required": ["file_names"] } } ] @HTTPClient.check_param @components_run_trace def run(self, message: Message, location: str = "true", timeout: float = None, retry: int = 0) -> Message: """ 执行二维码识别操作。 Args: message (Message): 输入的图片或图片URL下载地址,用于执行识别操作。例如: Message(content={"raw_image": b"...", "location": ""}) 或 Message(content={"url": "https://image/download/url"})。 location (str, 可选): 是否需要返回二维码位置信息,默认为 "true"。 timeout (float, 可选): HTTP请求的超时时间。 retry (int, 可选): HTTP请求的重试次数。 Returns: Message: 识别结果,包含识别到的二维码信息。例如: Message(name=msg, content={'codes_result': [{'type': 'QR_CODE', 'text': ['http://weixin.qq.com/r/cS7M1PHE5qyZrbW393tj'], 'location': {'top': 63, 'left': 950, 'width': 220, 'height': 211}}, ...]}, mtype=dict) Raises: InvalidRequestArgumentError: 如果 location 参数非法,将抛出该异常。 """ inp = QRcodeInMsg(**message.content) req = QRcodeRequest() if inp.raw_image: req.image = base64.b64encode(inp.raw_image) if inp.url: req.url = inp.url if not isinstance(location, str) or location not in ('true', 'false'): raise InvalidRequestArgumentError( f"illegal location, expected location is 'true' or 'false', got {location}") req.location = location result = self._recognize(req, timeout, retry) out = QRcodeOutMsg(**result.model_dump()) return Message(content=out.model_dump()) def _recognize(self, request: QRcodeRequest, timeout: float = None, retry: int = 0, request_id: str = None) -> QRcodeResponse: r"""调用二维码识别底层能力 参数: request (obj: `QRcodeRequest`) : 二维码识别输入参数 返回: response (obj: `QRcodeResponse`): 二维码识别返回结果 """ if not request.image and not request.url: raise ValueError( "request format error, one of image or url must be set") data = QRcodeRequest.model_dump(request) if self.http_client.retry.total != retry: self.http_client.retry.total = retry headers = self.http_client.auth_header(request_id) headers['content-type'] = 'application/x-www-form-urlencoded' headers['Accept'] = 'application/json' url = self.http_client.service_url("/v1/bce/aip/ocr/v1/qrcode") response = self.http_client.session.post( url, headers=headers, data=data, timeout=timeout) self.http_client.check_response_header(response) data = response.json() self.http_client.check_response_json(data) request_id = self.http_client.response_request_id(response) self.__class__._check_service_error(request_id, data) res = QRcodeResponse(**data) res.request_id = request_id return res @staticmethod def _check_service_error(request_id: str, data: dict): r"""个性化服务response参数检查 参数: request (dict) : 二维码识别body返回 返回: 无 """ if "error_code" in data or "error_msg" in data: raise AppBuilderServerException( request_id=request_id, service_err_code=data.get("error_code"), service_err_message=data.get("error_msg") ) @components_run_stream_trace def tool_eval(self, file_names:Optional[list]=[], location: Optional[str]="false", **kwargs): """ ToolEval方法,用于执行二维码识别操作。 Args: file_names (list, 可选): 待识别文件的文件名列表。 location (str, 可选): 是否需要返回二维码位置信息,默认为 "false"。 Yields: ComponentOutput: 识别结果,包含识别到的二维码信息。 """ result = {} traceid = kwargs.get("_sys_traceid", "") # file_name sys_file_names = file_names if not sys_file_names: sys_file_names = kwargs.get("_sys_file_names", []) sys_file_urls = kwargs.get("_sys_file_urls", {}) for file_name in sys_file_names: if utils.is_url(file_name): file_url = file_name else: file_url = sys_file_urls.get(file_name, None) if file_url is None: raise InvalidRequestArgumentError( f"request format error, file {file_name} url does not exist") req = QRcodeRequest() req.url = file_url if not isinstance(location, str) or location.lower() not in ("true", "false"): raise InvalidRequestArgumentError( f"illegal location, expected location is 'true' or 'false', got {location}" ) req.location = location.lower() resp = self._recognize(req, request_id=traceid) result[file_name] = [ item["text"] for item in resp.model_dump().get("codes_result", []) ] result = json.dumps(result, ensure_ascii=False) llm_result = self.create_output( type="text", visible_scope="llm", text={"info": result}, name="llm_text" ) yield llm_result user_result = self.create_output( type="text", visible_scope="user", text={"info": ""}, name="user_text" ) yield user_result ================================================ FILE: python/core/components/v2/qrcode_ocr/model.py ================================================ # Copyright (c) 2023 Baidu, Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """qrcode ocr model.""" import proto from typing import List, Optional from pydantic import BaseModel, Field class QRcodeRequest(BaseModel): """二维码识别请求体参数. Attributes: image (str): 可选。图像内容的base64编码。 url (str): 可选。图像的URL地址,经过base64编码。 图像大小必须小于4MB,图像的最短边长大于15像素,最长边长大于4096像素。 location (str): 可选。是否输出二维 - false:默认值,不返回位置信息; - true:返回图中二维码/条形码的位置信息,包括上边距、左边距、宽度、高度 必须设置image或url属性之一,如果两者都设置了,将使用image属性。 """ image: str = Field(default="", description="可选。图像内容的base64编码") url: str = Field( default="", description= "可选。图像的URL地址,经过base64编码,图像大小必须小于4MB,\n" "图像的最短边长大于15像素,最长边长大于4096像素 ") location: str = Field(default="false", description="可选。是否输出二维码/条形码位置信息") class QRcodeLocation(BaseModel): """条形码/二维码位置信息。 属性: top (int): 条形码/二维码的上边距。 left (int): 条形码/二维码的左边距。 width (int): 条形码/二维码的宽度。 height (int): 条形码/二维码的高度。 """ top: int = Field(default=0, description="条形码/二维码的上边距") left: int = Field(default=0, description="条形码/二维码的左边距") width: int = Field(default=0, description="条形码/二维码的宽度") height: int = Field(default=0, description="条形码/二维码的高度") class QRcodeRes(BaseModel): """二维码识别结果。 属性: type (str): 识别码类型条码类型包括:9种条形码(UPC_A、UPC_E、EAN_13、EAN_8、CODE_39、CODE_93、CODE_128、ITF、CODABAR), 4种二维码(QR_CODE、DATA_MATRIX、AZTEC、PDF_417)。 text (list[str]): 条形码/二维码识别内容,目前仅支持输出中英文结果。 location (QRcodeLocation): 条形码/二维码位置信息,包括上边距、左边距、宽度、高度,当请求参数 location = true 时返回 """ type: str = Field(default="", description="识别码类型条码类型包括:9种条形码(UPC_A、UPC_E、EAN_13\n" "、EAN_8、CODE_39、CODE_93、CODE_128、ITF、CODABAR),\n" "4种二维码(QR_CODE、DATA_MATRIX、AZTEC、PDF_417)。") text: list[str] = Field(default=[], description="条形码/二维码识别内容,目前仅支持输出中英文结果") location: Optional[QRcodeLocation] = Field(default=None, description="条形码/二维码位置信息,包括上边距、左边距、宽度、高度,当请求参数 location = true 时返回") class QRcodeResponse(BaseModel): """二维码识别响应消息。 Attributes: request_id (str): 请求ID。 log_id (int): 用于问题识别的唯一日志ID。 codes_result_num (int):识别结果数,表示codes_result的元素个数 result (List[QRcodeRes]): 定位和识别结果数组。 """ request_id: str = Field(default="", description="请求ID") log_id: int = Field(default=0, description="用于问题识别的唯一日志ID") codes_result_num: int = Field(default=0, description="识别结果数,表示codes_result的元素个数") codes_result: Optional[list[QRcodeRes]] = Field(default=[], description="定位和识别结果数组") class QRcodeInMsg(BaseModel): """ 二维码识别输入消息 属性: raw_image(bytes): 图像原始内容 url(str): 图像下载链接 """ raw_image: bytes = Field(default=b"", description="图像原始内容") url: str = Field(default="", description="图像下载链接") class QRcodeOCRLocation(BaseModel): """ 条形码/二维码位置信息 属性: top(int): 条形码/二维码的上边距 left(int): 条形码/二维码的左边距 width(int): 条形码/二维码的宽度 height(int): 条形码/二维码的高度 """ top: int = Field(default=0, description="条形码/二维码的上边距") left: int = Field(default=0, description="条形码/二维码的左边距") width: int = Field(default=0, description="条形码/二维码的宽度") height: int = Field(default=0, description="条形码/二维码的高度") class QRcodeOCRRes(BaseModel): """ 条形码/二维码位置信息 属性: type(int): 识别码类型条码类型 text(List[str]): 条形码/二维码识别内容 location(Object): 条形码/二维码位置信息 """ type: str = Field(default="", description="识别码类型条码类型") text: List[str] = Field(default=[], description="条形码/二维码识别内容") location: QRcodeOCRLocation = Field(default=QRcodeOCRLocation(), description="条形码/二维码位置信息") class QRcodeOutMsg(BaseModel): r"""识别结果列表""" codes_result: List[QRcodeOCRRes] = Field(default=[], description="识别结果列表") ================================================ FILE: python/core/components/v2/table_ocr/__init__.py ================================================ # Copyright (c) 2024 Baidu, Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. ================================================ FILE: python/core/components/v2/table_ocr/component.py ================================================ # Copyright (c) 2024 Baidu, Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """table ocr component.""" import base64 import json import logging from typing import Optional from appbuilder.core import utils from appbuilder.core.component import Component from appbuilder.core.components.table_ocr.model import * from appbuilder.core.message import Message from appbuilder.core._client import HTTPClient from appbuilder.core.constants import COMPONENT_SUPPORT_FILE_NUMBER from appbuilder.core._exception import AppBuilderServerException, InvalidRequestArgumentError from appbuilder.utils.trace.tracer_wrapper import components_run_trace, components_run_stream_trace class TableOCR(Component): r""" 支持识别图片中的表格内容,返回各表格的表头表尾内容、单元格文字内容及其行列位置信息,全面覆盖各类表格样式,包括常规有线表格、 无线表格、含合并单元格表格。同时,支持多表格内容识别。 Examples: .. code-block:: python import appbuilder # 请前往千帆AppBuilder官网创建密钥,流程详见:https://cloud.baidu.com/doc/AppBuilder/s/Olq6grrt6#1%E3%80%81%E5%88%9B%E5%BB%BA%E5%AF%86%E9%92%A5 os.environ["APPBUILDER_TOKEN"] = '...' table_ocr = appbuilder.TableOCR() with open("./table_ocr_test.png", "rb") as f: out = self.component.run(appbuilder.Message(content={"raw_image": f.read()})) print(out.content) """ name = "table_ocr" version = "v1" manifests = [ { "name": "table_ocr", "description": "需要识别图片中的表格内容,使用该工具, 但不支持html后缀文件的识别", "parameters": { "type": "object", "properties": { "file_names": { "type": "array", "items": { "type": "string" }, "description": "待识别图片的文件名" }, "file_urls": { "type": "array", "items": { "type": "string" }, "description": "待识别图片的文件url" } }, "anyOf": [ { "required": [ "file_names" ] }, { "required": [ "file_urls" ] } ] } } ] @HTTPClient.check_param @components_run_trace def run(self, message: Message, timeout: float = None, retry: int = 0) -> Message: """ 表格文字识别 Args: message (Message): 输入图片或图片url下载地址用于执行识别操作。 举例: Message(content={"raw_image": b"..."}) 或 Message(content={"url": "https://image/download/url"})。 timeout (float, 可选): HTTP超时时间。 retry (int, 可选): HTTP重试次数。 Returns: message (Message): 识别结果。 举例: Message(name=msg, content={'tables_result': [{ 'table_location': [{'x': 15, 'y': 15}, {'x': 371, 'y': 15}, {'x': 371, 'y': 98}, {'x': 15, 'y': 98}], 'header': [], 'body': [{'cell_location': [{'x': 15, 'y': 15}, {'x': 120, 'y': 15}, {'x': 120, 'y': 58}, {'x': 15, 'y': 58}], 'row_start': 0, 'row_end': 1, 'col_start': 0, 'col_end': 1, 'words': '参数'}, {'cell_location': [{'x': 120, 'y': 15}, {'x': 371, 'y': 15}, {'x': 371, 'y': 58}, {'x': 120, 'y': 58}], 'row_start': 0, 'row_end': 1, 'col_start': 1, 'col_end': 2, 'words': '值'}, {'cell_location': [{'x': 15, 'y': 58}, {'x': 120, 'y': 58}, {'x': 120, 'y': 98}, {'x': 15, 'y': 98}], 'row_start': 1, 'row_end': 2, 'col_start': 0, 'col_end': 1, 'words': 'Content-Type'}, {'cell_location': [{'x': 120, 'y': 58}, {'x': 371, 'y': 58}, {'x': 371, 'y': 98}, {'x': 120, 'y': 98}], 'row_start': 1, 'row_end': 2, 'col_start': 1, 'col_end': 2, 'words': 'application/x-www-form-urlencoded'}], 'footer': []}]}, mtype=dict) """ inp = TableOCRInMsg(**message.content) req = TableOCRRequest() if inp.raw_image: req.image = base64.b64encode(inp.raw_image) if inp.url: req.url = inp.url req.cell_contents = "false" result, _ = self._recognize(req, timeout, retry) result_dict = proto.Message.to_dict(result) out = TableOCROutMsg(**result_dict) return Message(content=out.model_dump()) def _recognize(self, request: TableOCRRequest, timeout: float = None, retry: int = 0, request_id: str = None) -> TableOCRResponse: r"""调用底层接口进行表格文字识别 参数: request (obj: `TableOCRRequest`) : 表格文字识别输入参数 返回: response (obj: `TableOCRResponse`): 表格文字识别返回结果 """ if not request.image and not request.url: raise ValueError( "request format error, one of image or url must be set") data = TableOCRRequest.to_dict(request) if self.http_client.retry.total != retry: self.http_client.retry.total = retry headers = self.http_client.auth_header(request_id) headers['content-type'] = 'application/x-www-form-urlencoded' url = self.http_client.service_url("/v1/bce/aip/ocr/v1/table") response = self.http_client.session.post( url, headers=headers, data=data, timeout=timeout) self.http_client.check_response_header(response) data = response.json() self.http_client.check_response_json(data) request_id = self.http_client.response_request_id(response) self.__class__._check_service_error(request_id, data) res = TableOCRResponse.from_json(json.dumps(data)) res.request_id = request_id return res, data @staticmethod def _check_service_error(request_id: str, data: dict): r"""个性化服务response参数检查 参数: request (dict) : 表格文字识别body返回 返回: 无 """ if "error_code" in data or "error_msg" in data: raise AppBuilderServerException( request_id=request_id, service_err_code=data.get("error_code"), service_err_message=data.get("error_msg") ) def get_table_markdown(self, tables_result): """ 将表格识别结果转换为Markdown格式。 Args: tables_result (list): 表格识别结果列表,每个元素是一个包含表格数据的字典,其中包含表格体(body)等字段。 Returns: list: 包含Markdown格式表格的字符串列表。 """ markdowns = [] for table in tables_result: cells = table["body"] max_row = max(cell['row_end'] for cell in cells) max_col = max(cell['col_end'] for cell in cells) # 初始化表格数组 table_arr = [[''] * max_col for _ in range(max_row)] # 填充表格数据 for cell in cells: row = cell['row_start'] col = cell['col_start'] table_arr[row][col] = cell['words'] markdown_table = "" for row in table_arr: markdown_table += "| " + " | ".join(row) + " |\n" # 生成分隔行 separator = "| " + " | ".join(['---'] * max_col) + " |\n" # 插入分隔行在表头下方 header, body = markdown_table.split('\n', 1) markdown_table = header + '\n' + separator + body markdowns.append(markdown_table) return markdowns @components_run_stream_trace def tool_eval(self, file_names: Optional[List[str]] = [], file_urls: Optional[List[str]] = [], **kwargs): """ 处理并评估传入的文件列表,并返回表格数据的Markdown格式表示。 Args: file_names (List[str]): 待处理的文件列表。 file_urls(List[str]): 待处理的文件url。 **kwargs: 其他可选参数。 Returns: Generator: 生成包含处理结果的生成器。 Raises: InvalidRequestArgumentError: 如果请求格式错误,文件URL不存在。 """ if not file_names and not file_urls: raise InvalidRequestArgumentError( request_id=kwargs.get("_sys_traceid", ""), message="file_names and file_urls cannot both be empty" ) supported_file_type = ["png", "jpg", "jpeg", "webp", "heic", "tif", "tiff", "dcm", "mha", "nii.gz"] traceid = kwargs.get("_sys_traceid", "") sys_file_urls = kwargs.get("_sys_file_urls", {}) available_file_urls = {} unsupported_files = [] unknown_files = [] if file_names: for file_name in file_names: if len(available_file_urls) >= 10: break file_type = file_name.split(".")[-1].lower() if file_name in sys_file_urls: if file_type in supported_file_type: available_file_urls[file_name] = sys_file_urls.get(file_name, "") else: unsupported_files.append(file_name) else: unknown_files.append(file_name) if file_names: for img_name in file_names: if img_name in sys_file_urls: available_file_urls[img_name] = sys_file_urls.get(img_name, "") for file_url in file_urls: if len(available_file_urls) >= 10: break if file_url in list(sys_file_urls.values()): continue file_name = file_url.split("/")[-1].split("?")[0] file_type = file_name.split(".")[-1].lower() if file_type in supported_file_type: available_file_urls[file_url] = file_url else: unsupported_files.append(file_url) for file_name, file_url in available_file_urls.items(): try: req = TableOCRRequest() req.url = file_url req.cell_contents = "false" resp, raw_data = self._recognize(req, request_id=traceid) tables_result = proto.Message.to_dict(resp)["tables_result"] markdowns = self.get_table_markdown(tables_result) rec_res = { file_name: markdowns } res = json.dumps(rec_res, ensure_ascii=False) yield self.create_output(type="text", text=res, raw_data=raw_data, visible_scope="llm") yield self.create_output(type="text", text="", raw_data=raw_data, visible_scope="user") except Exception as e: logging.warning(f"{file_name} ocr failed with exception: {e}") continue for file in unsupported_files: rec_res = { file: "不支持的文件类型,请确认是否为图片文件" } res = json.dumps(rec_res, ensure_ascii=False) yield self.create_output(type="text", text=res, name="text_1", visible_scope='llm') yield self.create_output(type="text", text=f"", name="text_2", visible_scope='user') for file in unknown_files: rec_res = { file: "无法获取url,请确认是否上传成功" } res = json.dumps(rec_res, ensure_ascii=False) yield self.create_output(type="text", text=res, name="text_1", visible_scope='llm') yield self.create_output(type="text", text=f"", name="text_2", visible_scope='user') ================================================ FILE: python/core/components/v2/text_to_image/__init__.py ================================================ # Copyright (c) 2024 Baidu, Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. ================================================ FILE: python/core/components/v2/text_to_image/component.py ================================================ # Copyright (c) 2024 Baidu, Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. r"""Text2Image component. """ import time import math from typing import Generator, Union, Optional from appbuilder.core.component import Component from appbuilder.core.message import Message from appbuilder.core._client import HTTPClient from appbuilder.core.utils import get_filename_from_url from appbuilder.core._exception import AppBuilderServerException, RiskInputException from appbuilder.core.components.text_to_image.model import Text2ImageSubmitRequest, Text2ImageQueryRequest, \ Text2ImageQueryResponse, Text2ImageSubmitResponse, Text2ImageOutMessage from appbuilder.utils.trace.tracer_wrapper import components_run_trace, components_run_stream_trace class Text2Image(Component): r""" 文生图组件,即对于输入的文本,输出生成的图片url。 Examples: .. code-block:: python import appbuilder text_to_image = appbuilder.Text2Image() os.environ["APPBUILDER_TOKEN"] = '...' content_data = {"prompt": "上海的经典风景", "width": 1024, "height": 1024, "image_num": 1} msg = appbuilder.Message(content_data) out = text_to_image.run(inp) # 打印生成结果 print(out.content) # eg: {"img_urls": ["xxx"]} """ name = "text_to_image" version = "v1" manifests = [ { "name": "text_to_image", "description": "文生图,该组件只用于图片创作。当用户需要进行场景、人物、海报等内容的绘制时,使用该画图组件。如果用户需要生成图表(柱状图、折线图、雷达图等),则必须使用代码解释器。", "parameters": { "type": "object", "properties": { "query": { "type": "string", "description": "文生图用的query。特别注意,这个字段只能由中文字符组成,不能含有任何英语描述。" } }, "required": [ "query" ] } } ] @HTTPClient.check_param @components_run_trace def run( self, message: Message, width: int = 1024, height: int = 1024, image_num: int = 1, image: Optional[str] = None, url: Optional[str] = None, pdf_file: Optional[str] = None, pdf_file_num: Optional[str] = None, change_degree: Optional[int] = None, text_content: Optional[str] = None, task_time_out: Optional[int]= None, text_check: Optional[int] = 1, request_id: Optional[str] = None ): """ 执行文本到图像的生成任务。 Args: message (Message): 包含任务相关信息的消息对象。 width (int, optional): 生成的图像的宽度,默认为1024。 height (int, optional): 生成的图像的高度,默认为1024。 image_num (int, optional): 生成图像的数量,默认为1。 image (Optional[str], optional): 参考图像的路径或URL,默认为None。 url (Optional[str], optional): 参考图像的URL,默认为None。 pdf_file (Optional[str], optional): 参考PDF文件的路径,默认为None。 pdf_file_num (Optional[str], optional): 参考PDF文件中的页码范围,默认为None。 change_degree (Optional[int], optional): 图像变换的程度,默认为None。 text_content (Optional[str], optional): 需要转换的文本内容,默认为None。 task_time_out (Optional[int], optional): 任务超时时间,默认为None。 text_check (Optional[int], optional): 是否进行文本内容检查,默认为1。 request_id (Optional[str], optional): 请求的唯一标识,默认为None。 Returns: Message: 包含生成图像URL的消息对象。 Raises: HTTPError: 请求失败时抛出异常。 """ prompt=message.content["prompt"] img_urls, _ = self._recognize( prompt = prompt, width = width, height = height, image_num = image_num, image = image, url = url, pdf_file = pdf_file, pdf_file_num = pdf_file_num, change_degree = change_degree, text_content = text_content, task_time_out = task_time_out, text_check = text_check, request_id = request_id ) if len(img_urls) == 0: raise RiskInputException(f'prompt{prompt} 中可能存在敏感词') out = Text2ImageOutMessage(img_urls=img_urls) return Message(content=out.model_dump()) @components_run_stream_trace def tool_eval( self, query: str, **kwargs, ) -> Union[Generator[str, None, None], str]: """ 根据输入的查询内容生成输出。 Args: query (str): 查询内容。 **kwargs: 其他参数,包含: _sys_traceid (str, optional): 系统追踪ID,默认为None。 width (int, optional): 图片宽度,默认为1024。 height (int, optional): 图片高度,默认为1024。 image_num (int, optional): 图片数量,默认为1。 image (Union[str, bytes], optional): 图片数据,默认为None。 url (str, optional): 图片URL,默认为None。 pdf_file (Union[str, bytes], optional): PDF文件数据,默认为None。 pdf_file_num (int, optional): PDF文件页数,默认为None。 change_degree (int, optional): 图片旋转角度,默认为None。 text_content (str, optional): 文本内容,默认为None。 task_time_out (int, optional): 任务超时时间,默认为None。 text_check (int, optional): 文本校验等级,默认为1。 Returns: Union[Generator[str, None, None], str]: 生成的输出。 Raises: RiskInputException: 当查询内容中存在敏感词时抛出。 """ request_id = kwargs.get("_sys_traceid", None) prompt = query width = kwargs.get("width", 1024) height = kwargs.get("height", 1024) image_num = kwargs.get("image_num", 1) image = kwargs.get("image", None) url = kwargs.get("url", None) pdf_file = kwargs.get("pdf_file", None) pdf_file_num = kwargs.get("pdf_file_num", None) change_degree = kwargs.get("change_degree", None) text_content = kwargs.get("text_content", None) task_time_out = kwargs.get("task_time_out", None) text_check = kwargs.get("text_check", 1) img_urls, raw_data = self._recognize( prompt = prompt, width = width, height = height, image_num = image_num, image = image, url = url, pdf_file = pdf_file, pdf_file_num = pdf_file_num, change_degree = change_degree, text_content = text_content, task_time_out = task_time_out, text_check = text_check, request_id = request_id ) if len(img_urls) == 0: raise RiskInputException(f'query:{query} 中可能存在敏感词') for url_number in range(len(img_urls)): yield self.create_output( type='image', text={ 'filename': get_filename_from_url(img_urls[url_number]), 'url': img_urls[url_number], }, raw_data=raw_data, visible_scope='all', ) def _recognize( self, prompt: str, width: int = 1024, height: int = 1024, image_num: int = 1, image: Optional[str] = None, url: Optional[str] = None, pdf_file: Optional[str] = None, pdf_file_num: Optional[str] = None, change_degree: Optional[int] = None, text_content: Optional[str] = None, task_time_out: Optional[int]= None, text_check: Optional[int] = 1, request_id: Optional[str] = None ): """ 识别并生成图片。 Args: prompt (str): 提示文本,用于生成图片。 width (int, optional): 图片宽度,默认为1024。 height (int, optional): 图片高度,默认为1024。 image_num (int, optional): 生成图片的数量,默认为1。 image (str, optional): 传入图片路径,默认为None。 url (str, optional): 图片URL,默认为None。 pdf_file (str, optional): PDF文件路径,默认为None。 pdf_file_num (str, optional): 需要转换的PDF页数,默认为None。 change_degree (int, optional): 图片旋转角度,默认为None。 text_content (str, optional): 文本内容,默认为None。 task_time_out (int, optional): 任务超时时间,默认为None。 text_check (int, optional): 文本校验选项,默认为1。 request_id (str, optional): 请求ID,默认为None。 Returns: tuple: 包含生成的图片URL列表和返回数据的元组。 """ headers = self._http_client.auth_header() headers["Content-Type"] = "application/json" api_url = self._http_client.service_url("/v1/bce/aip/ernievilg/v1/txt2imgv2") req = Text2ImageSubmitRequest( prompt=prompt, width=width, height=height, image_num=image_num, image=image, url=url, pdf_file=pdf_file, pdf_file_num=pdf_file_num, change_degree=change_degree, text_content=text_content, task_time_out=task_time_out, text_check=text_check ) response = self.http_client.session.post(api_url, json=req.model_dump(), headers=headers, timeout=None) self._http_client.check_response_header(response) request_id = self._http_client.response_request_id(response) data = response.json() self.check_service_error(request_id, data) resp= Text2ImageSubmitResponse(**data) taskId = resp.data.task_id if taskId is not None: task_request_time = 1 while True: request = Text2ImageQueryRequest(task_id=taskId) text2ImageQueryResponse, data = self.queryText2ImageData(request, request_id=request_id) if text2ImageQueryResponse.data.task_progress is not None: task_progress = float(text2ImageQueryResponse.data.task_progress) if math.isclose(1.0, task_progress, rel_tol=1e-9, abs_tol=0.0): break # NOTE(chengmo):文生图组件的返回时间在10s以上,查询过于频繁会被限流,导致异常报错 # 此处采用 yangyongzhen老师提供的方案,前三次查询间隔3s,后三次查询间隔逐渐增大 if task_request_time <= 3: time.sleep(3) else: time.sleep(task_request_time) task_request_time += 1 img_urls = self.extract_img_urls(text2ImageQueryResponse) return img_urls, data else: error_msg = resp.error_msg if error_msg is not None: error_detail = resp.error_detail if error_detail is not None: error_msg = "" for error_item in error_detail: msg = error_item.msg words = error_item.words if msg: error_msg += msg if words: error_msg += ":" + ",".join(words) + ";" else: error_msg = "文生图组件执行失败" raise RiskInputException(error_msg) def queryText2ImageData( self, request: Text2ImageQueryRequest, timeout: float = None, retry: int = 0, request_id: str = None, ) -> Text2ImageQueryResponse: """ 将文本查询请求转换为图像数据。 Args: request (Text2ImageQueryRequest): 输入请求,必填参数。 timeout (float, optional): 请求的超时时间,默认为None。 retry (int, optional): 请求的重试次数,默认为0。 request_id (str, optional): 请求的唯一标识符,默认为None。 Returns: Text2ImageQueryResponse: 接口返回的输出消息。 """ url = self.http_client.service_url("/v1/bce/aip/ernievilg/v1/getImgv2") data = { "task_id": request.task_id } headers = self.http_client.auth_header(request_id) headers['content-type'] = 'application/json' if retry != self.http_client.retry.total: self.http_client.retry.total = retry response = self.http_client.session.post(url, json=data, headers=headers, timeout=timeout) self.http_client.check_response_header(response) data = response.json() self.http_client.check_response_json(data) request_id = self.http_client.response_request_id(response) self.__class__.check_service_error(request_id, data) response = Text2ImageQueryResponse(**data) return response, data def extract_img_urls(self, response: Text2ImageQueryResponse): """ 从作画生成的返回结果中提取图片url。 Args: response (obj:`Text2ImageQueryResponse`): 作画生成的返回结果。 Returns: List[str]: 从返回体中提取的图片url列表。 """ img_urls = [] if response and response.data and response.data.sub_task_result_list: for sub_task_result in response.data.sub_task_result_list: if sub_task_result and sub_task_result.final_image_list: for final_image in sub_task_result.final_image_list: if final_image and final_image.img_url: img_urls.append(final_image.img_url) return img_urls @staticmethod def check_service_error(request_id: str, data: dict): """ 检查服务错误信息 Args: request_id (str): 请求ID data (dict): 响应数据 Raises: AppBuilderServerException: 如果响应数据中包含错误信息,则抛出异常 Returns: None """ if "error_code" in data or "error_msg" in data: service_err_message = data.get("error_msg") service_err_code=data.get("error_code") if "error_detail" in data: error_detail = data.get("error_detail", []) if error_detail: service_err_message += ": " for error_item in error_detail: msg = error_item.get("msg", "") words = error_item.get("words", []) if msg: service_err_message += msg if words: service_err_message += ":" + ",".join(words) + ";" raise AppBuilderServerException( request_id=request_id, service_err_code=service_err_code, service_err_message=service_err_message ) ================================================ FILE: python/core/components/v2/translate/__init__.py ================================================ # Copyright (c) 2023 Baidu, Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. ================================================ FILE: python/core/components/v2/translate/component.py ================================================ # Copyright (c) 2024 Baidu, Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # -*- coding: utf-8 -*- """ 文本翻译-通用版组件 """ import json from appbuilder.core.message import Message from appbuilder.core.component import Component from appbuilder.core._client import HTTPClient from appbuilder.core._exception import AppBuilderServerException, InvalidRequestArgumentError from appbuilder.core.components.translate.model import * from appbuilder.utils.trace.tracer_wrapper import components_run_trace, components_run_stream_trace class Translation(Component): r""" 文本翻译组件,可支持中、英、日、韩等200+语言互译,100+语种自动检测。 支持语种列表可参照 https://ai.baidu.com/ai-doc/MT/4kqryjku9#%E8%AF%AD%E7%A7%8D%E5%88%97%E8%A1%A8 Examples: .. code-block:: python import appbuilder # 请前往千帆AppBuilder官网创建密钥,流程详见:https://cloud.baidu.com/doc/AppBuilder/s/Olq6grrt6#1%E3%80%81%E5%88%9B%E5%BB%BA%E5%AF%86%E9%92%A5 os.environ["APPBUILDER_TOKEN"] = '...' translate = appbuilder.Translation() resp = translate(appbuilder.Message("你好\n中国"), to_lang="en") # 输出 {'from_lang':'zh', 'to_lang':'en', 'trans_result':[{'src':'你好','dst':'hello'},{'src':'中国','dst':'China'}]} print(resp.content) """ name = "translate" version = "v1" manifests = [ { "name": "translation", "description": "文本翻译通用版工具,会根据指定的目标语言对文本进行翻译,并返回翻译后的文本。", "parameters": { "type": "object", "properties": { "q": { "type": "string", "description": "需要翻译的源文本,文本翻译工具会将该文本翻译成对应的目标语言" }, "to_lang": { "type": "string", "description": "翻译的目标语言类型,'en'表示翻译成英语, 'zh'表示翻译成中文,'yue'表示翻译成粤语,'wyw'表示翻译成文言文," "'jp'表示翻译成日语,'kor'表示翻译成韩语,'fra'表示翻译成法语,'spa'表示翻译成西班牙语,'th'表示翻译成泰语," "'ara'表示翻译成阿拉伯语,'ru'表示翻译成俄语,'pt'表示翻译成葡萄牙语,'de'表示翻译成德语,'it'表示翻译成意大利语," "'el'表示翻译成希腊语,'nl'表示翻译成荷兰语,'pl'表示翻译成波兰语,'bul'表示翻译成保加利亚语,'est'表示翻译成爱沙尼亚语," "'dan'表示翻译成丹麦语, 'fin'表示翻译成芬兰语,'cs'表示翻译成捷克语,'rom'表示翻译成罗马尼亚语,'slo'表示翻译成斯洛文尼亚语," "'swe'表示翻译成瑞典语,'hu'表示翻译成匈牙利语,'cht'表示翻译成繁体中文,'vie'表示翻译成越南语,默认为'en'", "enum": ["en", "zh", "yue", "wyw", "jp", "kor", "fra", "spa", "th", "ara", "ru", "pt", "de", "it", "el", "nl", "pl", "bul", "est", "dan", "fin", "cs", "rom", "slo", "swe", "hu", "cht", "vie"] } }, "required": [ "q" ] } } ] @HTTPClient.check_param @components_run_trace def run(self, message: Message, from_lang: str = "auto", to_lang: str = "en", timeout: float = None, retry: int = 0) -> Message: """ 根据提供的文本以及语种参数执行文本翻译 Args: message (Message): 翻译文本。 from_lang (str): 翻译的源语言。默认为 "auto"。 to_lang (str): 翻译的目标语言。默认为 "en"。 timeout (float, optional): 翻译请求的超时时间。 retry (int, optional): 重试次数。 Returns: Message: 返回的文本翻译结果。 例如,Message(content={'from_lang': 'zh', 'to_lang': 'en', 'trans_result': [{'src': '你好', 'dst': 'hello'}]}) """ req = TranslateRequest() req.q = message.content req.from_lang = from_lang req.to_lang = to_lang result, data = self._translate(req, timeout=timeout, retry=retry) result_dict = proto.Message.to_dict(result) out = TranslateOutMsg(**result_dict["result"]) return Message(content=out.model_dump()) def _translate(self, request: TranslateRequest, timeout: float = None, retry: int = 0, request_id: str = None) -> TranslateResponse: """ 根据提供的 TranslateRequest 执行文本翻译。 Args: request (TranslateRequest): 翻译请求参数。 timeout (float, optional): 请求超时时间。 retry (int, optional): 重试次数。 Returns: TranslateResponse: 文本翻译结果的响应体。 """ if not request.to_lang or not request.q: raise ValueError("params `to_lang` and `q` must be set") if not request.from_lang: request.from_lang = "auto" request_data = TranslateRequest.to_json(request) if retry != self.http_client.retry.total: self.http_client.retry.total = retry headers = self.http_client.auth_header(request_id) headers['content-type'] = 'application/json;charset=utf-8' url = self.http_client.service_url("/v1/bce/aip/mt/texttrans/v1") response = self.http_client.session.post(url, headers=headers, data=request_data, timeout=timeout) self.http_client.check_response_header(response) data = response.json() request_id = self.http_client.response_request_id(response) self.http_client.check_response_json(data) if "error_code" in data and "error_msg" in data: raise AppBuilderServerException(request_id=request_id, service_err_code=data["error_code"], service_err_message=data["error_msg"]) json_str = json.dumps(data) return TranslateResponse(TranslateResponse.from_json(json_str)), data @components_run_stream_trace def tool_eval(self, q: str, to_lang: str = "en", **kwargs): """ 评估翻译工具的功能。 Args: q (str): 需要翻译的文本。 to_lang (str, optional): 目标语言,默认为 "en"。 **kwargs: 其他参数。 Returns: 生成器,生成翻译结果。 Raises: InvalidRequestArgumentError: 如果参数 `q` 未设置,则引发此异常。 """ traceid = kwargs.get("_sys_traceid", "") text = q req = TranslateRequest() if not text: raise InvalidRequestArgumentError("param `q` must be set") req.q = text req.to_lang = to_lang result_response, raw_data = self._translate(req, request_id=traceid) results = proto.Message.to_dict(result_response)["result"] trans_result = results["trans_result"] res = { "原文本": "\n ".join(item["src"] for item in trans_result), "翻译结果": "\n ".join(item["dst"] for item in trans_result) } res = json.dumps(res, ensure_ascii=False, indent=4) yield self.create_output(type="text", text=res, raw_data=raw_data, visible_scope='llm') yield self.create_output(type="text", text="", raw_data=raw_data, visible_scope='user') ================================================ FILE: python/core/components/v2/tree_mind/__init__.py ================================================ # Copyright (c) 2023 Baidu, Inc. All Rights Reserved. # 版权所有 (c) 2023 百度公司。保留所有权利。 # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. ================================================ FILE: python/core/components/v2/tree_mind/component.py ================================================ # Copyright (c) 2023 Baidu, Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. r"""树图工具""" import json from urllib.parse import urlparse, unquote from typing import Dict, List, Optional, Any from appbuilder.core.message import Message from appbuilder.core._client import HTTPClient from appbuilder.core._exception import * from appbuilder.core.utils import get_filename_from_url from appbuilder.utils.trace.tracer_wrapper import components_run_trace, components_run_stream_trace from appbuilder.core.components.v2.tree_mind.model import TreeMindRequest, TreeMindResponse from appbuilder.core.component import Component class TreeMind(Component): r""" 树图工具,提供智能思维导图制作工具和丰富的模板,支持脑图、逻辑图、树形图、鱼骨图、组织架构图、时间轴、时间线等多种专业格式。 .. code-block:: python import os import requests import appbuilder # 请前往千帆AppBuilder官网创建密钥,流程详见:https://cloud.baidu.com/doc/AppBuilder/s/Olq6grrt6#1%E3%80%81%E5%88%9B%E5%BB%BA%E5%AF%86%E9%92%A5 os.environ["GATEWAY_URL"] = "..." os.environ["APPBUILDER_TOKEN"] = "..." treemind = appbuilder.TreeMind() resp = treemind.run(appbuilder.Message("生成一份年度总结的思维导图"), to_lang="en") print(resp.content) # 输出 {'from_lang':'zh', 'to_lang':'en', 'trans_result':[{'src':'你好','dst':'hello'},{'src':'中国','dst':'China'}]} """ name = "tree_mind" version = "v1" manifests = [ { "name": "tree_mind", "description": "根据用户输入的信息,生成详细智能思维导图、脑图、逻辑图、树形图、鱼骨图、组织架构图、时间轴、时间线等多种专业格式思维导图", "parameters": { "type": "object", "properties": { "query": { "type": "string", "description": "用户想要生成思维导图的内容" }, }, "required": [ "query" ] } } ] def _post(self, query, **kwargs): if query is None or query == "": raise InvalidRequestArgumentError("query is empty!" ) request = TreeMindRequest(query_text=query) headers = self.http_client.auth_header(kwargs.get("_sys_traceid")) headers['Content-Type'] = 'application/json' tree_mind_url = self.http_client.service_url("/v1/component/component/query_mind_open") payload = TreeMindRequest.model_dump(request) response = self.http_client.session.post(tree_mind_url, headers=headers, json=payload) self.http_client.check_response_header(response) data = response.text treemind_dict = json.loads(data.split("data:")[-1]) treemind_response = TreeMindResponse(**treemind_dict) if treemind_response.errCode == '0': jump_link = treemind_response.info.downloadInfo.fileInfo.jumpLink img_link = treemind_response.info.downloadInfo.fileInfo.pic return img_link, jump_link, None else: return None, None, treemind_response.errMsg @components_run_stream_trace def tool_eval( self, query, **kwargs, ): r"""调用树图查询接口 Args: query (string): 用户想要生成思维导图的内容 Returns: dict: 返回生成的思维导图的图片链接和跳转链接 """ img_link, jump_link, errMsg = self._post(query, **kwargs) if not errMsg: inst = "你必须遵循指令,输出无需总结,只需要将,“原样输出内容”对应的内容原样输出即可:\n" img_res = f"原样输出内容:![图片url]({img_link})\n" jump_res = f"{query}的思维导图已经为您生成好了,您可以通过这个链接编辑:编辑链接:{jump_link}。" end_talk = "如果您觉得这个思维导图还不够完美,或者您的想法需要更自由地表达,点击编辑按钮,对思维导图变形、变色、变内容、甚至可以添加新的元素,快来试试吧!" result = inst + img_res + jump_res + end_talk llm_result = self.create_output( type="text", text=result, visible_scope='llm', name="text", raw_data={"event_status": "done"} ) yield llm_result img_link_result = self.create_output( type="image", text={ "filename": get_filename_from_url(img_link), "url": img_link }, visible_scope='all', name="img_link_url", raw_data={"event_status": "done"} ) yield img_link_result jump_link_result = self.create_output( type="urls", text={ "url": jump_link }, visible_scope='all', name="jump_link_url" ) yield jump_link_result else: result = "生成失败," + errMsg llm_result = self.create_output( type="text", text=result, visible_scope='llm', name="text", raw_data={"event_status": "done"} ) yield llm_result @HTTPClient.check_param @components_run_trace def run(self, message: Message, **kwargs) -> Message: """运行组件 Args: message (Message): 消息对象 Returns: Message: 返回消息对象 """ query = message.content img_link, jump_link, errMsg = self._post(query, **kwargs) if not errMsg: result = { "result": "思维导图已经为您生成好了,您可以点击'img_link'对应的链接查看,如果您觉得这个思维导图还不够完美,或者您的想法需要更自由地表达,点击'edit_link'对应的链接,对思维导图变形、变色、变内容、甚至可以添加新的元素", "img_link": img_link, "edit_link": jump_link } return Message(content=result) else: return Message(content={"error": errMsg}) ================================================ FILE: python/core/components/v2/tree_mind/model.py ================================================ # Copyright (c) 2023 Baidu, Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """ 树图model """ import proto from typing import List, Optional from pydantic import BaseModel class TreeMindRequest(BaseModel): query_text:str class FileInfo(BaseModel): jumpLink: str jumpText: str pic: str class DownloadInfo(BaseModel): fileInfo: FileInfo endDesc: str class Info(BaseModel): downloadInfo: DownloadInfo class TreeMindResponse(BaseModel): errCode: str errMsg: str time_diff: Optional[int] = None info: Optional[Info] = None ================================================ FILE: python/core/console/__init__.py ================================================ # Copyright (c) 2023 Baidu, Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from .dataset import Dataset from .rag import RAG from .appbuilder_client import AppBuilderClient from .appbuilder_client import get_app_list, describe_apps, describe_app from .knowledge_base import KnowledgeBase from .knowledge_base import CustomProcessRule ================================================ FILE: python/core/console/ai_search/__init__.py ================================================ # Copyright (c) 2025 Baidu, Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from .ai_search import AISearch ================================================ FILE: python/core/console/ai_search/ai_search.py ================================================ # Copyright (c) 2025 Baidu, Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import json from appbuilder.core.component import Message, Component from appbuilder.core.console.ai_search import data_class from appbuilder.utils.sse_util import SSEClient from appbuilder.core._exception import AppBuilderServerException class AISearch(Component): def __init__(self, **kwargs): super().__init__(**kwargs) def run(self, messages, search_source=None, resource_type_filter=None, search_filter=None, search_recency_filter=None, search_domain_filter=None, model=None, instruction=None, temperature=None, top_p=None, prompt_template=None, search_mode=None, enable_reasoning=None, enable_deep_search=None, additional_knowledge=None, max_completion_tokens=None, response_format="auto", enable_corner_markers=True, enable_followup_queries=False, stream=False, safety_level=None, max_refer_search_items=None, config_id=None, model_appid=None): req = data_class.AISearchRequest( messages=messages, search_source=search_source, resource_type_filter=resource_type_filter, search_filter=search_filter, search_recency_filter=search_recency_filter, search_domain_filter=search_domain_filter, model=model, instruction=instruction, temperature=temperature, top_p=top_p, prompt_template=prompt_template, search_mode=search_mode, enable_reasoning=enable_reasoning, enable_deep_search=enable_deep_search, additional_knowledge=additional_knowledge, max_completion_tokens=max_completion_tokens, response_format=response_format, enable_corner_markers=enable_corner_markers, enable_followup_queries=enable_followup_queries, stream=stream, safety_level=safety_level, max_refer_search_items=max_refer_search_items, config_id=config_id, model_appid=model_appid ) headers = self.http_client.auth_header_v2() headers["Content-Type"] = "application/json" url = self.http_client.service_url_v2("/ai_search/chat/completions") response = self.http_client.session.post( url, headers=headers, json=req.model_dump(exclude_none=True), timeout=None, stream=True ) self.http_client.check_response_header(response) request_id = self.http_client.response_request_id(response) if stream: client = SSEClient(response) return Message(content=self._iterate_events(request_id, client.events())) else: data = response.json() resp = data_class.AISearchResponse(**data) return Message(content=resp) @staticmethod def _iterate_events(request_id, events): for event in events: try: data = event.data if len(data) == 0: data = event.raw data = json.loads(data) except json.JSONDecodeError as e: raise AppBuilderServerException( request_id=request_id, message="json decoder failed {}".format(str(e)), ) resp = data_class.AISearchResponse(**data) yield resp ================================================ FILE: python/core/console/ai_search/data_class.py ================================================ # Copyright (c) 2025 Baidu, Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from pydantic import BaseModel, Field from typing import Optional, Union, Annotated, List from typing_extensions import Literal, override, TypeAlias PropertyFormat = Literal["iso8601", "base64", "custom"] class PropertyInfo: """Metadata class to be used in Annotated types to provide information about a given type. For example: class MyParams(TypedDict): account_holder_name: Annotated[str, PropertyInfo(alias='accountHolderName')] This means that {'account_holder_name': 'Robert'} will be transformed to {'accountHolderName': 'Robert'} before being sent to the API. """ alias: Optional[str] format: Optional[PropertyFormat] format_template: Optional[str] discriminator: Optional[str] def __init__( self, *, alias: Optional[str] = None, format: Optional[PropertyFormat] = None, format_template: Optional[str] = None, discriminator: Optional[str] = None, ) -> None: self.alias = alias self.format = format self.format_template = format_template self.discriminator = discriminator @override def __repr__(self) -> str: return ( f"{self.__class__.__name__}(alias='{self.alias}', format={self.format}, " f"format_template='{self.format_template}', discriminator='{self.discriminator}')" ) class ImageURL(BaseModel): """image url""" url: str class ImageURLContentBlock(BaseModel): """A block containing an image URL.""" image_url: ImageURL type: Literal["image_url"] = "image_url" class TextContentBlock(BaseModel): """A block containing plain text.""" text: str = "text" type: Literal["text"] MessageContent: TypeAlias = Annotated[ Union[ImageURLContentBlock, TextContentBlock], PropertyInfo(discriminator="type"), ] class Message(BaseModel): role: str = Field(..., description="角色设定,可选值:user:用户,assistant:模型") content: Union[str, list[MessageContent]] = Field(..., description="消息内容") class SearchResource(BaseModel): """搜索资源类型模型。""" top_k: int = Field(..., description="要检索的搜索结果数量") type: str = Field(..., description="模态类型(网页/图片内容/视频)") class PageTime(BaseModel): """时间过滤""" gth: Optional[str] = Field("") gt: Optional[str] = Field("") lth: Optional[str] = Field("") lt: Optional[str] = Field("") class Range(BaseModel): """区间查找""" page_time: Optional[PageTime] = Field( None, description="模态类型(网页/图片内容/视频)" ) class Match(BaseModel): """匹配查找""" site: Optional[list[str]] = Field([], description="搜索站点") class SearchFilter(BaseModel): """搜索资源类型模型。""" range: Optional[Range] = Field(None) match: Optional[Match] = Field(None) class KnowledgeData(BaseModel): """知识数据模型。""" content: str = Field(..., description="知识内容") title: Optional[str] = Field(None, description="知识标题") url: Optional[str] = Field(None, description="知识链接") release_date: Optional[str] = Field(None, description="发布日期") class Knowledge(BaseModel): """自定义知识模型。""" priority: Optional[int] = Field( 0, ge=-20, le=20, description="优先级范围[-20,20],默认值0, 值越小优先级越高" ) data_type: Optional[str] = Field(None, description="数据类型") id: Optional[int] = Field(None, description="知识ID") data: KnowledgeData = Field(..., description="详细知识内容") class AISearchRequest(BaseModel): """ 请求参数:参考文档:https://cloud.baidu.com/doc/AppBuilder/s/amaxd2det """ messages: List[Message] = Field( ..., description="搜索输入;array的长度需要是奇数, role必须是user-assistant-user交替,以user开始以user结束;在百度搜索时,仅支持单论输入,若传入多轮输入,则以用户传入最后的content为输入查询。", ) search_source: Optional[str] = Field( "使用的搜索引擎版本;可选值:baidu_search_v1、baidu_search_v2。智能搜索生成时均可输入,兼容性考虑默认为baidu_search_v1。V2相比于V1:提升了性能表现,提升了数据内容的丰富度,更适用于结合大模型使用的场景,建议默认使用V2。" ) resource_type_filter: Optional[List[SearchResource]] = Field( [SearchResource(type="web", top_k=20)], description="单次搜索最大返回数量。" ) search_filter: Optional[SearchFilter] = Field( None, description="根据SearchFilter下的子条件做检索过滤,使用方式详见后文;仅search_source为baidu_search_v2时生效", ) search_recency_filter: Optional[str] = Field( None, description="根据网页发布时间进行筛选;week:最近7天/month:最近30天/semiyear:最近180天/year:最近一年", ) search_domain_filter: Optional[List[str]] = Field( None, description='支持设置基于站点的过滤条件,对搜索到的结果按指定站点进行筛选,仅返回来自所设站点的内容。例如:设置["baidu.com"] ,在搜索到的结果中仅返回来自 baidu.com 的搜索结果。', ) model: Optional[str] = Field( None, description="使用的模型名。不传模型名称时,搜索模式为百度搜索,传入模型名称时则为智能搜索生成", ) instruction: Optional[str] = Field( "", description="人设指令,用于设定输出风格等。注意:字符长度需要小于等于2000" ) temperature: Optional[float] = Field( 1e-10, gt=0, le=1, description="模型采样参数。较高的数值会使输出更加随机,而较低的数值会使其更加集中和确定。", ) top_p: Optional[float] = Field( 1e-10, gt=0, le=1, description="模型采样参数。影响输出文本的多样性,取值越大,生成文本的多样性越强。", ) prompt_template: Optional[str] = Field( None, description="面向高阶用户开放自定义prompt模版,普通用户不需要设置。" ) search_mode: Optional[str] = Field( default="auto", description="搜索模式,默认auto,(auto:自动判断是否需要搜索/required:必须执行搜索/disabled:禁用搜索功能仅模型回答)", ) enable_reasoning: Optional[bool] = Field( True, description="是否开启深度思考,仅对DeepSeek-R1、文心X1模型生效,开启后,在总结前会进行模型推理和思考并输出相关内容。", ) enable_deep_search: Optional[bool] = Field( False, description="是否开启深搜索。深搜索会产生10次以内的智能搜索生成服务调用。", ) additional_knowledge: Optional[List[Knowledge]] = Field( [], description="调用方提供的定制化知识内容集合,与公开的联网搜索结果构成合集,注入到模型中进行问答总结。知识注入的条数和长度, 与模型有关,限制最大10条。可以配合 priority(优先级参数)使用,让本地搜索结果在能回答问题时优先被采用。当前支持三个优先级:-1、0、1,数值越小优先级越高,回答时会优先选择高优先级的内容。其中,百度搜索结果的优先级为 0。", ) max_completion_tokens: Optional[int] = Field( 2048, description="默认2048,不同模型支持的最大输出token不一样。" ) response_format: Optional[str] = Field( "auto", description="输出内容样式。默认值 auto。auto:智能判断是纯文本输出还是图文混排输出。text:文本输出。rich_text: 图文混排输出。如:在美食和旅游两个场景下,输出文本中嵌入markdown语法的图片内容。", ) enable_corner_markers: Optional[bool] = Field( True, description="用于设置在最后生成的总结内容正文时,是否返回角标用于标记模型输出内容的参考来源。true:开启角标,false:隐藏角标。", ) enable_followup_queries: Optional[bool] = Field( False, description="针对用户问题和大模型回答结果,给出推荐的追问。true: 开启追问。false:不开启追问。", ) stream: Optional[bool] = Field(False, description="是否使用流式响应") safety_level: Optional[str] = Field( "standard", description="安全等级参数,standard-标准, strict-严格" ) max_refer_search_items: Optional[int] = Field( 100, description="调节用于模型问答总结的最大搜索条数,默认是全部搜索结果。" ) config_id: Optional[str] = Field( None, description="指定使用该配置id下的领域知识注入、网页黑名单、问答干预策略等配置", ) model_appid: Optional[str] = Field(None, description="模型调用appid") class Usage(BaseModel): completion_tokens: Optional[int] = Field(None, description="完成的token数") prompt_tokens: Optional[int] = Field(None, description="提示的token数") total_tokens: Optional[int] = Field(None, description="总共的token数") class VideoDetail(BaseModel): url: Optional[str] = Field(None, description="视频链接") height: Optional[str] = Field(None, description="视频高度") width: Optional[str] = Field(None, description="视频宽度") size: Optional[str] = Field(None, description="视频大小,单位Bytes") duration: Optional[str] = Field(None, description="视频长度,单位秒") hover_pic: Optional[str] = Field(None, description="视频封面图") class ImageDetail(BaseModel): url: Optional[str] = Field(None, description="图片链接") height: Optional[str] = Field(None, description="图片高度") width: Optional[str] = Field(None, description="图片宽度") class Reference(BaseModel): id: Optional[int] = Field(..., description="引用编号1、2、3") title: Optional[str] = Field(..., description="网页标题") url: Optional[str] = Field(..., description="网页地址") web_anchor: Optional[str] = Field(..., description="网站锚文本或网站标题") icon: Optional[str] = Field(None, description="站点图标") content: Optional[str] = Field(None, description="网站内容") date: Optional[str] = Field(None, description="网页日期") type: Optional[Literal["web", "image", "video"]] = Field( None, description="检索资源类型" ) image: Optional[ImageDetail] = Field(None, description="图片详情") video: Optional[VideoDetail] = Field(None, description="视频详情") class Delta(BaseModel): """ AI响应增量数据对象,用于流式传输场景 """ content: str = Field(..., description="completion内容") role: Literal["assistant"] = Field(..., description="固定值assistant") reasoning_content: Optional[str] = Field( None, description="仅适用于 deepseek思考系列模型。内容为 assistant 消息中在最终答案之前的推理内容", ) class ChoiceMessage(BaseModel): """ AI响应消息实体,封装完整对话交互数据 """ content: str = Field(..., min_length=1, description="生成内容主体,要求非空字符串") role: Literal["assistant"] = Field( "assistant", description="消息角色标识符,固定为assistant" ) reasoning_content: Optional[str] = Field( None, min_length=1, description="推理逻辑内容,仅deepseek思考系列模型返回时有效" ) class Choice(BaseModel): """ 模型生成结果选择器,封装不同格式的响应输出 """ index: int = Field(..., ge=0, description="生成结果在选择列表中的序号,从0开始计数") finish_reason: Optional[Literal["stop", "length"]] = Field( None, description="生成终止原因:stop=自然停止 | length=长度限制" ) message: Optional[ChoiceMessage] = Field( None, description="完整响应消息(非流式模式使用)" ) delta: Optional[Delta] = Field(None, description="增量响应数据(流式模式使用)") class AISearchResponse(BaseModel): request_id: str = Field( ..., description="请求request_id", ) is_safe: Optional[bool] = Field( None, description="query是否安全") choices: Optional[List[Choice]] = Field( None, min_items=1, description=" 模型生成的 completion 的选择列表" ) code: Optional[str] = Field(None, description="错误代码,当发生异常时返回") message: Optional[str] = Field( None, min_length=5, description="错误信息,当发生异常时返回" ) usage: Optional["Usage"] = Field(None, description="token开销") references: Optional[List[Reference]] = Field( None, description="模型回答参考引用内容" ) followup_queries: Optional[List[str]] = Field( None, description="追问问题", ) ================================================ FILE: python/core/console/appbuilder_client/__init__.py ================================================ # Copyright (c) 2024 Baidu, Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from .appbuilder_client import AppBuilderClient from .appbuilder_client import get_app_list, describe_apps, describe_app ================================================ FILE: python/core/console/appbuilder_client/appbuilder_client.py ================================================ # Copyright (c) 2024 Baidu, Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """AppBuilderClient组件""" import os import json from typing import Optional, Union, Any from appbuilder.core.component import Message, Component from appbuilder.core.manifest.models import Manifest from appbuilder.core.console.appbuilder_client import data_class from appbuilder.core._exception import AppBuilderServerException from appbuilder.utils.sse_util import SSEClient from appbuilder.core._client import HTTPClient from appbuilder.utils.func_utils import deprecated from appbuilder.utils.trace.tracer_wrapper import client_run_trace, client_tool_trace @deprecated(reason="use describe_apps instead") @client_tool_trace def get_app_list( limit: int = 10, after: str = "", before: str = "", secret_key: Optional[str] = None, gateway_v2: Optional[str] = None, ) -> list[data_class.AppOverview]: """ 该接口查询用户下状态为已发布的应用列表 Args: limit (int, optional): 返回结果的最大数量,默认值为10。 after (str, optional): 返回结果中第一个应用的游标值,用于分页查询。默认值为空字符串。 before (str, optional): 返回结果中最后一个应用的游标值,用于分页查询。默认值为空字符串。 secret_key (Optional[str], optional): 认证密钥。如果未指定,则使用默认的密钥。默认值为None。 gateway_v2 (Optional[str], optional): 网关地址。如果未指定,则使用默认的地址。默认值为None。 Returns: list[data_class.AppOverview]: 应用列表。 """ client = HTTPClient(secret_key=secret_key, gateway_v2=gateway_v2) headers = client.auth_header_v2() headers["Content-Type"] = "application/json" url = client.service_url_v2("/apps") request = data_class.AppBuilderClientAppListRequest( limit=limit, after=after, before=before ) response = client.session.get( url=url, headers=headers, params=request.model_dump(), ) client.check_console_response(response) client.check_response_header(response) data = response.json() resp = data_class.AppBuilderClientAppListResponse(**data) out = resp.data return out @client_tool_trace def describe_apps( marker: Optional[str] = None, maxKeys: int = 10, secret_key: Optional[str] = None, gateway: Optional[str] = None, ) -> list[data_class.AppOverview]: """ 该接口查询用户下状态为已发布的应用列表 Args: maxKeys (int, optional): 返回结果的最大数量,默认值为10,最大为100。 marker (str, optional): 起始位置,即从哪个游标开始查询,默认值为空字符串。 secret_key (Optional[str], optional): 认证密钥。如果未指定,则使用默认的密钥。默认值为None。 gateway (Optional[str], optional): 网关地址。如果未指定,则使用默认的地址。默认值为None。 Returns: DescribeAppsResponse: 应用列表。 """ client = HTTPClient(secret_key=secret_key, gateway_v2=gateway) headers = client.auth_header_v2() headers["Content-Type"] = "application/json" url = client.service_url_v2("/app?Action=DescribeApps") request = data_class.DescribeAppsRequest(MaxKeys=maxKeys, Marker=marker) response = client.session.post( url=url, json=request.model_dump(), headers=headers, ) client.check_response_header(response) data = response.json() resp = data_class.DescribeAppsResponse(**data) out = resp.data return out @client_tool_trace def describe_app( app_id: str, secret_key: Optional[str] = None, gateway: Optional[str] = None, ) -> data_class.DescribeAppResponse: """ 查询用户的应用详情。 Args: app_id (str): 应用ID。 Returns: DescribeAppResponse: 应用详情。 """ client = HTTPClient(secret_key=secret_key, gateway_v2=gateway) headers = client.auth_header_v2() headers["Content-Type"] = "application/json" url = client.service_url_v2("/app?Action=DescribeApp") request = data_class.DescribeAppRequest(id=app_id) response = client.session.post( url=url, json=request.model_dump(), headers=headers, ) client.check_response_header(response) data = response.json() resp = data_class.DescribeAppResponse(**data) return resp @client_tool_trace def get_all_apps(): """ 获取所有应用列表。 Args: 无参数。 Returns: List[App]: 包含所有应用信息的列表,每个元素为一个App对象, 其中App对象的结构取决于get_app_list函数的返回结果。 """ app_list = [] response_per_time = describe_apps(maxKeys=100) list_len_per_time = len(response_per_time) if list_len_per_time != 0: app_list.extend(response_per_time) while list_len_per_time == 100: after_id = response_per_time[-1].id response_per_time = describe_apps(marker=after_id, maxKeys=100) list_len_per_time = len(response_per_time) if list_len_per_time != 0: app_list.extend(response_per_time) return app_list class AppBuilderClient(Component): r""" AppBuilderClient 组件支持调用在[百度智能云千帆AppBuilder](https://cloud.baidu.com/product/AppBuilder)平台上 构建并发布的智能体应用,具体包括创建会话、上传文档、运行对话等。 Examples: .. code-block:: python import appbuilder # 请前往千帆AppBuilder官网创建密钥,流程详见:https://cloud.baidu.com/doc/AppBuilder/s/Olq6grrt6#1%E3%80%81%E5%88%9B%E5%BB%BA%E5%AF%86%E9%92%A5 os.environ["APPBUILDER_TOKEN"] = '...' # 可在Console 应用页面获取 app_id = "app_id" client = appbuilder.AppBuilderClient("app_id") conversation_id = client.create_conversation() file_id = client.upload_local_file(conversation_id, "/path/to/file") message = client.run(conversation_id, "今天你好吗?") # 打印对话结果 print(message.content) """ def __init__(self, app_id: str, **kwargs): r"""初始化智能体应用 Args: app_id (str: 必须) : 应用唯一ID Returns: response (obj: `AppBuilderClient`): 智能体实例 """ super().__init__(**kwargs) if (not isinstance(app_id, str)) or len(app_id) == 0: raise ValueError( "app_id must be a str, and length is bigger then zero," "please go to official website which is 'https://cloud.baidu.com/product/AppBuilder'" " to get a valid app_id after your application is published." ) self.app_id = app_id self._mcp_context = None @client_tool_trace def create_conversation(self) -> str: r"""创建会话并返回会话ID 会话ID在服务端用于上下文管理、绑定会话文档等,如需开始新的会话,请创建并使用新的会话ID Args: 无 Returns: response (str): 唯一会话ID """ headers = self.http_client.auth_header_v2() headers["Content-Type"] = "application/json" url = self.http_client.service_url_v2("/app/conversation") response = self.http_client.session.post( url, headers=headers, json={"app_id": self.app_id}, timeout=None ) self.http_client.check_response_header(response) data = response.json() resp = data_class.CreateConversationResponse(**data) return resp.conversation_id @client_tool_trace def upload_local_file(self, conversation_id, local_file_path: str) -> str: r"""上传文件并将文件与会话ID进行绑定,后续可使用该文件ID进行对话,目前仅支持上传xlsx、jsonl、pdf、png等文件格式 该接口用于在对话中上传文件供大模型处理,文件的有效期为7天并且不超过对话的有效期。一次只能上传一个文件。 Args: conversation_id (str) : 会话ID local_file_path (str) : 本地文件路径 Returns: response (str): 唯一文件ID """ return self.upload_file(conversation_id, local_file_path=local_file_path) @client_tool_trace def upload_file(self, conversation_id, local_file_path: str=None, file_url: str=None) -> str: r"""上传文件并将文件与会话ID进行绑定,后续可使用该文件ID进行对话,目前仅支持上传xlsx、jsonl、pdf、png等文件格式 该接口用于在对话中上传文件供大模型处理,文件的有效期为7天并且不超过对话的有效期。一次只能上传一个文件。 Args: conversation_id (str) : 会话ID local_file_path (str) : 本地文件路径 file_url(str): 待上传的文件url Returns: response (str): 唯一文件ID """ if len(conversation_id) == 0: raise ValueError( "conversation_id is empty, you can run self.create_conversation to get a conversation_id" ) if local_file_path is None and file_url is None: raise ValueError( "local_file_path and file_url cannot both be empty" ) if local_file_path: filepath = os.path.abspath(local_file_path) if not os.path.exists(filepath): raise FileNotFoundError(f"{filepath} and {file_url} does not exist") headers = self.http_client.auth_header_v2() url = self.http_client.service_url_v2("/app/conversation/file/upload") multipart_form_data = { "app_id": (None, self.app_id), "conversation_id": (None, conversation_id), } if local_file_path: multipart_form_data["file"] = ( os.path.basename(local_file_path), open(local_file_path, "rb"), ) else: multipart_form_data["file_url"] = (None, file_url) response = self.http_client.session.post( url, files=multipart_form_data, headers=headers ) self.http_client.check_response_header(response) data = response.json() resp = data_class.FileUploadResponse(**data) return resp.id @client_run_trace def run( self, conversation_id: str, query: str = "", file_ids: list = [], stream: bool = False, tools: list[Union[data_class.Tool, Manifest, data_class.MCPTool]] = None, tool_outputs: list[data_class.ToolOutput] = None, tool_choice: data_class.ToolChoice = None, end_user_id: str = None, action: data_class.Action = None, mcp_authorization: list[dict] = None, parameters: dict[str, Any] = None, custom_metadata: data_class.CustomMetadata = None, **kwargs, ) -> Message: r"""运行智能体应用 Args: query (str): query内容 conversation_id (str): 唯一会话ID,如需开始新的会话,请使用self.create_conversation创建新的会话 file_ids (list[str]): 文件ID列表 stream (bool): 为True时,流式返回,需要将message.content.answer拼接起来才是完整的回答;为False时,对应非流式返回 tools (list[Union[data_class.Tool,Manifest,data_class.MCPTool]]): 一个Tool或Manifest组成的列表,其中每个Tool(Manifest)对应一个工具的配置, 默认为None tool_outputs (list[data_class.ToolOutput]): 工具输出列表,格式为list[ToolOutput], ToolOutputd内容为本地的工具执行结果,以自然语言/json dump str描述,默认为None tool_choice (data_class.ToolChoice): 控制大模型使用组件的方式,默认为None end_user_id (str): 用户ID,用于区分不同用户 action (data_class.Action): 对话时要进行的特殊操作。如回复工作流agent中“信息收集节点“的消息。 mcp_authorization (list[dict]): mcp鉴权配置:目前仅适配百度网盘 parameters: 用户在工作流Agent中自定义添加的参数,对应画布中开始节点用户新增的参数。例如: "parameters": {"custom_variable1": "abc", "custom_variable2": 1.23 } custom_metadata: 自定义角色指令,适用于自主规划agent kwargs: 其他参数 Returns: message (Message): 对话结果,一个Message对象,使用message.content获取内容。 """ if len(conversation_id) == 0: raise ValueError( "conversation_id is empty, you can run self.create_conversation to get a conversation_id" ) if query == "" and (tool_outputs is None or len(tool_outputs) == 0): raise ValueError( "AppBuilderClient Run API: query and tool_outputs cannot both be empty" ) if not tool_outputs: self._mcp_context = None formatted_tools = [] if tools: formatted_tools = [ data_class.ToAppBuilderTool(tool)[0] for tool in tools ] for tool in tools: _, is_mcp_tool = data_class.ToAppBuilderTool(tool) if is_mcp_tool and self._mcp_context is None: self._mcp_context = "client" req = data_class.AppBuilderClientRequest( app_id=self.app_id, conversation_id=conversation_id, query=query, stream=True if stream else False, file_ids=file_ids, tools=formatted_tools, tool_outputs=tool_outputs, tool_choice=tool_choice, end_user_id=end_user_id, action=action, mcp_authorization=mcp_authorization, parameters=parameters, custom_metadata=custom_metadata, ) headers = self.http_client.auth_header_v2(mcp_context=self._mcp_context) headers["Content-Type"] = "application/json" url = self.http_client.service_url_v2("/app/conversation/runs") response = self.http_client.session.post( url, headers=headers, json=req.model_dump(), timeout=None, stream=True ) self.http_client.check_response_header(response) request_id = self.http_client.response_request_id(response) if stream: client = SSEClient(response) return Message(content=self._iterate_events(request_id, client.events())) else: data = response.json() resp = data_class.AppBuilderClientResponse(**data) out = data_class.AppBuilderClientAnswer() AppBuilderClient._transform(resp, out) return Message(content=out) @client_run_trace def feedback( self, conversation_id: str, message_id: str, type: str, flag: list[str] = None, reason: str = None, ): r"""点踩点赞 Args: conversation_id (str): 唯一会话ID,如需开始新的会话,请使用self.create_conversation创建新的会话 message_id (str): 消息ID,对话后会返回消息ID type (str): 点赞点踩枚举值 cancel:取消评论, upvote:点赞, downvote:点踩 flag(list[str]): 点踩原因枚举值:答非所问、内容缺失、没有帮助、逻辑问题、偏见歧视、事实错误 reason(str): 对于点赞点踩额外补充的原因。 Returns: request_id (str): 请求ID """ if len(conversation_id) == 0: raise ValueError( "conversation_id is empty, you can run self.create_conversation to get a conversation_id" ) req = data_class.FeedbackRequest( app_id=self.app_id, conversation_id=conversation_id, message_id=message_id, type=type, flag=flag, reason=reason, ) headers = self.http_client.auth_header_v2() headers["Content-Type"] = "application/json" url = self.http_client.service_url_v2("/app/conversation/feedback") response = self.http_client.session.post( url, headers=headers, json=req.model_dump(exclude_none=True), timeout=None, stream=True ) self.http_client.check_response_header(response) request_id = self.http_client.response_request_id(response) return request_id def run_with_handler( self, conversation_id: str, query: str = "", file_ids: list = [], tools: list[Union[data_class.Tool, Manifest, data_class.MCPTool]] = None, stream: bool = False, event_handler=None, action=None, **kwargs, ): r"""运行智能体应用,并通过事件处理器处理事件 Args: conversation_id (str): 唯一会话ID,如需开始新的会话,请使用self.create_conversation创建新的会话 query (str): 查询字符串 file_ids (list): 文件ID列表 tools(list[Union[data_class.Tool,Manifest,data_class.MCPTool]], 可选): 一个Tool或Manifest组成的列表,其中每个Tool(Manifest)对应一个工具的配置, 默认为None stream (bool): 是否流式响应 event_handler (EventHandler): 事件处理器 action(data_class.Action) 对话时要进行的特殊操作。如回复工作流agent中“信息收集节点“的消息。 kwargs: 其他参数 Returns: EventHandler: 事件处理器 """ assert event_handler is not None, "event_handler is None" event_handler.init( appbuilder_client=self, conversation_id=conversation_id, query=query, file_ids=file_ids, tools=tools, stream=stream, action=action, **kwargs, ) return event_handler def run_multiple_dialog_with_handler( self, conversation_id: str, queries: iter = None, file_ids: iter = None, tools: iter = None, stream: bool = False, event_handler=None, actions: iter = None, **kwargs, ): r"""运行智能体应用,并通过事件处理器处理事件 Args: conversation_id (str): 唯一会话ID,如需开始新的会话,请使用self.create_conversation创建新的会话 queries (iter): 查询字符串可迭代对象 file_ids (iter): 文件ID列表 tools(iter, 可选): 一个Tool或Manifest组成的列表,其中每个Tool(Manifest)对应一个工具的配置, 默认为None stream (bool): 是否流式响应 event_handler (EventHandler): 事件处理器 actions(iter) 对话时要进行的特殊操作。如回复工作流agent中“信息收集节点“的消息。 kwargs: 其他参数 Returns: EventHandler: 事件处理器 """ assert event_handler is not None, "event_handler is None" assert queries is not None, "queries is None" iter_queries = iter(queries) iter_file_ids = iter(file_ids) if file_ids else iter([]) iter_tools = iter(tools) if tools else iter([]) iter_actions = iter(actions) if actions else iter([]) for index, query in enumerate(iter_queries): file_id = next(iter_file_ids, None) tool = next(iter_tools, None) action = next(iter_actions, None) if index == 0: yield from self.run_with_handler( conversation_id=conversation_id, query=query, file_ids=file_id, tools=tool, stream=stream, event_handler=event_handler, action=action, **kwargs, ) else: event_handler.new_dialog( query=query, file_ids=file_id, tools=tool, stream=stream, action=action, ) yield event_handler event_handler.reset_state() @staticmethod def _iterate_events(request_id, events): for event in events: try: data = event.data if len(data) == 0: data = event.raw data = json.loads(data) except json.JSONDecodeError as e: raise AppBuilderServerException( request_id=request_id, message="json decoder failed {}".format(str(e)), ) inp = data_class.AppBuilderClientResponse(**data) out = data_class.AppBuilderClientAnswer() AppBuilderClient._transform(inp, out) yield out @staticmethod def _check_console_response(request_id: str, data): if data["code"] != 0: raise AppBuilderServerException( request_id=request_id, service_err_code=data["code"], service_err_message="message={}".format(data["message"]), ) @staticmethod def _transform( inp: data_class.AppBuilderClientResponse, out: data_class.AppBuilderClientAnswer ): out.answer = inp.answer out.message_id = inp.message_id for ev in inp.content: event = data_class.Event( code=ev.event_code, message=ev.event_message, status=ev.event_status, event_type=ev.event_type, content_type=ev.content_type, detail=ev.outputs, usage=ev.usage, tool_calls=ev.tool_calls, ) out.events.append(event) class AgentBuilder(AppBuilderClient): r"""AgentBuilder是继承自AppBuilderClient的一个子类,用于构建和管理智能体应用。 支持调用在[百度智能云千帆AppBuilder](https://cloud.baidu.com/product/AppBuilder)平台上 构建并发布的智能体应用,具体包括创建会话、上传文档、运行对话等。 Examples: .. code-block:: python import appbuilder # 请前往千帆AppBuilder官网创建密钥,流程详见:https://cloud.baidu.com/doc/AppBuilder/s/Olq6grrt6#1%E3%80%81%E5%88%9B%E5%BB%BA%E5%AF%86%E9%92%A5 os.environ["APPBUILDER_TOKEN"] = '...' # 可在Console 应用页面获取 app_id = "app_id" client = appbuilder.AppBuilderClient("app_id") conversation_id = client.create_conversation() file_id = client.upload_local_file(conversation_id, "/path/to/file") message = client.run(conversation_id, "今天你好吗?") # 打印对话结果 print(message.content) """ @deprecated( reason="AgentBuilder is deprecated, please use AppBuilderClient instead", version="1.0.0", ) def __init__(self, app_id: str): r"""初始化方法,用于创建一个新的实例对象。 为了避免歧义,减少用户上手门槛,推荐使用该类调用AgentBuilder Args: app_id (str): 应用程序的唯一标识符。 Returns: response (obj: `AgentBuilder`): 智能体实例 """ super().__init__(app_id) ================================================ FILE: python/core/console/appbuilder_client/async_appbuilder_client.py ================================================ # Copyright (c) 2024 Baidu, Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import json import os from typing import Union, Any from aiohttp import FormData from appbuilder.core.component import Message, Component from appbuilder.core.console.appbuilder_client import data_class, AppBuilderClient from appbuilder.core.manifest.models import Manifest from appbuilder.core._exception import AppBuilderServerException from appbuilder.utils.sse_util import AsyncSSEClient class AsyncAppBuilderClient(Component): def __init__(self, app_id, **kwargs): super().__init__(is_aysnc=True, **kwargs) if (not isinstance(app_id, str)) or len(app_id) == 0: raise ValueError( "app_id must be a str, and length is bigger then zero," "please go to official website which is 'https://cloud.baidu.com/product/AppBuilder'" " to get a valid app_id after your application is published." ) self.app_id = app_id self._mcp_context = None async def create_conversation(self) -> str: r"""异步创建会话并返回会话ID 会话ID在服务端用于上下文管理、绑定会话文档等,如需开始新的会话,请创建并使用新的会话ID Args: 无 Returns: response (str): 唯一会话ID """ headers = self.http_client.auth_header_v2() headers["Content-Type"] = "application/json" url = self.http_client.service_url_v2("/app/conversation") response = await self.http_client.session.post( url, headers=headers, json={"app_id": self.app_id}, timeout=None ) await self.http_client.check_response_header(response) data = await response.json() resp = data_class.CreateConversationResponse(**data) return resp.conversation_id async def run( self, conversation_id: str, query: str = "", file_ids: list = [], stream: bool = False, tools: list[Union[data_class.Tool, Manifest, data_class.MCPTool]] = None, tool_outputs: list[data_class.ToolOutput] = None, tool_choice: data_class.ToolChoice = None, end_user_id: str = None, action: data_class.Action = None, mcp_authorization: list[dict] = None, parameters: dict[str, Any] = None, custom_metadata: data_class.CustomMetadata = None, **kwargs, ) -> Message: r"""异步运行智能体应用 Args: query (str): query内容 conversation_id (str): 唯一会话ID,如需开始新的会话,请使用self.create_conversation创建新的会话 file_ids (list[str]): 文件ID列表 stream (bool): 为True时,流式返回,需要将message.content.answer拼接起来才是完整的回答;为False时,对应非流式返回 tools (list[Union[data_class.Tool,Manifest,data_class.MCPTool]]): 一个Tool或Manifest组成的列表,其中每个Tool(Manifest)对应一个工具的配置, 默认为None tool_outputs (list[data_class.ToolOutput]): 工具输出列表,格式为list[ToolOutput], ToolOutputd内容为本地的工具执行结果,以自然语言/json dump str描述,默认为None tool_choice (data_class.ToolChoice): 控制大模型使用组件的方式,默认为None end_user_id (str): 用户ID,用于区分不同用户 action (data_class.Action): 对话时要进行的特殊操作。如回复工作流agent中“信息收集节点“的消息。 mcp_authorization (list[dict]): mcp鉴权配置:目前仅适配百度网盘 parameters: 用户在工作流Agent中自定义添加的参数,对应画布中开始节点用户新增的参数。例如: "parameters": {"custom_variable1": "abc", "custom_variable2": 1.23 } custom_metadata: 自定义角色指令,适用于自主规划agent kwargs: 其他参数 Returns: message (Message): 对话结果,一个Message对象,使用message.content获取内容。 """ if len(conversation_id) == 0: raise ValueError( "conversation_id is empty, you can run self.create_conversation to get a conversation_id" ) if query == "" and (tool_outputs is None or len(tool_outputs) == 0): raise ValueError( "AppBuilderClient Run API: query and tool_outputs cannot both be empty" ) if not tool_outputs: self._mcp_context = None formatted_tools = [] if tools: formatted_tools = [ data_class.ToAppBuilderTool(tool)[0] for tool in tools ] for tool in tools: _, is_mcp_tool = data_class.ToAppBuilderTool(tool) if is_mcp_tool and self._mcp_context is None: self._mcp_context = "client" req = data_class.AppBuilderClientRequest( app_id=self.app_id, conversation_id=conversation_id, query=query, stream=True if stream else False, file_ids=file_ids, tools=formatted_tools, tool_outputs=tool_outputs, tool_choice=tool_choice, end_user_id=end_user_id, action=action, mcp_authorization=mcp_authorization, parameters=parameters, custom_metadata=custom_metadata, ) headers = self.http_client.auth_header_v2(mcp_context=self._mcp_context) headers["Content-Type"] = "application/json" url = self.http_client.service_url_v2("/app/conversation/runs") response = await self.http_client.session.post( url, headers=headers, json=req.model_dump(), timeout=None ) await self.http_client.check_response_header(response) request_id = await self.http_client.response_request_id(response) if stream: client = AsyncSSEClient(response) return Message(content=self._iterate_events(request_id, client.events())) else: data = await response.json() resp = data_class.AppBuilderClientResponse(**data) out = data_class.AppBuilderClientAnswer() AppBuilderClient._transform(resp, out) return Message(content=out) async def upload_local_file(self, conversation_id, local_file_path: str) -> str: r"""异步运行,上传文件并将文件与会话ID进行绑定,后续可使用该文件ID进行对话,目前仅支持上传xlsx、jsonl、pdf、png等文件格式 该接口用于在对话中上传文件供大模型处理,文件的有效期为7天并且不超过对话的有效期。一次只能上传一个文件。 Args: conversation_id (str) : 会话ID local_file_path (str) : 本地文件路径 Returns: response (str): 唯一文件ID """ return await self.upload_local_file(conversation_id, local_file_path) async def upload_file(self, conversation_id, local_file_path: str=None, file_url: str=None) -> str: r"""异步运行,上传文件并将文件与会话ID进行绑定,后续可使用该文件ID进行对话,目前仅支持上传xlsx、jsonl、pdf、png等文件格式 该接口用于在对话中上传文件供大模型处理,文件的有效期为7天并且不超过对话的有效期。一次只能上传一个文件。 Args: conversation_id (str) : 会话ID local_file_path (str) : 本地文件路径 file_url (str) : 文件URL Returns: response (str): 唯一文件ID """ if len(conversation_id) == 0: raise ValueError( "conversation_id is empty, you can run self.create_conversation to get a conversation_id" ) if local_file_path is None and file_url is None: raise ValueError( "local_file_path and file_url cannot both be empty" ) if local_file_path: filepath = os.path.abspath(local_file_path) if not os.path.exists(filepath): raise FileNotFoundError(f"{filepath} does not exist") multipart_form_data = FormData() multipart_form_data.add_field(name="app_id", value=self.app_id) multipart_form_data.add_field( name="conversation_id", value=conversation_id) if local_file_path: multipart_form_data.add_field( name="file", value=open(local_file_path, "rb"), filename=os.path.basename(local_file_path), ) else: multipart_form_data.add_field(name="file_url", value=file_url) headers = self.http_client.auth_header_v2() url = self.http_client.service_url_v2("/app/conversation/file/upload") response = await self.http_client.session.post( url, data=multipart_form_data, headers=headers ) await self.http_client.check_response_header(response) data = await response.json() resp = data_class.FileUploadResponse(**data) return resp.id async def run_with_handler( self, conversation_id: str, query: str = "", file_ids: list = [], tools: list[Union[data_class.Tool, Manifest, data_class.MCPTool]] = None, stream: bool = False, event_handler=None, action=None, **kwargs, ): r"""异步运行智能体应用,并通过事件处理器处理事件 Args: conversation_id (str): 唯一会话ID,如需开始新的会话,请使用self.create_conversation创建新的会话 query (str): 查询字符串 file_ids (list): 文件ID列表 tools(list[Union[data_class.Tool,Manifest,data_class.MCPTool]], 可选): 一个Tool或Manifest组成的列表,其中每个Tool(Manifest)对应一个工具的配置, 默认为None stream (bool): 是否流式响应 event_handler (EventHandler): 事件处理器 action(data_class.Action) 对话时要进行的特殊操作。如回复工作流agent中“信息收集节点“的消息。 kwargs: 其他参数 Returns: EventHandler: 事件处理器 """ assert event_handler is not None, "event_handler is None" await event_handler.init( appbuilder_client=self, conversation_id=conversation_id, query=query, file_ids=file_ids, tools=tools, stream=stream, action=action, **kwargs, ) return event_handler async def run_multiple_dialog_with_handler( self, conversation_id: str, queries: iter = None, file_ids: iter = None, tools: iter = None, stream: bool = False, event_handler=None, actions: iter = None, **kwargs, ): r"""运行智能体应用,并通过事件处理器处理事件 Args: conversation_id (str): 唯一会话ID,如需开始新的会话,请使用self.create_conversation创建新的会话 queries (iter): 查询字符串可迭代对象 file_ids (iter): 文件ID列表 tools(iter, 可选): 一个Tool或Manifest组成的列表,其中每个Tool(Manifest)对应一个工具的配置, 默认为None stream (bool): 是否流式响应 event_handler (EventHandler): 事件处理器 actions(iter) 对话时要进行的特殊操作。如回复工作流agent中“信息收集节点“的消息。 kwargs: 其他参数 Returns: EventHandler: 事件处理器 """ assert event_handler is not None, "event_handler is None" assert queries is not None, "queries is None" iter_queries = iter(queries) iter_file_ids = iter(file_ids) if file_ids else iter([]) iter_tools = iter(tools) if tools else iter([]) iter_actions = iter(actions) if actions else iter([]) for index, query in enumerate(iter_queries): file_id = next(iter_file_ids, None) tool = next(iter_tools, None) action = next(iter_actions, None) if index == 0: await event_handler.init( appbuilder_client=self, conversation_id=conversation_id, query=query, file_ids=file_id, tools=tool, stream=stream, action=action, **kwargs, ) yield event_handler else: await event_handler.new_dialog( query=query, file_ids=file_id, tools=tool, stream=stream, action=action, ) yield event_handler await event_handler.reset_state() @staticmethod async def _iterate_events(request_id, events): async for event in events: try: data = event.data if len(data) == 0: data = event.raw data = json.loads(data) except json.JSONDecodeError as e: raise AppBuilderServerException( request_id=request_id, message="json decoder failed {}".format(str(e)), ) inp = data_class.AppBuilderClientResponse(**data) out = data_class.AppBuilderClientAnswer() AppBuilderClient._transform(inp, out) yield out ================================================ FILE: python/core/console/appbuilder_client/async_event_handler.py ================================================ # Copyright (c) 2024 Baidu, Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from appbuilder.utils.logger_util import logger from appbuilder.core.console.appbuilder_client import data_class class AppBuilderClientRunContext(object): def __init__(self) -> None: """ 初始化方法。 Args: 无参数。 Returns: None """ self.current_event = None self.current_tool_calls = None self.current_status = None self.need_tool_submit = False self.is_complete = False self.current_thought = "" class AsyncAppBuilderEventHandler(object): def __init__(self): pass async def init( self, appbuilder_client, conversation_id, query, file_ids=None, tools=None, stream: bool = False, event_handler=None, action=None, **kwargs, ): """ 初始化类实例并设置相关参数。 Args: appbuilder_client (object): AppBuilder客户端实例对象。 conversation_id (str): 对话ID。 query (str): 用户输入的查询语句。 file_ids (list, optional): 文件ID列表,默认为None。 tools (list, optional): 工具列表,默认为None。 stream (bool, optional): 是否使用流式处理,默认为False。 event_handler (callable, optional): 事件处理函数,默认为None。 action (object, optional): 对话时要进行的特殊操作。如回复工作流agent中“信息收集节点“的消息。 **kwargs: 其他可选参数。 Returns: None """ self._appbuilder_client = appbuilder_client self._conversation_id = conversation_id self._query = query self._file_ids = file_ids self._tools = tools self._stream = stream self._event_handler = event_handler self._kwargs = kwargs self._is_complete = False self._need_tool_call = False self._last_tool_output = None self._action = action self._iterator = ( self.__run_process__() if not self._stream else self.__stream_run_process__() ) async def __run_process__(self): """ 运行进程,并在每次执行后生成结果。 Args: 无参数。 Returns: Generator: 生成器,每次执行后返回结果。 """ while not self._is_complete: if not self._need_tool_call: res = await self._run() await self.__event_process__(res) else: res = await self._submit_tool_output() await self.__event_process__(res) yield res if self._need_tool_call and self._is_complete: await self.reset_state() async def __async_run_process__(self): """ 异步运行进程,并在每次执行后生成结果 Args: 无参数 Returns: Generator[Any, None, None]: 生成器,每次执行后返回结果 """ while not self._is_complete: if not self._need_tool_call: res = await self._run() await self.__event_process__(res) else: res = await self._submit_tool_output() await self.__event_process__(res) yield res if self._need_tool_call and self._is_complete: await self.reset_state() async def __event_process__(self, run_response): """ 处理事件响应。 Args: run_response (RunResponse): 运行时响应对象。 Returns: None Raises: ValueError: 当解析事件时发生异常或工具输出为空时。 """ try: event = run_response.content.events[-1] except Exception as e: raise ValueError(e) event_status = event.status if event.status == "success": self._is_complete = True elif event.status == "interrupt": self._need_tool_call = True context_func_map = { "preparing": self.preparing, "running": self.running, "error": self.error, "done": self.done, "interrupt": self.interrupt, "success": self.success, } run_context = AppBuilderClientRunContext() await self._update_run_context(run_context, run_response.content) await self.handle_event_type(run_context, run_response.content) await self.handle_content_type(run_context, run_response.content) if event_status in context_func_map: func = context_func_map[event_status] func_res = await func(run_context, run_response.content) if event_status == "interrupt": assert isinstance(func_res, list) if len(func_res) == 0: raise ValueError("Tool output is empty") else: if not isinstance(func_res[0], data_class.ToolOutput): try: check_tool_output = data_class.ToolOutput( **func_res[0]) except Exception as e: logger.error( "func interrupt's output should be list[ToolOutput] or list[dict(can be trans to ToolOutput)]" ) raise ValueError(e) self._last_tool_output = func_res else: logger.warning( "Unknown status: {}, response data: {}".format( event_status, run_response ) ) async def __stream_run_process__(self): """ 异步流式运行处理函数 Args: 无参数 Returns: Generator[Any, None, None]: 返回处理结果的生成器 """ while not self._is_complete: if not self._need_tool_call: res = await self._run() else: res = await self._submit_tool_output() async for msg in self.__stream_event_process__(res): yield msg async def __stream_event_process__(self, run_response): """ 处理流事件,并调用对应的方法 Args: run_response: 包含流事件信息的响应对象 Returns: None Raises: ValueError: 当处理事件时发生异常或中断时工具输出为空时 """ async for msg in run_response.content: if len(msg.events) == 0: continue try: event = msg.events[-1] except Exception as e: raise ValueError(e) event_status = event.status if event.status == "success": self._is_complete = True elif event.status == "interrupt": self._need_tool_call = True context_func_map = { "preparing": self.preparing, "running": self.running, "error": self.error, "done": self.done, "interrupt": self.interrupt, "success": self.success, } run_context = AppBuilderClientRunContext() await self._update_run_context(run_context, msg) await self.handle_event_type(run_context, msg) await self.handle_content_type(run_context, msg) if event_status in context_func_map: func = context_func_map[event_status] func_res = await func(run_context, msg) if event_status == "interrupt": assert isinstance(func_res, list) if len(func_res) == 0: raise ValueError("Tool output is empty") else: if not isinstance(func_res[0], data_class.ToolOutput): try: check_tool_output = data_class.ToolOutput( **func_res[0]) except Exception as e: logger.info( "func interrupt's output should be list[ToolOutput] or list[dict(can be trans to ToolOutput)]" ) raise ValueError(e) self._last_tool_output = func_res else: logger.warning( "Unknown status: {}, response data: {}".format( event_status, run_response ) ) yield msg async def _update_run_context(self, run_context, run_response): """ 更新运行上下文。 Args: run_context (dict): 运行上下文字典。 run_response (object): 运行响应对象。 Returns: None """ run_context.current_event = run_response.events[-1] run_context.current_tool_calls = run_context.current_event.tool_calls run_context.current_status = run_context.current_event.status run_context.need_tool_submit = run_context.current_status == "interrupt" run_context.is_complete = run_context.current_status == "success" try: run_context.current_thought = ( run_context.current_event.detail.get("text", {}) .get("function_call", {}) .get("thought", "") ) if run_context.current_thought == "": run_context.current_thought = run_response.events[0].detail.get( "text", "" ) except Exception: pass async def _run(self): res = await self._appbuilder_client.run( conversation_id=self._conversation_id, query=self._query, file_ids=self._file_ids, stream=self._stream, tools=self._tools, action=self._action, ) return res async def _submit_tool_output(self): assert self._last_tool_output is not None res = await self._appbuilder_client.run( conversation_id=self._conversation_id, file_ids=self._file_ids, stream=self._stream, tool_outputs=self._last_tool_output, ) return res async def __anext__(self): return await self._iterator.__anext__() async def __aiter__(self): async for item in self._iterator: yield item def __enter__(self): return self def __exit__(self, exc_type, exc_val, exc_tb) -> None: if exc_type is not None: raise exc_val return async def reset_state(self): """ 重置该对象的状态,将所有实例变量设置为默认值。 Args: 无 Returns: 无 """ self._appbuilder_client = None self._conversation_id = None self._query = None self._file_ids = None self._tools = None self._stream = False self._event_handler = None self._kwargs = None self._last_tool_output = None self._is_complete = False self._need_tool_call = False self._iterator = None async def new_dialog( self, query=None, file_ids=None, tools=None, action=None, stream: bool = None, event_handler=None, **kwargs, ): """ 重置handler部分参数,用于复用该handler进行多轮对话。 Args: query (str): 用户输入的查询语句。 file_ids (list, optional): 文件ID列表,默认为None。 tools (list, optional): 工具列表,默认为None。 stream (bool, optional): 是否使用流式处理,默认为False。 action (object, optional): 对话时要进行的特殊操作。如回复工作流agent中“信息收集节点“的消息。 event_handler (callable, optional): 事件处理函数,默认为None。 **kwargs: 其他可选参数。 Returns: None """ self._query = query or self._query self._stream = stream or self._stream self._file_ids = file_ids self._tools = tools self._event_handler = event_handler self._kwargs = kwargs self._action = action # 重置部分状态 self._is_complete = False self._need_tool_call = False self._last_tool_output = None self._iterator = ( self.__run_process__() if not self._stream else self.__stream_run_process__() ) async def until_done(self): """ 迭代并遍历内部迭代器中的所有元素,直到迭代器耗尽。 Args: 无参数。 Returns: 无返回值。 """ async for _ in self._iterator: pass async def handle_content_type(self, run_context, run_response): # 用户可重载该方法,用于处理不同类型的content_type pass async def handle_event_type(self, run_context, run_response): # 用户可重载该方法,用于处理不同类型的event_type pass async def interrupt(self, run_context, run_response): # 用户可重载该方法,当event_status为interrupt时,会调用该方法 pass async def preparing(self, run_context, run_response): # 用户可重载该方法,当event_status为preparing时,会调用该方法 pass async def running(self, run_context, run_response): # 用户可重载该方法,当event_status为running时,会调用该方法 pass async def error(self, run_context, run_response): # 用户可重载该方法,当event_status为error时,会调用该方法 pass async def done(self, run_context, run_response): # 用户可重载该方法,当event_status为done时,会调用该方法 pass async def success(self, run_context, run_response): # 用户可重载该方法,当event_status为success时,会调用该方法 pass class AsyncToolCallEventHandler(AsyncAppBuilderEventHandler): def __init__(self, mcp_client=None, functions=[]): super().__init__() self.mcp_client = mcp_client self.functions = functions self.result = "" async def init( self, appbuilder_client, conversation_id, query, file_ids=None, tools=None, stream: bool = False, event_handler=None, action=None, **kwargs, ): await super().init( appbuilder_client, conversation_id, query, file_ids, tools, stream, event_handler, action, **kwargs, ) self.result = "" async def reset_state(self): await super().reset_state() self.result = "" async def new_dialog( self, query=None, file_ids=None, tools=None, action=None, stream=None, event_handler=None, **kwargs, ): await super().new_dialog( query, file_ids, tools, action, stream, event_handler, **kwargs ) self.result = "" async def interrupt(self, run_context, run_response): thought = run_context.current_thought logger.debug("Agent 中间思考: {}\n".format(thought)) tool_output = [] for tool_call in run_context.current_tool_calls: function_name = tool_call.function.name function_arguments = tool_call.function.arguments result = "" function_map = {f.__name__: f for f in self.functions} if function_name in function_map: result = function_map[function_name]( **tool_call.function.arguments) logger.debug("ToolCall结果: {}\n".format(result)) elif self.mcp_client: logger.debug( "MCP工具名称: {}, MCP参数:{}\n".format( function_name, function_arguments ) ) mcp_server_result = await self.mcp_client.call_tool( function_name, function_arguments ) logger.debug("MCP ToolCall结果: {}\n".format(mcp_server_result)) for i, content in enumerate(mcp_server_result.content): if content.type == "text": result = result + mcp_server_result.content[i].text else: logger.warning(f"Tool not found: {function_name}") tool_output.append( { "tool_call_id": tool_call.id, "output": result, } ) return tool_output async def running(self, run_context, run_response): if self._stream and run_response.answer and run_response.answer != "": logger.debug("Agent 流式回答: {}".format(run_response.answer)) self.result += run_response.answer async def success(self, run_context, run_response): if not self._stream: logger.debug("Agent 非流式回答: {}".format(run_response.answer)) self.result = run_response.answer ================================================ FILE: python/core/console/appbuilder_client/data_class.py ================================================ # Copyright (c) 2024 Baidu, Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from pydantic import BaseModel from pydantic import Field from typing import Union, Any from typing import Optional from appbuilder.core.manifest.models import Manifest class Function(BaseModel): name: str = Field(..., description="工具名称") description: str = Field(..., description="工具描述") parameters: dict = Field(..., description="工具参数, json_schema格式") class Tool(BaseModel): type: str = "function" function: Function = Field(..., description="工具信息") class MCPTool(BaseModel): name: str = Field(..., description="工具名称") description: str = Field(..., description="工具描述") inputSchema: dict = Field(..., description="工具参数, json_schema格式") def ToAppBuilderTool(tool): if "type" in tool and tool["type"]: return Tool(**tool), False if hasattr(tool, 'inputSchema') and hasattr(tool, 'inputSchema'): return Tool(type="function", function=Function(name=tool.name, description=tool.description, parameters=tool.inputSchema)), True else: return tool, False class ToolOutput(BaseModel): tool_call_id: str = Field(..., description="工具调用ID") output: str = Field(..., description="工具输出") class FunctionCallDetail(BaseModel): name: str = Field(..., description="函数的名称") arguments: dict = Field(..., description="模型希望您传递给函数的参数") class ToolCall(BaseModel): id: str = Field(..., description="工具调用ID") type: str = Field( "function", description="需要输出的工具调用的类型。就目前而言,这始终是function") function: FunctionCallDetail = Field(..., description="函数定义") class ToolChoiceFunction(BaseModel): name: str = Field( ..., description="组件的英文名称(唯一标识),用户通过工作流完成自定义组件后,可在个人空间-组件下查看组件英文名称", ) input: dict = Field( ..., description="当组件没有入参或者必填的入参只有一个时可省略,必填的入参只有一个且省略时,使用query字段的值作为入参", ) class ToolChoice(BaseModel): type: str = Field( ..., description="auto/function,auto表示由LLM自动判断调什么组件;function表示由用户指定调用哪个组件", ) function: Optional[ToolChoiceFunction] = Field( ..., description="当type为function时,需要指定调用哪个组件" ) class ActionInterruptEvent(BaseModel): id: str = Field(..., description="要回复的'信息收集节点'中断事件ID") type: str = Field(..., description="要回复的'信息收集节点'中断事件类型,当前仅chat") class ActionParameters(BaseModel): interrupt_event: ActionInterruptEvent = Field( ..., description="要回复的'信息收集节点'中断事件") class CustomMetadata(BaseModel): override_role_instruction: str = Field(..., description="自定义角色指令,适用于自主规划agent") class Action(BaseModel): action_type: str = Field(..., description="action类型,目前可用值'resume', 用于回复信息收集节点的消息") parameters: ActionParameters = Field( ..., description="对话时要进行的特殊操作。如回复工作流agent中'信息收集节点'的消息。", ) @classmethod def create_resume_action(cls, event_id): return { "action_type": "resume", "parameters": { "interrupt_event": { "id": event_id, "type": "chat" } } } class AppBuilderClientRequest(BaseModel): """会话请求参数 属性: query (str): 查询参数 response_mode (str): streaming或blocking conversation_id (str): 会话ID file_ids(list[str]): 文件ID app_id:应用ID """ query: Optional[str] = None stream: Optional[bool] = False conversation_id: str file_ids: Optional[list[str]] = None app_id: str tools: Optional[list[Union[Tool, Manifest]]] = None tool_outputs: Optional[list[ToolOutput]] = None tool_choice: Optional[ToolChoice] = None end_user_id: Optional[str] = None action: Optional[Action] = None mcp_authorization: Optional[list[dict]] = None parameters: Optional[dict[str, Any]] = None custom_metadata: Optional[CustomMetadata] = None class Usage(BaseModel): """ 模型用量 仅Chat Agent和Function Call有,按照各个独立的event_type计数。 """ prompt_tokens: int = 0 completion_tokens: int = 0 total_tokens: int = 0 name: str = "" class OriginalEvent(BaseModel): """会话请求参数 属性: event_code (int): 0代表成功,非0为失败 event_message (str): 错误详情 event_type(str):事件类型 event_status(str):事件状态 content_type(str):内容类型 outputs(dict):事件输出 """ event_code: int = "" event_message: str = "" event_type: str = "" event_id: str = "" event_status: str = "" content_type: str = "" outputs: dict = {} usage: Optional[Usage] = None tool_calls: Optional[list[ToolCall]] = None class AppBuilderClientResponse(BaseModel): """会话请求参数 属性: request_id (int): 请求ID date (str): 消息返回时间的时间戳 answer (str): 模型回答 conversation_id(str): 会话ID message_id(str): 消息ID is_completion(bool): 是否结束 content(list): 内容详情 """ request_id: str = "" date: str = "" answer: str = "" conversation_id: str = "" message_id: str = "" is_completion: Optional[bool] = False content: list[OriginalEvent] = [] class TextDetail(BaseModel): """content_type=text,详情内容 属性: text(str): 文本详情 """ text: str = "" class CodeDetail(BaseModel): """content_type=code,详情内容 属性: text(str): 文本详情 code: 代码解释器工具生产的代码 files: 代码解释器生成的可下载文件地址列表 """ text: str = "" code: str = "" files: list[str] = [] class RAGReference(BaseModel): """RAG应用详情 属性: id (int): 对应来源ID from (str): 信息来源 url (str): BaiduSearch 的专用字段 content(str): 般用来当做文档名或者链接的title使用,前端展示可以根据情况截断。 segment_id(str): 片段ID document_id(str): 文档ID document_name(str): 文档名 knowledgebase_id(str): 知识库id 知识问答专有字段 """ id: str = "" from_: str = Field(..., alias='from') url: str = "" content: str = "" segment_id: str = "" document_id: str = "" dataset_id: str = "" document_name: str = "" knowledgebase_id: str = "" class RAGDetail(BaseModel): """content_type=rag,详情内容 属性: text(str): 文本详情 references(list[RAGReference]): 引用详情 """ text: str = "" references: list[RAGReference] = [] class FunctionCallDetail(BaseModel): """content_type=function_call,详情内容 属性: text(str): 文本详情 """ text: Union[str, dict] = "" image: str = "" audio: str = "" video: str = "" class ImageDetail(BaseModel): """content_type=function_call,详情内容 属性: image(str): 图片下载地址 """ image: str = "" class AudioDetail(BaseModel): """content_type=audio,详情内容 属性: image(str): 音频下载地址 """ audio: str = "" class VideoDetail(BaseModel): """content_type=video,详情内容 属性: video(str): 视频下载地址 """ video: str = "" class StatusDetail(BaseModel): pass class DefaultDetail(BaseModel): """content_type为其它时,详情内容 属性: urls(list[str]): 件链接列表 files(list[str]): 下载文件地址列表 image(str): 工具生成的图片url video(str): 工具生成的语音url audio(str):工具生成的音频url """ urls: list[str] = [] files: list[str] = [] image: str = "" video: str = "" audio: str = "" class Event(BaseModel): """执行步骤的具体内容 属性: code (int): 响应code码 message (str): 错误详情 status (str): 状态描述,preparing(准备运行)running(运行中)error(执行错误) done(执行完成) event_type(str): 事件类型 content_type(str): 内容类型 detail(dict): 事件详情 usage(Usage): 模型调用的token用量 """ code: int = 0 message: str = "" status: str = "" event_type: str = "" content_type: str = "" detail: dict = {} usage: Optional[Usage] = None tool_calls: Optional[list[ToolCall]] = None class AppBuilderClientAnswer(BaseModel): """执行步骤的具体内容 属性: answer(str): query回答内容 events( list[Event]): 事件列表 """ answer: str = "" message_id: str = "" events: list[Event] = [] class FileUploadResponse(BaseModel): """文档上传结果 属性: request_id (str): 请求ID id (str): 文件ID conversation_id (str): 对话ID """ request_id: str = "" id: str = "" conversation_id: str = "" class CreateConversationResponse(BaseModel): """文档上传结果 属性: code (int): 响应code码 request_id (str): 请求ID conversation_id (str): 对话ID """ request_id: str = "" conversation_id: str = "" class AppBuilderClientAppListRequest(BaseModel): limit: int = Field( default=10, description="当次查询的数据大小,默认10,最大值100", le=100, ge=1) after: str = Field( default="", description="用于分页的游标。after 是一个应用的id,它定义了在列表中的位置。例如,如果你发出一个列表请求并收到 10个对象,以 app_id_123 结束,那么你后续的调用可以包含 after=app_id_123 以获取列表的下一页数据。") before: str = Field(default="", description="用于分页的游标。与after相反,填写它将获取前一页数据") class AppOverview(BaseModel): id: str = Field("", description="应用ID") name: str = Field("", description="应用名称") description: str = Field("", description="应用简介") appType: Optional[str] = Field( None, description="应用类型:agent、chatflow。agent:自主规划Agent, chatflow:工作流Agent。" ) isPublished: Optional[bool] = Field(None, description="是否已发布") updateTime: Optional[int] = Field(None, description="更新时间。时间戳,单位秒") class AppBuilderClientAppListResponse(BaseModel): request_id: str = Field("", description="请求ID") data: Optional[list[AppOverview]] = Field( [], description="应用概览列表") class DescribeAppsRequest(BaseModel): maxKeys: int = Field( default=10, description="当次查询的数据大小,默认10,最大值100", le=100, ge=1) marker: str = Field( default=None, description="用于分页的游标。marker 是应用的id,它定义了在列表中的位置。例如,如果你发出一个列表请求并收到 10个对象,以 app_id_123 开始,那么可以使用 marker=app_id_123 来获取列表的下一页数据") class DescribeAppsResponse(BaseModel): requestId: str = Field("", description="请求ID") marker: str = Field("", description="起始位置") isTruncated: bool = Field(False, description="是否有更多数据") nextMarker: str = Field("", description="下一次起始位置") maxKeys: int = Field(0, description="最大返回数量") data: list[AppOverview] = Field([], description="应用概览列表") class DescribeAppRequest(BaseModel): id: str = Field(..., description="应用ID") class DescribeAppResponse(BaseModel): requestId: str = Field("", description="请求ID") id: str = Field("", description="应用ID") name: str = Field("", description="应用名称") description: str = Field("", description="应用描述") instruction: str = Field("", description="用户指令") prologue: str = Field("", description="开场白") exampleQueries: list[str] = Field("", description="推荐问题") followupQueries: dict = Field("", description="追问") components: Optional[list[dict]] = Field(None, description="引用组件列表") knowledgeBaseConfig: Optional[dict] = Field(None, description="知识库配置") modelConfig: Optional[dict] = Field(None, description="模型配置") background: Optional[dict] = Field(None, description="背景图配置") class FeedbackRequest(BaseModel): app_id: str = Field(..., description="应用ID") conversation_id: str = Field(..., description="对话ID") message_id: str = Field(..., description="对应的消息ID") type: str = Field( ..., description="点赞点踩枚举值 cancel:取消评论, upvote:点赞, downvote:点踩", ) flag: Optional[list[str]] = Field( None, description="点踩原因枚举值:答非所问、内容缺失、没有帮助、逻辑问题、偏见歧视、事实错误", ) reason: Optional[str] = Field(None, description="对于点赞点踩额外补充的原因。") ================================================ FILE: python/core/console/appbuilder_client/event_handler.py ================================================ # Copyright (c) 2024 Baidu, Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import os from appbuilder.utils.sse_util import SSEClient from appbuilder.utils.logger_util import logger from appbuilder.core.console.appbuilder_client import data_class class AppBuilderClientRunContext(object): def __init__(self) -> None: """ 初始化方法。 Args: 无参数。 Returns: None """ self.current_event = None self.current_tool_calls = None self.current_status = None self.need_tool_submit = False self.is_complete = False self.current_thought = "" class AppBuilderEventHandler(object): def __init__(self): pass def init( self, appbuilder_client, conversation_id, query, file_ids=None, tools=None, stream: bool = False, event_handler=None, action=None, **kwargs ): """ 初始化类实例并设置相关参数。 Args: appbuilder_client (object): AppBuilder客户端实例对象。 conversation_id (str): 对话ID。 query (str): 用户输入的查询语句。 file_ids (list, optional): 文件ID列表,默认为None。 tools (list, optional): 工具列表,默认为None。 stream (bool, optional): 是否使用流式处理,默认为False。 event_handler (callable, optional): 事件处理函数,默认为None。 action (object, optional): 对话时要进行的特殊操作。如回复工作流agent中“信息收集节点“的消息。 **kwargs: 其他可选参数。 Returns: None """ self._appbuilder_client = appbuilder_client self._conversation_id = conversation_id self._query = query self._file_ids = file_ids self._tools = tools self._stream = stream self._event_handler = event_handler self._kwargs = kwargs self._is_complete = False self._need_tool_call = False self._last_tool_output = None self._action = action self._iterator = self.__run_process__( ) if not self._stream else self.__stream_run_process__() def __run_process__(self): """ 运行进程,并在每次执行后生成结果。 Args: 无参数。 Returns: Generator: 生成器,每次执行后返回结果。 """ while not self._is_complete: if not self._need_tool_call: res = self._run() self.__event_process__(res) else: res = self._submit_tool_output() self.__event_process__(res) yield res if self._need_tool_call and self._is_complete: self.reset_state() def __event_process__(self, run_response): """ 处理事件响应。 Args: run_response (RunResponse): 运行时响应对象。 Returns: None Raises: ValueError: 当解析事件时发生异常或工具输出为空时。 """ try: event = run_response.content.events[-1] except Exception as e: raise ValueError(e) event_status = event.status if event.status == 'success': self._is_complete = True elif event.status == 'interrupt': self._need_tool_call = True context_func_map = { "preparing": self.preparing, "running": self.running, "error": self.error, "done": self.done, "interrupt": self.interrupt, "success": self.success, } run_context = AppBuilderClientRunContext() self._update_run_context(run_context, run_response.content) self.handle_event_type(run_context, run_response.content) self.handle_content_type(run_context, run_response.content) if event_status in context_func_map: func = context_func_map[event_status] func_res = func(run_context, run_response.content) if event_status == "interrupt": assert isinstance(func_res, list) if len(func_res) == 0: raise ValueError("Tool output is empty") else: if not isinstance(func_res[0], data_class.ToolOutput): try: check_tool_output = data_class.ToolOutput( **func_res[0]) except Exception as e: logger.error( "func interrupt's output should be list[ToolOutput] or list[dict(can be trans to ToolOutput)]") raise ValueError(e) self._last_tool_output = func_res else: logger.warning( "Unknown status: {}, response data: {}".format(event_status, run_response)) def __stream_run_process__(self): """ 流式运行处理函数 Args: 无参数。 Returns: Generator[Any, None, None]: 返回处理结果的生成器。 """ while not self._is_complete: if not self._need_tool_call: res = self._run() else: res = self._submit_tool_output() for msg in self.__stream_event_process__(res): yield msg def __stream_event_process__(self, run_response): """ 处理流事件,并调用对应的方法 Args: run_response: 包含流事件信息的响应对象 Returns: None Raises: ValueError: 当处理事件时发生异常或中断时工具输出为空时 """ for msg in run_response.content: if len(msg.events) == 0: continue try: event = msg.events[-1] except Exception as e: raise ValueError(e) event_status = event.status if event.status == 'success': self._is_complete = True elif event.status == 'interrupt': self._need_tool_call = True context_func_map = { "preparing": self.preparing, "running": self.running, "error": self.error, "done": self.done, "interrupt": self.interrupt, "success": self.success, } run_context = AppBuilderClientRunContext() self._update_run_context(run_context, msg) self.handle_event_type(run_context, msg) self.handle_content_type(run_context, msg) if event_status in context_func_map: func = context_func_map[event_status] func_res = func(run_context, msg) if event_status == "interrupt": assert isinstance(func_res, list) if len(func_res) == 0: raise ValueError("Tool output is empty") else: if not isinstance(func_res[0], data_class.ToolOutput): try: check_tool_output = data_class.ToolOutput( **func_res[0]) except Exception as e: logger.info( "func interrupt's output should be list[ToolOutput] or list[dict(can be trans to ToolOutput)]") raise ValueError(e) self._last_tool_output = func_res else: logger.warning( "Unknown status: {}, response data: {}".format(event_status, run_response)) yield msg def _update_run_context(self, run_context, run_response): """ 更新运行上下文。 Args: run_context (dict): 运行上下文字典。 run_response (object): 运行响应对象。 Returns: None """ run_context.current_event = run_response.events[-1] run_context.current_tool_calls = run_context.current_event.tool_calls run_context.current_status = run_context.current_event.status run_context.need_tool_submit = run_context.current_status == 'interrupt' run_context.is_complete = run_context.current_status == 'success' try: run_context.current_thought = run_context.current_event.detail.get( "text", {}).get( "function_call", {}).get( "thought", "") if run_context.current_thought == "": run_context.current_thought = ( run_response.events[0].detail.get("text", "") ) except Exception: pass def _run(self): res = self._appbuilder_client.run( conversation_id=self._conversation_id, query=self._query, file_ids=self._file_ids, stream=self._stream, tools=self._tools, action=self._action, ) return res def _submit_tool_output(self): assert self._last_tool_output is not None res = self._appbuilder_client.run( conversation_id=self._conversation_id, file_ids=self._file_ids, stream=self._stream, tool_outputs=self._last_tool_output ) return res def __next__(self): return self._iterator.__next__() def __iter__(self): for item in self._iterator: yield item def __enter__(self): return self def __exit__(self, exc_type, exc_val, exc_tb) -> None: if exc_type is not None: raise exc_val return def reset_state(self): """ 重置该对象的状态,将所有实例变量设置为默认值。 Args: 无 Returns: 无 """ self._appbuilder_client = None self._conversation_id = None self._query = None self._file_ids = None self._tools = None self._stream = False self._event_handler = None self._kwargs = None self._last_tool_output = None self._is_complete = False self._need_tool_call = False self._iterator = None def new_dialog( self, query=None, file_ids=None, tools=None, action=None, stream: bool = None, event_handler=None, **kwargs ): """ 重置handler部分参数,用于复用该handler进行多轮对话。 Args: query (str): 用户输入的查询语句。 file_ids (list, optional): 文件ID列表,默认为None。 tools (list, optional): 工具列表,默认为None。 stream (bool, optional): 是否使用流式处理,默认为False。 action (object, optional): 对话时要进行的特殊操作。如回复工作流agent中“信息收集节点“的消息。 event_handler (callable, optional): 事件处理函数,默认为None。 **kwargs: 其他可选参数。 Returns: None """ self._query = query or self._query self._stream = stream or self._stream self._file_ids = file_ids self._tools = tools self._event_handler = event_handler self._kwargs = kwargs self._action = action # 重置部分状态 self._is_complete = False self._need_tool_call = False self._last_tool_output = None self._iterator = ( self.__run_process__() if not self._stream else self.__stream_run_process__() ) def until_done(self): """ 迭代并遍历内部迭代器中的所有元素,直到迭代器耗尽。 Args: 无参数。 Returns: 无返回值。 """ for _ in self._iterator: pass def handle_content_type(self, run_context, run_response): # 用户可重载该方法,用于处理不同类型的content_type pass def handle_event_type(self, run_context, run_response): # 用户可重载该方法,用于处理不同类型的event_type pass def interrupt(self, run_context, run_response): # 用户可重载该方法,当event_status为interrupt时,会调用该方法 pass def preparing(self, run_context, run_response): # 用户可重载该方法,当event_status为preparing时,会调用该方法 pass def running(self, run_context, run_response): # 用户可重载该方法,当event_status为running时,会调用该方法 pass def error(self, run_context, run_response): # 用户可重载该方法,当event_status为error时,会调用该方法 pass def done(self, run_context, run_response): # 用户可重载该方法,当event_status为done时,会调用该方法 pass def success(self, run_context, run_response): # 用户可重载该方法,当event_status为success时,会调用该方法 pass class ToolCallEventHandler(AppBuilderEventHandler): def __init__(self, functions): super().__init__() self.functions = functions self.result = "" def init( self, appbuilder_client, conversation_id, query, file_ids=None, tools=None, stream: bool = False, event_handler=None, action=None, **kwargs ): super().init(appbuilder_client, conversation_id, query, file_ids, tools, stream, event_handler, action, **kwargs) self.result = "" def reset_state(self): super().reset_state() self.result = "" def new_dialog(self, query=None, file_ids=None, tools=None, action=None, stream=None, event_handler=None, **kwargs): super().new_dialog(query, file_ids, tools, action, stream, event_handler, **kwargs) self.result = "" def interrupt(self, run_context, run_response): thought = run_context.current_thought logger.debug("Agent 中间思考: {}\n".format(thought)) tool_output = [] for tool_call in run_context.current_tool_calls: function_name = tool_call.function.name function_arguments = tool_call.function.arguments result = "" function_map = {f.__name__: f for f in self.functions} if function_name in function_map: result = function_map[function_name](**function_arguments) logger.debug("ToolCall结果: {}\n".format(result)) else: logger.error( "{} is not a valid tool".format(function_name)) tool_output.append( { "tool_call_id": tool_call.id, "output": result, } ) return tool_output def running(self, run_context, run_response): if self._stream and run_response.answer and run_response.answer != "": logger.debug("Agent 流式回答: {}".format(run_response.answer)) self.result += run_response.answer def success(self, run_context, run_response): if not self._stream: logger.debug("Agent 非流式回答: {}".format(run_response.answer)) self.result = run_response.answer ================================================ FILE: python/core/console/base.py ================================================ # Copyright (c) 2023 Baidu, Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from appbuilder.utils.sse_util import SSEClient from appbuilder.core._exception import AppBuilderServerException from appbuilder.core.components.llms.base import CompletionResponse, LLMMessage class ConsoleLLMMessage(LLMMessage): conversation_id: str = "" def __str__(self): return f"Message(name={self.name}, content={self.content}, mtype={self.mtype}, extra={self.extra}, conversation_id={self.conversation_id})" class ConsoleCompletionResponse(CompletionResponse): """ console端大模型返回结果解析 """ error_no = 0 error_msg = "" result = None log_id = "" extra = None conversation_id = "" def __init__(self, response, stream: bool = False): """初始化客户端状态。""" super().__init__(response, stream) self.error_no = 0 self.error_msg = "" self.log_id = response.headers.get("X-Appbuilder-Request-Id", None) self.extra = {} if not stream: data = response.json() if "code" in data and data.get("code") != 0: raise AppBuilderServerException(self.log_id, data["code"], data["message"]) self.result = data.get("result").get("answer", None) self.conversation_id = data.get("result").get("conversation_id", "") content = data.get("result").get("content", None) if content: for item in content: if item.get("content_type") == "references": references = item.get("outputs").get("references") if references: for ref in references: key = ref["from"] if key in self.extra.keys(): self.extra[key].append(ref) else: self.extra[key] = [ref] def message_iterable_wrapper(self, message): """ 对模型输出的 Message 对象进行包装。 当 Message 是流式数据时,数据被迭代完后,将重新更新 content 为 blocking 的字符串。 """ class IterableWrapper: def __init__(self, stream_content): self._content = stream_content self._concat = "" self._extra = {} def __iter__(self): return self def __next__(self): try: resp = next(self._content) result_json = resp.get("result") char = result_json.get("answer", "") conversation_id = result_json.get("conversation_id", "") content = result_json.get("content", None) if content: for item in content: if item.get("content_type") == "references": references = item.get("outputs").get("references") if references: for ref in references: key = ref["from"] if key in self._extra.keys(): self._extra[key].append(ref) else: self._extra[key] = [ref] message.extra = self._extra # Update the original extra message.conversation_id = conversation_id self._concat += char return char except StopIteration: message.content = self._concat # Update the original content raise from collections.abc import Generator if isinstance(message.content, Generator): # Replace the original content with the custom iterable message.content = IterableWrapper(message.content) return message def to_message(self): """将响应结果转换为Message对象。 Returns: Message: Message对象。 """ message = ConsoleLLMMessage() message.id = self.log_id message.content = self.result message.extra = self.extra message.conversation_id = self.conversation_id return self.message_iterable_wrapper(message) ================================================ FILE: python/core/console/component_client/__init__.py ================================================ # Copyright (c) 2024 Baidu, Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from .component_client import ComponentClient ================================================ FILE: python/core/console/component_client/component_client.py ================================================ # Copyright (c) 2024 Baidu, Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """组件""" import json from appbuilder.core.component import Component, Message from appbuilder.core.console.component_client import data_class from appbuilder.core._exception import AppBuilderServerException from appbuilder.utils.logger_util import logger from appbuilder.utils.trace.tracer_wrapper import client_run_trace from appbuilder.utils.sse_util import SSEClient class ComponentClient(Component): def __init__(self, **kwargs): r"""初始化 Returns: response (obj: `ComponentClient`): 组件实例 """ super().__init__(**kwargs) @client_run_trace def run( self, component_id: str, sys_origin_query: str, version: str = None, action: str = None, stream: bool = False, sys_file_urls: dict = None, sys_conversation_id: str = None, sys_end_user_id: str = None, sys_chat_history: list = None, **kwargs, ) -> Message: """ 组件运行 Args: component_id (str): 工作流组件ID或官方组件名称 sys_origin_query (str): 用户输入的原始查询语句 version (str): 组件版本号 action (str): 组件动作 stream (bool): 是否流式返回 sys_file_urls (dict): 文件地址 sys_conversation_id (str): 会话ID sys_end_user_id (str): 用户ID sys_chat_history (list): 聊天 kwargs: 其他参数 Returns: message (Message): 对话结果,一个Message对象,使用message.content获取内容。 """ headers = self.http_client.auth_header_v2() headers["Content-Type"] = "application/json" headers["X-Appbuilder-From"] = "sdk" url_suffix = f"/components/{component_id}" if version is not None: url_suffix += f"/version/{version}" if action is not None: url_suffix += f"?action={action}" url = self.http_client.service_url_v2(url_suffix) all_params = { '_sys_origin_query': sys_origin_query, '_sys_file_urls': sys_file_urls, '_sys_conversation_id': sys_conversation_id, '_sys_chat_history': sys_chat_history, '_sys_end_user_id': sys_end_user_id, **kwargs } parameters = data_class.RunRequest.Parameters(**all_params) request = data_class.RunRequest( stream=stream, parameters=parameters, ) response = self.http_client.session.post( url, headers=headers, json=request.model_dump(exclude_none=True, by_alias=True), timeout=None, ) request_id = self.http_client.check_response_header(response) if stream: client = SSEClient(response) return Message(content=self._iterate_events(request_id, client.events())) else: data = response.json() resp = data_class.RunResponse(**data) return Message(content=resp) @staticmethod def _iterate_events(request_id, events): for event in events: try: data = event.data if len(data) == 0: data = event.raw data = json.loads(data) except json.JSONDecodeError as e: raise AppBuilderServerException( request_id=request_id, message="json decoder failed {}".format(str(e)), ) resp = data_class.RunResponse(**data) yield resp ================================================ FILE: python/core/console/component_client/data_class.py ================================================ # Copyright (c) 2024 Baidu, Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from pydantic import BaseModel from pydantic import Field from typing import Optional, Union from appbuilder.core.component import ComponentOutput, Content class RunRequest(BaseModel): """ Component Run方法请求体 """ class Parameters(BaseModel, extra="allow"): """ Parameters""" class Message(BaseModel): """ Message""" role: str = Field(..., description="对话角色,枚举:user、assistant") content: str = Field(..., description="对话内容") sys_origin_query: str = Field( ..., description="用户query文字,画布中开始节点的系统参数rawQuery", alias="_sys_origin_query" ) sys_file_urls: Optional[dict] = Field( None, description='{"xxx.pdf": "http:///"},画布中开始节点的系统参数fileUrls', alias="_sys_file_urls" ) sys_conversation_id: Optional[str] = Field( None, description="对话id,可通过新建会话接口创建, 画布中开始节点的系统参数conversationId", alias="_sys_conversation_id" ) sys_end_user_id: Optional[str] = Field( None, description="终端用户id,画布中开始节点的系统参数end_user_id", alias="_sys_end_user_id" ) sys_chat_history: Optional[list[Message]] = Field( None, description="聊天历史记录", alias="_sys_chat_history" ) stream: bool = Field(default=False, description='是否流式返回') parameters: Parameters = Field(..., description="调用传参") class ContentWithEvent(Content): """ ContentWithEvent """ class Event(BaseModel): """ Event""" id: str = Field(..., description="事件id") status: str = Field(..., description="事件状态,枚举:preparing、running、error、done") name: str = Field( ..., description="事件名,相当于调用的深度,深度与前端的渲染逻辑有关系", ) created_time: str = Field( ..., description="当前event发送时间", ) error_code: str = Field( None, description="错误码", ) error_message: str = Field( None, description="错误信息", ) event: Event = Field(None, description="事件信息") class RunResponse(BaseModel): """ Component Run方法响应体 """ conversation_id: str = Field(None, description="对话id") message_id: str = Field(None, description="消息id") trace_id: str = Field(None, description="追踪id") user_id: str = Field(None, description="开发者UUID(计费依赖)") end_user_id: str = Field(None, description="终端用户id") status: str = Field(None, description="对话状态,有interrupt, running, error, done四种枚举值") role: str = Field(None, description="当前消息来源,默认tool") content: list[ContentWithEvent] = Field( None, description="当前组件返回内容的主要payload,List[ContentWithEvent],每个 Content 包括了当前 event 的一个元素", ) request_id: str = Field(None, description="请求id") code: Union[str, int] = Field(None, description="响应码") message: str = Field(None, description="响应消息") ================================================ FILE: python/core/console/dataset/__init__.py ================================================ # Copyright (c) 2023 Baidu, Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from .dataset import Dataset ================================================ FILE: python/core/console/dataset/dataset.py ================================================ from typing import List, Dict from appbuilder.core._client import HTTPClient from appbuilder.core.console.dataset.model import DocumentListResponse, AddDocumentsResponse from appbuilder.core.constants import MAX_DOCUMENTS_NUM, SUPPORTED_FILE_TYPE import json import os from appbuilder.utils.func_utils import deprecated from appbuilder.utils.trace.tracer_wrapper import client_tool_trace class Dataset: r""" console知识库操作工具 Examples: .. code-block:: python import appbuilder import os os.environ["APPBUILDER_TOKEN"] = '...' dataset = appbuilder.Dataset.create_dataset("baidu-test") # 上传文档 file_paths = ["./test.pdf"] document_infos = dataset.add_documents(file_paths) # 获取第一页的文档列表, 每页10条 document_list = dataset.get_documents(1, 10) # 删除文档 document_ids = [document_infos.document_ids[0]] dataset.delete_documents(document_ids) """ create_url: str = "/v1/ai_engine/agi_platform/v1/datasets/create" add_file_url: str = "/v1/ai_engine/agi_platform/v1/datasets/documents" get_file_list_url: str = "/v1/ai_engine/agi_platform/v1/datasets/documents/list_page" delete_file_url: str = "/v1/ai_engine/agi_platform/v1/datasets/document/delete" upload_file_url: str = "/v1/ai_engine/agi_platform/v1/datasets/files/upload" def __init__(self, dataset_id: str = "", dataset_name: str = ""): r""" 初始化Dataset实例 Args: dataset_id: 知识库ID dataset_name: 知识库名称 Returns: Dataset: 知识库实例 """ self.dataset_id = dataset_id self.dataset_name = dataset_name self._http_client = None @property def http_client(self): if self._http_client is None: self._http_client = HTTPClient() return self._http_client @classmethod def create_dataset(cls, dataset_name: str): r""" 创建知识库 Args: dataset_name: 知识库名称 Returns: Dataset: 创建成功的知识库实例 """ payload = json.dumps({"name": dataset_name}) http_client = HTTPClient() headers = http_client.auth_header() headers["Content-Type"] = "application/json" response = http_client.session.post(url=http_client.service_url(cls.create_url), headers=headers, data=payload) http_client.check_response_header(response) http_client.check_console_response(response) response = response.json()["result"] return Dataset(dataset_id=response["id"], dataset_name=response["name"]) @deprecated() def add_documents(self, file_path_list: List[str], is_custom_process_rule: bool = False, custom_process_rule: Dict = None, is_enhanced: bool = False) -> AddDocumentsResponse: r""" 向知识库中添加文档 Args: file_path_list: 文档路径列表 is_custom_process_rule: 是否使用自定义文档处理规则, 默认为False, 使用平台的默认规则,为True时使用自定义规则 custom_process_rule: 自定义文档规则,当is_custom_process_rule为True时生效,格式示例如下: { "separators": ["。", ","], # 文本切分符,支持这几种[ , , "?", , "!", "?", "……"] "target_length": 300, # 文本切片片段长度,取值范围[300, 800] "overlap_rate": 0.3 # 文本片段重叠率,取值范围[0, 0.3] } is_enhanced: 是否开启知识增强, 默认为False,在检索问答时通过知识点来索引到对应的切片,大模型根据切片内容生成答案,开启知识增强会调用大模型抽取更加丰富的知识点,增加切片的召回率 Returns: AddDocumentsResponse: 添加文档的响应结果,包含以下属性: - dataset_id (str): 知识库id - document_ids (List[str]): 文档id列表 """ for file_path in file_path_list: file_type = file_path.split(".")[-1].lower() if file_type not in SUPPORTED_FILE_TYPE: raise ValueError(f"Unsupported file type: {file_path}, only support file types: {SUPPORTED_FILE_TYPE}") documents = self.get_documents(1, MAX_DOCUMENTS_NUM) current_documents_num = len(documents.data) if len(file_path_list) + current_documents_num > MAX_DOCUMENTS_NUM: raise ValueError(f"too much documents. at most upload {MAX_DOCUMENTS_NUM} documents per dataset,left {MAX_DOCUMENTS_NUM-current_documents_num} documents can be uploaded") file_ids = [] for file_path in file_path_list: upload_res = self._upload_document(file_path) file_ids.append(upload_res["id"]) payload = {"dataset_id": self.dataset_id, "file_ids": file_ids, "is_custom_process_rule": is_custom_process_rule, "is_enhanced": is_enhanced} if is_custom_process_rule and custom_process_rule: payload["custom_process_rule"] = custom_process_rule payload = json.dumps(payload) headers = self.http_client.auth_header() headers["Content-Type"] = "application/json" response = self.http_client.session.post(url=self.http_client.service_url(self.add_file_url), headers=headers, data=payload) self.http_client.check_response_header(response) self.http_client.check_console_response(response) res = AddDocumentsResponse.parse_obj(response.json()["result"]) return res def _upload_document(self, file_path: str): r""" 上传文档 Args: file_path: 文档路径 Returns: 上传文档的信息 """ headers = self.http_client.auth_header() with open(file_path, 'rb') as file: files = {'file': (os.path.basename(file_path), file)} response = self.http_client.session.post(url=self.http_client.service_url(self.upload_file_url), files=files, headers=headers) self.http_client.check_response_header(response) self.http_client.check_console_response(response) res = response.json()["result"] return res @deprecated() def delete_documents(self, document_ids: List[str]): r""" 删除知识库中的文档 Args: document_ids: 文档id列表 Returns: None """ for document_id in document_ids: self._delete_document(document_id) def _delete_document(self, document_id): """ 删除知识库中的文档 参数: document_id: 文档id """ payload = json.dumps({"dataset_id": self.dataset_id, "document_id": document_id}) headers = self.http_client.auth_header() headers["Content-Type"] = "application/json" response = self.http_client.session.post(url=self.http_client.service_url(self.delete_file_url), headers=headers, data=payload) self.http_client.check_response_header(response) self.http_client.check_console_response(response) @deprecated() def get_documents(self, page: int, limit: int, keyword: str = "") -> DocumentListResponse: r""" 获取知识库中的文档列表 Args: page: 第几页 limit: 每页文档数 keyword: 文件名关键字,支持模糊查询 Returns: DocumentListResponses实例,返回示例: { "data": [ { "id":"d2d1bc1a-1763-4162-88b2-0dad225da16f", # 文档id "name": "唐诗三百首(全集)全新编辑版.pdf", # 文档名称 "created_from": "web", # 创建来源 "created_by": "76efed91-cf19-435d-993c-cdd901d6d13c", # 创建人 "created_at": 1705958975, # 创建时间 "indexing_status": "indexing", # 文档处理状态 "error": null, # 文档处理错误信息 "enabled": true, # 文档是否启用 "disabled_at": null, # 文档禁用时间 "disabled_by": null, # 文档禁用人 "display_status": "indexing", # 文档显示状态,和前端展示状态一致 "word_count": 5024 # 文档字数 } ], "has_more": false, # 是否还有下一页 "limit": 10, # 每页文档数 "total": 1, # 总页数 "page": 1 # 当前页 } """ payload = json.dumps({"dataset_id": self.dataset_id, "page": page, "limit": limit, "keyword": keyword}) headers = self.http_client.auth_header() headers["Content-Type"] = "application/json" response = self.http_client.session.post(url=self.http_client.service_url(self.get_file_list_url), headers=headers, data=payload) self.http_client.check_response_header(response) self.http_client.check_console_response(response) res = DocumentListResponse.parse_obj(response.json()["result"]) return res ================================================ FILE: python/core/console/dataset/model.py ================================================ from typing import List, Optional from pydantic import BaseModel class DocumentInfo(BaseModel): id: str name: str created_at: int indexing_status: str error: Optional[str] = None enabled: bool disabled_at: Optional[int] = None disabled_by: Optional[str] = None display_status: str word_count: int class DocumentListResponse(BaseModel): data: List[DocumentInfo] has_more: bool limit: int total: int page: int class AddDocumentsResponse(BaseModel): dataset_id: str document_ids: List[str] ================================================ FILE: python/core/console/knowledge_base/__init__.py ================================================ # Copyright (c) 2024 Baidu, Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from .knowledge_base import KnowledgeBase from .data_class import ( CustomProcessRule, DocumentSource, DocumentSourceUrlConfig, DocumentProcessOption, DocumentChoices, DocumentSeparator, DocumentPattern, DocumentChunker, ) ================================================ FILE: python/core/console/knowledge_base/data_class.py ================================================ # Copyright (c) 2024 Baidu, Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from __future__ import annotations from datetime import datetime from pydantic import BaseModel, Field from enum import Enum from typing import Union, Optional, List class KnowledgeBaseUploadFileResponse(BaseModel): request_id: str = Field(..., description="请求ID") id: str = Field(..., description="文件ID") name: str = Field(..., description="文件名称") class CustomProcessRule(BaseModel): separators: list[str] = Field(..., description="分段符号列表", example=[ ",", "?"]) target_length: int = Field(..., description="分段最大长度", ge=300, le=1200) overlap_rate: float = Field( ..., description="分段重叠最大字数占比,推荐值0.25", ge=0, le=0.3, example=0.2 ) class KnowledgeBaseAddDocumentRequest(BaseModel): knowledge_base_id: str = Field(..., description="知识库ID") content_type: str = Field( "raw_text", description="文档类型", enum=["raw_text", "qa"] ) file_ids: list[str] = Field(..., description="文件ID列表") is_enhanced: bool = Field(False, description="是否开启知识增强") custom_process_rule: Optional[CustomProcessRule] = Field( None, description="自定义分段规则" ) class KnowledgeBaseAddDocumentResponse(BaseModel): request_id: str = Field(..., description="请求ID") knowledge_base_id: str = Field(..., description="知识库ID") document_ids: list[str] = Field(..., description="成功新建的文档id集合") class KnowledgeBaseDeleteDocumentRequest(BaseModel): knowledge_base_id: str = Field(..., description="知识库ID") document_id: str = Field(..., description="待删除的文档id") class KnowledgeBaseDeleteDocumentResponse(BaseModel): request_id: str = Field(..., description="请求ID") class KnowledgeBaseGetDocumentsListRequest(BaseModel): knowledge_base_id: str = Field(..., description="知识库ID") limit: int = Field( 10, description="返回文档数量大小,默认10,最大值100", le=100, ge=1 ) after: str = Field( "", description="用于分页的游标。after 是一个文档的id,它定义了在列表中的位置。例如,如果你发出一个列表请求并收到 10个对象,以 app_id_123 结束,那么你后续的调用可以包含 after=app_id_123 以获取列表的下一页数据。", ) before: str = Field( "", description="用于分页的游标。与after相反,填写它将获取前一页数据,如果和after都传,两个参数都会起到分页效果,维度是创建时间", ) class DocumentMeta(BaseModel): source: Optional[str] = Field(None, description="文档来源") file_id: Optional[str] = Field(None, description="文档对应的文件ID") url: Optional[str] = Field(None, description="原文件下载链接") mime_type: Optional[str] = Field( None, description="文件类型,目前支持doc/txt/docx/pdf/ppt/pptx/xlsx/xls/csv/json这几种文件类型。如果是通过url方式导入的文档,该值为url", ) file_size: Optional[int] = Field(None, description="文件大小,单位bytes") class Document(BaseModel): id: str = Field(..., description="文档ID") name: str = Field(..., description="文档名称") created_at: int = Field(..., description="文档创建时间") word_count: int = Field(..., description="文档字数") enabled: bool = Field(True, description="文档是否可用") meta: Optional[DocumentMeta] = Field( ..., description="文档元信息,包括source、file_id" ) class KnowledgeBaseGetDocumentsListResponse(BaseModel): request_id: str = Field(..., description="请求ID") data: list[Document] = Field([], description="文档信息列表") class DescribeDocumentsRequest(BaseModel): knowledgeBaseId: str = Field(..., description="知识库ID") marker: Optional[str] = Field(None, description="起始位置") maxKeys: int = Field( 10, description="返回文档数量大小,默认10,最大值100" ) class DescribeDocumentMeata(BaseModel): source: Optional[str] = Field(None, description="文档来源") fileId: Optional[str] = Field(None, description="文档对应的文件ID") class DescribeDocument(BaseModel): id: str = Field(..., description="文档ID") name: str = Field(..., description="文档名称") createdAt: str = Field(..., description="文档创建时间") wordCount: int = Field(..., description="文档字数") enabled: bool = Field(True, description="文档是否可用") displayStatus: str = Field( ..., description="文档状态。available:可用,queuing:排队中,notConfigured:数据待配置,parsing:解析中,indexing:处理中,parseError:解析失败,error:处理失败, retrainingSegmentUnusable:重建切片中,切片不可用, retrainErrSegmentUsable:重建切片错误,旧切片可用", ) meta: Optional[DescribeDocumentMeata] = Field(..., description="文档元信息,包括source、fileId") class DescribeDocumentsResponse(BaseModel): requestId: str = Field(..., description="请求ID") marker: str = Field(..., description="起始位置") isTruncated: bool = Field( ..., description="true表示后面还有数据,false表示已经是最后一页" ) nextMarker: str = Field(..., description="下一页起始位置") maxKeys: int = Field(..., description="本次查询包含的最大结果集数量") data: list[DescribeDocument] = Field(..., description="文档信息列表") class KnowledgeBaseConfigIndex(BaseModel): type: str = Field(..., description="索引类型", enum=["public", "bes", "vdb"]) clusterId: Optional[str] = Field(None, description="集群/实例 ID") username: Optional[str] = Field(None, description="bes用户名") password: Optional[str] = Field(None, description="bes密码") location: Optional[str] = Field( None, description="托管资源的区域", enum=["bj", "bd", "sz", "gz"]) class KnowledgeBaseConfigCatalogue(BaseModel): pathPrefix: Optional[str] = Field(None, description="知识库所属目录绝对路径") class KnowledgeBaseConfig(BaseModel): index: Optional[KnowledgeBaseConfigIndex] = Field(..., description="索引配置") catalogue: Optional[KnowledgeBaseConfigCatalogue] = Field( None, description="知识库目录配置") class KnowledgeBaseCreateKnowledgeBaseRequest(BaseModel): name: str = Field(..., description="知识库名称") description: str = Field(None, description="知识库描述") config: Optional[KnowledgeBaseConfig] = Field(..., description="知识库配置") class KnowledgeBaseGetDetailRequest(BaseModel): id: str = Field(..., description="知识库ID") class KnowledgeBaseDetailResponse(BaseModel): requestId: str = Field(..., description="请求ID") id: str = Field(..., description="知识库ID") name: str = Field(..., description="知识库名称") description: Optional[str] = Field(None, description="知识库描述") config: Optional[KnowledgeBaseConfig] = Field(..., description="知识库配置") class KnowledgeBaseModifyRequest(BaseModel): id: str = Field(..., description="知识库ID") name: Optional[str] = Field(None, description="知识库名称") description: Optional[str] = Field(None, description="知识库描述") config: Optional[KnowledgeBaseConfig] = Field(None, description="知识库配置") class KnowledgeBaseDeleteRequest(BaseModel): id: str = Field(..., description="知识库ID") class KnowledgeBaseGetListRequest(BaseModel): marker: Optional[str] = Field(None, description="起始位置") keyword: Optional[str] = Field(None, description="搜索关键字") maxKeys: int = Field( 10, description="返回文档数量大小,默认10,最大值100", le=100, ge=1 ) class KnowledgeBaseGetListConfigIndex(BaseModel): type: str = Field(None, description="索引类型") esUrl: Optional[str] = Field('', description="es地址") class KnowledgeBaseGetListConfig(BaseModel): index: Optional[KnowledgeBaseGetListConfigIndex] = Field( ..., description="索引配置") class KnowledgeBaseGetListDetailResponse(BaseModel): id: str = Field(..., description="知识库ID") name: str = Field(..., description="知识库名称") description: Optional[str] = Field(None, description="知识库描述") config: Optional[KnowledgeBaseGetListConfig] = Field( ..., description="知识库配置") class KnowledgeBaseGetListResponse(BaseModel): requestId: str = Field(..., description="请求ID") data: list[KnowledgeBaseGetListDetailResponse] = Field( [], description="知识库详情列表") marker: str = Field(..., description="起始位置") nextMarker: str = Field(..., description="下一页起始位置") maxKeys: int = Field(10, description="返回文档数量大小,默认10,最大值100") isTruncated: bool = Field(..., description="是否有更多结果") class DocumentSourceUrlConfig(BaseModel): frequency: int = Field( ..., description="更新频率,目前支持的更新频率为-1(不自动更新),1(每天),3(每3天),7(每7天),30(每30天)。", ) class DocumentSource(BaseModel): type: str = Field(..., description="数据来源类型", enum=["bos", "web"]) urls: list[str] = Field(None, description="文档URL") urlDepth: int = Field(None, description="url下钻深度,1时不下钻") urlConfigs: Optional[list[DocumentSourceUrlConfig]] = Field( None, description="该字段的长度需要和source、urls字段长度保持一致。") class DocumentChoices(BaseModel): choices: list[str] = Field(..., description="选择项") class DocumentSeparator(BaseModel): separators: list[str] = Field(..., description="分段符号") targetLength: int = Field(..., description="分段最大长度") overlapRate: float = Field(..., description="分段重叠最大字数占比,推荐值0.25") class DocumentPattern(BaseModel): markPosition: str = Field( ..., description="命中内容放置策略, head:前序切片, tail:后序切片, drop:匹配后丢弃", enum=["head", "tail", "drop"], ) regex: str = Field(..., description="正则表达式") targetLength: int = Field(..., description="分段最大长度") overlapRate: float = Field(..., description="分段重叠最大字数占比,推荐值0.25") class DocumentChunker(BaseModel): choices: list[str] = Field( ..., description="使用哪些chunker方法 (separator | pattern | onePage),separator:自定义切片—标识符,pattern:自定义切片—标识符中选择正则表达式,onePage:整文件切片", ) prependInfo: list[str] = Field( None, description="chunker关联元数据,可选值为title (增加标题), filename(增加文件名)", ) separator: Optional[DocumentSeparator] = Field(None, description="分段符号") pattern: Optional[DocumentPattern] = Field(None, description="正则表达式") class DocumentProcessOption(BaseModel): template: str = Field( ..., description="模板类型,ppt: 模版配置—ppt幻灯片, resume:模版配置—简历文档, paper:模版配置—论文文档, custom:自定义配置—自定义切片, default:自定义配置—默认切分", enum=["ppt", "paper", "qaPair", "resume", " custom", "default"], ) parser: Optional[DocumentChoices] = Field( None, description="解析方法(文字提取默认启动,参数不体现,layoutAnalysis版面分析,ocr光学字符识别,pageImageAnalysis文档图片解析,chartAnalysis图表解析,tableAnalysis表格深度解析,按需增加)", ) knowledgeAugmentation: Optional[DocumentChoices] = Field( None, description="知识增强,faq、spokenQuery、spo、shortSummary按需增加。问题生成:faq、spokenQuery,段落摘要:shortSummary,三元组知识抽取:spo", ) chunker: Optional[DocumentChunker] = Field(None, description="分段器类型") class KnowledgeBaseCreateDocumentsRequest(BaseModel): id: str = Field(..., description="知识库ID") source: DocumentSource = Field(..., description="文档来源") contentFormat: str = Field( ..., description="文档内容格式, (rawText 普通文件上传)" ) processOption: Optional[DocumentProcessOption] = Field( None, description="文档处理选项" ) class KnowledgeBaseCreateDocumentsResponse(BaseModel): requestId: str = Field(..., description="请求ID") documentIds: list[str] = Field(..., description="文档ID列表") class KnowledgeBaseUploadDocumentsResponse(BaseModel): requestId: str = Field(..., description="请求ID") documentId: str = Field(..., description="文档ID") class CreateChunkRequest(BaseModel): knowledgeBaseId: str = Field(None, description="知识库ID") documentId: str = Field(..., description="文档ID") content: str = Field(..., description="文档内容") class CreateChunkResponse(BaseModel): id: str = Field(..., description="切片ID") class ModifyChunkRequest(BaseModel): knowledgeBaseId: str = Field(None, description="知识库ID") chunkId: str = Field(..., description="切片ID") content: str = Field(..., description="文档内容") enable: bool = Field(..., description="是否启用") class DeleteChunkRequest(BaseModel): knowledgeBaseId: str = Field(None, description="知识库ID") chunkId: str = Field(..., description="切片ID") class DescribeChunkRequest(BaseModel): knowledgeBaseId: str = Field(None, description="知识库ID") chunkId: str = Field(..., description="切片ID") class DescribeChunkResponse(BaseModel): id: str = Field(..., description="切片ID") type: str = Field(..., description="切片类型") knowledgeBaseId: str = Field(..., description="知识库ID") documentId: str = Field(..., description="文档ID") content: str = Field(..., description="文档内容") enabled: bool = Field(..., description="是否启用") wordCount: int = Field(..., description="切片内字符数量") tokenCount: int = Field(..., description="切片内token数量") status: str = Field(..., description="切片状态") statusMessage: str = Field(..., description="切片状态信息") imageUrls: list[str] = Field(..., description="图片地址") createTime: int = Field(..., description="创建时间") updateTime: int = Field(None, description="更新时间") class DescribeChunksRequest(BaseModel): knowledgeBaseId: str = Field(None, description="知识库ID") documentId: str = Field(..., description="文档ID") marker: Optional[str] = Field(None, description="起始位置") maxKeys: Optional[int] = Field( None, description="返回文档数量大小,默认10,最大值100" ) type: Optional[str] = Field( None, description="切片类型。RAW:原文切片、NEW:新增切片、COPY:复制切片" ) keyword: Optional[str] = Field( None, description="根据关键字模糊匹配切片,最大长度2000字符" ) class DescribeChunksResponse(BaseModel): data: list[DescribeChunkResponse] = Field(..., description="切片列表") marker: str = Field(..., description="起始位置") isTruncated: bool = Field( ..., description="true表示后面还有数据,false表示已经是最后一页" ) nextMarker: str = Field(..., description="下一页起始位置") maxKeys: int = Field(..., description="本次查询包含的最大结果集数量") class MetadataFilter(BaseModel): operator: str = Field(..., description="操作符名称。==:等于,in:在数组中,not_in:不在数组中") field: str = Field(None, description="字段名,目前支持doc_id") value: Union[str, list[str]] = Field( ..., description="字段值,如果是in操作符,value为数组" ) class MetadataFilters(BaseModel): filters: list[MetadataFilter] = Field(..., description="过滤条件") condition: str = Field(..., description="文档组合条件。and:与,or:或") class PreRankingConfig(BaseModel): bm25_weight: float = Field( None, description="粗排bm25比重,取值范围在 [0, 1],默认0.75" ) vec_weight: float = Field( None, description="粗排向量余弦分比重,取值范围在 [0, 1],默认0.25" ) bm25_b: float = Field( None, description="控制文档长度对评分影响的参数,取值范围在 [0, 1],默认0.75" ) bm25_k1: float = Field( None, description="词频饱和因子,控制词频(TF)对评分的影响,常取值范围在 [1.2, 2.0],默认1.5", ) bm25_max_score: float = Field( None, description="得分归一化参数,不建议修改,默认50" ) class QueryType(str, Enum): FULLTEXT = "fulltext" # 全文检索 SEMANTIC = "semantic" # 语义检索 HYBRID = "hybrid" # 混合检索 class ElasticSearchRetrieveConfig(BaseModel): # 托管资源为共享资源 或 BES资源时使用该配置 name: str = Field(..., description="配置名称") type: str = Field(None, description="elastic_search标志,该节点为es全文检索") threshold: float = Field(None, description="得分阈值,默认0.1") top: int = Field(None, description="召回数量,默认400") class VectorDBRetrieveConfig(BaseModel): name: str = Field(..., description="该节点的自定义名称。") type: str = Field("vector_db", description="该节点的类型,默认为vector_db。") threshold: Optional[float] = Field( 0.1, description="得分阈值。取值范围:[0, 1]", ge=0.0, le=1.0) top: Optional[int] = Field( 400, description="召回数量。取值范围:[0, 800]", ge=0, le=800) pre_ranking: Optional[PreRankingConfig] = Field(None, description="粗排配置") class SmallToBigConfig(BaseModel): name: str = Field(..., description="配置名称") type: str = Field( "small_to_big", description="small_to_big标志,该节点为small_to_big节点") class RankingConfig(BaseModel): name: str = Field(..., description="配置名称") type: str = Field(None, description="ranking标志,该节点为ranking节点") inputs: list[str] = Field( ..., description='输入的节点名,如es检索配置的名称为pipeline_001,则该inputs为["pipeline_001"]', ) model_name: str = Field(None, description="ranking模型名(当前仅一种,暂不生效)") top: int = Field(None, description="取切片top进行排序,默认20,最大400") class QueryPipelineConfig(BaseModel): id: str = Field( None, description="配置唯一标识,如果用这个id,则引用已经配置好的QueryPipeline" ) pipeline: list[Union[ElasticSearchRetrieveConfig, RankingConfig, VectorDBRetrieveConfig, SmallToBigConfig]] = Field( None, description="配置的Pipeline,如果没有用id,可以用这个对象指定一个新的配置" ) class QueryKnowledgeBaseRequest(BaseModel): query: str = Field(..., description="检索query") type: Optional[QueryType] = Field( None, description="检索策略的枚举, fulltext:全文检索, semantic:语义检索, hybrid:混合检索") top: int = Field(None, description="返回结果数量") skip: int = Field( None, description="跳过多少条记录, 通过top和skip可以实现类似分页的效果,比如top 10 skip 0,取第一页的10个,top 10 skip 10,取第二页的10个", ) rank_score_threshold: float = Field( 0.4, description="重排序匹配分阈值,只有rank_score大于等于该分值的切片重排序时才会被筛选出来。当且仅当,pipeline_config中配置了ranking节点时,该过滤条件生效。取值范围: [0, 1]。", ge=0.0, le=1.0, ) knowledgebase_ids: list[str] = Field(..., description="知识库ID列表") metadata_filters: Optional[MetadataFilters] = Field(None, description="元数据过滤条件") pipeline_config: Optional[QueryPipelineConfig] = Field(None, description="检索配置") class RowLine(BaseModel): key: str = Field(..., description="列名") index: int = Field(..., description="列号") value: str = Field(..., description="列值") enable_indexing: bool = Field(..., description="是否索引") enable_response: bool = Field( ..., description="是否参与问答(即该列数据是否对大模型可见)。当前值固定为true。", ) class ChunkLocation(BaseModel): page_num: list[int] = Field(..., description="页面") box: list[list[int]] = Field( ..., description="文本内容位置,在视觉上是文本框,格式是长度为4的int数组,含义是[x, y, width, height]", ) class Chunk(BaseModel): chunk_id: str = Field(..., description="切片ID") knowledgebase_id: str = Field(..., description="知识库ID") document_id: str = Field(..., description="文档ID") document_name: str = Field(None, description="文档名称") meta: dict = Field(None, description="文档元数据") chunk_type: str = Field(..., description="切片类型") content: str = Field(..., description="切片内容") create_time: datetime = Field(..., description="创建时间") update_time: datetime = Field(..., description="更新时间") retrieval_score: float = Field(..., description="粗检索得分") rank_score: float = Field(..., description="rerank得分") locations: ChunkLocation = Field(None, description="切片位置") children: List[Chunk] = Field(None, description="子切片") class QueryKnowledgeBaseResponse(BaseModel): requestId: str = Field(None, description="请求ID") code: str = Field(None, description="状态码") message: str = Field(None, description="状态信息") chunks: list[Chunk] = Field(..., description="切片列表") total_count: int = Field(..., description="切片总数") ================================================ FILE: python/core/console/knowledge_base/knowledge_base.py ================================================ # Copyright (c) 2024 Baidu, Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import os import json import uuid from typing import Optional from appbuilder.core._client import HTTPClient from appbuilder.core.console.knowledge_base import data_class from appbuilder.core.component import Message, Component from appbuilder.utils.func_utils import deprecated from appbuilder.utils.trace.tracer_wrapper import client_tool_trace class KnowledgeBase(Component): r""" console知识库操作工具,用于创建、删除、查询、更新知识库等操作 Examples: .. code-block:: python import os import appbuilder os.environ["APPBUILDER_TOKEN"] = "your_appbuilder_token" my_knowledge_base_id = "your_knowledge_base_id" my_knowledge = appbuilder.KnowledgeBase(my_knowledge_base_id) print("知识库ID: ", my_knowledge.knowledge_id) list_res = my_knowledge.describe_documents() print("文档列表: ", list_res) """ def __init__( self, knowledge_id: Optional[str] = None, knowledge_name: Optional[str] = None, **kwargs ): r""" 初始化KnowledgeBase类实例 Args: knowledge_id (Optional[str]): 知识库ID knowledge_name (Optional[str]): 知识库名称 """ super().__init__(**kwargs) self.knowledge_id = knowledge_id self.knowledge_name = knowledge_name @classmethod @deprecated() def create_knowledge(cls, knowledge_name: str) -> "KnowledgeBase": r""" 创建知识库 Deprecated: use create_knowledge_base instead Args: knowledge_name (str): 知识库名称 Returns: KnowledgeBase: 返回一个KnowledgeBase对象 """ payload = json.dumps({"name": knowledge_name}) http_client = HTTPClient() headers = http_client.auth_header() headers["Content-Type"] = "application/json" create_url = "/v1/ai_engine/agi_platform/v1/datasets/create" response = http_client.session.post( url=http_client.service_url(create_url), headers=headers, data=payload ) http_client.check_response_header(response) http_client.check_console_response(response) response = response.json()["result"] return KnowledgeBase( knowledge_id=response["id"], knowledge_name=response["name"] ) @deprecated() def upload_file( self, file_path: str, client_token: str = None ) -> data_class.KnowledgeBaseUploadFileResponse: r""" 上传文件到知识库 Args: file_path (str): 文件路径 client_token (str, optional): 客户端令牌。默认为None,此时会自动生成一个随机UUID作为客户端令牌。 Returns: KnowledgeBaseUploadFileResponse: 返回一个KnowledgeBaseUploadFileResponse对象,包含以下属性: - request_id (int): 请求id - id (str): 文件id - name (dict): 文件名称 """ if not os.path.exists(file_path): raise FileNotFoundError("File {} does not exist".format(file_path)) headers = self.http_client.auth_header_v2() if not client_token: client_token = str(uuid.uuid4()) url = self.http_client.service_url_v2("/file", client_token=client_token) with open(file_path, "rb") as f: multipart_form_data = {"file": (os.path.basename(file_path), f)} response = self.http_client.session.post( url=url, headers=headers, files=multipart_form_data, ) self.http_client.check_response_header(response) self.http_client.check_console_response(response) data = response.json() resp = data_class.KnowledgeBaseUploadFileResponse(**data) return resp @deprecated() def add_document( self, content_type: str, file_ids: list[str] = [], is_enhanced: bool = False, custom_process_rule: Optional[data_class.CustomProcessRule] = None, knowledge_base_id: Optional[str] = None, client_token: str = None, ) -> data_class.KnowledgeBaseAddDocumentResponse: r""" 添加文档到知识库 Args: content_type (str): 内容类型,可选值有"raw_text", "qa"。 file_ids (List[str], optional): 文件ID列表。默认为空列表。 is_enhanced (bool, optional): 是否增强。默认为False。 custom_process_rule (Optional[data_class.CustomProcessRule], optional): 自定义处理规则。默认为None。 knowledge_base_id (Optional[str], optional): 知识库ID。默认为None,此时使用当前类的knowledge_id属性。 client_token (str): 客户端令牌。默认为None,此时会自动生成一个随机UUID作为客户端令牌。 Returns: KnowledgeBaseAddDocumentResponse: 添加文档的相应结果。包含以下属性: - request_id (str): 请求ID - knowledge_base_id (str): 知识库ID - document_ids (list[str]): 成功新建的文档id集合 """ if self.knowledge_id == None and knowledge_base_id == None: raise ValueError( "knowledge_base_id cannot be empty, please call `create` first or use existing one" ) headers = self.http_client.auth_header_v2() headers["content-type"] = "application/json" if not client_token: client_token = str(uuid.uuid4()) url = self.http_client.service_url_v2( "/knowledge_base/document", client_token=client_token ) request = data_class.KnowledgeBaseAddDocumentRequest( knowledge_base_id=knowledge_base_id or self.knowledge_id, content_type=content_type, file_ids=file_ids, is_enhanced=is_enhanced, custom_process_rule=custom_process_rule, ) response = self.http_client.session.post( url=url, headers=headers, json=request.model_dump() ) self.http_client.check_response_header(response) self.http_client.check_console_response(response) data = response.json() resp = data_class.KnowledgeBaseAddDocumentResponse(**data) return resp def delete_document( self, document_id: str, knowledge_base_id: Optional[str] = None, client_token: str = None, ) -> data_class.KnowledgeBaseDeleteDocumentResponse: r""" 删除知识库中的文档 Args: document_id (str): 文档ID knowledge_base_id (Optional[str], optional): 知识库ID。默认为None,此时使用当前类的knowledge_id属性。 client_token (str): 客户端令牌。默认为None,此时会自动生成一个随机UUID作为客户端令牌。 Returns: KnowledgeBaseDeleteDocumentResponse: 删除文档的响应消息,包含以下属性: - request_id (str): 请求ID """ if self.knowledge_id == None and knowledge_base_id == None: raise ValueError( "knowledge_base_id cannot be empty, please call `create` first or use existing one" ) headers = self.http_client.auth_header_v2() headers["content-type"] = "application/json" if not client_token: client_token = str(uuid.uuid4()) url = self.http_client.service_url_v2( "/knowledge_base/document", client_token=client_token ) request = data_class.KnowledgeBaseDeleteDocumentRequest( knowledge_base_id=knowledge_base_id or self.knowledge_id, document_id=document_id, ) response = self.http_client.session.delete( url=url, headers=headers, params=request.model_dump() ) self.http_client.check_response_header(response) self.http_client.check_console_response(response) data = response.json() resp = data_class.KnowledgeBaseDeleteDocumentResponse(**data) return resp def describe_documents(self, knowledge_base_id: Optional[str]=None, marker: Optional[str] = None, maxKeys: int = 10): r""" 获取知识库中的文档列表 Args: knowledge_base_id (Optional[str], optional): 知识库ID。默认为None,此时使用当前类的knowledge_id属性。 marker (Optional[str], optional): 分页标记。默认为None。 maxKeys (int, optional): 最大键数。默认为10。 Returns: DescribeDocumentsResponse: 描述文档的响应消息, 一个DescribeDocumentsResponse对象,包含以下属性: - data (list[DescribeDocument]): 切片列表 - marker (str): 起始位置 - isTruncated (bool): true表示后面还有数据,false表示已经是最后一页 - nextMarker (str): 下一页起始位置 - maxKeys (int): 本次查询包含的最大结果集数量 """ if self.knowledge_id == None and knowledge_base_id == None: raise ValueError( "knowledge_base_id cannot be empty, please call `create` first or use existing one" ) headers = self.http_client.auth_header_v2() headers["content-type"] = "application/json" url = self.http_client.service_url_v2("/knowledgeBase?Action=DescribeDocuments") request = data_class.DescribeDocumentsRequest( knowledgeBaseId=knowledge_base_id or self.knowledge_id, marker=marker, maxKeys=maxKeys ) response = self.http_client.session.post( url=url, headers=headers, json=request.model_dump( exclude_none=True) ) self.http_client.check_response_header(response) self.http_client.check_console_response(response) data = response.json() resp = data_class.DescribeDocumentsResponse(**data) return resp @deprecated("use describe_documents instead") def get_documents_list( self, limit: int = 10, after: Optional[str] = "", before: Optional[str] = "", knowledge_base_id: Optional[str] = None, ) -> data_class.KnowledgeBaseGetDocumentsListResponse: r""" 获取知识库中的文档列表 Args: limit (int, optional): 限制数量。默认为10。 after (Optional[str], optional): 起始位置。默认为空字符串""。 before (Optional[str], optional): 结束位置。默认为空字符串""。 knowledge_base_id (Optional[str], optional): 知识库ID。默认为None,此时使用当前类的knowledge_id属性。 Returns: KnowledgeBaseGetDocumentsListResponse: 知识库文档列表服务的响应消息,包含以下属性: - request_id (str): 请求ID - data (list[Document]): 文档信息列表 """ if self.knowledge_id == None and knowledge_base_id == None: raise ValueError( "knowledge_base_id cannot be empty, please call `create` first or use existing one" ) headers = self.http_client.auth_header_v2() headers["content-type"] = "application/json" url = self.http_client.service_url_v2("/knowledge_base/documents") request = data_class.KnowledgeBaseGetDocumentsListRequest( knowledge_base_id=knowledge_base_id or self.knowledge_id, limit=limit, after=after, before=before, ) response = self.http_client.session.get( url=url, headers=headers, params=request.model_dump() ) self.http_client.check_response_header(response) self.http_client.check_console_response(response) data = response.json() resp = data_class.KnowledgeBaseGetDocumentsListResponse(**data) return resp def create_knowledge_base( self, name: str, description: str, type: str = "public", clusterId: str = None, esUserName: str = None, esPassword: str = None, location: str = None, client_token: str = None, pathPrefix: str = None, ) -> data_class.KnowledgeBaseDetailResponse: r""" 创建知识库 Args: name (str): 知识库名称。 description (str): 知识库描述。 type (str, optional): 知识库类型。默认为"public"。 esUrl (str, optional): Elasticsearch服务器地址。默认为None。 esUserName (str, optional): Elasticsearch用户名。默认为None。 esPassword (str, optional): Elasticsearch密码。默认为None。 client_token (str, optional): 客户端令牌。默认为None,此时会自动生成一个随机UUID作为客户端令牌。 pathPrefix (str, optional): 知识库所属目录绝对路径。默认为None。 Returns: KnowledgeBaseDetailResponse: 创建知识库的响应消息,包含以下属性: - id (str): 知识库ID - name (str): 知识库名称 - description (Optional[str], optional): 知识库描述 - config (Optional[KnowledgeBaseConfig], optional): 知识库配置 """ headers = self.http_client.auth_header_v2() headers["content-type"] = "application/json" if not client_token: client_token = str(uuid.uuid4()) url = self.http_client.service_url_v2( "/knowledgeBase?Action=CreateKnowledgeBase", client_token=client_token ) request = data_class.KnowledgeBaseCreateKnowledgeBaseRequest( name=name, description=description, config={ "index": { "type": type, "clusterId": clusterId, "username": esUserName, "password": esPassword, "location": location, }, }, ) if pathPrefix != None: request.config.catalogue = { "pathPrefix": pathPrefix, } response = self.http_client.session.post( url=url, headers=headers, json=request.model_dump( exclude_none=True) ) self.http_client.check_response_header(response) self.http_client.check_console_response(response) data = response.json() resp = data_class.KnowledgeBaseDetailResponse(**data) self.knowledge_id = resp.id self.knowledge_name = resp.name return resp def get_knowledge_base_detail( self, knowledge_base_id: Optional[str] = None ) -> data_class.KnowledgeBaseDetailResponse: r""" 获取知识库详情 Args: knowledge_base_id (Optional[str], optional): 知识库ID,如果不指定则使用当前实例的knowledge_id属性。默认值为None。 Returns: KnowledgeBaseDetailResponse: 知识库详情,返回一个KnowledgeBaseDetailResponse对象,包含以下属性: - id (str): 知识库ID - name(str): 知识库名称 - description(Optional[str], optional): 知识库描述 - config(Optional[KnowledgeBaseConfig], optional): 知识库配置 """ if self.knowledge_id == None and knowledge_base_id == None: raise ValueError( "knowledge_base_id cannot be empty, please call `create` first or use existing one" ) request = data_class.KnowledgeBaseGetDetailRequest( id=knowledge_base_id or self.knowledge_id ) headers = self.http_client.auth_header_v2() headers["content-type"] = "application/json" url = self.http_client.service_url_v2( "/knowledgeBase?Action=DescribeKnowledgeBase" ) response = self.http_client.session.post( url=url, headers=headers, json=request.model_dump() ) self.http_client.check_response_header(response) self.http_client.check_console_response(response) data = response.json() resp = data_class.KnowledgeBaseDetailResponse(**data) return resp def modify_knowledge_base( self, knowledge_base_id: Optional[str] = None, name: Optional[str] = None, description: Optional[str] = None, client_token: str = None, pathPrefix: str = None, ): r""" 修改知识库信息 Args: knowledge_base_id (Optional[str], optional): 知识库ID,如果不指定则使用当前实例的knowledge_id属性。默认值为None。 name (Optional[str], optional): 新的知识库名称。默认值为None。 description (Optional[str], optional): 新的知识库描述。默认值为None。 client_token (str, optional): 客户端令牌。默认为None,此时会自动生成一个随机UUID作为客户端令牌。 pathPrefix (str, optional): 知识库所属目录绝对路径。默认为None。 Returns: dict: 响应数据,包含请求ID: requestId。 """ if self.knowledge_id == None and knowledge_base_id == None: raise ValueError( "knowledge_base_id cannot be empty, please call `create` first or use existing one" ) request = data_class.KnowledgeBaseModifyRequest( id=knowledge_base_id or self.knowledge_id, name=name, description=description, ) if pathPrefix != None: request.config = { "catalogue": { "pathPrefix": pathPrefix, } } headers = self.http_client.auth_header_v2() headers["content-type"] = "application/json" if not client_token: client_token = str(uuid.uuid4()) url = self.http_client.service_url_v2( "/knowledgeBase?Action=ModifyKnowledgeBase", client_token=client_token ) response = self.http_client.session.post( url=url, headers=headers, json=request.model_dump( exclude_none=True) ) self.http_client.check_response_header(response) self.http_client.check_console_response(response) data = response.json() return data def delete_knowledge_base( self, knowledge_base_id: Optional[str] = None, client_token: str = None ): r""" 删除知识库 Args: knowledge_base_id (Optional[str], optional): 知识库ID,如果不指定则使用当前实例的knowledge_id属性。默认值为None。 client_token (str, optional): 客户端令牌。默认为None,此时会自动生成一个随机UUID作为客户端令牌。 Returns: 响应数据,包含请求ID: requestId """ if self.knowledge_id == None and knowledge_base_id == None: raise ValueError( "knowledge_base_id cannot be empty, please call `create` first or use existing one" ) request = data_class.KnowledgeBaseDeleteRequest( id=knowledge_base_id or self.knowledge_id ) headers = self.http_client.auth_header_v2() headers["content-type"] = "application/json" if not client_token: client_token = str(uuid.uuid4()) url = self.http_client.service_url_v2( "/knowledgeBase?Action=DeleteKnowledgeBase", client_token=client_token ) response = self.http_client.session.post( url=url, headers=headers, json=request.model_dump() ) self.http_client.check_response_header(response) self.http_client.check_console_response(response) data = response.json() return data def create_documents( self, id: Optional[str] = None, contentFormat: str = "", source: data_class.DocumentSource = None, processOption: data_class.DocumentProcessOption = None, client_token: str = None, ) -> data_class.KnowledgeBaseCreateDocumentsResponse: r""" 创建文档 Args: id (Optional[str], optional): 知识库ID,如果不指定则使用当前实例的knowledge_id属性。默认值为None。 contentFormat (str, optional): 文档内容格式,可以是"rawText"。默认值为""。 source (data_class.DocumentSource, optional): 文档源数据。默认值为None。 processOption (data_class.DocumentProcessOption, optional): 文档处理选项。默认值为None。 client_token (str, optional): 客户端令牌。默认为None,此时会自动生成一个随机UUID作为客户端令牌。 Returns: KnowledgeBaseCreateDocumentsResponse: 创建知识库文档的响应消息,返回一个KnowledgeBaseCreateDocumentsResponse对象,包含以下属性: - requestId (str): 请求ID - documentIds (list[str]): 文档ID列表 """ if self.knowledge_id == None and id == None: raise ValueError( "knowledge_base_id cannot be empty, please call `create` first or use existing one" ) headers = self.http_client.auth_header_v2() headers["content-type"] = "application/json" if not client_token: client_token = str(uuid.uuid4()) url = self.http_client.service_url_v2( "/knowledgeBase?Action=CreateDocuments", client_token=client_token ) request = data_class.KnowledgeBaseCreateDocumentsRequest( id=id or self.knowledge_id, source=source, contentFormat=contentFormat, processOption=processOption, ) response = self.http_client.session.post( url=url, headers=headers, json=request.model_dump( exclude_none=True) ) self.http_client.check_response_header(response) self.http_client.check_console_response(response) data = response.json() resp = data_class.KnowledgeBaseCreateDocumentsResponse(**data) return resp def get_knowledge_base_list( self, knowledge_base_id: Optional[str] = None, maxKeys: int = 10, keyword: Optional[str] = None, ) -> data_class.KnowledgeBaseGetListResponse: r""" 获取知识库列表 Args: knowledge_base_id (Optional[str], optional): 知识库ID,如果不指定则使用当前实例的knowledge_id属性。默认值为None。 maxKeys (int, optional): 最大键数。默认值为10。 keyword (Optional[str], optional): 关键字。默认值为None。 Returns: KnowledgeBaseGetListResponse: 获取知识库列表的响应消息,返回一个KnowledgeBaseGetListResponse对象,包含以下属性: - requestId (str): 请求ID - data (list[KnowledgeBaseDetailResponse]): 知识库详情列表 - marker (str): 起始位置 - nextMarker (str): 下一页起始位置 - maxKeys (int): 返回文档数量大小,默认10,最大值100 - isTruncated (bool): 是否有更多结果 """ request = data_class.KnowledgeBaseGetListRequest( marker=knowledge_base_id or self.knowledge_id, maxKeys=maxKeys, keyword=keyword, ) headers = self.http_client.auth_header_v2() headers["content-type"] = "application/json" url = self.http_client.service_url_v2( "/knowledgeBase?Action=DescribeKnowledgeBases" ) response = self.http_client.session.post( url=url, headers=headers, json=request.model_dump( exclude_none=True) ) self.http_client.check_response_header(response) self.http_client.check_console_response(response) data = response.json() resp = data_class.KnowledgeBaseGetListResponse(**data) return resp def upload_documents( self, file_path: str, content_format: str = "rawText", id: Optional[str] = None, processOption: data_class.DocumentProcessOption = None, client_token: str = None, ) -> data_class.KnowledgeBaseUploadDocumentsResponse: r""" 上传文档 Args: file_path (str): 文件路径 content_format (str, optional): 内容格式。默认值为"rawText"。 id (Optional[str], optional): 知识库ID,如果不指定则使用当前实例的knowledge_id属性。默认值为None。 processOption (data_class.DocumentProcessOption, optional): 文档处理选项。默认值为None。 client_token (str, optional): 客户端令牌。默认为None,此时会自动生成一个随机UUID作为客户端令牌。 Returns: KnowledgeBaseUploadDocumentsResponse: 创建知识库文档的响应消息,返回一个KnowledgeBaseUploadDocumentsResponse对象,包含以下属性: - requestId (str): 请求ID - documentId (str): 文档ID """ if not os.path.exists(file_path): raise FileNotFoundError("File {} does not exist".format(file_path)) headers = self.http_client.auth_header_v2() if not client_token: client_token = str(uuid.uuid4()) url = self.http_client.service_url_v2( "/knowledgeBase?Action=UploadDocuments", client_token=client_token ) with open(file_path, "rb") as f: multipart_form_data = {"file": (os.path.basename(file_path), f)} request = data_class.KnowledgeBaseCreateDocumentsRequest( id=id or self.knowledge_id, source=data_class.DocumentSource(type="file"), contentFormat=content_format, processOption=processOption, ) data = { "payload": request.model_dump_json(exclude_none=True), } response = self.http_client.session.post( url=url, headers=headers, data=data, files=multipart_form_data, ) self.http_client.check_response_header(response) self.http_client.check_console_response(response) data = response.json() resp = data_class.KnowledgeBaseUploadDocumentsResponse(**data) return resp def create_chunk( self, documentId: str, content: str, client_token: str = None, knowledgebase_id: Optional[str] = None, ) -> data_class.CreateChunkResponse: r""" 创建文档块 Args: documentId (str): 文档ID content (str): 内容 client_token (str, optional): 客户端令牌。默认为None,此时会自动生成一个随机UUID作为客户端令牌。 Returns: CreateChunkResponse: 创建文档块的相应消息, 包含以下属性: - id (str): 切片ID """ headers = self.http_client.auth_header_v2() headers["content-type"] = "application/json" if not client_token: client_token = str(uuid.uuid4()) url = self.http_client.service_url_v2( "/knowledgeBase?Action=CreateChunk", client_token=client_token ) request = data_class.CreateChunkRequest( knowledgeBaseId=knowledgebase_id or self.knowledge_id, documentId=documentId, content=content, ) response = self.http_client.session.post( url=url, headers=headers, json=request.model_dump( exclude_none=True) ) self.http_client.check_response_header(response) self.http_client.check_console_response(response) data = response.json() resp = data_class.CreateChunkResponse(**data) return resp def modify_chunk( self, chunkId: str, content: str, enable: bool, knowledgebase_id: Optional[str] = None, client_token: str = None, ): r""" 修改文档块 Args: chunkId (str): 文档块ID content (str): 内容 enable (bool): 是否启用 Returns: dict: 响应数据,包含请求ID: requestId """ headers = self.http_client.auth_header_v2() headers["content-type"] = "application/json" if not client_token: client_token = str(uuid.uuid4()) url = self.http_client.service_url_v2( "/knowledgeBase?Action=ModifyChunk", client_token=client_token ) request = data_class.ModifyChunkRequest( knowledgeBaseId=knowledgebase_id or self.knowledge_id, chunkId=chunkId, content=content, enable=enable, ) response = self.http_client.session.post( url=url, headers=headers, json=request.model_dump( exclude_none=True) ) self.http_client.check_response_header(response) self.http_client.check_console_response(response) data = response.json() return data def delete_chunk( self, chunkId: str, knowledgebase_id: Optional[str] = None, client_token: str = None, ): r""" 删除文档块 Args: chunkId (str): 文档块ID client_token (str, optional): 客户端令牌。默认为None,此时会自动生成一个随机UUID作为客户端令牌。 Returns: dict: 响应数据,包含请求ID: requestId """ headers = self.http_client.auth_header_v2() headers["content-type"] = "application/json" if not client_token: client_token = str(uuid.uuid4()) url = self.http_client.service_url_v2( "/knowledgeBase?Action=DeleteChunk", client_token=client_token ) request = data_class.DeleteChunkRequest( knowledgeBaseId=knowledgebase_id or self.knowledge_id, chunkId=chunkId, ) response = self.http_client.session.post( url=url, headers=headers, json=request.model_dump( exclude_none=True) ) self.http_client.check_response_header(response) self.http_client.check_console_response(response) data = response.json() return data def describe_chunk( self, chunkId: str, knowledgebase_id: Optional[str] = None, ) -> data_class.DescribeChunkResponse: r""" 获取文档块详情 Args: chunkId (str): 文档块ID Returns: DescribeChunkResponse: 文档块详情,一个DescribeChunkResponse对象,包含以下属性: - id (str): 切片ID - type (str): 切片类型 - knowledgeBaseId (str): 知识库ID - documentId (str): 文档ID - content (str): 文档内容 - enabled (bool): 是否启用 - wordCount (int): 切片内字符数量 - tokenCount (int): 切片内token数量 - status (str): 切片状态 - statusMessage (str): 切片状态信息 - createTime (int): 创建时间 - updateTime (int): 更新时间 """ headers = self.http_client.auth_header_v2() headers["content-type"] = "application/json" url = self.http_client.service_url_v2("/knowledgeBase?Action=DescribeChunk") request = data_class.DescribeChunkRequest( knowledgeBaseId=knowledgebase_id or self.knowledge_id, chunkId=chunkId, ) response = self.http_client.session.post( url=url, headers=headers, json=request.model_dump( exclude_none=True) ) self.http_client.check_response_header(response) self.http_client.check_console_response(response) data = response.json() resp = data_class.DescribeChunkResponse(**data) return resp def describe_chunks( self, documentId: str, knowledgebase_id: Optional[str] = None, marker: str = None, maxKeys: int = None, type: str = None, keyword: str = None, ) -> data_class.DescribeChunksResponse: r""" 获取文档块列表 Args: documentId (str): 文档ID marker (str, optional): 分页标记,用于指定从哪个位置开始返回结果。默认为None,表示从头开始返回结果。 maxKeys (int, optional): 最大返回数量,用于限制每次请求返回的最大文档块数目。默认为None,表示不限制返回数量。 type (str, optional): 文档块类型。默认为None,表示不限定类型。 keyword (str, optional): 根据关键字模糊匹配切片,最大长度2000字符。 Returns: DescribeChunksResponse: 文档块列表,一个DescribeChunksResponse对象,包含以下属性: - data (list[DescribeChunkResponse]): 切片列表 - marker (str): 起始位置 - isTruncated (bool): true表示后面还有数据,false表示已经是最后一页 - nextMarker (str): 下一页起始位置 - maxKeys (int): 本次查询包含的最大结果集数量 """ headers = self.http_client.auth_header_v2() headers["content-type"] = "application/json" url = self.http_client.service_url_v2( "/knowledgeBase?Action=DescribeChunks") request = data_class.DescribeChunksRequest( knowledgeBaseId=knowledgebase_id or self.knowledge_id, documentId=documentId, marker=marker, maxKeys=maxKeys, type=type, keyword=keyword, ) response = self.http_client.session.post( url=url, headers=headers, json=request.model_dump( exclude_none=True) ) self.http_client.check_response_header(response) self.http_client.check_console_response(response) data = response.json() resp = data_class.DescribeChunksResponse(**data) return resp def get_all_documents(self, knowledge_base_id: Optional[str] = None) -> list: """ 获取知识库中所有文档。 Args: knowledge_base_id (Optional[str], optional): 知识库的ID。如果为None,则使用当前实例的knowledge_id。默认为None。 Returns: list: 包含所有文档的列表。 Raises: ValueError: 如果knowledge_base_id为空,且当前实例没有已创建的knowledge_id时抛出。 """ if self.knowledge_id == None and knowledge_base_id == None: raise ValueError( "knowledge_base_id cannot be empty, please call `create` first or use existing one" ) knowledge_base_id = knowledge_base_id or self.knowledge_id doc_list = [] response_per_time = self.get_documents_list( knowledge_base_id=knowledge_base_id, limit=100 ) list_len_per_time = len(response_per_time.data) if list_len_per_time != 0: doc_list.extend(response_per_time.data) while list_len_per_time == 100: after_id = response_per_time.data[-1].id response_per_time = self.get_documents_list( knowledge_base_id=knowledge_base_id, after=after_id, limit=100 ) list_len_per_time = len(response_per_time.data) if list_len_per_time != 0: doc_list.extend(response_per_time.data) return doc_list def query_knowledge_base( self, query: str, knowledgebase_ids: list[str], type: Optional[data_class.QueryType] = None, metadata_filters: Optional[data_class.MetadataFilters] = None, pipeline_config: Optional[data_class.QueryPipelineConfig] = None, rank_score_threshold: Optional[float] = 0.4, top: int = 6, skip: int = 0, ) -> data_class.QueryKnowledgeBaseResponse: """ 检索知识库 Args: request (data_class.QueryKnowledgeBaseRequest): 检索知识库的请求对象 Returns: data_class.QueryKnowledgeBaseResponse: 检索知识库的响应对象 """ headers = self.http_client.auth_header_v2() headers["content-type"] = "application/json" url = self.http_client.service_url_v2("/knowledgebases/query") request = data_class.QueryKnowledgeBaseRequest( query=query, knowledgebase_ids=knowledgebase_ids, type=type, metadata_filters=metadata_filters, pipeline_config=pipeline_config, rank_score_threshold=rank_score_threshold, top=top, skip=skip, ) response = self.http_client.session.post( url=url, headers=headers, json=request.model_dump( exclude_none=True) ) self.http_client.check_response_header(response) self.http_client.check_console_response(response) data = response.json() resp = data_class.QueryKnowledgeBaseResponse(**data) return resp ================================================ FILE: python/core/console/rag/__init__.py ================================================ # Copyright (c) 2023 Baidu, Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from .rag import RAG ================================================ FILE: python/core/console/rag/rag.py ================================================ import json from appbuilder.core._client import HTTPClient from appbuilder.core.component import Message, Component from appbuilder.core.console.base import ConsoleCompletionResponse class RAG(Component): """ console RAG组件,利用console端RAG应用进行问答 Examples: .. code-block:: python import appbuilder import os os.environ["APPBUILDER_TOKEN"] = '...' conversation_id = '...' app_id = '...' # 线上知识库ID conversation_id = '...' # 会话ID,可选参数,不传默认新建会话 rag_app = appbuilder.console.RAG(app_id) query = "中国的首都在哪里" answer = rag_app.run(appbuilder.Message(query)) # 新建会话 print(answer) conversation_id = answer.conversation_id # 获取会话ID,可用于下次会话 print(conversation_id) query = "它有哪些旅游景点" answer = rag_app.run(appbuilder.Message(query), conversation_id) # 接上次会话 print(answer.content) print(answer.extra) # 获取结果来源 """ name = "rag" integrated_url: str = "/v1/ai_engine/agi_platform/v1/instance/integrated" # debug_url: str = "/debug" def __init__(self, app_id: str = ""): super().__init__() self.app_id = app_id self._http_client = None @property def http_client(self): if self._http_client is None: self._http_client = HTTPClient() return self._http_client def run(self, query: Message, conversation_id: str = "", stream: bool = False) -> Message: """ RAG问答 Args: query: 用户输入的文本 stream: 是否开启流式模式 conversation_id: 会话ID,不传表示新建对话 Returns: Message: rag答案 """ response_mode = "streaming" if stream else "blocking" payload = json.dumps({"query": query.content, "app_id": self.app_id, "response_mode": response_mode, "conversation_id": conversation_id}) headers = self.http_client.auth_header() headers["Content-Type"] = "application/json" response = self.http_client.session.post(url=self.http_client.service_url(self.integrated_url), headers=headers, data=payload, stream=True) response = ConsoleCompletionResponse(response, stream) return response.to_message() def debug(self, query: Message): pass ================================================ FILE: python/core/constants.py ================================================ # Copyright (c) 2023 Baidu, Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. SECRET_KEY_PREFIX = "Bearer" GATEWAY_URL = "https://appbuilder.baidu.com" GATEWAY_INNER_URL = "http://appbuilder.sdns.baidu.com" GATEWAY_URL_V2 = "https://qianfan.baidubce.com" CONSOLE_OPENAPI_VERSION = "/v2" CONSOLE_OPENAPI_PREFIX = "" MAX_DOCUMENTS_NUM = 800 SUPPORTED_FILE_TYPE = ["txt", "pdf", "doc", "docx"] COMPONENT_SUPPORT_FILE_NUMBER = 10 ================================================ FILE: python/core/context.py ================================================ # Copyright (c) 2023 Baidu, Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import uuid import logging from typing import Optional from contextvars import ContextVar _LOCAL_KEY = 'LOCAL-' class SessionContext: """ 维护当前 Session 的上下文信息。 """ id: str session_id: str request_id: str user_id: Optional[str] session_vars_dict: dict def __init__(self, id: str, session_id: str, request_id: str, user_id: Optional[str] = None): self.id = id self.session_id = session_id self.request_id = request_id self.user_id = user_id self.session_vars_dict = {} context_var: ContextVar[SessionContext] = ContextVar("appbuilder_session") def init_context( session_id: str, request_id: str, user_id: Optional[str] = None, ) -> SessionContext: """ 初始化 Session 的上下文信息。 """ ctx = SessionContext( id=str(uuid.uuid4()), session_id=session_id, request_id=request_id, user_id=user_id, ) context_var.set(ctx) return ctx def get_context() -> SessionContext: """ 获取当前 Session 的上下文信息。 """ try: return context_var.get() except LookupError: session_id = _LOCAL_KEY + str(uuid.uuid4())[:-len(_LOCAL_KEY)] request_id = _LOCAL_KEY + str(uuid.uuid4())[:-len(_LOCAL_KEY)] logging.debug( "Unable to find the AgentRuntime context. You need to use UserSession " "in AgentRuntime.serve or AgentRuntime.chainlit_demo. " f"Generate session_id({session_id}) and request_id({request_id}) here for local debugging.") ctx = init_context(session_id=session_id, request_id=request_id) return ctx ================================================ FILE: python/core/functional.py ================================================ # Copyright (c) 2023 Baidu, Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. ================================================ FILE: python/core/manifest/__init__.py ================================================ # Copyright (c) 2024 Baidu, Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. ================================================ FILE: python/core/manifest/manifest_decorator.py ================================================ # Copyright (c) 2024 Baidu, Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import inspect from typing import Any, Dict, Optional from pydantic.v1 import BaseModel as PydanticBaseModel # noqa: F403 # type: ignore from pydantic.v1 import create_model from appbuilder.core.manifest.manifest_signature import get_signature from appbuilder.core.manifest.models import Manifest, PropertyModel, ParametersModel def manifest( *, description: Optional[str] = None, name: Optional[str] = None, ): """ Decorator for functions. Use some information to extract meta about function. Priority as follows: 1. User provided value via arguments 2. Function signature + annotations Args: description (str, optional): The functionality of the function, general user guideline. name (str, optional): The name of the function. """ def decorator(func): """Decorator for function.""" # Get meta from signature sig_params, sig_returns = get_signature(func=func) # Get meta from decorator dec_params_list = ( func.__ab_manifest_parameters__ if hasattr(func, "__ab_manifest_parameters__") else [] ) dec_params = {item.name: item for item in dec_params_list} properties = {} required_fields = [] for param in sig_params: dec_param = dec_params.get(param["name"]) param_type = param.get("type_") or getattr(dec_param, "type", None) param_info = { "name": param["name"], # 参数名称 "type": param_type, "description": getattr( dec_params.get(param["name"]), "description", None ), # 描述 "required": param.get( "required", getattr(dec_params.get(param["name"]), "required", True) ), # 是否必需 } # 构造 PropertyModel properties[param["name"]] = PropertyModel( name=param_info["name"], type=param_info["type"], description=param_info["description"], required=param_info["required"], ) # 记录必需参数 if param_info["required"]: required_fields.append(param["name"]) # 确定函数的最终名称和描述 final_name = name or func.__name__ final_desc = description or func.__doc__ parameters_model = ParametersModel( type="object", properties={ k: v.model_dump(exclude_none=False) for k, v in properties.items() }, required=required_fields, ) view = Manifest( type="function", function={ "name": final_name, "description": final_desc, "parameters": parameters_model.model_dump(), }, ) # Attach view to function. func.__ab_manifest__ = view # Compatible to semantic kernel 0.9 ~ 1.6 according to this url: https://github.com/microsoft/semantic-kernel/blob/main/python/semantic_kernel/functions/kernel_function_decorator.py func.__kernel_function__ = True func.__kernel_function_description__ = final_desc func.__kernel_function_name__ = final_name return func return decorator def manifest_parameter( *, name: str, description: str = None, type: str = None, required: bool = True, ): """ Decorator for function parameters. Args: name -- The name of the parameter description -- The description of the parameter default_value -- The default value of the parameter type -- The type of the parameter, used for function calling required -- Whether the parameter is required example -- The example of the parameter """ def decorator(func): """Decorator for function parameter.""" new_view = PropertyModel( name=name, type=type, description=description, required=required, ) # Update parameter view lists for function_parameter decorator. # This will be merged into ManifestView if function decorator runs last like: # @manifest # @manifest_parameter # @manifest_parameter if hasattr(func, "__ab_manifest_parameters__"): current_views = func.__ab_manifest_parameters__ else: current_views = [] current_views.append(new_view) func.__ab_manifest_parameters__ = current_views if hasattr(func, "__ab_manifest__"): # 获取现有的 parameters parameters_dict = func.__ab_manifest__.function.get("parameters", {}) parameters_model = ParametersModel(**parameters_dict) # 更新 properties existing_property = parameters_model.properties.get(new_view.name) if existing_property: merged_property = PropertyModel.merge(existing_property, new_view) parameters_model.properties[new_view.name] = merged_property else: parameters_model.properties[new_view.name] = new_view # 更新 required 字段 if new_view.required: if new_view.name not in parameters_model.required: parameters_model.required.append(new_view.name) else: if new_view.name in parameters_model.required: parameters_model.required.remove(new_view.name) # 更新 func.__ab_manifest__.function["parameters"] func.__ab_manifest__.function["parameters"] = parameters_model.model_dump() # Compatible to semantic kernel 0.9 ~ 1.6 according to this url: https://github.com/microsoft/semantic-kernel/blob/main/python/semantic_kernel/functions/kernel_function_decorator.py if hasattr(func, "__kernel_function_parameters__"): item = { "name": name, "description": description, "type": type, "required": required, } new_list = _update_list( item, func.__kernel_function_parameters__, lambda item, new_item: item["name"] == new_item["name"], lambda item, new_item: _merge_dict(item, new_item), ) func.__kernel_function_parameters__ = new_list return func return decorator def _merge_dict(current_dict, new_dict): result = current_dict.copy() for k, v in new_dict.items(): if v: result[k] = v return result # Replace the parameter with the same name and keep order. # Since there are few parameters for each function, keep use list for simplicity def _update_list(new_item, list, condition, replacer): new_list = [] replaced = False for item in list: if condition(item, new_item): replaced = True merged_item = replacer(item, new_item) new_list.append(merged_item) # Missing parameter append to the end. if not replaced: new_list.append(new_item) return new_list ================================================ FILE: python/core/manifest/manifest_signature.py ================================================ # Copyright (c) 2024 Baidu, Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import inspect from inspect import Parameter, Signature from typing import Any, Dict, Union, Optional, List, get_origin, get_args import logging NoneType = type(None) # 映射内置泛型类型到 typing 模块的名称 TYPE_MAPPING = { dict: "Dict", list: "List", set: "Set", tuple: "Tuple", Union: "Union", Optional: "Optional", Any: "Any", int: "int", str: "str", float: "float", bool: "bool", # 根据需要添加更多映射 } def get_signature(func): """ 获取函数的签名视图。 Args: func (function): 目标函数。 Returns: tuple: 包含两个元素的元组,第一个元素为函数参数的解析结果列表,第二个元素为函数返回值的解析结果字典。 """ signature = inspect.signature(func) _parameters = [ _parse_parameter(param) for param in signature.parameters.values() if param.name != "self" ] signature_returns = ( _parse_annotation(signature.return_annotation) if signature.return_annotation != Signature.empty else {} ) return _parameters, signature_returns def _parse_parameter(param: Parameter) -> Dict[str, Any]: ret = {} if param != Parameter.empty: ret = _parse_annotation(param.annotation) ret["name"] = param.name if param.default != Parameter.empty: ret["default_value"] = param.default ret["required"] = False return ret def _parse_annotation(annotation: Parameter) -> Dict[str, Any]: # The keys of this dict is compatible with semantic-kernel, do not change them if annotation == Signature.empty: return {"type_": "Any", "required": True} if isinstance(annotation, str): return {"type_": annotation, "required": True} ret = _parse_internal_annotation(annotation, True) if hasattr(annotation, "__metadata__") and annotation.__metadata__: ret["description"] = annotation.__metadata__[0] return ret def _parse_internal_annotation(annotation: Any, required: bool) -> Dict[str, Any]: if hasattr(annotation, "__forward_arg__"): return {"type_": annotation.__forward_arg__, "required": required} # 获取 origin 和 args origin = get_origin(annotation) args = get_args(annotation) # 确定 parent_type if origin is not None: parent_type = TYPE_MAPPING.get( origin, origin.__name__ if hasattr(origin, "__name__") else str(origin) ) else: parent_type = TYPE_MAPPING.get( annotation, annotation.__name__ if hasattr(annotation, "__name__") else str(annotation), ) if parent_type == "Optional": required = False if args: results = [_parse_internal_annotation(arg, required) for arg in args] type_objects = [ result["type_object"] for result in results if "type_object" in result and result["type_object"] is not NoneType ] str_results = [result["type_"] for result in results] if "NoneType" in str_results: str_results.remove("NoneType") required = False if parent_type == "Union": if len(str_results) == 1: type_ = f"Optional[{str_results[0]}]" else: type_ = f"Union[{', '.join(str_results)}]" else: type_ = f"{parent_type}[{', '.join(str_results)}]" else: if parent_type == "Union": # 所有选项都为非必需 required = not (all(not result["required"] for result in results)) type_ = f"{parent_type}[{', '.join(str_results)}]" ret = {"type_": type_, "required": required} if type_objects and len(type_objects) == 1: ret["type_object"] = type_objects[0] logging.debug( f"Parsed annotation: {annotation}, type_: {type_}, required: {required}" ) return ret type_ = TYPE_MAPPING.get( annotation, annotation.__name__ if hasattr(annotation, "__name__") else str(annotation), ) logging.debug( f"Parsed annotation: {annotation}, type_: {type_}, required: {required}" ) return { "type_": type_, "type_object": annotation, "required": required, } ================================================ FILE: python/core/manifest/models.py ================================================ # Copyright (c) 2023 Baidu, Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from pydantic import BaseModel, Field from typing import Dict, List, Literal, Any, Optional from appbuilder.core.manifest.manifest_signature import get_signature class PropertyModel(BaseModel): """参数属性模型,用于描述函数参数的类型和元数据。 Attributes: type (Optional[str]): 参数的类型。 description (Optional[str]): 参数的描述信息。 """ name: str type: Optional[str] description: Optional[str] required: bool = True @classmethod def merge(cls, a: "PropertyModel", b: "PropertyModel") -> "PropertyModel": """Merge two parameter views.""" return cls( name=a.name, description=(b.description or a.description), type=(b.type or a.type), required=(b.required if b.required is not None else a.required), ) class ParametersModel(BaseModel): """函数参数模型,用于定义函数的参数结构。 Attributes: type (Literal["object"]): 表示参数集合的类型,固定为 "object"。 properties (Dict[str, PropertyModel]): 参数的具体属性映射,其中键是参数名,值是对应的属性模型。 required (List[str]): 必须提供的参数列表。 """ type: Literal["object"] properties: Dict[str, PropertyModel] required: List[str] class Manifest(BaseModel): """函数模型,用于描述函数的元信息。 Attributes: type (Literal["function"]): 表示模型的类型,固定为 "function"。 function (Dict[str, Any]): 函数的详细信息,包括名称、描述、参数、返回值等。 """ type: Literal["function"] function: Dict[str, Any] @classmethod def from_function(cls, func) -> "Manifest": """ 利用 manifest_signature.py 提供的 get_signature 方法解析函数的签名和参数信息, 并生成一个 Manifest 实例。 Args: func: 要转换的函数。 Returns: Manifest: 包含函数元信息的模型。 """ # 使用 manifest_signature 提取函数签名信息 sig_params, sig_returns = get_signature(func) # 构造参数模型 properties = {} required = [] if hasattr(func, "__ab_manifest__"): return func.__ab_manifest__ for param in sig_params: param_info = { "name": param["name"], # 参数名称 "type": param.get("type_", None), # 类型 "description": param.get("description", None), # 描述 "required": param.get("required", False), # 是否必需 } # 验证类型字段是否有有效值 if not param_info["type"]: param_info["type"] = "Any" # 构造 PropertyModel properties[param["name"]] = PropertyModel( name=param_info["name"], type=param_info["type"], description=param_info["description"], required=param_info["required"], ) # 记录必需参数 if param_info["required"]: required.append(param["name"]) # 构造 ParametersModel parameters_model = ParametersModel( type="object", properties=properties, required=required, ) # 构造 Manifest 对象 manifest = cls( type="function", function={ "name": func.__name__, "description": func.__doc__, # 去掉多余的空格 "parameters": parameters_model.model_dump(), }, ) return manifest ================================================ FILE: python/core/message.py ================================================ # Copyright (c) 2023 Baidu, Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import uuid from pydantic import BaseModel from typing import Optional, TypeVar, Generic _T = TypeVar("_T") class Message(BaseModel, Generic[_T], extra='allow'): """ Message class Attributes: content: The message content name: The message name mtype: The message type id: The message id """ content: Optional[_T] = {} name: Optional[str] = "msg" mtype: Optional[str] = "dict" id: Optional[str] = str(uuid.uuid4()) def __init__(self, content: Optional[_T] = None, **data): if content is not None: data['content'] = content super().__init__(**data) self.mtype = type(self.content).__name__ def __str__(self): return f"Message(name={self.name}, content={self.content}, mtype={self.mtype})" def __repr__(self): return f"{self.__class__.__name__}(name={self.name!r}, content={self.content!r}, mtype={self.mtype!r})" ================================================ FILE: python/core/session_message.py ================================================ # Copyright (c) 2023 Baidu, Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import datetime import uuid db = None def get_db_base_class(): try: from sqlalchemy.orm import declarative_base except ImportError as e: raise ImportError("Please install SQLAlchemy first: python3 -m pip install SQLAlchemy==2.0.31") global db if not db: db = declarative_base() return db class SessionMessage(get_db_base_class()): """ 会话 Message 数据模型,用于在数据库中存储和管理会话消息。 以下是每个字段的注释: __tablename__:数据库表名为 appbuilder_session_messages,这是该类对应的数据库表名。 id:主键字段,使用UUID作为默认值,确保每条记录的唯一性。 session_id:会话ID字段,不允许为空,用于标识会话。 request_id:请求ID字段,不允许为空,用于标识请求。 message_key:Message 键字段,不允许为空,用于标识 Message 的关键字。 message_value:Message 值字段,不允许为空,用于存储 Message 的具体内容,使用JSON格式存储。 created_at:创建时间字段,使用当前时间作为默认值,不允许为空。 updated_at:更新时间字段,使用当前时间作为默认值,不允许为空。 deleted:删除标记字段,使用False作为默认值,不允许为空。当该字段为True时,表示该条记录已被删除。 """ from sqlalchemy import create_engine, Column, Integer, String, JSON, DateTime, Boolean __tablename__ = 'appbuilder_session_messages' id = Column(String(36), primary_key=True, default=lambda: str(uuid.uuid4()), unique=True) session_id = Column(String(36), nullable=False) request_id = Column(String(36), nullable=False) message_key = Column(String(128), nullable=False) message_value = Column(JSON, nullable=False) created_at = Column(DateTime, default=datetime.datetime.now, nullable=False) updated_at = Column(DateTime, default=datetime.datetime.now, nullable=False) deleted = Column(Boolean, default=False, nullable=False) ================================================ FILE: python/core/user_session.py ================================================ # Copyright (c) 2023 Baidu, Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import datetime import uuid import json import os import logging from typing import Union, List, Dict, Optional, Any from appbuilder.core.message import Message from appbuilder.core.context import get_context, _LOCAL_KEY def lazy_import_sqlalchemy(): try: import sqlalchemy from sqlalchemy import create_engine, Column, Integer, String, JSON, DateTime, Boolean from sqlalchemy.orm import declarative_base, sessionmaker except ImportError as e: raise ImportError("Please install SQLAlchemy first: python3 -m pip install SQLAlchemy==2.0.31") class UserSession(object): """ 会话数据管理工具,实例化后将是一个全局变量。 提供保存对话数据与获取历史数据的方法,**必须**在 AgentRuntime 启动的服务中使用。 """ _instance = None _initialized = False def __new__(cls, *args, **kwargs): """ 单例模式 """ lazy_import_sqlalchemy() if cls._instance is None: cls._instance = object.__new__(cls) return cls._instance def __init__(self, user_session_config: Optional[Union[Any, str]] = None): """ 初始化 UserSession Args: user_session_config (str|None): Session 配置字符串,遵循 sqlalchemy 后端定义,参考文档 https://docs.sqlalchemy.org/en/20/core/engines.html#backend-specific-urls Returns: None """ if self._initialized: return self._initialized = True import sqlalchemy from sqlalchemy.orm import sessionmaker from sqlalchemy.orm import declarative_base from sqlalchemy import create_engine from appbuilder.core. session_message import get_db_base_class _db = get_db_base_class() if user_session_config is None: user_session_config = "sqlite:///user_session.db" if not isinstance(user_session_config, (sqlalchemy.engine.URL, str)): raise ValueError("user_session_config must be sqlalchemy.URL or str") logging.info(f"create user_session by {user_session_config}") engine = create_engine(user_session_config) _db.metadata.create_all(engine) # 创建表 Session = sessionmaker(engine) self._db_session = Session() def get_history(self, key: str, limit: int=10) -> List[Message]: """ 获取同个 session 中名为 key 的历史变量。 在非服务化版本中从内存获取。在服务化版本中,将从数据库获取。 Args: key (str): 变量名 limit (int): 最近 limit 条 Message 数据 Returns: List[Message] """ from appbuilder.core.session_message import SessionMessage ctx = get_context() if ctx.session_id.startswith(_LOCAL_KEY): # 非服务化版本使用内存存储 if key not in ctx.session_vars_dict: return [] session_messages = ctx.session_vars_dict[key][-limit:] return session_messages else: # 服务化版本使用数据库存储 session_messages = self._db_session.query(SessionMessage).filter( SessionMessage.session_id == ctx.session_id, SessionMessage.message_key == key, SessionMessage.deleted == False).order_by( SessionMessage.updated_at.desc()).limit(limit).all() return [Message(content=item.message_value) for item in session_messages][::-1] def append(self, message_dict: Dict[str, Message]) -> None: """ 将 message_dict 中的变量保存到 session 中。 在非服务化版本中使用内存存储。在服务化版本中,将使用数据库进行存储。 Args: message_dict (Dict[str, Message]): 包含 Message 的字典,其中键为字符串类型,值为 Message 类型。 Returns: None """ ctx = get_context() if ctx.session_id.startswith(_LOCAL_KEY): # 非服务化版本使用内存存储 for key, message in message_dict.items(): if not isinstance(message, Message): raise ValueError("session format error, message must be Message type") if key not in ctx.session_vars_dict: ctx.session_vars_dict[key] = [] ctx.session_vars_dict[key].append(message) else: # 服务化版本使用数据库存储 for key, message in message_dict.items(): if not isinstance(message, Message): raise ValueError("session format error, message must be Message type") if key in ctx.session_vars_dict: raise KeyError( f"session format error, key {key} has already been appended" ) ctx.session_vars_dict[key] = message def _post_append(self) -> None: """ 后置保存。流式数据不能直接保存到数据库,需要通过该方法后置保存。 Args: None Returns: None """ from appbuilder.core.session_message import SessionMessage ctx = get_context() try: for key, message_value in ctx.session_vars_dict.items(): message = SessionMessage( session_id=ctx.session_id, request_id=ctx.request_id, message_key=key, message_value=json.loads(message_value.json(exclude_none=True)), created_at=datetime.datetime.now(), updated_at=datetime.datetime.now()) self._db_session.add(message) self._db_session.commit() ctx.session_vars_dict = {} except Exception as e: logging.error(e) self._db_session.rollback() raise e ================================================ FILE: python/core/utils.py ================================================ # Copyright (c) 2023 Baidu, Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import time import itertools from typing import List from urllib.parse import urlparse, unquote from appbuilder.core._client import HTTPClient from appbuilder.core._exception import TypeNotSupportedException, ModelNotSupportedException from appbuilder.utils.model_util import GetModelListRequestV2, Models, RemoteModelCollector from functools import lru_cache def utils_get_user_agent(): return 'appbuilder-sdk-python/{}'.format("__version__") # Todo(chengmo): 此处返回的模型名称为原始名称,并非推荐使用的short name # 应当返回一个详细的列表,告知用户原始名 + 对应的short名 # 同时考虑是否返回每个模型可用的余额 def get_model_list( secret_key: str = "", api_type_filter: List[str] = [], is_available: bool = False, refresh_type: str = "tolerant", force_refresh: bool = False ) -> list: """ 返回用户的模型列表。 参数: secret_key(str,可选): 用户鉴权token, 默认从环境变量中获取: os.getenv("APPBUILDER_TOKEN", "")。 api_type_filter(List[str], 可选): 根据apiType过滤,["chat", "completions", "embeddings", "text2image"],不填包括所有的。 is_available(bool, 可选): 是否返回可用模型列表, 默认返回所有模型。 refresh_type(str, 可选): 获取模型列表的方式,默认在出错时使用兜底策略。 force_refresh(bool, 可选): 是否强制刷新缓存,默认不强制刷新。 返回: list: 模型列表。 """ api_type_set = {"chat", "completions", "embeddings", "text2image", "image2text", "rerankers", "multimodal"} if api_type_filter and not set(api_type_filter).issubset(api_type_set): raise TypeNotSupportedException( f"mismatched argument api_type_filter, expected in {api_type_set}" ) request = GetModelListRequestV2(refresh_type=refresh_type, force_refresh=force_refresh) model = Models(secret_key=secret_key) response = model.list_v2(request) models = [] for model in itertools.chain(response.result.common, response.result.custom): if ( (is_available and model.chargeStatus not in ["Opened", "Free"]) or model.serviceType not in api_type_filter ): continue models.append(model.name) return models def get_filename_from_url(url): """从给定URL中提取文件名""" parsed_url = urlparse(url) # 提取路径部分 path = parsed_url.path # 从路径中获取文件名 filename = path.split('/')[-1] # 解码URL编码的文件名 return unquote(filename) def convert_cloudhub_url(client: HTTPClient, qianfan_url: str) -> str: """将千帆url转换为AppBuilder url""" qianfan_url_prefix = "rpc/2.0/ai_custom/v1/wenxinworkshop" cloudhub_url_prefix = "rpc/2.0/cloud_hub/v1/bce/wenxinworkshop/ai_custom/v1" index = str.find(qianfan_url, qianfan_url_prefix) if index == -1: raise ValueError(f"url format error, {qianfan_url} is not a valid qianfan url") url_suffix = qianfan_url[index + len(qianfan_url_prefix):] return "{}/{}{}".format(client.gateway, cloudhub_url_prefix, url_suffix) def convert_cloudhub_url_v2(client: HTTPClient, qianfan_url: str) -> str: """将千帆url转换为AppBuilder url""" qianfan_url_prefix = "rpc/2.0/ai_custom/v1/wenxinworkshop" cloudhub_url_prefix = "rpc/2.0/cloud_hub/v1/bce/wenxinworkshop/ai_custom/v1" index = str.find(qianfan_url, qianfan_url_prefix) if index == -1: raise ValueError(f"url format error, {qianfan_url} is not a valid qianfan url") url_suffix = qianfan_url[index + len(qianfan_url_prefix):] return "{}/{}{}".format(client.gateway, cloudhub_url_prefix, url_suffix) def is_url(string): """ 判断字符串是否是URL :param string: :return: """ result = urlparse(string) return all([result.scheme, result.netloc]) def ttl_lru_cache(seconds_to_live: int, maxsize: int = 128): """ Time aware lru caching """ def wrapper(func): @lru_cache(maxsize) def inner(__ttl, *args, **kwargs): # Note that __ttl is not passed down to func, # as it's only used to trigger cache miss after some time return func(*args, **kwargs) return lambda *args, **kwargs: inner(time.time() // seconds_to_live, *args, **kwargs) return wrapper class ModelInfo: """ 模型信息类 """ def __init__(self, client: HTTPClient): """根据模型名称获取并初始化模型信息""" self.client = client response = Models(client).list() self.model_list = [*response.result.common, *response.result.custom] def get_model_url(self, model_name: str) -> str: """获取模型在工作台网关的请求url""" short_name = model_name remote_model_name_collector = RemoteModelCollector() origin_name = remote_model_name_collector.get_remote_name_by_short_name(short_name) if not origin_name: origin_name = short_name for model in self.model_list: if model.name == origin_name: return model.url # return convert_cloudhub_url(self.client, model.url) raise ModelNotSupportedException(f"Model[{model_name}] not available! " f"You can query available models through: appbuilder.get_model_list()") def get_model_type(self, model_name: str) -> str: """获取模型类型""" short_name = model_name remote_model_name_collector = RemoteModelCollector() origin_name = remote_model_name_collector.get_remote_name_by_short_name(short_name) if not origin_name: origin_name = short_name for model in self.model_list: if model.name == origin_name: return model.apiType raise ModelNotSupportedException(f"Model[{model_name}] not available! " f"You can query available models through: appbuilder.get_model_list()") ================================================ FILE: python/mcp_server/README.md ================================================ # MCP Component Server The MCP Component Server is a FastMCP server based implementation that converts AppBuilder Components into FastMCP tools, enabling seamless integration of Baidu cloud AI services into MCP-compatible environments. ## Overview The `MCPComponentServer` class provides a bridge between AppBuilder Components and FastMCP tools, allowing you to: - Convert AppBuilder Components into MCP-compatible tools - Handle various content types (text, images, audio, references) - Manage visibility scopes for different audiences - Support streaming responses through generators ## Features - Automatic conversion of AppBuilder Components to MCP tools - Support for multiple content types: - Text content - Image content - Audio content - Reference content - Configurable host and port settings - Built-in error handling and logging - Support for custom tool registration - Automatic MIME type detection for media content ## Usage ### Basic Setup ```python from appbuilder import GeneralOCR, TextGeneration from mcp.server import MCPComponentServer # Create server instance server = MCPComponentServer("AI Service", host="localhost", port=8000) # Add AppBuilder components ocr = GeneralOCR() server.add_component(ocr) text_gen = TextGeneration() server.add_component(text_gen) # Run the server server.run() ``` ### Adding Custom Tools ```python @server.tool() def custom_function(param1: str, param2: int) -> str: """Custom tool description""" return f"Processed: {param1} {param2}" ``` ### Adding Resources ```python @server.resource() def get_resource(): """Resource description""" return {"data": "resource content"} ``` ## Content Type Handling The server automatically handles various content types: 1. **Text Content**: Converts text outputs to MCP TextContent 2. **Image Content**: Handles both base64 and URL-based images 3. **Audio Content**: Processes audio files with automatic MIME type detection 4. **Reference Content**: Manages document references and citations ## Configuration The server can be configured with various parameters: ```python server = MCPComponentServer( name="Service Name", host="localhost", # Default: "localhost" port=8000, # Default: 8000 **kwargs # Additional FastMCP arguments ) ``` ================================================ FILE: python/mcp_server/__init__.py ================================================ # Copyright (c) 2024 Baidu, Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from .server import MCPComponentServer from .client import MCPClient from .openapi import OpenAPIMCPConverter from .ai_search.ai_search_server import AIsearch from .knowledge_base.knowledge_base_server import ( create_knowledge_base, query_knowledge_base, describe_knowledge_base, list_knowledge_bases, upload_document, list_documents, ) from .app.app_server import ( list_apps, create_conversation, run ) __all__ = [ "MCPComponentServer", "MCPClient", "OpenAPIMCPConverter" "AIsearch", "create_knowledge_base", "query_knowledge_base", "describe_knowledge_base", "list_knowledge_bases", "upload_document", "list_documents", "list_apps", "create_conversation", "run", ] ================================================ FILE: python/mcp_server/ai_search/README.md ================================================ # Baidu AI Search Baidu AI Search component combines Baidu's search capabilities with large language model technology to provide intelligent responses with real-time web information references, supporting various industry application scenarios. It offers rich standardized capabilities such as: - Custom persona settings - Model selection - Query rewriting (including time-sensitive and multi-turn approaches to enhance search results) - Search scope configuration (choice of modalities, site ranges and publication dates) - Customizable number of reference links ## Quick Start 1. Get your AppBuilder API Key from the console 2. Format your authorization token as: `Bearer+` (keep the "+" in between) 3. Config with ```json { "mcpServers": { "baidu_ai_search": { "url": "http://appbuilder.baidu.com/v2/ai_search/mcp/sse?api_key=Bearer+bce-v3/ALTAK..." } } } ``` For more details, please refer to [百度AI搜索](https://cloud.baidu.com/doc/AppBuilder/s/zm8pn5cju) ================================================ FILE: python/mcp_server/ai_search/__init__.py ================================================ """ MCP Server for AI Search. This module provides an integrated AI search solution that combines Baidu Search capabilities with Large Language Models (LLMs). It enables Retrieval-Augmented Generation (RAG) workflows by retrieving relevant information from Baidu Search and using LLMs to generate contextually appropriate responses. """ from .ai_search_server import AIsearch, server __all__ = ["AIsearch", "server"] ================================================ FILE: python/mcp_server/ai_search/ai_search_server.py ================================================ """ Baidu AI Search MCP Server stdio server file. We also support access via SSE protocol. The access address is: http://appbuilder.baidu.com/v2/ai_search/mcp/sse?api_key= You can refer to this webpage https://cloud.baidu.com/doc/AppBuilder/s/klv2eywua to obtain the api_key, in the format of "Bearer+bce…". """ import os import json from mcp.server import FastMCP from appbuilder.core.components.rag_with_baidu_search_pro import RagWithBaiduSearchPro from types import SimpleNamespace # You can refer to this webpage https://cloud.baidu.com/doc/AppBuilder/s/klv2eywua to obtain the api_key # format is "bce-v3/ALTAK-..." # os.environ["APPBUILDER_TOKEN"] = "bce-v3/ALTAK-..." server = FastMCP(name="AB Component Server") # You can switch to other models supported by AppBuilder init_args = { "model": "DeepSeek-V3.1", } @server.tool() def AIsearch( query, stream=False, instruction=None, temperature=1e-10, top_p=1e-10, search_top_k=4, hide_corner_markers=True, ): """ 执行搜索。 Args: query (str): 搜索请求。 stream (bool, optional): 是否以流的形式接收响应数据。默认为False。 instruction (Instruction, optional): 指令信息对象。默认为None。 temperature (float, optional): 温度参数,控制生成文本的随机性。默认为1e-10。 top_p (float, optional): 累积概率阈值,用于控制生成文本的多样性。默认为1e-10。 search_top_k (int, optional): 搜索候选结果的数量。默认为4。 hide_corner_markers (bool, optional): 是否隐藏响应中的边界标记。默认为True。 Returns: Message: 处理后的信息对象。 Raises: AppBuilderServerException: 如果输入信息或指令过长,将抛出此异常。 """ os.environ["APPBUILDER_SDK_MCP_CONTEXT"] = "server" message = SimpleNamespace(role="user", content="{}".format(query)) search_instance = RagWithBaiduSearchPro( model=init_args["model"] ) response = search_instance.run( message=message, stream=stream, instruction=instruction, model=init_args["model"], temperature=temperature, top_p=top_p, search_top_k=search_top_k, hide_corner_markers=hide_corner_markers, ) return response.content + "\n\n" + json.dumps(response.extra, ensure_ascii=False) if __name__ == "__main__": server.run() ================================================ FILE: python/mcp_server/app/README.md ================================================ # App MCP Server App MCP Server provides a set of tools for using Agent from AppBuilder through the MCP protocol. It allows you to list apps, create conversations, run with AppBuilder Agent. ## Features * **List Apps**: Get your AppBuilder application list. * **Create Conversation**: Create a new conversation_id, which is valid for 7 days. After that, it may not work and needs to be regenerated. * **Run**: Send messages to the agent application during a conversation. ## Quick Start 1. Get your AppBuilder API Key from the console 2. Format your authorization token as: `Bearer+` (keep the "+" in between) 3. Config with ```json { "mcpServers": { "appbuilder-app": { "url": "http://appbuilder.baidu.com/v2/app/mcp/sse?api_key=Bearer+bce-v3/ALTAK..." } } } ``` ## Available Tools ### get_all_apps Retrieve a list of all available AppBuilder applications. **Parameters:** No parameter required **Returns:** - List of dictionaries, each containing an app's id, name, and description. ### create_conversation Create a new conversation session for a specific AppBuilder application. **Parameters:** - `app_id` (str): ID of the Application. **Returns:** - `converstaion_id`(str) : ID of the conversation. ### run Execute a conversation query with a specific AppBuilder application. **Parameters:** - `app_id` (str): The unique identifier of the target application - `conversation_id `(str): The conversation session identifier - `query `(str): The input text/query to send to the application **Returns:** - The response content from the conversation ## Usage Examples ### Get your AppBuilder application list ```python import asyncio import os import json from appbuilder.mcp_server.client import MCPClient os.environ["APPBUILDER_TOKEN"] = "YOUR_APPBUILDER_TOKEN" async def main(): client = MCPClient() await client.connect_to_server(service_url=service_url) print(client.tools) result = await client.call_tool( "get_all_apps", {} ) print(result) if __name__ == "__main__": service_url = "http://appbuilder.baidu.com/v2/app/mcp/sse?api_key=Bearer+" + os.environ.get("APPBUILDER_TOKEN") loop = asyncio.get_event_loop() loop.run_until_complete(main()) ``` ### Chat with AppBuilder Application ```python import asyncio import json import os from appbuilder.mcp_server.client import MCPClient os.environ["APPBUILDER_TOKEN"] = "YOUR_APPBUILDER_TOKEN" os.environ["APP_ID"] = "YOUR_APP_ID" async def main(): client = MCPClient() await client.connect_to_server(service_url=service_url) app_id = os.environ.get("APP_ID") result = await client.call_tool( "create_conversation", {"app_id": app_id} ) conversation_id = result.content[0].text print(conversation_id) result = await client.call_tool( "run", { "app_id": app_id, "conversation_id": conversation_id, "query": "hello", }, ) print(result.content[0].text) if __name__ == "__main__": service_url = "http://appbuilder.baidu.com/v2/app/mcp/sse?api_key=Bearer+" + os.environ.get("APPBUILDER_TOKEN") loop = asyncio.get_event_loop() loop.run_until_complete(main()) ``` ================================================ FILE: python/mcp_server/app/__init__.py ================================================ """ MCP Server for AppBuilder App. This module provides functionality for App operations. """ from .app_server import server __all__ = ["server"] ================================================ FILE: python/mcp_server/app/app_server.py ================================================ """ Baidu AppBuilder MCP Server This server provides MCP (Model Context Protocol) tools for interacting with Baidu AppBuilder applications. It supports both stdio and SSE (Server-Sent Events) protocols. SSE Access: URL: http://appbuilder.baidu.com/v2/ai_search/mcp/sse?api_key= Authentication: - Requires an AppBuilder API key in the format "bce-v3/ALTAK-..." - Get your API key from: https://cloud.baidu.com/doc/AppBuilder/s/klv2eywua Features: - List all available AppBuilder applications - Create new conversations with specific apps - Run with queries and get responses Example Usage: 1. Set your AppBuilder token: os.environ["APPBUILDER_TOKEN"] = "bce-v3/ALTAK-..." 2. Run the server: python app_server.py 3. Use MCP client to interact with the server tools: - get_all_apps() - create_conversation(app_id) - run(app_id, conversation_id, query) """ import os from typing import Optional, List, Dict from mcp.server import FastMCP import appbuilder from appbuilder.core.component import Component server = FastMCP(name="AppBuilder App MCP Server") @server.tool() def list_apps() -> List[Dict]: """ Retrieve a list of all available AppBuilder applications. Returns: List[Dict]: A list of dictionaries containing app details with the following keys: - id (str): Unique identifier of the app - name (str): Name of the app - description (str): Description of the app - appType (str): Type of the app - isPublished (bool): Publication status of the app - updateTime (str): Last update timestamp """ apps = appbuilder.get_all_apps() return [{ "id": app.id, "name": app.name, "description": app.description, "appType": app.appType, "isPublished": app.isPublished, "updateTime": app.updateTime } for app in apps] @server.tool() def create_conversation(app_id: str) -> str: """ Create a new conversation session for a specific AppBuilder application. Args: app_id (str): The unique identifier of the target application Returns: str: A unique conversation identifier that can be used for subsequent interactions Example: conversation_id = create_conversation("fcc766c4-2bf2-46a3-a63b-1341b05bac49") """ client = appbuilder.AppBuilderClient(app_id) conversation_id = client.create_conversation() return conversation_id @server.tool() def run(app_id: str, conversation_id: str, query: str) -> str: """ Execute a conversation query with a specific AppBuilder application. Args: app_id (str): The unique identifier of the target application conversation_id (str): The conversation session identifier query (str): The input text/query to send to the application Returns: str: The response content from the conversation Example: response = run_conversation( "fcc766c4-2bf2-46a3-a63b-1341b05bac49", "conv-123", "今天北京天气如何" ) """ client = appbuilder.AppBuilderClient(app_id) output = client.run(conversation_id, query) return output.content.answer if __name__ == "__main__": server.run() ================================================ FILE: python/mcp_server/client.py ================================================ # Based on https://modelcontextprotocol.io/quickstart/client import sys from typing import Optional from contextlib import AsyncExitStack from mcp.client.session import ClientSession from mcp.client.stdio import StdioServerParameters from mcp.client.stdio import stdio_client from mcp.client.sse import sse_client from appbuilder.utils.logger_util import logger class MCPClient: def __init__(self): # Initialize session and client objects self.session: Optional[ClientSession] = None self.exit_stack = AsyncExitStack() self.tools = None self.sessions = {} self.tool_to_server = {} self._session_context = None self._streams_context = None async def connect_to_server( self, server_script_path: str = None, service_url: str = None, env: dict = None ): """Connect to an MCP server Args: server_script_path: Path to the server script (.py or .js) service_url: URL of the service """ if server_script_path is not None: await self._connect_to_stdio_server(server_script_path, env=env) elif service_url is not None: await self._connect_to_sse_server(service_url) else: raise ValueError( "Either server_script_path or service_url must be provided." ) async def _connect_to_stdio_server(self, server_script_path: str, env: dict = None): is_python = server_script_path.endswith(".py") is_js = server_script_path.endswith(".js") if not (is_python or is_js): raise ValueError("Server script must be a .py or .js file") command = sys.executable if is_python else "node" server_params = StdioServerParameters( command=command, args=[server_script_path], env=env ) stdio_transport = await self.exit_stack.enter_async_context( stdio_client(server_params) ) self.stdio, self.write = stdio_transport self.session = await self.exit_stack.enter_async_context( ClientSession(self.stdio, self.write) ) await self.session.initialize() response = await self.session.list_tools() tools = response.tools self.tools = tools logger.info( "\nConnected to server with tools:" + str([tool.name for tool in tools]) ) cmd_key = f"{command} {' '.join(server_script_path)}" self._store_session_and_tools(cmd_key) async def _connect_to_sse_server(self, service_url: str): self._streams_context = sse_client(url=service_url) streams = await self._streams_context.__aenter__() self._session_context = ClientSession(*streams) self.session: ClientSession = await self._session_context.__aenter__() await self.session.initialize() response = await self.session.list_tools() tools = response.tools self.tools = tools logger.info( "\nConnected to server with tools:" + str([tool.name for tool in tools]) ) self._store_session_and_tools(service_url) def _store_session_and_tools(self, cmd_key): new_sessions = {cmd_key: self.session} new_sessions.update(self.sessions) self.sessions = new_sessions for tool in self.tools: if tool.name in self.tool_to_server: raise ValueError(f"Duplicate tool name: {tool.name}") self.tool_to_server[tool.name] = cmd_key async def call_tool(self, tool_name, tool_args): server_cmd = self.tool_to_server.get(tool_name) if server_cmd is None: raise ValueError(f"Tool '{tool_name}' not found") session = self.sessions[server_cmd] result = await session.call_tool(name=tool_name, arguments=tool_args) return result async def cleanup(self): """Clean up resources""" await self.exit_stack.aclose() """Properly clean up the session and streams""" if self._session_context: await self._session_context.__aexit__(None, None, None) if self._streams_context: await self._streams_context.__aexit__(None, None, None) ================================================ FILE: python/mcp_server/http_client.py ================================================ import asyncio import json import logging from typing import Any, Dict, Optional, Union, List, Tuple import aiohttp from aiohttp import ClientTimeout # Set up logging logging.basicConfig(level=logging.INFO) logger = logging.getLogger(__name__) class HTTPClient: """ HTTP client with retry mechanism, timeout handling, and error reporting. Supports exponential backoff for retries. """ def __init__( self, base_url: Optional[str] = None, headers: Optional[Dict[str, str]] = None, default_timeout: int = 30, max_retries: int = 3, ): """ Initialize the HTTP client. Args: base_url: Base URL for all requests headers: Default headers to include in all requests default_timeout: Default timeout in seconds max_retries: Maximum number of retry attempts """ self.base_url = base_url self.headers = headers or {} self.default_timeout = default_timeout self.max_retries = max_retries self.session: Optional[aiohttp.ClientSession] = None async def _ensure_session(self) -> None: """Ensure aiohttp session exists and is open""" if self.session is None or self.session.closed: self.session = aiohttp.ClientSession( timeout=ClientTimeout(total=self.default_timeout), headers=self.headers ) async def close(self) -> None: """Close the HTTP session""" if self.session and not self.session.closed: await self.session.close() self.session = None async def request( self, method: str, url: str, params: Optional[Dict[str, Any]] = None, headers: Optional[Dict[str, Any]] = None, data: Optional[str] = None, json_data: Optional[Dict[str, Any]] = None, timeout: Optional[int] = None, max_retries: Optional[int] = None, ) -> Dict[str, Any]: """ Make an HTTP request with retry mechanism. Args: method: HTTP method (GET, POST, PUT, DELETE, etc.) url: URL path (will be joined with base_url if provided) params: Query parameters headers: Additional headers (will be merged with default headers) data: Request body as string json_data: Request body as JSON (will be serialized) timeout: Request timeout in seconds (overrides default_timeout) max_retries: Maximum retry attempts (overrides default max_retries) Returns: Dictionary with response data or error information """ # Use provided values or fall back to defaults timeout = timeout or self.default_timeout max_retries = max_retries if max_retries is not None else self.max_retries # Merge headers merged_headers = dict(self.headers) if headers: merged_headers.update(headers) # Handle JSON data if json_data: data = json.dumps(json_data) merged_headers['Content-Type'] = 'application/json' # Construct full URL from urllib.parse import urljoin full_url = urljoin(self.base_url, url) if self.base_url else url await self._ensure_session() # Implement retry logic retries = 0 while retries <= max_retries: try: logger.info(f"Making {method} request to {full_url} (Attempt {retries+1}/{max_retries+1})") async with self.session.request( method=method.upper(), url=full_url, params=params, headers=merged_headers, data=data, timeout=ClientTimeout(total=timeout) ) as response: response.raise_for_status() # Handle different response content types content_type = response.headers.get('content-type', '') if 'application/json' in content_type: result = await response.json() else: result = await response.text() return { 'success': True, 'status_code': response.status, 'content_type': content_type, 'data': result } except (aiohttp.ClientResponseError, aiohttp.ClientConnectorError) as e: error_message = str(e) error_body = None if isinstance(e, aiohttp.ClientResponseError): try: error_body = await response.json() except: try: error_body = await response.text() except: error_body = "Could not read response body" error_message = f"{error_message} - {error_body}" retries += 1 if retries <= max_retries: wait_time = 2 ** retries # Exponential backoff logger.warning(f"Request failed: {error_message}. Retrying in {wait_time} seconds...") await asyncio.sleep(wait_time) else: logger.error(f"Request failed after {max_retries+1} attempts: {error_message}") return { 'success': False, 'error': { 'type': 'http_error' if isinstance(e, aiohttp.ClientResponseError) else 'network_error', 'status_code': e.status if isinstance(e, aiohttp.ClientResponseError) else None, 'detail': error_message } } except aiohttp.ClientError as e: logger.error(f"Client error: {str(e)}") return { 'success': False, 'error': { 'type': 'network_error', 'detail': str(e) } } except asyncio.TimeoutError: retries += 1 if retries <= max_retries: wait_time = 2 ** retries # Exponential backoff logger.warning(f"Request timed out after {timeout} seconds. Retrying in {wait_time} seconds...") await asyncio.sleep(wait_time) else: logger.error(f"Request timed out after {max_retries+1} attempts") return { 'success': False, 'error': { 'type': 'timeout_error', 'detail': f"Request timed out after {timeout} seconds" } } except Exception as e: logger.error(f"Unexpected error: {str(e)}") return { 'success': False, 'error': { 'type': 'unexpected_error', 'detail': str(e) } } async def get(self, url: str, **kwargs) -> Dict[str, Any]: """Convenience method for GET requests""" return await self.request("GET", url, **kwargs) async def post(self, url: str, **kwargs) -> Dict[str, Any]: """Convenience method for POST requests""" return await self.request("POST", url, **kwargs) async def put(self, url: str, **kwargs) -> Dict[str, Any]: """Convenience method for PUT requests""" return await self.request("PUT", url, **kwargs) async def patch(self, url: str, **kwargs) -> Dict[str, Any]: """Convenience method for PATCH requests""" return await self.request("PATCH", url, **kwargs) async def delete(self, url: str, **kwargs) -> Dict[str, Any]: """Convenience method for DELETE requests""" return await self.request("DELETE", url, **kwargs) ================================================ FILE: python/mcp_server/knowledge_base/README.md ================================================ # Knowledge Base MCP Server Knowledge Base MCP Server provides a set of tools for managing knowledge bases and documents through the MCP protocol. It allows you to create, query, and manage knowledge bases and their contents. ## Features * **Knowledge Base Creation and Management**: Create new knowledge bases and list all available knowledge bases. * **Document Management**: Upload files to knowledge bases and list all documents in a knowledge base. * **Knowledge Base Querying**: Search knowledge bases with query strings. ## Quick Start 1. Get your AppBuilder API Key from the console 2. Format your authorization token as: `Bearer+` (keep the "+" in between) 3. Config with ```json { "mcpServers": { "knowledge_base": { "url": "http://appbuilder.baidu.com/v2/knowledgeBase/mcp/sse?api_key=Bearer+bce-v3/ALTAK..." } } } ``` ## Available Tools ### create_knowledge_base Creates a new knowledge base. **Parameters:** - `name` (str): Name of the KnowledgeBase. - `description` (str): Description of the KnowledgeBase. **Returns:** - Dictionary containing the knowledge base ID, name, description, and request ID. ### describe_knowledge_base Get details of a specific KnowledgeBase. **Parameters:** - `id` (str): ID of the KnowledgeBase. **Returns:** - Dictionary containing the knowledge base ID, name, and description. ### list_knowledge_bases List all KnowledgeBases. **Parameters:** - `max_keys` (int, optional): Maximum number of KnowledgeBases to return. Default is 10. **Returns:** - List of dictionaries, each containing a knowledge base's ID, name, and description. ### query_knowledge_base Query content from KnowledgeBases. **Parameters:** - `query` (str): Search query string. - `id_list` (list[str]): List of KnowledgeBase IDs to search in. **Returns:** - List of dictionaries, each containing a chunk's ID, content, document ID, and document name. ### upload_document Upload documents to a KnowledgeBase. **Parameters:** - `id` (str): KnowledgeBase ID. - `file_path` (str): Path to the file to upload. - `template` (str, optional): Optional processing template to use. Options: "ppt", "paper", "resume", or "default". Default is "default". **Returns:** - Dictionary containing the document ID and request ID. ### list_documents Get all documents in a KnowledgeBase. **Parameters:** - `id` (str): Knowledge base ID. **Returns:** - List of dictionaries, each containing a document's ID, name, and word count. ## Usage Examples ```python import asyncio import json import io import os import appbuilder from appbuilder.mcp_server.client import MCPClient os.environ["APPBUILDER_TOKEN"] = "YOUR_APPBUILDER_TOKEN" async def main(): mcp_client = MCPClient() await mcp_client.connect_to_server(service_url=service_url) # case create_knowledge_base result = await mcp_client.call_tool( "create_knowledge_base", {"name": "mcp测试可删", "description": "mcp测试,可删"}, ) knowledge_base_info = json.loads(result.content[0].text) knowledge_base_id = knowledge_base_info.get("id") assert knowledge_base_id is not None # case describe_knowledge_base appbuilder.logger.debug(f"create knowledge base success: {knowledge_base_id}") result = await mcp_client.call_tool( "describe_knowledge_base", {"id": knowledge_base_id}, ) knowledge_base_info = json.loads(result.content[0].text) knowledge_base_id = knowledge_base_info.get("id") assert knowledge_base_id is not None appbuilder.logger.debug(f"describe knowledge base success: {knowledge_base_id}") # case list_knowledge_bases result = await mcp_client.call_tool( "list_knowledge_bases", {"max_keys": 10}, ) assert len(result.content) == 10 appbuilder.logger.debug(f"list knowledge bases success: {len(result.content)}") # case upload_document file_content = "这里是你的文件内容字符串" with io.BytesIO(file_content.encode("utf-8")) as f: result = await mcp_client.call_tool( "upload_document", {"id": knowledge_base_id, "file_data": f, "file_name": "test.txt"}, ) document_info = json.loads(result.content[0].text) document_id = document_info.get("documentId") assert document_id is not None appbuilder.logger.debug(f"upload document success: {document_id}") # case list_documents result = await mcp_client.call_tool( "list_documents", {"id": knowledge_base_id}, ) print(result) appbuilder.logger.debug(f"list documents base success: {knowledge_base_id}") # case query_knowledge_base result = await mcp_client.call_tool( "query_knowledge_base", {"query": "分子", "id_list": [knowledge_base_id]}, ) assert result.content[0].text is not None appbuilder.logger.debug("query knowledge base success") if __name__ == "__main__": service_url = ( "http://appbuilder.baidu.com/v2/ai_search/mcp/sse?api_key=" + os.environ.get("APPBUILDER_TOKEN") ) loop = asyncio.get_event_loop() loop.run_until_complete(main()) ``` ================================================ FILE: python/mcp_server/knowledge_base/__init__.py ================================================ """ MCP Server for Knowledge Base. This module provides functionality for knowledge base operations. """ from .knowledge_base_server import ( create_knowledge_base, query_knowledge_base, describe_knowledge_base, list_knowledge_bases, upload_document, list_documents, server ) __all__ = [ "create_knowledge_base", "query_knowledge_base", "describe_knowledge_base", "list_knowledge_bases", "upload_document", "list_documents", "server" ] ================================================ FILE: python/mcp_server/knowledge_base/knowledge_base_server.py ================================================ """ Baidu AI Search MCP Server stdio server file. We also support access via SSE protocol. The access address is: http://appbuilder.baidu.com/v2/ai_search/mcp/sse?api_key= You can refer to this webpage https://cloud.baidu.com/doc/AppBuilder/s/klv2eywua to obtain the api_key, in the format of "Bearer+bce…". """ from enum import Enum from typing import Literal from mcp.server import FastMCP from appbuilder import KnowledgeBase, DocumentProcessOption, DocumentChoices class TemplateType(str, Enum): PPT = "ppt" PAPER = "paper" RESUME = "resume" CUSTOM = "custom" DEFAULT = "default" QA_PAIR = "qaPair" class ParserChoices(str, Enum): LAYOUT_ANALYSIS = "layoutAnalysis" OCR = "ocr" PAGE_IMAGE_ANALYSIS = "pageImageAnalysis" CHART_ANALYSIS = "chartAnalysis" TABLE_ANALYSIS = "tableAnalysis" server = FastMCP(name="AppBuilder KnowledgeBase MCP Server") @server.tool() def create_knowledge_base(name: str, description: str): """ Create a new KnowledgeBase. Args: name: Name of the KnowledgeBase description: Description of the KnowledgeBase """ client = KnowledgeBase() kb = client.create_knowledge_base(name=name, description=description, type="public") return { "id": kb.id, "name": kb.name, "description": kb.description, "requestId": kb.requestId } @server.tool() def describe_knowledge_base(id: str): """ Get details of a specific KnowledgeBase. Args: id: ID of the KnowledgeBase """ client = KnowledgeBase() kb = client.get_knowledge_base_detail(id) return { "id": kb.id, "name": kb.name, "description": kb.description } @server.tool() def list_knowledge_bases(max_keys: int = 10): """ List all KnowledgeBase. Args: max_keys: Maximum number of KnowledgeBase to return (default: 10) """ client = KnowledgeBase() resp = client.get_knowledge_base_list(maxKeys=max_keys) return [{ "id": kb.id, "name": kb.name, "description": kb.description } for kb in resp.data] @server.tool() def query_knowledge_base(query: str, id_list: list[str]): """ Query content from KnowledgeBases. Args: query: Search query string id_list: List of KnowledgeBase ID to search in """ client = KnowledgeBase() resp = client.query_knowledge_base(query, knowledgebase_ids=id_list) return [{ "chunk_id": chunk.chunk_id, "content": chunk.content, "document_id": chunk.document_id, "document_name": chunk.document_name } for chunk in resp.chunks] @server.tool() def upload_document( id: str, file_path: str, template: Literal["ppt", "paper", "resume", "default"] = "default", ): """ Upload documents to a KnowledgeBase. Args: id: KnowledgeBase ID file_path: Path to the file to upload template: Optional processing template to use. Options: - ppt: PPT slides - paper: Academic papers - resume: Resume documents - default: Default configuration """ if template not in TemplateType.__members__.values(): raise ValueError(f"Invalid template. Must be one of: {list(TemplateType.__members__.values())}") content_format: str = "rawText" option = DocumentProcessOption(template=template) option.parser = DocumentChoices(choices=["layoutAnalysis", "ocr", "pageImageAnalysis", "chartAnalysis", "tableAnalysis"]) client = KnowledgeBase() resp = client.upload_documents( id=id, content_format=content_format, file_path=file_path, processOption=option ) return { "documentId": resp.documentId, "requestId": resp.requestId } @server.tool() def list_documents(id: str): """ Get all documents in a KnowledgeBase. Args: id: Knowledge base ID """ client = KnowledgeBase() resp = client.get_all_documents(id) return [{ "id": doc.id, "name": doc.name, "word_count": doc.word_count } for doc in resp] if __name__ == "__main__": server.run() ================================================ FILE: python/mcp_server/openapi.py ================================================ from dataclasses import dataclass from typing import Dict, List, Any, Optional, Callable, Awaitable import asyncio import yaml import json import aiohttp from .http_client import HTTPClient @dataclass class MCPTool: name: str description: str input_schema: Dict[str, Any] operation_id: str method: str path: str parameters: List[Dict[str, Any]] request_body: Optional[Dict[str, Any]] = None def create_handler(self, converter: 'OpenAPIMCPConverter') -> Callable: """ Create a handler function for this tool that can be registered with MCP. Returns: Callable: An async function that handles tool execution """ async def handler(arguments: Dict[str, Any]) -> Dict[str, Any]: # Prepare request parameters url = self.path query_params = {} headers = {} body = None # Handle path parameters for param in self.parameters: if 'name' not in param: continue param_name = param['name'] if param_name in arguments: value = arguments[param_name] # Convert to string if needed if isinstance(value, (int, float, bool)): value = str(value) if param.get('in') == 'path': url = url.replace(f"{{{param_name}}}", value) elif param.get('in') == 'query': query_params[param_name] = value elif param.get('in') == 'header': headers[param_name] = value # Handle request body if self.request_body: content_type = next(iter(self.request_body['content'].keys())) body_schema = self.request_body['content'][content_type]['schema'] body = {} for prop_name in body_schema.get('properties', {}): if prop_name in arguments: body[prop_name] = arguments[prop_name] # Make the API call using the converter's HTTP client response = await converter.http_client.request( method=self.method, url=url, params=query_params, headers=headers, json=body if body else None ) return response # Set metadata on the handler handler.__name__ = self.name handler.__doc__ = self.description return handler class OpenAPIMCPConverter: def __init__(self, base_url: Optional[str] = None, headers: Optional[Dict[str, str]] = None, timeout: float = 30.0, max_retries: int = 3): """ Initialize the converter Args: base_url: Base URL for API calls headers: Default headers for API calls timeout: Timeout for API calls in seconds max_retries: Maximum number of retry attempts """ self.base_url = base_url self.headers = headers or {} self.tools: Dict[str, MCPTool] = {} self.http_client = HTTPClient( base_url=base_url, headers=headers, default_timeout=timeout, max_retries=max_retries ) def create_tools(self, prefix: str = "") -> Dict[str, Callable]: """ Create callable handlers for all tools with optional prefix Args: prefix: Optional prefix to add to tool names Returns: Dict[str, Callable]: Dictionary of tool name to handler function """ handlers = {} for tool_name, tool in self.tools.items(): prefixed_name = f"{prefix}{tool_name}" if prefix else tool_name handlers[prefixed_name] = tool.create_handler(self) return handlers async def close(self) -> None: """Close the HTTP client session""" await self.http_client.close() async def load_spec(self, spec_source: str) -> None: """ Load OpenAPI spec from URL or file Args: spec_source: URL or file path to OpenAPI spec """ if spec_source.startswith(('http://', 'https://')): # Use HTTP client to fetch the spec response = await self.http_client.get(spec_source) if not response.get('success', False): error = response.get('error', {}) raise Exception(f"Failed to load spec: {error.get('detail', 'Unknown error')}") # Parse the response data if isinstance(response['data'], dict): spec = response['data'] else: # If data is not a dict, try to parse it as JSON spec = json.loads(response['data']) else: with open(spec_source, 'r', encoding='utf-8') as f: if spec_source.endswith(('.yaml', '.yml')): spec = yaml.safe_load(f) else: spec = json.load(f) # Set base URL if not provided if not self.base_url and 'servers' in spec: self.base_url = spec['servers'][0]['url'] # Update HTTP client with new base_url self.http_client.base_url = self.base_url await self._process_spec(spec) async def _process_spec(self, spec: Dict[str, Any]) -> None: """Process OpenAPI spec and create MCP tools""" for path, path_item in spec['paths'].items(): for method, operation in path_item.items(): if method.lower() not in ['get', 'post', 'put', 'delete', 'patch']: continue tool = self._create_tool(path, method, operation) self.tools[tool.name] = tool def _create_tool(self, path: str, method: str, operation: Dict[str, Any]) -> MCPTool: """Create MCPTool from OpenAPI operation""" # Use operationId if available, otherwise create from method and path operation_id = operation.get('operationId') or f"{method}_{path}" # Collect parameters parameters = operation.get('parameters', []) required_params = [] # Build input schema properties = {} for param in parameters: # Skip parameters without a name if 'name' not in param: print(f"Warning: Parameter without name in {path} {method}") continue param_name = param['name'] if param.get('required', False): required_params.append(param_name) param_schema = param.get('schema', {}).copy() # Create a copy to modify # Handle parameter enums if 'enum' in param_schema: param_schema['enum'] = [str(v) for v in param_schema['enum']] # Handle parameter types if param_schema.get('type') == 'integer': param_schema['type'] = ['integer', 'string'] # Allow string input for integers properties[param_name] = { 'type': param_schema.get('type', 'string'), 'description': param.get('description', ''), 'required': param.get('required', False) } # Add enum values if present if 'enum' in param_schema: properties[param_name]['enum'] = param_schema['enum'] # Add request body if present if 'requestBody' in operation: content = operation['requestBody']['content'] if 'application/json' in content: body_schema = content['application/json']['schema'] if 'properties' in body_schema: for prop_name, prop_schema in body_schema['properties'].items(): properties[prop_name] = { 'type': prop_schema.get('type', 'string'), 'description': prop_schema.get('description', ''), 'required': prop_name in body_schema.get('required', []) } if 'enum' in prop_schema: properties[prop_name]['enum'] = prop_schema['enum'] input_schema = { 'type': 'object', 'properties': properties, 'required': required_params } return MCPTool( name=operation_id, description=operation.get('summary', operation.get('description', '')), input_schema=input_schema, operation_id=operation_id, method=method, path=path, parameters=parameters, request_body=operation.get('requestBody') ) def list_tools(self) -> List[Dict[str, Any]]: """Return list of tools in MCP format""" return [ { 'name': tool.name, 'description': tool.description, 'input_schema': tool.input_schema } for tool in self.tools.values() ] async def call_tool(self, tool_name: str, arguments: Dict[str, Any] = None, max_retries: int = None, timeout: int = None) -> Dict[str, Any]: """Execute tool by making API call""" if arguments is None: arguments = {} if tool_name not in self.tools: return { 'error': { 'type': 'tool_not_found', 'detail': f"Tool '{tool_name}' not found" } } tool = self.tools[tool_name] # Prepare request parameters url = tool.path query_params = {} headers = {} # Handle path parameters for param in tool.parameters: # Skip parameters without a name if 'name' not in param: continue param_name = param['name'] if param_name in arguments: value = arguments[param_name] # Convert to string if needed if isinstance(value, (int, float, bool)): value = str(value) if param.get('in') == 'path': url = url.replace(f"{{{param_name}}}", value) elif param.get('in') == 'query': query_params[param_name] = value elif param.get('in') == 'header': headers[param_name] = value # Handle request body if tool.request_body: body_params = { k: v for k, v in arguments.items() if k not in query_params and k not in headers } if body_params: json_data = body_params else: json_data = None else: json_data = None # Make the request using our HTTP client response = await self.http_client.request( method=tool.method, url=url, params=query_params, headers=headers, json_data=json_data, timeout=timeout, max_retries=max_retries ) # Handle the response if response.get('success', False): result = response['data'] return { 'content': [ { 'type': 'json' if isinstance(result, (dict, list)) else 'text', 'json' if isinstance(result, (dict, list)) else 'text': result } ] } else: # Return the error information return { 'error': response.get('error', { 'type': 'unknown_error', 'detail': 'Unknown error occurred' }) } ================================================ FILE: python/mcp_server/server.py ================================================ # Copyright (c) 2024 Baidu, Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import os import appbuilder from appbuilder.core.component import Component, Image, Audio, References, Content from appbuilder.core._exception import * from appbuilder.mcp_server.sse import SseServerTransport from appbuilder.mcp_server.openapi import OpenAPIMCPConverter from starlette.applications import Starlette from starlette.routing import Mount, Route from typing import Any, Literal, Optional, Dict from collections.abc import Generator from starlette.requests import Request import logging import inspect import requests import base64 import io from functools import wraps logging.basicConfig(level=logging.INFO) try: from mcp.server.fastmcp import FastMCP from mcp.server.fastmcp.server import _convert_to_content from mcp.types import ( ImageContent, TextContent, EmbeddedResource, TextResourceContents, BlobResourceContents, Annotations ) except ImportError: raise ImportError( "Could not import FastMCP. Please install MCP package with: " "pip install mcp" ) class MCPComponentServer: """ A server that converts Appbuilder Components to FastMCP tools. Examples: .. code-block:: python # Create server server = MCPComponentServer("AI Service") # Add components with default URLs based on their names ocr = GeneralOCR() server.add_component(ocr) # Will use default URL based on component name # Add component with custom URL text_gen = TextGeneration() server.add_component(text_gen) # Will use default URL based on component name # Add custom tool @server.tool() def add(a: int, b: int) -> int: '''Add two numbers''' return a + b # Run server server.run() """ def __init__(self, name: str, host: str = "localhost", port: int = 8000, **kwargs: Any): """ Initialize the ComponentMCPServer. Args: name (str): Name of the server host (str): Host address to bind to (default: "localhost") port (int): Port number to listen on (default: 8000) **kwargs: Additional arguments passed to FastMCP """ self.mcp = FastMCP(name, host=host, port=port, **kwargs) def tool(self, *args, **kwargs): """ Decorator to register a custom tool function. Passes through to FastMCP's tool decorator. Args: *args: Positional arguments for FastMCP tool decorator **kwargs: Keyword arguments for FastMCP tool decorator """ return self.mcp.tool(*args, **kwargs) def resource(self, *args, **kwargs): """ Decorator to register a resource. Passes through to FastMCP's resource decorator. Args: *args: Positional arguments for FastMCP resource decorator **kwargs: Keyword arguments for FastMCP resource decorator """ return self.mcp.resource(*args, **kwargs) async def add_openapi_spec( self, spec_url: str, prefix: str = "", base_url: Optional[str] = None, headers: Optional[Dict[str, str]] = None ) -> Dict[str, Any]: """ Add an OpenAPI specification and register its tools. Args: spec_url: OpenAPI specification URL or file path (.json or .yaml) prefix: Optional prefix for all tool names from this spec base_url: Optional base URL for API calls headers: Optional default headers for API calls Returns: Dict containing success status and list of added tools """ try: # Create and configure converter converter = OpenAPIMCPConverter( base_url=base_url, headers=headers ) # Load spec await converter.load_spec(str(spec_url)) # Register tools tools_added = [] for tool_name, handler in converter.create_tools(prefix).items(): self.mcp.add_tool( handler, name=tool_name, description=handler.__doc__ ) tools_added.append(tool_name) # Store converter for cleanup self._converters[prefix or "default"] = converter return { 'success': True, 'tools_added': tools_added } except Exception as e: return { 'success': False, 'error': str(e) } def _convert_visible_scope_to_audience( self, visible_scope: str ) -> list[str]: if visible_scope == "llm": return ["assistant"] elif visible_scope == "user": return ["user"] else: return ["user", "assistant"] def _get_mimetype_from_bytes(self, data: bytes) -> str: import filetype kind = filetype.guess(data) return kind.mime def _convert_image_to_image_content( self, text: Image, audience: list[str] ) -> ImageContent: """convert base64 data, such as image/audio to ImageContent""" try: if text.base64: logging.info("create ImageContent from Image.byte") base64_data = text.base64 image_byte = io.BytesIO(base64.b64decode(base64_data)) else: logging.info("create ImageContent from Image.url") response = requests.get(text.url) response.raise_for_status() image = response.content base64_data = base64.b64encode(image).decode('utf-8') image_byte = io.BytesIO(image) mime_type = self._get_mimetype_from_bytes(image_byte) # create ImageContent return ImageContent( type="image", data=base64_data, mimeType=mime_type, annotations=Annotations( audience=audience ) ) except Exception as e: logging.error("failed convet image to ImageContent") raise e def _convert_audio_to_embedded_resource( self, text: Audio, audience: str = Literal["user", "assistant"] ) -> EmbeddedResource: """convert audio to EmebeddedResource""" try: if text.base64: logging.info("convert audio to EmbeddedResource from Audio.byte") base64_data = text.base64 audio_byte = io.BytesIO(base64.b64decode(base64_data)) else: logging.info("convert audio to EmbeddedResource from Audio.url") # get data response = requests.get(text.url) response.raise_for_status() # convert to base64 base64_data = base64.b64encode(response.content).decode('utf-8') audio_byte = io.BytesIO(response.content) # detect audio type audio_type = self._get_mimetype_from_bytes(audio_byte) # create EmbeddedResource return EmbeddedResource( type="resource", resource=BlobResourceContents( blob=base64_data, uri=text.url, mimeType=audio_type ), annotations=Annotations( audience=audience ) ) except Exception as e: logging.error("failed to convert audio to EmbeddedResource") raise e def _convert_reference_to_embedded_resource( self, text: References, audience: str = Literal["user", "assistant"] ) -> EmbeddedResource: """convert reference to EmbeddedResource""" from urllib.parse import unquote return EmbeddedResource( type="resource", resource=TextResourceContents( uri=unquote(text.doc_id), text=text.content, mimeType="text/plain" ), annotations=Annotations( audience=audience ) ) def _convert_component_output_to_text_content( self, text: Content, audience: str = Literal["user", "assistant"] ) -> TextContent: """convert ComponentOutput to json_str""" return TextContent( type="text", text=text.model_dump_json(), annotations=Annotations( audience=audience ) ) def _convert_generator( self, result: Generator ) -> list[TextContent|ImageContent|EmbeddedResource]: """convert geneartor to list of TextContent, ImageContent and EmbeddedResource""" output = [] for iter in result: type = iter.content[0].type text = iter.content[0].text visible_scope = iter.content[0].visible_scope audience = self._convert_visible_scope_to_audience(visible_scope) if type in ["text", "oral_text"]: text_output = TextContent( type="text", text=iter.content[0].text.info, annotations=Annotations( audience=audience ) ) output.append(text_output) else: match type: case "image": image_output = self._convert_image_to_image_content( text, audience ) output.append(image_output) case "references": reference_output = self._convert_reference_to_embedded_resource( text, audience ) output.append(reference_output) case "audio": audio_output = self._convert_audio_to_embedded_resource(text, audience) output.append(audio_output) iter_output = self._convert_component_output_to_text_content(iter, audience) output.append(iter_output) output = _convert_to_content(output) return output def convert_component_to_tool(self, component: Component) -> None: """ Add an Appbuilder Component and register its tools under the component's URL namespace. Args: component (Component): The component instance to add """ # Register each manifest as a separate tool for manifest in component.manifests: tool_name = manifest["name"] tool_decription = manifest["description"] def create_tool_fn(func): signature = inspect.signature(func) @wraps(func) def wrapper(*args, **kwargs) -> Any: try: # call tool_eval bound_values = signature.bind(*args, **kwargs) os.environ["APPBUILDER_SDK_MCP_CONTEXT"] = "server" if "kwargs" in bound_values.kwargs: inner_kwargs = bound_values.kwargs["kwargs"] if isinstance(inner_kwargs, dict): outer_kwargs = bound_values.kwargs outer_kwargs.pop("kwargs") inner_kwargs.update(outer_kwargs) new_bound_values = signature.bind(*args, **inner_kwargs) result = func(*new_bound_values.args, **new_bound_values.kwargs) else: result = func(*bound_values.args, **bound_values.kwargs) else: result = func(*bound_values.args, **bound_values.kwargs) if result is NotImplementedError: logging.error(f"tool_eval not implemented in {tool_name}") raise NotImplementedError(f"tool_eval not implemented in {tool_name}") list_result = self._convert_generator(result) return list_result except Exception as e: logging.error(f"Error in {tool_name}: {str(e)}") raise wrapper.__signature__ = signature return wrapper # Create tool function with metadata tool_fn = create_tool_fn(component.tool_eval) tool_fn.__name__ = tool_name tool_fn.__doc__ = tool_decription # Register with FastMCP using name and description from manifest self.mcp.tool(name=tool_name, description=tool_decription)(tool_fn) def add_component( self, component: Component, ): """add AppBuilder official tool as MCP server""" try: component_name = component.__class__.__name__ self.convert_component_to_tool(component) logging.info(f"component: {component_name} has been added") except Exception as e: logging.exception(f"Failed to add component {component_name}: {str(e)}") raise e def run(self, transport: Literal["stdio", "sse"] = "stdio", redis_client=None) -> None: """Run the FastMCP server. Note this is a synchronous function. Args: transport: Transport protocol to use ("stdio" or "sse") """ if transport == "sse": return self.create_sse_app(redis_client) self.mcp.run() def create_sse_app(self, redis_client = None) -> Starlette: """Return an instance of the SSE server app.""" mcp_server = self.mcp._mcp_server sse = SseServerTransport("/mcp/messages/", redis_client=redis_client) async def handle_sse(request: Request): async with sse.connect_sse( request.scope, request.receive, request._send, ) as streams: await mcp_server.run( streams[0], streams[1], mcp_server.create_initialization_options(), ) return Starlette( routes=[ Route("/mcp/sse", endpoint=handle_sse), Mount("/mcp/messages", app=sse.handle_post_message), ], ) ================================================ FILE: python/mcp_server/sse.py ================================================ """ SSE Server Transport Module This module implements a Server-Sent Events (SSE) transport layer for MCP servers. Example usage: ``` # Create an SSE transport at an endpoint sse = SseServerTransport(endpoint="/messages/", redis_client=None) # Create Starlette routes for SSE and message handling routes = [ Route("/sse", endpoint=handle_sse), Mount("/messages/", app=sse.handle_post_message), ] # Define handler functions async def handle_sse(request): async with sse.connect_sse( request.scope, request.receive, request._send ) as streams: await app.run( streams[0], streams[1], app.create_initialization_options() ) # Create and run Starlette app starlette_app = Starlette(routes=routes) uvicorn.run(starlette_app, host="0.0.0.0", port=port) ``` See SseServerTransport class documentation for more details. """ import logging import pickle from contextlib import asynccontextmanager from typing import Any from urllib.parse import quote from uuid import UUID, uuid4 import anyio from anyio.streams.memory import MemoryObjectReceiveStream, MemoryObjectSendStream from pydantic import ValidationError from sse_starlette import EventSourceResponse from starlette.requests import Request from starlette.responses import Response from starlette.types import Receive, Scope, Send import mcp.types as types logger = logging.getLogger(__name__) class SseServerTransport: """ SSE server transport for MCP. This class provides _two_ ASGI applications, suitable to be used with a framework like Starlette and a server like Hypercorn: 1. connect_sse() is an ASGI application which receives incoming GET requests, and sets up a new SSE stream to send server messages to the client. 2. handle_post_message() is an ASGI application which receives incoming POST requests, which should contain client messages that link to a previously-established SSE session. """ _endpoint: str _read_stream_writers: dict[ UUID, MemoryObjectSendStream[types.JSONRPCMessage | Exception] ] def __init__(self, endpoint: str, redis_client=None) -> None: """ Creates a new SSE server transport, which will direct the client to POST messages to the relative or absolute URL given. redis_client: redis client based on aioredis. """ super().__init__() self._redis_client = redis_client self._endpoint = endpoint self._read_stream_writers = {} logger.debug(f"SseServerTransport initialized with endpoint: {endpoint}") @asynccontextmanager async def connect_sse(self, scope: Scope, receive: Receive, send: Send): if scope["type"] != "http": logger.error("connect_sse received non-HTTP request") raise ValueError("connect_sse can only handle HTTP requests") logger.debug("Setting up SSE connection") read_stream: MemoryObjectReceiveStream[types.JSONRPCMessage | Exception] read_stream_writer: MemoryObjectSendStream[types.JSONRPCMessage | Exception] write_stream: MemoryObjectSendStream[types.JSONRPCMessage] write_stream_reader: MemoryObjectReceiveStream[types.JSONRPCMessage] read_stream_writer, read_stream = anyio.create_memory_object_stream(0) write_stream, write_stream_reader = anyio.create_memory_object_stream(0) session_id = uuid4() session_uri = f"{quote(self._endpoint)}?session_id={session_id.hex}" self._read_stream_writers[session_id] = read_stream_writer logger.debug(f"Created new session with ID: {session_id}") sse_stream_writer, sse_stream_reader = anyio.create_memory_object_stream[ dict[str, Any] ](0) async def sse_writer(): logger.debug("Starting SSE writer") async with sse_stream_writer, write_stream_reader: await sse_stream_writer.send({"event": "endpoint", "data": session_uri}) logger.debug(f"Sent endpoint event: {session_uri}") async for message in write_stream_reader: logger.debug(f"Sending message via SSE: {message}") await sse_stream_writer.send( { "event": "message", "data": message.model_dump_json( by_alias=True, exclude_none=True ), } ) async with anyio.create_task_group() as tg: response = EventSourceResponse( content=sse_stream_reader, data_sender_callable=sse_writer ) logger.debug("Starting SSE response task") tg.start_soon(response, scope, receive, send) if self._redis_client: tg.start_soon(self._subscribe_loop, session_id) logger.debug("Yielding read and write streams") yield (read_stream, write_stream) async def _subscribe_loop(self, session_id: UUID): pubsub = self._redis_client.pubsub() await pubsub.psubscribe(self._redis_channel(session_id)) async for message in pubsub.listen(): if message["type"] == "pmessage": json_data = pickle.loads(message["data"]) logger.debug(f"Received message on {session_id.hex}: {json_data}") try: message = types.JSONRPCMessage.model_validate(json_data) logger.debug( f"{session_id.hex} Validated client message: {message}" ) except ValidationError as err: logger.error(f"{session_id} Failed to parse message: {err}") await self._read_stream_writers[session_id].send(err) return logger.debug(f"{session_id.hex} Sending message to writer: {message}") await self._read_stream_writers[session_id].send(message) async def handle_post_message( self, scope: Scope, receive: Receive, send: Send ) -> None: logger.debug("Handling POST message") request = Request(scope, receive) session_id_param = request.query_params.get("session_id") if session_id_param is None: logger.warning("Received request without session_id") response = Response("session_id is required", status_code=400) return await response(scope, receive, send) try: session_id = UUID(hex=session_id_param) logger.debug(f"Parsed session ID: {session_id}") except ValueError: logger.warning(f"Received invalid session ID: {session_id_param}") response = Response("Invalid session ID", status_code=400) return await response(scope, receive, send) writer = self._read_stream_writers.get(session_id) if not writer: logger.warning(f"Could not find session for ID: {session_id}") response = Response("Could not find session", status_code=404) return await response(scope, receive, send) body = await request.body() logger.debug(f"Received JSON: {body}") if self._redis_client: response = Response("Accepted", status_code=202) json_data = await request.json() await response(scope, receive, send) await self._redis_client.publish( self._redis_channel(session_id), pickle.dumps(json_data) ) return try: message = types.JSONRPCMessage.model_validate_json(body) logger.debug(f"Validated client message: {message}") except ValidationError as err: logger.error(f"Failed to parse message: {err}") response = Response("Could not parse message", status_code=400) await response(scope, receive, send) await writer.send(err) return logger.debug(f"Sending message to writer: {message}") response = Response("Accepted", status_code=202) await response(scope, receive, send) await writer.send(message) def _redis_channel(self, session_id: UUID) -> str: return f"mcp-{session_id.hex}" ================================================ FILE: python/tests/__init__.py ================================================ # Copyright (c) 2023 Baidu, Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. ================================================ FILE: python/tests/component_check.py ================================================ import json import os import inspect from jsonschema import validate from pydantic import BaseModel from appbuilder.utils.func_utils import Singleton from appbuilder.tests.component_schemas import type_to_json_schemas from appbuilder.utils.json_schema_to_model import json_schema_to_pydantic_model class CheckInfo(BaseModel): check_rule_name: str check_result: bool check_detail: str class RuleBase(object): def __init__(self): self.invalid = False def check(self, component_cls) -> CheckInfo: raise NotImplementedError def reset_state(self): self.invalid = False class ComponentCheckBase(metaclass=Singleton): def __init__(self): self.rules = {} def register_rule(self, rule_name: str, rule_obj: RuleBase): if not isinstance(rule_obj, RuleBase): raise TypeError("rule_obj must be a subclass of RuleBase") if rule_name in self.rules: raise ValueError(f"Rule {rule_name} already exists.") self.rules[rule_name] = rule_obj def remove_rule(self, rule_name: str): del self.rules[rule_name] def notify(self, component_obj, component_case) -> tuple[bool, list]: check_pass = True check_details = {} reasons = [] for rule_name, rule_obj in self.rules.items(): if rule_name == "ToolEvalOutputJsonRule": res = rule_obj.check(component_obj, component_case) else: res = rule_obj.check(component_obj) check_details[rule_name] = res if res.check_result == False: check_pass = False reasons.append(res.check_detail) if check_pass: return True, reasons else: return False, reasons class ManifestValidRule(RuleBase): """ 通过尝试将component的manifest转换为pydantic模型来检查manifest是否符合规范 """ def __init__(self, **kwargs): super().__init__() self.rule_name = "ManifestValidRule" def check(self, component_obj) -> CheckInfo: check_pass_flag = True invalid_details = [] try: if not hasattr(component_obj, "manifests"): raise ValueError("No manifests found") manifests = component_obj.manifests # NOTE(暂时检查manifest中的第一个mainfest) if not manifests or len(manifests) == 0: raise ValueError("No manifests found") manifest = manifests[0] tool_name = manifest['name'] tool_desc = manifest['description'] schema = manifest["parameters"] schema["title"] = tool_name # 第一步,将json schema转换为pydantic模型 pydantic_model = json_schema_to_pydantic_model(schema, tool_name) check_to_json = pydantic_model.schema_json() json_to_dict = json.loads(check_to_json) if "properties" in schema: properties = schema["properties"] for key, value in properties.items(): if "type" not in value: invalid_details.append("\'type' must be in properties item: {}".format(key)) if "description" not in value: invalid_details.append("\'description' must be in properties item: {}".format(key)) except Exception as e: print(e) check_pass_flag = False invalid_details.append(str(e)) if len(invalid_details) > 0: check_pass_flag = False invalid_details = ",".join(invalid_details) else: check_pass_flag = True invalid_details = "" return CheckInfo( check_rule_name=self.rule_name, check_result=check_pass_flag, check_detail=invalid_details) Data_Type = { 'string': str, 'integer': int, 'object': int, 'array': list, 'boolean': bool, 'null': None, } class InitKwargsRule(RuleBase): def __init__(self): super().__init__() self.rule_name = "InitKwargsRule" def _accepts_kwargs(self, func): """ 检查函数是否接受 **kwargs 参数。 """ sig = inspect.signature(func) params = sig.parameters return any(p.kind == inspect.Parameter.VAR_KEYWORD for p in params.values()) def check(self, component_obj) -> CheckInfo: if not self._accepts_kwargs(component_obj.__init__): return CheckInfo( check_rule_name=self.rule_name, check_result=False, check_detail="组件的__init__初始化方法需要添加**kwargs参数" ) else: return CheckInfo( check_rule_name=self.rule_name, check_result=True, check_detail="" ) class ToolEvalKwargsRule(RuleBase): def __init__(self): super().__init__() self.rule_name = "ToolEvalKwargsRule" def _accepts_kwargs(self, func): """ 检查函数是否接受 **kwargs 参数。 """ sig = inspect.signature(func) params = sig.parameters return any(p.kind == inspect.Parameter.VAR_KEYWORD for p in params.values()) def check(self, component_obj) -> CheckInfo: if not self._accepts_kwargs(component_obj.tool_eval): return CheckInfo( check_rule_name=self.rule_name, check_result=False, check_detail="组件的__init__初始化方法需要添加**kwargs参数" ) else: return CheckInfo( check_rule_name=self.rule_name, check_result=True, check_detail="" ) class MainfestMatchToolEvalRule(RuleBase): def __init__(self): super().__init__() self.rule_name = "MainfestMatchToolEvalRule" def check(self, component_obj) -> CheckInfo: check_pass_flag = True invalid_details = [] try: if not hasattr(component_obj, "manifests"): raise ValueError("No manifests found") manifests = component_obj.manifests # NOTE(暂时检查manifest中的第一个mainfest) if not manifests or len(manifests) == 0: raise ValueError("No manifests found") manifest = manifests[0] if 'parameters' in manifest and 'properties' in manifest['parameters']: properties = manifest['parameters']['properties'] manifest_var = properties.keys() else: manifest_var = [] # 交互检查 tool_eval_input_params = [] print("required_params: {}".format(manifest_var)) signature = inspect.signature(component_obj.tool_eval) ileagal_params = [] for param_name, param in signature.parameters.items(): if param_name == 'kwargs' or param_name == 'args' or param_name == 'self': continue tool_eval_input_params.append(param_name) if param_name not in manifest_var: check_pass_flag = False ileagal_params.append(param_name) if len(ileagal_params) > 0: invalid_details.append("tool_eval 参数 {} 不在 mainfest 参数列表中".format(",".join(ileagal_params))) ileagal_params =[] for required_param in manifest_var: if required_param not in tool_eval_input_params: check_pass_flag = False ileagal_params.append(required_param) if len(ileagal_params) > 0: invalid_details.append("mainfest 参数 {} 不在 tool_eval 参数列表中".format(",".join(ileagal_params))) return CheckInfo( check_rule_name=self.rule_name, check_result=check_pass_flag, check_detail=",".join(invalid_details)) except Exception as e: check_pass_flag = False invalid_details.append(str(e)) return CheckInfo( check_rule_name=self.rule_name, check_result=check_pass_flag, check_detail=",".join(invalid_details)) class ToolEvalInputNameRule(RuleBase): """ 检查tool_eval的输入参数中,是否包含系统保留的输入名称 """ def __init__(self): super().__init__() self.rule_name = 'ToolEvalInputNameRule' self.system_input_name = [ "_sys_name", "_sys_origin_query", "_sys_user_instruction", "_sys_file_names", "_sys_file_urls", "_sys_current_time", "_sys_chat_history", "_sys_used_tool", "_sys_uid", "_sys_traceid", "_sys_conversation_id", "_sys_gateway_endpoint", "_sys_appbuiler_token", "_sys_debug", "_sys_custom_variables", "_sys_thought_model_config", "_sys_rag_model_config", "_sys_parent_span_id", "_sys_span_id", "_sys_memory", "_sys_code_execution_endpoint", "_sys_session_id" ] def check(self, component_obj) -> CheckInfo: tool_eval_signature = inspect.signature(component_obj.tool_eval) params = tool_eval_signature.parameters invalid_details = [] check_pass_flag = True for param_name in params: if param_name == 'self': continue if param_name in self.system_input_name: invalid_details.append(param_name) check_pass_flag = False return CheckInfo( check_rule_name=self.rule_name, check_result=check_pass_flag, check_detail="以下ToolEval方法参数名称是系统保留字段,请更换:{}".format(",".join(invalid_details)) if len(invalid_details) > 0 else "") class ToolEvalOutputJsonRule(RuleBase): """ 检查tool_eval的输出结果是否符合对应的json schema """ def __init__(self, **kwargs): super().__init__() self.rule_name = 'ToolEvalOutputJsonRule' def _check_pre_format(self, outputs): invalid_details = [] if "content" not in outputs: invalid_details.append("ToolEval返回值不符合规范:返回内容缺少content") return invalid_details for content in outputs["content"]: if "type" not in content: invalid_details.append("ToolEval返回值不符合规范:返回content缺少type") break out_type = content["type"] if out_type not in type_to_json_schemas: invalid_details.append("ToolEval返回值不符合JSON Schema:返回content.type={} 不是合法的输出类型".format(out_type)) break return invalid_details def _check_jsonschema(self, outputs, output_schemas): """检查输出格式是否符合对应的json schema """ invalid_details = [] if len(self._check_pre_format(outputs)) > 0 : return invalid_details for content in outputs["content"]: out_type = content["type"] out_schema = type_to_json_schemas[out_type] if out_schema not in output_schemas: invalid_details.append("ToolEval返回值不符合JSON Schema:{} 不是该组件期望的Json Schema输出类型".format(out_schema['$schema'])) continue try: validate(instance=content, schema=out_schema) except Exception as e: invalid_details.append("ToolEval返回值不符合JSON Schema: {}\n".format(e.message)) return invalid_details def _gather_iter_outputs(self, outputs): text_output = "" oral_text_output = "" code_output = "" for content in outputs.content: out_type = content.type if out_type == "text": text_output += content.text.info elif out_type == "oral_text": oral_text_output += content.text.info elif out_type == "code": code_output += content.text.code return { "text": text_output, "oral_text": oral_text_output, "code": code_output, } def _check_text_and_code(self, component_case, output_dict): """检查输出的内容是否符合预期,只检查text(包含oral_text)和code """ if not hasattr(component_case,"outputs"): return [] expected_output = component_case.outputs() expected_output_texts = [] expected_output_oral_texts = [] expected_output_codes = [] if "text" in expected_output: expected_output_texts = expected_output["text"] if "oral_text" in expected_output: expected_output_oral_texts = expected_output["oral_text"] if "code" in expected_output: expected_output_codes = expected_output["code"] lost_texts = [] lost_oral_texts = [] lost_code = [] for expected_output_text in expected_output_texts: if expected_output_text not in output_dict["text"]: lost_texts.append(expected_output_text) for expected_output_oral_text in expected_output_oral_texts: if expected_output_oral_text not in output_dict["oral_text"]: lost_oral_texts.append(expected_output_oral_text) for expected_output_code in expected_output_codes: if expected_output_code not in output_dict["code"]: lost_code.append(expected_output_code) error_message = "" if len(lost_texts) > 0: error_message += "应包含text:{}".format(", ".join(lost_texts)) if len(lost_oral_texts) > 0: error_message += "应包含oral_text:{}".format(", ".join(lost_oral_texts)) if len(lost_code) > 0: error_message += "应包含code:{}".format(", ".join(lost_code)) if error_message != "": return ["ToolEval返回内容与预期不符: " + error_message] else: return [] def check(self, component_obj, component_case) -> CheckInfo: invalid_details = [] input_dict = component_case.inputs() output_json_schemas = component_case.schemas() try: stream_output_dict = {"text": "", "oral_text":"", "code": ""} stream_outputs = component_obj.tool_eval(**input_dict) for stream_output in stream_outputs: iter_invalid_detail = self._check_jsonschema(stream_output.model_dump(), output_json_schemas) invalid_details.extend(iter_invalid_detail) iter_output_dict = self._gather_iter_outputs(stream_output) stream_output_dict["text"] += iter_output_dict["text"] stream_output_dict["oral_text"] += iter_output_dict["oral_text"] stream_output_dict["code"] += iter_output_dict["code"] if len(invalid_details) == 0: invalid_details.extend(self._check_text_and_code(component_case, stream_output_dict)) except Exception as e: invalid_details.append("ToolEval执行失败: {}".format(e)) if len(invalid_details) > 0: return CheckInfo( check_rule_name=self.rule_name, check_result=False, check_detail=",".join(invalid_details)) else: return CheckInfo( check_rule_name=self.rule_name, check_result=True, check_detail="") def register_component_check_rule(rule_name: str, rule_cls: RuleBase): component_checker = ComponentCheckBase() component_checker.register_rule(rule_name, rule_cls()) def check_component_with_retry(component_import_res_tuple): """ 使用重试机制检查组件。测试用例失败后会重试两次。 Args: component_import_res_tuple (tuple): 包含组件和导入结果的元组。 Returns: list: 包含错误信息的数据列表。 """ component, import_res, component_case_cls = component_import_res_tuple component_check_base = ComponentCheckBase() if inspect.isclass(component): component_name = component.__name__ else: component_name = component error_data = [] max_retries = 2 # 设置最大重试次数 attempts = 0 while attempts <= max_retries: if import_res["import_error"] != "": error_data.append({"Component Name": component_name, "Error Message": import_res["import_error"]}) print("组件名称:{} 错误信息:{}".format(component_name, import_res["import_error"])) break component_case = component_case_cls() envs = component_case.envs() os.environ.update(envs) component_cls = import_res["obj"] component_obj = component_cls(**component_case.init_args()) try: # 此处的self.component_check_base.notify需要根据实际情况修改 pass_check, reasons = component_check_base.notify(component_obj, component_case) # 示例修改 reasons = list(set(reasons)) if not pass_check: error_data.append({"Component Name": component_name, "Error Message": ", ".join(reasons)}) print("组件名称:{} 错误信息:{}".format(component_name, ", ".join(reasons))) # 如果检查失败,增加尝试次数并重试 attempts += 1 if attempts <= max_retries: print("组件名称:{} 将重试,当前尝试次数:{}".format(component_name, attempts)) continue # 如果检查通过,则退出循环 break except Exception as e: error_data.append({"Component Name": component_name, "Error Message": str(e)}) print("组件名称:{} 错误信息:{}".format(component_name, str(e))) # 如果发生异常,增加尝试次数并重试 attempts += 1 if attempts <= max_retries: print("组件名称:{} 将重试,当前尝试次数:{}".format(component_name, attempts)) continue finally: for env in envs: os.environ.pop(env) return error_data def write_error_data(txt_file_path, error_df, error_stats): """将组件错误信息写入文件 Args: error_df (Union[pd.DataFrame, None]): 错误信息表格 error_stats (dict): 错误统计信息 """ with open(txt_file_path, 'w') as file: file.write("Component Name\tError Message\n") for _, row in error_df.iterrows(): file.write(f"{row['Component Name']}\t{row['Error Message']}\n") file.write("\n错误统计信息:\n") for error, count in error_stats.items(): file.write(f"错误信息: {error}, 出现次数: {count}\n") print(f"\n错误信息已写入: {txt_file_path}") register_component_check_rule("ManifestValidRule", ManifestValidRule) register_component_check_rule("MainfestMatchToolEvalRule", MainfestMatchToolEvalRule) register_component_check_rule("ToolEvalInputNameRule", ToolEvalInputNameRule) register_component_check_rule("ToolEvalOutputJsonRule", ToolEvalOutputJsonRule) register_component_check_rule("InitKwargsRule", InitKwargsRule) register_component_check_rule("ToolEvalKwargsRule", ToolEvalKwargsRule) ================================================ FILE: python/tests/component_collector.py ================================================ # Copyright (c) 2024 Baidu, Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import os import appbuilder # SKIP名单中的组件无需检查,直接跳过 SKIP_COMPONENTS = [ ] V2_SKIP_COMPONENTS = [ "ASR", "TreeMind", "Text2Image"# 偶现性报错,暂时跳过 ] # 白名单中的组件因历史原因,检查失败,但可以正常使用,因此加入白名单 COMPONENT_WHITE_LIST = [ "RagWithBaiduSearchPro", "RAGWithBaiduSearch", "MRC", "OralQueryGeneration", "QAPairMining", "SimilarQuestion", "StyleWriting", "StyleRewrite", "TagExtraction", "Nl2pandasComponent", "QueryRewrite", "DialogSummary", "HallucinationDetection", "Playground", "ASR", "GeneralOCR", "ObjectRecognition", "Text2Image", "LandmarkRecognition", "TTS", "ExtractTableFromDoc", "DocParser", "DocSplitter", "BESRetriever", "BESVectorStoreIndex", "BaiduVDBVectorStoreIndex", "BaiduVDBRetriever", "TableParams", "Reranker", "PPTGenerationFromInstruction", "PPTGenerationFromPaper", "PPTGenerationFromFile", "DishRecognition", "Translation", "AnimalRecognition", "DocCropEnhance", "QRcodeOCR", "TableOCR", "DocFormatConverter", "Embedding", "Matching", "NL2Sql", "SelectTable", "PlantRecognition", "HandwriteOCR", "ImageUnderstand", "MixCardOCR", "DocumentUnderstanding", "TreeMind" ] def get_component_white_list(): return COMPONENT_WHITE_LIST def get_components(components_list, import_prefix, skip_components): components = {} for component in components_list: if not isinstance(component, str): component = component.__name__ if component in skip_components: continue try: component_obj = eval(import_prefix+component) components[component]= { "obj": component_obj, "import_error": "" } except Exception as e: print("Component: {} import with error: {}".format(component, str(e))) components[component]= { "obj": None, "import_error": str(e) } return components def get_all_components(): from appbuilder import __COMPONENTS__ all_components = get_components(__COMPONENTS__, "appbuilder.", SKIP_COMPONENTS) return all_components def get_v2_components(): from appbuilder.core.components.v2 import __V2_COMPONENTS__ v2_components = get_components(__V2_COMPONENTS__, "appbuilder.core.components.v2.", V2_SKIP_COMPONENTS) return v2_components if __name__ == '__main__': all_components = get_all_components() v2_components = get_v2_components() print("all_components: ", all_components) print("v2_components: ", v2_components) ================================================ FILE: python/tests/component_schemas.py ================================================ import copy base_item_schema = { "$schema": "base iter template", "type": "object", "properties": { "type": { "type": "string" }, "name": { "type": "string" }, "text": { "type": "object" }, "visible_scope": { "enum": ["llm", "user", "all"] }, "raw_data": { "type": "object" }, "usage": { "type": "object", "properties": { "prompt_tokens": { "type": "integer" }, "completion_tokens": { "type": "integer" }, "total_tokens": { "type": "integer" }, "name": { "type": "string" } }, }, "metrics": { "type": "object", "properties": { "first_token_time(s)": { "type": "number" }, "total_time(s)": { "type": "number" }, "memory_used(MB)": { "type": "number" } } } }, "required": ["type", "text"] } text_schema = copy.deepcopy(base_item_schema) text_schema["$schema"] = "text_schema" text_schema["properties"]["type"] = { "type": "string", "enum": ["text"] } text_schema["properties"]["text"] = { "type": "object", "properties": { "info": { "type": "string" } }, "required": ["info"] } code_schema = copy.deepcopy(base_item_schema) code_schema["$schema"] = "code_schema" code_schema["properties"]["type"] = { "type": "string", "enum": ["code"] } code_schema["properties"]["text"] = { "type": "object", "properties": { "code": { "type": "string" } }, "required": ["code"] } file_schema = copy.deepcopy(base_item_schema) file_schema["$schema"] = "file_schema" file_schema["properties"]["type"] = { "type": "string", "enum": ["files"] } file_schema["properties"]["text"] = { "type": "object", "properties": { "filename": { "type": "string" }, "url": { "type": "string" } }, "required": ["filename", "url"] } url_schema = copy.deepcopy(base_item_schema) url_schema["$schema"] = "url_schema" url_schema["properties"]["type"] = { "type": "string", "enum": ["urls"] } url_schema["properties"]["text"] = { "type": "object", "properties": { "url": { "type": "string" } }, "required": ["url"] } oral_text_schema = copy.deepcopy(base_item_schema) oral_text_schema["$schema"] = "oral_text_schema" oral_text_schema["properties"]["type"] = { "type": "string", "enum": ["oral_text"] } oral_text_schema["properties"]["text"] = { "type": "object", "properties": { "info": { "type": "string" } }, "required": ["info"] } references_schema = copy.deepcopy(base_item_schema) references_schema["$schema"] = "references_schema" references_schema["properties"]["type"] = { "type": "string", "enum": ["references"] } references_schema["properties"]["text"] = { "type": "object", "properties": { "type": { "type": "string" }, "doc_id": { "type": "string" }, "content": { "type": "string" }, "title": { "type": "string" }, "source": { "type": "string" }, "extra": { "type": "object" } }, "required": ["type", "doc_id", "content", "title", "source"] } image_schema = copy.deepcopy(base_item_schema) image_schema["$schema"] = "image_schema" image_schema["properties"]["type"] = { "type": "string", "enum": ["image"] } image_schema["properties"]["text"] = { "type": "object", "properties": { "filename": { "type": "string" }, "url": { "type": "string" }, "base64": { "type": "string" } }, "required": ["filename", "url"] } chart_schema = copy.deepcopy(base_item_schema) chart_schema["$schema"] = "chart_schema" chart_schema["properties"]["type"] = { "type": "string", "enum": ["chart"] } chart_schema["properties"]["text"] = { "type": "object", "properties": { "type": { "type": "string" }, "data": { "type": "string" } }, "required": ["type", "data"] } audio_schema = copy.deepcopy(base_item_schema) audio_schema["$schema"] = "audio_schema" audio_schema["properties"]["type"] = { "type": "string", "enum": ["audio"] } audio_schema["properties"]["text"] = { "type": "object", "properties": { "filename": { "type": "string" }, "url": { "type": "string" }, "base64": { "type": "string" } }, "required": ["filename", "url"] } json_schema = copy.deepcopy(base_item_schema) json_schema["$schema"] = "json_schema" json_schema["properties"]["type"] = { "type": "string", "enum": ["json"] } json_schema["properties"]["text"] = { "type": "object", "properties": { "data": { "type": "string" } }, "required": ["data"] } plan_schema = copy.deepcopy(base_item_schema) plan_schema["$schema"] = "plan_schema" plan_schema["properties"]["type"] = { "type": "string", "enum": ["plan"] } plan_schema["properties"]["text"] = { "type": "object", "properties": { "detail": { "type": "string" }, "steps": { "type": "array", "items": { "type": "object", "properties": { "name": {"type": "string"}, "arguments": { "type": "object", "additionalProperties": True } }, "required": ["name", "arguments"] } } }, "required": ["detail", "steps"] } function_call_schema = copy.deepcopy(base_item_schema) function_call_schema["$schema"] = "function_call_schema" function_call_schema["properties"]["type"] = { "type": "string", "enum": ["function_call"] } function_call_schema["properties"]["text"] = { "type": "object", "properties": { "thought": { "type": "string" }, "name": { "type": "string", }, "arguments": { "type": "object", "additionalProperties": True } }, "required": ["thought", "name", "arguments"], } type_to_json_schemas = { "text": text_schema, 'code': code_schema, "files": file_schema, "urls": url_schema, "oral_text": oral_text_schema, "references": references_schema, "image": image_schema, "chart": chart_schema, "audio": audio_schema, "json": json_schema, "plan": plan_schema, "function_call": function_call_schema, } ================================================ FILE: python/tests/component_tool_eval_cases.py ================================================ # Copyright (c) 2023 Baidu, Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from appbuilder.core.component import Component from appbuilder.tests.component_schemas import text_schema, url_schema, image_schema, code_schema, file_schema, \ oral_text_schema, references_schema, chart_schema, audio_schema, plan_schema, function_call_schema class Case(): def init_args(self): return {} def inputs(self): return NotImplementedError() def outputs(self): return {} def schemas(self): return NotImplementedError() def envs(self): return {} class AnimalRecognitionCase(Case): def inputs(self): return { "img_name": "", "img_url": "https://bj.bcebos.com/v1/appbuilder/animal_recognize_test.png?" \ "authorization=bce-auth-v1%2FALTAKGa8m4qCUasgoljdEDAzLm%2F2024-01-24T" \ "12%3A19%3A16Z%2F-1%2Fhost%2F411bad53034fa8f9c6edbe5c4909d76ecf6fad68" \ "62cf937c03f8c5260d51c6ae" } def outputs(self): return {"text": ["熊猫"]} def schemas(self): return [text_schema] class ASRCase(Case): def inputs(self): return { "file_url": "https://bj.bcebos.com/v1/appbuilder/asr_test.pcm?authorization=bce-auth-v1" \ "%2FALTAKGa8m4qCUasgoljdEDAzLm%2F2024-01-11T10%3A56%3A41Z%2F-1%2Fhost" \ "%2Fa6c4d2ca8a3f0259f4cae8ae3fa98a9f75afde1a063eaec04847c99ab7d1e411" } def outputs(self): return {"text": ["北京科技馆"]} def schemas(self): return [text_schema] class TreeMindCase(Case): def inputs(self): return {"query": "生成一份年度总结的思维导图"} def schemas(self): return [text_schema, url_schema] class ImageUnderstandCase(Case): def inputs(self): return { "img_url": "https://bj.bcebos.com/v1/appbuilder/animal_recognize_test.png?" \ "authorization=bce-auth-v1%2FALTAKGa8m4qCUasgoljdEDAzLm%2F2024-01-24T" \ "12%3A19%3A16Z%2F-1%2Fhost%2F411bad53034fa8f9c6edbe5c4909d76ecf6fad68" \ "62cf937c03f8c5260d51c6ae", "img_name": "test_img.jpg" } def outputs(self): return {"text": ["熊猫"]} def schemas(self): return [text_schema] class Text2ImageCase(Case): def inputs(self): return {"query": "生成一张熊猫图片"} def schemas(self): return [url_schema] class StyleRewriteCase(Case): def init_args(self): return {"model": "DeepSeek-V3.1"} def inputs(self): return {"query": "文心大模型发布新版"} def schemas(self): return [text_schema] class QRcodeOCRCase(Case): def inputs(self): image_url = "https://bj.bcebos.com/v1/appbuilder/qrcode_ocr_test.png?" \ "authorization=bce-auth-v1%2FALTAKGa8m4qCUasgoljdEDAzLm%2F2024-" \ "01-24T12%3A45%3A13Z%2F-1%2Fhost%2Ffc43d07b41903aeeb5a023131ba6" \ "e74ab057ce26d50e966dc31ff083e6a9c41b" return { "file_names": ["text"], "_sys_file_urls": {"text": image_url} } def schemas(self): return [text_schema] def outputs(self): return {"text": ["ocr文字识别"]} class HallucinationDetectionCase(Case): def init_args(self): return {"model": "DeepSeek-V3.1"} def inputs(self): return { "query": '澳门新麻蒲烤肉店每天开门吗?', "context": ('澳门美食: 澳门新麻蒲韩国烤肉店\n' '在澳门一年四季之中除了火锅,烤肉也相当受欢迎。提到韩烧,有一间令我印象最深刻,就是号称韩国第一的烤肉店-新麻蒲韩国烤肉店,光是韩国的分店便多' '达四百多间,海外分店更是遍布世界各地,2016年便落户澳门筷子基区,在原本已经食肆林立的地方一起百花齐放!店内的装修跟韩国分店还完度几乎没差,让' '食客彷如置身于韩国的感觉,还要大赞其抽风系统不俗,离开时身上都不会沾上烤肉味耶!\n' '时间:周一至周日 下午5:00 - 上午3:00\n' '电话:+853 2823 4012\n' '地址:澳门筷子基船澳街海擎天第三座地下O号铺96号\n' '必食推介:\n' '护心肉二人套餐\n' '来新麻蒲必试的有两样东西,现在差不多每间烤肉店都有炉边烤蛋,但大家知道吗?原来新麻蒲就是炉边烤蛋的开创者,既然是始祖,这已经是个非吃不可的理' '由!还有一款必试的就是护心肉,即是猪的横隔膜与肝中间的部分,每头猪也只有200克这种肉,非常珍贵,其味道吃起来有种独特的肉香味,跟牛护心肉一样' '精彩!\n' '秘制猪皮\n' '很多怕胖的女生看到猪皮就怕怕,但其实猪皮含有大量胶原蛋白,营养价值很高呢!这里红通通的猪皮还经过韩国秘制酱汁处理过,会有一点点辣味。烤猪皮的' '时候也需特别注意火侯,这样吃起来才会有外脆内Q的口感!'), "answer": '澳门新麻蒲烤肉店并不是每天开门,周日休息。' } def schemas(self): return [text_schema] def outputs(self): return {"text": ["存在幻觉"]} class HandWriteOCRCase(Case): def inputs(self): image_url = "https://bj.bcebos.com/v1/appbuilder/test_handw" \ "rite_ocr.jpg?authorization=bce-auth-v1%2FALTAKGa8" \ "m4qCUasgoljdEDAzLm%2F2024-01-23T11%3A58%3A09Z%2F-1%2Fhost%2" \ "F677f93445fb65157bee11cd492ce213d5c56e7a41827e45ce7e32b083d195c8b" return { "file_names": ["text"], "_sys_file_urls": {"text": image_url} } def schemas(self): return [text_schema] def outputs(self): return {"text": ["银杏树"]} class MixCardOCRCase(Case): def inputs(self): image_url = ("https://bj.bcebos.com/v1/appbuilder/test_mix_card_ocr.jpeg?" "authorization=bce-auth-v1%2FALTAKGa8m4qCUasgoljdEDAzLm%2F2024-01-24T06" "%3A18%3A11Z%2F-1%2Fhost%2F695b8041c1ded194b9e80dbe" "1865e4393da5a3515e90d72d81ef18296bd29598") return { "file_names": ["test"], "_sys_file_urls": {"test": image_url} } def schemas(self): return [text_schema] def outputs(self): return {"text": ["北京市公安局"]} class TranslationCase(Case): def inputs(self): return { "q": "你好", "to_lang": "en", } def schemas(self): return [text_schema] def outputs(self): return {"text": ["hello"]} class GeneralOCRCase(Case): def inputs(self): return { "img_url": "https://bj.bcebos.com/v1/appbuilder/general_ocr_test.png?" \ "authorization=bce-auth-v1%2FALTAKGa8m4qCUasgoljdEDAzLm%2F2024-01-" \ "11T10%3A59%3A17Z%2F-1%2Fhost%2F081bf7bcccbda5207c82a4de074628b04ae" \ "857a27513734d765495f89ffa5f73", "img_name": "test_img.jpg" } def outputs(self): return {"text": ["识别结果"]} def schemas(self): return [text_schema] class TableOCRCase(Case): def inputs(self): image_url = "https://bj.bcebos.com/v1/appbuilder/table_ocr_test.png?" \ "authorization=bce-auth-v1%2FALTAKGa8m4qCUasgoljdEDAzLm%2F2024-01-24T12%3A37%3A09Z%2F-1%2Fhost%2Fab528a5a9120d328dc6d18c6" \ "064079145ff4698856f477b820147768fc2187d3" return { "file_names": [image_url] } def schemas(self): return [text_schema] def outputs(self): return {"text": ["http"]} class Text2ImageCase(Case): def inputs(self): return { 'query': '生成一张小猫图片', } def schemas(self): return [image_schema] class StyleWritingCase(Case): def init_args(self): return {"model": "DeepSeek-V3.1"} def inputs(self): return { "query": "帮我写一篇关于足球的文案", "style": "小红书", "length": 100, } def schemas(self): return [text_schema] def outputs(self): return {"text": ["足球"]} class TreeMindCase(Case): def inputs(self): return { "query": "生成一份年度总结的思维导图" } def schemas(self): return [text_schema, url_schema, image_schema] class PlantRecognitionCase(Case): def inputs(self): img_url = "https://bj.bcebos.com/v1/appbuilder/animal_recognize_test.png?" \ "authorization=bce-auth-v1%2FALTAKGa8m4qCUasgoljdEDAzLm%2F2024-01-24T" \ "12%3A19%3A16Z%2F-1%2Fhost%2F411bad53034fa8f9c6edbe5c4909d76ecf6fad68" \ "62cf937c03f8c5260d51c6ae" img_name = "test_img.jpg" return { "img_url": img_url, "img_name": img_name } def schemas(self): return [text_schema] def outputs(self): return {"text": ["非植物"]} class ASRCase(Case): def inputs(self): audio_file_url = "https://bj.bcebos.com/v1/appbuilder/asr_test.pcm?authorization=bce-auth-v1" \ "%2FALTAKGa8m4qCUasgoljdEDAzLm%2F2024-01-11T10%3A56%3A41Z%2F-1%2Fhost" \ "%2Fa6c4d2ca8a3f0259f4cae8ae3fa98a9f75afde1a063eaec04847c99ab7d1e411" return { "file_url": audio_file_url } def schemas(self): return [text_schema] def outputs(self): return {"text": ["北京科技馆"]} class ObjectRecognitionCase(Case): def inputs(self): img_url = "https://bj.bcebos.com/v1/appbuilder/object_recognize_test.png?" \ "authorization=bce-auth-v1%2FALTAKGa8m4qCUasgoljdEDAzLm%2F2024-01-" \ "11T11%3A00%3A19Z%2F-1%2Fhost%2F2c31bf29205f61e58df661dc80af31a1dc" \ "1ba1de0a8f072bc5a87102bd32f9e3" return { "img_url": img_url } def schemas(self): return [text_schema] def outputs(self): return {"text": ["苹果"]} class SimilarQuestionCase(Case): def init_args(self): return {"model": "DeepSeek-V3.1"} def inputs(self): return { "query": "我想吃冰淇淋,哪里的冰淇淋比较好吃?" } def schemas(self): return [text_schema] def outputs(self): return {"text": ["冰淇淋"]} class OralQueryGenerationCase(Case): def init_args(self): return {"model": "DeepSeek-V3.1"} def inputs(self): text = ('文档标题:在OPPO Reno5上使用视频超级防抖\n' '文档摘要:OPPO Reno5上的视频超级防抖,视频超级防抖3.0,多代视频防抖算法积累,这一代依旧超级防抖超级稳。 开启视频超级' '防抖 开启路径:打开「相机 > 视频 > 点击屏幕上方的“超级防抖”标识」 后置视频同时支持超级防抖和超级防抖Pro功能,开启超级' '防抖后手机屏幕将出现超级防抖Pro开关,点击即可开启或关闭。 除此之外,前置视频同样加持防抖算法,边走边拍也能稳定聚焦脸部' ',实时视频分享您的生活。') return { "text": text } def schemas(self): return [text_schema] def outputs(self): return {"text": ["OPPO"]} class QueryRewriteCase(Case): def init_args(self): return {"model": "DeepSeek-V3.1"} def inputs(self): return { "query": "我想吃冰淇淋,哪里的冰淇淋比较好吃?", "rewrite_type": "带机器人回复" } def schemas(self): return [text_schema] def outputs(self): return {"text": ["冰淇淋"]} class Nl2pandasComponentCase(Case): def init_args(self): return {"model": "DeepSeek-V3.1"} def inputs(self): return { "query": "给我一份2020年到2022年每年的销售额", "table_info": '''表格列信息如下: 学校名 : 清华附小 , 字符串类型,代表小学学校的名称 所属地区 : 西城区 , 字符串类型,表示该小学学校所在的位置 创办时间 : 1998 , 数字值类型,表示该小学学校的创办时间 类别 : 公立小学 , 字符串类型,表示该小学学校所在的类别 学生人数 : 2000 , 数字值类型,表示该小学学校的学生数量 教职工人数 : 140 , 数字值类型,表示该小学学校的教职工数量 教学班数量 : 122 , 数字值类型,表示该小学学校的教学班数量 ''' } def schemas(self): return [text_schema] class DialogSummaryCase(Case): def init_args(self): return {"model": "DeepSeek-V3.1"} def inputs(self): return { "query": "请给我总结一下这段对话", } def schemas(self): return [text_schema] class MRCCase(Case): def init_args(self): return {"model": "DeepSeek-V3.1"} def inputs(self): return { "query": "残疾人怎么办相关证件", "context_list": [ """如何办理残疾人通行证一、残疾人通行证办理条件: 1、持有中华人民共和国残疾人证,下肢残疾或者听力残疾; 2、持有准驾车型为C1(听力残疾)、C2(左下肢残疾、听力残疾)、C5(右下肢、双下肢残疾)的机动车驾驶证, 听力残疾人驾驶证须有“驾驶机动车应佩戴助听设备”的批注(批注请到各车管分所办理);""", """3、本人拥有本市登记核发的非营运小型载客汽车,车辆须在检验有效期内,并有有效交强险凭证, C5车辆加装操纵辅助装置后已办理变更手续。二、办理地点:北京市朝阳区左家庄北里35号: 北京市无障碍环境建设促进中心(北京市残疾人辅助器具资源中心),咨询电话:63547715 或68397831。三、所需材料:1、 有效的身份证明原件和复印件;2、残疾人证原件和复印件;3、驾驶证原件和复印件; 4、车辆行驶证原件和复印件;5、有效的机动车交强险凭证。""" ] } def schemas(self): return [text_schema] class IsComplexQueryCase(Case): def init_args(self): return {"model": "DeepSeek-V3.1"} def inputs(self): return { "query": "吸塑包装盒在工业化生产和物流运输中分别有什么重要性?", } def schemas(self): return [text_schema] def outputs(self): return {"text": ["复杂问题"]} class QAPairMiningCase(Case): def init_args(self): return {"model": "DeepSeek-V3.1"} def inputs(self): return { "query": "2017年,工商银行根据外部宏观环境变化...", } def schemas(self): return [text_schema] class QueryDecompositionCase(Case): def init_args(self): return {"model": "DeepSeek-V3.1"} def inputs(self): return { "query": "吸塑包装盒在工业化生产和物流运输中分别有什么重要性?", } def schemas(self): return [text_schema] class TagExtractionCase(Case): def init_args(self): return {"model": "DeepSeek-V3.1"} def inputs(self): return { "query": "本实用新型公开了一种可利用热能的太阳能光伏光热一体化组件,包括太阳能电池,还包括有吸热板,太阳能电池粘附在吸热板顶面,吸热板内嵌入有热电材料制成的内芯,吸热板底面设置有蛇形管。本实用新型结构紧凑,安装方便,能充分利用太阳能电池散发的热能,具有较高的热能利用率。", } def schemas(self): return [text_schema] component_tool_eval_cases = { "AnimalRecognition": AnimalRecognitionCase, "ImageUnderstand": ImageUnderstandCase, "ASR": ASRCase, "TreeMind": TreeMindCase, "StyleRewrite": StyleRewriteCase, "HallucinationDetection": HallucinationDetectionCase, "QRcodeOCR": QRcodeOCRCase, "HandwriteOCR": HandWriteOCRCase, "MixCardOCR": MixCardOCRCase, "Translation": TranslationCase, "GeneralOCR": GeneralOCRCase, "TableOCR": TableOCRCase, "Text2Image": Text2ImageCase, "StyleWriting": StyleWritingCase, "TreeMind": TreeMindCase, "PlantRecognition": PlantRecognitionCase, "ASR": ASRCase, "ObjectRecognition": ObjectRecognitionCase, "SimilarQuestion": SimilarQuestionCase, "OralQueryGeneration": OralQueryGenerationCase, "QueryRewrite": QueryRewriteCase, "Nl2pandasComponent": Nl2pandasComponentCase, "DialogSummary": DialogSummaryCase, "MRC": MRCCase, "IsComplexQuery": IsComplexQueryCase, "QAPairMining": QAPairMiningCase, "QueryDecomposition": QueryDecompositionCase, "TagExtraction": TagExtractionCase, } ================================================ FILE: python/tests/data/ghes-3.0.json ================================================ { "openapi": "3.1.0", "info": { "version": "1.1.4", "title": "GitHub v3 REST API", "description": "GitHub's v3 REST API.", "license": { "name": "MIT", "url": "https://spdx.org/licenses/MIT" }, "termsOfService": "https://docs.github.com/articles/github-terms-of-service", "contact": { "name": "Support", "url": "https://support.github.com/contact?tags=dotcom-rest-api" } }, "tags": [ { "name": "actions", "description": "Endpoints to manage GitHub Actions using the REST API." }, { "name": "activity", "description": "Activity APIs provide access to notifications, subscriptions, and timelines." }, { "name": "apps", "description": "Information for integrations and installations." }, { "name": "billing", "description": "Monitor charges and usage from Actions and Packages." }, { "name": "checks", "description": "Rich interactions with checks run by your integrations." }, { "name": "code-scanning", "description": "Retrieve code scanning alerts from a repository." }, { "name": "codes-of-conduct", "description": "Insight into codes of conduct for your communities." }, { "name": "codespaces", "description": "Endpoints to manage Codespaces using the REST API." }, { "name": "emojis", "description": "List emojis available to use on GitHub." }, { "name": "enterprise-admin", "description": "Administer a GitHub enterprise." }, { "name": "dependabot", "description": "Endpoints to manage Dependabot." }, { "name": "gists", "description": "View, modify your gists." }, { "name": "git", "description": "Raw Git functionality." }, { "name": "gitignore", "description": "View gitignore templates" }, { "name": "interactions", "description": "Owner or admin management of users interactions." }, { "name": "issues", "description": "Interact with GitHub Issues." }, { "name": "licenses", "description": "View various OSS licenses." }, { "name": "markdown", "description": "Render GitHub flavored markdown" }, { "name": "meta", "description": "Endpoints that give information about the API." }, { "name": "migrations", "description": "Move projects to or from GitHub." }, { "name": "oauth-authorizations", "description": "Manage access of OAuth applications" }, { "name": "orgs", "description": "Interact with GitHub Orgs." }, { "name": "packages", "description": "Manage packages for authenticated users and organizations." }, { "name": "projects", "description": "Interact with GitHub Projects." }, { "name": "pulls", "description": "Interact with GitHub Pull Requests." }, { "name": "rate-limit", "description": "Check your current rate limit status" }, { "name": "reactions", "description": "Interact with reactions to various GitHub entities." }, { "name": "repos", "description": "Interact with GitHub Repos." }, { "name": "scim", "description": "Provisioning of GitHub organization membership for SCIM-enabled providers." }, { "name": "search", "description": "Look for stuff on GitHub." }, { "name": "secret-scanning", "description": "Retrieve secret scanning alerts from a repository." }, { "name": "server-statistics", "description": "GHES statistics" }, { "name": "teams", "description": "Interact with GitHub Teams." }, { "name": "users", "description": "Interact with and view information about users and also current user." } ], "servers": [ { "url": "{protocol}://{hostname}/api/v3", "variables": { "hostname": { "description": "Self-hosted Enterprise Server or Enterprise Cloud hostname", "default": "HOSTNAME" }, "protocol": { "description": "Self-hosted Enterprise Server or Enterprise Cloud protocol", "default": "http" } } } ], "externalDocs": { "description": "GitHub Enterprise Developer Docs", "url": "https://docs.github.com/enterprise-server@3.0/rest/" }, "paths": { "/": { "get": { "summary": "GitHub API Root", "description": "Get Hypermedia links to resources accessible in GitHub's REST API", "tags": [ "meta" ], "operationId": "meta/root", "responses": { "200": { "description": "Response", "content": { "application/json": { "schema": { "type": "object", "properties": { "current_user_url": { "type": "string", "format": "uri-template" }, "current_user_authorizations_html_url": { "type": "string", "format": "uri-template" }, "authorizations_url": { "type": "string", "format": "uri-template" }, "code_search_url": { "type": "string", "format": "uri-template" }, "commit_search_url": { "type": "string", "format": "uri-template" }, "emails_url": { "type": "string", "format": "uri-template" }, "emojis_url": { "type": "string", "format": "uri-template" }, "events_url": { "type": "string", "format": "uri-template" }, "feeds_url": { "type": "string", "format": "uri-template" }, "followers_url": { "type": "string", "format": "uri-template" }, "following_url": { "type": "string", "format": "uri-template" }, "gists_url": { "type": "string", "format": "uri-template" }, "hub_url": { "type": "string", "format": "uri-template" }, "issue_search_url": { "type": "string", "format": "uri-template" }, "issues_url": { "type": "string", "format": "uri-template" }, "keys_url": { "type": "string", "format": "uri-template" }, "label_search_url": { "type": "string", "format": "uri-template" }, "notifications_url": { "type": "string", "format": "uri-template" }, "organization_url": { "type": "string", "format": "uri-template" }, "organization_repositories_url": { "type": "string", "format": "uri-template" }, "organization_teams_url": { "type": "string", "format": "uri-template" }, "public_gists_url": { "type": "string", "format": "uri-template" }, "rate_limit_url": { "type": "string", "format": "uri-template" }, "repository_url": { "type": "string", "format": "uri-template" }, "repository_search_url": { "type": "string", "format": "uri-template" }, "current_user_repositories_url": { "type": "string", "format": "uri-template" }, "starred_url": { "type": "string", "format": "uri-template" }, "starred_gists_url": { "type": "string", "format": "uri-template" }, "topic_search_url": { "type": "string", "format": "uri-template" }, "user_url": { "type": "string", "format": "uri-template" }, "user_organizations_url": { "type": "string", "format": "uri-template" }, "user_repositories_url": { "type": "string", "format": "uri-template" }, "user_search_url": { "type": "string", "format": "uri-template" } }, "required": [ "current_user_url", "current_user_authorizations_html_url", "authorizations_url", "code_search_url", "commit_search_url", "emails_url", "emojis_url", "events_url", "feeds_url", "followers_url", "following_url", "gists_url", "hub_url", "issue_search_url", "issues_url", "keys_url", "label_search_url", "notifications_url", "organization_url", "organization_repositories_url", "organization_teams_url", "public_gists_url", "rate_limit_url", "repository_url", "repository_search_url", "current_user_repositories_url", "starred_url", "starred_gists_url", "user_url", "user_organizations_url", "user_repositories_url", "user_search_url" ] } } } } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": true, "category": "meta" }, "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/overview/resources-in-the-rest-api#root-endpoint" } } }, "/admin/hooks": { "get": { "summary": "List global webhooks", "description": "", "operationId": "enterprise-admin/list-global-webhooks", "tags": [ "enterprise-admin" ], "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/enterprise-admin#list-global-webhooks" }, "parameters": [ { "name": "accept", "description": "This API is under preview and subject to change.", "in": "header", "schema": { "type": "string", "default": "application/vnd.github.superpro-preview+json" }, "required": true }, { "$ref": "#/components/parameters/per-page" }, { "$ref": "#/components/parameters/page" } ], "responses": { "200": { "description": "Response", "content": { "application/json": { "schema": { "type": "array", "items": { "$ref": "#/components/schemas/global-hook" } }, "examples": { "default": { "$ref": "#/components/examples/global-hook-items" } } } }, "headers": { "Link": { "$ref": "#/components/headers/link" } } } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": false, "category": "enterprise-admin", "subcategory": "global-webhooks", "previews": [ { "required": true, "name": "superpro", "note": "The [Global Webhooks API](https://docs.github.com/enterprise-server@3.0/rest/reference/enterprise-admin#global-webhooks) is currently available for developers to preview. To access the API during the preview period, you must provide a custom [media type](https://docs.github.com/enterprise-server@3.0/rest/overview/media-types) in the `Accept` header:\n```shell\napplication/vnd.github.superpro-preview+json\n```" } ] } }, "post": { "summary": "Create a global webhook", "description": "", "operationId": "enterprise-admin/create-global-webhook", "tags": [ "enterprise-admin" ], "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/enterprise-admin#create-a-global-webhook" }, "responses": { "201": { "description": "Response", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/global-hook" }, "examples": { "default": { "$ref": "#/components/examples/global-hook" } } } } } }, "requestBody": { "required": true, "content": { "application/json": { "schema": { "type": "object", "properties": { "name": { "type": "string", "description": "Must be passed as \"web\"." }, "config": { "type": "object", "description": "Key/value pairs to provide settings for this webhook.", "properties": { "url": { "type": "string", "description": "The URL to which the payloads will be delivered." }, "content_type": { "type": "string", "description": "The media type used to serialize the payloads. Supported values include `json` and `form`. The default is `form`." }, "secret": { "type": "string", "description": "If provided, the `secret` will be used as the `key` to generate the HMAC hex digest value in the [`X-Hub-Signature`](https://docs.github.com/enterprise-server@3.0/webhooks/event-payloads/#delivery-headers) header." }, "insecure_ssl": { "type": "string", "description": "Determines whether the SSL certificate of the host for `url` will be verified when delivering payloads. Supported values include `0` (verification is performed) and `1` (verification is not performed). The default is `0`. **We strongly recommend not setting this to `1` as you are subject to man-in-the-middle and other attacks.**" } }, "required": [ "url" ] }, "events": { "type": "array", "description": "The [events](https://docs.github.com/enterprise-server@3.0/webhooks/event-payloads) that trigger this webhook. A global webhook can be triggered by `user` and `organization` events. Default: `user` and `organization`.", "items": { "type": "string" } }, "active": { "type": "boolean", "description": "Determines if notifications are sent when the webhook is triggered. Set to `true` to send notifications.", "default": true } }, "required": [ "name", "config" ] }, "example": { "name": "web", "events": [ "organization", "user" ], "config": { "url": "https://example.com/webhook", "content_type": "json", "secret": "secret" } } } } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": false, "category": "enterprise-admin", "subcategory": "global-webhooks", "previews": [ { "required": true, "name": "superpro", "note": "The [Global Webhooks API](https://docs.github.com/enterprise-server@3.0/rest/reference/enterprise-admin#global-webhooks) is currently available for developers to preview. To access the API during the preview period, you must provide a custom [media type](https://docs.github.com/enterprise-server@3.0/rest/overview/media-types) in the `Accept` header:\n```shell\napplication/vnd.github.superpro-preview+json\n```" } ] }, "parameters": [ { "name": "accept", "description": "This API is under preview and subject to change.", "in": "header", "schema": { "type": "string", "default": "application/vnd.github.superpro-preview+json" }, "required": true } ] } }, "/admin/hooks/{hook_id}": { "get": { "summary": "Get a global webhook", "description": "", "operationId": "enterprise-admin/get-global-webhook", "tags": [ "enterprise-admin" ], "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/enterprise-admin#get-a-global-webhook" }, "parameters": [ { "name": "accept", "description": "This API is under preview and subject to change.", "in": "header", "schema": { "type": "string", "default": "application/vnd.github.superpro-preview+json" }, "required": true }, { "$ref": "#/components/parameters/hook-id" } ], "responses": { "200": { "description": "Response", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/global-hook" }, "examples": { "default": { "$ref": "#/components/examples/global-hook" } } } } } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": false, "category": "enterprise-admin", "subcategory": "global-webhooks", "previews": [ { "required": true, "name": "superpro", "note": "The [Global Webhooks API](https://docs.github.com/enterprise-server@3.0/rest/reference/enterprise-admin#global-webhooks) is currently available for developers to preview. To access the API during the preview period, you must provide a custom [media type](https://docs.github.com/enterprise-server@3.0/rest/overview/media-types) in the `Accept` header:\n```shell\napplication/vnd.github.superpro-preview+json\n```" } ] } }, "patch": { "summary": "Update a global webhook", "description": "Parameters that are not provided will be overwritten with the default value or removed if no default exists.", "operationId": "enterprise-admin/update-global-webhook", "tags": [ "enterprise-admin" ], "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/enterprise-admin#update-a-global-webhook" }, "parameters": [ { "name": "accept", "description": "This API is under preview and subject to change.", "in": "header", "schema": { "type": "string", "default": "application/vnd.github.superpro-preview+json" }, "required": true }, { "$ref": "#/components/parameters/hook-id" } ], "responses": { "200": { "description": "Response", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/global-hook-2" }, "examples": { "default": { "$ref": "#/components/examples/global-hook-2" } } } } } }, "requestBody": { "content": { "application/json": { "schema": { "type": "object", "properties": { "config": { "type": "object", "description": "Key/value pairs to provide settings for this webhook.", "properties": { "url": { "type": "string", "description": "The URL to which the payloads will be delivered." }, "content_type": { "type": "string", "description": "The media type used to serialize the payloads. Supported values include `json` and `form`. The default is `form`." }, "secret": { "type": "string", "description": "If provided, the `secret` will be used as the `key` to generate the HMAC hex digest value in the [`X-Hub-Signature`](https://docs.github.com/enterprise-server@3.0/webhooks/event-payloads/#delivery-headers) header." }, "insecure_ssl": { "type": "string", "description": "Determines whether the SSL certificate of the host for `url` will be verified when delivering payloads. Supported values include `0` (verification is performed) and `1` (verification is not performed). The default is `0`. **We strongly recommend not setting this to `1` as you are subject to man-in-the-middle and other attacks.**" } }, "required": [ "url" ] }, "events": { "type": "array", "description": "The [events](https://docs.github.com/enterprise-server@3.0/webhooks/event-payloads) that trigger this webhook. A global webhook can be triggered by `user` and `organization` events. Default: `user` and `organization`.", "items": { "type": "string" } }, "active": { "type": "boolean", "description": "Determines if notifications are sent when the webhook is triggered. Set to `true` to send notifications.", "default": true } } }, "example": { "events": [ "organization" ], "config": { "url": "https://example.com/webhook" } } } } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": false, "category": "enterprise-admin", "subcategory": "global-webhooks", "previews": [ { "required": true, "name": "superpro", "note": "The [Global Webhooks API](https://docs.github.com/enterprise-server@3.0/rest/reference/enterprise-admin#global-webhooks) is currently available for developers to preview. To access the API during the preview period, you must provide a custom [media type](https://docs.github.com/enterprise-server@3.0/rest/overview/media-types) in the `Accept` header:\n```shell\napplication/vnd.github.superpro-preview+json\n```" } ] } }, "delete": { "summary": "Delete a global webhook", "description": "", "operationId": "enterprise-admin/delete-global-webhook", "tags": [ "enterprise-admin" ], "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/enterprise-admin#delete-a-global-webhook" }, "parameters": [ { "name": "accept", "description": "This API is under preview and subject to change.", "in": "header", "schema": { "type": "string", "default": "application/vnd.github.superpro-preview+json" }, "required": true }, { "$ref": "#/components/parameters/hook-id" } ], "responses": { "204": { "description": "Response" } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": false, "category": "enterprise-admin", "subcategory": "global-webhooks", "previews": [ { "required": true, "name": "superpro", "note": "The [Global Webhooks API](https://docs.github.com/enterprise-server@3.0/rest/reference/enterprise-admin#global-webhooks) is currently available for developers to preview. To access the API during the preview period, you must provide a custom [media type](https://docs.github.com/enterprise-server@3.0/rest/overview/media-types) in the `Accept` header:\n```shell\napplication/vnd.github.superpro-preview+json\n```" } ] } } }, "/admin/hooks/{hook_id}/pings": { "post": { "summary": "Ping a global webhook", "description": "This will trigger a [ping event](https://docs.github.com/enterprise-server@3.0/webhooks/#ping-event) to be sent to the webhook.", "operationId": "enterprise-admin/ping-global-webhook", "tags": [ "enterprise-admin" ], "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/enterprise-admin#ping-a-global-webhook" }, "parameters": [ { "name": "accept", "description": "This API is under preview and subject to change.", "in": "header", "schema": { "type": "string", "default": "application/vnd.github.superpro-preview+json" }, "required": true }, { "$ref": "#/components/parameters/hook-id" } ], "responses": { "204": { "description": "Response" } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": false, "category": "enterprise-admin", "subcategory": "global-webhooks", "previews": [ { "required": true, "name": "superpro", "note": "The [Global Webhooks API](https://docs.github.com/enterprise-server@3.0/rest/reference/enterprise-admin#global-webhooks) is currently available for developers to preview. To access the API during the preview period, you must provide a custom [media type](https://docs.github.com/enterprise-server@3.0/rest/overview/media-types) in the `Accept` header:\n```shell\napplication/vnd.github.superpro-preview+json\n```" } ] } } }, "/admin/keys": { "get": { "summary": "List public keys", "description": "", "operationId": "enterprise-admin/list-public-keys", "tags": [ "enterprise-admin" ], "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/enterprise-admin#list-public-keys" }, "parameters": [ { "$ref": "#/components/parameters/per-page" }, { "$ref": "#/components/parameters/page" }, { "$ref": "#/components/parameters/direction" }, { "name": "sort", "in": "query", "required": false, "schema": { "type": "string", "enum": [ "created", "updated", "accessed" ], "default": "created" } }, { "name": "since", "description": "Only show public keys accessed after the given time.", "in": "query", "required": false, "schema": { "type": "string" } } ], "responses": { "200": { "description": "Response", "content": { "application/json": { "schema": { "type": "array", "items": { "$ref": "#/components/schemas/public-key-full" } }, "examples": { "default": { "$ref": "#/components/examples/enterprise-public-key-items" } } } }, "headers": { "Link": { "$ref": "#/components/headers/link" } } } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": false, "category": "enterprise-admin", "subcategory": "users" } } }, "/admin/keys/{key_ids}": { "delete": { "summary": "Delete a public key", "description": "", "operationId": "enterprise-admin/delete-public-key", "tags": [ "enterprise-admin" ], "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/enterprise-admin#delete-a-public-key" }, "parameters": [ { "$ref": "#/components/parameters/key-ids" } ], "responses": { "204": { "description": "Response" } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": false, "category": "enterprise-admin", "subcategory": "users" } } }, "/admin/ldap/teams/{team_id}/mapping": { "patch": { "summary": "Update LDAP mapping for a team", "description": "Updates the [distinguished name](https://www.ldap.com/ldap-dns-and-rdns) (DN) of the LDAP entry to map to a team. [LDAP synchronization](https://docs.github.com/enterprise/admin/guides/user-management/using-ldap/#enabling-ldap-sync) must be enabled to map LDAP entries to a team. Use the [Create a team](https://docs.github.com/enterprise-server@3.0/rest/reference/teams/#create-a-team) endpoint to create a team with LDAP mapping.\n\nIf you pass the `hellcat-preview` media type, you can also update the LDAP mapping of a child team.", "operationId": "enterprise-admin/update-ldap-mapping-for-team", "tags": [ "enterprise-admin" ], "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/enterprise-admin#update-ldap-mapping-for-a-team" }, "parameters": [ { "$ref": "#/components/parameters/team-id" } ], "responses": { "200": { "description": "Response", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/ldap-mapping-team" }, "examples": { "default": { "$ref": "#/components/examples/ldap-mapping-team" } } } } } }, "requestBody": { "required": true, "content": { "application/json": { "schema": { "type": "object", "properties": { "ldap_dn": { "type": "string", "description": "The [distinguished name](https://www.ldap.com/ldap-dns-and-rdns) (DN) of the LDAP entry to map to a team." } }, "required": [ "ldap_dn" ] }, "example": { "ldap_dn": "cn=Enterprise Ops,ou=teams,dc=github,dc=com" } } } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": false, "category": "enterprise-admin", "subcategory": "ldap", "previews": [ { "required": false, "name": "hellcat", "note": "The Nested Teams API is currently available for developers to preview. See the [blog post](https://developer.github.com/changes/2017-08-30-preview-nested-teams) for full details. To access the API, you must provide a custom [media type](https://docs.github.com/enterprise-server@3.0/rest/overview/media-types) in the `Accept` header:\n```shell\napplication/vnd.github.hellcat-preview+json\n```" } ] } } }, "/admin/ldap/teams/{team_id}/sync": { "post": { "summary": "Sync LDAP mapping for a team", "description": "Note that this API call does not automatically initiate an LDAP sync. Rather, if a `201` is returned, the sync job is queued successfully, and is performed when the instance is ready.", "operationId": "enterprise-admin/sync-ldap-mapping-for-team", "tags": [ "enterprise-admin" ], "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/enterprise-admin#sync-ldap-mapping-for-a-team" }, "parameters": [ { "$ref": "#/components/parameters/team-id" } ], "responses": { "201": { "description": "Response", "content": { "application/json": { "schema": { "type": "object", "properties": { "status": { "type": "string" } } }, "example": { "status": "queued" } } } } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": false, "category": "enterprise-admin", "subcategory": "ldap" } } }, "/admin/ldap/users/{username}/mapping": { "patch": { "summary": "Update LDAP mapping for a user", "description": "", "operationId": "enterprise-admin/update-ldap-mapping-for-user", "tags": [ "enterprise-admin" ], "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/enterprise-admin#update-ldap-mapping-for-a-user" }, "parameters": [ { "$ref": "#/components/parameters/username" } ], "responses": { "200": { "description": "Response", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/ldap-mapping-user" }, "examples": { "default": { "$ref": "#/components/examples/ldap-mapping-user" } } } } } }, "requestBody": { "required": true, "content": { "application/json": { "schema": { "type": "object", "properties": { "ldap_dn": { "type": "string", "description": "The [distinguished name](https://www.ldap.com/ldap-dns-and-rdns) (DN) of the LDAP entry to map to a team." } }, "required": [ "ldap_dn" ] }, "example": { "ldap_dn": "uid=asdf,ou=users,dc=github,dc=com" } } } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": false, "category": "enterprise-admin", "subcategory": "ldap" } } }, "/admin/ldap/users/{username}/sync": { "post": { "summary": "Sync LDAP mapping for a user", "description": "Note that this API call does not automatically initiate an LDAP sync. Rather, if a `201` is returned, the sync job is queued successfully, and is performed when the instance is ready.", "operationId": "enterprise-admin/sync-ldap-mapping-for-user", "tags": [ "enterprise-admin" ], "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/enterprise-admin#sync-ldap-mapping-for-a-user" }, "parameters": [ { "$ref": "#/components/parameters/username" } ], "responses": { "201": { "description": "Response", "content": { "application/json": { "schema": { "type": "object", "properties": { "status": { "type": "string" } } }, "example": { "status": "queued" } } } } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": false, "category": "enterprise-admin", "subcategory": "ldap" } } }, "/admin/organizations": { "post": { "summary": "Create an organization", "description": "", "operationId": "enterprise-admin/create-org", "tags": [ "enterprise-admin" ], "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/enterprise-admin#create-an-organization" }, "responses": { "201": { "description": "Response", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/organization-simple" }, "examples": { "default": { "$ref": "#/components/examples/organization-simple" } } } } } }, "requestBody": { "required": true, "content": { "application/json": { "schema": { "type": "object", "properties": { "login": { "type": "string", "description": "The organization's username." }, "admin": { "type": "string", "description": "The login of the user who will manage this organization." }, "profile_name": { "type": "string", "description": "The organization's display name." } }, "required": [ "login", "admin" ] }, "example": { "login": "github", "profile_name": "GitHub, Inc.", "admin": "monalisaoctocat" } } } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": false, "category": "enterprise-admin", "subcategory": "orgs" } } }, "/admin/organizations/{org}": { "patch": { "summary": "Update an organization name", "description": "", "operationId": "enterprise-admin/update-org-name", "tags": [ "enterprise-admin" ], "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/enterprise-admin#update-an-organization-name" }, "parameters": [ { "$ref": "#/components/parameters/org" } ], "responses": { "202": { "description": "Response", "content": { "application/json": { "schema": { "type": "object", "properties": { "message": { "type": "string" }, "url": { "type": "string" } } }, "example": { "message": "Job queued to rename organization. It may take a few minutes to complete.", "url": "https:///api/v3/organizations/1" } } } } }, "requestBody": { "required": true, "content": { "application/json": { "schema": { "type": "object", "properties": { "login": { "type": "string", "description": "The organization's new name." } }, "required": [ "login" ] }, "example": { "login": "the-new-octocats" } } } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": false, "category": "enterprise-admin", "subcategory": "orgs" } } }, "/admin/pre-receive-environments": { "get": { "summary": "List pre-receive environments", "description": "", "operationId": "enterprise-admin/list-pre-receive-environments", "tags": [ "enterprise-admin" ], "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/enterprise-admin#list-pre-receive-environments" }, "parameters": [ { "$ref": "#/components/parameters/per-page" }, { "$ref": "#/components/parameters/page" }, { "$ref": "#/components/parameters/direction" }, { "name": "sort", "in": "query", "required": false, "schema": { "type": "string", "enum": [ "created", "updated", "name" ], "default": "created" } } ], "responses": { "200": { "description": "Response", "content": { "application/json": { "schema": { "type": "array", "items": { "$ref": "#/components/schemas/pre-receive-environment" } }, "examples": { "default": { "$ref": "#/components/examples/pre-receive-environment-items" } } } } } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": false, "category": "enterprise-admin", "subcategory": "pre-receive-environments", "previews": [ { "required": true, "name": "eye-scream", "note": "APIs for managing pre-receive hooks are currently available for developers to preview. During the preview period, the APIs may change without advance notice.\n\nTo access the API you must provide a custom [media type](/rest/overview/media-types) in the `Accept` header:\n\n```shell\napplication/vnd.github.eye-scream-preview\n```" } ] } }, "post": { "summary": "Create a pre-receive environment", "description": "", "operationId": "enterprise-admin/create-pre-receive-environment", "tags": [ "enterprise-admin" ], "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/enterprise-admin#create-a-pre-receive-environment" }, "responses": { "201": { "description": "Response", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/pre-receive-environment" }, "examples": { "default": { "$ref": "#/components/examples/pre-receive-environment" } } } } } }, "requestBody": { "required": true, "content": { "application/json": { "schema": { "type": "object", "properties": { "name": { "type": "string", "description": "The new pre-receive environment's name." }, "image_url": { "type": "string", "description": "URL from which to download a tarball of this environment." } }, "required": [ "name", "image_url" ] }, "example": { "name": "DevTools Hook Env", "image_url": "https://my_file_server/path/to/devtools_env.tar.gz" } } } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": false, "category": "enterprise-admin", "subcategory": "pre-receive-environments", "previews": [ { "required": true, "name": "eye-scream", "note": "APIs for managing pre-receive hooks are currently available for developers to preview. During the preview period, the APIs may change without advance notice.\n\nTo access the API you must provide a custom [media type](/rest/overview/media-types) in the `Accept` header:\n\n```shell\napplication/vnd.github.eye-scream-preview\n```" } ] } } }, "/admin/pre-receive-environments/{pre_receive_environment_id}": { "get": { "summary": "Get a pre-receive environment", "description": "", "operationId": "enterprise-admin/get-pre-receive-environment", "tags": [ "enterprise-admin" ], "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/enterprise-admin#get-a-pre-receive-environment" }, "parameters": [ { "$ref": "#/components/parameters/pre-receive-environment-id" } ], "responses": { "200": { "description": "Response", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/pre-receive-environment" }, "examples": { "default": { "$ref": "#/components/examples/pre-receive-environment" } } } } } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": false, "category": "enterprise-admin", "subcategory": "pre-receive-environments", "previews": [ { "required": true, "name": "eye-scream", "note": "APIs for managing pre-receive hooks are currently available for developers to preview. During the preview period, the APIs may change without advance notice.\n\nTo access the API you must provide a custom [media type](/rest/overview/media-types) in the `Accept` header:\n\n```shell\napplication/vnd.github.eye-scream-preview\n```" } ] } }, "patch": { "summary": "Update a pre-receive environment", "description": "You cannot modify the default environment. If you attempt to modify the default environment, you will receive a `422 Unprocessable Entity` response.", "operationId": "enterprise-admin/update-pre-receive-environment", "tags": [ "enterprise-admin" ], "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/enterprise-admin#update-a-pre-receive-environment" }, "parameters": [ { "$ref": "#/components/parameters/pre-receive-environment-id" } ], "responses": { "200": { "description": "Response", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/pre-receive-environment" }, "examples": { "default-response": { "$ref": "#/components/examples/pre-receive-environment-default-response" } } } } }, "422": { "description": "Client Errors", "content": { "application/json": { "schema": { "type": "object", "properties": { "message": { "type": "string" }, "errors": { "type": "array", "items": { "type": "object", "properties": { "resource": { "type": "string" }, "code": { "type": "string" }, "message": { "type": "string" } } } } } }, "examples": { "client-errors": { "value": { "message": "Validation Failed", "errors": [ { "resource": "PreReceiveEnvironment", "code": "custom", "message": "Cannot modify or delete the default environment" } ] } } } } } } }, "requestBody": { "content": { "application/json": { "schema": { "type": "object", "properties": { "name": { "type": "string", "description": "This pre-receive environment's new name." }, "image_url": { "type": "string", "description": "URL from which to download a tarball of this environment." } } } } } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": false, "category": "enterprise-admin", "subcategory": "pre-receive-environments", "previews": [ { "required": true, "name": "eye-scream", "note": "APIs for managing pre-receive hooks are currently available for developers to preview. During the preview period, the APIs may change without advance notice.\n\nTo access the API you must provide a custom [media type](/rest/overview/media-types) in the `Accept` header:\n\n```shell\napplication/vnd.github.eye-scream-preview\n```" } ] } }, "delete": { "summary": "Delete a pre-receive environment", "description": "If you attempt to delete an environment that cannot be deleted, you will receive a `422 Unprocessable Entity` response.\n\nThe possible error messages are:\n\n* _Cannot modify or delete the default environment_\n* _Cannot delete environment that has hooks_\n* _Cannot delete environment when download is in progress_", "operationId": "enterprise-admin/delete-pre-receive-environment", "tags": [ "enterprise-admin" ], "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/enterprise-admin#delete-a-pre-receive-environment" }, "parameters": [ { "$ref": "#/components/parameters/pre-receive-environment-id" } ], "responses": { "204": { "description": "Response" }, "422": { "description": "Client Errors", "content": { "application/json": { "schema": { "type": "object", "properties": { "message": { "type": "string" }, "errors": { "type": "array", "items": { "type": "object", "properties": { "resource": { "type": "string" }, "code": { "type": "string" }, "message": { "type": "string" } } } } } }, "examples": { "client-errors": { "value": { "message": "Validation Failed", "errors": [ { "resource": "PreReceiveEnvironment", "code": "custom", "message": "Cannot modify or delete the default environment" } ] } } } } } } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": false, "category": "enterprise-admin", "subcategory": "pre-receive-environments", "previews": [ { "required": true, "name": "eye-scream", "note": "APIs for managing pre-receive hooks are currently available for developers to preview. During the preview period, the APIs may change without advance notice.\n\nTo access the API you must provide a custom [media type](/rest/overview/media-types) in the `Accept` header:\n\n```shell\napplication/vnd.github.eye-scream-preview\n```" } ] } } }, "/admin/pre-receive-environments/{pre_receive_environment_id}/downloads": { "post": { "summary": "Start a pre-receive environment download", "description": "Triggers a new download of the environment tarball from the environment's `image_url`. When the download is finished, the newly downloaded tarball will overwrite the existing environment.\n\nIf a download cannot be triggered, you will receive a `422 Unprocessable Entity` response.\n\nThe possible error messages are:\n\n* _Cannot modify or delete the default environment_\n* _Can not start a new download when a download is in progress_", "operationId": "enterprise-admin/start-pre-receive-environment-download", "tags": [ "enterprise-admin" ], "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/enterprise-admin#start-a-pre-receive-environment-download" }, "parameters": [ { "$ref": "#/components/parameters/pre-receive-environment-id" } ], "responses": { "202": { "description": "Response", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/pre-receive-environment-download-status" }, "examples": { "default-response": { "$ref": "#/components/examples/pre-receive-environment-download-status-default-response" } } } } }, "422": { "description": "Client Errors", "content": { "application/json": { "schema": { "type": "object", "properties": { "message": { "type": "string" }, "errors": { "type": "array", "items": { "type": "object", "properties": { "resource": { "type": "string" }, "code": { "type": "string" }, "message": { "type": "string" } } } } } }, "examples": { "client-errors": { "value": { "message": "Validation Failed", "errors": [ { "resource": "PreReceiveEnvironment", "code": "custom", "message": "Can not start a new download when a download is in progress" } ] } } } } } } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": false, "category": "enterprise-admin", "subcategory": "pre-receive-environments", "previews": [ { "required": true, "name": "eye-scream", "note": "APIs for managing pre-receive hooks are currently available for developers to preview. During the preview period, the APIs may change without advance notice.\n\nTo access the API you must provide a custom [media type](/rest/overview/media-types) in the `Accept` header:\n\n```shell\napplication/vnd.github.eye-scream-preview\n```" } ] } } }, "/admin/pre-receive-environments/{pre_receive_environment_id}/downloads/latest": { "get": { "summary": "Get the download status for a pre-receive environment", "description": "In addition to seeing the download status at the \"[Get a pre-receive environment](#get-a-pre-receive-environment)\" endpoint, there is also this separate endpoint for just the download status.", "operationId": "enterprise-admin/get-download-status-for-pre-receive-environment", "tags": [ "enterprise-admin" ], "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/enterprise-admin#get-the-download-status-for-a-pre-receive-environment" }, "parameters": [ { "$ref": "#/components/parameters/pre-receive-environment-id" } ], "responses": { "200": { "description": "Response", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/pre-receive-environment-download-status" }, "examples": { "default": { "$ref": "#/components/examples/pre-receive-environment-download-status" } } } } } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": false, "category": "enterprise-admin", "subcategory": "pre-receive-environments", "previews": [ { "required": true, "name": "eye-scream", "note": "APIs for managing pre-receive hooks are currently available for developers to preview. During the preview period, the APIs may change without advance notice.\n\nTo access the API you must provide a custom [media type](/rest/overview/media-types) in the `Accept` header:\n\n```shell\napplication/vnd.github.eye-scream-preview\n```" } ] } } }, "/admin/pre-receive-hooks": { "get": { "summary": "List pre-receive hooks", "description": "", "operationId": "enterprise-admin/list-pre-receive-hooks", "tags": [ "enterprise-admin" ], "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/enterprise-admin#list-pre-receive-hooks" }, "parameters": [ { "$ref": "#/components/parameters/per-page" }, { "$ref": "#/components/parameters/page" }, { "$ref": "#/components/parameters/direction" }, { "name": "sort", "description": "One of `created` (when the repository was starred) or `updated` (when it was last pushed to) or `name`.", "in": "query", "required": false, "schema": { "type": "string", "enum": [ "created", "updated", "name" ], "default": "created" } } ], "responses": { "200": { "description": "Response", "content": { "application/json": { "schema": { "type": "array", "items": { "$ref": "#/components/schemas/pre-receive-hook" } }, "examples": { "default": { "$ref": "#/components/examples/pre-receive-hook-items" } } } } } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": false, "category": "enterprise-admin", "subcategory": "pre-receive-hooks", "previews": [ { "required": true, "name": "eye-scream", "note": "APIs for managing pre-receive hooks are currently available for developers to preview. During the preview period, the APIs may change without advance notice.\n\nTo access the API you must provide a custom [media type](/rest/overview/media-types) in the `Accept` header:\n\n```shell\napplication/vnd.github.eye-scream-preview\n```" } ] } }, "post": { "summary": "Create a pre-receive hook", "description": "", "operationId": "enterprise-admin/create-pre-receive-hook", "tags": [ "enterprise-admin" ], "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/enterprise-admin#create-a-pre-receive-hook" }, "responses": { "201": { "description": "Response", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/pre-receive-hook" }, "examples": { "default": { "$ref": "#/components/examples/pre-receive-hook" } } } } } }, "requestBody": { "required": true, "content": { "application/json": { "schema": { "type": "object", "properties": { "name": { "type": "string", "description": "The name of the hook." }, "script": { "type": "string", "description": "The script that the hook runs." }, "script_repository": { "type": "object", "description": "The GitHub repository where the script is kept.", "properties": { }, "additionalProperties": true }, "environment": { "type": "object", "description": "The pre-receive environment where the script is executed.", "properties": { }, "additionalProperties": true }, "enforcement": { "type": "string", "description": "The state of enforcement for this hook. default: `disabled`" }, "allow_downstream_configuration": { "type": "boolean", "description": "Whether enforcement can be overridden at the org or repo level. default: `false`" } }, "required": [ "name", "script", "script_repository", "environment" ] }, "example": { "name": "Check Commits", "script": "scripts/commit_check.sh", "enforcement": "disabled", "allow_downstream_configuration": false, "script_repository": { "full_name": "DevIT/hooks" }, "environment": { "id": 2 } } } } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": false, "category": "enterprise-admin", "subcategory": "pre-receive-hooks", "previews": [ { "required": true, "name": "eye-scream", "note": "APIs for managing pre-receive hooks are currently available for developers to preview. During the preview period, the APIs may change without advance notice.\n\nTo access the API you must provide a custom [media type](/rest/overview/media-types) in the `Accept` header:\n\n```shell\napplication/vnd.github.eye-scream-preview\n```" } ] } } }, "/admin/pre-receive-hooks/{pre_receive_hook_id}": { "get": { "summary": "Get a pre-receive hook", "description": "", "operationId": "enterprise-admin/get-pre-receive-hook", "tags": [ "enterprise-admin" ], "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/enterprise-admin#get-a-pre-receive-hook" }, "parameters": [ { "$ref": "#/components/parameters/pre-receive-hook-id" } ], "responses": { "200": { "description": "Response", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/pre-receive-hook" }, "examples": { "default": { "$ref": "#/components/examples/pre-receive-hook" } } } } } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": false, "category": "enterprise-admin", "subcategory": "pre-receive-hooks", "previews": [ { "required": true, "name": "eye-scream", "note": "APIs for managing pre-receive hooks are currently available for developers to preview. During the preview period, the APIs may change without advance notice.\n\nTo access the API you must provide a custom [media type](/rest/overview/media-types) in the `Accept` header:\n\n```shell\napplication/vnd.github.eye-scream-preview\n```" } ] } }, "patch": { "summary": "Update a pre-receive hook", "description": "", "operationId": "enterprise-admin/update-pre-receive-hook", "tags": [ "enterprise-admin" ], "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/enterprise-admin#update-a-pre-receive-hook" }, "parameters": [ { "$ref": "#/components/parameters/pre-receive-hook-id" } ], "responses": { "200": { "description": "Response", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/pre-receive-hook" }, "examples": { "default": { "$ref": "#/components/examples/pre-receive-hook-2" } } } } } }, "requestBody": { "content": { "application/json": { "schema": { "type": "object", "properties": { "name": { "type": "string", "description": "The name of the hook." }, "script": { "type": "string", "description": "The script that the hook runs." }, "script_repository": { "type": "object", "description": "The GitHub repository where the script is kept.", "properties": { }, "additionalProperties": true }, "environment": { "type": "object", "description": "The pre-receive environment where the script is executed.", "properties": { }, "additionalProperties": true }, "enforcement": { "type": "string", "description": "The state of enforcement for this hook." }, "allow_downstream_configuration": { "type": "boolean", "description": "Whether enforcement can be overridden at the org or repo level." } } }, "example": { "name": "Check Commits", "environment": { "id": 1 }, "allow_downstream_configuration": true } } } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": false, "category": "enterprise-admin", "subcategory": "pre-receive-hooks", "previews": [ { "required": true, "name": "eye-scream", "note": "APIs for managing pre-receive hooks are currently available for developers to preview. During the preview period, the APIs may change without advance notice.\n\nTo access the API you must provide a custom [media type](/rest/overview/media-types) in the `Accept` header:\n\n```shell\napplication/vnd.github.eye-scream-preview\n```" } ] } }, "delete": { "summary": "Delete a pre-receive hook", "description": "", "operationId": "enterprise-admin/delete-pre-receive-hook", "tags": [ "enterprise-admin" ], "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/enterprise-admin#delete-a-pre-receive-hook" }, "parameters": [ { "$ref": "#/components/parameters/pre-receive-hook-id" } ], "responses": { "204": { "description": "Response" } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": false, "category": "enterprise-admin", "subcategory": "pre-receive-hooks", "previews": [ { "required": true, "name": "eye-scream", "note": "APIs for managing pre-receive hooks are currently available for developers to preview. During the preview period, the APIs may change without advance notice.\n\nTo access the API you must provide a custom [media type](/rest/overview/media-types) in the `Accept` header:\n\n```shell\napplication/vnd.github.eye-scream-preview\n```" } ] } } }, "/admin/tokens": { "get": { "summary": "List personal access tokens", "description": "Lists personal access tokens for all users, including admin users.", "operationId": "enterprise-admin/list-personal-access-tokens", "tags": [ "enterprise-admin" ], "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/enterprise-admin#list-personal-access-tokens" }, "parameters": [ { "$ref": "#/components/parameters/per-page" }, { "$ref": "#/components/parameters/page" } ], "responses": { "200": { "description": "Response", "content": { "application/json": { "schema": { "type": "array", "items": { "$ref": "#/components/schemas/authorization" } }, "examples": { "default": { "$ref": "#/components/examples/authorization-items" } } } }, "headers": { "Link": { "$ref": "#/components/headers/link" } } } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": false, "category": "enterprise-admin", "subcategory": "users" } } }, "/admin/tokens/{token_id}": { "delete": { "summary": "Delete a personal access token", "description": "Deletes a personal access token. Returns a `403 - Forbidden` status when a personal access token is in use. For example, if you access this endpoint with the same personal access token that you are trying to delete, you will receive this error.", "operationId": "enterprise-admin/delete-personal-access-token", "tags": [ "enterprise-admin" ], "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/enterprise-admin#delete-a-personal-access-token" }, "parameters": [ { "$ref": "#/components/parameters/token-id" } ], "responses": { "204": { "description": "Response" } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": false, "category": "enterprise-admin", "subcategory": "users" } } }, "/admin/users": { "post": { "summary": "Create a user", "description": "If an external authentication mechanism is used, the login name should match the login name in the external system. If you are using LDAP authentication, you should also [update the LDAP mapping](https://docs.github.com/enterprise-server@3.0/rest/reference/enterprise-admin#update-ldap-mapping-for-a-user) for the user.\n\nThe login name will be normalized to only contain alphanumeric characters or single hyphens. For example, if you send `\"octo_cat\"` as the login, a user named `\"octo-cat\"` will be created.\n\nIf the login name or email address is already associated with an account, the server will return a `422` response.", "operationId": "enterprise-admin/create-user", "tags": [ "enterprise-admin" ], "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/enterprise-admin#create-a-user" }, "responses": { "201": { "description": "Response", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/simple-user" }, "examples": { "default": { "$ref": "#/components/examples/simple-user" } } } } } }, "requestBody": { "required": true, "content": { "application/json": { "schema": { "type": "object", "properties": { "login": { "type": "string", "description": "The user's username." }, "email": { "type": "string", "description": "**Required for built-in authentication.** The user's email address. This parameter can be omitted when using CAS, LDAP, or SAML. For details on built-in and centrally-managed authentication, see the the [GitHub authentication guide](https://docs.github.com/enterprise/2.18/admin/guides/user-management/authenticating-users-for-your-github-enterprise-server-instance/)." } }, "required": [ "login" ] }, "example": { "login": "monalisa", "email": "octocat@github.com" } } } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": false, "category": "enterprise-admin", "subcategory": "users" } } }, "/admin/users/{username}": { "patch": { "summary": "Update the username for a user", "description": "", "operationId": "enterprise-admin/update-username-for-user", "tags": [ "enterprise-admin" ], "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/enterprise-admin#update-the-username-for-a-user" }, "parameters": [ { "$ref": "#/components/parameters/username" } ], "responses": { "202": { "description": "Response", "content": { "application/json": { "schema": { "type": "object", "properties": { "message": { "type": "string" }, "url": { "type": "string" } } }, "example": { "message": "Job queued to rename user. It may take a few minutes to complete.", "url": "https://api.github.com/user/1" } } } } }, "requestBody": { "required": true, "content": { "application/json": { "schema": { "type": "object", "properties": { "login": { "type": "string", "description": "The user's new username." } }, "required": [ "login" ] }, "example": { "login": "thenewmonalisa" } } } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": false, "category": "enterprise-admin", "subcategory": "users" } }, "delete": { "summary": "Delete a user", "description": "Deleting a user will delete all their repositories, gists, applications, and personal settings. [Suspending a user](https://docs.github.com/enterprise-server@3.0/rest/reference/enterprise-admin#suspend-a-user) is often a better option.\n\nYou can delete any user account except your own.", "operationId": "enterprise-admin/delete-user", "tags": [ "enterprise-admin" ], "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/enterprise-admin#delete-a-user" }, "parameters": [ { "$ref": "#/components/parameters/username" } ], "responses": { "204": { "description": "Response" } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": false, "category": "enterprise-admin", "subcategory": "users" } } }, "/admin/users/{username}/authorizations": { "post": { "summary": "Create an impersonation OAuth token", "description": "", "operationId": "enterprise-admin/create-impersonation-o-auth-token", "tags": [ "enterprise-admin" ], "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/enterprise-admin#create-an-impersonation-oauth-token" }, "parameters": [ { "$ref": "#/components/parameters/username" } ], "responses": { "201": { "description": "Response", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/authorization" }, "examples": { "default": { "$ref": "#/components/examples/authorization" } } } } } }, "requestBody": { "required": true, "content": { "application/json": { "schema": { "type": "object", "properties": { "scopes": { "type": "array", "description": "A list of [scopes](https://docs.github.com/enterprise-server@3.0/apps/building-oauth-apps/understanding-scopes-for-oauth-apps/).", "items": { "type": "string" } } } } } } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": false, "category": "enterprise-admin", "subcategory": "users" } }, "delete": { "summary": "Delete an impersonation OAuth token", "description": "", "operationId": "enterprise-admin/delete-impersonation-o-auth-token", "tags": [ "enterprise-admin" ], "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/enterprise-admin#delete-an-impersonation-oauth-token" }, "parameters": [ { "$ref": "#/components/parameters/username" } ], "responses": { "204": { "description": "Response" } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": false, "category": "enterprise-admin", "subcategory": "users" } } }, "/app": { "get": { "summary": "Get the authenticated app", "description": "Returns the GitHub App associated with the authentication credentials used. To see how many app installations are associated with this GitHub App, see the `installations_count` in the response. For more details about your app's installations, see the \"[List installations for the authenticated app](https://docs.github.com/enterprise-server@3.0/rest/reference/apps#list-installations-for-the-authenticated-app)\" endpoint.\n\nYou must use a [JWT](https://docs.github.com/enterprise-server@3.0/apps/building-github-apps/authenticating-with-github-apps/#authenticating-as-a-github-app) to access this endpoint.", "tags": [ "apps" ], "operationId": "apps/get-authenticated", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/apps#get-the-authenticated-app" }, "parameters": [ ], "responses": { "200": { "description": "Response", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/integration" }, "examples": { "default": { "$ref": "#/components/examples/integration" } } } } } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": true, "category": "apps", "subcategory": null } } }, "/app-manifests/{code}/conversions": { "post": { "summary": "Create a GitHub App from a manifest", "description": "Use this endpoint to complete the handshake necessary when implementing the [GitHub App Manifest flow](https://docs.github.com/enterprise-server@3.0/apps/building-github-apps/creating-github-apps-from-a-manifest/). When you create a GitHub App with the manifest flow, you receive a temporary `code` used to retrieve the GitHub App's `id`, `pem` (private key), and `webhook_secret`.", "tags": [ "apps" ], "operationId": "apps/create-from-manifest", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/apps#create-a-github-app-from-a-manifest" }, "parameters": [ { "name": "code", "in": "path", "required": true, "schema": { "type": "string" } } ], "requestBody": { "required": false, "content": { "application/json": { "schema": { "type": "object", "additionalProperties": false } } } }, "responses": { "201": { "description": "Response", "content": { "application/json": { "schema": { "allOf": [ { "$ref": "#/components/schemas/integration" }, { "type": "object", "properties": { "client_id": { "type": "string" }, "client_secret": { "type": "string" }, "webhook_secret": { "type": [ "string", "null" ] }, "pem": { "type": "string" } }, "required": [ "client_id", "client_secret", "webhook_secret", "pem" ], "additionalProperties": true } ] }, "examples": { "default": { "$ref": "#/components/examples/integration-from-manifest" } } } } }, "404": { "$ref": "#/components/responses/not_found" }, "422": { "$ref": "#/components/responses/validation_failed_simple" } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": false, "category": "apps", "subcategory": null } } }, "/app/hook/config": { "get": { "summary": "Get a webhook configuration for an app", "description": "Returns the webhook configuration for a GitHub App. For more information about configuring a webhook for your app, see \"[Creating a GitHub App](/developers/apps/creating-a-github-app).\"\n\nYou must use a [JWT](https://docs.github.com/enterprise-server@3.0/apps/building-github-apps/authenticating-with-github-apps/#authenticating-as-a-github-app) to access this endpoint.", "tags": [ "apps" ], "operationId": "apps/get-webhook-config-for-app", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/apps#get-a-webhook-configuration-for-an-app" }, "responses": { "200": { "description": "Response", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/webhook-config" }, "examples": { "default": { "$ref": "#/components/examples/webhook-config" } } } } } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": false, "category": "apps", "subcategory": "webhooks" } }, "patch": { "summary": "Update a webhook configuration for an app", "description": "Updates the webhook configuration for a GitHub App. For more information about configuring a webhook for your app, see \"[Creating a GitHub App](/developers/apps/creating-a-github-app).\"\n\nYou must use a [JWT](https://docs.github.com/enterprise-server@3.0/apps/building-github-apps/authenticating-with-github-apps/#authenticating-as-a-github-app) to access this endpoint.", "tags": [ "apps" ], "operationId": "apps/update-webhook-config-for-app", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/apps#update-a-webhook-configuration-for-an-app" }, "requestBody": { "required": false, "content": { "application/json": { "schema": { "type": "object", "properties": { "url": { "$ref": "#/components/schemas/webhook-config-url" }, "content_type": { "$ref": "#/components/schemas/webhook-config-content-type" }, "secret": { "$ref": "#/components/schemas/webhook-config-secret" }, "insecure_ssl": { "$ref": "#/components/schemas/webhook-config-insecure-ssl" } }, "example": { "content_type": "json", "insecure_ssl": "0", "secret": "********", "url": "https://example.com/webhook" } } } } }, "responses": { "200": { "description": "Response", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/webhook-config" }, "examples": { "default": { "$ref": "#/components/examples/webhook-config" } } } } } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": false, "category": "apps", "subcategory": "webhooks" } } }, "/app/installations": { "get": { "summary": "List installations for the authenticated app", "description": "You must use a [JWT](https://docs.github.com/enterprise-server@3.0/apps/building-github-apps/authenticating-with-github-apps/#authenticating-as-a-github-app) to access this endpoint.\n\nThe permissions the installation has are included under the `permissions` key.", "tags": [ "apps" ], "operationId": "apps/list-installations", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/apps#list-installations-for-the-authenticated-app" }, "parameters": [ { "$ref": "#/components/parameters/per-page" }, { "$ref": "#/components/parameters/page" }, { "$ref": "#/components/parameters/since" }, { "name": "outdated", "in": "query", "required": false, "schema": { "type": "string" } } ], "responses": { "200": { "description": "The permissions the installation has are included under the `permissions` key.", "content": { "application/json": { "schema": { "type": "array", "items": { "$ref": "#/components/schemas/installation" } }, "examples": { "default": { "$ref": "#/components/examples/base-installation-items" } } } }, "headers": { "Link": { "$ref": "#/components/headers/link" } } } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": true, "category": "apps", "subcategory": null } } }, "/app/installations/{installation_id}": { "get": { "summary": "Get an installation for the authenticated app", "description": "Enables an authenticated GitHub App to find an installation's information using the installation id.\n\nYou must use a [JWT](https://docs.github.com/enterprise-server@3.0/apps/building-github-apps/authenticating-with-github-apps/#authenticating-as-a-github-app) to access this endpoint.", "tags": [ "apps" ], "operationId": "apps/get-installation", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/apps#get-an-installation-for-the-authenticated-app" }, "parameters": [ { "$ref": "#/components/parameters/installation-id" } ], "responses": { "200": { "description": "Response", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/installation" }, "examples": { "default": { "$ref": "#/components/examples/base-installation" } } } } }, "404": { "$ref": "#/components/responses/not_found" }, "415": { "$ref": "#/components/responses/preview_header_missing" } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": true, "category": "apps", "subcategory": null } }, "delete": { "summary": "Delete an installation for the authenticated app", "description": "Uninstalls a GitHub App on a user, organization, or business account. If you prefer to temporarily suspend an app's access to your account's resources, then we recommend the \"[Suspend an app installation](https://docs.github.com/enterprise-server@3.0/rest/reference/apps/#suspend-an-app-installation)\" endpoint.\n\nYou must use a [JWT](https://docs.github.com/enterprise-server@3.0/apps/building-github-apps/authenticating-with-github-apps/#authenticating-as-a-github-app) to access this endpoint.", "tags": [ "apps" ], "operationId": "apps/delete-installation", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/apps#delete-an-installation-for-the-authenticated-app" }, "parameters": [ { "$ref": "#/components/parameters/installation-id" } ], "responses": { "204": { "description": "Response" }, "404": { "$ref": "#/components/responses/not_found" } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": false, "category": "apps", "subcategory": null } } }, "/app/installations/{installation_id}/access_tokens": { "post": { "summary": "Create an installation access token for an app", "description": "Creates an installation access token that enables a GitHub App to make authenticated API requests for the app's installation on an organization or individual account. Installation tokens expire one hour from the time you create them. Using an expired token produces a status code of `401 - Unauthorized`, and requires creating a new installation token. By default the installation token has access to all repositories that the installation can access. To restrict the access to specific repositories, you can provide the `repository_ids` when creating the token. When you omit `repository_ids`, the response does not contain the `repositories` key.\n\nYou must use a [JWT](https://docs.github.com/enterprise-server@3.0/apps/building-github-apps/authenticating-with-github-apps/#authenticating-as-a-github-app) to access this endpoint.", "tags": [ "apps" ], "operationId": "apps/create-installation-access-token", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/apps/#create-an-installation-access-token-for-an-app" }, "parameters": [ { "$ref": "#/components/parameters/installation-id" } ], "requestBody": { "required": false, "content": { "application/json": { "schema": { "type": "object", "properties": { "repositories": { "description": "List of repository names that the token should have access to", "type": "array", "items": { "type": "string", "examples": [ "rails" ] } }, "repository_ids": { "description": "List of repository IDs that the token should have access to", "type": "array", "items": { "type": "integer" }, "examples": [ 1 ] }, "permissions": { "$ref": "#/components/schemas/app-permissions" } } } } } }, "responses": { "201": { "description": "Response", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/installation-token" }, "examples": { "default": { "$ref": "#/components/examples/installation-token" } } } } }, "403": { "$ref": "#/components/responses/forbidden" }, "415": { "$ref": "#/components/responses/preview_header_missing" }, "401": { "$ref": "#/components/responses/requires_authentication" }, "404": { "$ref": "#/components/responses/not_found" }, "422": { "$ref": "#/components/responses/validation_failed" } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": true, "category": "apps", "subcategory": null } } }, "/app/installations/{installation_id}/suspended": { "put": { "summary": "Suspend an app installation", "description": "Suspends a GitHub App on a user, organization, or business account, which blocks the app from accessing the account's resources. When a GitHub App is suspended, the app's access to the GitHub Enterprise Server API or webhook events is blocked for that account.\n\nYou must use a [JWT](https://docs.github.com/enterprise-server@3.0/apps/building-github-apps/authenticating-with-github-apps/#authenticating-as-a-github-app) to access this endpoint.", "tags": [ "apps" ], "operationId": "apps/suspend-installation", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/apps#suspend-an-app-installation" }, "parameters": [ { "$ref": "#/components/parameters/installation-id" } ], "responses": { "204": { "description": "Response" }, "404": { "$ref": "#/components/responses/not_found" } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": false, "category": "apps", "subcategory": null } }, "delete": { "summary": "Unsuspend an app installation", "description": "Removes a GitHub App installation suspension.\n\nYou must use a [JWT](https://docs.github.com/enterprise-server@3.0/apps/building-github-apps/authenticating-with-github-apps/#authenticating-as-a-github-app) to access this endpoint.", "tags": [ "apps" ], "operationId": "apps/unsuspend-installation", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/apps#unsuspend-an-app-installation" }, "parameters": [ { "$ref": "#/components/parameters/installation-id" } ], "responses": { "204": { "description": "Response" }, "404": { "$ref": "#/components/responses/not_found" } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": false, "category": "apps", "subcategory": null } } }, "/applications/grants": { "get": { "summary": "List your grants", "description": "**Deprecation Notice:** GitHub Enterprise Server will discontinue the [OAuth Authorizations API](https://docs.github.com/enterprise-server@3.0/rest/reference/oauth-authorizations/), which is used by integrations to create personal access tokens and OAuth tokens, and you must now create these tokens using our [web application flow](https://docs.github.com/enterprise-server@3.0/developers/apps/authorizing-oauth-apps#web-application-flow). The [OAuth Authorizations API](https://docs.github.com/enterprise-server@3.0/rest/reference/oauth-authorizations) will be removed on November, 13, 2020. For more information, including scheduled brownouts, see the [blog post](https://developer.github.com/changes/2020-02-14-deprecating-oauth-auth-endpoint/).\n\nYou can use this API to list the set of OAuth applications that have been granted access to your account. Unlike the [list your authorizations](https://docs.github.com/enterprise-server@3.0/rest/reference/oauth-authorizations#list-your-authorizations) API, this API does not manage individual tokens. This API will return one entry for each OAuth application that has been granted access to your account, regardless of the number of tokens an application has generated for your user. The list of OAuth applications returned matches what is shown on [the application authorizations settings screen within GitHub](https://github.com/settings/applications#authorized). The `scopes` returned are the union of scopes authorized for the application. For example, if an application has one token with `repo` scope and another token with `user` scope, the grant will return `[\"repo\", \"user\"]`.", "tags": [ "oauth-authorizations" ], "operationId": "oauth-authorizations/list-grants", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/oauth-authorizations#list-your-grants" }, "parameters": [ { "$ref": "#/components/parameters/per-page" }, { "$ref": "#/components/parameters/page" }, { "name": "client_id", "in": "query", "required": false, "description": "The client ID of your GitHub app.", "schema": { "type": "string" } } ], "responses": { "200": { "description": "Response", "content": { "application/json": { "schema": { "type": "array", "items": { "$ref": "#/components/schemas/application-grant" } }, "examples": { "default": { "$ref": "#/components/examples/application-grant-items" } } } }, "headers": { "Link": { "$ref": "#/components/headers/link" } } }, "304": { "$ref": "#/components/responses/not_modified" }, "403": { "$ref": "#/components/responses/forbidden" }, "401": { "$ref": "#/components/responses/requires_authentication" }, "404": { "$ref": "#/components/responses/not_found" } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": false, "removalDate": "2020-11-13", "deprecationDate": "2020-02-14", "category": "oauth-authorizations", "subcategory": null }, "deprecated": true } }, "/applications/grants/{grant_id}": { "get": { "summary": "Get a single grant", "description": "**Deprecation Notice:** GitHub Enterprise Server will discontinue the [OAuth Authorizations API](https://docs.github.com/enterprise-server@3.0/rest/reference/oauth-authorizations), which is used by integrations to create personal access tokens and OAuth tokens, and you must now create these tokens using our [web application flow](https://docs.github.com/enterprise-server@3.0/apps/building-oauth-apps/authorizing-oauth-apps/#web-application-flow). The [OAuth Authorizations API](https://docs.github.com/enterprise-server@3.0/rest/reference/oauth-authorizations) will be removed on November, 13, 2020. For more information, including scheduled brownouts, see the [blog post](https://developer.github.com/changes/2020-02-14-deprecating-oauth-auth-endpoint/).", "tags": [ "oauth-authorizations" ], "operationId": "oauth-authorizations/get-grant", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/oauth-authorizations#get-a-single-grant" }, "parameters": [ { "$ref": "#/components/parameters/grant-id" } ], "responses": { "200": { "description": "Response", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/application-grant" }, "examples": { "default": { "$ref": "#/components/examples/application-grant" } } } } }, "304": { "$ref": "#/components/responses/not_modified" }, "403": { "$ref": "#/components/responses/forbidden" }, "401": { "$ref": "#/components/responses/requires_authentication" } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": false, "removalDate": "2020-11-13", "deprecationDate": "2020-02-14", "category": "oauth-authorizations", "subcategory": null }, "deprecated": true }, "delete": { "summary": "Delete a grant", "description": "**Deprecation Notice:** GitHub Enterprise Server will discontinue the [OAuth Authorizations API](https://docs.github.com/enterprise-server@3.0/rest/reference/oauth-authorizations/), which is used by integrations to create personal access tokens and OAuth tokens, and you must now create these tokens using our [web application flow](https://docs.github.com/enterprise-server@3.0/developers/apps/authorizing-oauth-apps#web-application-flow). The [OAuth Authorizations API](https://docs.github.com/enterprise-server@3.0/rest/reference/oauth-authorizations/) will be removed on November, 13, 2020. For more information, including scheduled brownouts, see the [blog post](https://developer.github.com/changes/2020-02-14-deprecating-oauth-auth-endpoint/).\n\nDeleting an OAuth application's grant will also delete all OAuth tokens associated with the application for your user. Once deleted, the application has no access to your account and is no longer listed on [the application authorizations settings screen within GitHub](https://github.com/settings/applications#authorized).", "tags": [ "oauth-authorizations" ], "operationId": "oauth-authorizations/delete-grant", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/oauth-authorizations#delete-a-grant" }, "parameters": [ { "$ref": "#/components/parameters/grant-id" } ], "responses": { "204": { "description": "Response" }, "304": { "$ref": "#/components/responses/not_modified" }, "403": { "$ref": "#/components/responses/forbidden" }, "401": { "$ref": "#/components/responses/requires_authentication" } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": false, "removalDate": "2020-11-13", "deprecationDate": "2020-02-14", "category": "oauth-authorizations", "subcategory": null }, "deprecated": true } }, "/applications/{client_id}/grant": { "delete": { "summary": "Delete an app authorization", "description": "OAuth application owners can revoke a grant for their OAuth application and a specific user. You must use [Basic Authentication](https://docs.github.com/enterprise-server@3.0/rest/overview/other-authentication-methods#basic-authentication) when accessing this endpoint, using the OAuth application's `client_id` and `client_secret` as the username and password. You must also provide a valid OAuth `access_token` as an input parameter and the grant for the token's owner will be deleted.\nDeleting an OAuth application's grant will also delete all OAuth tokens associated with the application for the user. Once deleted, the application will have no access to the user's account and will no longer be listed on [the application authorizations settings screen within GitHub](https://github.com/settings/applications#authorized).", "operationId": "apps/delete-authorization", "tags": [ "apps" ], "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/apps#delete-an-app-authorization" }, "parameters": [ { "$ref": "#/components/parameters/client-id" } ], "requestBody": { "required": true, "content": { "application/json": { "schema": { "type": "object", "properties": { "access_token": { "type": "string", "description": "The OAuth access token used to authenticate to the GitHub API." } }, "required": [ "access_token" ] }, "example": { "access_token": "e72e16c7e42f292c6912e7710c838347ae178b4a" } } } }, "responses": { "204": { "description": "Response" }, "422": { "$ref": "#/components/responses/validation_failed" } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": false, "category": "apps", "subcategory": "oauth-applications" } } }, "/applications/{client_id}/grants/{access_token}": { "delete": { "summary": "Revoke a grant for an application", "description": "**Deprecation Notice:** GitHub Enterprise Server will discontinue OAuth endpoints that contain `access_token` in the path parameter. We have introduced new endpoints that allow you to securely manage tokens for OAuth Apps by moving `access_token` to the request body. For more information, see the [blog post](https://developer.github.com/changes/2020-02-14-deprecating-oauth-app-endpoint/).\n\nOAuth application owners can revoke a grant for their OAuth application and a specific user. You must use [Basic Authentication](https://docs.github.com/enterprise-server@3.0/rest/overview/other-authentication-methods#basic-authentication) when accessing this endpoint, using the OAuth application's `client_id` and `client_secret` as the username and password. You must also provide a valid token as `:access_token` and the grant for the token's owner will be deleted.\n\nDeleting an OAuth application's grant will also delete all OAuth tokens associated with the application for the user. Once deleted, the application will have no access to the user's account and will no longer be listed on [the Applications settings page under \"Authorized OAuth Apps\" on GitHub Enterprise Server](https://github.com/settings/applications#authorized).", "tags": [ "apps" ], "operationId": "apps/revoke-grant-for-application", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/apps#revoke-a-grant-for-an-application" }, "parameters": [ { "$ref": "#/components/parameters/client-id" }, { "$ref": "#/components/parameters/access-token" } ], "responses": { "204": { "description": "Response" } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": false, "removalDate": "2021-05-05", "deprecationDate": "2020-02-14", "category": "apps", "subcategory": "oauth-applications" }, "deprecated": true } }, "/applications/{client_id}/token": { "post": { "summary": "Check a token", "description": "OAuth applications can use a special API method for checking OAuth token validity without exceeding the normal rate limits for failed login attempts. Authentication works differently with this particular endpoint. You must use [Basic Authentication](https://docs.github.com/enterprise-server@3.0/rest/overview/other-authentication-methods#basic-authentication) to use this endpoint, where the username is the OAuth application `client_id` and the password is its `client_secret`. Invalid tokens will return `404 NOT FOUND`.", "tags": [ "apps" ], "operationId": "apps/check-token", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/apps#check-a-token" }, "parameters": [ { "$ref": "#/components/parameters/client-id" } ], "requestBody": { "required": true, "content": { "application/json": { "schema": { "properties": { "access_token": { "description": "The access_token of the OAuth application.", "type": "string" } }, "required": [ "access_token" ], "type": "object" } } } }, "responses": { "200": { "description": "Response", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/authorization" }, "examples": { "default": { "$ref": "#/components/examples/authorization-with-user" } } } } }, "422": { "$ref": "#/components/responses/validation_failed" }, "404": { "$ref": "#/components/responses/not_found" } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": false, "category": "apps", "subcategory": "oauth-applications" } }, "patch": { "summary": "Reset a token", "description": "OAuth applications can use this API method to reset a valid OAuth token without end-user involvement. Applications must save the \"token\" property in the response because changes take effect immediately. You must use [Basic Authentication](https://docs.github.com/enterprise-server@3.0/rest/overview/other-authentication-methods#basic-authentication) when accessing this endpoint, using the OAuth application's `client_id` and `client_secret` as the username and password. Invalid tokens will return `404 NOT FOUND`.", "tags": [ "apps" ], "operationId": "apps/reset-token", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/apps#reset-a-token" }, "parameters": [ { "$ref": "#/components/parameters/client-id" } ], "requestBody": { "required": true, "content": { "application/json": { "schema": { "properties": { "access_token": { "description": "The access_token of the OAuth application.", "type": "string" } }, "required": [ "access_token" ], "type": "object" } } } }, "responses": { "200": { "description": "Response", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/authorization" }, "examples": { "default": { "$ref": "#/components/examples/authorization-with-user" } } } } }, "422": { "$ref": "#/components/responses/validation_failed" } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": false, "category": "apps", "subcategory": "oauth-applications" } }, "delete": { "summary": "Delete an app token", "description": "OAuth application owners can revoke a single token for an OAuth application. You must use [Basic Authentication](https://docs.github.com/enterprise-server@3.0/rest/overview/other-authentication-methods#basic-authentication) when accessing this endpoint, using the OAuth application's `client_id` and `client_secret` as the username and password.", "tags": [ "apps" ], "operationId": "apps/delete-token", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/apps#delete-an-app-token" }, "parameters": [ { "$ref": "#/components/parameters/client-id" } ], "requestBody": { "required": true, "content": { "application/json": { "schema": { "type": "object", "properties": { "access_token": { "type": "string", "description": "The OAuth access token used to authenticate to the GitHub API." } }, "required": [ "access_token" ] }, "example": { "access_token": "e72e16c7e42f292c6912e7710c838347ae178b4a" } } } }, "responses": { "204": { "description": "Response" }, "422": { "$ref": "#/components/responses/validation_failed" } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": false, "category": "apps", "subcategory": "oauth-applications" } } }, "/applications/{client_id}/token/scoped": { "post": { "summary": "Create a scoped access token", "description": "Use a non-scoped user-to-server OAuth access token to create a repository scoped and/or permission scoped user-to-server OAuth access token. You can specify which repositories the token can access and which permissions are granted to the token. You must use [Basic Authentication](https://docs.github.com/enterprise-server@3.0/rest/overview/other-authentication-methods#basic-authentication) when accessing this endpoint, using the OAuth application's `client_id` and `client_secret` as the username and password. Invalid tokens will return `404 NOT FOUND`.", "tags": [ "apps" ], "operationId": "apps/scope-token", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/apps#create-a-scoped-access-token" }, "parameters": [ { "$ref": "#/components/parameters/client-id" } ], "requestBody": { "required": true, "content": { "application/json": { "schema": { "type": "object", "properties": { "access_token": { "type": "string", "description": "The OAuth access token used to authenticate to the GitHub API.", "examples": [ "e72e16c7e42f292c6912e7710c838347ae178b4a" ] }, "target": { "description": "The name of the user or organization to scope the user-to-server access token to. **Required** unless `target_id` is specified.", "type": "string", "examples": [ "octocat" ] }, "target_id": { "description": "The ID of the user or organization to scope the user-to-server access token to. **Required** unless `target` is specified.", "type": "integer", "examples": [ 1 ] }, "repositories": { "description": "The list of repository names to scope the user-to-server access token to. `repositories` may not be specified if `repository_ids` is specified.", "type": "array", "items": { "type": "string", "examples": [ "rails" ] } }, "repository_ids": { "description": "The list of repository IDs to scope the user-to-server access token to. `repository_ids` may not be specified if `repositories` is specified.", "type": "array", "items": { "type": "integer" }, "examples": [ 1 ] }, "permissions": { "$ref": "#/components/schemas/app-permissions" } }, "required": [ "access_token" ] } } } }, "responses": { "200": { "description": "Response", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/authorization" }, "examples": { "default": { "$ref": "#/components/examples/scope-token" } } } } }, "401": { "$ref": "#/components/responses/requires_authentication" }, "403": { "$ref": "#/components/responses/forbidden" }, "404": { "$ref": "#/components/responses/not_found" }, "422": { "$ref": "#/components/responses/validation_failed" } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": false, "category": "apps", "subcategory": "oauth-applications" } } }, "/applications/{client_id}/tokens/{access_token}": { "get": { "summary": "Check an authorization", "description": "**Deprecation Notice:** GitHub Enterprise Server will discontinue OAuth endpoints that contain `access_token` in the path parameter. We have introduced new endpoints that allow you to securely manage tokens for OAuth Apps by moving `access_token` to the request body. For more information, see the [blog post](https://developer.github.com/changes/2020-02-14-deprecating-oauth-app-endpoint/).\n\nOAuth applications can use a special API method for checking OAuth token validity without exceeding the normal rate limits for failed login attempts. Authentication works differently with this particular endpoint. You must use [Basic Authentication](https://docs.github.com/enterprise-server@3.0/rest/overview/other-authentication-methods#basic-authentication) when accessing this endpoint, using the OAuth application's `client_id` and `client_secret` as the username and password. Invalid tokens will return `404 NOT FOUND`.", "tags": [ "apps" ], "operationId": "apps/check-authorization", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/apps#check-an-authorization" }, "parameters": [ { "$ref": "#/components/parameters/client-id" }, { "$ref": "#/components/parameters/access-token" } ], "responses": { "200": { "description": "Response", "content": { "application/json": { "schema": { "anyOf": [ { "type": "null" }, { "$ref": "#/components/schemas/authorization" } ] }, "examples": { "default": { "$ref": "#/components/examples/authorization-with-user" } } } } }, "404": { "$ref": "#/components/responses/not_found" } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": false, "removalDate": "2021-05-05", "deprecationDate": "2020-02-14", "category": "apps", "subcategory": "oauth-applications" }, "deprecated": true }, "post": { "summary": "Reset an authorization", "description": "**Deprecation Notice:** GitHub Enterprise Server will discontinue OAuth endpoints that contain `access_token` in the path parameter. We have introduced new endpoints that allow you to securely manage tokens for OAuth Apps by moving `access_token` to the request body. For more information, see the [blog post](https://developer.github.com/changes/2020-02-14-deprecating-oauth-app-endpoint/).\n\nOAuth applications can use this API method to reset a valid OAuth token without end-user involvement. Applications must save the \"token\" property in the response because changes take effect immediately. You must use [Basic Authentication](https://docs.github.com/enterprise-server@3.0/rest/overview/other-authentication-methods#basic-authentication) when accessing this endpoint, using the OAuth application's `client_id` and `client_secret` as the username and password. Invalid tokens will return `404 NOT FOUND`.", "tags": [ "apps" ], "operationId": "apps/reset-authorization", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/apps#reset-an-authorization" }, "parameters": [ { "$ref": "#/components/parameters/client-id" }, { "$ref": "#/components/parameters/access-token" } ], "responses": { "200": { "description": "Response", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/authorization" }, "examples": { "default": { "$ref": "#/components/examples/authorization-with-user" } } } } } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": false, "removalDate": "2021-05-05", "deprecationDate": "2020-02-14", "category": "apps", "subcategory": "oauth-applications" }, "deprecated": true }, "delete": { "summary": "Revoke an authorization for an application", "description": "**Deprecation Notice:** GitHub Enterprise Server will discontinue OAuth endpoints that contain `access_token` in the path parameter. We have introduced new endpoints that allow you to securely manage tokens for OAuth Apps by moving `access_token` to the request body. For more information, see the [blog post](https://developer.github.com/changes/2020-02-14-deprecating-oauth-app-endpoint/).\n\nOAuth application owners can revoke a single token for an OAuth application. You must use [Basic Authentication](https://docs.github.com/enterprise-server@3.0/rest/overview/other-authentication-methods#basic-authentication) when accessing this endpoint, using the OAuth application's `client_id` and `client_secret` as the username and password.", "tags": [ "apps" ], "operationId": "apps/revoke-authorization-for-application", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/apps#revoke-an-authorization-for-an-application" }, "parameters": [ { "$ref": "#/components/parameters/client-id" }, { "$ref": "#/components/parameters/access-token" } ], "responses": { "204": { "description": "Response" } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": false, "removalDate": "2021-05-05", "deprecationDate": "2020-02-14", "category": "apps", "subcategory": "oauth-applications" }, "deprecated": true } }, "/apps/{app_slug}": { "get": { "summary": "Get an app", "description": "**Note**: The `:app_slug` is just the URL-friendly name of your GitHub App. You can find this on the settings page for your GitHub App (e.g., `https://github.com/settings/apps/:app_slug`).\n\nIf the GitHub App you specify is public, you can access this endpoint without authenticating. If the GitHub App you specify is private, you must authenticate with a [personal access token](https://docs.github.com/articles/creating-a-personal-access-token-for-the-command-line/) or an [installation access token](https://docs.github.com/enterprise-server@3.0/apps/building-github-apps/authenticating-with-github-apps/#authenticating-as-an-installation) to access this endpoint.", "tags": [ "apps" ], "operationId": "apps/get-by-slug", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/apps/#get-an-app" }, "parameters": [ { "$ref": "#/components/parameters/app-slug" } ], "responses": { "200": { "description": "Response", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/integration" }, "examples": { "default": { "$ref": "#/components/examples/integration" } } } } }, "403": { "$ref": "#/components/responses/forbidden" }, "404": { "$ref": "#/components/responses/not_found" }, "415": { "$ref": "#/components/responses/preview_header_missing" } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": true, "category": "apps", "subcategory": null } } }, "/authorizations": { "get": { "summary": "List your authorizations", "description": "**Deprecation Notice:** GitHub Enterprise Server will discontinue the [OAuth Authorizations API](https://docs.github.com/enterprise-server@3.0/rest/reference/oauth-authorizations), which is used by integrations to create personal access tokens and OAuth tokens, and you must now create these tokens using our [web application flow](https://docs.github.com/enterprise-server@3.0/apps/building-oauth-apps/authorizing-oauth-apps/#web-application-flow). The [OAuth Authorizations API](https://docs.github.com/enterprise-server@3.0/rest/reference/oauth-authorizations) will be removed on November, 13, 2020. For more information, including scheduled brownouts, see the [blog post](https://developer.github.com/changes/2020-02-14-deprecating-oauth-auth-endpoint/).", "tags": [ "oauth-authorizations" ], "operationId": "oauth-authorizations/list-authorizations", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/oauth-authorizations#list-your-authorizations" }, "parameters": [ { "$ref": "#/components/parameters/per-page" }, { "$ref": "#/components/parameters/page" }, { "name": "client_id", "in": "query", "required": false, "description": "The client ID of your GitHub app.", "schema": { "type": "string" } } ], "responses": { "200": { "description": "Response", "content": { "application/json": { "schema": { "type": "array", "items": { "$ref": "#/components/schemas/authorization" } }, "examples": { "default": { "$ref": "#/components/examples/authorization-items" } } } }, "headers": { "Link": { "$ref": "#/components/headers/link" } } }, "304": { "$ref": "#/components/responses/not_modified" }, "403": { "$ref": "#/components/responses/forbidden" }, "401": { "$ref": "#/components/responses/requires_authentication" }, "404": { "$ref": "#/components/responses/not_found" } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": false, "removalDate": "2020-11-13", "deprecationDate": "2020-02-14", "category": "oauth-authorizations", "subcategory": null }, "deprecated": true }, "post": { "summary": "Create a new authorization", "description": "**Deprecation Notice:** GitHub Enterprise Server will discontinue the [OAuth Authorizations API](https://docs.github.com/enterprise-server@3.0/rest/reference/oauth-authorizations), which is used by integrations to create personal access tokens and OAuth tokens, and you must now create these tokens using our [web application flow](https://docs.github.com/enterprise-server@3.0/developers/apps/authorizing-oauth-apps#web-application-flow). The [OAuth Authorizations API](https://docs.github.com/enterprise-server@3.0/rest/reference/oauth-authorizations) will be removed on November, 13, 2020. For more information, including scheduled brownouts, see the [blog post](https://developer.github.com/changes/2020-02-14-deprecating-oauth-auth-endpoint/).\n\n**Warning:** Apps must use the [web application flow](https://docs.github.com/enterprise-server@3.0/apps/building-oauth-apps/authorizing-oauth-apps/#web-application-flow) to obtain OAuth tokens that work with GitHub Enterprise Server SAML organizations. OAuth tokens created using the Authorizations API will be unable to access GitHub Enterprise Server SAML organizations. For more information, see the [blog post](https://developer.github.com/changes/2019-11-05-deprecated-passwords-and-authorizations-api).\n\nCreates OAuth tokens using [Basic Authentication](https://docs.github.com/enterprise-server@3.0/rest/overview/other-authentication-methods#basic-authentication). If you have two-factor authentication setup, Basic Authentication for this endpoint requires that you use a one-time password (OTP) and your username and password instead of tokens. For more information, see \"[Working with two-factor authentication](https://docs.github.com/enterprise-server@3.0/rest/overview/other-authentication-methods#working-with-two-factor-authentication).\"\n\nTo create tokens for a particular OAuth application using this endpoint, you must authenticate as the user you want to create an authorization for and provide the app's client ID and secret, found on your OAuth application's settings page. If your OAuth application intends to create multiple tokens for one user, use `fingerprint` to differentiate between them.\n\nYou can also create tokens on GitHub Enterprise Server from the [personal access tokens settings](https://github.com/settings/tokens) page. Read more about these tokens in [the GitHub Help documentation](https://docs.github.com/articles/creating-an-access-token-for-command-line-use).\n\nOrganizations that enforce SAML SSO require personal access tokens to be allowed. Read more about allowing tokens in [the GitHub Help documentation](https://docs.github.com/articles/about-identity-and-access-management-with-saml-single-sign-on).", "tags": [ "oauth-authorizations" ], "operationId": "oauth-authorizations/create-authorization", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/oauth-authorizations#create-a-new-authorization" }, "parameters": [ ], "requestBody": { "required": false, "content": { "application/json": { "schema": { "type": "object", "properties": { "scopes": { "description": "A list of scopes that this authorization is in.", "type": [ "array", "null" ], "items": { "type": "string" }, "examples": [ "public_repo", "user" ] }, "note": { "description": "A note to remind you what the OAuth token is for.", "type": "string", "examples": [ "Update all gems" ] }, "note_url": { "description": "A URL to remind you what app the OAuth token is for.", "type": "string" }, "client_id": { "description": "The OAuth app client key for which to create the token.", "maxLength": 20, "type": "string" }, "client_secret": { "description": "The OAuth app client secret for which to create the token.", "maxLength": 40, "type": "string" }, "fingerprint": { "description": "A unique string to distinguish an authorization from others created for the same client ID and user.", "type": "string" } } } } } }, "responses": { "201": { "description": "Response", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/authorization" }, "examples": { "default": { "$ref": "#/components/examples/authorization" } } } }, "headers": { "Location": { "example": "https://api.github.com/authorizations/1", "schema": { "type": "string" } } } }, "422": { "$ref": "#/components/responses/validation_failed" }, "410": { "$ref": "#/components/responses/gone" }, "304": { "$ref": "#/components/responses/not_modified" }, "403": { "$ref": "#/components/responses/forbidden" }, "401": { "$ref": "#/components/responses/requires_authentication" } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": false, "removalDate": "2020-11-13", "deprecationDate": "2020-02-14", "category": "oauth-authorizations", "subcategory": null }, "deprecated": true } }, "/authorizations/clients/{client_id}": { "put": { "summary": "Get-or-create an authorization for a specific app", "description": "**Deprecation Notice:** GitHub Enterprise Server will discontinue the [OAuth Authorizations API](https://docs.github.com/enterprise-server@3.0/rest/reference/oauth-authorizations/), which is used by integrations to create personal access tokens and OAuth tokens, and you must now create these tokens using our [web application flow](https://docs.github.com/enterprise-server@3.0/developers/apps/authorizing-oauth-apps#web-application-flow). The [OAuth Authorizations API](https://docs.github.com/enterprise-server@3.0/rest/reference/oauth-authorizations) will be removed on November, 13, 2020. For more information, including scheduled brownouts, see the [blog post](https://developer.github.com/changes/2020-02-14-deprecating-oauth-auth-endpoint/).\n\n**Warning:** Apps must use the [web application flow](https://docs.github.com/enterprise-server@3.0/apps/building-oauth-apps/authorizing-oauth-apps/#web-application-flow) to obtain OAuth tokens that work with GitHub Enterprise Server SAML organizations. OAuth tokens created using the Authorizations API will be unable to access GitHub Enterprise Server SAML organizations. For more information, see the [blog post](https://developer.github.com/changes/2019-11-05-deprecated-passwords-and-authorizations-api).\n\nCreates a new authorization for the specified OAuth application, only if an authorization for that application doesn't already exist for the user. The URL includes the 20 character client ID for the OAuth app that is requesting the token. It returns the user's existing authorization for the application if one is present. Otherwise, it creates and returns a new one.\n\nIf you have two-factor authentication setup, Basic Authentication for this endpoint requires that you use a one-time password (OTP) and your username and password instead of tokens. For more information, see \"[Working with two-factor authentication](https://docs.github.com/enterprise-server@3.0/rest/overview/other-authentication-methods#working-with-two-factor-authentication).\"\n\n**Deprecation Notice:** GitHub Enterprise Server will discontinue the [OAuth Authorizations API](https://docs.github.com/enterprise-server@3.0/rest/reference/oauth-authorizations/), which is used by integrations to create personal access tokens and OAuth tokens, and you must now create these tokens using our [web application flow](https://docs.github.com/enterprise-server@3.0/developers/apps/authorizing-oauth-apps#web-application-flow). The [OAuth Authorizations API](https://docs.github.com/enterprise-server@3.0/rest/reference/oauth-authorizations) will be removed on November, 13, 2020. For more information, including scheduled brownouts, see the [blog post](https://developer.github.com/changes/2020-02-14-deprecating-oauth-auth-endpoint/).", "tags": [ "oauth-authorizations" ], "operationId": "oauth-authorizations/get-or-create-authorization-for-app", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/oauth-authorizations#get-or-create-an-authorization-for-a-specific-app" }, "parameters": [ { "$ref": "#/components/parameters/client-id" } ], "requestBody": { "required": true, "content": { "application/json": { "schema": { "properties": { "client_secret": { "description": "The OAuth app client secret for which to create the token.", "maxLength": 40, "type": "string" }, "scopes": { "description": "A list of scopes that this authorization is in.", "type": [ "array", "null" ], "items": { "type": "string" }, "examples": [ "public_repo", "user" ] }, "note": { "description": "A note to remind you what the OAuth token is for.", "type": "string", "examples": [ "Update all gems" ] }, "note_url": { "description": "A URL to remind you what app the OAuth token is for.", "type": "string" }, "fingerprint": { "description": "A unique string to distinguish an authorization from others created for the same client ID and user.", "type": "string" } }, "required": [ "client_secret" ], "type": "object" } } } }, "responses": { "200": { "description": "if returning an existing token", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/authorization" }, "examples": { "response-if-returning-an-existing-token": { "$ref": "#/components/examples/authorization-response-if-returning-an-existing-token-2" } } } }, "headers": { "Location": { "example": "https://api.github.com/authorizations/1", "schema": { "type": "string" } } } }, "201": { "description": "**Deprecation Notice:** GitHub will discontinue the [OAuth Authorizations API](https://docs.github.com/enterprise-server@3.0/rest/reference/oauth-authorizations), which is used by integrations to create personal access tokens and OAuth tokens, and you must now create these tokens using our [web application flow](https://docs.github.com/enterprise-server@3.0/apps/building-oauth-apps/authorizing-oauth-apps/#web-application-flow). The [OAuth Authorizations API](https://docs.github.com/enterprise-server@3.0/rest/reference/oauth-authorizations) will be removed on November, 13, 2020. For more information, including scheduled brownouts, see the [blog post](https://developer.github.com/changes/2020-02-14-deprecating-oauth-auth-endpoint/).", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/authorization" }, "examples": { "default": { "$ref": "#/components/examples/authorization" } } } }, "headers": { "Location": { "example": "https://api.github.com/authorizations/1", "schema": { "type": "string" } } } }, "422": { "$ref": "#/components/responses/validation_failed" }, "304": { "$ref": "#/components/responses/not_modified" }, "403": { "$ref": "#/components/responses/forbidden" }, "401": { "$ref": "#/components/responses/requires_authentication" } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": false, "removalDate": "2020-11-13", "deprecationDate": "2020-02-14", "category": "oauth-authorizations", "subcategory": null }, "deprecated": true } }, "/authorizations/clients/{client_id}/{fingerprint}": { "put": { "summary": "Get-or-create an authorization for a specific app and fingerprint", "description": "**Deprecation Notice:** GitHub Enterprise Server will discontinue the [OAuth Authorizations API](https://docs.github.com/enterprise-server@3.0/rest/reference/oauth-authorizations/), which is used by integrations to create personal access tokens and OAuth tokens, and you must now create these tokens using our [web application flow](https://docs.github.com/enterprise-server@3.0/developers/apps/authorizing-oauth-apps#web-application-flow). The [OAuth Authorizations API](https://docs.github.com/enterprise-server@3.0/rest/reference/oauth-authorizations) will be removed on November, 13, 2020. For more information, including scheduled brownouts, see the [blog post](https://developer.github.com/changes/2020-02-14-deprecating-oauth-auth-endpoint/).\n\n**Warning:** Apps must use the [web application flow](https://docs.github.com/enterprise-server@3.0/apps/building-oauth-apps/authorizing-oauth-apps/#web-application-flow) to obtain OAuth tokens that work with GitHub Enterprise Server SAML organizations. OAuth tokens created using the Authorizations API will be unable to access GitHub Enterprise Server SAML organizations. For more information, see the [blog post](https://developer.github.com/changes/2019-11-05-deprecated-passwords-and-authorizations-api).\n\nThis method will create a new authorization for the specified OAuth application, only if an authorization for that application and fingerprint do not already exist for the user. The URL includes the 20 character client ID for the OAuth app that is requesting the token. `fingerprint` is a unique string to distinguish an authorization from others created for the same client ID and user. It returns the user's existing authorization for the application if one is present. Otherwise, it creates and returns a new one.\n\nIf you have two-factor authentication setup, Basic Authentication for this endpoint requires that you use a one-time password (OTP) and your username and password instead of tokens. For more information, see \"[Working with two-factor authentication](https://docs.github.com/enterprise-server@3.0/rest/overview/other-authentication-methods#working-with-two-factor-authentication).\"", "tags": [ "oauth-authorizations" ], "operationId": "oauth-authorizations/get-or-create-authorization-for-app-and-fingerprint", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/oauth-authorizations#get-or-create-an-authorization-for-a-specific-app-and-fingerprint" }, "parameters": [ { "$ref": "#/components/parameters/client-id" }, { "name": "fingerprint", "in": "path", "required": true, "schema": { "type": "string" } } ], "requestBody": { "required": true, "content": { "application/json": { "schema": { "properties": { "client_secret": { "description": "The OAuth app client secret for which to create the token.", "maxLength": 40, "type": "string" }, "scopes": { "description": "A list of scopes that this authorization is in.", "type": [ "array", "null" ], "items": { "type": "string" }, "examples": [ "public_repo", "user" ] }, "note": { "description": "A note to remind you what the OAuth token is for.", "type": "string", "examples": [ "Update all gems" ] }, "note_url": { "description": "A URL to remind you what app the OAuth token is for.", "type": "string" } }, "required": [ "client_secret" ], "type": "object" } } } }, "responses": { "200": { "description": "if returning an existing token", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/authorization" }, "examples": { "response-if-returning-an-existing-token": { "$ref": "#/components/examples/authorization-response-if-returning-an-existing-token" } } } }, "headers": { "Location": { "example": "https://api.github.com/authorizations/1", "schema": { "type": "string" } } } }, "201": { "description": "Response if returning a new token", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/authorization" }, "examples": { "default": { "$ref": "#/components/examples/authorization-3" } } } }, "headers": { "Location": { "example": "https://api.github.com/authorizations/1", "schema": { "type": "string" } } } }, "422": { "$ref": "#/components/responses/validation_failed" } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": false, "removalDate": "2020-11-13", "deprecationDate": "2020-02-14", "category": "oauth-authorizations", "subcategory": null }, "deprecated": true } }, "/authorizations/{authorization_id}": { "get": { "summary": "Get a single authorization", "description": "**Deprecation Notice:** GitHub Enterprise Server will discontinue the [OAuth Authorizations API](https://docs.github.com/enterprise-server@3.0/rest/reference/oauth-authorizations), which is used by integrations to create personal access tokens and OAuth tokens, and you must now create these tokens using our [web application flow](https://docs.github.com/enterprise-server@3.0/apps/building-oauth-apps/authorizing-oauth-apps/#web-application-flow). The [OAuth Authorizations API](https://docs.github.com/enterprise-server@3.0/rest/reference/oauth-authorizations) will be removed on November, 13, 2020. For more information, including scheduled brownouts, see the [blog post](https://developer.github.com/changes/2020-02-14-deprecating-oauth-auth-endpoint/).", "tags": [ "oauth-authorizations" ], "operationId": "oauth-authorizations/get-authorization", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/oauth-authorizations#get-a-single-authorization" }, "parameters": [ { "$ref": "#/components/parameters/authorization-id" } ], "responses": { "200": { "description": "Response", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/authorization" }, "examples": { "default": { "$ref": "#/components/examples/authorization-2" } } } } }, "304": { "$ref": "#/components/responses/not_modified" }, "403": { "$ref": "#/components/responses/forbidden" }, "401": { "$ref": "#/components/responses/requires_authentication" } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": false, "removalDate": "2020-11-13", "deprecationDate": "2020-02-14", "category": "oauth-authorizations", "subcategory": null }, "deprecated": true }, "patch": { "summary": "Update an existing authorization", "description": "**Deprecation Notice:** GitHub Enterprise Server will discontinue the [OAuth Authorizations API](https://docs.github.com/enterprise-server@3.0/rest/reference/oauth-authorizations/), which is used by integrations to create personal access tokens and OAuth tokens, and you must now create these tokens using our [web application flow](https://docs.github.com/enterprise-server@3.0/developers/apps/authorizing-oauth-apps#web-application-flow). The [OAuth Authorizations API](https://docs.github.com/enterprise-server@3.0/rest/reference/oauth-authorizations) will be removed on November, 13, 2020. For more information, including scheduled brownouts, see the [blog post](https://developer.github.com/changes/2020-02-14-deprecating-oauth-auth-endpoint/).\n\nIf you have two-factor authentication setup, Basic Authentication for this endpoint requires that you use a one-time password (OTP) and your username and password instead of tokens. For more information, see \"[Working with two-factor authentication](https://docs.github.com/enterprise-server@3.0/rest/overview/other-authentication-methods#working-with-two-factor-authentication).\"\n\nYou can only send one of these scope keys at a time.", "tags": [ "oauth-authorizations" ], "operationId": "oauth-authorizations/update-authorization", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/oauth-authorizations#update-an-existing-authorization" }, "parameters": [ { "$ref": "#/components/parameters/authorization-id" } ], "requestBody": { "required": false, "content": { "application/json": { "schema": { "type": "object", "properties": { "scopes": { "description": "A list of scopes that this authorization is in.", "type": [ "array", "null" ], "items": { "type": "string" }, "examples": [ "public_repo", "user" ] }, "add_scopes": { "description": "A list of scopes to add to this authorization.", "type": "array", "items": { "type": "string" } }, "remove_scopes": { "description": "A list of scopes to remove from this authorization.", "type": "array", "items": { "type": "string" } }, "note": { "description": "A note to remind you what the OAuth token is for.", "type": "string", "examples": [ "Update all gems" ] }, "note_url": { "description": "A URL to remind you what app the OAuth token is for.", "type": "string" }, "fingerprint": { "description": "A unique string to distinguish an authorization from others created for the same client ID and user.", "type": "string" } } } } } }, "responses": { "200": { "description": "Response", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/authorization" }, "examples": { "default": { "$ref": "#/components/examples/authorization-2" } } } } }, "422": { "$ref": "#/components/responses/validation_failed" } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": false, "removalDate": "2020-11-13", "deprecationDate": "2020-02-14", "category": "oauth-authorizations", "subcategory": null }, "deprecated": true }, "delete": { "summary": "Delete an authorization", "description": "**Deprecation Notice:** GitHub Enterprise Server will discontinue the [OAuth Authorizations API](https://docs.github.com/enterprise-server@3.0/rest/reference/oauth-authorizations), which is used by integrations to create personal access tokens and OAuth tokens, and you must now create these tokens using our [web application flow](https://docs.github.com/enterprise-server@3.0/apps/building-oauth-apps/authorizing-oauth-apps/#web-application-flow). The [OAuth Authorizations API](https://docs.github.com/enterprise-server@3.0/rest/reference/oauth-authorizations) will be removed on November, 13, 2020. For more information, including scheduled brownouts, see the [blog post](https://developer.github.com/changes/2020-02-14-deprecating-oauth-auth-endpoint/).", "tags": [ "oauth-authorizations" ], "operationId": "oauth-authorizations/delete-authorization", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/oauth-authorizations#delete-an-authorization" }, "parameters": [ { "$ref": "#/components/parameters/authorization-id" } ], "responses": { "204": { "description": "Response" }, "304": { "$ref": "#/components/responses/not_modified" }, "403": { "$ref": "#/components/responses/forbidden" }, "401": { "$ref": "#/components/responses/requires_authentication" } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": false, "removalDate": "2020-11-13", "deprecationDate": "2020-02-14", "category": "oauth-authorizations", "subcategory": null }, "deprecated": true } }, "/codes_of_conduct": { "get": { "summary": "Get all codes of conduct", "description": "", "tags": [ "codes-of-conduct" ], "operationId": "codes-of-conduct/get-all-codes-of-conduct", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/codes-of-conduct#get-all-codes-of-conduct" }, "parameters": [ ], "responses": { "200": { "description": "Response", "content": { "application/json": { "schema": { "type": "array", "items": { "$ref": "#/components/schemas/code-of-conduct" } }, "examples": { "default": { "$ref": "#/components/examples/code-of-conduct-simple-items" } } } } }, "304": { "$ref": "#/components/responses/not_modified" } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": true, "category": "codes-of-conduct", "subcategory": null } } }, "/codes_of_conduct/{key}": { "get": { "summary": "Get a code of conduct", "description": "", "tags": [ "codes-of-conduct" ], "operationId": "codes-of-conduct/get-conduct-code", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/codes-of-conduct#get-a-code-of-conduct" }, "parameters": [ { "name": "key", "in": "path", "required": true, "schema": { "type": "string" } } ], "responses": { "200": { "description": "Response", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/code-of-conduct" }, "examples": { "default": { "$ref": "#/components/examples/code-of-conduct" } } } } }, "404": { "$ref": "#/components/responses/not_found" }, "304": { "$ref": "#/components/responses/not_modified" } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": true, "category": "codes-of-conduct", "subcategory": null } } }, "/emojis": { "get": { "summary": "Get emojis", "description": "Lists all the emojis available to use on GitHub Enterprise Server.", "operationId": "emojis/get", "tags": [ "emojis" ], "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/emojis#get-emojis" }, "parameters": [ ], "responses": { "200": { "content": { "application/json": { "schema": { "type": "object", "additionalProperties": { "type": "string" } } } }, "description": "Response" }, "304": { "$ref": "#/components/responses/not_modified" } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": true, "category": "emojis", "subcategory": null } } }, "/enterprise/announcement": { "get": { "summary": "Get the global announcement banner", "description": "Gets the current message and expiration date of the global announcement banner in your enterprise.", "tags": [ "enterprise-admin" ], "operationId": "enterprise-admin/get-announcement", "responses": { "200": { "description": "Response", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/announcement" }, "examples": { "default": { "$ref": "#/components/examples/announcement" } } } } } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": false, "category": "enterprise-admin", "subcategory": "announcement" } }, "patch": { "summary": "Set the global announcement banner", "description": "Sets the message and expiration time for the global announcement banner in your enterprise.", "tags": [ "enterprise-admin" ], "operationId": "enterprise-admin/set-announcement", "requestBody": { "required": true, "content": { "application/json": { "schema": { "$ref": "#/components/schemas/announcement" } } } }, "responses": { "200": { "description": "Response", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/announcement" }, "examples": { "default": { "$ref": "#/components/examples/announcement" } } } } } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": false, "category": "enterprise-admin", "subcategory": "announcement" } }, "delete": { "summary": "Remove the global announcement banner", "description": "Removes the global announcement banner in your enterprise.", "tags": [ "enterprise-admin" ], "operationId": "enterprise-admin/remove-announcement", "responses": { "204": { "description": "Response" } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": false, "category": "enterprise-admin", "subcategory": "announcement" } } }, "/enterprise/settings/license": { "get": { "summary": "Get license information", "description": "", "operationId": "enterprise-admin/get-license-information", "tags": [ "enterprise-admin" ], "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/enterprise-admin#get-license-information" }, "responses": { "200": { "description": "Response", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/license-info" }, "examples": { "default": { "$ref": "#/components/examples/license-info" } } } } } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": false, "category": "enterprise-admin", "subcategory": "license" } } }, "/enterprise/stats/all": { "get": { "summary": "Get all statistics", "description": "", "operationId": "enterprise-admin/get-all-stats", "tags": [ "enterprise-admin" ], "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/enterprise-admin#get-statistics" }, "responses": { "200": { "description": "Response", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/enterprise-overview" }, "examples": { "default": { "$ref": "#/components/examples/enterprise-overview" } } } } } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": false, "category": "enterprise-admin", "subcategory": "admin-stats" } } }, "/enterprise/stats/comments": { "get": { "summary": "Get comment statistics", "description": "", "operationId": "enterprise-admin/get-comment-stats", "tags": [ "enterprise-admin" ], "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/enterprise-admin#get-comment-statistics" }, "responses": { "200": { "description": "Response", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/enterprise-comment-overview" } } } } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": false, "category": "enterprise-admin", "subcategory": "admin-stats" } } }, "/enterprise/stats/gists": { "get": { "summary": "Get gist statistics", "description": "", "operationId": "enterprise-admin/get-gist-stats", "tags": [ "enterprise-admin" ], "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/enterprise-admin#get-gist-statistics" }, "responses": { "200": { "description": "Response", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/enterprise-gist-overview" } } } } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": false, "category": "enterprise-admin", "subcategory": "admin-stats" } } }, "/enterprise/stats/hooks": { "get": { "summary": "Get hooks statistics", "operationId": "enterprise-admin/get-hooks-stats", "tags": [ "enterprise-admin" ], "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/enterprise-admin#get-hooks-statistics" }, "responses": { "200": { "description": "Response", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/enterprise-hook-overview" } } } } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": false, "category": "enterprise-admin", "subcategory": "admin-stats" } } }, "/enterprise/stats/issues": { "get": { "summary": "Get issue statistics", "description": "", "operationId": "enterprise-admin/get-issue-stats", "tags": [ "enterprise-admin" ], "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/enterprise-admin#get-issues-statistics" }, "responses": { "200": { "description": "Response", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/enterprise-issue-overview" } } } } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": false, "category": "enterprise-admin", "subcategory": "admin-stats" } } }, "/enterprise/stats/milestones": { "get": { "summary": "Get milestone statistics", "description": "", "operationId": "enterprise-admin/get-milestone-stats", "tags": [ "enterprise-admin" ], "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/enterprise-admin#get-milestone-statistics" }, "responses": { "200": { "description": "Response", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/enterprise-milestone-overview" } } } } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": false, "category": "enterprise-admin", "subcategory": "admin-stats" } } }, "/enterprise/stats/orgs": { "get": { "summary": "Get organization statistics", "description": "", "operationId": "enterprise-admin/get-org-stats", "tags": [ "enterprise-admin" ], "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/enterprise-admin#get-organization-statistics" }, "responses": { "200": { "description": "Response", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/enterprise-organization-overview" } } } } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": false, "category": "enterprise-admin", "subcategory": "admin-stats" } } }, "/enterprise/stats/pages": { "get": { "summary": "Get pages statistics", "description": "", "operationId": "enterprise-admin/get-pages-stats", "tags": [ "enterprise-admin" ], "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/enterprise-admin#get-pages-statistics" }, "responses": { "200": { "description": "Response", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/enterprise-page-overview" } } } } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": false, "category": "enterprise-admin", "subcategory": "admin-stats" } } }, "/enterprise/stats/pulls": { "get": { "summary": "Get pull request statistics", "description": "", "operationId": "enterprise-admin/get-pull-request-stats", "tags": [ "enterprise-admin" ], "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/enterprise-admin#get-pull-requests-statistics" }, "responses": { "200": { "description": "Response", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/enterprise-pull-request-overview" } } } } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": false, "category": "enterprise-admin", "subcategory": "admin-stats" } } }, "/enterprise/stats/repos": { "get": { "summary": "Get repository statistics", "operationId": "enterprise-admin/get-repo-stats", "tags": [ "enterprise-admin" ], "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/enterprise-admin#get-repository-statistics" }, "responses": { "200": { "description": "Response", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/enterprise-repository-overview" } } } } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": false, "category": "enterprise-admin", "subcategory": "admin-stats" } } }, "/enterprise/stats/users": { "get": { "summary": "Get users statistics", "description": "", "operationId": "enterprise-admin/get-user-stats", "tags": [ "enterprise-admin" ], "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/enterprise-admin#get-users-statistics" }, "responses": { "200": { "description": "Response", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/enterprise-user-overview" } } } } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": false, "category": "enterprise-admin", "subcategory": "admin-stats" } } }, "/enterprises/{enterprise}/actions/permissions": { "get": { "summary": "Get GitHub Actions permissions for an enterprise", "description": "Gets the GitHub Actions permissions policy for organizations and allowed actions in an enterprise.\n\nYou must authenticate using an access token with the `admin:enterprise` scope to use this endpoint.", "operationId": "enterprise-admin/get-github-actions-permissions-enterprise", "tags": [ "enterprise-admin" ], "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/actions#get-github-actions-permissions-for-an-enterprise" }, "parameters": [ { "$ref": "#/components/parameters/enterprise" } ], "responses": { "200": { "description": "Response", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/actions-enterprise-permissions" }, "examples": { "default": { "$ref": "#/components/examples/actions-enterprise-permissions" } } } } } }, "x-github": { "enabledForGitHubApps": false, "githubCloudOnly": false, "category": "actions", "subcategory": "permissions" } }, "put": { "summary": "Set GitHub Actions permissions for an enterprise", "description": "Sets the GitHub Actions permissions policy for organizations and allowed actions in an enterprise.\n\nYou must authenticate using an access token with the `admin:enterprise` scope to use this endpoint.", "operationId": "enterprise-admin/set-github-actions-permissions-enterprise", "tags": [ "enterprise-admin" ], "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/actions#set-github-actions-permissions-for-an-enterprise" }, "parameters": [ { "$ref": "#/components/parameters/enterprise" } ], "responses": { "204": { "description": "Response" } }, "requestBody": { "required": true, "content": { "application/json": { "schema": { "type": "object", "properties": { "enabled_organizations": { "$ref": "#/components/schemas/enabled-organizations" }, "allowed_actions": { "$ref": "#/components/schemas/allowed-actions" } }, "required": [ "enabled_organizations" ] }, "example": { "enabled_organizations": "all", "allowed_actions": "selected" } } } }, "x-github": { "enabledForGitHubApps": false, "githubCloudOnly": false, "category": "actions", "subcategory": "permissions" } } }, "/enterprises/{enterprise}/actions/permissions/organizations": { "get": { "summary": "List selected organizations enabled for GitHub Actions in an enterprise", "description": "Lists the organizations that are selected to have GitHub Actions enabled in an enterprise. To use this endpoint, the enterprise permission policy for `enabled_organizations` must be configured to `selected`. For more information, see \"[Set GitHub Actions permissions for an enterprise](#set-github-actions-permissions-for-an-enterprise).\"\n\nYou must authenticate using an access token with the `admin:enterprise` scope to use this endpoint.", "operationId": "enterprise-admin/list-selected-organizations-enabled-github-actions-enterprise", "tags": [ "enterprise-admin" ], "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/actions#list-selected-organizations-enabled-for-github-actions-in-an-enterprise" }, "parameters": [ { "$ref": "#/components/parameters/enterprise" }, { "$ref": "#/components/parameters/per-page" }, { "$ref": "#/components/parameters/page" } ], "responses": { "200": { "description": "Response", "content": { "application/json": { "schema": { "type": "object", "properties": { "total_count": { "type": "number" }, "organizations": { "type": "array", "items": { "$ref": "#/components/schemas/organization-simple" } } }, "required": [ "total_count", "organizations" ] }, "examples": { "default": { "$ref": "#/components/examples/organization-targets" } } } } } }, "x-github": { "enabledForGitHubApps": false, "githubCloudOnly": false, "category": "actions", "subcategory": "permissions" } }, "put": { "summary": "Set selected organizations enabled for GitHub Actions in an enterprise", "description": "Replaces the list of selected organizations that are enabled for GitHub Actions in an enterprise. To use this endpoint, the enterprise permission policy for `enabled_organizations` must be configured to `selected`. For more information, see \"[Set GitHub Actions permissions for an enterprise](#set-github-actions-permissions-for-an-enterprise).\"\n\nYou must authenticate using an access token with the `admin:enterprise` scope to use this endpoint.", "operationId": "enterprise-admin/set-selected-organizations-enabled-github-actions-enterprise", "tags": [ "enterprise-admin" ], "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/actions#set-selected-organizations-enabled-for-github-actions-in-an-enterprise" }, "parameters": [ { "$ref": "#/components/parameters/enterprise" } ], "responses": { "204": { "description": "Response" } }, "requestBody": { "required": true, "content": { "application/json": { "schema": { "type": "object", "properties": { "selected_organization_ids": { "description": "List of organization IDs to enable for GitHub Actions.", "type": "array", "items": { "type": "integer", "description": "Unique identifier of the organization." } } }, "required": [ "selected_organization_ids" ] }, "example": { "selected_organization_ids": [ 32, 91 ] } } } }, "x-github": { "enabledForGitHubApps": false, "githubCloudOnly": false, "category": "actions", "subcategory": "permissions" } } }, "/enterprises/{enterprise}/actions/permissions/organizations/{org_id}": { "put": { "summary": "Enable a selected organization for GitHub Actions in an enterprise", "description": "Adds an organization to the list of selected organizations that are enabled for GitHub Actions in an enterprise. To use this endpoint, the enterprise permission policy for `enabled_organizations` must be configured to `selected`. For more information, see \"[Set GitHub Actions permissions for an enterprise](#set-github-actions-permissions-for-an-enterprise).\"\n\nYou must authenticate using an access token with the `admin:enterprise` scope to use this endpoint.", "operationId": "enterprise-admin/enable-selected-organization-github-actions-enterprise", "tags": [ "enterprise-admin" ], "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/actions#enable-a-selected-organization-for-github-actions-in-an-enterprise" }, "parameters": [ { "$ref": "#/components/parameters/enterprise" }, { "$ref": "#/components/parameters/org-id" } ], "responses": { "204": { "description": "Response" } }, "x-github": { "enabledForGitHubApps": false, "githubCloudOnly": false, "category": "actions", "subcategory": "permissions" } }, "delete": { "summary": "Disable a selected organization for GitHub Actions in an enterprise", "description": "Removes an organization from the list of selected organizations that are enabled for GitHub Actions in an enterprise. To use this endpoint, the enterprise permission policy for `enabled_organizations` must be configured to `selected`. For more information, see \"[Set GitHub Actions permissions for an enterprise](#set-github-actions-permissions-for-an-enterprise).\"\n\nYou must authenticate using an access token with the `admin:enterprise` scope to use this endpoint.", "operationId": "enterprise-admin/disable-selected-organization-github-actions-enterprise", "tags": [ "enterprise-admin" ], "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/actions#disable-a-selected-organization-for-github-actions-in-an-enterprise" }, "parameters": [ { "$ref": "#/components/parameters/enterprise" }, { "$ref": "#/components/parameters/org-id" } ], "responses": { "204": { "description": "Response" } }, "x-github": { "enabledForGitHubApps": false, "githubCloudOnly": false, "category": "actions", "subcategory": "permissions" } } }, "/enterprises/{enterprise}/actions/permissions/selected-actions": { "get": { "summary": "Get allowed actions for an enterprise", "description": "Gets the selected actions that are allowed in an enterprise. To use this endpoint, the enterprise permission policy for `allowed_actions` must be configured to `selected`. For more information, see \"[Set GitHub Actions permissions for an enterprise](#set-github-actions-permissions-for-an-enterprise).\"\n\nYou must authenticate using an access token with the `admin:enterprise` scope to use this endpoint.", "operationId": "enterprise-admin/get-allowed-actions-enterprise", "tags": [ "enterprise-admin" ], "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/actions#get-allowed-actions-for-an-enterprise" }, "parameters": [ { "$ref": "#/components/parameters/enterprise" } ], "responses": { "200": { "description": "Response", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/selected-actions" }, "examples": { "default": { "$ref": "#/components/examples/selected-actions" } } } } } }, "x-github": { "enabledForGitHubApps": false, "githubCloudOnly": false, "category": "actions", "subcategory": "permissions" } }, "put": { "summary": "Set allowed actions for an enterprise", "description": "Sets the actions that are allowed in an enterprise. To use this endpoint, the enterprise permission policy for `allowed_actions` must be configured to `selected`. For more information, see \"[Set GitHub Actions permissions for an enterprise](#set-github-actions-permissions-for-an-enterprise).\"\n\nYou must authenticate using an access token with the `admin:enterprise` scope to use this endpoint.", "operationId": "enterprise-admin/set-allowed-actions-enterprise", "tags": [ "enterprise-admin" ], "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/actions#set-allowed-actions-for-an-enterprise" }, "parameters": [ { "$ref": "#/components/parameters/enterprise" } ], "responses": { "204": { "description": "Response" } }, "requestBody": { "required": true, "content": { "application/json": { "schema": { "$ref": "#/components/schemas/selected-actions" }, "examples": { "selected_actions": { "$ref": "#/components/examples/selected-actions" } } } } }, "x-github": { "enabledForGitHubApps": false, "githubCloudOnly": false, "category": "actions", "subcategory": "permissions" } } }, "/enterprises/{enterprise}/actions/runner-groups": { "get": { "summary": "List self-hosted runner groups for an enterprise", "description": "Lists all self-hosted runner groups for an enterprise.\n\nYou must authenticate using an access token with the `admin:enterprise` scope to use this endpoint.", "operationId": "enterprise-admin/list-self-hosted-runner-groups-for-enterprise", "tags": [ "enterprise-admin" ], "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/actions#list-self-hosted-runner-groups-for-an-enterprise" }, "parameters": [ { "$ref": "#/components/parameters/enterprise" }, { "$ref": "#/components/parameters/per-page" }, { "$ref": "#/components/parameters/page" } ], "responses": { "200": { "description": "Response", "content": { "application/json": { "schema": { "type": "object", "properties": { "total_count": { "type": "number" }, "runner_groups": { "type": "array", "items": { "$ref": "#/components/schemas/runner-groups-enterprise" } } }, "required": [ "total_count", "runner_groups" ] }, "examples": { "default": { "$ref": "#/components/examples/runner-groups-enterprise" } } } } } }, "x-github": { "enabledForGitHubApps": false, "githubCloudOnly": false, "category": "actions", "subcategory": "self-hosted-runner-groups" } }, "post": { "summary": "Create a self-hosted runner group for an enterprise", "description": "Creates a new self-hosted runner group for an enterprise.\n\nYou must authenticate using an access token with the `admin:enterprise` scope to use this endpoint.", "operationId": "enterprise-admin/create-self-hosted-runner-group-for-enterprise", "tags": [ "enterprise-admin" ], "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/actions#create-self-hosted-runner-group-for-an-enterprise" }, "parameters": [ { "$ref": "#/components/parameters/enterprise" } ], "requestBody": { "required": true, "content": { "application/json": { "schema": { "type": "object", "properties": { "name": { "description": "Name of the runner group.", "type": "string" }, "visibility": { "description": "Visibility of a runner group. You can select all organizations or select individual organization. Can be one of: `all` or `selected`", "type": "string", "enum": [ "selected", "all" ] }, "selected_organization_ids": { "description": "List of organization IDs that can access the runner group.", "type": "array", "items": { "type": "integer", "description": "Unique identifier of the organization." } }, "runners": { "description": "List of runner IDs to add to the runner group.", "type": "array", "items": { "type": "integer", "description": "Unique identifier of the runner." } }, "allows_public_repositories": { "description": "Whether the runner group can be used by `public` repositories.", "type": "boolean", "default": false } }, "required": [ "name" ] }, "example": { "name": "Expensive hardware runners", "visibility": "selected", "selected_organization_ids": [ 32, 91 ], "runners": [ 9, 2 ] } } } }, "responses": { "201": { "description": "Response", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/runner-groups-enterprise" }, "examples": { "default": { "$ref": "#/components/examples/runner-group-enterprise" } } } } } }, "x-github": { "enabledForGitHubApps": false, "githubCloudOnly": false, "category": "actions", "subcategory": "self-hosted-runner-groups" } } }, "/enterprises/{enterprise}/actions/runner-groups/{runner_group_id}": { "get": { "summary": "Get a self-hosted runner group for an enterprise", "description": "Gets a specific self-hosted runner group for an enterprise.\n\nYou must authenticate using an access token with the `admin:enterprise` scope to use this endpoint.", "operationId": "enterprise-admin/get-self-hosted-runner-group-for-enterprise", "tags": [ "enterprise-admin" ], "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/actions#get-a-self-hosted-runner-group-for-an-enterprise" }, "parameters": [ { "$ref": "#/components/parameters/enterprise" }, { "$ref": "#/components/parameters/runner-group-id" } ], "responses": { "200": { "description": "Response", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/runner-groups-enterprise" }, "examples": { "default": { "$ref": "#/components/examples/runner-group-enterprise" } } } } } }, "x-github": { "enabledForGitHubApps": false, "githubCloudOnly": false, "category": "actions", "subcategory": "self-hosted-runner-groups" } }, "patch": { "summary": "Update a self-hosted runner group for an enterprise", "description": "Updates the `name` and `visibility` of a self-hosted runner group in an enterprise.\n\nYou must authenticate using an access token with the `admin:enterprise` scope to use this endpoint.", "operationId": "enterprise-admin/update-self-hosted-runner-group-for-enterprise", "tags": [ "enterprise-admin" ], "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/actions#update-a-self-hosted-runner-group-for-an-enterprise" }, "parameters": [ { "$ref": "#/components/parameters/enterprise" }, { "$ref": "#/components/parameters/runner-group-id" } ], "requestBody": { "required": false, "content": { "application/json": { "schema": { "type": "object", "properties": { "name": { "description": "Name of the runner group.", "type": "string" }, "visibility": { "description": "Visibility of a runner group. You can select all organizations or select individual organizations. Can be one of: `all` or `selected`", "type": "string", "enum": [ "selected", "all" ], "default": "all" }, "allows_public_repositories": { "description": "Whether the runner group can be used by `public` repositories.", "type": "boolean", "default": false } } }, "example": { "name": "Expensive hardware runners", "visibility": "selected" } } } }, "responses": { "200": { "description": "Response", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/runner-groups-enterprise" }, "examples": { "default": { "$ref": "#/components/examples/runner-group-update-enterprise" } } } } } }, "x-github": { "enabledForGitHubApps": false, "githubCloudOnly": false, "category": "actions", "subcategory": "self-hosted-runner-groups" } }, "delete": { "summary": "Delete a self-hosted runner group from an enterprise", "description": "Deletes a self-hosted runner group for an enterprise.\n\nYou must authenticate using an access token with the `admin:enterprise` scope to use this endpoint.", "operationId": "enterprise-admin/delete-self-hosted-runner-group-from-enterprise", "tags": [ "enterprise-admin" ], "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/actions#delete-a-self-hosted-runner-group-from-an-enterprise" }, "parameters": [ { "$ref": "#/components/parameters/enterprise" }, { "$ref": "#/components/parameters/runner-group-id" } ], "responses": { "204": { "description": "Response" } }, "x-github": { "enabledForGitHubApps": false, "githubCloudOnly": false, "category": "actions", "subcategory": "self-hosted-runner-groups" } } }, "/enterprises/{enterprise}/actions/runner-groups/{runner_group_id}/organizations": { "get": { "summary": "List organization access to a self-hosted runner group in an enterprise", "description": "Lists the organizations with access to a self-hosted runner group.\n\nYou must authenticate using an access token with the `admin:enterprise` scope to use this endpoint.", "operationId": "enterprise-admin/list-org-access-to-self-hosted-runner-group-in-enterprise", "tags": [ "enterprise-admin" ], "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/actions#list-organization-access-to-a-self-hosted-runner-group-in-a-enterprise" }, "parameters": [ { "$ref": "#/components/parameters/enterprise" }, { "$ref": "#/components/parameters/runner-group-id" }, { "$ref": "#/components/parameters/per-page" }, { "$ref": "#/components/parameters/page" } ], "responses": { "200": { "description": "Response", "content": { "application/json": { "schema": { "type": "object", "properties": { "total_count": { "type": "number" }, "organizations": { "type": "array", "items": { "$ref": "#/components/schemas/organization-simple" } } }, "required": [ "total_count", "organizations" ] }, "examples": { "default": { "$ref": "#/components/examples/organization-targets" } } } } } }, "x-github": { "enabledForGitHubApps": false, "githubCloudOnly": false, "category": "actions", "subcategory": "self-hosted-runner-groups" } }, "put": { "summary": "Set organization access for a self-hosted runner group in an enterprise", "description": "Replaces the list of organizations that have access to a self-hosted runner configured in an enterprise.\n\nYou must authenticate using an access token with the `admin:enterprise` scope to use this endpoint.", "operationId": "enterprise-admin/set-org-access-to-self-hosted-runner-group-in-enterprise", "tags": [ "enterprise-admin" ], "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/actions#set-organization-access-to-a-self-hosted-runner-group-in-an-enterprise" }, "parameters": [ { "$ref": "#/components/parameters/enterprise" }, { "$ref": "#/components/parameters/runner-group-id" } ], "requestBody": { "required": true, "content": { "application/json": { "schema": { "type": "object", "properties": { "selected_organization_ids": { "description": "List of organization IDs that can access the runner group.", "type": "array", "items": { "type": "integer", "description": "Unique identifier of the organization." } } }, "required": [ "selected_organization_ids" ] }, "example": { "selected_organization_ids": [ 32, 91 ] } } } }, "responses": { "204": { "description": "Response" } }, "x-github": { "enabledForGitHubApps": false, "githubCloudOnly": false, "category": "actions", "subcategory": "self-hosted-runner-groups" } } }, "/enterprises/{enterprise}/actions/runner-groups/{runner_group_id}/organizations/{org_id}": { "put": { "summary": "Add organization access to a self-hosted runner group in an enterprise", "description": "Adds an organization to the list of selected organizations that can access a self-hosted runner group. The runner group must have `visibility` set to `selected`. For more information, see \"[Create a self-hosted runner group for an enterprise](#create-a-self-hosted-runner-group-for-an-enterprise).\"\n\nYou must authenticate using an access token with the `admin:enterprise` scope to use this endpoint.", "operationId": "enterprise-admin/add-org-access-to-self-hosted-runner-group-in-enterprise", "tags": [ "enterprise-admin" ], "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/actions#add-organization-access-to-a-self-hosted-runner-group-in-an-enterprise" }, "parameters": [ { "$ref": "#/components/parameters/enterprise" }, { "$ref": "#/components/parameters/runner-group-id" }, { "$ref": "#/components/parameters/org-id" } ], "responses": { "204": { "description": "Response" } }, "x-github": { "enabledForGitHubApps": false, "githubCloudOnly": false, "category": "actions", "subcategory": "self-hosted-runner-groups" } }, "delete": { "summary": "Remove organization access to a self-hosted runner group in an enterprise", "description": "Removes an organization from the list of selected organizations that can access a self-hosted runner group. The runner group must have `visibility` set to `selected`. For more information, see \"[Create a self-hosted runner group for an enterprise](#create-a-self-hosted-runner-group-for-an-enterprise).\"\n\nYou must authenticate using an access token with the `admin:enterprise` scope to use this endpoint.", "operationId": "enterprise-admin/remove-org-access-to-self-hosted-runner-group-in-enterprise", "tags": [ "enterprise-admin" ], "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/actions#remove-organization-access-to-a-self-hosted-runner-group-in-an-enterprise" }, "parameters": [ { "$ref": "#/components/parameters/enterprise" }, { "$ref": "#/components/parameters/runner-group-id" }, { "$ref": "#/components/parameters/org-id" } ], "responses": { "204": { "description": "Response" } }, "x-github": { "enabledForGitHubApps": false, "githubCloudOnly": false, "category": "actions", "subcategory": "self-hosted-runner-groups" } } }, "/enterprises/{enterprise}/actions/runner-groups/{runner_group_id}/runners": { "get": { "summary": "List self-hosted runners in a group for an enterprise", "description": "Lists the self-hosted runners that are in a specific enterprise group.\n\nYou must authenticate using an access token with the `admin:enterprise` scope to use this endpoint.", "operationId": "enterprise-admin/list-self-hosted-runners-in-group-for-enterprise", "tags": [ "enterprise-admin" ], "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/actions#list-self-hosted-runners-in-a-group-for-an-enterprise" }, "parameters": [ { "$ref": "#/components/parameters/enterprise" }, { "$ref": "#/components/parameters/runner-group-id" }, { "$ref": "#/components/parameters/per-page" }, { "$ref": "#/components/parameters/page" } ], "responses": { "200": { "description": "Response", "content": { "application/json": { "schema": { "type": "object", "properties": { "total_count": { "type": "number" }, "runners": { "type": "array", "items": { "$ref": "#/components/schemas/runner" } } }, "required": [ "total_count", "runners" ] }, "examples": { "default": { "$ref": "#/components/examples/runner-paginated" } } } }, "headers": { "Link": { "$ref": "#/components/headers/link" } } } }, "x-github": { "enabledForGitHubApps": false, "githubCloudOnly": false, "category": "actions", "subcategory": "self-hosted-runner-groups" } }, "put": { "summary": "Set self-hosted runners in a group for an enterprise", "description": "Replaces the list of self-hosted runners that are part of an enterprise runner group.\n\nYou must authenticate using an access token with the `admin:enterprise` scope to use this endpoint.", "operationId": "enterprise-admin/set-self-hosted-runners-in-group-for-enterprise", "tags": [ "enterprise-admin" ], "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/actions#set-self-hosted-runners-in-a-group-for-an-enterprise" }, "parameters": [ { "$ref": "#/components/parameters/enterprise" }, { "$ref": "#/components/parameters/runner-group-id" } ], "requestBody": { "required": true, "content": { "application/json": { "schema": { "type": "object", "properties": { "runners": { "description": "List of runner IDs to add to the runner group.", "type": "array", "items": { "type": "integer", "description": "Unique identifier of the runner." } } }, "required": [ "runners" ] }, "example": { "runners": [ 9, 2 ] } } } }, "responses": { "204": { "description": "Response" } }, "x-github": { "enabledForGitHubApps": false, "githubCloudOnly": false, "category": "actions", "subcategory": "self-hosted-runner-groups" } } }, "/enterprises/{enterprise}/actions/runner-groups/{runner_group_id}/runners/{runner_id}": { "put": { "summary": "Add a self-hosted runner to a group for an enterprise", "description": "Adds a self-hosted runner to a runner group configured in an enterprise.\n\nYou must authenticate using an access token with the `admin:enterprise`\nscope to use this endpoint.", "operationId": "enterprise-admin/add-self-hosted-runner-to-group-for-enterprise", "tags": [ "enterprise-admin" ], "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/actions#add-a-self-hosted-runner-to-a-group-for-an-enterprise" }, "parameters": [ { "$ref": "#/components/parameters/enterprise" }, { "$ref": "#/components/parameters/runner-group-id" }, { "$ref": "#/components/parameters/runner-id" } ], "responses": { "204": { "description": "Response" } }, "x-github": { "enabledForGitHubApps": false, "githubCloudOnly": false, "category": "actions", "subcategory": "self-hosted-runner-groups" } }, "delete": { "summary": "Remove a self-hosted runner from a group for an enterprise", "description": "Removes a self-hosted runner from a group configured in an enterprise. The runner is then returned to the default group.\n\nYou must authenticate using an access token with the `admin:enterprise` scope to use this endpoint.", "operationId": "enterprise-admin/remove-self-hosted-runner-from-group-for-enterprise", "tags": [ "enterprise-admin" ], "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/actions#remove-a-self-hosted-runner-from-a-group-for-an-enterprise" }, "parameters": [ { "$ref": "#/components/parameters/enterprise" }, { "$ref": "#/components/parameters/runner-group-id" }, { "$ref": "#/components/parameters/runner-id" } ], "responses": { "204": { "description": "Response" } }, "x-github": { "enabledForGitHubApps": false, "githubCloudOnly": false, "category": "actions", "subcategory": "self-hosted-runner-groups" } } }, "/enterprises/{enterprise}/actions/runners": { "get": { "summary": "List self-hosted runners for an enterprise", "description": "Lists all self-hosted runners configured for an enterprise.\n\nYou must authenticate using an access token with the `admin:enterprise` scope to use this endpoint.", "operationId": "enterprise-admin/list-self-hosted-runners-for-enterprise", "tags": [ "enterprise-admin" ], "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/actions#list-self-hosted-runners-for-an-enterprise" }, "parameters": [ { "$ref": "#/components/parameters/enterprise" }, { "$ref": "#/components/parameters/per-page" }, { "$ref": "#/components/parameters/page" } ], "responses": { "200": { "description": "Response", "content": { "application/json": { "schema": { "type": "object", "properties": { "total_count": { "type": "number" }, "runners": { "type": "array", "items": { "$ref": "#/components/schemas/runner" } } } }, "examples": { "default": { "$ref": "#/components/examples/runner-paginated" } } } }, "headers": { "Link": { "$ref": "#/components/headers/link" } } } }, "x-github": { "enabledForGitHubApps": false, "githubCloudOnly": false, "category": "actions", "subcategory": "self-hosted-runners" } } }, "/enterprises/{enterprise}/actions/runners/downloads": { "get": { "summary": "List runner applications for an enterprise", "description": "Lists binaries for the runner application that you can download and run.\n\nYou must authenticate using an access token with the `admin:enterprise` scope to use this endpoint.", "operationId": "enterprise-admin/list-runner-applications-for-enterprise", "tags": [ "enterprise-admin" ], "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/actions#list-runner-applications-for-an-enterprise" }, "parameters": [ { "$ref": "#/components/parameters/enterprise" } ], "responses": { "200": { "description": "Response", "content": { "application/json": { "schema": { "type": "array", "items": { "$ref": "#/components/schemas/runner-application" } }, "examples": { "default": { "$ref": "#/components/examples/runner-application-items" } } } } } }, "x-github": { "enabledForGitHubApps": false, "githubCloudOnly": false, "category": "actions", "subcategory": "self-hosted-runners" } } }, "/enterprises/{enterprise}/actions/runners/registration-token": { "post": { "summary": "Create a registration token for an enterprise", "description": "Returns a token that you can pass to the `config` script. The token expires after one hour.\n\nYou must authenticate using an access token with the `admin:enterprise` scope to use this endpoint.\n\n#### Example using registration token\n\nConfigure your self-hosted runner, replacing `TOKEN` with the registration token provided by this endpoint.\n\n```\n./config.sh --url https://github.com/enterprises/octo-enterprise --token TOKEN\n```", "operationId": "enterprise-admin/create-registration-token-for-enterprise", "tags": [ "enterprise-admin" ], "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/actions#create-a-registration-token-for-an-enterprise" }, "parameters": [ { "$ref": "#/components/parameters/enterprise" } ], "responses": { "201": { "description": "Response", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/authentication-token" }, "examples": { "default": { "$ref": "#/components/examples/authentication-token" } } } } } }, "x-github": { "enabledForGitHubApps": false, "githubCloudOnly": false, "category": "actions", "subcategory": "self-hosted-runners" } } }, "/enterprises/{enterprise}/actions/runners/remove-token": { "post": { "summary": "Create a remove token for an enterprise", "description": "Returns a token that you can pass to the `config` script to remove a self-hosted runner from an enterprise. The token expires after one hour.\n\nYou must authenticate using an access token with the `admin:enterprise` scope to use this endpoint.\n\n#### Example using remove token\n\nTo remove your self-hosted runner from an enterprise, replace `TOKEN` with the remove token provided by this\nendpoint.\n\n```\n./config.sh remove --token TOKEN\n```", "operationId": "enterprise-admin/create-remove-token-for-enterprise", "tags": [ "enterprise-admin" ], "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/actions#create-a-remove-token-for-an-enterprise" }, "parameters": [ { "$ref": "#/components/parameters/enterprise" } ], "responses": { "201": { "description": "Response", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/authentication-token" }, "examples": { "default": { "$ref": "#/components/examples/authentication-token-2" } } } } } }, "x-github": { "enabledForGitHubApps": false, "githubCloudOnly": false, "category": "actions", "subcategory": "self-hosted-runners" } } }, "/enterprises/{enterprise}/actions/runners/{runner_id}": { "get": { "summary": "Get a self-hosted runner for an enterprise", "description": "Gets a specific self-hosted runner configured in an enterprise.\n\nYou must authenticate using an access token with the `admin:enterprise` scope to use this endpoint.", "operationId": "enterprise-admin/get-self-hosted-runner-for-enterprise", "tags": [ "enterprise-admin" ], "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/actions#get-a-self-hosted-runner-for-an-enterprise" }, "parameters": [ { "$ref": "#/components/parameters/enterprise" }, { "$ref": "#/components/parameters/runner-id" } ], "responses": { "200": { "description": "Response", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/runner" }, "examples": { "default": { "$ref": "#/components/examples/runner" } } } } } }, "x-github": { "enabledForGitHubApps": false, "githubCloudOnly": false, "category": "actions", "subcategory": "self-hosted-runners" } }, "delete": { "summary": "Delete a self-hosted runner from an enterprise", "description": "Forces the removal of a self-hosted runner from an enterprise. You can use this endpoint to completely remove the runner when the machine you were using no longer exists.\n\nYou must authenticate using an access token with the `admin:enterprise` scope to use this endpoint.", "operationId": "enterprise-admin/delete-self-hosted-runner-from-enterprise", "tags": [ "enterprise-admin" ], "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/actions#delete-self-hosted-runner-from-an-enterprise" }, "parameters": [ { "$ref": "#/components/parameters/enterprise" }, { "$ref": "#/components/parameters/runner-id" } ], "responses": { "204": { "description": "Response" } }, "x-github": { "enabledForGitHubApps": false, "githubCloudOnly": false, "category": "actions", "subcategory": "self-hosted-runners" } } }, "/events": { "get": { "summary": "List public events", "description": "We delay the public events feed by five minutes, which means the most recent event returned by the public events API actually occurred at least five minutes ago.", "tags": [ "activity" ], "operationId": "activity/list-public-events", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/activity#list-public-events" }, "parameters": [ { "$ref": "#/components/parameters/per-page" }, { "$ref": "#/components/parameters/page" } ], "responses": { "200": { "description": "Response", "content": { "application/json": { "schema": { "type": "array", "items": { "$ref": "#/components/schemas/event" } } } } }, "304": { "$ref": "#/components/responses/not_modified" }, "403": { "$ref": "#/components/responses/forbidden" }, "503": { "$ref": "#/components/responses/service_unavailable" } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": true, "category": "activity", "subcategory": "events" } } }, "/feeds": { "get": { "summary": "Get feeds", "description": "GitHub Enterprise Server provides several timeline resources in [Atom](http://en.wikipedia.org/wiki/Atom_(standard)) format. The Feeds API lists all the feeds available to the authenticated user:\n\n* **Timeline**: The GitHub Enterprise Server global public timeline\n* **User**: The public timeline for any user, using [URI template](https://docs.github.com/enterprise-server@3.0/rest/overview/resources-in-the-rest-api#hypermedia)\n* **Current user public**: The public timeline for the authenticated user\n* **Current user**: The private timeline for the authenticated user\n* **Current user actor**: The private timeline for activity created by the authenticated user\n* **Current user organizations**: The private timeline for the organizations the authenticated user is a member of.\n* **Security advisories**: A collection of public announcements that provide information about security-related vulnerabilities in software on GitHub Enterprise Server.\n\n**Note**: Private feeds are only returned when [authenticating via Basic Auth](https://docs.github.com/enterprise-server@3.0/rest/overview/other-authentication-methods#basic-authentication) since current feed URIs use the older, non revocable auth tokens.", "tags": [ "activity" ], "operationId": "activity/get-feeds", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/activity#get-feeds" }, "parameters": [ ], "responses": { "200": { "description": "Response", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/feed" }, "examples": { "default": { "$ref": "#/components/examples/feed" } } } } } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": true, "category": "activity", "subcategory": "feeds" } } }, "/gists": { "get": { "summary": "List gists for the authenticated user", "description": "Lists the authenticated user's gists or if called anonymously, this endpoint returns all public gists:", "tags": [ "gists" ], "operationId": "gists/list", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/gists#list-gists-for-the-authenticated-user" }, "parameters": [ { "$ref": "#/components/parameters/since" }, { "$ref": "#/components/parameters/per-page" }, { "$ref": "#/components/parameters/page" } ], "responses": { "200": { "description": "Response", "content": { "application/json": { "schema": { "type": "array", "items": { "$ref": "#/components/schemas/base-gist" } }, "examples": { "default": { "$ref": "#/components/examples/base-gist-items" } } } }, "headers": { "Link": { "$ref": "#/components/headers/link" } } }, "304": { "$ref": "#/components/responses/not_modified" }, "403": { "$ref": "#/components/responses/forbidden" } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": false, "category": "gists", "subcategory": null } }, "post": { "summary": "Create a gist", "description": "Allows you to add a new gist with one or more files.\n\n**Note:** Don't name your files \"gistfile\" with a numerical suffix. This is the format of the automatic naming scheme that Gist uses internally.", "operationId": "gists/create", "tags": [ "gists" ], "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/gists#create-a-gist" }, "parameters": [ ], "requestBody": { "required": true, "content": { "application/json": { "schema": { "properties": { "description": { "description": "Description of the gist", "type": "string", "examples": [ "Example Ruby script" ] }, "files": { "description": "Names and content for the files that make up the gist", "type": "object", "additionalProperties": { "type": "object", "properties": { "content": { "description": "Content of the file", "readOnly": false, "type": "string" } }, "required": [ "content" ] }, "examples": [ { "hello.rb": { "content": "puts \"Hello, World!\"" } } ] }, "public": { "oneOf": [ { "description": "Flag indicating whether the gist is public", "type": "boolean", "default": false, "examples": [ true ] }, { "type": "string", "default": "false", "enum": [ "true", "false" ], "examples": [ "true" ] } ] } }, "required": [ "files" ], "type": "object" } } } }, "responses": { "201": { "description": "Response", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/gist-simple" }, "examples": { "default": { "$ref": "#/components/examples/gist" } } } }, "headers": { "Location": { "example": "https://api.github.com/gists/aa5a315d61ae9438b18d", "schema": { "type": "string" } } } }, "422": { "$ref": "#/components/responses/validation_failed" }, "304": { "$ref": "#/components/responses/not_modified" }, "404": { "$ref": "#/components/responses/not_found" }, "403": { "$ref": "#/components/responses/forbidden" } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": false, "category": "gists", "subcategory": null } } }, "/gists/public": { "get": { "summary": "List public gists", "description": "List public gists sorted by most recently updated to least recently updated.\n\nNote: With [pagination](https://docs.github.com/enterprise-server@3.0/rest/overview/resources-in-the-rest-api#pagination), you can fetch up to 3000 gists. For example, you can fetch 100 pages with 30 gists per page or 30 pages with 100 gists per page.", "tags": [ "gists" ], "operationId": "gists/list-public", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/gists#list-public-gists" }, "parameters": [ { "$ref": "#/components/parameters/since" }, { "$ref": "#/components/parameters/per-page" }, { "$ref": "#/components/parameters/page" } ], "responses": { "200": { "description": "Response", "content": { "application/json": { "schema": { "type": "array", "items": { "$ref": "#/components/schemas/base-gist" } }, "examples": { "default": { "$ref": "#/components/examples/base-gist-items" } } } }, "headers": { "Link": { "$ref": "#/components/headers/link" } } }, "422": { "$ref": "#/components/responses/validation_failed" }, "304": { "$ref": "#/components/responses/not_modified" }, "403": { "$ref": "#/components/responses/forbidden" } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": false, "category": "gists", "subcategory": null } } }, "/gists/starred": { "get": { "summary": "List starred gists", "description": "List the authenticated user's starred gists:", "tags": [ "gists" ], "operationId": "gists/list-starred", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/gists#list-starred-gists" }, "parameters": [ { "$ref": "#/components/parameters/since" }, { "$ref": "#/components/parameters/per-page" }, { "$ref": "#/components/parameters/page" } ], "responses": { "200": { "description": "Response", "content": { "application/json": { "schema": { "type": "array", "items": { "$ref": "#/components/schemas/base-gist" } }, "examples": { "default": { "$ref": "#/components/examples/base-gist-items" } } } }, "headers": { "Link": { "$ref": "#/components/headers/link" } } }, "401": { "$ref": "#/components/responses/requires_authentication" }, "304": { "$ref": "#/components/responses/not_modified" }, "403": { "$ref": "#/components/responses/forbidden" } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": false, "category": "gists", "subcategory": null } } }, "/gists/{gist_id}": { "get": { "summary": "Get a gist", "description": "", "tags": [ "gists" ], "operationId": "gists/get", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/gists#get-a-gist" }, "parameters": [ { "$ref": "#/components/parameters/gist-id" } ], "responses": { "200": { "description": "Response", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/gist-simple" }, "examples": { "default": { "$ref": "#/components/examples/gist" } } } } }, "403": { "$ref": "#/components/responses/forbidden_gist" }, "404": { "$ref": "#/components/responses/not_found" }, "304": { "$ref": "#/components/responses/not_modified" } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": false, "category": "gists", "subcategory": null } }, "patch": { "summary": "Update a gist", "description": "Allows you to update or delete a gist file and rename gist files. Files from the previous version of the gist that aren't explicitly changed during an edit are unchanged.", "tags": [ "gists" ], "operationId": "gists/update", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/gists/#update-a-gist" }, "parameters": [ { "$ref": "#/components/parameters/gist-id" } ], "requestBody": { "required": true, "content": { "application/json": { "schema": { "properties": { "description": { "description": "Description of the gist", "type": "string", "examples": [ "Example Ruby script" ] }, "files": { "description": "Names of files to be updated", "type": "object", "additionalProperties": { "type": [ "object", "null" ], "properties": { "content": { "description": "The new content of the file", "type": "string" }, "filename": { "description": "The new filename for the file", "type": [ "string", "null" ] } }, "anyOf": [ { "required": [ "content" ] }, { "required": [ "filename" ] }, { "type": "object", "maxProperties": 0 } ] }, "examples": [ { "hello.rb": { "content": "blah", "filename": "goodbye.rb" } } ] } }, "anyOf": [ { "required": [ "description" ] }, { "required": [ "files" ] } ], "type": [ "object", "null" ] } } } }, "responses": { "200": { "description": "Response", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/gist-simple" }, "examples": { "default": { "$ref": "#/components/examples/gist" } } } } }, "422": { "$ref": "#/components/responses/validation_failed" }, "404": { "$ref": "#/components/responses/not_found" } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": false, "category": "gists", "subcategory": null } }, "delete": { "summary": "Delete a gist", "description": "", "tags": [ "gists" ], "operationId": "gists/delete", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/gists#delete-a-gist" }, "parameters": [ { "$ref": "#/components/parameters/gist-id" } ], "responses": { "204": { "description": "Response" }, "404": { "$ref": "#/components/responses/not_found" }, "304": { "$ref": "#/components/responses/not_modified" }, "403": { "$ref": "#/components/responses/forbidden" } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": false, "category": "gists", "subcategory": null } } }, "/gists/{gist_id}/comments": { "get": { "summary": "List gist comments", "description": "", "tags": [ "gists" ], "operationId": "gists/list-comments", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/gists#list-gist-comments" }, "parameters": [ { "$ref": "#/components/parameters/gist-id" }, { "$ref": "#/components/parameters/per-page" }, { "$ref": "#/components/parameters/page" } ], "responses": { "200": { "description": "Response", "content": { "application/json": { "schema": { "type": "array", "items": { "$ref": "#/components/schemas/gist-comment" } }, "examples": { "default": { "$ref": "#/components/examples/gist-comment-items" } } } }, "headers": { "Link": { "$ref": "#/components/headers/link" } } }, "304": { "$ref": "#/components/responses/not_modified" }, "404": { "$ref": "#/components/responses/not_found" }, "403": { "$ref": "#/components/responses/forbidden" } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": false, "category": "gists", "subcategory": "comments" } }, "post": { "summary": "Create a gist comment", "description": "", "tags": [ "gists" ], "operationId": "gists/create-comment", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/gists#create-a-gist-comment" }, "parameters": [ { "$ref": "#/components/parameters/gist-id" } ], "requestBody": { "required": true, "content": { "application/json": { "schema": { "properties": { "body": { "description": "The comment text.", "type": "string", "maxLength": 65535, "examples": [ "Body of the attachment" ] } }, "type": "object", "required": [ "body" ] } } } }, "responses": { "201": { "description": "Response", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/gist-comment" }, "examples": { "default": { "$ref": "#/components/examples/gist-comment" } } } }, "headers": { "Location": { "example": "https://api.github.com/gists/a6db0bec360bb87e9418/comments/1", "schema": { "type": "string" } } } }, "304": { "$ref": "#/components/responses/not_modified" }, "404": { "$ref": "#/components/responses/not_found" }, "403": { "$ref": "#/components/responses/forbidden" } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": false, "category": "gists", "subcategory": "comments" } } }, "/gists/{gist_id}/comments/{comment_id}": { "get": { "summary": "Get a gist comment", "description": "", "tags": [ "gists" ], "operationId": "gists/get-comment", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/gists#get-a-gist-comment" }, "parameters": [ { "$ref": "#/components/parameters/gist-id" }, { "$ref": "#/components/parameters/comment-id" } ], "responses": { "200": { "description": "Response", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/gist-comment" }, "examples": { "default": { "$ref": "#/components/examples/gist-comment" } } } } }, "304": { "$ref": "#/components/responses/not_modified" }, "404": { "$ref": "#/components/responses/not_found" }, "403": { "$ref": "#/components/responses/forbidden_gist" } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": false, "category": "gists", "subcategory": "comments" } }, "patch": { "summary": "Update a gist comment", "description": "", "tags": [ "gists" ], "operationId": "gists/update-comment", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/gists#update-a-gist-comment" }, "parameters": [ { "$ref": "#/components/parameters/gist-id" }, { "$ref": "#/components/parameters/comment-id" } ], "requestBody": { "required": true, "content": { "application/json": { "schema": { "properties": { "body": { "description": "The comment text.", "type": "string", "maxLength": 65535, "examples": [ "Body of the attachment" ] } }, "type": "object", "required": [ "body" ] } } } }, "responses": { "200": { "description": "Response", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/gist-comment" }, "examples": { "default": { "$ref": "#/components/examples/gist-comment" } } } } }, "404": { "$ref": "#/components/responses/not_found" } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": false, "category": "gists", "subcategory": "comments" } }, "delete": { "summary": "Delete a gist comment", "description": "", "tags": [ "gists" ], "operationId": "gists/delete-comment", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/gists#delete-a-gist-comment" }, "parameters": [ { "$ref": "#/components/parameters/gist-id" }, { "$ref": "#/components/parameters/comment-id" } ], "responses": { "204": { "description": "Response" }, "304": { "$ref": "#/components/responses/not_modified" }, "404": { "$ref": "#/components/responses/not_found" }, "403": { "$ref": "#/components/responses/forbidden" } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": false, "category": "gists", "subcategory": "comments" } } }, "/gists/{gist_id}/commits": { "get": { "summary": "List gist commits", "description": "", "tags": [ "gists" ], "operationId": "gists/list-commits", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/gists#list-gist-commits" }, "parameters": [ { "$ref": "#/components/parameters/gist-id" }, { "$ref": "#/components/parameters/per-page" }, { "$ref": "#/components/parameters/page" } ], "responses": { "200": { "description": "Response", "content": { "application/json": { "schema": { "type": "array", "items": { "$ref": "#/components/schemas/gist-commit" } }, "examples": { "default": { "$ref": "#/components/examples/gist-commit-items" } } } }, "headers": { "Link": { "example": "; rel=\"next\"", "schema": { "type": "string" } } } }, "404": { "$ref": "#/components/responses/not_found" }, "304": { "$ref": "#/components/responses/not_modified" }, "403": { "$ref": "#/components/responses/forbidden" } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": false, "category": "gists", "subcategory": null } } }, "/gists/{gist_id}/forks": { "get": { "summary": "List gist forks", "description": "", "tags": [ "gists" ], "operationId": "gists/list-forks", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/gists#list-gist-forks" }, "parameters": [ { "$ref": "#/components/parameters/gist-id" }, { "$ref": "#/components/parameters/per-page" }, { "$ref": "#/components/parameters/page" } ], "responses": { "200": { "description": "Response", "content": { "application/json": { "schema": { "type": "array", "items": { "$ref": "#/components/schemas/gist-simple" } }, "examples": { "default": { "$ref": "#/components/examples/gist-fork-items" } } } }, "headers": { "Link": { "$ref": "#/components/headers/link" } } }, "404": { "$ref": "#/components/responses/not_found" }, "304": { "$ref": "#/components/responses/not_modified" }, "403": { "$ref": "#/components/responses/forbidden" } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": false, "category": "gists", "subcategory": null } }, "post": { "summary": "Fork a gist", "description": "**Note**: This was previously `/gists/:gist_id/fork`.", "tags": [ "gists" ], "operationId": "gists/fork", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/gists#fork-a-gist" }, "parameters": [ { "$ref": "#/components/parameters/gist-id" } ], "responses": { "201": { "description": "Response", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/base-gist" }, "examples": { "default": { "$ref": "#/components/examples/base-gist" } } } }, "headers": { "Location": { "example": "https://api.github.com/gists/aa5a315d61ae9438b18d", "schema": { "type": "string" } } } }, "404": { "$ref": "#/components/responses/not_found" }, "422": { "$ref": "#/components/responses/validation_failed" }, "304": { "$ref": "#/components/responses/not_modified" }, "403": { "$ref": "#/components/responses/forbidden" } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": false, "category": "gists", "subcategory": null } } }, "/gists/{gist_id}/star": { "get": { "summary": "Check if a gist is starred", "description": "", "tags": [ "gists" ], "operationId": "gists/check-is-starred", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/gists#check-if-a-gist-is-starred" }, "parameters": [ { "$ref": "#/components/parameters/gist-id" } ], "responses": { "204": { "description": "Response if gist is starred" }, "404": { "description": "Not Found if gist is not starred", "content": { "application/json": { "schema": { "type": "object", "properties": { }, "additionalProperties": false } } } }, "304": { "$ref": "#/components/responses/not_modified" }, "403": { "$ref": "#/components/responses/forbidden" } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": false, "category": "gists", "subcategory": null } }, "put": { "summary": "Star a gist", "description": "Note that you'll need to set `Content-Length` to zero when calling out to this endpoint. For more information, see \"[HTTP verbs](https://docs.github.com/enterprise-server@3.0/rest/overview/resources-in-the-rest-api#http-verbs).\"", "tags": [ "gists" ], "operationId": "gists/star", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/gists#star-a-gist" }, "parameters": [ { "$ref": "#/components/parameters/gist-id" } ], "responses": { "204": { "description": "Response" }, "404": { "$ref": "#/components/responses/not_found" }, "304": { "$ref": "#/components/responses/not_modified" }, "403": { "$ref": "#/components/responses/forbidden" } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": false, "category": "gists", "subcategory": null } }, "delete": { "summary": "Unstar a gist", "description": "", "tags": [ "gists" ], "operationId": "gists/unstar", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/gists#unstar-a-gist" }, "parameters": [ { "$ref": "#/components/parameters/gist-id" } ], "responses": { "204": { "description": "Response" }, "304": { "$ref": "#/components/responses/not_modified" }, "404": { "$ref": "#/components/responses/not_found" }, "403": { "$ref": "#/components/responses/forbidden" } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": false, "category": "gists", "subcategory": null } } }, "/gists/{gist_id}/{sha}": { "get": { "summary": "Get a gist revision", "description": "", "tags": [ "gists" ], "operationId": "gists/get-revision", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/gists#get-a-gist-revision" }, "parameters": [ { "$ref": "#/components/parameters/gist-id" }, { "name": "sha", "in": "path", "required": true, "schema": { "type": "string" } } ], "responses": { "200": { "description": "Response", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/gist-simple" }, "examples": { "default": { "$ref": "#/components/examples/gist" } } } } }, "422": { "$ref": "#/components/responses/validation_failed" }, "404": { "$ref": "#/components/responses/not_found" }, "403": { "$ref": "#/components/responses/forbidden" } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": false, "category": "gists", "subcategory": null } } }, "/gitignore/templates": { "get": { "summary": "Get all gitignore templates", "description": "List all templates available to pass as an option when [creating a repository](https://docs.github.com/enterprise-server@3.0/rest/reference/repos#create-a-repository-for-the-authenticated-user).", "operationId": "gitignore/get-all-templates", "tags": [ "gitignore" ], "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/gitignore#get-all-gitignore-templates" }, "parameters": [ ], "responses": { "200": { "description": "Response", "content": { "application/json": { "schema": { "type": "array", "items": { "type": "string" } }, "example": [ "Actionscript", "Android", "AppceleratorTitanium", "Autotools", "Bancha", "C", "C++" ] } } }, "304": { "$ref": "#/components/responses/not_modified" } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": true, "category": "gitignore", "subcategory": null } } }, "/gitignore/templates/{name}": { "get": { "summary": "Get a gitignore template", "description": "The API also allows fetching the source of a single template.\nUse the raw [media type](https://docs.github.com/enterprise-server@3.0/rest/overview/media-types/) to get the raw contents.", "operationId": "gitignore/get-template", "tags": [ "gitignore" ], "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/gitignore#get-a-gitignore-template" }, "parameters": [ { "name": "name", "in": "path", "required": true, "schema": { "type": "string" } } ], "responses": { "200": { "description": "Response", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/gitignore-template" }, "examples": { "default": { "$ref": "#/components/examples/gitignore-template" } } } } }, "304": { "$ref": "#/components/responses/not_modified" } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": true, "category": "gitignore", "subcategory": null } } }, "/installation/repositories": { "get": { "summary": "List repositories accessible to the app installation", "description": "List repositories that an app installation can access.\n\nYou must use an [installation access token](https://docs.github.com/enterprise-server@3.0/apps/building-github-apps/authenticating-with-github-apps/#authenticating-as-an-installation) to access this endpoint.", "tags": [ "apps" ], "operationId": "apps/list-repos-accessible-to-installation", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/apps#list-repositories-accessible-to-the-app-installation" }, "parameters": [ { "$ref": "#/components/parameters/per-page" }, { "$ref": "#/components/parameters/page" } ], "responses": { "200": { "description": "Response", "content": { "application/json": { "schema": { "type": "object", "required": [ "total_count", "repositories" ], "properties": { "total_count": { "type": "integer" }, "repositories": { "type": "array", "items": { "$ref": "#/components/schemas/repository" } }, "repository_selection": { "type": "string", "examples": [ "selected" ] } } }, "examples": { "default": { "$ref": "#/components/examples/repository-paginated-2" } } } }, "headers": { "Link": { "$ref": "#/components/headers/link" } } }, "403": { "$ref": "#/components/responses/forbidden" }, "304": { "$ref": "#/components/responses/not_modified" }, "401": { "$ref": "#/components/responses/requires_authentication" } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": true, "category": "apps", "subcategory": "installations", "previews": [ { "required": false, "name": "mercy", "note": "The `topics` property for repositories on GitHub is currently available for developers to preview. To view the `topics` property in calls that return repository results, you must provide a custom [media type](https://docs.github.com/enterprise-server@3.0/rest/overview/media-types) in the `Accept` header:\n```shell\napplication/vnd.github.mercy-preview+json\n```" } ] } } }, "/installation/token": { "delete": { "summary": "Revoke an installation access token", "description": "Revokes the installation token you're using to authenticate as an installation and access this endpoint.\n\nOnce an installation token is revoked, the token is invalidated and cannot be used. Other endpoints that require the revoked installation token must have a new installation token to work. You can create a new token using the \"[Create an installation access token for an app](https://docs.github.com/enterprise-server@3.0/rest/reference/apps#create-an-installation-access-token-for-an-app)\" endpoint.\n\nYou must use an [installation access token](https://docs.github.com/enterprise-server@3.0/apps/building-github-apps/authenticating-with-github-apps/#authenticating-as-an-installation) to access this endpoint.", "tags": [ "apps" ], "operationId": "apps/revoke-installation-access-token", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/apps#revoke-an-installation-access-token" }, "parameters": [ ], "responses": { "204": { "description": "Response" } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": true, "category": "apps", "subcategory": "installations" } } }, "/issues": { "get": { "summary": "List issues assigned to the authenticated user", "description": "List issues assigned to the authenticated user across all visible repositories including owned repositories, member\nrepositories, and organization repositories. You can use the `filter` query parameter to fetch issues that are not\nnecessarily assigned to you.\n\n\n**Note**: GitHub's REST API v3 considers every pull request an issue, but not every issue is a pull request. For this\nreason, \"Issues\" endpoints may return both issues and pull requests in the response. You can identify pull requests by\nthe `pull_request` key. Be aware that the `id` of a pull request returned from \"Issues\" endpoints will be an _issue id_. To find out the pull\nrequest id, use the \"[List pull requests](https://docs.github.com/enterprise-server@3.0/rest/reference/pulls#list-pull-requests)\" endpoint.", "tags": [ "issues" ], "operationId": "issues/list", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/issues#list-issues-assigned-to-the-authenticated-user" }, "parameters": [ { "name": "filter", "description": "Indicates which sorts of issues to return. Can be one of: \n\\* `assigned`: Issues assigned to you \n\\* `created`: Issues created by you \n\\* `mentioned`: Issues mentioning you \n\\* `subscribed`: Issues you're subscribed to updates for \n\\* `all` or `repos`: All issues the authenticated user can see, regardless of participation or creation", "in": "query", "required": false, "schema": { "type": "string", "enum": [ "assigned", "created", "mentioned", "subscribed", "repos", "all" ], "default": "assigned" } }, { "name": "state", "description": "Indicates the state of the issues to return. Can be either `open`, `closed`, or `all`.", "in": "query", "required": false, "schema": { "type": "string", "enum": [ "open", "closed", "all" ], "default": "open" } }, { "$ref": "#/components/parameters/labels" }, { "name": "sort", "description": "What to sort results by. Can be either `created`, `updated`, `comments`.", "in": "query", "required": false, "schema": { "type": "string", "enum": [ "created", "updated", "comments" ], "default": "created" } }, { "$ref": "#/components/parameters/direction" }, { "$ref": "#/components/parameters/since" }, { "name": "collab", "in": "query", "required": false, "schema": { "type": "boolean" } }, { "name": "orgs", "in": "query", "required": false, "schema": { "type": "boolean" } }, { "name": "owned", "in": "query", "required": false, "schema": { "type": "boolean" } }, { "name": "pulls", "in": "query", "required": false, "schema": { "type": "boolean" } }, { "$ref": "#/components/parameters/per-page" }, { "$ref": "#/components/parameters/page" } ], "responses": { "200": { "description": "Response", "content": { "application/json": { "schema": { "type": "array", "items": { "$ref": "#/components/schemas/issue" } }, "examples": { "default": { "$ref": "#/components/examples/issue-with-repo-items" } } } }, "headers": { "Link": { "$ref": "#/components/headers/link" } } }, "422": { "$ref": "#/components/responses/validation_failed" }, "304": { "$ref": "#/components/responses/not_modified" }, "404": { "$ref": "#/components/responses/not_found" } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": false, "category": "issues", "previews": [ { "required": false, "name": "machine-man", "note": "If an issue event is created via a GitHub App, the response will include the `performed_via_github_app` object with\tinformation about the GitHub App. For more information, see the [related blog\tpost](https://developer.github.com/changes/2016-09-14-Integrations-Early-Access).\nTo receive the `performed_via_github_app` object in the response, you must provide a custom [media type](https://docs.github.com/enterprise-server@3.0/rest/overview/media-types) in the `Accept` header:\n```shell\napplication/vnd.github.machine-man-preview\n```" }, { "required": false, "name": "squirrel-girl", "note": "An additional `reactions` object in the issue comment payload is currently available for developers to preview. During the preview period, the APIs may change without advance notice. Please see the [blog post](https://developer.github.com/changes/2016-05-12-reactions-api-preview) for full details.\n\nTo access the API you must provide a custom [media type](https://docs.github.com/enterprise-server@3.0/rest/overview/media-types) in the `Accept` header:\n```shell\napplication/vnd.github.squirrel-girl-preview\n```\nThe `reactions` key will have the following payload where `url` can be used to construct the API location for [listing and creating](https://docs.github.com/enterprise-server@3.0/rest/reference/reactions) reactions." } ] } } }, "/licenses": { "get": { "summary": "Get all commonly used licenses", "description": "", "tags": [ "licenses" ], "operationId": "licenses/get-all-commonly-used", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/licenses#get-all-commonly-used-licenses" }, "parameters": [ { "name": "featured", "in": "query", "required": false, "schema": { "type": "boolean" } }, { "$ref": "#/components/parameters/per-page" }, { "$ref": "#/components/parameters/page" } ], "responses": { "200": { "description": "Response", "content": { "application/json": { "schema": { "type": "array", "items": { "$ref": "#/components/schemas/license-simple" } }, "examples": { "default": { "$ref": "#/components/examples/license-simple-items" } } } } }, "304": { "$ref": "#/components/responses/not_modified" } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": true, "category": "licenses", "subcategory": null } } }, "/licenses/{license}": { "get": { "summary": "Get a license", "description": "", "tags": [ "licenses" ], "operationId": "licenses/get", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/licenses#get-a-license" }, "parameters": [ { "name": "license", "in": "path", "required": true, "schema": { "type": "string" } } ], "responses": { "200": { "description": "Response", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/license" }, "examples": { "default": { "$ref": "#/components/examples/license" } } } } }, "403": { "$ref": "#/components/responses/forbidden" }, "404": { "$ref": "#/components/responses/not_found" }, "304": { "$ref": "#/components/responses/not_modified" } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": true, "category": "licenses", "subcategory": null } } }, "/markdown": { "post": { "summary": "Render a Markdown document", "description": "", "operationId": "markdown/render", "tags": [ "markdown" ], "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/markdown#render-a-markdown-document" }, "parameters": [ ], "requestBody": { "required": true, "content": { "application/json": { "schema": { "properties": { "text": { "description": "The Markdown text to render in HTML.", "type": "string" }, "mode": { "description": "The rendering mode. Can be either `markdown` or `gfm`.", "enum": [ "markdown", "gfm" ], "default": "markdown", "type": "string", "examples": [ "markdown" ] }, "context": { "description": "The repository context to use when creating references in `gfm` mode. For example, setting `context` to `octo-org/octo-repo` will change the text `#42` into an HTML link to issue 42 in the `octo-org/octo-repo` repository.", "type": "string" } }, "required": [ "text" ], "type": "object" } } } }, "responses": { "200": { "description": "Response", "headers": { "Content-Type": { "$ref": "#/components/headers/content-type" }, "Content-Length": { "example": "279", "schema": { "type": "string" } }, "X-CommonMarker-Version": { "$ref": "#/components/headers/x-common-marker-version" } }, "content": { "text/html": { "schema": { "type": "string" } } } }, "304": { "$ref": "#/components/responses/not_modified" } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": true, "category": "markdown", "subcategory": null } } }, "/markdown/raw": { "post": { "summary": "Render a Markdown document in raw mode", "description": "You must send Markdown as plain text (using a `Content-Type` header of `text/plain` or `text/x-markdown`) to this endpoint, rather than using JSON format. In raw mode, [GitHub Flavored Markdown](https://github.github.com/gfm/) is not supported and Markdown will be rendered in plain format like a README.md file. Markdown content must be 400 KB or less.", "operationId": "markdown/render-raw", "tags": [ "markdown" ], "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/markdown#render-a-markdown-document-in-raw-mode" }, "parameters": [ ], "requestBody": { "required": false, "content": { "text/plain": { "schema": { "type": "string" } }, "text/x-markdown": { "schema": { "type": "string" } } } }, "responses": { "200": { "description": "Response", "headers": { "X-CommonMarker-Version": { "$ref": "#/components/headers/x-common-marker-version" } }, "content": { "text/html": { "schema": { "type": "string" } } } }, "304": { "$ref": "#/components/responses/not_modified" } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": true, "category": "markdown", "subcategory": null } } }, "/meta": { "get": { "summary": "Get GitHub Enterprise Server meta information", "description": "", "tags": [ "meta" ], "operationId": "meta/get", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/meta#get-github-meta-information" }, "parameters": [ ], "responses": { "200": { "description": "Response", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/api-overview" }, "examples": { "default": { "$ref": "#/components/examples/api-overview" } } } } }, "304": { "$ref": "#/components/responses/not_modified" } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": true, "category": "meta", "subcategory": null } } }, "/networks/{owner}/{repo}/events": { "get": { "summary": "List public events for a network of repositories", "description": "", "tags": [ "activity" ], "operationId": "activity/list-public-events-for-repo-network", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/activity#list-public-events-for-a-network-of-repositories" }, "parameters": [ { "$ref": "#/components/parameters/owner" }, { "$ref": "#/components/parameters/repo" }, { "$ref": "#/components/parameters/per-page" }, { "$ref": "#/components/parameters/page" } ], "responses": { "200": { "description": "Response", "content": { "application/json": { "schema": { "type": "array", "items": { "$ref": "#/components/schemas/event" } } } } }, "404": { "$ref": "#/components/responses/not_found" }, "403": { "$ref": "#/components/responses/forbidden" }, "304": { "$ref": "#/components/responses/not_modified" }, "301": { "$ref": "#/components/responses/moved_permanently" } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": true, "category": "activity", "subcategory": "events" } } }, "/notifications": { "get": { "summary": "List notifications for the authenticated user", "description": "List all notifications for the current user, sorted by most recently updated.", "tags": [ "activity" ], "operationId": "activity/list-notifications-for-authenticated-user", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/activity#list-notifications-for-the-authenticated-user" }, "parameters": [ { "$ref": "#/components/parameters/all" }, { "$ref": "#/components/parameters/participating" }, { "$ref": "#/components/parameters/since" }, { "$ref": "#/components/parameters/before" }, { "$ref": "#/components/parameters/per-page" }, { "$ref": "#/components/parameters/page" } ], "responses": { "200": { "description": "Response", "content": { "application/json": { "schema": { "type": "array", "items": { "$ref": "#/components/schemas/thread" } }, "examples": { "default": { "$ref": "#/components/examples/thread-items" } } } }, "headers": { "Link": { "$ref": "#/components/headers/link" } } }, "304": { "$ref": "#/components/responses/not_modified" }, "403": { "$ref": "#/components/responses/forbidden" }, "401": { "$ref": "#/components/responses/requires_authentication" }, "422": { "$ref": "#/components/responses/validation_failed" } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": false, "category": "activity", "subcategory": "notifications" } }, "put": { "summary": "Mark notifications as read", "description": "Marks all notifications as \"read\" removes it from the [default view on GitHub Enterprise Server](https://github.com/notifications). If the number of notifications is too large to complete in one request, you will receive a `202 Accepted` status and GitHub Enterprise Server will run an asynchronous process to mark notifications as \"read.\" To check whether any \"unread\" notifications remain, you can use the [List notifications for the authenticated user](https://docs.github.com/enterprise-server@3.0/rest/reference/activity#list-notifications-for-the-authenticated-user) endpoint and pass the query parameter `all=false`.", "tags": [ "activity" ], "operationId": "activity/mark-notifications-as-read", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/activity#mark-notifications-as-read" }, "parameters": [ ], "requestBody": { "required": false, "content": { "application/json": { "schema": { "type": "object", "properties": { "last_read_at": { "description": "Describes the last point that notifications were checked.", "type": "string", "format": "date-time" }, "read": { "description": "Whether the notification has been read.", "type": "boolean" } } } } } }, "responses": { "202": { "description": "Response", "content": { "application/json": { "schema": { "type": "object", "properties": { "message": { "type": "string" } } } } } }, "205": { "description": "Reset Content" }, "304": { "$ref": "#/components/responses/not_modified" }, "403": { "$ref": "#/components/responses/forbidden" }, "401": { "$ref": "#/components/responses/requires_authentication" } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": false, "category": "activity", "subcategory": "notifications" } } }, "/notifications/threads/{thread_id}": { "get": { "summary": "Get a thread", "description": "", "tags": [ "activity" ], "operationId": "activity/get-thread", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/activity#get-a-thread" }, "parameters": [ { "$ref": "#/components/parameters/thread-id" } ], "responses": { "200": { "description": "Response", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/thread" }, "examples": { "default": { "$ref": "#/components/examples/thread" } } } } }, "304": { "$ref": "#/components/responses/not_modified" }, "403": { "$ref": "#/components/responses/forbidden" }, "401": { "$ref": "#/components/responses/requires_authentication" } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": false, "category": "activity", "subcategory": "notifications" } }, "patch": { "summary": "Mark a thread as read", "description": "", "tags": [ "activity" ], "operationId": "activity/mark-thread-as-read", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/activity#mark-a-thread-as-read" }, "parameters": [ { "$ref": "#/components/parameters/thread-id" } ], "responses": { "205": { "description": "Reset Content" }, "304": { "$ref": "#/components/responses/not_modified" }, "403": { "$ref": "#/components/responses/forbidden" } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": false, "category": "activity", "subcategory": "notifications" } } }, "/notifications/threads/{thread_id}/subscription": { "get": { "summary": "Get a thread subscription for the authenticated user", "description": "This checks to see if the current user is subscribed to a thread. You can also [get a repository subscription](https://docs.github.com/enterprise-server@3.0/rest/reference/activity#get-a-repository-subscription).\n\nNote that subscriptions are only generated if a user is participating in a conversation--for example, they've replied to the thread, were **@mentioned**, or manually subscribe to a thread.", "tags": [ "activity" ], "operationId": "activity/get-thread-subscription-for-authenticated-user", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/activity#get-a-thread-subscription-for-the-authenticated-user" }, "parameters": [ { "$ref": "#/components/parameters/thread-id" } ], "responses": { "200": { "description": "Response", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/thread-subscription" }, "examples": { "default": { "$ref": "#/components/examples/thread-subscription" } } } } }, "304": { "$ref": "#/components/responses/not_modified" }, "403": { "$ref": "#/components/responses/forbidden" }, "401": { "$ref": "#/components/responses/requires_authentication" } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": false, "category": "activity", "subcategory": "notifications" } }, "put": { "summary": "Set a thread subscription", "description": "If you are watching a repository, you receive notifications for all threads by default. Use this endpoint to ignore future notifications for threads until you comment on the thread or get an **@mention**.\n\nYou can also use this endpoint to subscribe to threads that you are currently not receiving notifications for or to subscribed to threads that you have previously ignored.\n\nUnsubscribing from a conversation in a repository that you are not watching is functionally equivalent to the [Delete a thread subscription](https://docs.github.com/enterprise-server@3.0/rest/reference/activity#delete-a-thread-subscription) endpoint.", "tags": [ "activity" ], "operationId": "activity/set-thread-subscription", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/activity#set-a-thread-subscription" }, "parameters": [ { "$ref": "#/components/parameters/thread-id" } ], "requestBody": { "required": false, "content": { "application/json": { "schema": { "properties": { "ignored": { "description": "Whether to block all notifications from a thread.", "default": false, "type": "boolean" } }, "type": "object" } } } }, "responses": { "200": { "description": "Response", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/thread-subscription" }, "examples": { "default": { "$ref": "#/components/examples/thread-subscription" } } } } }, "304": { "$ref": "#/components/responses/not_modified" }, "403": { "$ref": "#/components/responses/forbidden" }, "401": { "$ref": "#/components/responses/requires_authentication" } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": false, "category": "activity", "subcategory": "notifications" } }, "delete": { "summary": "Delete a thread subscription", "description": "Mutes all future notifications for a conversation until you comment on the thread or get an **@mention**. If you are watching the repository of the thread, you will still receive notifications. To ignore future notifications for a repository you are watching, use the [Set a thread subscription](https://docs.github.com/enterprise-server@3.0/rest/reference/activity#set-a-thread-subscription) endpoint and set `ignore` to `true`.", "tags": [ "activity" ], "operationId": "activity/delete-thread-subscription", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/activity#delete-a-thread-subscription" }, "parameters": [ { "$ref": "#/components/parameters/thread-id" } ], "responses": { "204": { "description": "Response" }, "304": { "$ref": "#/components/responses/not_modified" }, "403": { "$ref": "#/components/responses/forbidden" }, "401": { "$ref": "#/components/responses/requires_authentication" } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": false, "category": "activity", "subcategory": "notifications" } } }, "/octocat": { "get": { "summary": "Get Octocat", "description": "Get the octocat as ASCII art", "tags": [ "meta" ], "operationId": "meta/get-octocat", "parameters": [ { "name": "s", "in": "query", "description": "The words to show in Octocat's speech bubble", "schema": { "type": "string" }, "required": false } ], "responses": { "200": { "description": "Response", "content": { "application/octocat-stream": { "schema": { "type": "string" } } } } }, "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/meta#get-octocat" }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": true, "category": "meta" } } }, "/organizations": { "get": { "summary": "List organizations", "description": "Lists all organizations, in the order that they were created on GitHub Enterprise Server.\n\n**Note:** Pagination is powered exclusively by the `since` parameter. Use the [Link header](https://docs.github.com/enterprise-server@3.0/rest/overview/resources-in-the-rest-api#link-header) to get the URL for the next page of organizations.", "tags": [ "orgs" ], "operationId": "orgs/list", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/orgs#list-organizations" }, "parameters": [ { "$ref": "#/components/parameters/since-org" }, { "$ref": "#/components/parameters/per-page" } ], "responses": { "200": { "description": "Response", "content": { "application/json": { "schema": { "type": "array", "items": { "$ref": "#/components/schemas/organization-simple" } }, "examples": { "default": { "$ref": "#/components/examples/organization-simple-items" } } } }, "headers": { "Link": { "example": "; rel=\"next\"", "schema": { "type": "string" } } } }, "304": { "$ref": "#/components/responses/not_modified" } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": true, "category": "orgs", "subcategory": null } } }, "/orgs/{org}": { "get": { "summary": "Get an organization", "description": "To see many of the organization response values, you need to be an authenticated organization owner with the `admin:org` scope. When the value of `two_factor_requirement_enabled` is `true`, the organization requires all members, billing managers, and outside collaborators to enable [two-factor authentication](https://docs.github.com/articles/securing-your-account-with-two-factor-authentication-2fa/).\n\nGitHub Apps with the `Organization plan` permission can use this endpoint to retrieve information about an organization's GitHub Enterprise Server plan. See \"[Authenticating with GitHub Apps](https://docs.github.com/enterprise-server@3.0/apps/building-github-apps/authenticating-with-github-apps/)\" for details. For an example response, see 'Response with GitHub Enterprise Server plan information' below.\"", "tags": [ "orgs" ], "operationId": "orgs/get", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/orgs#get-an-organization" }, "parameters": [ { "$ref": "#/components/parameters/org" } ], "responses": { "200": { "description": "Response", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/organization-full" }, "examples": { "default-response": { "$ref": "#/components/examples/organization-full-default-response" } } } } }, "404": { "$ref": "#/components/responses/not_found" } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": true, "category": "orgs", "previews": [ { "required": false, "name": "surtur", "note": "New repository creation permissions are available to preview. You can now use `members_can_create_public_repositories`, `members_can_create_private_repositories`, and `members_can_create_internal_repositories`. You can only allow members to create internal repositories if your organization is associated with an enterprise account using GitHub Enterprise Cloud or GitHub Enterprise Server 2.20+. These parameters provide more granular permissions to configure the type of repositories organization members can create.\n\nTo access these new parameters during the preview period, you must provide a custom [media type](https://docs.github.com/enterprise-server@3.0/rest/overview/media-types) in the `Accept` header:\n```shell\napplication/vnd.github.surtur-preview+json\n```" } ] } }, "patch": { "summary": "Update an organization", "description": "**Parameter Deprecation Notice:** GitHub Enterprise Server will replace and discontinue `members_allowed_repository_creation_type` in favor of more granular permissions. The new input parameters are `members_can_create_public_repositories`, `members_can_create_private_repositories` for all organizations and `members_can_create_internal_repositories` for organizations associated with an enterprise account using GitHub Enterprise Cloud or GitHub Enterprise Server 2.20+. For more information, see the [blog post](https://developer.github.com/changes/2019-12-03-internal-visibility-changes).\n\nEnables an authenticated organization owner with the `admin:org` scope to update the organization's profile and member privileges.", "tags": [ "orgs" ], "operationId": "orgs/update", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/orgs/#update-an-organization" }, "parameters": [ { "$ref": "#/components/parameters/org" } ], "requestBody": { "required": false, "content": { "application/json": { "schema": { "type": "object", "properties": { "billing_email": { "type": "string", "description": "Billing email address. This address is not publicized." }, "company": { "type": "string", "description": "The company name." }, "email": { "type": "string", "description": "The publicly visible email address." }, "twitter_username": { "type": "string", "description": "The Twitter username of the company." }, "location": { "type": "string", "description": "The location." }, "name": { "type": "string", "description": "The shorthand name of the company." }, "description": { "type": "string", "description": "The description of the company." }, "has_organization_projects": { "type": "boolean", "description": "Toggles whether an organization can use organization projects." }, "has_repository_projects": { "type": "boolean", "description": "Toggles whether repositories that belong to the organization can use repository projects." }, "default_repository_permission": { "type": "string", "description": "Default permission level members have for organization repositories: \n\\* `read` - can pull, but not push to or administer this repository. \n\\* `write` - can pull and push, but not administer this repository. \n\\* `admin` - can pull, push, and administer this repository. \n\\* `none` - no permissions granted by default.", "enum": [ "read", "write", "admin", "none" ], "default": "read" }, "members_can_create_repositories": { "type": "boolean", "description": "Toggles the ability of non-admin organization members to create repositories. Can be one of: \n\\* `true` - all organization members can create repositories. \n\\* `false` - only organization owners can create repositories. \nDefault: `true` \n**Note:** A parameter can override this parameter. See `members_allowed_repository_creation_type` in this table for details. **Note:** A parameter can override this parameter. See `members_allowed_repository_creation_type` in this table for details.", "default": true }, "members_can_create_internal_repositories": { "type": "boolean", "description": "Toggles whether organization members can create internal repositories, which are visible to all enterprise members. You can only allow members to create internal repositories if your organization is associated with an enterprise account using GitHub Enterprise Cloud or GitHub Enterprise Server 2.20+. Can be one of: \n\\* `true` - all organization members can create internal repositories. \n\\* `false` - only organization owners can create internal repositories. \nDefault: `true`. For more information, see \"[Restricting repository creation in your organization](https://docs.github.com/github/setting-up-and-managing-organizations-and-teams/restricting-repository-creation-in-your-organization)\" in the GitHub Help documentation." }, "members_can_create_private_repositories": { "type": "boolean", "description": "Toggles whether organization members can create private repositories, which are visible to organization members with permission. Can be one of: \n\\* `true` - all organization members can create private repositories. \n\\* `false` - only organization owners can create private repositories. \nDefault: `true`. For more information, see \"[Restricting repository creation in your organization](https://docs.github.com/github/setting-up-and-managing-organizations-and-teams/restricting-repository-creation-in-your-organization)\" in the GitHub Help documentation." }, "members_can_create_public_repositories": { "type": "boolean", "description": "Toggles whether organization members can create public repositories, which are visible to anyone. Can be one of: \n\\* `true` - all organization members can create public repositories. \n\\* `false` - only organization owners can create public repositories. \nDefault: `true`. For more information, see \"[Restricting repository creation in your organization](https://docs.github.com/github/setting-up-and-managing-organizations-and-teams/restricting-repository-creation-in-your-organization)\" in the GitHub Help documentation." }, "members_allowed_repository_creation_type": { "type": "string", "description": "Specifies which types of repositories non-admin organization members can create. Can be one of: \n\\* `all` - all organization members can create public and private repositories. \n\\* `private` - members can create private repositories. This option is only available to repositories that are part of an organization on GitHub Enterprise Cloud. \n\\* `none` - only admin members can create repositories. \n**Note:** This parameter is deprecated and will be removed in the future. Its return value ignores internal repositories. Using this parameter overrides values set in `members_can_create_repositories`. See the parameter deprecation notice in the operation description for details.", "enum": [ "all", "private", "none" ] }, "members_can_create_pages": { "type": "boolean", "description": "Toggles whether organization members can create GitHub Pages sites. Can be one of: \n\\* `true` - all organization members can create GitHub Pages sites. \n\\* `false` - no organization members can create GitHub Pages sites. Existing published sites will not be impacted.", "default": true }, "members_can_fork_private_repositories": { "type": "boolean", "description": "Toggles whether organization members can fork private organization repositories. Can be one of: \n\\* `true` - all organization members can fork private repositories within the organization. \n\\* `false` - no organization members can fork private repositories within the organization.", "default": false }, "blog": { "type": "string", "examples": [ "\"http://github.blog\"" ] } } }, "example": { "billing_email": "mona@github.com", "company": "GitHub", "email": "mona@github.com", "twitter_username": "github", "location": "San Francisco", "name": "github", "description": "GitHub, the company.", "default_repository_permission": "read", "members_can_create_repositories": true, "members_allowed_repository_creation_type": "all" } } } }, "responses": { "200": { "description": "Response", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/organization-full" }, "examples": { "default": { "$ref": "#/components/examples/organization-full" } } } } }, "422": { "description": "Validation failed", "content": { "application/json": { "schema": { "oneOf": [ { "$ref": "#/components/schemas/validation-error" }, { "$ref": "#/components/schemas/validation-error-simple" } ] } } } }, "409": { "$ref": "#/components/responses/conflict" } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": true, "category": "orgs", "previews": [ { "required": false, "name": "surtur", "note": "New repository creation permissions are available to preview. You can now use `members_can_create_public_repositories`, `members_can_create_private_repositories`, and `members_can_create_internal_repositories`. You can only allow members to create internal repositories if your organization is associated with an enterprise account using GitHub Enterprise Cloud or GitHub Enterprise Server 2.20+. These parameters provide more granular permissions to configure the type of repositories organization members can create.\n\nTo access these new parameters during the preview period, you must provide a custom [media type](https://docs.github.com/enterprise-server@3.0/rest/overview/media-types) in the `Accept` header:\n```shell\napplication/vnd.github.surtur-preview+json\n```" } ] } } }, "/orgs/{org}/actions/permissions": { "get": { "summary": "Get GitHub Actions permissions for an organization", "description": "Gets the GitHub Actions permissions policy for repositories and allowed actions in an organization.\n\nYou must authenticate using an access token with the `admin:org` scope to use this endpoint. GitHub Apps must have the `administration` organization permission to use this API.", "operationId": "actions/get-github-actions-permissions-organization", "tags": [ "actions" ], "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/actions#get-github-actions-permissions-for-an-organization" }, "parameters": [ { "$ref": "#/components/parameters/org" } ], "responses": { "200": { "description": "Response", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/actions-organization-permissions" }, "examples": { "default": { "$ref": "#/components/examples/actions-organization-permissions" } } } } } }, "x-github": { "enabledForGitHubApps": true, "githubCloudOnly": false, "category": "actions", "subcategory": "permissions" } }, "put": { "summary": "Set GitHub Actions permissions for an organization", "description": "Sets the GitHub Actions permissions policy for repositories and allowed actions in an organization.\n\nIf the organization belongs to an enterprise that has set restrictive permissions at the enterprise level, such as `allowed_actions` to `selected` actions, then you cannot override them for the organization.\n\nYou must authenticate using an access token with the `admin:org` scope to use this endpoint. GitHub Apps must have the `administration` organization permission to use this API.", "operationId": "actions/set-github-actions-permissions-organization", "tags": [ "actions" ], "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/actions#set-github-actions-permissions-for-an-organization" }, "parameters": [ { "$ref": "#/components/parameters/org" } ], "responses": { "204": { "description": "Response" } }, "requestBody": { "required": true, "content": { "application/json": { "schema": { "type": "object", "properties": { "enabled_repositories": { "$ref": "#/components/schemas/enabled-repositories" }, "allowed_actions": { "$ref": "#/components/schemas/allowed-actions" } }, "required": [ "enabled_repositories" ] }, "example": { "enabled_repositories": "all", "allowed_actions": "selected" } } } }, "x-github": { "enabledForGitHubApps": true, "githubCloudOnly": false, "category": "actions", "subcategory": "permissions" } } }, "/orgs/{org}/actions/permissions/repositories": { "get": { "summary": "List selected repositories enabled for GitHub Actions in an organization", "description": "Lists the selected repositories that are enabled for GitHub Actions in an organization. To use this endpoint, the organization permission policy for `enabled_repositories` must be configured to `selected`. For more information, see \"[Set GitHub Actions permissions for an organization](#set-github-actions-permissions-for-an-organization).\"\n\nYou must authenticate using an access token with the `admin:org` scope to use this endpoint. GitHub Apps must have the `administration` organization permission to use this API.", "operationId": "actions/list-selected-repositories-enabled-github-actions-organization", "tags": [ "actions" ], "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/actions#list-selected-repositories-enabled-for-github-actions-in-an-organization" }, "parameters": [ { "$ref": "#/components/parameters/org" }, { "$ref": "#/components/parameters/per-page" }, { "$ref": "#/components/parameters/page" } ], "responses": { "200": { "description": "Response", "content": { "application/json": { "schema": { "type": "object", "required": [ "total_count", "repositories" ], "properties": { "total_count": { "type": "number" }, "repositories": { "type": "array", "items": { "$ref": "#/components/schemas/repository" } } } }, "examples": { "default": { "$ref": "#/components/examples/repository-paginated" } } } } } }, "x-github": { "enabledForGitHubApps": true, "githubCloudOnly": false, "category": "actions", "subcategory": "permissions" } }, "put": { "summary": "Set selected repositories enabled for GitHub Actions in an organization", "description": "Replaces the list of selected repositories that are enabled for GitHub Actions in an organization. To use this endpoint, the organization permission policy for `enabled_repositories` must be configured to `selected`. For more information, see \"[Set GitHub Actions permissions for an organization](#set-github-actions-permissions-for-an-organization).\"\n\nYou must authenticate using an access token with the `admin:org` scope to use this endpoint. GitHub Apps must have the `administration` organization permission to use this API.", "operationId": "actions/set-selected-repositories-enabled-github-actions-organization", "tags": [ "actions" ], "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/actions#set-selected-repositories-enabled-for-github-actions-in-an-organization" }, "parameters": [ { "$ref": "#/components/parameters/org" } ], "responses": { "204": { "description": "Response" } }, "requestBody": { "required": true, "content": { "application/json": { "schema": { "type": "object", "properties": { "selected_repository_ids": { "description": "List of repository IDs to enable for GitHub Actions.", "type": "array", "items": { "type": "integer", "description": "Unique identifier of the repository." } } }, "required": [ "selected_repository_ids" ] }, "example": { "selected_repository_ids": [ 32, 42 ] } } } }, "x-github": { "enabledForGitHubApps": true, "githubCloudOnly": false, "category": "actions", "subcategory": "permissions" } } }, "/orgs/{org}/actions/permissions/repositories/{repository_id}": { "put": { "summary": "Enable a selected repository for GitHub Actions in an organization", "description": "Adds a repository to the list of selected repositories that are enabled for GitHub Actions in an organization. To use this endpoint, the organization permission policy for `enabled_repositories` must be must be configured to `selected`. For more information, see \"[Set GitHub Actions permissions for an organization](#set-github-actions-permissions-for-an-organization).\"\n\nYou must authenticate using an access token with the `admin:org` scope to use this endpoint. GitHub Apps must have the `administration` organization permission to use this API.", "operationId": "actions/enable-selected-repository-github-actions-organization", "tags": [ "actions" ], "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/actions#enable-a-selected-repository-for-github-actions-in-an-organization" }, "parameters": [ { "$ref": "#/components/parameters/org" }, { "$ref": "#/components/parameters/repository-id" } ], "responses": { "204": { "description": "Response" } }, "x-github": { "enabledForGitHubApps": true, "githubCloudOnly": false, "category": "actions", "subcategory": "permissions" } }, "delete": { "summary": "Disable a selected repository for GitHub Actions in an organization", "description": "Removes a repository from the list of selected repositories that are enabled for GitHub Actions in an organization. To use this endpoint, the organization permission policy for `enabled_repositories` must be configured to `selected`. For more information, see \"[Set GitHub Actions permissions for an organization](#set-github-actions-permissions-for-an-organization).\"\n\nYou must authenticate using an access token with the `admin:org` scope to use this endpoint. GitHub Apps must have the `administration` organization permission to use this API.", "operationId": "actions/disable-selected-repository-github-actions-organization", "tags": [ "actions" ], "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/actions#disable-a-selected-repository-for-github-actions-in-an-organization" }, "parameters": [ { "$ref": "#/components/parameters/org" }, { "$ref": "#/components/parameters/repository-id" } ], "responses": { "204": { "description": "Response" } }, "x-github": { "enabledForGitHubApps": true, "githubCloudOnly": false, "category": "actions", "subcategory": "permissions" } } }, "/orgs/{org}/actions/permissions/selected-actions": { "get": { "summary": "Get allowed actions for an organization", "description": "Gets the selected actions that are allowed in an organization. To use this endpoint, the organization permission policy for `allowed_actions` must be configured to `selected`. For more information, see \"[Set GitHub Actions permissions for an organization](#set-github-actions-permissions-for-an-organization).\"\"\n\nYou must authenticate using an access token with the `admin:org` scope to use this endpoint. GitHub Apps must have the `administration` organization permission to use this API.", "operationId": "actions/get-allowed-actions-organization", "tags": [ "actions" ], "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/actions#get-allowed-actions-for-an-organization" }, "parameters": [ { "$ref": "#/components/parameters/org" } ], "responses": { "200": { "description": "Response", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/selected-actions" }, "examples": { "default": { "$ref": "#/components/examples/selected-actions" } } } } } }, "x-github": { "enabledForGitHubApps": true, "githubCloudOnly": false, "category": "actions", "subcategory": "permissions" } }, "put": { "summary": "Set allowed actions for an organization", "description": "Sets the actions that are allowed in an organization. To use this endpoint, the organization permission policy for `allowed_actions` must be configured to `selected`. For more information, see \"[Set GitHub Actions permissions for an organization](#set-github-actions-permissions-for-an-organization).\"\n\nIf the organization belongs to an enterprise that has `selected` actions set at the enterprise level, then you cannot override any of the enterprise's allowed actions settings.\n\nTo use the `patterns_allowed` setting for private repositories, the organization must belong to an enterprise. If the organization does not belong to an enterprise, then the `patterns_allowed` setting only applies to public repositories in the organization.\n\nYou must authenticate using an access token with the `admin:org` scope to use this endpoint. GitHub Apps must have the `administration` organization permission to use this API.", "operationId": "actions/set-allowed-actions-organization", "tags": [ "actions" ], "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/actions#set-allowed-actions-for-an-organization" }, "parameters": [ { "$ref": "#/components/parameters/org" } ], "responses": { "204": { "description": "Response" } }, "requestBody": { "required": false, "content": { "application/json": { "schema": { "$ref": "#/components/schemas/selected-actions" }, "examples": { "selected_actions": { "$ref": "#/components/examples/selected-actions" } } } } }, "x-github": { "enabledForGitHubApps": true, "githubCloudOnly": false, "category": "actions", "subcategory": "permissions" } } }, "/orgs/{org}/actions/runner-groups": { "get": { "summary": "List self-hosted runner groups for an organization", "description": "Lists all self-hosted runner groups configured in an organization and inherited from an enterprise.\nYou must authenticate using an access token with the `admin:org` scope to use this endpoint.", "operationId": "actions/list-self-hosted-runner-groups-for-org", "tags": [ "actions" ], "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/actions#list-self-hosted-runner-groups-for-an-organization" }, "parameters": [ { "$ref": "#/components/parameters/org" }, { "$ref": "#/components/parameters/per-page" }, { "$ref": "#/components/parameters/page" } ], "responses": { "200": { "description": "Response", "content": { "application/json": { "schema": { "type": "object", "required": [ "total_count", "runner_groups" ], "properties": { "total_count": { "type": "number" }, "runner_groups": { "type": "array", "items": { "$ref": "#/components/schemas/runner-groups-org" } } } }, "examples": { "default": { "$ref": "#/components/examples/runner-groups-org" } } } } } }, "x-github": { "enabledForGitHubApps": true, "githubCloudOnly": false, "category": "actions", "subcategory": "self-hosted-runner-groups" } }, "post": { "summary": "Create a self-hosted runner group for an organization", "description": "The self-hosted runner groups REST API is available with GitHub Enterprise Cloud and GitHub Enterprise Server. For more information, see \"[GitHub's products](https://docs.github.com/github/getting-started-with-github/githubs-products).\"\n\nCreates a new self-hosted runner group for an organization.\n\nYou must authenticate using an access token with the `admin:org` scope to use this endpoint.", "operationId": "actions/create-self-hosted-runner-group-for-org", "tags": [ "actions" ], "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/actions#create-a-self-hosted-runner-group-for-an-organization" }, "parameters": [ { "$ref": "#/components/parameters/org" } ], "requestBody": { "required": true, "content": { "application/json": { "schema": { "type": "object", "properties": { "name": { "description": "Name of the runner group.", "type": "string" }, "visibility": { "description": "Visibility of a runner group. You can select all repositories, select individual repositories, or limit access to private repositories. Can be one of: `all`, `selected`, or `private`.", "type": "string", "enum": [ "selected", "all", "private" ], "default": "all" }, "selected_repository_ids": { "description": "List of repository IDs that can access the runner group.", "type": "array", "items": { "type": "integer", "description": "Unique identifier of the repository." } }, "runners": { "description": "List of runner IDs to add to the runner group.", "type": "array", "items": { "type": "integer", "description": "Unique identifier of the runner." } }, "allows_public_repositories": { "description": "Whether the runner group can be used by `public` repositories.", "type": "boolean", "default": false } }, "required": [ "name" ] }, "example": { "name": "Expensive hardware runners", "visibility": "selected", "selected_repository_ids": [ 32, 91 ], "runners": [ 9, 2 ] } } } }, "responses": { "201": { "description": "Response", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/runner-groups-org" }, "examples": { "default": { "$ref": "#/components/examples/runner-group" } } } } } }, "x-github": { "enabledForGitHubApps": true, "githubCloudOnly": false, "category": "actions", "subcategory": "self-hosted-runner-groups" } } }, "/orgs/{org}/actions/runner-groups/{runner_group_id}": { "get": { "summary": "Get a self-hosted runner group for an organization", "description": "Gets a specific self-hosted runner group for an organization.\nYou must authenticate using an access token with the `admin:org` scope to use this endpoint.", "operationId": "actions/get-self-hosted-runner-group-for-org", "tags": [ "actions" ], "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/actions#get-a-self-hosted-runner-group-for-an-organization" }, "parameters": [ { "$ref": "#/components/parameters/org" }, { "$ref": "#/components/parameters/runner-group-id" } ], "responses": { "200": { "description": "Response", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/runner-groups-org" }, "examples": { "default": { "$ref": "#/components/examples/runner-group-item" } } } } } }, "x-github": { "enabledForGitHubApps": true, "githubCloudOnly": false, "category": "actions", "subcategory": "self-hosted-runner-groups" } }, "patch": { "summary": "Update a self-hosted runner group for an organization", "description": "Updates the `name` and `visibility` of a self-hosted runner group in an organization.\nYou must authenticate using an access token with the `admin:org` scope to use this endpoint.", "operationId": "actions/update-self-hosted-runner-group-for-org", "tags": [ "actions" ], "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/actions#update-a-self-hosted-runner-group-for-an-organization" }, "parameters": [ { "$ref": "#/components/parameters/org" }, { "$ref": "#/components/parameters/runner-group-id" } ], "requestBody": { "required": true, "content": { "application/json": { "schema": { "type": "object", "properties": { "name": { "description": "Name of the runner group.", "type": "string" }, "visibility": { "description": "Visibility of a runner group. You can select all repositories, select individual repositories, or all private repositories. Can be one of: `all`, `selected`, or `private`.", "type": "string", "enum": [ "selected", "all", "private" ] }, "allows_public_repositories": { "description": "Whether the runner group can be used by `public` repositories.", "type": "boolean", "default": false } }, "required": [ "name" ] }, "example": { "name": "Expensive hardware runners", "visibility": "selected" } } } }, "responses": { "200": { "description": "Response", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/runner-groups-org" }, "examples": { "default": { "$ref": "#/components/examples/runner-group" } } } } } }, "x-github": { "enabledForGitHubApps": true, "githubCloudOnly": false, "category": "actions", "subcategory": "self-hosted-runner-groups" } }, "delete": { "summary": "Delete a self-hosted runner group from an organization", "description": "Deletes a self-hosted runner group for an organization.\nYou must authenticate using an access token with the `admin:org` scope to use this endpoint.", "operationId": "actions/delete-self-hosted-runner-group-from-org", "tags": [ "actions" ], "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/actions#delete-a-self-hosted-runner-group-from-an-organization" }, "parameters": [ { "$ref": "#/components/parameters/org" }, { "$ref": "#/components/parameters/runner-group-id" } ], "responses": { "204": { "description": "Response" } }, "x-github": { "enabledForGitHubApps": true, "githubCloudOnly": false, "category": "actions", "subcategory": "self-hosted-runner-groups" } } }, "/orgs/{org}/actions/runner-groups/{runner_group_id}/repositories": { "get": { "summary": "List repository access to a self-hosted runner group in an organization", "description": "The self-hosted runner groups REST API is available with GitHub Enterprise Cloud and GitHub Enterprise Server. For more information, see \"[GitHub's products](https://docs.github.com/github/getting-started-with-github/githubs-products).\"\n\nLists the repositories with access to a self-hosted runner group configured in an organization.\n\nYou must authenticate using an access token with the `admin:org` scope to use this endpoint.", "operationId": "actions/list-repo-access-to-self-hosted-runner-group-in-org", "tags": [ "actions" ], "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/actions#list-repository-access-to-a-self-hosted-runner-group-in-an-organization" }, "parameters": [ { "$ref": "#/components/parameters/org" }, { "$ref": "#/components/parameters/runner-group-id" }, { "$ref": "#/components/parameters/page" }, { "$ref": "#/components/parameters/per-page" } ], "responses": { "200": { "description": "Response", "content": { "application/json": { "schema": { "type": "object", "required": [ "total_count", "repositories" ], "properties": { "total_count": { "type": "number" }, "repositories": { "type": "array", "items": { "$ref": "#/components/schemas/minimal-repository" } } } }, "examples": { "default": { "$ref": "#/components/examples/minimal-repository-paginated" } } } } } }, "x-github": { "enabledForGitHubApps": true, "githubCloudOnly": false, "category": "actions", "subcategory": "self-hosted-runner-groups" } }, "put": { "summary": "Set repository access for a self-hosted runner group in an organization", "description": "Replaces the list of repositories that have access to a self-hosted runner group configured in an organization.\nYou must authenticate using an access token with the `admin:org` scope to use this endpoint.", "operationId": "actions/set-repo-access-to-self-hosted-runner-group-in-org", "tags": [ "actions" ], "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/actions#set-repository-access-to-a-self-hosted-runner-group-in-an-organization" }, "parameters": [ { "$ref": "#/components/parameters/org" }, { "$ref": "#/components/parameters/runner-group-id" } ], "requestBody": { "required": true, "content": { "application/json": { "schema": { "type": "object", "properties": { "selected_repository_ids": { "description": "List of repository IDs that can access the runner group.", "type": "array", "items": { "type": "integer", "description": "Unique identifier of the repository." } } }, "required": [ "selected_repository_ids" ] }, "example": { "selected_repository_ids": [ 32, 91 ] } } } }, "responses": { "204": { "description": "Response" } }, "x-github": { "enabledForGitHubApps": true, "githubCloudOnly": false, "category": "actions", "subcategory": "self-hosted-runner-groups" } } }, "/orgs/{org}/actions/runner-groups/{runner_group_id}/repositories/{repository_id}": { "put": { "summary": "Add repository access to a self-hosted runner group in an organization", "description": "Adds a repository to the list of selected repositories that can access a self-hosted runner group. The runner group must have `visibility` set to `selected`. For more information, see \"[Create a self-hosted runner group for an organization](#create-a-self-hosted-runner-group-for-an-organization).\"\nYou must authenticate using an access token with the `admin:org` scope to use this endpoint.", "operationId": "actions/add-repo-access-to-self-hosted-runner-group-in-org", "tags": [ "actions" ], "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/actions#add-repository-acess-to-a-self-hosted-runner-group-in-an-organization" }, "parameters": [ { "$ref": "#/components/parameters/org" }, { "$ref": "#/components/parameters/runner-group-id" }, { "$ref": "#/components/parameters/repository-id" } ], "responses": { "204": { "description": "Response" } }, "x-github": { "enabledForGitHubApps": true, "githubCloudOnly": true, "category": "actions", "subcategory": "self-hosted-runner-groups" } }, "delete": { "summary": "Remove repository access to a self-hosted runner group in an organization", "description": "Removes a repository from the list of selected repositories that can access a self-hosted runner group. The runner group must have `visibility` set to `selected`. For more information, see \"[Create a self-hosted runner group for an organization](#create-a-self-hosted-runner-group-for-an-organization).\"\nYou must authenticate using an access token with the `admin:org` scope to use this endpoint.", "operationId": "actions/remove-repo-access-to-self-hosted-runner-group-in-org", "tags": [ "actions" ], "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/actions#remove-repository-access-to-a-self-hosted-runner-group-in-an-organization" }, "parameters": [ { "$ref": "#/components/parameters/org" }, { "$ref": "#/components/parameters/runner-group-id" }, { "$ref": "#/components/parameters/repository-id" } ], "responses": { "204": { "description": "Response" } }, "x-github": { "enabledForGitHubApps": true, "githubCloudOnly": false, "category": "actions", "subcategory": "self-hosted-runner-groups" } } }, "/orgs/{org}/actions/runner-groups/{runner_group_id}/runners": { "get": { "summary": "List self-hosted runners in a group for an organization", "description": "Lists self-hosted runners that are in a specific organization group.\nYou must authenticate using an access token with the `admin:org` scope to use this endpoint.", "operationId": "actions/list-self-hosted-runners-in-group-for-org", "tags": [ "actions" ], "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/actions#list-self-hosted-runners-in-a-group-for-an-organization" }, "parameters": [ { "$ref": "#/components/parameters/org" }, { "$ref": "#/components/parameters/runner-group-id" }, { "$ref": "#/components/parameters/per-page" }, { "$ref": "#/components/parameters/page" } ], "responses": { "200": { "description": "Response", "content": { "application/json": { "schema": { "type": "object", "required": [ "total_count", "runners" ], "properties": { "total_count": { "type": "number" }, "runners": { "type": "array", "items": { "$ref": "#/components/schemas/runner" } } } }, "examples": { "default": { "$ref": "#/components/examples/runner-paginated" } } } }, "headers": { "Link": { "$ref": "#/components/headers/link" } } } }, "x-github": { "enabledForGitHubApps": true, "githubCloudOnly": false, "category": "actions", "subcategory": "self-hosted-runner-groups" } }, "put": { "summary": "Set self-hosted runners in a group for an organization", "description": "Replaces the list of self-hosted runners that are part of an organization runner group.\nYou must authenticate using an access token with the `admin:org` scope to use this endpoint.", "operationId": "actions/set-self-hosted-runners-in-group-for-org", "tags": [ "actions" ], "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/actions#set-self-hosted-runners-in-a-group-for-an-organization" }, "parameters": [ { "$ref": "#/components/parameters/org" }, { "$ref": "#/components/parameters/runner-group-id" } ], "requestBody": { "required": true, "content": { "application/json": { "schema": { "type": "object", "properties": { "runners": { "description": "List of runner IDs to add to the runner group.", "type": "array", "items": { "type": "integer", "description": "Unique identifier of the runner." } } }, "required": [ "runners" ] }, "example": { "runners": [ 9, 2 ] } } } }, "responses": { "204": { "description": "Response" } }, "x-github": { "enabledForGitHubApps": true, "githubCloudOnly": false, "category": "actions", "subcategory": "self-hosted-runner-groups" } } }, "/orgs/{org}/actions/runner-groups/{runner_group_id}/runners/{runner_id}": { "put": { "summary": "Add a self-hosted runner to a group for an organization", "description": "Adds a self-hosted runner to a runner group configured in an organization.\nYou must authenticate using an access token with the `admin:org` scope to use this endpoint.", "operationId": "actions/add-self-hosted-runner-to-group-for-org", "tags": [ "actions" ], "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/actions#add-a-self-hosted-runner-to-a-group-for-an-organization" }, "parameters": [ { "$ref": "#/components/parameters/org" }, { "$ref": "#/components/parameters/runner-group-id" }, { "$ref": "#/components/parameters/runner-id" } ], "responses": { "204": { "description": "Response" } }, "x-github": { "enabledForGitHubApps": true, "githubCloudOnly": false, "category": "actions", "subcategory": "self-hosted-runner-groups" } }, "delete": { "summary": "Remove a self-hosted runner from a group for an organization", "description": "Removes a self-hosted runner from a group configured in an organization. The runner is then returned to the default group.\nYou must authenticate using an access token with the `admin:org` scope to use this endpoint.", "operationId": "actions/remove-self-hosted-runner-from-group-for-org", "tags": [ "actions" ], "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/actions#remove-a-self-hosted-runner-from-a-group-for-an-organization" }, "parameters": [ { "$ref": "#/components/parameters/org" }, { "$ref": "#/components/parameters/runner-group-id" }, { "$ref": "#/components/parameters/runner-id" } ], "responses": { "204": { "description": "Response" } }, "x-github": { "enabledForGitHubApps": true, "githubCloudOnly": false, "category": "actions", "subcategory": "self-hosted-runner-groups" } } }, "/orgs/{org}/actions/runners": { "get": { "summary": "List self-hosted runners for an organization", "description": "Lists all self-hosted runners configured in an organization.\n\nYou must authenticate using an access token with the `admin:org` scope to use this endpoint.", "tags": [ "actions" ], "operationId": "actions/list-self-hosted-runners-for-org", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/actions#list-self-hosted-runners-for-an-organization" }, "parameters": [ { "$ref": "#/components/parameters/org" }, { "$ref": "#/components/parameters/per-page" }, { "$ref": "#/components/parameters/page" } ], "responses": { "200": { "description": "Response", "content": { "application/json": { "schema": { "type": "object", "required": [ "total_count", "runners" ], "properties": { "total_count": { "type": "integer" }, "runners": { "type": "array", "items": { "$ref": "#/components/schemas/runner" } } } }, "examples": { "default": { "$ref": "#/components/examples/runner-paginated" } } } }, "headers": { "Link": { "$ref": "#/components/headers/link" } } } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": true, "category": "actions", "subcategory": "self-hosted-runners" } } }, "/orgs/{org}/actions/runners/downloads": { "get": { "summary": "List runner applications for an organization", "description": "Lists binaries for the runner application that you can download and run.\n\nYou must authenticate using an access token with the `admin:org` scope to use this endpoint.", "tags": [ "actions" ], "operationId": "actions/list-runner-applications-for-org", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/actions#list-runner-applications-for-an-organization" }, "parameters": [ { "$ref": "#/components/parameters/org" } ], "responses": { "200": { "description": "Response", "content": { "application/json": { "schema": { "type": "array", "items": { "$ref": "#/components/schemas/runner-application" } }, "examples": { "default": { "$ref": "#/components/examples/runner-application-items" } } } } } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": true, "category": "actions", "subcategory": "self-hosted-runners" } } }, "/orgs/{org}/actions/runners/registration-token": { "post": { "summary": "Create a registration token for an organization", "description": "Returns a token that you can pass to the `config` script. The token expires after one hour.\n\nYou must authenticate using an access token with the `admin:org` scope to use this endpoint.\n\n#### Example using registration token\n\nConfigure your self-hosted runner, replacing `TOKEN` with the registration token provided by this endpoint.\n\n```\n./config.sh --url https://github.com/octo-org --token TOKEN\n```", "tags": [ "actions" ], "operationId": "actions/create-registration-token-for-org", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/actions#create-a-registration-token-for-an-organization" }, "parameters": [ { "$ref": "#/components/parameters/org" } ], "responses": { "201": { "description": "Response", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/authentication-token" }, "examples": { "default": { "$ref": "#/components/examples/authentication-token" } } } } } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": true, "category": "actions", "subcategory": "self-hosted-runners" } } }, "/orgs/{org}/actions/runners/remove-token": { "post": { "summary": "Create a remove token for an organization", "description": "Returns a token that you can pass to the `config` script to remove a self-hosted runner from an organization. The token expires after one hour.\n\nYou must authenticate using an access token with the `admin:org` scope to use this endpoint.\n\n#### Example using remove token\n\nTo remove your self-hosted runner from an organization, replace `TOKEN` with the remove token provided by this\nendpoint.\n\n```\n./config.sh remove --token TOKEN\n```", "tags": [ "actions" ], "operationId": "actions/create-remove-token-for-org", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/actions#create-a-remove-token-for-an-organization" }, "parameters": [ { "$ref": "#/components/parameters/org" } ], "responses": { "201": { "description": "Response", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/authentication-token" }, "examples": { "default": { "$ref": "#/components/examples/authentication-token-2" } } } } } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": true, "category": "actions", "subcategory": "self-hosted-runners" } } }, "/orgs/{org}/actions/runners/{runner_id}": { "get": { "summary": "Get a self-hosted runner for an organization", "description": "Gets a specific self-hosted runner configured in an organization.\n\nYou must authenticate using an access token with the `admin:org` scope to use this endpoint.", "tags": [ "actions" ], "operationId": "actions/get-self-hosted-runner-for-org", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/actions#get-a-self-hosted-runner-for-an-organization" }, "parameters": [ { "$ref": "#/components/parameters/org" }, { "$ref": "#/components/parameters/runner-id" } ], "responses": { "200": { "description": "Response", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/runner" }, "examples": { "default": { "$ref": "#/components/examples/runner" } } } } } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": true, "category": "actions", "subcategory": "self-hosted-runners" } }, "delete": { "summary": "Delete a self-hosted runner from an organization", "description": "Forces the removal of a self-hosted runner from an organization. You can use this endpoint to completely remove the runner when the machine you were using no longer exists.\n\nYou must authenticate using an access token with the `admin:org` scope to use this endpoint.", "tags": [ "actions" ], "operationId": "actions/delete-self-hosted-runner-from-org", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/actions#delete-a-self-hosted-runner-from-an-organization" }, "parameters": [ { "$ref": "#/components/parameters/org" }, { "$ref": "#/components/parameters/runner-id" } ], "responses": { "204": { "description": "Response" } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": true, "category": "actions", "subcategory": "self-hosted-runners" } } }, "/orgs/{org}/actions/secrets": { "get": { "summary": "List organization secrets", "description": "Lists all secrets available in an organization without revealing their encrypted values. You must authenticate using an access token with the `admin:org` scope to use this endpoint. GitHub Apps must have the `secrets` organization permission to use this endpoint.", "tags": [ "actions" ], "operationId": "actions/list-org-secrets", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/actions#list-organization-secrets" }, "parameters": [ { "$ref": "#/components/parameters/org" }, { "$ref": "#/components/parameters/per-page" }, { "$ref": "#/components/parameters/page" } ], "responses": { "200": { "description": "Response", "content": { "application/json": { "schema": { "type": "object", "required": [ "total_count", "secrets" ], "properties": { "total_count": { "type": "integer" }, "secrets": { "type": "array", "items": { "$ref": "#/components/schemas/organization-actions-secret" } } } }, "examples": { "default": { "$ref": "#/components/examples/organization-actions-secret-paginated" } } } }, "headers": { "Link": { "$ref": "#/components/headers/link" } } } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": true, "category": "actions", "subcategory": "secrets" } } }, "/orgs/{org}/actions/secrets/public-key": { "get": { "summary": "Get an organization public key", "description": "Gets your public key, which you need to encrypt secrets. You need to encrypt a secret before you can create or update secrets. You must authenticate using an access token with the `admin:org` scope to use this endpoint. GitHub Apps must have the `secrets` organization permission to use this endpoint.", "tags": [ "actions" ], "operationId": "actions/get-org-public-key", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/actions#get-an-organization-public-key" }, "parameters": [ { "$ref": "#/components/parameters/org" } ], "responses": { "200": { "description": "Response", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/actions-public-key" }, "examples": { "default": { "$ref": "#/components/examples/actions-public-key" } } } } } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": true, "category": "actions", "subcategory": "secrets" } } }, "/orgs/{org}/actions/secrets/{secret_name}": { "get": { "summary": "Get an organization secret", "description": "Gets a single organization secret without revealing its encrypted value. You must authenticate using an access token with the `admin:org` scope to use this endpoint. GitHub Apps must have the `secrets` organization permission to use this endpoint.", "tags": [ "actions" ], "operationId": "actions/get-org-secret", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/actions#get-an-organization-secret" }, "parameters": [ { "$ref": "#/components/parameters/org" }, { "$ref": "#/components/parameters/secret-name" } ], "responses": { "200": { "description": "Response", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/organization-actions-secret" }, "examples": { "default": { "$ref": "#/components/examples/organization-actions-secret" } } } } } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": true, "category": "actions", "subcategory": "secrets" } }, "put": { "summary": "Create or update an organization secret", "description": "Creates or updates an organization secret with an encrypted value. Encrypt your secret using\n[LibSodium](https://libsodium.gitbook.io/doc/bindings_for_other_languages). You must authenticate using an access\ntoken with the `admin:org` scope to use this endpoint. GitHub Apps must have the `secrets` organization permission to\nuse this endpoint.\n\n#### Example encrypting a secret using Node.js\n\nEncrypt your secret using the [tweetsodium](https://github.com/github/tweetsodium) library.\n\n```\nconst sodium = require('tweetsodium');\n\nconst key = \"base64-encoded-public-key\";\nconst value = \"plain-text-secret\";\n\n// Convert the message and key to Uint8Array's (Buffer implements that interface)\nconst messageBytes = Buffer.from(value);\nconst keyBytes = Buffer.from(key, 'base64');\n\n// Encrypt using LibSodium.\nconst encryptedBytes = sodium.seal(messageBytes, keyBytes);\n\n// Base64 the encrypted secret\nconst encrypted = Buffer.from(encryptedBytes).toString('base64');\n\nconsole.log(encrypted);\n```\n\n\n#### Example encrypting a secret using Python\n\nEncrypt your secret using [pynacl](https://pynacl.readthedocs.io/en/latest/public/#nacl-public-sealedbox) with Python 3.\n\n```\nfrom base64 import b64encode\nfrom nacl import encoding, public\n\ndef encrypt(public_key: str, secret_value: str) -> str:\n \"\"\"Encrypt a Unicode string using the public key.\"\"\"\n public_key = public.PublicKey(public_key.encode(\"utf-8\"), encoding.Base64Encoder())\n sealed_box = public.SealedBox(public_key)\n encrypted = sealed_box.encrypt(secret_value.encode(\"utf-8\"))\n return b64encode(encrypted).decode(\"utf-8\")\n```\n\n#### Example encrypting a secret using C#\n\nEncrypt your secret using the [Sodium.Core](https://www.nuget.org/packages/Sodium.Core/) package.\n\n```\nvar secretValue = System.Text.Encoding.UTF8.GetBytes(\"mySecret\");\nvar publicKey = Convert.FromBase64String(\"2Sg8iYjAxxmI2LvUXpJjkYrMxURPc8r+dB7TJyvvcCU=\");\n\nvar sealedPublicKeyBox = Sodium.SealedPublicKeyBox.Create(secretValue, publicKey);\n\nConsole.WriteLine(Convert.ToBase64String(sealedPublicKeyBox));\n```\n\n#### Example encrypting a secret using Ruby\n\nEncrypt your secret using the [rbnacl](https://github.com/RubyCrypto/rbnacl) gem.\n\n```ruby\nrequire \"rbnacl\"\nrequire \"base64\"\n\nkey = Base64.decode64(\"+ZYvJDZMHUfBkJdyq5Zm9SKqeuBQ4sj+6sfjlH4CgG0=\")\npublic_key = RbNaCl::PublicKey.new(key)\n\nbox = RbNaCl::Boxes::Sealed.from_public_key(public_key)\nencrypted_secret = box.encrypt(\"my_secret\")\n\n# Print the base64 encoded secret\nputs Base64.strict_encode64(encrypted_secret)\n```", "tags": [ "actions" ], "operationId": "actions/create-or-update-org-secret", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/actions#create-or-update-an-organization-secret" }, "parameters": [ { "$ref": "#/components/parameters/org" }, { "$ref": "#/components/parameters/secret-name" } ], "requestBody": { "required": true, "content": { "application/json": { "schema": { "type": "object", "properties": { "encrypted_value": { "type": "string", "description": "Value for your secret, encrypted with [LibSodium](https://libsodium.gitbook.io/doc/bindings_for_other_languages) using the public key retrieved from the [Get an organization public key](https://docs.github.com/enterprise-server@3.0/rest/reference/actions#get-an-organization-public-key) endpoint.", "pattern": "^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=|[A-Za-z0-9+/]{4})$" }, "key_id": { "type": "string", "description": "ID of the key you used to encrypt the secret." }, "visibility": { "type": "string", "description": "Configures the access that repositories have to the organization secret. Can be one of: \n\\- `all` - All repositories in an organization can access the secret. \n\\- `private` - Private repositories in an organization can access the secret. \n\\- `selected` - Only specific repositories can access the secret.", "enum": [ "all", "private", "selected" ] }, "selected_repository_ids": { "type": "array", "description": "An array of repository ids that can access the organization secret. You can only provide a list of repository ids when the `visibility` is set to `selected`. You can manage the list of selected repositories using the [List selected repositories for an organization secret](https://docs.github.com/enterprise-server@3.0/rest/reference/actions#list-selected-repositories-for-an-organization-secret), [Set selected repositories for an organization secret](https://docs.github.com/enterprise-server@3.0/rest/reference/actions#set-selected-repositories-for-an-organization-secret), and [Remove selected repository from an organization secret](https://docs.github.com/enterprise-server@3.0/rest/reference/actions#remove-selected-repository-from-an-organization-secret) endpoints.", "items": { "type": "string" } } }, "required": [ "visibility" ] }, "example": { "encrypted_value": "c2VjcmV0", "key_id": "012345678912345678", "visibility": "selected", "selected_repository_ids": [ "1296269", "1296280" ] } } } }, "responses": { "201": { "description": "Response when creating a secret", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/empty-object" } } } }, "204": { "description": "Response when updating a secret" } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": true, "category": "actions", "subcategory": "secrets" } }, "delete": { "summary": "Delete an organization secret", "description": "Deletes a secret in an organization using the secret name. You must authenticate using an access token with the `admin:org` scope to use this endpoint. GitHub Apps must have the `secrets` organization permission to use this endpoint.", "tags": [ "actions" ], "operationId": "actions/delete-org-secret", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/actions#delete-an-organization-secret" }, "parameters": [ { "$ref": "#/components/parameters/org" }, { "$ref": "#/components/parameters/secret-name" } ], "responses": { "204": { "description": "Response" } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": true, "category": "actions", "subcategory": "secrets" } } }, "/orgs/{org}/actions/secrets/{secret_name}/repositories": { "get": { "summary": "List selected repositories for an organization secret", "description": "Lists all repositories that have been selected when the `visibility` for repository access to a secret is set to `selected`. You must authenticate using an access token with the `admin:org` scope to use this endpoint. GitHub Apps must have the `secrets` organization permission to use this endpoint.", "tags": [ "actions" ], "operationId": "actions/list-selected-repos-for-org-secret", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/actions#list-selected-repositories-for-an-organization-secret" }, "parameters": [ { "$ref": "#/components/parameters/org" }, { "$ref": "#/components/parameters/secret-name" }, { "$ref": "#/components/parameters/page" }, { "$ref": "#/components/parameters/per-page" } ], "responses": { "200": { "description": "Response", "content": { "application/json": { "schema": { "type": "object", "required": [ "total_count", "repositories" ], "properties": { "total_count": { "type": "integer" }, "repositories": { "type": "array", "items": { "$ref": "#/components/schemas/minimal-repository" } } } }, "examples": { "default": { "$ref": "#/components/examples/public-repository-paginated" } } } } } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": true, "category": "actions", "subcategory": "secrets" } }, "put": { "summary": "Set selected repositories for an organization secret", "description": "Replaces all repositories for an organization secret when the `visibility` for repository access is set to `selected`. The visibility is set when you [Create or update an organization secret](https://docs.github.com/enterprise-server@3.0/rest/reference/actions#create-or-update-an-organization-secret). You must authenticate using an access token with the `admin:org` scope to use this endpoint. GitHub Apps must have the `secrets` organization permission to use this endpoint.", "tags": [ "actions" ], "operationId": "actions/set-selected-repos-for-org-secret", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/actions#set-selected-repositories-for-an-organization-secret" }, "parameters": [ { "$ref": "#/components/parameters/org" }, { "$ref": "#/components/parameters/secret-name" } ], "requestBody": { "required": true, "content": { "application/json": { "schema": { "type": "object", "properties": { "selected_repository_ids": { "type": "array", "description": "An array of repository ids that can access the organization secret. You can only provide a list of repository ids when the `visibility` is set to `selected`. You can add and remove individual repositories using the [Set selected repositories for an organization secret](https://docs.github.com/enterprise-server@3.0/rest/reference/actions#set-selected-repositories-for-an-organization-secret) and [Remove selected repository from an organization secret](https://docs.github.com/enterprise-server@3.0/rest/reference/actions#remove-selected-repository-from-an-organization-secret) endpoints.", "items": { "type": "integer" } } }, "required": [ "selected_repository_ids" ] }, "example": { "selected_repository_ids": [ 64780797 ] } } } }, "responses": { "204": { "description": "Response" } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": true, "category": "actions", "subcategory": "secrets" } } }, "/orgs/{org}/actions/secrets/{secret_name}/repositories/{repository_id}": { "put": { "summary": "Add selected repository to an organization secret", "description": "Adds a repository to an organization secret when the `visibility` for repository access is set to `selected`. The visibility is set when you [Create or update an organization secret](https://docs.github.com/enterprise-server@3.0/rest/reference/actions#create-or-update-an-organization-secret). You must authenticate using an access token with the `admin:org` scope to use this endpoint. GitHub Apps must have the `secrets` organization permission to use this endpoint.", "tags": [ "actions" ], "operationId": "actions/add-selected-repo-to-org-secret", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/actions#add-selected-repository-to-an-organization-secret" }, "parameters": [ { "$ref": "#/components/parameters/org" }, { "$ref": "#/components/parameters/secret-name" }, { "name": "repository_id", "in": "path", "required": true, "schema": { "type": "integer" } } ], "responses": { "204": { "description": "No Content when repository was added to the selected list" }, "409": { "description": "Conflict when visibility type is not set to selected" } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": true, "category": "actions", "subcategory": "secrets" } }, "delete": { "summary": "Remove selected repository from an organization secret", "description": "Removes a repository from an organization secret when the `visibility` for repository access is set to `selected`. The visibility is set when you [Create or update an organization secret](https://docs.github.com/enterprise-server@3.0/rest/reference/actions#create-or-update-an-organization-secret). You must authenticate using an access token with the `admin:org` scope to use this endpoint. GitHub Apps must have the `secrets` organization permission to use this endpoint.", "tags": [ "actions" ], "operationId": "actions/remove-selected-repo-from-org-secret", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/actions#remove-selected-repository-from-an-organization-secret" }, "parameters": [ { "$ref": "#/components/parameters/org" }, { "$ref": "#/components/parameters/secret-name" }, { "name": "repository_id", "in": "path", "required": true, "schema": { "type": "integer" } } ], "responses": { "204": { "description": "Response when repository was removed from the selected list" }, "409": { "description": "Conflict when visibility type not set to selected" } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": true, "category": "actions", "subcategory": "secrets" } } }, "/orgs/{org}/events": { "get": { "summary": "List public organization events", "description": "", "tags": [ "activity" ], "operationId": "activity/list-public-org-events", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/activity#list-public-organization-events" }, "parameters": [ { "$ref": "#/components/parameters/org" }, { "$ref": "#/components/parameters/per-page" }, { "$ref": "#/components/parameters/page" } ], "responses": { "200": { "description": "Response", "content": { "application/json": { "schema": { "type": "array", "items": { "$ref": "#/components/schemas/event" } } } } } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": true, "category": "activity", "subcategory": "events" } } }, "/orgs/{org}/hooks": { "get": { "summary": "List organization webhooks", "description": "", "tags": [ "orgs" ], "operationId": "orgs/list-webhooks", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/orgs#list-organization-webhooks" }, "parameters": [ { "$ref": "#/components/parameters/org" }, { "$ref": "#/components/parameters/per-page" }, { "$ref": "#/components/parameters/page" } ], "responses": { "200": { "description": "Response", "content": { "application/json": { "schema": { "type": "array", "items": { "$ref": "#/components/schemas/org-hook" } }, "examples": { "default": { "$ref": "#/components/examples/org-hook-items" } } } }, "headers": { "Link": { "$ref": "#/components/headers/link" } } }, "404": { "$ref": "#/components/responses/not_found" } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": true, "category": "orgs", "subcategory": "webhooks" } }, "post": { "summary": "Create an organization webhook", "description": "Here's how you can create a hook that posts payloads in JSON format:", "tags": [ "orgs" ], "operationId": "orgs/create-webhook", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/orgs#create-an-organization-webhook" }, "parameters": [ { "$ref": "#/components/parameters/org" } ], "requestBody": { "required": true, "content": { "application/json": { "schema": { "type": "object", "properties": { "name": { "type": "string", "description": "Must be passed as \"web\"." }, "config": { "type": "object", "description": "Key/value pairs to provide settings for this webhook. [These are defined below](https://docs.github.com/enterprise-server@3.0/rest/reference/orgs#create-hook-config-params).", "properties": { "url": { "$ref": "#/components/schemas/webhook-config-url" }, "content_type": { "$ref": "#/components/schemas/webhook-config-content-type" }, "secret": { "$ref": "#/components/schemas/webhook-config-secret" }, "insecure_ssl": { "$ref": "#/components/schemas/webhook-config-insecure-ssl" }, "username": { "type": "string", "examples": [ "\"kdaigle\"" ] }, "password": { "type": "string", "examples": [ "\"password\"" ] } }, "required": [ "url" ] }, "events": { "type": "array", "description": "Determines what [events](https://docs.github.com/enterprise-server@3.0/webhooks/event-payloads) the hook is triggered for.", "default": [ "push" ], "items": { "type": "string" } }, "active": { "type": "boolean", "description": "Determines if notifications are sent when the webhook is triggered. Set to `true` to send notifications.", "default": true } }, "required": [ "name", "config" ] }, "example": { "name": "web", "active": true, "events": [ "push", "pull_request" ], "config": { "url": "http://example.com/webhook", "content_type": "json" } } } } }, "responses": { "201": { "description": "Response", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/org-hook" }, "examples": { "default": { "$ref": "#/components/examples/org-hook" } } } }, "headers": { "Location": { "example": "https://api.github.com/orgs/octocat/hooks/1", "schema": { "type": "string" } } } }, "422": { "$ref": "#/components/responses/validation_failed" }, "404": { "$ref": "#/components/responses/not_found" } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": true, "category": "orgs", "subcategory": "webhooks" } } }, "/orgs/{org}/hooks/{hook_id}": { "get": { "summary": "Get an organization webhook", "description": "Returns a webhook configured in an organization. To get only the webhook `config` properties, see \"[Get a webhook configuration for an organization](/rest/reference/orgs#get-a-webhook-configuration-for-an-organization).\"", "tags": [ "orgs" ], "operationId": "orgs/get-webhook", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/orgs#get-an-organization-webhook" }, "parameters": [ { "$ref": "#/components/parameters/org" }, { "$ref": "#/components/parameters/hook-id" } ], "responses": { "200": { "description": "Response", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/org-hook" }, "examples": { "default": { "$ref": "#/components/examples/org-hook" } } } } }, "404": { "$ref": "#/components/responses/not_found" } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": true, "category": "orgs", "subcategory": "webhooks" } }, "patch": { "summary": "Update an organization webhook", "description": "Updates a webhook configured in an organization. When you update a webhook, the `secret` will be overwritten. If you previously had a `secret` set, you must provide the same `secret` or set a new `secret` or the secret will be removed. If you are only updating individual webhook `config` properties, use \"[Update a webhook configuration for an organization](/rest/reference/orgs#update-a-webhook-configuration-for-an-organization).\"", "tags": [ "orgs" ], "operationId": "orgs/update-webhook", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/orgs#update-an-organization-webhook" }, "parameters": [ { "$ref": "#/components/parameters/org" }, { "$ref": "#/components/parameters/hook-id" } ], "requestBody": { "required": false, "content": { "application/json": { "schema": { "type": "object", "properties": { "config": { "type": "object", "description": "Key/value pairs to provide settings for this webhook. [These are defined below](https://docs.github.com/enterprise-server@3.0/rest/reference/orgs#update-hook-config-params).", "properties": { "url": { "$ref": "#/components/schemas/webhook-config-url" }, "content_type": { "$ref": "#/components/schemas/webhook-config-content-type" }, "secret": { "$ref": "#/components/schemas/webhook-config-secret" }, "insecure_ssl": { "$ref": "#/components/schemas/webhook-config-insecure-ssl" } }, "required": [ "url" ] }, "events": { "type": "array", "description": "Determines what [events](https://docs.github.com/enterprise-server@3.0/webhooks/event-payloads) the hook is triggered for.", "default": [ "push" ], "items": { "type": "string" } }, "active": { "type": "boolean", "description": "Determines if notifications are sent when the webhook is triggered. Set to `true` to send notifications.", "default": true }, "name": { "type": "string", "examples": [ "\"web\"" ] } } }, "example": { "active": true, "events": [ "pull_request" ] } } } }, "responses": { "200": { "description": "Response", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/org-hook" }, "examples": { "default": { "$ref": "#/components/examples/org-hook-2" } } } } }, "422": { "$ref": "#/components/responses/validation_failed" }, "404": { "$ref": "#/components/responses/not_found" } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": true, "category": "orgs", "subcategory": "webhooks" } }, "delete": { "summary": "Delete an organization webhook", "description": "", "tags": [ "orgs" ], "operationId": "orgs/delete-webhook", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/orgs#delete-an-organization-webhook" }, "parameters": [ { "$ref": "#/components/parameters/org" }, { "$ref": "#/components/parameters/hook-id" } ], "responses": { "204": { "description": "Response" }, "404": { "$ref": "#/components/responses/not_found" } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": true, "category": "orgs", "subcategory": "webhooks" } } }, "/orgs/{org}/hooks/{hook_id}/config": { "get": { "summary": "Get a webhook configuration for an organization", "description": "Returns the webhook configuration for an organization. To get more information about the webhook, including the `active` state and `events`, use \"[Get an organization webhook ](/rest/reference/orgs#get-an-organization-webhook).\"\n\nAccess tokens must have the `admin:org_hook` scope, and GitHub Apps must have the `organization_hooks:read` permission.", "tags": [ "orgs" ], "operationId": "orgs/get-webhook-config-for-org", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/orgs#get-a-webhook-configuration-for-an-organization" }, "parameters": [ { "$ref": "#/components/parameters/org" }, { "$ref": "#/components/parameters/hook-id" } ], "responses": { "200": { "description": "Response", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/webhook-config" }, "examples": { "default": { "$ref": "#/components/examples/webhook-config" } } } } } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": true, "category": "orgs", "subcategory": "webhooks" } }, "patch": { "summary": "Update a webhook configuration for an organization", "description": "Updates the webhook configuration for an organization. To update more information about the webhook, including the `active` state and `events`, use \"[Update an organization webhook ](/rest/reference/orgs#update-an-organization-webhook).\"\n\nAccess tokens must have the `admin:org_hook` scope, and GitHub Apps must have the `organization_hooks:write` permission.", "tags": [ "orgs" ], "operationId": "orgs/update-webhook-config-for-org", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/orgs#update-a-webhook-configuration-for-an-organization" }, "parameters": [ { "$ref": "#/components/parameters/org" }, { "$ref": "#/components/parameters/hook-id" } ], "requestBody": { "required": false, "content": { "application/json": { "schema": { "type": "object", "properties": { "url": { "$ref": "#/components/schemas/webhook-config-url" }, "content_type": { "$ref": "#/components/schemas/webhook-config-content-type" }, "secret": { "$ref": "#/components/schemas/webhook-config-secret" }, "insecure_ssl": { "$ref": "#/components/schemas/webhook-config-insecure-ssl" } }, "example": { "content_type": "json", "insecure_ssl": "0", "secret": "********", "url": "https://example.com/webhook" }, "additionalProperties": false } } } }, "responses": { "200": { "description": "Response", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/webhook-config" }, "examples": { "default": { "$ref": "#/components/examples/webhook-config" } } } } } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": true, "category": "orgs", "subcategory": "webhooks" } } }, "/orgs/{org}/hooks/{hook_id}/pings": { "post": { "summary": "Ping an organization webhook", "description": "This will trigger a [ping event](https://docs.github.com/enterprise-server@3.0/webhooks/#ping-event) to be sent to the hook.", "tags": [ "orgs" ], "operationId": "orgs/ping-webhook", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/orgs#ping-an-organization-webhook" }, "parameters": [ { "$ref": "#/components/parameters/org" }, { "$ref": "#/components/parameters/hook-id" } ], "responses": { "204": { "description": "Response" }, "404": { "$ref": "#/components/responses/not_found" } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": true, "category": "orgs", "subcategory": "webhooks" } } }, "/orgs/{org}/installation": { "get": { "summary": "Get an organization installation for the authenticated app", "description": "Enables an authenticated GitHub App to find the organization's installation information.\n\nYou must use a [JWT](https://docs.github.com/enterprise-server@3.0/apps/building-github-apps/authenticating-with-github-apps/#authenticating-as-a-github-app) to access this endpoint.", "tags": [ "apps" ], "operationId": "apps/get-org-installation", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/apps#get-an-organization-installation-for-the-authenticated-app" }, "parameters": [ { "$ref": "#/components/parameters/org" } ], "responses": { "200": { "description": "Response", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/installation" }, "examples": { "default": { "$ref": "#/components/examples/installation" } } } } } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": false, "category": "apps", "subcategory": null } } }, "/orgs/{org}/installations": { "get": { "summary": "List app installations for an organization", "description": "Lists all GitHub Apps in an organization. The installation count includes all GitHub Apps installed on repositories in the organization. You must be an organization owner with `admin:read` scope to use this endpoint.", "tags": [ "orgs" ], "operationId": "orgs/list-app-installations", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/orgs#list-app-installations-for-an-organization" }, "parameters": [ { "$ref": "#/components/parameters/org" }, { "$ref": "#/components/parameters/per-page" }, { "$ref": "#/components/parameters/page" } ], "responses": { "200": { "description": "Response", "content": { "application/json": { "schema": { "type": "object", "required": [ "total_count", "installations" ], "properties": { "total_count": { "type": "integer" }, "installations": { "type": "array", "items": { "$ref": "#/components/schemas/installation" } } } }, "examples": { "default": { "$ref": "#/components/examples/installation-paginated" } } } }, "headers": { "Link": { "$ref": "#/components/headers/link" } } } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": true, "category": "orgs", "subcategory": null } } }, "/orgs/{org}/issues": { "get": { "summary": "List organization issues assigned to the authenticated user", "description": "List issues in an organization assigned to the authenticated user.\n\n**Note**: GitHub's REST API v3 considers every pull request an issue, but not every issue is a pull request. For this\nreason, \"Issues\" endpoints may return both issues and pull requests in the response. You can identify pull requests by\nthe `pull_request` key. Be aware that the `id` of a pull request returned from \"Issues\" endpoints will be an _issue id_. To find out the pull\nrequest id, use the \"[List pull requests](https://docs.github.com/enterprise-server@3.0/rest/reference/pulls#list-pull-requests)\" endpoint.", "tags": [ "issues" ], "operationId": "issues/list-for-org", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/issues#list-organization-issues-assigned-to-the-authenticated-user" }, "parameters": [ { "$ref": "#/components/parameters/org" }, { "name": "filter", "description": "Indicates which sorts of issues to return. Can be one of: \n\\* `assigned`: Issues assigned to you \n\\* `created`: Issues created by you \n\\* `mentioned`: Issues mentioning you \n\\* `subscribed`: Issues you're subscribed to updates for \n\\* `all` or `repos`: All issues the authenticated user can see, regardless of participation or creation", "in": "query", "required": false, "schema": { "type": "string", "enum": [ "assigned", "created", "mentioned", "subscribed", "repos", "all" ], "default": "assigned" } }, { "name": "state", "description": "Indicates the state of the issues to return. Can be either `open`, `closed`, or `all`.", "in": "query", "required": false, "schema": { "type": "string", "enum": [ "open", "closed", "all" ], "default": "open" } }, { "$ref": "#/components/parameters/labels" }, { "name": "sort", "description": "What to sort results by. Can be either `created`, `updated`, `comments`.", "in": "query", "required": false, "schema": { "type": "string", "enum": [ "created", "updated", "comments" ], "default": "created" } }, { "$ref": "#/components/parameters/direction" }, { "$ref": "#/components/parameters/since" }, { "$ref": "#/components/parameters/per-page" }, { "$ref": "#/components/parameters/page" } ], "responses": { "200": { "description": "Response", "content": { "application/json": { "schema": { "type": "array", "items": { "$ref": "#/components/schemas/issue" } }, "examples": { "default": { "$ref": "#/components/examples/issue-with-repo-items" } } } }, "headers": { "Link": { "$ref": "#/components/headers/link" } } }, "404": { "$ref": "#/components/responses/not_found" } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": false, "category": "issues", "previews": [ { "required": false, "name": "machine-man", "note": "If an issue event is created via a GitHub App, the response will include the `performed_via_github_app` object with\tinformation about the GitHub App. For more information, see the [related blog\tpost](https://developer.github.com/changes/2016-09-14-Integrations-Early-Access).\nTo receive the `performed_via_github_app` object in the response, you must provide a custom [media type](https://docs.github.com/enterprise-server@3.0/rest/overview/media-types) in the `Accept` header:\n```shell\napplication/vnd.github.machine-man-preview\n```" }, { "required": false, "name": "squirrel-girl", "note": "An additional `reactions` object in the issue comment payload is currently available for developers to preview. During the preview period, the APIs may change without advance notice. Please see the [blog post](https://developer.github.com/changes/2016-05-12-reactions-api-preview) for full details.\n\nTo access the API you must provide a custom [media type](https://docs.github.com/enterprise-server@3.0/rest/overview/media-types) in the `Accept` header:\n```shell\napplication/vnd.github.squirrel-girl-preview\n```\nThe `reactions` key will have the following payload where `url` can be used to construct the API location for [listing and creating](https://docs.github.com/enterprise-server@3.0/rest/reference/reactions) reactions." } ] } } }, "/orgs/{org}/members": { "get": { "summary": "List organization members", "description": "List all users who are members of an organization. If the authenticated user is also a member of this organization then both concealed and public members will be returned.", "tags": [ "orgs" ], "operationId": "orgs/list-members", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/orgs#list-organization-members" }, "parameters": [ { "$ref": "#/components/parameters/org" }, { "name": "filter", "description": "Filter members returned in the list. Can be one of: \n\\* `2fa_disabled` - Members without [two-factor authentication](https://github.com/blog/1614-two-factor-authentication) enabled. Available for organization owners. \n\\* `all` - All members the authenticated user can see.", "in": "query", "required": false, "schema": { "type": "string", "enum": [ "2fa_disabled", "all" ], "default": "all" } }, { "name": "role", "description": "Filter members returned by their role. Can be one of: \n\\* `all` - All members of the organization, regardless of role. \n\\* `admin` - Organization owners. \n\\* `member` - Non-owner organization members.", "in": "query", "required": false, "schema": { "type": "string", "enum": [ "all", "admin", "member" ], "default": "all" } }, { "$ref": "#/components/parameters/per-page" }, { "$ref": "#/components/parameters/page" } ], "responses": { "200": { "description": "Response", "content": { "application/json": { "schema": { "type": "array", "items": { "$ref": "#/components/schemas/simple-user" } }, "examples": { "default": { "$ref": "#/components/examples/simple-user-items" } } } }, "headers": { "Link": { "$ref": "#/components/headers/link" } } }, "302": { "description": "Response if requester is not an organization member", "headers": { "Location": { "example": "https://api.github.com/orgs/github/public_members", "schema": { "type": "string" } } } }, "422": { "$ref": "#/components/responses/validation_failed" } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": true, "category": "orgs", "subcategory": "members" } } }, "/orgs/{org}/members/{username}": { "get": { "summary": "Check organization membership for a user", "description": "Check if a user is, publicly or privately, a member of the organization.", "tags": [ "orgs" ], "operationId": "orgs/check-membership-for-user", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/orgs#check-organization-membership-for-a-user" }, "parameters": [ { "$ref": "#/components/parameters/org" }, { "$ref": "#/components/parameters/username" } ], "responses": { "204": { "description": "Response if requester is an organization member and user is a member" }, "302": { "description": "Response if requester is not an organization member", "headers": { "Location": { "example": "https://api.github.com/orgs/github/public_members/pezra", "schema": { "type": "string" } } } }, "404": { "description": "Not Found if requester is an organization member and user is not a member" } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": true, "category": "orgs", "subcategory": "members" } }, "delete": { "summary": "Remove an organization member", "description": "Removing a user from this list will remove them from all teams and they will no longer have any access to the organization's repositories.", "tags": [ "orgs" ], "operationId": "orgs/remove-member", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/orgs#remove-an-organization-member" }, "parameters": [ { "$ref": "#/components/parameters/org" }, { "$ref": "#/components/parameters/username" } ], "responses": { "204": { "description": "Response" }, "403": { "$ref": "#/components/responses/forbidden" } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": true, "category": "orgs", "subcategory": "members" } } }, "/orgs/{org}/memberships/{username}": { "get": { "summary": "Get organization membership for a user", "description": "In order to get a user's membership with an organization, the authenticated user must be an organization member. The `state` parameter in the response can be used to identify the user's membership status.", "tags": [ "orgs" ], "operationId": "orgs/get-membership-for-user", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/orgs#get-organization-membership-for-a-user" }, "parameters": [ { "$ref": "#/components/parameters/org" }, { "$ref": "#/components/parameters/username" } ], "responses": { "200": { "description": "Response", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/org-membership" }, "examples": { "response-if-user-has-an-active-admin-membership-with-organization": { "$ref": "#/components/examples/org-membership-response-if-user-has-an-active-admin-membership-with-organization" } } } } }, "404": { "$ref": "#/components/responses/not_found" }, "403": { "$ref": "#/components/responses/forbidden" } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": true, "category": "orgs", "subcategory": "members" } }, "put": { "summary": "Set organization membership for a user", "description": "Only authenticated organization owners can add a member to the organization or update the member's role.\n\n* If the authenticated user is _adding_ a member to the organization, the invited user will receive an email inviting them to the organization. The user's [membership status](https://docs.github.com/enterprise-server@3.0/rest/reference/orgs#get-organization-membership-for-a-user) will be `pending` until they accept the invitation.\n \n* Authenticated users can _update_ a user's membership by passing the `role` parameter. If the authenticated user changes a member's role to `admin`, the affected user will receive an email notifying them that they've been made an organization owner. If the authenticated user changes an owner's role to `member`, no email will be sent.\n\n**Rate limits**\n\nTo prevent abuse, the authenticated user is limited to 50 organization invitations per 24 hour period. If the organization is more than one month old or on a paid plan, the limit is 500 invitations per 24 hour period.", "tags": [ "orgs" ], "operationId": "orgs/set-membership-for-user", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/orgs#set-organization-membership-for-a-user" }, "parameters": [ { "$ref": "#/components/parameters/org" }, { "$ref": "#/components/parameters/username" } ], "requestBody": { "required": false, "content": { "application/json": { "schema": { "type": "object", "properties": { "role": { "type": "string", "description": "The role to give the user in the organization. Can be one of: \n\\* `admin` - The user will become an owner of the organization. \n\\* `member` - The user will become a non-owner member of the organization.", "enum": [ "admin", "member" ], "default": "member" } } } } } }, "responses": { "200": { "description": "Response", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/org-membership" }, "examples": { "response-if-user-already-had-membership-with-organization": { "$ref": "#/components/examples/org-membership-response-if-user-has-an-active-admin-membership-with-organization" } } } } }, "422": { "$ref": "#/components/responses/validation_failed" }, "403": { "$ref": "#/components/responses/forbidden" } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": true, "category": "orgs", "subcategory": "members" } }, "delete": { "summary": "Remove organization membership for a user", "description": "In order to remove a user's membership with an organization, the authenticated user must be an organization owner.\n\nIf the specified user is an active member of the organization, this will remove them from the organization. If the specified user has been invited to the organization, this will cancel their invitation. The specified user will receive an email notification in both cases.", "tags": [ "orgs" ], "operationId": "orgs/remove-membership-for-user", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/orgs#remove-organization-membership-for-a-user" }, "parameters": [ { "$ref": "#/components/parameters/org" }, { "$ref": "#/components/parameters/username" } ], "responses": { "204": { "description": "Response" }, "403": { "$ref": "#/components/responses/forbidden" }, "404": { "$ref": "#/components/responses/not_found" } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": true, "category": "orgs", "subcategory": "members" } } }, "/orgs/{org}/outside_collaborators": { "get": { "summary": "List outside collaborators for an organization", "description": "List all users who are outside collaborators of an organization.", "tags": [ "orgs" ], "operationId": "orgs/list-outside-collaborators", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/orgs#list-outside-collaborators-for-an-organization" }, "parameters": [ { "$ref": "#/components/parameters/org" }, { "name": "filter", "description": "Filter the list of outside collaborators. Can be one of: \n\\* `2fa_disabled`: Outside collaborators without [two-factor authentication](https://github.com/blog/1614-two-factor-authentication) enabled. \n\\* `all`: All outside collaborators.", "in": "query", "required": false, "schema": { "type": "string", "enum": [ "2fa_disabled", "all" ], "default": "all" } }, { "$ref": "#/components/parameters/per-page" }, { "$ref": "#/components/parameters/page" } ], "responses": { "200": { "description": "Response", "content": { "application/json": { "schema": { "type": "array", "items": { "$ref": "#/components/schemas/simple-user" } }, "examples": { "default": { "$ref": "#/components/examples/simple-user-items" } } } }, "headers": { "Link": { "$ref": "#/components/headers/link" } } } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": true, "category": "orgs", "subcategory": "outside-collaborators" } } }, "/orgs/{org}/outside_collaborators/{username}": { "put": { "summary": "Convert an organization member to outside collaborator", "description": "When an organization member is converted to an outside collaborator, they'll only have access to the repositories that their current team membership allows. The user will no longer be a member of the organization. For more information, see \"[Converting an organization member to an outside collaborator](https://docs.github.com/articles/converting-an-organization-member-to-an-outside-collaborator/)\".", "tags": [ "orgs" ], "operationId": "orgs/convert-member-to-outside-collaborator", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/orgs#convert-an-organization-member-to-outside-collaborator" }, "parameters": [ { "$ref": "#/components/parameters/org" }, { "$ref": "#/components/parameters/username" } ], "responses": { "202": { "description": "User is getting converted asynchronously", "content": { "application/json": { "schema": { "type": "object", "properties": { }, "additionalProperties": false } } } }, "204": { "description": "User was converted" }, "403": { "description": "Forbidden if user is the last owner of the organization or not a member of the organization" }, "404": { "$ref": "#/components/responses/not_found" } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": true, "category": "orgs", "subcategory": "outside-collaborators" } }, "delete": { "summary": "Remove outside collaborator from an organization", "description": "Removing a user from this list will remove them from all the organization's repositories.", "tags": [ "orgs" ], "operationId": "orgs/remove-outside-collaborator", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/orgs#remove-outside-collaborator-from-an-organization" }, "parameters": [ { "$ref": "#/components/parameters/org" }, { "$ref": "#/components/parameters/username" } ], "responses": { "204": { "description": "Response" }, "422": { "description": "Unprocessable Entity if user is a member of the organization", "content": { "application/json": { "schema": { "type": "object", "properties": { "message": { "type": "string" }, "documentation_url": { "type": "string" } } }, "examples": { "response-if-user-is-a-member-of-the-organization": { "value": { "message": "You cannot specify an organization member to remove as an outside collaborator.", "documentation_url": "https://docs.github.com/enterprise-server@3.0/rest/reference/orgs#remove-outside-collaborator" } } } } } } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": true, "category": "orgs", "subcategory": "outside-collaborators" } } }, "/orgs/{org}/pre-receive-hooks": { "get": { "summary": "List pre-receive hooks for an organization", "description": "List all pre-receive hooks that are enabled or testing for this organization as well as any disabled hooks that can be configured at the organization level. Globally disabled pre-receive hooks that do not allow downstream configuration are not listed.", "operationId": "enterprise-admin/list-pre-receive-hooks-for-org", "tags": [ "enterprise-admin" ], "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/enterprise-admin#list-pre-receive-hooks-for-an-organization" }, "parameters": [ { "$ref": "#/components/parameters/org" }, { "$ref": "#/components/parameters/per-page" }, { "$ref": "#/components/parameters/page" }, { "$ref": "#/components/parameters/direction" }, { "name": "sort", "description": "The sort order for the response collection.", "in": "query", "required": false, "schema": { "type": "string", "enum": [ "created", "updated", "name" ], "default": "created" } } ], "responses": { "200": { "description": "Response", "content": { "application/json": { "schema": { "type": "array", "items": { "$ref": "#/components/schemas/org-pre-receive-hook" } }, "examples": { "default": { "$ref": "#/components/examples/org-pre-receive-hook-items" } } } } } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": true, "category": "enterprise-admin", "subcategory": "org-pre-receive-hooks", "previews": [ { "required": true, "name": "eye-scream", "note": "APIs for managing pre-receive hooks are currently available for developers to preview. During the preview period, the APIs may change without advance notice.\n\nTo access the API you must provide a custom [media type](/rest/overview/media-types) in the `Accept` header:\n\n```shell\napplication/vnd.github.eye-scream-preview\n```" } ] } } }, "/orgs/{org}/pre-receive-hooks/{pre_receive_hook_id}": { "get": { "summary": "Get a pre-receive hook for an organization", "description": "", "operationId": "enterprise-admin/get-pre-receive-hook-for-org", "tags": [ "enterprise-admin" ], "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/enterprise-admin#get-a-pre-receive-hook-for-an-organization" }, "parameters": [ { "$ref": "#/components/parameters/org" }, { "$ref": "#/components/parameters/pre-receive-hook-id" } ], "responses": { "200": { "description": "Response", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/org-pre-receive-hook" }, "examples": { "default": { "$ref": "#/components/examples/org-pre-receive-hook" } } } } } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": true, "category": "enterprise-admin", "subcategory": "org-pre-receive-hooks", "previews": [ { "required": true, "name": "eye-scream", "note": "APIs for managing pre-receive hooks are currently available for developers to preview. During the preview period, the APIs may change without advance notice.\n\nTo access the API you must provide a custom [media type](/rest/overview/media-types) in the `Accept` header:\n\n```shell\napplication/vnd.github.eye-scream-preview\n```" } ] } }, "patch": { "summary": "Update pre-receive hook enforcement for an organization", "description": "For pre-receive hooks which are allowed to be configured at the org level, you can set `enforcement` and `allow_downstream_configuration`", "operationId": "enterprise-admin/update-pre-receive-hook-enforcement-for-org", "tags": [ "enterprise-admin" ], "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/enterprise-admin#update-pre-receive-hook-enforcement-for-an-organization" }, "parameters": [ { "$ref": "#/components/parameters/org" }, { "$ref": "#/components/parameters/pre-receive-hook-id" } ], "responses": { "200": { "description": "Response", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/org-pre-receive-hook" }, "examples": { "default": { "$ref": "#/components/examples/org-pre-receive-hook-2" } } } } } }, "requestBody": { "content": { "application/json": { "schema": { "type": "object", "properties": { "enforcement": { "description": "The state of enforcement for the hook on this repository.", "type": "string" }, "allow_downstream_configuration": { "description": "Whether repositories can override enforcement.", "type": "boolean" } } }, "example": { "enforcement": "enabled", "allow_downstream_configuration": false } } } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": true, "category": "enterprise-admin", "subcategory": "org-pre-receive-hooks", "previews": [ { "required": true, "name": "eye-scream", "note": "APIs for managing pre-receive hooks are currently available for developers to preview. During the preview period, the APIs may change without advance notice.\n\nTo access the API you must provide a custom [media type](/rest/overview/media-types) in the `Accept` header:\n\n```shell\napplication/vnd.github.eye-scream-preview\n```" } ] } }, "delete": { "summary": "Remove pre-receive hook enforcement for an organization", "description": "Removes any overrides for this hook at the org level for this org.", "operationId": "enterprise-admin/remove-pre-receive-hook-enforcement-for-org", "tags": [ "enterprise-admin" ], "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/enterprise-admin#remove-pre-receive-hook-enforcement-for-an-organization" }, "parameters": [ { "$ref": "#/components/parameters/org" }, { "$ref": "#/components/parameters/pre-receive-hook-id" } ], "responses": { "200": { "description": "Response", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/org-pre-receive-hook" }, "examples": { "default": { "$ref": "#/components/examples/org-pre-receive-hook" } } } } } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": true, "category": "enterprise-admin", "subcategory": "org-pre-receive-hooks", "previews": [ { "required": true, "name": "eye-scream", "note": "APIs for managing pre-receive hooks are currently available for developers to preview. During the preview period, the APIs may change without advance notice.\n\nTo access the API you must provide a custom [media type](/rest/overview/media-types) in the `Accept` header:\n\n```shell\napplication/vnd.github.eye-scream-preview\n```" } ] } } }, "/orgs/{org}/projects": { "get": { "summary": "List organization projects", "description": "Lists the projects in an organization. Returns a `404 Not Found` status if projects are disabled in the organization. If you do not have sufficient privileges to perform this action, a `401 Unauthorized` or `410 Gone` status is returned.", "tags": [ "projects" ], "operationId": "projects/list-for-org", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/projects#list-organization-projects" }, "parameters": [ { "$ref": "#/components/parameters/org" }, { "name": "state", "description": "Indicates the state of the projects to return. Can be either `open`, `closed`, or `all`.", "in": "query", "required": false, "schema": { "type": "string", "enum": [ "open", "closed", "all" ], "default": "open" } }, { "$ref": "#/components/parameters/per-page" }, { "$ref": "#/components/parameters/page" } ], "responses": { "200": { "description": "Response", "content": { "application/json": { "schema": { "type": "array", "items": { "$ref": "#/components/schemas/project" } }, "examples": { "default": { "$ref": "#/components/examples/project-items" } } } }, "headers": { "Link": { "$ref": "#/components/headers/link" } } }, "422": { "$ref": "#/components/responses/validation_failed_simple" } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": true, "category": "projects", "previews": [ { "required": true, "name": "inertia", "note": "The Projects API is currently available for developers to preview. During the preview period, the API may change without advance notice. Please see the [blog post](https://developer.github.com/changes/2016-10-27-changes-to-projects-api) for full details. To access the API during the preview period, you must provide a custom [media type](https://docs.github.com/enterprise-server@3.0/rest/overview/media-types) in the `Accept` header:\n```shell\napplication/vnd.github.inertia-preview+json\n```" } ] } }, "post": { "summary": "Create an organization project", "description": "Creates an organization project board. Returns a `404 Not Found` status if projects are disabled in the organization. If you do not have sufficient privileges to perform this action, a `401 Unauthorized` or `410 Gone` status is returned.", "tags": [ "projects" ], "operationId": "projects/create-for-org", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/projects#create-an-organization-project" }, "parameters": [ { "$ref": "#/components/parameters/org" } ], "requestBody": { "required": true, "content": { "application/json": { "schema": { "type": "object", "properties": { "name": { "type": "string", "description": "The name of the project." }, "body": { "type": "string", "description": "The description of the project." } }, "required": [ "name" ] }, "example": { "name": "Organization Roadmap", "body": "High-level roadmap for the upcoming year." } } } }, "responses": { "201": { "description": "Response", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/project" }, "examples": { "default": { "$ref": "#/components/examples/project-2" } } } } }, "401": { "$ref": "#/components/responses/requires_authentication" }, "403": { "$ref": "#/components/responses/forbidden" }, "404": { "$ref": "#/components/responses/not_found" }, "410": { "$ref": "#/components/responses/gone" }, "422": { "$ref": "#/components/responses/validation_failed_simple" } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": true, "category": "projects", "previews": [ { "required": true, "name": "inertia", "note": "The Projects API is currently available for developers to preview. During the preview period, the API may change without advance notice. Please see the [blog post](https://developer.github.com/changes/2016-10-27-changes-to-projects-api) for full details. To access the API during the preview period, you must provide a custom [media type](https://docs.github.com/enterprise-server@3.0/rest/overview/media-types) in the `Accept` header:\n```shell\napplication/vnd.github.inertia-preview+json\n```" } ] } } }, "/orgs/{org}/public_members": { "get": { "summary": "List public organization members", "description": "Members of an organization can choose to have their membership publicized or not.", "tags": [ "orgs" ], "operationId": "orgs/list-public-members", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/orgs#list-public-organization-members" }, "parameters": [ { "$ref": "#/components/parameters/org" }, { "$ref": "#/components/parameters/per-page" }, { "$ref": "#/components/parameters/page" } ], "responses": { "200": { "description": "Response", "content": { "application/json": { "schema": { "type": "array", "items": { "$ref": "#/components/schemas/simple-user" } }, "examples": { "default": { "$ref": "#/components/examples/simple-user-items" } } } }, "headers": { "Link": { "$ref": "#/components/headers/link" } } } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": true, "category": "orgs", "subcategory": "members" } } }, "/orgs/{org}/public_members/{username}": { "get": { "summary": "Check public organization membership for a user", "description": "", "tags": [ "orgs" ], "operationId": "orgs/check-public-membership-for-user", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/orgs#check-public-organization-membership-for-a-user" }, "parameters": [ { "$ref": "#/components/parameters/org" }, { "$ref": "#/components/parameters/username" } ], "responses": { "204": { "description": "Response if user is a public member" }, "404": { "description": "Not Found if user is not a public member" } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": true, "category": "orgs", "subcategory": "members" } }, "put": { "summary": "Set public organization membership for the authenticated user", "description": "The user can publicize their own membership. (A user cannot publicize the membership for another user.)\n\nNote that you'll need to set `Content-Length` to zero when calling out to this endpoint. For more information, see \"[HTTP verbs](https://docs.github.com/enterprise-server@3.0/rest/overview/resources-in-the-rest-api#http-verbs).\"", "tags": [ "orgs" ], "operationId": "orgs/set-public-membership-for-authenticated-user", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/orgs#set-public-organization-membership-for-the-authenticated-user" }, "parameters": [ { "$ref": "#/components/parameters/org" }, { "$ref": "#/components/parameters/username" } ], "responses": { "204": { "description": "Response" }, "403": { "$ref": "#/components/responses/forbidden" } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": false, "category": "orgs", "subcategory": "members" } }, "delete": { "summary": "Remove public organization membership for the authenticated user", "description": "", "tags": [ "orgs" ], "operationId": "orgs/remove-public-membership-for-authenticated-user", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/orgs#remove-public-organization-membership-for-the-authenticated-user" }, "parameters": [ { "$ref": "#/components/parameters/org" }, { "$ref": "#/components/parameters/username" } ], "responses": { "204": { "description": "Response" } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": false, "category": "orgs", "subcategory": "members" } } }, "/orgs/{org}/repos": { "get": { "summary": "List organization repositories", "description": "Lists repositories for the specified organization.", "tags": [ "repos" ], "operationId": "repos/list-for-org", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/repos#list-organization-repositories" }, "parameters": [ { "$ref": "#/components/parameters/org" }, { "name": "type", "description": "Specifies the types of repositories you want returned. Can be one of `all`, `public`, `private`, `forks`, `sources`, `member`, `internal`. Note: For GitHub AE, can be one of `all`, `private`, `forks`, `sources`, `member`, `internal`. Default: `all`. If your organization is associated with an enterprise account using GitHub Enterprise Cloud or GitHub Enterprise Server 2.20+, `type` can also be `internal`. However, the `internal` value is not yet supported when a GitHub App calls this API with an installation access token.", "in": "query", "required": false, "schema": { "type": "string", "enum": [ "all", "public", "private", "forks", "sources", "member", "internal" ] } }, { "name": "sort", "description": "Can be one of `created`, `updated`, `pushed`, `full_name`.", "in": "query", "required": false, "schema": { "type": "string", "enum": [ "created", "updated", "pushed", "full_name" ], "default": "created" } }, { "name": "direction", "description": "Can be one of `asc` or `desc`. Default: when using `full_name`: `asc`, otherwise `desc`", "in": "query", "required": false, "schema": { "type": "string", "enum": [ "asc", "desc" ] } }, { "$ref": "#/components/parameters/per-page" }, { "$ref": "#/components/parameters/page" } ], "responses": { "200": { "description": "Response", "content": { "application/json": { "schema": { "type": "array", "items": { "$ref": "#/components/schemas/minimal-repository" } }, "examples": { "default": { "$ref": "#/components/examples/minimal-repository-items" } } } }, "headers": { "Link": { "$ref": "#/components/headers/link" } } } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": true, "category": "repos", "previews": [ { "required": false, "name": "nebula", "note": "You can set the visibility of a repository using the new `visibility` parameter in the [Repositories API](https://docs.github.com/enterprise-server@3.0/rest/reference/repos/), and get a repository's visibility with a new response key. For more information, see the [blog post](https://developer.github.com/changes/2019-12-03-internal-visibility-changes/).\n\nTo access repository visibility during the preview period, you must provide a custom [media type](https://docs.github.com/enterprise-server@3.0/rest/overview/media-types) in the `Accept` header:\n```shell\napplication/vnd.github.nebula-preview+json\n```" }, { "required": false, "name": "baptiste", "note": "The `is_template` and `template_repository` keys are currently available for developer to preview. See [Create a repository using a template](https://docs.github.com/enterprise-server@3.0/rest/reference/repos#create-a-repository-using-a-template) to learn how to create template repositories. To access these new response keys during the preview period, you must provide a custom [media type](https://docs.github.com/enterprise-server@3.0/rest/overview/media-types) in the `Accept` header:\n\n```shell\napplication/vnd.github.baptiste-preview+json\n```" } ] } }, "post": { "summary": "Create an organization repository", "description": "Creates a new repository in the specified organization. The authenticated user must be a member of the organization.\n\n**OAuth scope requirements**\n\nWhen using [OAuth](https://docs.github.com/enterprise-server@3.0/apps/building-oauth-apps/understanding-scopes-for-oauth-apps/), authorizations must include:\n\n* `public_repo` scope or `repo` scope to create a public repository. Note: For GitHub AE, use `repo` scope to create an internal repository.\n* `repo` scope to create a private repository", "tags": [ "repos" ], "operationId": "repos/create-in-org", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/repos#create-an-organization-repository" }, "parameters": [ { "$ref": "#/components/parameters/org" } ], "requestBody": { "required": true, "content": { "application/json": { "schema": { "type": "object", "properties": { "name": { "type": "string", "description": "The name of the repository." }, "description": { "type": "string", "description": "A short description of the repository." }, "homepage": { "type": "string", "description": "A URL with more information about the repository." }, "private": { "type": "boolean", "description": "Whether the repository is private.", "default": false }, "visibility": { "type": "string", "description": "Can be `public` or `private`. If your organization is associated with an enterprise account using GitHub Enterprise Cloud or GitHub Enterprise Server 2.20+, `visibility` can also be `internal`. Note: For GitHub Enterprise Server and GitHub AE, this endpoint will only list repositories available to all users on the enterprise. For more information, see \"[Creating an internal repository](https://docs.github.com/en/github/creating-cloning-and-archiving-repositories/about-repository-visibility#about-internal-repositories)\" in the GitHub Help documentation. \nThe `visibility` parameter overrides the `private` parameter when you use both parameters with the `nebula-preview` preview header.", "enum": [ "public", "private", "internal" ] }, "has_issues": { "type": "boolean", "description": "Either `true` to enable issues for this repository or `false` to disable them.", "default": true }, "has_projects": { "type": "boolean", "description": "Either `true` to enable projects for this repository or `false` to disable them. **Note:** If you're creating a repository in an organization that has disabled repository projects, the default is `false`, and if you pass `true`, the API returns an error.", "default": true }, "has_wiki": { "type": "boolean", "description": "Either `true` to enable the wiki for this repository or `false` to disable it.", "default": true }, "is_template": { "type": "boolean", "description": "Either `true` to make this repo available as a template repository or `false` to prevent it.", "default": false }, "team_id": { "type": "integer", "description": "The id of the team that will be granted access to this repository. This is only valid when creating a repository in an organization." }, "auto_init": { "type": "boolean", "description": "Pass `true` to create an initial commit with empty README.", "default": false }, "gitignore_template": { "type": "string", "description": "Desired language or platform [.gitignore template](https://github.com/github/gitignore) to apply. Use the name of the template without the extension. For example, \"Haskell\"." }, "license_template": { "type": "string", "description": "Choose an [open source license template](https://choosealicense.com/) that best suits your needs, and then use the [license keyword](https://docs.github.com/articles/licensing-a-repository/#searching-github-by-license-type) as the `license_template` string. For example, \"mit\" or \"mpl-2.0\"." }, "allow_squash_merge": { "type": "boolean", "description": "Either `true` to allow squash-merging pull requests, or `false` to prevent squash-merging.", "default": true }, "allow_merge_commit": { "type": "boolean", "description": "Either `true` to allow merging pull requests with a merge commit, or `false` to prevent merging pull requests with merge commits.", "default": true }, "allow_rebase_merge": { "type": "boolean", "description": "Either `true` to allow rebase-merging pull requests, or `false` to prevent rebase-merging.", "default": true }, "delete_branch_on_merge": { "type": "boolean", "description": "Either `true` to allow automatically deleting head branches when pull requests are merged, or `false` to prevent automatic deletion.", "default": false } }, "required": [ "name" ] }, "example": { "name": "Hello-World", "description": "This is your first repository", "homepage": "https://github.com", "private": false, "has_issues": true, "has_projects": true, "has_wiki": true } } } }, "responses": { "201": { "description": "Response", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/repository" }, "examples": { "default": { "$ref": "#/components/examples/repository" } } } }, "headers": { "Location": { "example": "https://api.github.com/repos/octocat/Hello-World", "schema": { "type": "string" } } } }, "403": { "$ref": "#/components/responses/forbidden" }, "422": { "$ref": "#/components/responses/validation_failed" } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": true, "category": "repos", "previews": [ { "required": false, "name": "nebula", "note": "You can set the visibility of a repository using the new `visibility` parameter in the [Repositories API](https://docs.github.com/enterprise-server@3.0/rest/reference/repos/), and get a repository's visibility with a new response key. For more information, see the [blog post](https://developer.github.com/changes/2019-12-03-internal-visibility-changes/).\n\nTo access repository visibility during the preview period, you must provide a custom [media type](https://docs.github.com/enterprise-server@3.0/rest/overview/media-types) in the `Accept` header:\n```shell\napplication/vnd.github.nebula-preview+json\n```" }, { "required": false, "name": "baptiste", "note": "The `is_template` and `template_repository` keys are currently available for developer to preview. See [Create a repository using a template](https://docs.github.com/enterprise-server@3.0/rest/reference/repos#create-a-repository-using-a-template) to learn how to create template repositories. To access these new response keys during the preview period, you must provide a custom [media type](https://docs.github.com/enterprise-server@3.0/rest/overview/media-types) in the `Accept` header:\n\n```shell\napplication/vnd.github.baptiste-preview+json\n```" } ] } } }, "/orgs/{org}/teams": { "get": { "summary": "List teams", "description": "Lists all teams in an organization that are visible to the authenticated user.", "tags": [ "teams" ], "operationId": "teams/list", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/teams#list-teams" }, "parameters": [ { "$ref": "#/components/parameters/org" }, { "$ref": "#/components/parameters/per-page" }, { "$ref": "#/components/parameters/page" } ], "responses": { "200": { "description": "Response", "content": { "application/json": { "schema": { "type": "array", "items": { "$ref": "#/components/schemas/team" } }, "examples": { "default": { "$ref": "#/components/examples/team-items" } } } }, "headers": { "Link": { "$ref": "#/components/headers/link" } } }, "403": { "$ref": "#/components/responses/forbidden" } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": true, "category": "teams", "subcategory": null } }, "post": { "summary": "Create a team", "description": "To create a team, the authenticated user must be a member or owner of `{org}`. By default, organization members can create teams. Organization owners can limit team creation to organization owners. For more information, see \"[Setting team creation permissions](https://docs.github.com/en/articles/setting-team-creation-permissions-in-your-organization).\"\n\nWhen you create a new team, you automatically become a team maintainer without explicitly adding yourself to the optional array of `maintainers`. For more information, see \"[About teams](https://docs.github.com/en/github/setting-up-and-managing-organizations-and-teams/about-teams)\".", "tags": [ "teams" ], "operationId": "teams/create", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/teams#create-a-team" }, "parameters": [ { "$ref": "#/components/parameters/org" } ], "requestBody": { "required": true, "content": { "application/json": { "schema": { "type": "object", "properties": { "name": { "type": "string", "description": "The name of the team." }, "description": { "type": "string", "description": "The description of the team." }, "maintainers": { "type": "array", "description": "List GitHub IDs for organization members who will become team maintainers.", "items": { "type": "string" } }, "repo_names": { "type": "array", "description": "The full name (e.g., \"organization-name/repository-name\") of repositories to add the team to.", "items": { "type": "string" } }, "privacy": { "type": "string", "description": "The level of privacy this team should have. The options are: \n**For a non-nested team:** \n\\* `secret` - only visible to organization owners and members of this team. \n\\* `closed` - visible to all members of this organization. \nDefault: `secret` \n**For a parent or child team:** \n\\* `closed` - visible to all members of this organization. \nDefault for child team: `closed`", "enum": [ "secret", "closed" ] }, "permission": { "type": "string", "description": "**Deprecated**. The permission that new repositories will be added to the team with when none is specified. Can be one of: \n\\* `pull` - team members can pull, but not push to or administer newly-added repositories. \n\\* `push` - team members can pull and push, but not administer newly-added repositories.", "enum": [ "pull", "push" ], "default": "pull" }, "parent_team_id": { "type": "integer", "description": "The ID of a team to set as the parent team." }, "ldap_dn": { "type": "string", "description": "The [distinguished name](https://www.ldap.com/ldap-dns-and-rdns) (DN) of the LDAP entry to map to a team. LDAP synchronization must be enabled to map LDAP entries to a team. Use the \"[Update LDAP mapping for a team](https://docs.github.com/enterprise-server@3.0/rest/reference/enterprise-admin#update-ldap-mapping-for-a-team)\" endpoint to change the LDAP DN. For more information, see \"[Using LDAP](https://docs.github.com/enterprise-server@3.0/admin/identity-and-access-management/authenticating-users-for-your-github-enterprise-server-instance/using-ldap#enabling-ldap-sync).\"" } }, "required": [ "name" ] }, "example": { "name": "Justice League", "description": "A great team", "permission": "push", "privacy": "closed" } } } }, "responses": { "201": { "description": "Response", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/team-full" }, "examples": { "default": { "$ref": "#/components/examples/team-full" } } } } }, "422": { "$ref": "#/components/responses/validation_failed" }, "403": { "$ref": "#/components/responses/forbidden" } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": true, "category": "teams", "subcategory": null } } }, "/orgs/{org}/teams/{team_slug}": { "get": { "summary": "Get a team by name", "description": "Gets a team using the team's `slug`. GitHub Enterprise Server generates the `slug` from the team `name`.\n\n**Note:** You can also specify a team by `org_id` and `team_id` using the route `GET /organizations/{org_id}/team/{team_id}`.", "tags": [ "teams" ], "operationId": "teams/get-by-name", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/teams#get-a-team-by-name" }, "parameters": [ { "$ref": "#/components/parameters/org" }, { "$ref": "#/components/parameters/team-slug" } ], "responses": { "200": { "description": "Response", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/team-full" }, "examples": { "default": { "$ref": "#/components/examples/team-full" } } } } }, "404": { "$ref": "#/components/responses/not_found" } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": true, "category": "teams", "subcategory": null } }, "patch": { "summary": "Update a team", "description": "To edit a team, the authenticated user must either be an organization owner or a team maintainer.\n\n**Note:** You can also specify a team by `org_id` and `team_id` using the route `PATCH /organizations/{org_id}/team/{team_id}`.", "tags": [ "teams" ], "operationId": "teams/update-in-org", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/teams#update-a-team" }, "parameters": [ { "$ref": "#/components/parameters/org" }, { "$ref": "#/components/parameters/team-slug" } ], "requestBody": { "required": false, "content": { "application/json": { "schema": { "type": "object", "properties": { "name": { "type": "string", "description": "The name of the team." }, "description": { "type": "string", "description": "The description of the team." }, "privacy": { "type": "string", "description": "The level of privacy this team should have. Editing teams without specifying this parameter leaves `privacy` intact. When a team is nested, the `privacy` for parent teams cannot be `secret`. The options are: \n**For a non-nested team:** \n\\* `secret` - only visible to organization owners and members of this team. \n\\* `closed` - visible to all members of this organization. \n**For a parent or child team:** \n\\* `closed` - visible to all members of this organization.", "enum": [ "secret", "closed" ] }, "permission": { "type": "string", "description": "**Deprecated**. The permission that new repositories will be added to the team with when none is specified. Can be one of: \n\\* `pull` - team members can pull, but not push to or administer newly-added repositories. \n\\* `push` - team members can pull and push, but not administer newly-added repositories. \n\\* `admin` - team members can pull, push and administer newly-added repositories.", "enum": [ "pull", "push", "admin" ], "default": "pull" }, "parent_team_id": { "type": [ "integer", "null" ], "description": "The ID of a team to set as the parent team." } } }, "example": { "name": "new team name", "description": "new team description", "privacy": "closed" } } } }, "responses": { "201": { "description": "Response", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/team-full" }, "examples": { "default": { "$ref": "#/components/examples/team-full" } } } } } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": true, "category": "teams", "subcategory": null } }, "delete": { "summary": "Delete a team", "description": "To delete a team, the authenticated user must be an organization owner or team maintainer.\n\nIf you are an organization owner, deleting a parent team will delete all of its child teams as well.\n\n**Note:** You can also specify a team by `org_id` and `team_id` using the route `DELETE /organizations/{org_id}/team/{team_id}`.", "tags": [ "teams" ], "operationId": "teams/delete-in-org", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/teams#delete-a-team" }, "parameters": [ { "$ref": "#/components/parameters/org" }, { "$ref": "#/components/parameters/team-slug" } ], "responses": { "204": { "description": "Response" } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": true, "category": "teams", "subcategory": null } } }, "/orgs/{org}/teams/{team_slug}/discussions": { "get": { "summary": "List discussions", "description": "List all discussions on a team's page. OAuth access tokens require the `read:discussion` [scope](https://docs.github.com/enterprise-server@3.0/apps/building-oauth-apps/understanding-scopes-for-oauth-apps/).\n\n**Note:** You can also specify a team by `org_id` and `team_id` using the route `GET /organizations/{org_id}/team/{team_id}/discussions`.", "tags": [ "teams" ], "operationId": "teams/list-discussions-in-org", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/teams#list-discussions" }, "parameters": [ { "$ref": "#/components/parameters/org" }, { "$ref": "#/components/parameters/team-slug" }, { "$ref": "#/components/parameters/direction" }, { "$ref": "#/components/parameters/per-page" }, { "$ref": "#/components/parameters/page" }, { "name": "pinned", "in": "query", "required": false, "description": "Pinned discussions only filter", "schema": { "type": "string" } } ], "responses": { "200": { "description": "Response", "content": { "application/json": { "schema": { "type": "array", "items": { "$ref": "#/components/schemas/team-discussion" } }, "examples": { "default": { "$ref": "#/components/examples/team-discussion-items" } } } }, "headers": { "Link": { "$ref": "#/components/headers/link" } } } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": true, "category": "teams", "subcategory": "discussions", "previews": [ { "required": false, "name": "squirrel-girl", "note": "An additional `reactions` object in the issue comment payload is currently available for developers to preview. During the preview period, the APIs may change without advance notice. Please see the [blog post](https://developer.github.com/changes/2016-05-12-reactions-api-preview) for full details.\n\nTo access the API you must provide a custom [media type](https://docs.github.com/enterprise-server@3.0/rest/overview/media-types) in the `Accept` header:\n```shell\napplication/vnd.github.squirrel-girl-preview\n```\nThe `reactions` key will have the following payload where `url` can be used to construct the API location for [listing and creating](https://docs.github.com/enterprise-server@3.0/rest/reference/reactions) reactions." } ] } }, "post": { "summary": "Create a discussion", "description": "Creates a new discussion post on a team's page. OAuth access tokens require the `write:discussion` [scope](https://docs.github.com/enterprise-server@3.0/apps/building-oauth-apps/understanding-scopes-for-oauth-apps/).\n\nThis endpoint triggers [notifications](https://docs.github.com/en/github/managing-subscriptions-and-notifications-on-github/about-notifications). Creating content too quickly using this endpoint may result in secondary rate limiting. See \"[Secondary rate limits](https://docs.github.com/enterprise-server@3.0/rest/overview/resources-in-the-rest-api#secondary-rate-limits)\" and \"[Dealing with secondary rate limits](https://docs.github.com/enterprise-server@3.0/rest/guides/best-practices-for-integrators#dealing-with-secondary-rate-limits)\" for details.\n\n**Note:** You can also specify a team by `org_id` and `team_id` using the route `POST /organizations/{org_id}/team/{team_id}/discussions`.", "tags": [ "teams" ], "operationId": "teams/create-discussion-in-org", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/teams#create-a-discussion" }, "parameters": [ { "$ref": "#/components/parameters/org" }, { "$ref": "#/components/parameters/team-slug" } ], "requestBody": { "required": true, "content": { "application/json": { "schema": { "type": "object", "properties": { "title": { "type": "string", "description": "The discussion post's title." }, "body": { "type": "string", "description": "The discussion post's body text." }, "private": { "type": "boolean", "description": "Private posts are only visible to team members, organization owners, and team maintainers. Public posts are visible to all members of the organization. Set to `true` to create a private post.", "default": false } }, "required": [ "title", "body" ] }, "example": { "title": "Our first team post", "body": "Hi! This is an area for us to collaborate as a team." } } } }, "responses": { "201": { "description": "Response", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/team-discussion" }, "examples": { "default": { "$ref": "#/components/examples/team-discussion" } } } } } }, "x-github": { "triggersNotification": true, "githubCloudOnly": false, "enabledForGitHubApps": true, "category": "teams", "subcategory": "discussions", "previews": [ { "required": false, "name": "squirrel-girl", "note": "An additional `reactions` object in the issue comment payload is currently available for developers to preview. During the preview period, the APIs may change without advance notice. Please see the [blog post](https://developer.github.com/changes/2016-05-12-reactions-api-preview) for full details.\n\nTo access the API you must provide a custom [media type](https://docs.github.com/enterprise-server@3.0/rest/overview/media-types) in the `Accept` header:\n```shell\napplication/vnd.github.squirrel-girl-preview\n```\nThe `reactions` key will have the following payload where `url` can be used to construct the API location for [listing and creating](https://docs.github.com/enterprise-server@3.0/rest/reference/reactions) reactions." } ] } } }, "/orgs/{org}/teams/{team_slug}/discussions/{discussion_number}": { "get": { "summary": "Get a discussion", "description": "Get a specific discussion on a team's page. OAuth access tokens require the `read:discussion` [scope](https://docs.github.com/enterprise-server@3.0/apps/building-oauth-apps/understanding-scopes-for-oauth-apps/).\n\n**Note:** You can also specify a team by `org_id` and `team_id` using the route `GET /organizations/{org_id}/team/{team_id}/discussions/{discussion_number}`.", "tags": [ "teams" ], "operationId": "teams/get-discussion-in-org", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/teams#get-a-discussion" }, "parameters": [ { "$ref": "#/components/parameters/org" }, { "$ref": "#/components/parameters/team-slug" }, { "$ref": "#/components/parameters/discussion-number" } ], "responses": { "200": { "description": "Response", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/team-discussion" }, "examples": { "default": { "$ref": "#/components/examples/team-discussion" } } } } } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": true, "category": "teams", "subcategory": "discussions", "previews": [ { "required": false, "name": "squirrel-girl", "note": "An additional `reactions` object in the issue comment payload is currently available for developers to preview. During the preview period, the APIs may change without advance notice. Please see the [blog post](https://developer.github.com/changes/2016-05-12-reactions-api-preview) for full details.\n\nTo access the API you must provide a custom [media type](https://docs.github.com/enterprise-server@3.0/rest/overview/media-types) in the `Accept` header:\n```shell\napplication/vnd.github.squirrel-girl-preview\n```\nThe `reactions` key will have the following payload where `url` can be used to construct the API location for [listing and creating](https://docs.github.com/enterprise-server@3.0/rest/reference/reactions) reactions." } ] } }, "patch": { "summary": "Update a discussion", "description": "Edits the title and body text of a discussion post. Only the parameters you provide are updated. OAuth access tokens require the `write:discussion` [scope](https://docs.github.com/enterprise-server@3.0/apps/building-oauth-apps/understanding-scopes-for-oauth-apps/).\n\n**Note:** You can also specify a team by `org_id` and `team_id` using the route `PATCH /organizations/{org_id}/team/{team_id}/discussions/{discussion_number}`.", "tags": [ "teams" ], "operationId": "teams/update-discussion-in-org", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/teams#update-a-discussion" }, "parameters": [ { "$ref": "#/components/parameters/org" }, { "$ref": "#/components/parameters/team-slug" }, { "$ref": "#/components/parameters/discussion-number" } ], "requestBody": { "required": false, "content": { "application/json": { "schema": { "type": "object", "properties": { "title": { "type": "string", "description": "The discussion post's title." }, "body": { "type": "string", "description": "The discussion post's body text." } } }, "example": { "title": "Welcome to our first team post" } } } }, "responses": { "200": { "description": "Response", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/team-discussion" }, "examples": { "default": { "$ref": "#/components/examples/team-discussion-2" } } } } } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": true, "category": "teams", "subcategory": "discussions", "previews": [ { "required": false, "name": "squirrel-girl", "note": "An additional `reactions` object in the issue comment payload is currently available for developers to preview. During the preview period, the APIs may change without advance notice. Please see the [blog post](https://developer.github.com/changes/2016-05-12-reactions-api-preview) for full details.\n\nTo access the API you must provide a custom [media type](https://docs.github.com/enterprise-server@3.0/rest/overview/media-types) in the `Accept` header:\n```shell\napplication/vnd.github.squirrel-girl-preview\n```\nThe `reactions` key will have the following payload where `url` can be used to construct the API location for [listing and creating](https://docs.github.com/enterprise-server@3.0/rest/reference/reactions) reactions." } ] } }, "delete": { "summary": "Delete a discussion", "description": "Delete a discussion from a team's page. OAuth access tokens require the `write:discussion` [scope](https://docs.github.com/enterprise-server@3.0/apps/building-oauth-apps/understanding-scopes-for-oauth-apps/).\n\n**Note:** You can also specify a team by `org_id` and `team_id` using the route `DELETE /organizations/{org_id}/team/{team_id}/discussions/{discussion_number}`.", "tags": [ "teams" ], "operationId": "teams/delete-discussion-in-org", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/teams#delete-a-discussion" }, "parameters": [ { "$ref": "#/components/parameters/org" }, { "$ref": "#/components/parameters/team-slug" }, { "$ref": "#/components/parameters/discussion-number" } ], "responses": { "204": { "description": "Response" } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": true, "category": "teams", "subcategory": "discussions" } } }, "/orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments": { "get": { "summary": "List discussion comments", "description": "List all comments on a team discussion. OAuth access tokens require the `read:discussion` [scope](https://docs.github.com/enterprise-server@3.0/apps/building-oauth-apps/understanding-scopes-for-oauth-apps/).\n\n**Note:** You can also specify a team by `org_id` and `team_id` using the route `GET /organizations/{org_id}/team/{team_id}/discussions/{discussion_number}/comments`.", "tags": [ "teams" ], "operationId": "teams/list-discussion-comments-in-org", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/teams#list-discussion-comments" }, "parameters": [ { "$ref": "#/components/parameters/org" }, { "$ref": "#/components/parameters/team-slug" }, { "$ref": "#/components/parameters/discussion-number" }, { "$ref": "#/components/parameters/direction" }, { "$ref": "#/components/parameters/per-page" }, { "$ref": "#/components/parameters/page" } ], "responses": { "200": { "description": "Response", "content": { "application/json": { "schema": { "type": "array", "items": { "$ref": "#/components/schemas/team-discussion-comment" } }, "examples": { "default": { "$ref": "#/components/examples/team-discussion-comment-items" } } } }, "headers": { "Link": { "$ref": "#/components/headers/link" } } } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": true, "category": "teams", "subcategory": "discussion-comments", "previews": [ { "required": false, "name": "squirrel-girl", "note": "An additional `reactions` object in the issue comment payload is currently available for developers to preview. During the preview period, the APIs may change without advance notice. Please see the [blog post](https://developer.github.com/changes/2016-05-12-reactions-api-preview) for full details.\n\nTo access the API you must provide a custom [media type](https://docs.github.com/enterprise-server@3.0/rest/overview/media-types) in the `Accept` header:\n```shell\napplication/vnd.github.squirrel-girl-preview\n```\nThe `reactions` key will have the following payload where `url` can be used to construct the API location for [listing and creating](https://docs.github.com/enterprise-server@3.0/rest/reference/reactions) reactions." } ] } }, "post": { "summary": "Create a discussion comment", "description": "Creates a new comment on a team discussion. OAuth access tokens require the `write:discussion` [scope](https://docs.github.com/enterprise-server@3.0/apps/building-oauth-apps/understanding-scopes-for-oauth-apps/).\n\nThis endpoint triggers [notifications](https://docs.github.com/en/github/managing-subscriptions-and-notifications-on-github/about-notifications). Creating content too quickly using this endpoint may result in secondary rate limiting. See \"[Secondary rate limits](https://docs.github.com/enterprise-server@3.0/rest/overview/resources-in-the-rest-api#secondary-rate-limits)\" and \"[Dealing with secondary rate limits](https://docs.github.com/enterprise-server@3.0/rest/guides/best-practices-for-integrators#dealing-with-secondary-rate-limits)\" for details.\n\n**Note:** You can also specify a team by `org_id` and `team_id` using the route `POST /organizations/{org_id}/team/{team_id}/discussions/{discussion_number}/comments`.", "tags": [ "teams" ], "operationId": "teams/create-discussion-comment-in-org", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/teams#create-a-discussion-comment" }, "parameters": [ { "$ref": "#/components/parameters/org" }, { "$ref": "#/components/parameters/team-slug" }, { "$ref": "#/components/parameters/discussion-number" } ], "requestBody": { "required": true, "content": { "application/json": { "schema": { "type": "object", "properties": { "body": { "type": "string", "description": "The discussion comment's body text." } }, "required": [ "body" ] }, "example": { "body": "Do you like apples?" } } } }, "responses": { "201": { "description": "Response", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/team-discussion-comment" }, "examples": { "default": { "$ref": "#/components/examples/team-discussion-comment" } } } } } }, "x-github": { "triggersNotification": true, "githubCloudOnly": false, "enabledForGitHubApps": true, "category": "teams", "subcategory": "discussion-comments", "previews": [ { "required": false, "name": "squirrel-girl", "note": "An additional `reactions` object in the issue comment payload is currently available for developers to preview. During the preview period, the APIs may change without advance notice. Please see the [blog post](https://developer.github.com/changes/2016-05-12-reactions-api-preview) for full details.\n\nTo access the API you must provide a custom [media type](https://docs.github.com/enterprise-server@3.0/rest/overview/media-types) in the `Accept` header:\n```shell\napplication/vnd.github.squirrel-girl-preview\n```\nThe `reactions` key will have the following payload where `url` can be used to construct the API location for [listing and creating](https://docs.github.com/enterprise-server@3.0/rest/reference/reactions) reactions." } ] } } }, "/orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments/{comment_number}": { "get": { "summary": "Get a discussion comment", "description": "Get a specific comment on a team discussion. OAuth access tokens require the `read:discussion` [scope](https://docs.github.com/enterprise-server@3.0/apps/building-oauth-apps/understanding-scopes-for-oauth-apps/).\n\n**Note:** You can also specify a team by `org_id` and `team_id` using the route `GET /organizations/{org_id}/team/{team_id}/discussions/{discussion_number}/comments/{comment_number}`.", "tags": [ "teams" ], "operationId": "teams/get-discussion-comment-in-org", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/teams#get-a-discussion-comment" }, "parameters": [ { "$ref": "#/components/parameters/org" }, { "$ref": "#/components/parameters/team-slug" }, { "$ref": "#/components/parameters/discussion-number" }, { "$ref": "#/components/parameters/comment-number" } ], "responses": { "200": { "description": "Response", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/team-discussion-comment" }, "examples": { "default": { "$ref": "#/components/examples/team-discussion-comment" } } } } } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": true, "category": "teams", "subcategory": "discussion-comments", "previews": [ { "required": false, "name": "squirrel-girl", "note": "An additional `reactions` object in the issue comment payload is currently available for developers to preview. During the preview period, the APIs may change without advance notice. Please see the [blog post](https://developer.github.com/changes/2016-05-12-reactions-api-preview) for full details.\n\nTo access the API you must provide a custom [media type](https://docs.github.com/enterprise-server@3.0/rest/overview/media-types) in the `Accept` header:\n```shell\napplication/vnd.github.squirrel-girl-preview\n```\nThe `reactions` key will have the following payload where `url` can be used to construct the API location for [listing and creating](https://docs.github.com/enterprise-server@3.0/rest/reference/reactions) reactions." } ] } }, "patch": { "summary": "Update a discussion comment", "description": "Edits the body text of a discussion comment. OAuth access tokens require the `write:discussion` [scope](https://docs.github.com/enterprise-server@3.0/apps/building-oauth-apps/understanding-scopes-for-oauth-apps/).\n\n**Note:** You can also specify a team by `org_id` and `team_id` using the route `PATCH /organizations/{org_id}/team/{team_id}/discussions/{discussion_number}/comments/{comment_number}`.", "tags": [ "teams" ], "operationId": "teams/update-discussion-comment-in-org", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/teams#update-a-discussion-comment" }, "parameters": [ { "$ref": "#/components/parameters/org" }, { "$ref": "#/components/parameters/team-slug" }, { "$ref": "#/components/parameters/discussion-number" }, { "$ref": "#/components/parameters/comment-number" } ], "requestBody": { "required": true, "content": { "application/json": { "schema": { "type": "object", "properties": { "body": { "type": "string", "description": "The discussion comment's body text." } }, "required": [ "body" ] }, "example": { "body": "Do you like pineapples?" } } } }, "responses": { "200": { "description": "Response", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/team-discussion-comment" }, "examples": { "default": { "$ref": "#/components/examples/team-discussion-comment-2" } } } } } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": true, "category": "teams", "subcategory": "discussion-comments", "previews": [ { "required": false, "name": "squirrel-girl", "note": "An additional `reactions` object in the issue comment payload is currently available for developers to preview. During the preview period, the APIs may change without advance notice. Please see the [blog post](https://developer.github.com/changes/2016-05-12-reactions-api-preview) for full details.\n\nTo access the API you must provide a custom [media type](https://docs.github.com/enterprise-server@3.0/rest/overview/media-types) in the `Accept` header:\n```shell\napplication/vnd.github.squirrel-girl-preview\n```\nThe `reactions` key will have the following payload where `url` can be used to construct the API location for [listing and creating](https://docs.github.com/enterprise-server@3.0/rest/reference/reactions) reactions." } ] } }, "delete": { "summary": "Delete a discussion comment", "description": "Deletes a comment on a team discussion. OAuth access tokens require the `write:discussion` [scope](https://docs.github.com/enterprise-server@3.0/apps/building-oauth-apps/understanding-scopes-for-oauth-apps/).\n\n**Note:** You can also specify a team by `org_id` and `team_id` using the route `DELETE /organizations/{org_id}/team/{team_id}/discussions/{discussion_number}/comments/{comment_number}`.", "tags": [ "teams" ], "operationId": "teams/delete-discussion-comment-in-org", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/teams#delete-a-discussion-comment" }, "parameters": [ { "$ref": "#/components/parameters/org" }, { "$ref": "#/components/parameters/team-slug" }, { "$ref": "#/components/parameters/discussion-number" }, { "$ref": "#/components/parameters/comment-number" } ], "responses": { "204": { "description": "Response" } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": true, "category": "teams", "subcategory": "discussion-comments" } } }, "/orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments/{comment_number}/reactions": { "get": { "summary": "List reactions for a team discussion comment", "description": "List the reactions to a [team discussion comment](https://docs.github.com/enterprise-server@3.0/rest/reference/teams#discussion-comments/). OAuth access tokens require the `read:discussion` [scope](https://docs.github.com/enterprise-server@3.0/apps/building-oauth-apps/understanding-scopes-for-oauth-apps/).\n\n**Note:** You can also specify a team by `org_id` and `team_id` using the route `GET /organizations/:org_id/team/:team_id/discussions/:discussion_number/comments/:comment_number/reactions`.", "tags": [ "reactions" ], "operationId": "reactions/list-for-team-discussion-comment-in-org", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/reactions#list-reactions-for-a-team-discussion-comment" }, "parameters": [ { "$ref": "#/components/parameters/org" }, { "$ref": "#/components/parameters/team-slug" }, { "$ref": "#/components/parameters/discussion-number" }, { "$ref": "#/components/parameters/comment-number" }, { "name": "content", "description": "Returns a single [reaction type](https://docs.github.com/enterprise-server@3.0/rest/reference/reactions#reaction-types). Omit this parameter to list all reactions to a team discussion comment.", "in": "query", "required": false, "schema": { "type": "string", "enum": [ "+1", "-1", "laugh", "confused", "heart", "hooray", "rocket", "eyes" ] } }, { "$ref": "#/components/parameters/per-page" }, { "$ref": "#/components/parameters/page" } ], "responses": { "200": { "description": "Response", "content": { "application/json": { "schema": { "type": "array", "items": { "$ref": "#/components/schemas/reaction" } }, "examples": { "default": { "$ref": "#/components/examples/reaction-items" } } } }, "headers": { "Link": { "$ref": "#/components/headers/link" } } } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": true, "category": "reactions", "previews": [ { "required": true, "name": "squirrel-girl", "note": "An additional `reactions` object in the issue comment payload is currently available for developers to preview. During the preview period, the APIs may change without advance notice. Please see the [blog post](https://developer.github.com/changes/2016-05-12-reactions-api-preview) for full details.\n\nTo access the API you must provide a custom [media type](https://docs.github.com/enterprise-server@3.0/rest/overview/media-types) in the `Accept` header:\n```shell\napplication/vnd.github.squirrel-girl-preview\n```\nThe `reactions` key will have the following payload where `url` can be used to construct the API location for [listing and creating](https://docs.github.com/enterprise-server@3.0/rest/reference/reactions) reactions." } ] } }, "post": { "summary": "Create reaction for a team discussion comment", "description": "Create a reaction to a [team discussion comment](https://docs.github.com/enterprise-server@3.0/rest/reference/teams#discussion-comments). OAuth access tokens require the `write:discussion` [scope](https://docs.github.com/enterprise-server@3.0/apps/building-oauth-apps/understanding-scopes-for-oauth-apps/). A response with an HTTP `200` status means that you already added the reaction type to this team discussion comment.\n\n**Note:** You can also specify a team by `org_id` and `team_id` using the route `POST /organizations/:org_id/team/:team_id/discussions/:discussion_number/comments/:comment_number/reactions`.", "tags": [ "reactions" ], "operationId": "reactions/create-for-team-discussion-comment-in-org", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/reactions#create-reaction-for-a-team-discussion-comment" }, "parameters": [ { "$ref": "#/components/parameters/org" }, { "$ref": "#/components/parameters/team-slug" }, { "$ref": "#/components/parameters/discussion-number" }, { "$ref": "#/components/parameters/comment-number" } ], "requestBody": { "required": true, "content": { "application/json": { "schema": { "type": "object", "properties": { "content": { "type": "string", "description": "The [reaction type](https://docs.github.com/enterprise-server@3.0/rest/reference/reactions#reaction-types) to add to the team discussion comment.", "enum": [ "+1", "-1", "laugh", "confused", "heart", "hooray", "rocket", "eyes" ] } }, "required": [ "content" ] }, "example": { "content": "heart" } } } }, "responses": { "200": { "description": "Response", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/reaction" }, "examples": { "default": { "$ref": "#/components/examples/reaction" } } } } }, "201": { "description": "Response", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/reaction" }, "examples": { "default": { "$ref": "#/components/examples/reaction" } } } } } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": true, "category": "reactions", "previews": [ { "required": true, "name": "squirrel-girl", "note": "An additional `reactions` object in the issue comment payload is currently available for developers to preview. During the preview period, the APIs may change without advance notice. Please see the [blog post](https://developer.github.com/changes/2016-05-12-reactions-api-preview) for full details.\n\nTo access the API you must provide a custom [media type](https://docs.github.com/enterprise-server@3.0/rest/overview/media-types) in the `Accept` header:\n```shell\napplication/vnd.github.squirrel-girl-preview\n```\nThe `reactions` key will have the following payload where `url` can be used to construct the API location for [listing and creating](https://docs.github.com/enterprise-server@3.0/rest/reference/reactions) reactions." } ] } } }, "/orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments/{comment_number}/reactions/{reaction_id}": { "delete": { "summary": "Delete team discussion comment reaction", "description": "**Note:** You can also specify a team or organization with `team_id` and `org_id` using the route `DELETE /organizations/:org_id/team/:team_id/discussions/:discussion_number/comments/:comment_number/reactions/:reaction_id`.\n\nDelete a reaction to a [team discussion comment](https://docs.github.com/enterprise-server@3.0/rest/reference/teams#discussion-comments). OAuth access tokens require the `write:discussion` [scope](https://docs.github.com/enterprise-server@3.0/apps/building-oauth-apps/understanding-scopes-for-oauth-apps/).", "tags": [ "reactions" ], "operationId": "reactions/delete-for-team-discussion-comment", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/reactions#delete-team-discussion-comment-reaction" }, "parameters": [ { "$ref": "#/components/parameters/org" }, { "$ref": "#/components/parameters/team-slug" }, { "$ref": "#/components/parameters/discussion-number" }, { "$ref": "#/components/parameters/comment-number" }, { "$ref": "#/components/parameters/reaction-id" } ], "responses": { "204": { "description": "Response" } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": true, "category": "reactions", "previews": [ { "required": true, "name": "squirrel-girl", "note": "An additional `reactions` object in the issue comment payload is currently available for developers to preview. During the preview period, the APIs may change without advance notice. Please see the [blog post](https://developer.github.com/changes/2016-05-12-reactions-api-preview) for full details.\n\nTo access the API you must provide a custom [media type](https://docs.github.com/enterprise-server@3.0/rest/overview/media-types) in the `Accept` header:\n```shell\napplication/vnd.github.squirrel-girl-preview\n```\nThe `reactions` key will have the following payload where `url` can be used to construct the API location for [listing and creating](https://docs.github.com/enterprise-server@3.0/rest/reference/reactions) reactions." } ] } } }, "/orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/reactions": { "get": { "summary": "List reactions for a team discussion", "description": "List the reactions to a [team discussion](https://docs.github.com/enterprise-server@3.0/rest/reference/teams#discussions). OAuth access tokens require the `read:discussion` [scope](https://docs.github.com/enterprise-server@3.0/apps/building-oauth-apps/understanding-scopes-for-oauth-apps/).\n\n**Note:** You can also specify a team by `org_id` and `team_id` using the route `GET /organizations/:org_id/team/:team_id/discussions/:discussion_number/reactions`.", "tags": [ "reactions" ], "operationId": "reactions/list-for-team-discussion-in-org", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/reactions#list-reactions-for-a-team-discussion" }, "parameters": [ { "$ref": "#/components/parameters/org" }, { "$ref": "#/components/parameters/team-slug" }, { "$ref": "#/components/parameters/discussion-number" }, { "name": "content", "description": "Returns a single [reaction type](https://docs.github.com/enterprise-server@3.0/rest/reference/reactions#reaction-types). Omit this parameter to list all reactions to a team discussion.", "in": "query", "required": false, "schema": { "type": "string", "enum": [ "+1", "-1", "laugh", "confused", "heart", "hooray", "rocket", "eyes" ] } }, { "$ref": "#/components/parameters/per-page" }, { "$ref": "#/components/parameters/page" } ], "responses": { "200": { "description": "Response", "content": { "application/json": { "schema": { "type": "array", "items": { "$ref": "#/components/schemas/reaction" } }, "examples": { "default": { "$ref": "#/components/examples/reaction-items" } } } }, "headers": { "Link": { "$ref": "#/components/headers/link" } } } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": true, "category": "reactions", "previews": [ { "required": true, "name": "squirrel-girl", "note": "An additional `reactions` object in the issue comment payload is currently available for developers to preview. During the preview period, the APIs may change without advance notice. Please see the [blog post](https://developer.github.com/changes/2016-05-12-reactions-api-preview) for full details.\n\nTo access the API you must provide a custom [media type](https://docs.github.com/enterprise-server@3.0/rest/overview/media-types) in the `Accept` header:\n```shell\napplication/vnd.github.squirrel-girl-preview\n```\nThe `reactions` key will have the following payload where `url` can be used to construct the API location for [listing and creating](https://docs.github.com/enterprise-server@3.0/rest/reference/reactions) reactions." } ] } }, "post": { "summary": "Create reaction for a team discussion", "description": "Create a reaction to a [team discussion](https://docs.github.com/enterprise-server@3.0/rest/reference/teams#discussions). OAuth access tokens require the `write:discussion` [scope](https://docs.github.com/enterprise-server@3.0/apps/building-oauth-apps/understanding-scopes-for-oauth-apps/). A response with an HTTP `200` status means that you already added the reaction type to this team discussion.\n\n**Note:** You can also specify a team by `org_id` and `team_id` using the route `POST /organizations/:org_id/team/:team_id/discussions/:discussion_number/reactions`.", "tags": [ "reactions" ], "operationId": "reactions/create-for-team-discussion-in-org", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/reactions#create-reaction-for-a-team-discussion" }, "parameters": [ { "$ref": "#/components/parameters/org" }, { "$ref": "#/components/parameters/team-slug" }, { "$ref": "#/components/parameters/discussion-number" } ], "requestBody": { "required": true, "content": { "application/json": { "schema": { "type": "object", "properties": { "content": { "type": "string", "description": "The [reaction type](https://docs.github.com/enterprise-server@3.0/rest/reference/reactions#reaction-types) to add to the team discussion.", "enum": [ "+1", "-1", "laugh", "confused", "heart", "hooray", "rocket", "eyes" ] } }, "required": [ "content" ] }, "example": { "content": "heart" } } } }, "responses": { "200": { "description": "Response", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/reaction" }, "examples": { "default": { "$ref": "#/components/examples/reaction" } } } } }, "201": { "description": "Response", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/reaction" }, "examples": { "default": { "$ref": "#/components/examples/reaction" } } } } } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": false, "category": "reactions", "previews": [ { "required": true, "name": "squirrel-girl", "note": "An additional `reactions` object in the issue comment payload is currently available for developers to preview. During the preview period, the APIs may change without advance notice. Please see the [blog post](https://developer.github.com/changes/2016-05-12-reactions-api-preview) for full details.\n\nTo access the API you must provide a custom [media type](https://docs.github.com/enterprise-server@3.0/rest/overview/media-types) in the `Accept` header:\n```shell\napplication/vnd.github.squirrel-girl-preview\n```\nThe `reactions` key will have the following payload where `url` can be used to construct the API location for [listing and creating](https://docs.github.com/enterprise-server@3.0/rest/reference/reactions) reactions." } ] } } }, "/orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/reactions/{reaction_id}": { "delete": { "summary": "Delete team discussion reaction", "description": "**Note:** You can also specify a team or organization with `team_id` and `org_id` using the route `DELETE /organizations/:org_id/team/:team_id/discussions/:discussion_number/reactions/:reaction_id`.\n\nDelete a reaction to a [team discussion](https://docs.github.com/enterprise-server@3.0/rest/reference/teams#discussions). OAuth access tokens require the `write:discussion` [scope](https://docs.github.com/enterprise-server@3.0/apps/building-oauth-apps/understanding-scopes-for-oauth-apps/).", "tags": [ "reactions" ], "operationId": "reactions/delete-for-team-discussion", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/reactions#delete-team-discussion-reaction" }, "parameters": [ { "$ref": "#/components/parameters/org" }, { "$ref": "#/components/parameters/team-slug" }, { "$ref": "#/components/parameters/discussion-number" }, { "$ref": "#/components/parameters/reaction-id" } ], "responses": { "204": { "description": "Response" } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": true, "category": "reactions", "previews": [ { "required": true, "name": "squirrel-girl", "note": "An additional `reactions` object in the issue comment payload is currently available for developers to preview. During the preview period, the APIs may change without advance notice. Please see the [blog post](https://developer.github.com/changes/2016-05-12-reactions-api-preview) for full details.\n\nTo access the API you must provide a custom [media type](https://docs.github.com/enterprise-server@3.0/rest/overview/media-types) in the `Accept` header:\n```shell\napplication/vnd.github.squirrel-girl-preview\n```\nThe `reactions` key will have the following payload where `url` can be used to construct the API location for [listing and creating](https://docs.github.com/enterprise-server@3.0/rest/reference/reactions) reactions." } ] } } }, "/orgs/{org}/teams/{team_slug}/members": { "get": { "summary": "List team members", "description": "Team members will include the members of child teams.\n\nTo list members in a team, the team must be visible to the authenticated user.", "tags": [ "teams" ], "operationId": "teams/list-members-in-org", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/teams#list-team-members" }, "parameters": [ { "$ref": "#/components/parameters/org" }, { "$ref": "#/components/parameters/team-slug" }, { "name": "role", "description": "Filters members returned by their role in the team. Can be one of: \n\\* `member` - normal members of the team. \n\\* `maintainer` - team maintainers. \n\\* `all` - all members of the team.", "in": "query", "required": false, "schema": { "type": "string", "enum": [ "member", "maintainer", "all" ], "default": "all" } }, { "$ref": "#/components/parameters/per-page" }, { "$ref": "#/components/parameters/page" } ], "responses": { "200": { "description": "Response", "content": { "application/json": { "schema": { "type": "array", "items": { "$ref": "#/components/schemas/simple-user" } }, "examples": { "default": { "$ref": "#/components/examples/simple-user-items" } } } }, "headers": { "Link": { "$ref": "#/components/headers/link" } } } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": true, "category": "teams", "subcategory": "members" } } }, "/orgs/{org}/teams/{team_slug}/memberships/{username}": { "get": { "summary": "Get team membership for a user", "description": "Team members will include the members of child teams.\n\nTo get a user's membership with a team, the team must be visible to the authenticated user.\n\n**Note:** You can also specify a team by `org_id` and `team_id` using the route `GET /organizations/{org_id}/team/{team_id}/memberships/{username}`.\n\n**Note:**\nThe response contains the `state` of the membership and the member's `role`.\n\nThe `role` for organization owners is set to `maintainer`. For more information about `maintainer` roles, see see [Create a team](https://docs.github.com/enterprise-server@3.0/rest/reference/teams#create-a-team).", "tags": [ "teams" ], "operationId": "teams/get-membership-for-user-in-org", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/teams#get-team-membership-for-a-user" }, "parameters": [ { "$ref": "#/components/parameters/org" }, { "$ref": "#/components/parameters/team-slug" }, { "$ref": "#/components/parameters/username" } ], "responses": { "200": { "description": "Response", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/team-membership" }, "examples": { "response-if-user-is-a-team-maintainer": { "$ref": "#/components/examples/team-membership-response-if-user-is-a-team-maintainer" } } } } }, "404": { "description": "if user has no team membership" } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": true, "category": "teams", "subcategory": "members" } }, "put": { "summary": "Add or update team membership for a user", "description": "Team synchronization is available for organizations using GitHub Enterprise Cloud. For more information, see [GitHub's products](https://docs.github.com/github/getting-started-with-github/githubs-products) in the GitHub Help documentation.\n\nAdds an organization member to a team. An authenticated organization owner or team maintainer can add organization members to a team.\n\n**Note:** When you have team synchronization set up for a team with your organization's identity provider (IdP), you will see an error if you attempt to use the API for making changes to the team's membership. If you have access to manage group membership in your IdP, you can manage GitHub Enterprise Server team membership through your identity provider, which automatically adds and removes team members in an organization. For more information, see \"[Synchronizing teams between your identity provider and GitHub Enterprise Server](https://docs.github.com/articles/synchronizing-teams-between-your-identity-provider-and-github/).\"\n\nAn organization owner can add someone who is not part of the team's organization to a team. When an organization owner adds someone to a team who is not an organization member, this endpoint will send an invitation to the person via email. This newly-created membership will be in the \"pending\" state until the person accepts the invitation, at which point the membership will transition to the \"active\" state and the user will be added as a member of the team.\n\nIf the user is already a member of the team, this endpoint will update the role of the team member's role. To update the membership of a team member, the authenticated user must be an organization owner or a team maintainer.\n\n**Note:** You can also specify a team by `org_id` and `team_id` using the route `PUT /organizations/{org_id}/team/{team_id}/memberships/{username}`.", "tags": [ "teams" ], "operationId": "teams/add-or-update-membership-for-user-in-org", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/teams#add-or-update-team-membership-for-a-user" }, "parameters": [ { "$ref": "#/components/parameters/org" }, { "$ref": "#/components/parameters/team-slug" }, { "$ref": "#/components/parameters/username" } ], "requestBody": { "required": false, "content": { "application/json": { "schema": { "type": "object", "properties": { "role": { "type": "string", "description": "The role that this user should have in the team. Can be one of: \n\\* `member` - a normal member of the team. \n\\* `maintainer` - a team maintainer. Able to add/remove other team members, promote other team members to team maintainer, and edit the team's name and description.", "enum": [ "member", "maintainer" ], "default": "member" } } } } } }, "responses": { "200": { "description": "Response", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/team-membership" }, "examples": { "response-if-users-membership-with-team-is-now-pending": { "$ref": "#/components/examples/team-membership-response-if-users-membership-with-team-is-now-pending" } } } } }, "403": { "description": "Forbidden if team synchronization is set up" }, "422": { "description": "Unprocessable Entity if you attempt to add an organization to a team" } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": true, "category": "teams", "subcategory": "members" } }, "delete": { "summary": "Remove team membership for a user", "description": "Team synchronization is available for organizations using GitHub Enterprise Cloud. For more information, see [GitHub's products](https://docs.github.com/github/getting-started-with-github/githubs-products) in the GitHub Help documentation.\n\nTo remove a membership between a user and a team, the authenticated user must have 'admin' permissions to the team or be an owner of the organization that the team is associated with. Removing team membership does not delete the user, it just removes their membership from the team.\n\n**Note:** When you have team synchronization set up for a team with your organization's identity provider (IdP), you will see an error if you attempt to use the API for making changes to the team's membership. If you have access to manage group membership in your IdP, you can manage GitHub Enterprise Server team membership through your identity provider, which automatically adds and removes team members in an organization. For more information, see \"[Synchronizing teams between your identity provider and GitHub Enterprise Server](https://docs.github.com/articles/synchronizing-teams-between-your-identity-provider-and-github/).\"\n\n**Note:** You can also specify a team by `org_id` and `team_id` using the route `DELETE /organizations/{org_id}/team/{team_id}/memberships/{username}`.", "tags": [ "teams" ], "operationId": "teams/remove-membership-for-user-in-org", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/teams#remove-team-membership-for-a-user" }, "parameters": [ { "$ref": "#/components/parameters/org" }, { "$ref": "#/components/parameters/team-slug" }, { "$ref": "#/components/parameters/username" } ], "responses": { "204": { "description": "Response" }, "403": { "description": "Forbidden if team synchronization is set up" } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": true, "category": "teams", "subcategory": "members" } } }, "/orgs/{org}/teams/{team_slug}/projects": { "get": { "summary": "List team projects", "description": "Lists the organization projects for a team.\n\n**Note:** You can also specify a team by `org_id` and `team_id` using the route `GET /organizations/{org_id}/team/{team_id}/projects`.", "tags": [ "teams" ], "operationId": "teams/list-projects-in-org", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/teams#list-team-projects" }, "parameters": [ { "$ref": "#/components/parameters/org" }, { "$ref": "#/components/parameters/team-slug" }, { "$ref": "#/components/parameters/per-page" }, { "$ref": "#/components/parameters/page" } ], "responses": { "200": { "description": "Response", "content": { "application/json": { "schema": { "type": "array", "items": { "$ref": "#/components/schemas/team-project" } }, "examples": { "default": { "$ref": "#/components/examples/team-project-items" } } } }, "headers": { "Link": { "$ref": "#/components/headers/link" } } } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": true, "category": "teams", "previews": [ { "required": true, "name": "inertia", "note": "The Projects API is currently available for developers to preview. During the preview period, the API may change without advance notice. Please see the [blog post](https://developer.github.com/changes/2016-10-27-changes-to-projects-api) for full details. To access the API during the preview period, you must provide a custom [media type](https://docs.github.com/enterprise-server@3.0/rest/overview/media-types) in the `Accept` header:\n```shell\napplication/vnd.github.inertia-preview+json\n```" } ] } } }, "/orgs/{org}/teams/{team_slug}/projects/{project_id}": { "get": { "summary": "Check team permissions for a project", "description": "Checks whether a team has `read`, `write`, or `admin` permissions for an organization project. The response includes projects inherited from a parent team.\n\n**Note:** You can also specify a team by `org_id` and `team_id` using the route `GET /organizations/{org_id}/team/{team_id}/projects/{project_id}`.", "tags": [ "teams" ], "operationId": "teams/check-permissions-for-project-in-org", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/teams#check-team-permissions-for-a-project" }, "parameters": [ { "$ref": "#/components/parameters/org" }, { "$ref": "#/components/parameters/team-slug" }, { "$ref": "#/components/parameters/project-id" } ], "responses": { "200": { "description": "Response", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/team-project" }, "examples": { "default": { "$ref": "#/components/examples/team-project" } } } } }, "404": { "description": "Not Found if project is not managed by this team" } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": true, "category": "teams", "previews": [ { "required": true, "name": "inertia", "note": "The Projects API is currently available for developers to preview. During the preview period, the API may change without advance notice. Please see the [blog post](https://developer.github.com/changes/2016-10-27-changes-to-projects-api) for full details. To access the API during the preview period, you must provide a custom [media type](https://docs.github.com/enterprise-server@3.0/rest/overview/media-types) in the `Accept` header:\n```shell\napplication/vnd.github.inertia-preview+json\n```" } ] } }, "put": { "summary": "Add or update team project permissions", "description": "Adds an organization project to a team. To add a project to a team or update the team's permission on a project, the authenticated user must have `admin` permissions for the project. The project and team must be part of the same organization.\n\n**Note:** You can also specify a team by `org_id` and `team_id` using the route `PUT /organizations/{org_id}/team/{team_id}/projects/{project_id}`.", "tags": [ "teams" ], "operationId": "teams/add-or-update-project-permissions-in-org", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/teams#add-or-update-team-project-permissions" }, "parameters": [ { "$ref": "#/components/parameters/org" }, { "$ref": "#/components/parameters/team-slug" }, { "$ref": "#/components/parameters/project-id" } ], "requestBody": { "required": false, "content": { "application/json": { "schema": { "type": [ "object", "null" ], "properties": { "permission": { "type": "string", "description": "The permission to grant to the team for this project. Can be one of: \n\\* `read` - team members can read, but not write to or administer this project. \n\\* `write` - team members can read and write, but not administer this project. \n\\* `admin` - team members can read, write and administer this project. \nDefault: the team's `permission` attribute will be used to determine what permission to grant the team on this project. Note that, if you choose not to pass any parameters, you'll need to set `Content-Length` to zero when calling out to this endpoint. For more information, see \"[HTTP verbs](https://docs.github.com/enterprise-server@3.0/rest/overview/resources-in-the-rest-api#http-verbs).\"", "enum": [ "read", "write", "admin" ] } } } } } }, "responses": { "204": { "description": "Response" }, "403": { "description": "Forbidden if the project is not owned by the organization", "content": { "application/json": { "schema": { "type": "object", "properties": { "message": { "type": "string" }, "documentation_url": { "type": "string" } } }, "examples": { "response-if-the-project-is-not-owned-by-the-organization": { "value": { "message": "Must have admin rights to Repository.", "documentation_url": "https://docs.github.com/enterprise-server@3.0/rest/reference/teams#add-or-update-team-project-permissions" } } } } } } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": true, "category": "teams", "previews": [ { "required": true, "name": "inertia", "note": "The Projects API is currently available for developers to preview. During the preview period, the API may change without advance notice. Please see the [blog post](https://developer.github.com/changes/2016-10-27-changes-to-projects-api) for full details. To access the API during the preview period, you must provide a custom [media type](https://docs.github.com/enterprise-server@3.0/rest/overview/media-types) in the `Accept` header:\n```shell\napplication/vnd.github.inertia-preview+json\n```" } ] } }, "delete": { "summary": "Remove a project from a team", "description": "Removes an organization project from a team. An organization owner or a team maintainer can remove any project from the team. To remove a project from a team as an organization member, the authenticated user must have `read` access to both the team and project, or `admin` access to the team or project. This endpoint removes the project from the team, but does not delete the project.\n\n**Note:** You can also specify a team by `org_id` and `team_id` using the route `DELETE /organizations/{org_id}/team/{team_id}/projects/{project_id}`.", "tags": [ "teams" ], "operationId": "teams/remove-project-in-org", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/teams#remove-a-project-from-a-team" }, "parameters": [ { "$ref": "#/components/parameters/org" }, { "$ref": "#/components/parameters/team-slug" }, { "$ref": "#/components/parameters/project-id" } ], "responses": { "204": { "description": "Response" } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": true, "category": "teams", "subcategory": null } } }, "/orgs/{org}/teams/{team_slug}/repos": { "get": { "summary": "List team repositories", "description": "Lists a team's repositories visible to the authenticated user.\n\n**Note:** You can also specify a team by `org_id` and `team_id` using the route `GET /organizations/{org_id}/team/{team_id}/repos`.", "tags": [ "teams" ], "operationId": "teams/list-repos-in-org", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/teams#list-team-repositories" }, "parameters": [ { "$ref": "#/components/parameters/org" }, { "$ref": "#/components/parameters/team-slug" }, { "$ref": "#/components/parameters/per-page" }, { "$ref": "#/components/parameters/page" } ], "responses": { "200": { "description": "Response", "content": { "application/json": { "schema": { "type": "array", "items": { "$ref": "#/components/schemas/minimal-repository" } }, "examples": { "default": { "$ref": "#/components/examples/minimal-repository-items" } } } }, "headers": { "Link": { "$ref": "#/components/headers/link" } } } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": true, "category": "teams", "subcategory": null } } }, "/orgs/{org}/teams/{team_slug}/repos/{owner}/{repo}": { "get": { "summary": "Check team permissions for a repository", "description": "Checks whether a team has `admin`, `push`, `maintain`, `triage`, or `pull` permission for a repository. Repositories inherited through a parent team will also be checked.\n\nYou can also get information about the specified repository, including what permissions the team grants on it, by passing the following custom [media type](https://docs.github.com/enterprise-server@3.0/rest/overview/media-types/) via the `application/vnd.github.v3.repository+json` accept header.\n\nIf a team doesn't have permission for the repository, you will receive a `404 Not Found` response status.\n\n**Note:** You can also specify a team by `org_id` and `team_id` using the route `GET /organizations/{org_id}/team/{team_id}/repos/{owner}/{repo}`.", "tags": [ "teams" ], "operationId": "teams/check-permissions-for-repo-in-org", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/teams/#check-team-permissions-for-a-repository" }, "parameters": [ { "$ref": "#/components/parameters/org" }, { "$ref": "#/components/parameters/team-slug" }, { "$ref": "#/components/parameters/owner" }, { "$ref": "#/components/parameters/repo" } ], "responses": { "200": { "description": "Alternative response with repository permissions", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/team-repository" }, "examples": { "alternative-response-with-repository-permissions": { "$ref": "#/components/examples/team-repository-alternative-response-with-repository-permissions" } } } } }, "204": { "description": "Response if team has permission for the repository. This is the response when the repository media type hasn't been provded in the Accept header." }, "404": { "description": "Not Found if team does not have permission for the repository" } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": true, "category": "teams", "subcategory": null } }, "put": { "summary": "Add or update team repository permissions", "description": "To add a repository to a team or update the team's permission on a repository, the authenticated user must have admin access to the repository, and must be able to see the team. The repository must be owned by the organization, or a direct fork of a repository owned by the organization. You will get a `422 Unprocessable Entity` status if you attempt to add a repository to a team that is not owned by the organization. Note that, if you choose not to pass any parameters, you'll need to set `Content-Length` to zero when calling out to this endpoint. For more information, see \"[HTTP verbs](https://docs.github.com/enterprise-server@3.0/rest/overview/resources-in-the-rest-api#http-verbs).\"\n\n**Note:** You can also specify a team by `org_id` and `team_id` using the route `PUT /organizations/{org_id}/team/{team_id}/repos/{owner}/{repo}`.\n\nFor more information about the permission levels, see \"[Repository permission levels for an organization](https://docs.github.com/en/github/setting-up-and-managing-organizations-and-teams/repository-permission-levels-for-an-organization#permission-levels-for-repositories-owned-by-an-organization)\".", "tags": [ "teams" ], "operationId": "teams/add-or-update-repo-permissions-in-org", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/teams/#add-or-update-team-repository-permissions" }, "parameters": [ { "$ref": "#/components/parameters/org" }, { "$ref": "#/components/parameters/team-slug" }, { "$ref": "#/components/parameters/owner" }, { "$ref": "#/components/parameters/repo" } ], "requestBody": { "required": false, "content": { "application/json": { "schema": { "type": "object", "properties": { "permission": { "type": "string", "description": "The permission to grant the team on this repository. Can be one of: \n\\* `pull` - team members can pull, but not push to or administer this repository. \n\\* `push` - team members can pull and push, but not administer this repository. \n\\* `admin` - team members can pull, push and administer this repository. \n\\* `maintain` - team members can manage the repository without access to sensitive or destructive actions. Recommended for project managers. Only applies to repositories owned by organizations. \n\\* `triage` - team members can proactively manage issues and pull requests without write access. Recommended for contributors who triage a repository. Only applies to repositories owned by organizations. \n \nIf no permission is specified, the team's `permission` attribute will be used to determine what permission to grant the team on this repository.", "enum": [ "pull", "push", "admin", "maintain", "triage" ], "default": "push" } } } } } }, "responses": { "204": { "description": "Response" } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": true, "category": "teams", "subcategory": null } }, "delete": { "summary": "Remove a repository from a team", "description": "If the authenticated user is an organization owner or a team maintainer, they can remove any repositories from the team. To remove a repository from a team as an organization member, the authenticated user must have admin access to the repository and must be able to see the team. This does not delete the repository, it just removes it from the team.\n\n**Note:** You can also specify a team by `org_id` and `team_id` using the route `DELETE /organizations/{org_id}/team/{team_id}/repos/{owner}/{repo}`.", "tags": [ "teams" ], "operationId": "teams/remove-repo-in-org", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/teams/#remove-a-repository-from-a-team" }, "parameters": [ { "$ref": "#/components/parameters/org" }, { "$ref": "#/components/parameters/team-slug" }, { "$ref": "#/components/parameters/owner" }, { "$ref": "#/components/parameters/repo" } ], "responses": { "204": { "description": "Response" } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": true, "category": "teams", "subcategory": null } } }, "/orgs/{org}/teams/{team_slug}/teams": { "get": { "summary": "List child teams", "description": "Lists the child teams of the team specified by `{team_slug}`.\n\n**Note:** You can also specify a team by `org_id` and `team_id` using the route `GET /organizations/{org_id}/team/{team_id}/teams`.", "tags": [ "teams" ], "operationId": "teams/list-child-in-org", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/teams#list-child-teams" }, "parameters": [ { "$ref": "#/components/parameters/org" }, { "$ref": "#/components/parameters/team-slug" }, { "$ref": "#/components/parameters/per-page" }, { "$ref": "#/components/parameters/page" } ], "responses": { "200": { "description": "if child teams exist", "content": { "application/json": { "schema": { "type": "array", "items": { "$ref": "#/components/schemas/team" } }, "examples": { "response-if-child-teams-exist": { "$ref": "#/components/examples/team-items-response-if-child-teams-exist" } } } }, "headers": { "Link": { "$ref": "#/components/headers/link" } } } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": true, "category": "teams", "subcategory": null } } }, "/projects/columns/cards/{card_id}": { "get": { "summary": "Get a project card", "description": "", "tags": [ "projects" ], "operationId": "projects/get-card", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/projects#get-a-project-card" }, "parameters": [ { "$ref": "#/components/parameters/card-id" } ], "responses": { "200": { "description": "Response", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/project-card" }, "examples": { "default": { "$ref": "#/components/examples/project-card" } } } } }, "304": { "$ref": "#/components/responses/not_modified" }, "403": { "$ref": "#/components/responses/forbidden" }, "401": { "$ref": "#/components/responses/requires_authentication" }, "404": { "$ref": "#/components/responses/not_found" } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": true, "category": "projects", "subcategory": "cards", "previews": [ { "required": true, "name": "inertia", "note": "The Projects API is currently available for developers to preview. During the preview period, the API may change without advance notice. Please see the [blog post](https://developer.github.com/changes/2016-10-27-changes-to-projects-api) for full details. To access the API during the preview period, you must provide a custom [media type](https://docs.github.com/enterprise-server@3.0/rest/overview/media-types) in the `Accept` header:\n```shell\napplication/vnd.github.inertia-preview+json\n```" } ] } }, "patch": { "summary": "Update an existing project card", "description": "", "tags": [ "projects" ], "operationId": "projects/update-card", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/projects#update-a-project-card" }, "parameters": [ { "$ref": "#/components/parameters/card-id" } ], "requestBody": { "required": false, "content": { "application/json": { "schema": { "type": "object", "properties": { "note": { "description": "The project card's note", "type": [ "string", "null" ], "examples": [ "Update all gems" ] }, "archived": { "description": "Whether or not the card is archived", "type": "boolean", "examples": [ false ] } } } } } }, "responses": { "200": { "description": "Response", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/project-card" }, "examples": { "default": { "$ref": "#/components/examples/project-card" } } } } }, "304": { "$ref": "#/components/responses/not_modified" }, "403": { "$ref": "#/components/responses/forbidden" }, "401": { "$ref": "#/components/responses/requires_authentication" }, "404": { "$ref": "#/components/responses/not_found" }, "422": { "$ref": "#/components/responses/validation_failed_simple" } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": true, "category": "projects", "subcategory": "cards", "previews": [ { "required": true, "name": "inertia", "note": "The Projects API is currently available for developers to preview. During the preview period, the API may change without advance notice. Please see the [blog post](https://developer.github.com/changes/2016-10-27-changes-to-projects-api) for full details. To access the API during the preview period, you must provide a custom [media type](https://docs.github.com/enterprise-server@3.0/rest/overview/media-types) in the `Accept` header:\n```shell\napplication/vnd.github.inertia-preview+json\n```" } ] } }, "delete": { "summary": "Delete a project card", "description": "", "tags": [ "projects" ], "operationId": "projects/delete-card", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/projects#delete-a-project-card" }, "parameters": [ { "$ref": "#/components/parameters/card-id" } ], "responses": { "204": { "description": "Response" }, "304": { "$ref": "#/components/responses/not_modified" }, "403": { "description": "Forbidden", "content": { "application/json": { "schema": { "type": "object", "properties": { "message": { "type": "string" }, "documentation_url": { "type": "string" }, "errors": { "type": "array", "items": { "type": "string" } } } } } } }, "401": { "$ref": "#/components/responses/requires_authentication" }, "404": { "$ref": "#/components/responses/not_found" } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": true, "category": "projects", "subcategory": "cards", "previews": [ { "required": true, "name": "inertia", "note": "The Projects API is currently available for developers to preview. During the preview period, the API may change without advance notice. Please see the [blog post](https://developer.github.com/changes/2016-10-27-changes-to-projects-api) for full details. To access the API during the preview period, you must provide a custom [media type](https://docs.github.com/enterprise-server@3.0/rest/overview/media-types) in the `Accept` header:\n```shell\napplication/vnd.github.inertia-preview+json\n```" } ] } } }, "/projects/columns/cards/{card_id}/moves": { "post": { "summary": "Move a project card", "description": "", "tags": [ "projects" ], "operationId": "projects/move-card", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/projects#move-a-project-card" }, "parameters": [ { "$ref": "#/components/parameters/card-id" } ], "requestBody": { "required": true, "content": { "application/json": { "schema": { "properties": { "position": { "description": "The position of the card in a column. Can be one of: `top`, `bottom`, or `after:` to place after the specified card.", "type": "string", "pattern": "^(?:top|bottom|after:\\d+)$", "examples": [ "bottom" ] }, "column_id": { "description": "The unique identifier of the column the card should be moved to", "type": "integer", "examples": [ 42 ] } }, "required": [ "position" ], "type": "object" } } } }, "responses": { "201": { "description": "Response", "content": { "application/json": { "schema": { "type": "object", "properties": { }, "additionalProperties": false } } } }, "304": { "$ref": "#/components/responses/not_modified" }, "403": { "description": "Forbidden", "content": { "application/json": { "schema": { "type": "object", "properties": { "message": { "type": "string" }, "documentation_url": { "type": "string" }, "errors": { "type": "array", "items": { "type": "object", "properties": { "code": { "type": "string" }, "message": { "type": "string" }, "resource": { "type": "string" }, "field": { "type": "string" } } } } } } } } }, "401": { "$ref": "#/components/responses/requires_authentication" }, "503": { "description": "Response", "content": { "application/json": { "schema": { "type": "object", "properties": { "code": { "type": "string" }, "message": { "type": "string" }, "documentation_url": { "type": "string" }, "errors": { "type": "array", "items": { "type": "object", "properties": { "code": { "type": "string" }, "message": { "type": "string" } } } } } } } } }, "422": { "$ref": "#/components/responses/validation_failed" } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": true, "category": "projects", "subcategory": "cards", "previews": [ { "required": true, "name": "inertia", "note": "The Projects API is currently available for developers to preview. During the preview period, the API may change without advance notice. Please see the [blog post](https://developer.github.com/changes/2016-10-27-changes-to-projects-api) for full details. To access the API during the preview period, you must provide a custom [media type](https://docs.github.com/enterprise-server@3.0/rest/overview/media-types) in the `Accept` header:\n```shell\napplication/vnd.github.inertia-preview+json\n```" } ] } } }, "/projects/columns/{column_id}": { "get": { "summary": "Get a project column", "description": "", "tags": [ "projects" ], "operationId": "projects/get-column", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/projects#get-a-project-column" }, "parameters": [ { "$ref": "#/components/parameters/column-id" } ], "responses": { "200": { "description": "Response", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/project-column" }, "examples": { "default": { "$ref": "#/components/examples/project-column" } } } } }, "304": { "$ref": "#/components/responses/not_modified" }, "403": { "$ref": "#/components/responses/forbidden" }, "404": { "$ref": "#/components/responses/not_found" }, "401": { "$ref": "#/components/responses/requires_authentication" } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": true, "category": "projects", "subcategory": "columns", "previews": [ { "required": true, "name": "inertia", "note": "The Projects API is currently available for developers to preview. During the preview period, the API may change without advance notice. Please see the [blog post](https://developer.github.com/changes/2016-10-27-changes-to-projects-api) for full details. To access the API during the preview period, you must provide a custom [media type](https://docs.github.com/enterprise-server@3.0/rest/overview/media-types) in the `Accept` header:\n```shell\napplication/vnd.github.inertia-preview+json\n```" } ] } }, "patch": { "summary": "Update an existing project column", "description": "", "tags": [ "projects" ], "operationId": "projects/update-column", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/projects#update-a-project-column" }, "parameters": [ { "$ref": "#/components/parameters/column-id" } ], "requestBody": { "required": true, "content": { "application/json": { "schema": { "properties": { "name": { "description": "Name of the project column", "type": "string", "examples": [ "Remaining tasks" ] } }, "required": [ "name" ], "type": "object" } } } }, "responses": { "200": { "description": "Response", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/project-column" }, "examples": { "default": { "$ref": "#/components/examples/project-column" } } } } }, "304": { "$ref": "#/components/responses/not_modified" }, "403": { "$ref": "#/components/responses/forbidden" }, "401": { "$ref": "#/components/responses/requires_authentication" } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": true, "category": "projects", "subcategory": "columns", "previews": [ { "required": true, "name": "inertia", "note": "The Projects API is currently available for developers to preview. During the preview period, the API may change without advance notice. Please see the [blog post](https://developer.github.com/changes/2016-10-27-changes-to-projects-api) for full details. To access the API during the preview period, you must provide a custom [media type](https://docs.github.com/enterprise-server@3.0/rest/overview/media-types) in the `Accept` header:\n```shell\napplication/vnd.github.inertia-preview+json\n```" } ] } }, "delete": { "summary": "Delete a project column", "description": "", "tags": [ "projects" ], "operationId": "projects/delete-column", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/projects#delete-a-project-column" }, "parameters": [ { "$ref": "#/components/parameters/column-id" } ], "responses": { "204": { "description": "Response" }, "304": { "$ref": "#/components/responses/not_modified" }, "403": { "$ref": "#/components/responses/forbidden" }, "401": { "$ref": "#/components/responses/requires_authentication" } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": true, "category": "projects", "subcategory": "columns", "previews": [ { "required": true, "name": "inertia", "note": "The Projects API is currently available for developers to preview. During the preview period, the API may change without advance notice. Please see the [blog post](https://developer.github.com/changes/2016-10-27-changes-to-projects-api) for full details. To access the API during the preview period, you must provide a custom [media type](https://docs.github.com/enterprise-server@3.0/rest/overview/media-types) in the `Accept` header:\n```shell\napplication/vnd.github.inertia-preview+json\n```" } ] } } }, "/projects/columns/{column_id}/cards": { "get": { "summary": "List project cards", "description": "", "tags": [ "projects" ], "operationId": "projects/list-cards", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/projects#list-project-cards" }, "parameters": [ { "$ref": "#/components/parameters/column-id" }, { "name": "archived_state", "description": "Filters the project cards that are returned by the card's state. Can be one of `all`,`archived`, or `not_archived`.", "in": "query", "required": false, "schema": { "type": "string", "enum": [ "all", "archived", "not_archived" ], "default": "not_archived" } }, { "$ref": "#/components/parameters/per-page" }, { "$ref": "#/components/parameters/page" } ], "responses": { "200": { "description": "Response", "content": { "application/json": { "schema": { "type": "array", "items": { "$ref": "#/components/schemas/project-card" } }, "examples": { "default": { "$ref": "#/components/examples/project-card-items" } } } }, "headers": { "Link": { "$ref": "#/components/headers/link" } } }, "304": { "$ref": "#/components/responses/not_modified" }, "403": { "$ref": "#/components/responses/forbidden" }, "401": { "$ref": "#/components/responses/requires_authentication" } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": true, "category": "projects", "subcategory": "cards", "previews": [ { "required": true, "name": "inertia", "note": "The Projects API is currently available for developers to preview. During the preview period, the API may change without advance notice. Please see the [blog post](https://developer.github.com/changes/2016-10-27-changes-to-projects-api) for full details. To access the API during the preview period, you must provide a custom [media type](https://docs.github.com/enterprise-server@3.0/rest/overview/media-types) in the `Accept` header:\n```shell\napplication/vnd.github.inertia-preview+json\n```" } ] } }, "post": { "summary": "Create a project card", "description": "", "tags": [ "projects" ], "operationId": "projects/create-card", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/projects#create-a-project-card" }, "parameters": [ { "$ref": "#/components/parameters/column-id" } ], "requestBody": { "required": true, "content": { "application/json": { "schema": { "oneOf": [ { "type": "object", "properties": { "note": { "description": "The project card's note", "type": [ "string", "null" ], "examples": [ "Update all gems" ] } }, "required": [ "note" ] }, { "type": "object", "properties": { "content_id": { "description": "The unique identifier of the content associated with the card", "type": "integer", "examples": [ 42 ] }, "content_type": { "description": "The piece of content associated with the card", "type": "string", "examples": [ "PullRequest" ] } }, "required": [ "content_id", "content_type" ] } ] } } } }, "responses": { "201": { "description": "Response", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/project-card" }, "examples": { "default": { "$ref": "#/components/examples/project-card" } } } } }, "304": { "$ref": "#/components/responses/not_modified" }, "403": { "$ref": "#/components/responses/forbidden" }, "401": { "$ref": "#/components/responses/requires_authentication" }, "422": { "description": "Validation failed", "content": { "application/json": { "schema": { "oneOf": [ { "$ref": "#/components/schemas/validation-error" }, { "$ref": "#/components/schemas/validation-error-simple" } ] } } } }, "503": { "description": "Response", "content": { "application/json": { "schema": { "type": "object", "properties": { "code": { "type": "string" }, "message": { "type": "string" }, "documentation_url": { "type": "string" }, "errors": { "type": "array", "items": { "type": "object", "properties": { "code": { "type": "string" }, "message": { "type": "string" } } } } } } } } } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": true, "category": "projects", "subcategory": "cards", "previews": [ { "required": true, "name": "inertia", "note": "The Projects API is currently available for developers to preview. During the preview period, the API may change without advance notice. Please see the [blog post](https://developer.github.com/changes/2016-10-27-changes-to-projects-api) for full details. To access the API during the preview period, you must provide a custom [media type](https://docs.github.com/enterprise-server@3.0/rest/overview/media-types) in the `Accept` header:\n```shell\napplication/vnd.github.inertia-preview+json\n```" } ] } } }, "/projects/columns/{column_id}/moves": { "post": { "summary": "Move a project column", "description": "", "tags": [ "projects" ], "operationId": "projects/move-column", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/projects#move-a-project-column" }, "parameters": [ { "$ref": "#/components/parameters/column-id" } ], "requestBody": { "required": true, "content": { "application/json": { "schema": { "properties": { "position": { "description": "The position of the column in a project. Can be one of: `first`, `last`, or `after:` to place after the specified column.", "type": "string", "pattern": "^(?:first|last|after:\\d+)$", "examples": [ "last" ] } }, "required": [ "position" ], "type": "object" } } } }, "responses": { "201": { "description": "Response", "content": { "application/json": { "schema": { "type": "object", "properties": { }, "additionalProperties": false } } } }, "304": { "$ref": "#/components/responses/not_modified" }, "403": { "$ref": "#/components/responses/forbidden" }, "422": { "$ref": "#/components/responses/validation_failed_simple" }, "401": { "$ref": "#/components/responses/requires_authentication" } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": true, "category": "projects", "subcategory": "columns", "previews": [ { "required": true, "name": "inertia", "note": "The Projects API is currently available for developers to preview. During the preview period, the API may change without advance notice. Please see the [blog post](https://developer.github.com/changes/2016-10-27-changes-to-projects-api) for full details. To access the API during the preview period, you must provide a custom [media type](https://docs.github.com/enterprise-server@3.0/rest/overview/media-types) in the `Accept` header:\n```shell\napplication/vnd.github.inertia-preview+json\n```" } ] } } }, "/projects/{project_id}": { "get": { "summary": "Get a project", "description": "Gets a project by its `id`. Returns a `404 Not Found` status if projects are disabled. If you do not have sufficient privileges to perform this action, a `401 Unauthorized` or `410 Gone` status is returned.", "tags": [ "projects" ], "operationId": "projects/get", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/projects#get-a-project" }, "parameters": [ { "$ref": "#/components/parameters/project-id" } ], "responses": { "200": { "description": "Response", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/project" }, "examples": { "default": { "$ref": "#/components/examples/project-3" } } } } }, "304": { "$ref": "#/components/responses/not_modified" }, "403": { "$ref": "#/components/responses/forbidden" }, "401": { "$ref": "#/components/responses/requires_authentication" } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": true, "category": "projects", "previews": [ { "required": true, "name": "inertia", "note": "The Projects API is currently available for developers to preview. During the preview period, the API may change without advance notice. Please see the [blog post](https://developer.github.com/changes/2016-10-27-changes-to-projects-api) for full details. To access the API during the preview period, you must provide a custom [media type](https://docs.github.com/enterprise-server@3.0/rest/overview/media-types) in the `Accept` header:\n```shell\napplication/vnd.github.inertia-preview+json\n```" } ] } }, "patch": { "summary": "Update a project", "description": "Updates a project board's information. Returns a `404 Not Found` status if projects are disabled. If you do not have sufficient privileges to perform this action, a `401 Unauthorized` or `410 Gone` status is returned.", "operationId": "projects/update", "tags": [ "projects" ], "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/projects#update-a-project" }, "parameters": [ { "$ref": "#/components/parameters/project-id" } ], "requestBody": { "required": false, "content": { "application/json": { "schema": { "properties": { "name": { "description": "Name of the project", "type": "string", "examples": [ "Week One Sprint" ] }, "body": { "description": "Body of the project", "type": [ "string", "null" ], "examples": [ "This project represents the sprint of the first week in January" ] }, "state": { "description": "State of the project; either 'open' or 'closed'", "type": "string", "examples": [ "open" ] }, "organization_permission": { "description": "The baseline permission that all organization members have on this project", "type": "string", "enum": [ "read", "write", "admin", "none" ] }, "private": { "description": "Whether or not this project can be seen by everyone.", "type": "boolean" } }, "type": "object" } } } }, "responses": { "200": { "description": "Response", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/project" }, "examples": { "default": { "$ref": "#/components/examples/project-3" } } } } }, "404": { "description": "Not Found if the authenticated user does not have access to the project" }, "304": { "$ref": "#/components/responses/not_modified" }, "403": { "description": "Forbidden", "content": { "application/json": { "schema": { "type": "object", "properties": { "message": { "type": "string" }, "documentation_url": { "type": "string" }, "errors": { "type": "array", "items": { "type": "string" } } } } } } }, "401": { "$ref": "#/components/responses/requires_authentication" }, "410": { "$ref": "#/components/responses/gone" }, "422": { "$ref": "#/components/responses/validation_failed_simple" } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": true, "category": "projects", "previews": [ { "required": true, "name": "inertia", "note": "The Projects API is currently available for developers to preview. During the preview period, the API may change without advance notice. Please see the [blog post](https://developer.github.com/changes/2016-10-27-changes-to-projects-api) for full details. To access the API during the preview period, you must provide a custom [media type](https://docs.github.com/enterprise-server@3.0/rest/overview/media-types) in the `Accept` header:\n```shell\napplication/vnd.github.inertia-preview+json\n```" } ] } }, "delete": { "summary": "Delete a project", "description": "Deletes a project board. Returns a `404 Not Found` status if projects are disabled.", "operationId": "projects/delete", "tags": [ "projects" ], "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/projects#delete-a-project" }, "parameters": [ { "$ref": "#/components/parameters/project-id" } ], "responses": { "204": { "description": "Delete Success" }, "304": { "$ref": "#/components/responses/not_modified" }, "403": { "description": "Forbidden", "content": { "application/json": { "schema": { "type": "object", "properties": { "message": { "type": "string" }, "documentation_url": { "type": "string" }, "errors": { "type": "array", "items": { "type": "string" } } } } } } }, "401": { "$ref": "#/components/responses/requires_authentication" }, "410": { "$ref": "#/components/responses/gone" }, "404": { "$ref": "#/components/responses/not_found" } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": true, "category": "projects", "previews": [ { "required": true, "name": "inertia", "note": "The Projects API is currently available for developers to preview. During the preview period, the API may change without advance notice. Please see the [blog post](https://developer.github.com/changes/2016-10-27-changes-to-projects-api) for full details. To access the API during the preview period, you must provide a custom [media type](https://docs.github.com/enterprise-server@3.0/rest/overview/media-types) in the `Accept` header:\n```shell\napplication/vnd.github.inertia-preview+json\n```" } ] } } }, "/projects/{project_id}/collaborators": { "get": { "summary": "List project collaborators", "description": "Lists the collaborators for an organization project. For a project, the list of collaborators includes outside collaborators, organization members that are direct collaborators, organization members with access through team memberships, organization members with access through default organization permissions, and organization owners. You must be an organization owner or a project `admin` to list collaborators.", "tags": [ "projects" ], "operationId": "projects/list-collaborators", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/projects#list-project-collaborators" }, "parameters": [ { "$ref": "#/components/parameters/project-id" }, { "name": "affiliation", "description": "Filters the collaborators by their affiliation. Can be one of: \n\\* `outside`: Outside collaborators of a project that are not a member of the project's organization. \n\\* `direct`: Collaborators with permissions to a project, regardless of organization membership status. \n\\* `all`: All collaborators the authenticated user can see.", "in": "query", "required": false, "schema": { "type": "string", "enum": [ "outside", "direct", "all" ], "default": "all" } }, { "$ref": "#/components/parameters/per-page" }, { "$ref": "#/components/parameters/page" } ], "responses": { "200": { "description": "Response", "content": { "application/json": { "schema": { "type": "array", "items": { "$ref": "#/components/schemas/simple-user" } }, "examples": { "default": { "$ref": "#/components/examples/simple-user-items" } } } }, "headers": { "Link": { "$ref": "#/components/headers/link" } } }, "404": { "$ref": "#/components/responses/not_found" }, "422": { "$ref": "#/components/responses/validation_failed" }, "304": { "$ref": "#/components/responses/not_modified" }, "403": { "$ref": "#/components/responses/forbidden" }, "401": { "$ref": "#/components/responses/requires_authentication" } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": true, "category": "projects", "subcategory": "collaborators", "previews": [ { "required": true, "name": "inertia", "note": "The Projects API is currently available for developers to preview. During the preview period, the API may change without advance notice. Please see the [blog post](https://developer.github.com/changes/2016-10-27-changes-to-projects-api) for full details. To access the API during the preview period, you must provide a custom [media type](https://docs.github.com/enterprise-server@3.0/rest/overview/media-types) in the `Accept` header:\n```shell\napplication/vnd.github.inertia-preview+json\n```" } ] } } }, "/projects/{project_id}/collaborators/{username}": { "put": { "summary": "Add project collaborator", "description": "Adds a collaborator to an organization project and sets their permission level. You must be an organization owner or a project `admin` to add a collaborator.", "tags": [ "projects" ], "operationId": "projects/add-collaborator", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/projects#add-project-collaborator" }, "parameters": [ { "$ref": "#/components/parameters/project-id" }, { "$ref": "#/components/parameters/username" } ], "requestBody": { "required": false, "content": { "application/json": { "schema": { "type": [ "object", "null" ], "properties": { "permission": { "description": "The permission to grant the collaborator.", "enum": [ "read", "write", "admin" ], "default": "write", "type": "string", "examples": [ "write" ] } } } } } }, "responses": { "204": { "description": "Response" }, "404": { "$ref": "#/components/responses/not_found" }, "422": { "$ref": "#/components/responses/validation_failed" }, "304": { "$ref": "#/components/responses/not_modified" }, "403": { "$ref": "#/components/responses/forbidden" }, "401": { "$ref": "#/components/responses/requires_authentication" } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": true, "category": "projects", "subcategory": "collaborators", "previews": [ { "required": true, "name": "inertia", "note": "The Projects API is currently available for developers to preview. During the preview period, the API may change without advance notice. Please see the [blog post](https://developer.github.com/changes/2016-10-27-changes-to-projects-api) for full details. To access the API during the preview period, you must provide a custom [media type](https://docs.github.com/enterprise-server@3.0/rest/overview/media-types) in the `Accept` header:\n```shell\napplication/vnd.github.inertia-preview+json\n```" } ] } }, "delete": { "summary": "Remove user as a collaborator", "description": "Removes a collaborator from an organization project. You must be an organization owner or a project `admin` to remove a collaborator.", "tags": [ "projects" ], "operationId": "projects/remove-collaborator", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/projects#remove-project-collaborator" }, "parameters": [ { "$ref": "#/components/parameters/project-id" }, { "$ref": "#/components/parameters/username" } ], "responses": { "204": { "description": "Response" }, "304": { "$ref": "#/components/responses/not_modified" }, "404": { "$ref": "#/components/responses/not_found" }, "403": { "$ref": "#/components/responses/forbidden" }, "422": { "$ref": "#/components/responses/validation_failed" }, "401": { "$ref": "#/components/responses/requires_authentication" } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": true, "category": "projects", "subcategory": "collaborators", "previews": [ { "required": true, "name": "inertia", "note": "The Projects API is currently available for developers to preview. During the preview period, the API may change without advance notice. Please see the [blog post](https://developer.github.com/changes/2016-10-27-changes-to-projects-api) for full details. To access the API during the preview period, you must provide a custom [media type](https://docs.github.com/enterprise-server@3.0/rest/overview/media-types) in the `Accept` header:\n```shell\napplication/vnd.github.inertia-preview+json\n```" } ] } } }, "/projects/{project_id}/collaborators/{username}/permission": { "get": { "summary": "Get project permission for a user", "description": "Returns the collaborator's permission level for an organization project. Possible values for the `permission` key: `admin`, `write`, `read`, `none`. You must be an organization owner or a project `admin` to review a user's permission level.", "tags": [ "projects" ], "operationId": "projects/get-permission-for-user", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/projects#get-project-permission-for-a-user" }, "parameters": [ { "$ref": "#/components/parameters/project-id" }, { "$ref": "#/components/parameters/username" } ], "responses": { "200": { "description": "Response", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/project-collaborator-permission" }, "examples": { "default": { "$ref": "#/components/examples/project-collaborator-permission" } } } } }, "404": { "$ref": "#/components/responses/not_found" }, "422": { "$ref": "#/components/responses/validation_failed" }, "304": { "$ref": "#/components/responses/not_modified" }, "403": { "$ref": "#/components/responses/forbidden" }, "401": { "$ref": "#/components/responses/requires_authentication" } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": true, "category": "projects", "subcategory": "collaborators", "previews": [ { "required": true, "name": "inertia", "note": "The Projects API is currently available for developers to preview. During the preview period, the API may change without advance notice. Please see the [blog post](https://developer.github.com/changes/2016-10-27-changes-to-projects-api) for full details. To access the API during the preview period, you must provide a custom [media type](https://docs.github.com/enterprise-server@3.0/rest/overview/media-types) in the `Accept` header:\n```shell\napplication/vnd.github.inertia-preview+json\n```" } ] } } }, "/projects/{project_id}/columns": { "get": { "summary": "List project columns", "description": "", "tags": [ "projects" ], "operationId": "projects/list-columns", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/projects#list-project-columns" }, "parameters": [ { "$ref": "#/components/parameters/project-id" }, { "$ref": "#/components/parameters/per-page" }, { "$ref": "#/components/parameters/page" } ], "responses": { "200": { "description": "Response", "content": { "application/json": { "schema": { "type": "array", "items": { "$ref": "#/components/schemas/project-column" } }, "examples": { "default": { "$ref": "#/components/examples/project-column-items" } } } }, "headers": { "Link": { "$ref": "#/components/headers/link" } } }, "304": { "$ref": "#/components/responses/not_modified" }, "403": { "$ref": "#/components/responses/forbidden" }, "401": { "$ref": "#/components/responses/requires_authentication" } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": true, "category": "projects", "subcategory": "columns", "previews": [ { "required": true, "name": "inertia", "note": "The Projects API is currently available for developers to preview. During the preview period, the API may change without advance notice. Please see the [blog post](https://developer.github.com/changes/2016-10-27-changes-to-projects-api) for full details. To access the API during the preview period, you must provide a custom [media type](https://docs.github.com/enterprise-server@3.0/rest/overview/media-types) in the `Accept` header:\n```shell\napplication/vnd.github.inertia-preview+json\n```" } ] } }, "post": { "summary": "Create a project column", "description": "", "tags": [ "projects" ], "operationId": "projects/create-column", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/projects#create-a-project-column" }, "parameters": [ { "$ref": "#/components/parameters/project-id" } ], "requestBody": { "required": true, "content": { "application/json": { "schema": { "properties": { "name": { "description": "Name of the project column", "type": "string", "examples": [ "Remaining tasks" ] } }, "required": [ "name" ], "type": "object" } } } }, "responses": { "201": { "description": "Response", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/project-column" }, "example": { "url": "https://api.github.com/projects/columns/367", "project_url": "https://api.github.com/projects/120", "cards_url": "https://api.github.com/projects/columns/367/cards", "id": 367, "node_id": "MDEzOlByb2plY3RDb2x1bW4zNjc=", "name": "To Do", "created_at": "2016-09-05T14:18:44Z", "updated_at": "2016-09-05T14:22:28Z" } } } }, "304": { "$ref": "#/components/responses/not_modified" }, "403": { "$ref": "#/components/responses/forbidden" }, "422": { "$ref": "#/components/responses/validation_failed_simple" }, "401": { "$ref": "#/components/responses/requires_authentication" } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": true, "category": "projects", "subcategory": "columns", "previews": [ { "required": true, "name": "inertia", "note": "The Projects API is currently available for developers to preview. During the preview period, the API may change without advance notice. Please see the [blog post](https://developer.github.com/changes/2016-10-27-changes-to-projects-api) for full details. To access the API during the preview period, you must provide a custom [media type](https://docs.github.com/enterprise-server@3.0/rest/overview/media-types) in the `Accept` header:\n```shell\napplication/vnd.github.inertia-preview+json\n```" } ] } } }, "/rate_limit": { "get": { "summary": "Get rate limit status for the authenticated user", "description": "**Note:** Accessing this endpoint does not count against your REST API rate limit.\n\n**Note:** The `rate` object is deprecated. If you're writing new API client code or updating existing code, you should use the `core` object instead of the `rate` object. The `core` object contains the same information that is present in the `rate` object.", "tags": [ "rate-limit" ], "operationId": "rate-limit/get", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/rate-limit#get-rate-limit-status-for-the-authenticated-user" }, "parameters": [ ], "responses": { "200": { "description": "Response", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/rate-limit-overview" }, "examples": { "default": { "$ref": "#/components/examples/rate-limit-overview" } } } }, "headers": { "X-RateLimit-Limit": { "$ref": "#/components/headers/x-rate-limit-limit" }, "X-RateLimit-Remaining": { "$ref": "#/components/headers/x-rate-limit-remaining" }, "X-RateLimit-Reset": { "$ref": "#/components/headers/x-rate-limit-reset" } } }, "304": { "$ref": "#/components/responses/not_modified" }, "404": { "$ref": "#/components/responses/not_found" } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": true, "category": "rate-limit", "subcategory": null } } }, "/reactions/{reaction_id}": { "delete": { "summary": "Delete a reaction (Legacy)", "description": "**Deprecation Notice:** This endpoint route is deprecated and will be removed from the Reactions API. We recommend migrating your existing code to use the new delete reactions endpoints. For more information, see this [blog post](https://developer.github.com/changes/2020-02-26-new-delete-reactions-endpoints/).\n\nOAuth access tokens require the `write:discussion` [scope](https://docs.github.com/enterprise-server@3.0/apps/building-oauth-apps/understanding-scopes-for-oauth-apps/), when deleting a [team discussion](https://docs.github.com/enterprise-server@3.0/rest/reference/teams#discussions) or [team discussion comment](https://docs.github.com/enterprise-server@3.0/rest/reference/teams#discussion-comments).", "tags": [ "reactions" ], "operationId": "reactions/delete-legacy", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/reactions/#delete-a-reaction-legacy" }, "parameters": [ { "$ref": "#/components/parameters/reaction-id" } ], "responses": { "204": { "description": "Response" }, "304": { "$ref": "#/components/responses/not_modified" }, "403": { "$ref": "#/components/responses/forbidden" }, "401": { "$ref": "#/components/responses/requires_authentication" }, "410": { "$ref": "#/components/responses/gone" } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": true, "removalDate": "2021-02-21", "deprecationDate": "2020-02-26", "category": "reactions", "previews": [ { "required": true, "name": "squirrel-girl", "note": "An additional `reactions` object in the issue comment payload is currently available for developers to preview. During the preview period, the APIs may change without advance notice. Please see the [blog post](https://developer.github.com/changes/2016-05-12-reactions-api-preview) for full details.\n\nTo access the API you must provide a custom [media type](https://docs.github.com/enterprise-server@3.0/rest/overview/media-types) in the `Accept` header:\n```shell\napplication/vnd.github.squirrel-girl-preview\n```\nThe `reactions` key will have the following payload where `url` can be used to construct the API location for [listing and creating](https://docs.github.com/enterprise-server@3.0/rest/reference/reactions) reactions." } ] }, "deprecated": true } }, "/repos/{owner}/{repo}": { "get": { "summary": "Get a repository", "description": "When you pass the `scarlet-witch-preview` media type, requests to get a repository will also return the repository's code of conduct if it can be detected from the repository's code of conduct file.\n\nThe `parent` and `source` objects are present when the repository is a fork. `parent` is the repository this repository was forked from, `source` is the ultimate source for the network.", "tags": [ "repos" ], "operationId": "repos/get", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/repos#get-a-repository" }, "parameters": [ { "$ref": "#/components/parameters/owner" }, { "$ref": "#/components/parameters/repo" } ], "responses": { "200": { "description": "Response", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/full-repository" }, "examples": { "default-response": { "$ref": "#/components/examples/full-repository-default-response" }, "response-with-scarlet-witch-preview-media-type": { "$ref": "#/components/examples/full-repository-response-with-scarlet-witch-preview-media-type" } } } } }, "403": { "$ref": "#/components/responses/forbidden" }, "404": { "$ref": "#/components/responses/not_found" }, "301": { "$ref": "#/components/responses/moved_permanently" } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": true, "category": "repos", "previews": [ { "required": false, "name": "nebula", "note": "You can set the visibility of a repository using the new `visibility` parameter in the [Repositories API](https://docs.github.com/enterprise-server@3.0/rest/reference/repos/), and get a repository's visibility with a new response key. For more information, see the [blog post](https://developer.github.com/changes/2019-12-03-internal-visibility-changes/).\n\nTo access repository visibility during the preview period, you must provide a custom [media type](https://docs.github.com/enterprise-server@3.0/rest/overview/media-types) in the `Accept` header:\n```shell\napplication/vnd.github.nebula-preview+json\n```" }, { "required": false, "name": "scarlet-witch", "note": "The Codes of Conduct API is currently available for developers to preview.\n\nTo access the API during the preview period, you must provide a custom [media type](https://docs.github.com/enterprise-server@3.0/rest/overview/media-types) in the `Accept` header:\n```shell\napplication/vnd.github.scarlet-witch-preview+json\n```" } ] } }, "patch": { "summary": "Update a repository", "description": "**Note**: To edit a repository's topics, use the [Replace all repository topics](https://docs.github.com/enterprise-server@3.0/rest/reference/repos#replace-all-repository-topics) endpoint.", "tags": [ "repos" ], "operationId": "repos/update", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/repos/#update-a-repository" }, "parameters": [ { "$ref": "#/components/parameters/owner" }, { "$ref": "#/components/parameters/repo" } ], "requestBody": { "required": false, "content": { "application/json": { "schema": { "type": "object", "properties": { "name": { "type": "string", "description": "The name of the repository." }, "description": { "type": "string", "description": "A short description of the repository." }, "homepage": { "type": "string", "description": "A URL with more information about the repository." }, "private": { "type": "boolean", "description": "Either `true` to make the repository private or `false` to make it public. Default: `false`. \n**Note**: You will get a `422` error if the organization restricts [changing repository visibility](https://docs.github.com/articles/repository-permission-levels-for-an-organization#changing-the-visibility-of-repositories) to organization owners and a non-owner tries to change the value of private. **Note**: You will get a `422` error if the organization restricts [changing repository visibility](https://docs.github.com/articles/repository-permission-levels-for-an-organization#changing-the-visibility-of-repositories) to organization owners and a non-owner tries to change the value of private.", "default": false }, "visibility": { "type": "string", "description": "Can be `public` or `private`. If your organization is associated with an enterprise account using GitHub Enterprise Cloud or GitHub Enterprise Server 2.20+, `visibility` can also be `internal`.\"", "enum": [ "public", "private", "internal" ] }, "has_issues": { "type": "boolean", "description": "Either `true` to enable issues for this repository or `false` to disable them.", "default": true }, "has_projects": { "type": "boolean", "description": "Either `true` to enable projects for this repository or `false` to disable them. **Note:** If you're creating a repository in an organization that has disabled repository projects, the default is `false`, and if you pass `true`, the API returns an error.", "default": true }, "has_wiki": { "type": "boolean", "description": "Either `true` to enable the wiki for this repository or `false` to disable it.", "default": true }, "is_template": { "type": "boolean", "description": "Either `true` to make this repo available as a template repository or `false` to prevent it.", "default": false }, "default_branch": { "type": "string", "description": "Updates the default branch for this repository." }, "allow_squash_merge": { "type": "boolean", "description": "Either `true` to allow squash-merging pull requests, or `false` to prevent squash-merging.", "default": true }, "allow_merge_commit": { "type": "boolean", "description": "Either `true` to allow merging pull requests with a merge commit, or `false` to prevent merging pull requests with merge commits.", "default": true }, "allow_rebase_merge": { "type": "boolean", "description": "Either `true` to allow rebase-merging pull requests, or `false` to prevent rebase-merging.", "default": true }, "delete_branch_on_merge": { "type": "boolean", "description": "Either `true` to allow automatically deleting head branches when pull requests are merged, or `false` to prevent automatic deletion.", "default": false }, "archived": { "type": "boolean", "description": "`true` to archive this repository. **Note**: You cannot unarchive repositories through the API.", "default": false }, "allow_forking": { "type": "boolean", "description": "Either `true` to allow private forks, or `false` to prevent private forks.", "default": false } } }, "example": { "name": "Hello-World", "description": "This is your first repository", "homepage": "https://github.com", "private": true, "has_issues": true, "has_projects": true, "has_wiki": true } } } }, "responses": { "200": { "description": "Response", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/full-repository" }, "examples": { "default": { "$ref": "#/components/examples/full-repository" } } } } }, "307": { "$ref": "#/components/responses/temporary_redirect" }, "403": { "$ref": "#/components/responses/forbidden" }, "422": { "$ref": "#/components/responses/validation_failed" }, "404": { "$ref": "#/components/responses/not_found" } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": true, "category": "repos", "previews": [ { "required": false, "name": "nebula", "note": "You can set the visibility of a repository using the new `visibility` parameter in the [Repositories API](https://docs.github.com/enterprise-server@3.0/rest/reference/repos/), and get a repository's visibility with a new response key. For more information, see the [blog post](https://developer.github.com/changes/2019-12-03-internal-visibility-changes/).\n\nTo access repository visibility during the preview period, you must provide a custom [media type](https://docs.github.com/enterprise-server@3.0/rest/overview/media-types) in the `Accept` header:\n```shell\napplication/vnd.github.nebula-preview+json\n```" }, { "required": false, "name": "baptiste", "note": "The `is_template` and `template_repository` keys are currently available for developer to preview. See [Create a repository using a template](https://docs.github.com/enterprise-server@3.0/rest/reference/repos#create-a-repository-using-a-template) to learn how to create template repositories. To access these new response keys during the preview period, you must provide a custom [media type](https://docs.github.com/enterprise-server@3.0/rest/overview/media-types) in the `Accept` header:\n\n```shell\napplication/vnd.github.baptiste-preview+json\n```" } ] } }, "delete": { "summary": "Delete a repository", "description": "Deleting a repository requires admin access. If OAuth is used, the `delete_repo` scope is required.\n\nIf an organization owner has configured the organization to prevent members from deleting organization-owned\nrepositories, you will get a `403 Forbidden` response.", "tags": [ "repos" ], "operationId": "repos/delete", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/repos#delete-a-repository" }, "parameters": [ { "$ref": "#/components/parameters/owner" }, { "$ref": "#/components/parameters/repo" } ], "responses": { "204": { "description": "Response" }, "403": { "description": "If an organization owner has configured the organization to prevent members from deleting organization-owned repositories, a member will get this response:", "content": { "application/json": { "schema": { "type": "object", "properties": { "message": { "type": "string" }, "documentation_url": { "type": "string" } } }, "example": { "message": "Organization members cannot delete repositories.", "documentation_url": "https://docs.github.com/enterprise-server@3.0/rest/reference/repos#delete-a-repository" } } } }, "307": { "$ref": "#/components/responses/temporary_redirect" }, "404": { "$ref": "#/components/responses/not_found" } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": true, "category": "repos", "subcategory": null } } }, "/repos/{owner}/{repo}/actions/artifacts": { "get": { "summary": "List artifacts for a repository", "description": "Lists all artifacts for a repository. Anyone with read access to the repository can use this endpoint. If the repository is private you must use an access token with the `repo` scope. GitHub Apps must have the `actions:read` permission to use this endpoint.", "tags": [ "actions" ], "operationId": "actions/list-artifacts-for-repo", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/actions#list-artifacts-for-a-repository" }, "parameters": [ { "$ref": "#/components/parameters/owner" }, { "$ref": "#/components/parameters/repo" }, { "$ref": "#/components/parameters/per-page" }, { "$ref": "#/components/parameters/page" } ], "responses": { "200": { "description": "Response", "content": { "application/json": { "schema": { "type": "object", "required": [ "total_count", "artifacts" ], "properties": { "total_count": { "type": "integer" }, "artifacts": { "type": "array", "items": { "$ref": "#/components/schemas/artifact" } } } }, "examples": { "default": { "$ref": "#/components/examples/artifact-paginated" } } } }, "headers": { "Link": { "$ref": "#/components/headers/link" } } } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": true, "category": "actions", "subcategory": "artifacts" } } }, "/repos/{owner}/{repo}/actions/artifacts/{artifact_id}": { "get": { "summary": "Get an artifact", "description": "Gets a specific artifact for a workflow run. Anyone with read access to the repository can use this endpoint. If the repository is private you must use an access token with the `repo` scope. GitHub Apps must have the `actions:read` permission to use this endpoint.", "tags": [ "actions" ], "operationId": "actions/get-artifact", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/actions#get-an-artifact" }, "parameters": [ { "$ref": "#/components/parameters/owner" }, { "$ref": "#/components/parameters/repo" }, { "$ref": "#/components/parameters/artifact-id" } ], "responses": { "200": { "description": "Response", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/artifact" }, "examples": { "default": { "$ref": "#/components/examples/artifact" } } } } } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": true, "category": "actions", "subcategory": "artifacts" } }, "delete": { "summary": "Delete an artifact", "description": "Deletes an artifact for a workflow run. You must authenticate using an access token with the `repo` scope to use this endpoint. GitHub Apps must have the `actions:write` permission to use this endpoint.", "tags": [ "actions" ], "operationId": "actions/delete-artifact", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/actions#delete-an-artifact" }, "parameters": [ { "$ref": "#/components/parameters/owner" }, { "$ref": "#/components/parameters/repo" }, { "$ref": "#/components/parameters/artifact-id" } ], "responses": { "204": { "description": "Response" } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": true, "category": "actions", "subcategory": "artifacts" } } }, "/repos/{owner}/{repo}/actions/artifacts/{artifact_id}/{archive_format}": { "get": { "summary": "Download an artifact", "description": "Gets a redirect URL to download an archive for a repository. This URL expires after 1 minute. Look for `Location:` in\nthe response header to find the URL for the download. The `:archive_format` must be `zip`. Anyone with read access to\nthe repository can use this endpoint. If the repository is private you must use an access token with the `repo` scope.\nGitHub Apps must have the `actions:read` permission to use this endpoint.", "tags": [ "actions" ], "operationId": "actions/download-artifact", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/actions#download-an-artifact" }, "parameters": [ { "$ref": "#/components/parameters/owner" }, { "$ref": "#/components/parameters/repo" }, { "$ref": "#/components/parameters/artifact-id" }, { "name": "archive_format", "in": "path", "required": true, "schema": { "type": "string" } } ], "responses": { "302": { "description": "Response", "headers": { "Location": { "$ref": "#/components/headers/location" } } } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": true, "category": "actions", "subcategory": "artifacts" } } }, "/repos/{owner}/{repo}/actions/jobs/{job_id}": { "get": { "summary": "Get a job for a workflow run", "description": "Gets a specific job in a workflow run. Anyone with read access to the repository can use this endpoint. If the repository is private you must use an access token with the `repo` scope. GitHub Apps must have the `actions:read` permission to use this endpoint.", "tags": [ "actions" ], "operationId": "actions/get-job-for-workflow-run", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/actions#get-a-job-for-a-workflow-run" }, "parameters": [ { "$ref": "#/components/parameters/owner" }, { "$ref": "#/components/parameters/repo" }, { "$ref": "#/components/parameters/job-id" } ], "responses": { "200": { "description": "Response", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/job" }, "examples": { "default": { "$ref": "#/components/examples/job" } } } } } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": true, "category": "actions", "subcategory": "workflow-jobs" } } }, "/repos/{owner}/{repo}/actions/jobs/{job_id}/logs": { "get": { "summary": "Download job logs for a workflow run", "description": "Gets a redirect URL to download a plain text file of logs for a workflow job. This link expires after 1 minute. Look\nfor `Location:` in the response header to find the URL for the download. Anyone with read access to the repository can\nuse this endpoint. If the repository is private you must use an access token with the `repo` scope. GitHub Apps must\nhave the `actions:read` permission to use this endpoint.", "tags": [ "actions" ], "operationId": "actions/download-job-logs-for-workflow-run", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/actions#download-job-logs-for-a-workflow-run" }, "parameters": [ { "$ref": "#/components/parameters/owner" }, { "$ref": "#/components/parameters/repo" }, { "$ref": "#/components/parameters/job-id" } ], "responses": { "302": { "description": "Response", "headers": { "Location": { "example": "https://pipelines.actions.githubusercontent.com/ab1f3cCFPB34Nd6imvFxpGZH5hNlDp2wijMwl2gDoO0bcrrlJj/_apis/pipelines/1/jobs/19/signedlogcontent?urlExpires=2020-01-22T22%3A44%3A54.1389777Z&urlSigningMethod=HMACV1&urlSignature=2TUDfIg4fm36OJmfPy6km5QD5DLCOkBVzvhWZM8B%2BUY%3D", "schema": { "type": "string" } } } } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": true, "category": "actions", "subcategory": "workflow-jobs" } } }, "/repos/{owner}/{repo}/actions/permissions": { "get": { "summary": "Get GitHub Actions permissions for a repository", "description": "Gets the GitHub Actions permissions policy for a repository, including whether GitHub Actions is enabled and the actions allowed to run in the repository.\n\nYou must authenticate using an access token with the `repo` scope to use this\nendpoint. GitHub Apps must have the `administration` repository permission to use this API.", "operationId": "actions/get-github-actions-permissions-repository", "tags": [ "actions" ], "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/actions#get-github-actions-permissions-for-a-repository" }, "parameters": [ { "$ref": "#/components/parameters/owner" }, { "$ref": "#/components/parameters/repo" } ], "responses": { "200": { "description": "Response", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/actions-repository-permissions" }, "examples": { "default": { "$ref": "#/components/examples/actions-repository-permissions" } } } } } }, "x-github": { "enabledForGitHubApps": true, "githubCloudOnly": false, "category": "actions", "subcategory": "permissions" } }, "put": { "summary": "Set GitHub Actions permissions for a repository", "description": "Sets the GitHub Actions permissions policy for enabling GitHub Actions and allowed actions in the repository.\n\nIf the repository belongs to an organization or enterprise that has set restrictive permissions at the organization or enterprise levels, such as `allowed_actions` to `selected` actions, then you cannot override them for the repository.\n\nYou must authenticate using an access token with the `repo` scope to use this endpoint. GitHub Apps must have the `administration` repository permission to use this API.", "operationId": "actions/set-github-actions-permissions-repository", "tags": [ "actions" ], "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/actions#set-github-actions-permissions-for-a-repository" }, "parameters": [ { "$ref": "#/components/parameters/owner" }, { "$ref": "#/components/parameters/repo" } ], "responses": { "204": { "description": "Response" } }, "requestBody": { "required": true, "content": { "application/json": { "schema": { "type": "object", "properties": { "enabled": { "$ref": "#/components/schemas/actions-enabled" }, "allowed_actions": { "$ref": "#/components/schemas/allowed-actions" } }, "required": [ "enabled" ] }, "example": { "enabled": true, "allowed_actions": "selected" } } } }, "x-github": { "enabledForGitHubApps": true, "githubCloudOnly": false, "category": "actions", "subcategory": "permissions" } } }, "/repos/{owner}/{repo}/actions/permissions/selected-actions": { "get": { "summary": "Get allowed actions for a repository", "description": "Gets the settings for selected actions that are allowed in a repository. To use this endpoint, the repository policy for `allowed_actions` must be configured to `selected`. For more information, see \"[Set GitHub Actions permissions for a repository](#set-github-actions-permissions-for-a-repository).\"\n\nYou must authenticate using an access token with the `repo` scope to use this endpoint. GitHub Apps must have the `administration` repository permission to use this API.", "operationId": "actions/get-allowed-actions-repository", "tags": [ "actions" ], "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/actions#get-allowed-actions-for-a-repository" }, "parameters": [ { "$ref": "#/components/parameters/owner" }, { "$ref": "#/components/parameters/repo" } ], "responses": { "200": { "description": "Response", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/selected-actions" }, "examples": { "default": { "$ref": "#/components/examples/selected-actions" } } } } } }, "x-github": { "enabledForGitHubApps": true, "githubCloudOnly": false, "category": "actions", "subcategory": "permissions" } }, "put": { "summary": "Set allowed actions for a repository", "description": "Sets the actions that are allowed in a repository. To use this endpoint, the repository permission policy for `allowed_actions` must be configured to `selected`. For more information, see \"[Set GitHub Actions permissions for a repository](#set-github-actions-permissions-for-a-repository).\"\n\nIf the repository belongs to an organization or enterprise that has `selected` actions set at the organization or enterprise levels, then you cannot override any of the allowed actions settings.\n\nTo use the `patterns_allowed` setting for private repositories, the repository must belong to an enterprise. If the repository does not belong to an enterprise, then the `patterns_allowed` setting only applies to public repositories.\n\nYou must authenticate using an access token with the `repo` scope to use this endpoint. GitHub Apps must have the `administration` repository permission to use this API.", "operationId": "actions/set-allowed-actions-repository", "tags": [ "actions" ], "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/actions#set-allowed-actions-for-a-repository" }, "parameters": [ { "$ref": "#/components/parameters/owner" }, { "$ref": "#/components/parameters/repo" } ], "responses": { "204": { "description": "Response" } }, "requestBody": { "required": false, "content": { "application/json": { "schema": { "$ref": "#/components/schemas/selected-actions" }, "examples": { "selected_actions": { "$ref": "#/components/examples/selected-actions" } } } } }, "x-github": { "enabledForGitHubApps": true, "githubCloudOnly": false, "category": "actions", "subcategory": "permissions" } } }, "/repos/{owner}/{repo}/actions/runners": { "get": { "summary": "List self-hosted runners for a repository", "description": "Lists all self-hosted runners configured in a repository. You must authenticate using an access token with the `repo` scope to use this endpoint.", "tags": [ "actions" ], "operationId": "actions/list-self-hosted-runners-for-repo", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/actions#list-self-hosted-runners-for-a-repository" }, "parameters": [ { "$ref": "#/components/parameters/owner" }, { "$ref": "#/components/parameters/repo" }, { "$ref": "#/components/parameters/per-page" }, { "$ref": "#/components/parameters/page" } ], "responses": { "200": { "description": "Response", "content": { "application/json": { "schema": { "type": "object", "required": [ "total_count", "runners" ], "properties": { "total_count": { "type": "integer" }, "runners": { "type": "array", "items": { "$ref": "#/components/schemas/runner" } } } }, "examples": { "default": { "$ref": "#/components/examples/runner-paginated" } } } }, "headers": { "Link": { "$ref": "#/components/headers/link" } } } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": true, "category": "actions", "subcategory": "self-hosted-runners" } } }, "/repos/{owner}/{repo}/actions/runners/downloads": { "get": { "summary": "List runner applications for a repository", "description": "Lists binaries for the runner application that you can download and run.\n\nYou must authenticate using an access token with the `repo` scope to use this endpoint.", "tags": [ "actions" ], "operationId": "actions/list-runner-applications-for-repo", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/actions#list-runner-applications-for-a-repository" }, "parameters": [ { "$ref": "#/components/parameters/owner" }, { "$ref": "#/components/parameters/repo" } ], "responses": { "200": { "description": "Response", "content": { "application/json": { "schema": { "type": "array", "items": { "$ref": "#/components/schemas/runner-application" } }, "examples": { "default": { "$ref": "#/components/examples/runner-application-items" } } } } } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": true, "category": "actions", "subcategory": "self-hosted-runners" } } }, "/repos/{owner}/{repo}/actions/runners/registration-token": { "post": { "summary": "Create a registration token for a repository", "description": "Returns a token that you can pass to the `config` script. The token expires after one hour. You must authenticate\nusing an access token with the `repo` scope to use this endpoint.\n\n#### Example using registration token\n \nConfigure your self-hosted runner, replacing `TOKEN` with the registration token provided by this endpoint.\n\n```\n./config.sh --url https://github.com/octo-org/octo-repo-artifacts --token TOKEN\n```", "tags": [ "actions" ], "operationId": "actions/create-registration-token-for-repo", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/actions#create-a-registration-token-for-a-repository" }, "parameters": [ { "$ref": "#/components/parameters/owner" }, { "$ref": "#/components/parameters/repo" } ], "responses": { "201": { "description": "Response", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/authentication-token" }, "examples": { "default": { "$ref": "#/components/examples/authentication-token" } } } } } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": true, "category": "actions", "subcategory": "self-hosted-runners" } } }, "/repos/{owner}/{repo}/actions/runners/remove-token": { "post": { "summary": "Create a remove token for a repository", "description": "Returns a token that you can pass to remove a self-hosted runner from a repository. The token expires after one hour.\nYou must authenticate using an access token with the `repo` scope to use this endpoint.\n\n#### Example using remove token\n \nTo remove your self-hosted runner from a repository, replace TOKEN with the remove token provided by this endpoint.\n\n```\n./config.sh remove --token TOKEN\n```", "tags": [ "actions" ], "operationId": "actions/create-remove-token-for-repo", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/actions#create-a-remove-token-for-a-repository" }, "parameters": [ { "$ref": "#/components/parameters/owner" }, { "$ref": "#/components/parameters/repo" } ], "responses": { "201": { "description": "Response", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/authentication-token" }, "examples": { "default": { "$ref": "#/components/examples/authentication-token-2" } } } } } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": true, "category": "actions", "subcategory": "self-hosted-runners" } } }, "/repos/{owner}/{repo}/actions/runners/{runner_id}": { "get": { "summary": "Get a self-hosted runner for a repository", "description": "Gets a specific self-hosted runner configured in a repository.\n\nYou must authenticate using an access token with the `repo` scope to use this\nendpoint.", "tags": [ "actions" ], "operationId": "actions/get-self-hosted-runner-for-repo", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/actions#get-a-self-hosted-runner-for-a-repository" }, "parameters": [ { "$ref": "#/components/parameters/owner" }, { "$ref": "#/components/parameters/repo" }, { "$ref": "#/components/parameters/runner-id" } ], "responses": { "200": { "description": "Response", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/runner" }, "examples": { "default": { "$ref": "#/components/examples/runner" } } } } } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": true, "category": "actions", "subcategory": "self-hosted-runners" } }, "delete": { "summary": "Delete a self-hosted runner from a repository", "description": "Forces the removal of a self-hosted runner from a repository. You can use this endpoint to completely remove the runner when the machine you were using no longer exists.\n\nYou must authenticate using an access token with the `repo`\nscope to use this endpoint.", "tags": [ "actions" ], "operationId": "actions/delete-self-hosted-runner-from-repo", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/actions#delete-a-self-hosted-runner-from-a-repository" }, "parameters": [ { "$ref": "#/components/parameters/owner" }, { "$ref": "#/components/parameters/repo" }, { "$ref": "#/components/parameters/runner-id" } ], "responses": { "204": { "description": "Response" } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": true, "category": "actions", "subcategory": "self-hosted-runners" } } }, "/repos/{owner}/{repo}/actions/runs": { "get": { "summary": "List workflow runs for a repository", "description": "Lists all workflow runs for a repository. You can use parameters to narrow the list of results. For more information about using parameters, see [Parameters](https://docs.github.com/enterprise-server@3.0/rest/overview/resources-in-the-rest-api#parameters).\n\nAnyone with read access to the repository can use this endpoint. If the repository is private you must use an access token with the `repo` scope. GitHub Apps must have the `actions:read` permission to use this endpoint.", "tags": [ "actions" ], "operationId": "actions/list-workflow-runs-for-repo", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/actions#list-workflow-runs-for-a-repository" }, "parameters": [ { "$ref": "#/components/parameters/owner" }, { "$ref": "#/components/parameters/repo" }, { "$ref": "#/components/parameters/actor" }, { "$ref": "#/components/parameters/workflow-run-branch" }, { "$ref": "#/components/parameters/event" }, { "$ref": "#/components/parameters/workflow-run-status" }, { "$ref": "#/components/parameters/per-page" }, { "$ref": "#/components/parameters/page" }, { "$ref": "#/components/parameters/created" }, { "$ref": "#/components/parameters/exclude-pull-requests" } ], "responses": { "200": { "description": "Response", "content": { "application/json": { "schema": { "type": "object", "required": [ "total_count", "workflow_runs" ], "properties": { "total_count": { "type": "integer" }, "workflow_runs": { "type": "array", "items": { "$ref": "#/components/schemas/workflow-run" } } } }, "examples": { "default": { "$ref": "#/components/examples/workflow-run-paginated" } } } }, "headers": { "Link": { "$ref": "#/components/headers/link" } } } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": true, "category": "actions", "subcategory": "workflow-runs" } } }, "/repos/{owner}/{repo}/actions/runs/{run_id}": { "get": { "summary": "Get a workflow run", "description": "Gets a specific workflow run. Anyone with read access to the repository can use this endpoint. If the repository is private you must use an access token with the `repo` scope. GitHub Apps must have the `actions:read` permission to use this endpoint.", "tags": [ "actions" ], "operationId": "actions/get-workflow-run", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/actions#get-a-workflow-run" }, "parameters": [ { "$ref": "#/components/parameters/owner" }, { "$ref": "#/components/parameters/repo" }, { "$ref": "#/components/parameters/run-id" }, { "$ref": "#/components/parameters/exclude-pull-requests" } ], "responses": { "200": { "description": "Response", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/workflow-run" }, "examples": { "default": { "$ref": "#/components/examples/workflow-run" } } } } } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": true, "category": "actions", "subcategory": "workflow-runs" } }, "delete": { "summary": "Delete a workflow run", "description": "Delete a specific workflow run. Anyone with write access to the repository can use this endpoint. If the repository is\nprivate you must use an access token with the `repo` scope. GitHub Apps must have the `actions:write` permission to use\nthis endpoint.", "operationId": "actions/delete-workflow-run", "tags": [ "actions" ], "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/actions#delete-a-workflow-run" }, "parameters": [ { "$ref": "#/components/parameters/owner" }, { "$ref": "#/components/parameters/repo" }, { "$ref": "#/components/parameters/run-id" } ], "responses": { "204": { "description": "Response" } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": true, "category": "actions", "subcategory": "workflow-runs" } } }, "/repos/{owner}/{repo}/actions/runs/{run_id}/artifacts": { "get": { "summary": "List workflow run artifacts", "description": "Lists artifacts for a workflow run. Anyone with read access to the repository can use this endpoint. If the repository is private you must use an access token with the `repo` scope. GitHub Apps must have the `actions:read` permission to use this endpoint.", "tags": [ "actions" ], "operationId": "actions/list-workflow-run-artifacts", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/actions#list-workflow-run-artifacts" }, "parameters": [ { "$ref": "#/components/parameters/owner" }, { "$ref": "#/components/parameters/repo" }, { "$ref": "#/components/parameters/run-id" }, { "$ref": "#/components/parameters/per-page" }, { "$ref": "#/components/parameters/page" } ], "responses": { "200": { "description": "Response", "content": { "application/json": { "schema": { "type": "object", "required": [ "total_count", "artifacts" ], "properties": { "total_count": { "type": "integer" }, "artifacts": { "type": "array", "items": { "$ref": "#/components/schemas/artifact" } } } }, "examples": { "default": { "$ref": "#/components/examples/artifact-paginated" } } } }, "headers": { "Link": { "$ref": "#/components/headers/link" } } } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": true, "category": "actions", "subcategory": "artifacts" } } }, "/repos/{owner}/{repo}/actions/runs/{run_id}/cancel": { "post": { "summary": "Cancel a workflow run", "description": "Cancels a workflow run using its `id`. You must authenticate using an access token with the `repo` scope to use this endpoint. GitHub Apps must have the `actions:write` permission to use this endpoint.", "tags": [ "actions" ], "operationId": "actions/cancel-workflow-run", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/actions#cancel-a-workflow-run" }, "parameters": [ { "$ref": "#/components/parameters/owner" }, { "$ref": "#/components/parameters/repo" }, { "$ref": "#/components/parameters/run-id" } ], "responses": { "202": { "description": "Response", "content": { "application/json": { "schema": { "type": "object", "properties": { }, "additionalProperties": false } } } } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": true, "category": "actions", "subcategory": "workflow-runs" } } }, "/repos/{owner}/{repo}/actions/runs/{run_id}/jobs": { "get": { "summary": "List jobs for a workflow run", "description": "Lists jobs for a workflow run. Anyone with read access to the repository can use this endpoint. If the repository is private you must use an access token with the `repo` scope. GitHub Apps must have the `actions:read` permission to use this endpoint. You can use parameters to narrow the list of results. For more information about using parameters, see [Parameters](https://docs.github.com/enterprise-server@3.0/rest/overview/resources-in-the-rest-api#parameters).", "tags": [ "actions" ], "operationId": "actions/list-jobs-for-workflow-run", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/actions#list-jobs-for-a-workflow-run" }, "parameters": [ { "$ref": "#/components/parameters/owner" }, { "$ref": "#/components/parameters/repo" }, { "$ref": "#/components/parameters/run-id" }, { "name": "filter", "description": "Filters jobs by their `completed_at` timestamp. Can be one of: \n\\* `latest`: Returns jobs from the most recent execution of the workflow run. \n\\* `all`: Returns all jobs for a workflow run, including from old executions of the workflow run.", "in": "query", "required": false, "schema": { "type": "string", "enum": [ "latest", "all" ], "default": "latest" } }, { "$ref": "#/components/parameters/per-page" }, { "$ref": "#/components/parameters/page" } ], "responses": { "200": { "description": "Response", "content": { "application/json": { "schema": { "type": "object", "required": [ "total_count", "jobs" ], "properties": { "total_count": { "type": "integer" }, "jobs": { "type": "array", "items": { "$ref": "#/components/schemas/job" } } } }, "examples": { "default": { "$ref": "#/components/examples/job-paginated" } } } }, "headers": { "Link": { "$ref": "#/components/headers/link" } } } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": true, "category": "actions", "subcategory": "workflow-jobs" } } }, "/repos/{owner}/{repo}/actions/runs/{run_id}/logs": { "get": { "summary": "Download workflow run logs", "description": "Gets a redirect URL to download an archive of log files for a workflow run. This link expires after 1 minute. Look for\n`Location:` in the response header to find the URL for the download. Anyone with read access to the repository can use\nthis endpoint. If the repository is private you must use an access token with the `repo` scope. GitHub Apps must have\nthe `actions:read` permission to use this endpoint.", "tags": [ "actions" ], "operationId": "actions/download-workflow-run-logs", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/actions#download-workflow-run-logs" }, "parameters": [ { "$ref": "#/components/parameters/owner" }, { "$ref": "#/components/parameters/repo" }, { "$ref": "#/components/parameters/run-id" } ], "responses": { "302": { "description": "Response", "headers": { "Location": { "example": "https://pipelines.actions.githubusercontent.com/ab1f3cCFPB34Nd6imvFxpGZH5hNlDp2wijMwl2gDoO0bcrrlJj/_apis/pipelines/1/runs/19/signedlogcontent?urlExpires=2020-01-22T22%3A44%3A54.1389777Z&urlSigningMethod=HMACV1&urlSignature=2TUDfIg4fm36OJmfPy6km5QD5DLCOkBVzvhWZM8B%2BUY%3D", "schema": { "type": "string" } } } } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": true, "category": "actions", "subcategory": "workflow-runs" } }, "delete": { "summary": "Delete workflow run logs", "description": "Deletes all logs for a workflow run. You must authenticate using an access token with the `repo` scope to use this endpoint. GitHub Apps must have the `actions:write` permission to use this endpoint.", "tags": [ "actions" ], "operationId": "actions/delete-workflow-run-logs", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/actions#delete-workflow-run-logs" }, "parameters": [ { "$ref": "#/components/parameters/owner" }, { "$ref": "#/components/parameters/repo" }, { "$ref": "#/components/parameters/run-id" } ], "responses": { "204": { "description": "Response" }, "403": { "$ref": "#/components/responses/forbidden" }, "500": { "$ref": "#/components/responses/internal_error" } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": true, "category": "actions", "subcategory": "workflow-runs" } } }, "/repos/{owner}/{repo}/actions/runs/{run_id}/rerun": { "post": { "summary": "Re-run a workflow", "description": "Re-runs your workflow run using its `id`. You must authenticate using an access token with the `repo` scope to use this endpoint. GitHub Apps must have the `actions:write` permission to use this endpoint.", "tags": [ "actions" ], "operationId": "actions/re-run-workflow", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/actions#re-run-a-workflow" }, "parameters": [ { "$ref": "#/components/parameters/owner" }, { "$ref": "#/components/parameters/repo" }, { "$ref": "#/components/parameters/run-id" } ], "responses": { "201": { "description": "Response", "content": { "application/json": { "schema": { "type": "object", "properties": { }, "additionalProperties": false } } } } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": false, "deprecationDate": "2021-09-14", "category": "actions", "subcategory": "workflow-runs" }, "deprecated": true } }, "/repos/{owner}/{repo}/actions/secrets": { "get": { "summary": "List repository secrets", "description": "Lists all secrets available in a repository without revealing their encrypted values. You must authenticate using an access token with the `repo` scope to use this endpoint. GitHub Apps must have the `secrets` repository permission to use this endpoint.", "tags": [ "actions" ], "operationId": "actions/list-repo-secrets", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/actions#list-repository-secrets" }, "parameters": [ { "$ref": "#/components/parameters/owner" }, { "$ref": "#/components/parameters/repo" }, { "$ref": "#/components/parameters/per-page" }, { "$ref": "#/components/parameters/page" } ], "responses": { "200": { "description": "Response", "content": { "application/json": { "schema": { "type": "object", "required": [ "total_count", "secrets" ], "properties": { "total_count": { "type": "integer" }, "secrets": { "type": "array", "items": { "$ref": "#/components/schemas/actions-secret" } } } }, "examples": { "default": { "$ref": "#/components/examples/actions-secret-paginated" } } } }, "headers": { "Link": { "$ref": "#/components/headers/link" } } } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": true, "category": "actions", "subcategory": "secrets" } } }, "/repos/{owner}/{repo}/actions/secrets/public-key": { "get": { "summary": "Get a repository public key", "description": "Gets your public key, which you need to encrypt secrets. You need to encrypt a secret before you can create or update secrets. Anyone with read access to the repository can use this endpoint. If the repository is private you must use an access token with the `repo` scope. GitHub Apps must have the `secrets` repository permission to use this endpoint.", "tags": [ "actions" ], "operationId": "actions/get-repo-public-key", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/actions#get-a-repository-public-key" }, "parameters": [ { "$ref": "#/components/parameters/owner" }, { "$ref": "#/components/parameters/repo" } ], "responses": { "200": { "description": "Response", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/actions-public-key" }, "examples": { "default": { "$ref": "#/components/examples/actions-public-key" } } } } } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": true, "category": "actions", "subcategory": "secrets" } } }, "/repos/{owner}/{repo}/actions/secrets/{secret_name}": { "get": { "summary": "Get a repository secret", "description": "Gets a single repository secret without revealing its encrypted value. You must authenticate using an access token with the `repo` scope to use this endpoint. GitHub Apps must have the `secrets` repository permission to use this endpoint.", "tags": [ "actions" ], "operationId": "actions/get-repo-secret", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/actions#get-a-repository-secret" }, "parameters": [ { "$ref": "#/components/parameters/owner" }, { "$ref": "#/components/parameters/repo" }, { "$ref": "#/components/parameters/secret-name" } ], "responses": { "200": { "description": "Response", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/actions-secret" }, "examples": { "default": { "$ref": "#/components/examples/actions-secret" } } } } } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": true, "category": "actions", "subcategory": "secrets" } }, "put": { "summary": "Create or update a repository secret", "description": "Creates or updates a repository secret with an encrypted value. Encrypt your secret using\n[LibSodium](https://libsodium.gitbook.io/doc/bindings_for_other_languages). You must authenticate using an access\ntoken with the `repo` scope to use this endpoint. GitHub Apps must have the `secrets` repository permission to use\nthis endpoint.\n\n#### Example encrypting a secret using Node.js\n\nEncrypt your secret using the [tweetsodium](https://github.com/github/tweetsodium) library.\n\n```\nconst sodium = require('tweetsodium');\n\nconst key = \"base64-encoded-public-key\";\nconst value = \"plain-text-secret\";\n\n// Convert the message and key to Uint8Array's (Buffer implements that interface)\nconst messageBytes = Buffer.from(value);\nconst keyBytes = Buffer.from(key, 'base64');\n\n// Encrypt using LibSodium.\nconst encryptedBytes = sodium.seal(messageBytes, keyBytes);\n\n// Base64 the encrypted secret\nconst encrypted = Buffer.from(encryptedBytes).toString('base64');\n\nconsole.log(encrypted);\n```\n\n\n#### Example encrypting a secret using Python\n\nEncrypt your secret using [pynacl](https://pynacl.readthedocs.io/en/latest/public/#nacl-public-sealedbox) with Python 3.\n\n```\nfrom base64 import b64encode\nfrom nacl import encoding, public\n\ndef encrypt(public_key: str, secret_value: str) -> str:\n \"\"\"Encrypt a Unicode string using the public key.\"\"\"\n public_key = public.PublicKey(public_key.encode(\"utf-8\"), encoding.Base64Encoder())\n sealed_box = public.SealedBox(public_key)\n encrypted = sealed_box.encrypt(secret_value.encode(\"utf-8\"))\n return b64encode(encrypted).decode(\"utf-8\")\n```\n\n#### Example encrypting a secret using C#\n\nEncrypt your secret using the [Sodium.Core](https://www.nuget.org/packages/Sodium.Core/) package.\n\n```\nvar secretValue = System.Text.Encoding.UTF8.GetBytes(\"mySecret\");\nvar publicKey = Convert.FromBase64String(\"2Sg8iYjAxxmI2LvUXpJjkYrMxURPc8r+dB7TJyvvcCU=\");\n\nvar sealedPublicKeyBox = Sodium.SealedPublicKeyBox.Create(secretValue, publicKey);\n\nConsole.WriteLine(Convert.ToBase64String(sealedPublicKeyBox));\n```\n\n#### Example encrypting a secret using Ruby\n\nEncrypt your secret using the [rbnacl](https://github.com/RubyCrypto/rbnacl) gem.\n\n```ruby\nrequire \"rbnacl\"\nrequire \"base64\"\n\nkey = Base64.decode64(\"+ZYvJDZMHUfBkJdyq5Zm9SKqeuBQ4sj+6sfjlH4CgG0=\")\npublic_key = RbNaCl::PublicKey.new(key)\n\nbox = RbNaCl::Boxes::Sealed.from_public_key(public_key)\nencrypted_secret = box.encrypt(\"my_secret\")\n\n# Print the base64 encoded secret\nputs Base64.strict_encode64(encrypted_secret)\n```", "tags": [ "actions" ], "operationId": "actions/create-or-update-repo-secret", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/actions#create-or-update-a-repository-secret" }, "parameters": [ { "$ref": "#/components/parameters/owner" }, { "$ref": "#/components/parameters/repo" }, { "$ref": "#/components/parameters/secret-name" } ], "requestBody": { "required": true, "content": { "application/json": { "schema": { "type": "object", "properties": { "encrypted_value": { "type": "string", "description": "Value for your secret, encrypted with [LibSodium](https://libsodium.gitbook.io/doc/bindings_for_other_languages) using the public key retrieved from the [Get a repository public key](https://docs.github.com/enterprise-server@3.0/rest/reference/actions#get-a-repository-public-key) endpoint.", "pattern": "^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=|[A-Za-z0-9+/]{4})$" }, "key_id": { "type": "string", "description": "ID of the key you used to encrypt the secret." } } }, "example": { "encrypted_value": "c2VjcmV0", "key_id": "012345678912345678" } } } }, "responses": { "201": { "description": "Response when creating a secret", "content": { "application/json": { "schema": { "type": "object", "properties": { }, "additionalProperties": false } } } }, "204": { "description": "Response when updating a secret" } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": true, "category": "actions", "subcategory": "secrets" } }, "delete": { "summary": "Delete a repository secret", "description": "Deletes a secret in a repository using the secret name. You must authenticate using an access token with the `repo` scope to use this endpoint. GitHub Apps must have the `secrets` repository permission to use this endpoint.", "tags": [ "actions" ], "operationId": "actions/delete-repo-secret", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/actions#delete-a-repository-secret" }, "parameters": [ { "$ref": "#/components/parameters/owner" }, { "$ref": "#/components/parameters/repo" }, { "$ref": "#/components/parameters/secret-name" } ], "responses": { "204": { "description": "Response" } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": true, "category": "actions", "subcategory": "secrets" } } }, "/repos/{owner}/{repo}/actions/workflows": { "get": { "summary": "List repository workflows", "description": "Lists the workflows in a repository. Anyone with read access to the repository can use this endpoint. If the repository is private you must use an access token with the `repo` scope. GitHub Apps must have the `actions:read` permission to use this endpoint.", "tags": [ "actions" ], "operationId": "actions/list-repo-workflows", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/actions#list-repository-workflows" }, "parameters": [ { "$ref": "#/components/parameters/owner" }, { "$ref": "#/components/parameters/repo" }, { "$ref": "#/components/parameters/per-page" }, { "$ref": "#/components/parameters/page" } ], "responses": { "200": { "description": "Response", "content": { "application/json": { "schema": { "type": "object", "required": [ "total_count", "workflows" ], "properties": { "total_count": { "type": "integer" }, "workflows": { "type": "array", "items": { "$ref": "#/components/schemas/workflow" } } } }, "examples": { "default": { "$ref": "#/components/examples/workflow-paginated" } } } }, "headers": { "Link": { "$ref": "#/components/headers/link" } } } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": true, "category": "actions", "subcategory": "workflows" } } }, "/repos/{owner}/{repo}/actions/workflows/{workflow_id}": { "get": { "summary": "Get a workflow", "description": "Gets a specific workflow. You can replace `workflow_id` with the workflow file name. For example, you could use `main.yaml`. Anyone with read access to the repository can use this endpoint. If the repository is private you must use an access token with the `repo` scope. GitHub Apps must have the `actions:read` permission to use this endpoint.", "tags": [ "actions" ], "operationId": "actions/get-workflow", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/actions#get-a-workflow" }, "parameters": [ { "$ref": "#/components/parameters/owner" }, { "$ref": "#/components/parameters/repo" }, { "$ref": "#/components/parameters/workflow-id" } ], "responses": { "200": { "description": "Response", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/workflow" }, "examples": { "default": { "$ref": "#/components/examples/workflow" } } } } } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": true, "category": "actions", "subcategory": "workflows" } } }, "/repos/{owner}/{repo}/actions/workflows/{workflow_id}/disable": { "put": { "summary": "Disable a workflow", "description": "Disables a workflow and sets the `state` of the workflow to `disabled_manually`. You can replace `workflow_id` with the workflow file name. For example, you could use `main.yaml`.\n\nYou must authenticate using an access token with the `repo` scope to use this endpoint. GitHub Apps must have the `actions:write` permission to use this endpoint.", "tags": [ "actions" ], "operationId": "actions/disable-workflow", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/actions#disable-a-workflow" }, "parameters": [ { "$ref": "#/components/parameters/owner" }, { "$ref": "#/components/parameters/repo" }, { "$ref": "#/components/parameters/workflow-id" } ], "responses": { "204": { "description": "Response" } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": true, "category": "actions", "subcategory": "workflows" } } }, "/repos/{owner}/{repo}/actions/workflows/{workflow_id}/dispatches": { "post": { "summary": "Create a workflow dispatch event", "description": "You can use this endpoint to manually trigger a GitHub Actions workflow run. You can replace `workflow_id` with the workflow file name. For example, you could use `main.yaml`.\n\nYou must configure your GitHub Actions workflow to run when the [`workflow_dispatch` webhook](/developers/webhooks-and-events/webhook-events-and-payloads#workflow_dispatch) event occurs. The `inputs` are configured in the workflow file. For more information about how to configure the `workflow_dispatch` event in the workflow file, see \"[Events that trigger workflows](/actions/reference/events-that-trigger-workflows#workflow_dispatch).\"\n\nYou must authenticate using an access token with the `repo` scope to use this endpoint. GitHub Apps must have the `actions:write` permission to use this endpoint. For more information, see \"[Creating a personal access token for the command line](https://docs.github.com/articles/creating-a-personal-access-token-for-the-command-line).\"", "operationId": "actions/create-workflow-dispatch", "tags": [ "actions" ], "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/actions#create-a-workflow-dispatch-event" }, "parameters": [ { "$ref": "#/components/parameters/owner" }, { "$ref": "#/components/parameters/repo" }, { "$ref": "#/components/parameters/workflow-id" } ], "responses": { "204": { "description": "Response" } }, "requestBody": { "required": true, "content": { "application/json": { "schema": { "type": "object", "properties": { "ref": { "type": "string", "description": "The git reference for the workflow. The reference can be a branch or tag name." }, "inputs": { "type": "object", "description": "Input keys and values configured in the workflow file. The maximum number of properties is 10. Any default properties configured in the workflow file will be used when `inputs` are omitted.", "additionalProperties": { "type": "string" }, "maxProperties": 10 } }, "required": [ "ref" ] }, "example": { "ref": "topic-branch", "inputs": { "name": "Mona the Octocat", "home": "San Francisco, CA" } } } } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": true, "category": "actions", "subcategory": "workflows" } } }, "/repos/{owner}/{repo}/actions/workflows/{workflow_id}/enable": { "put": { "summary": "Enable a workflow", "description": "Enables a workflow and sets the `state` of the workflow to `active`. You can replace `workflow_id` with the workflow file name. For example, you could use `main.yaml`.\n\nYou must authenticate using an access token with the `repo` scope to use this endpoint. GitHub Apps must have the `actions:write` permission to use this endpoint.", "tags": [ "actions" ], "operationId": "actions/enable-workflow", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/actions#enable-a-workflow" }, "parameters": [ { "$ref": "#/components/parameters/owner" }, { "$ref": "#/components/parameters/repo" }, { "$ref": "#/components/parameters/workflow-id" } ], "responses": { "204": { "description": "Response" } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": true, "category": "actions", "subcategory": "workflows" } } }, "/repos/{owner}/{repo}/actions/workflows/{workflow_id}/runs": { "get": { "summary": "List workflow runs", "description": "List all workflow runs for a workflow. You can replace `workflow_id` with the workflow file name. For example, you could use `main.yaml`. You can use parameters to narrow the list of results. For more information about using parameters, see [Parameters](https://docs.github.com/enterprise-server@3.0/rest/overview/resources-in-the-rest-api#parameters).\n\nAnyone with read access to the repository can use this endpoint. If the repository is private you must use an access token with the `repo` scope.", "tags": [ "actions" ], "operationId": "actions/list-workflow-runs", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/actions#list-workflow-runs" }, "parameters": [ { "$ref": "#/components/parameters/owner" }, { "$ref": "#/components/parameters/repo" }, { "$ref": "#/components/parameters/workflow-id" }, { "$ref": "#/components/parameters/actor" }, { "$ref": "#/components/parameters/workflow-run-branch" }, { "$ref": "#/components/parameters/event" }, { "$ref": "#/components/parameters/workflow-run-status" }, { "$ref": "#/components/parameters/per-page" }, { "$ref": "#/components/parameters/page" }, { "$ref": "#/components/parameters/created" }, { "$ref": "#/components/parameters/exclude-pull-requests" } ], "responses": { "200": { "description": "Response", "content": { "application/json": { "schema": { "type": "object", "required": [ "total_count", "workflow_runs" ], "properties": { "total_count": { "type": "integer" }, "workflow_runs": { "type": "array", "items": { "$ref": "#/components/schemas/workflow-run" } } } }, "examples": { "default": { "$ref": "#/components/examples/workflow-run-paginated" } } } }, "headers": { "Link": { "$ref": "#/components/headers/link" } } } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": true, "category": "actions", "subcategory": "workflow-runs" } } }, "/repos/{owner}/{repo}/assignees": { "get": { "summary": "List assignees", "description": "Lists the [available assignees](https://docs.github.com/articles/assigning-issues-and-pull-requests-to-other-github-users/) for issues in a repository.", "tags": [ "issues" ], "operationId": "issues/list-assignees", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/issues#list-assignees" }, "parameters": [ { "$ref": "#/components/parameters/owner" }, { "$ref": "#/components/parameters/repo" }, { "$ref": "#/components/parameters/per-page" }, { "$ref": "#/components/parameters/page" } ], "responses": { "200": { "description": "Response", "content": { "application/json": { "schema": { "type": "array", "items": { "$ref": "#/components/schemas/simple-user" } }, "examples": { "default": { "$ref": "#/components/examples/simple-user-items" } } } }, "headers": { "Link": { "$ref": "#/components/headers/link" } } }, "404": { "$ref": "#/components/responses/not_found" } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": true, "category": "issues", "subcategory": "assignees" } } }, "/repos/{owner}/{repo}/assignees/{assignee}": { "get": { "summary": "Check if a user can be assigned", "description": "Checks if a user has permission to be assigned to an issue in this repository.\n\nIf the `assignee` can be assigned to issues in the repository, a `204` header with no content is returned.\n\nOtherwise a `404` status code is returned.", "tags": [ "issues" ], "operationId": "issues/check-user-can-be-assigned", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/issues#check-if-a-user-can-be-assigned" }, "parameters": [ { "$ref": "#/components/parameters/owner" }, { "$ref": "#/components/parameters/repo" }, { "name": "assignee", "in": "path", "required": true, "schema": { "type": "string" } } ], "responses": { "204": { "description": "If the `assignee` can be assigned to issues in the repository, a `204` header with no content is returned." }, "404": { "description": "Otherwise a `404` status code is returned.", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/basic-error" } } } } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": true, "category": "issues", "subcategory": "assignees" } } }, "/repos/{owner}/{repo}/branches": { "get": { "summary": "List branches", "description": "", "tags": [ "repos" ], "operationId": "repos/list-branches", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/repos#list-branches" }, "parameters": [ { "$ref": "#/components/parameters/owner" }, { "$ref": "#/components/parameters/repo" }, { "name": "protected", "description": "Setting to `true` returns only protected branches. When set to `false`, only unprotected branches are returned. Omitting this parameter returns all branches.", "in": "query", "required": false, "schema": { "type": "boolean" } }, { "$ref": "#/components/parameters/per-page" }, { "$ref": "#/components/parameters/page" } ], "responses": { "200": { "description": "Response", "content": { "application/json": { "schema": { "type": "array", "items": { "$ref": "#/components/schemas/short-branch" } }, "examples": { "default": { "$ref": "#/components/examples/short-branch-with-protection-items" } } } }, "headers": { "Link": { "$ref": "#/components/headers/link" } } }, "404": { "$ref": "#/components/responses/not_found" } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": true, "category": "repos", "subcategory": "branches" } } }, "/repos/{owner}/{repo}/branches/{branch}": { "get": { "summary": "Get a branch", "description": "", "tags": [ "repos" ], "operationId": "repos/get-branch", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/repos#get-a-branch" }, "parameters": [ { "$ref": "#/components/parameters/owner" }, { "$ref": "#/components/parameters/repo" }, { "$ref": "#/components/parameters/branch" } ], "responses": { "200": { "description": "Response", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/branch-with-protection" } } } }, "301": { "$ref": "#/components/responses/moved_permanently" }, "415": { "$ref": "#/components/responses/preview_header_missing" }, "404": { "$ref": "#/components/responses/not_found" } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": true, "category": "repos", "subcategory": "branches" } } }, "/repos/{owner}/{repo}/branches/{branch}/protection": { "get": { "summary": "Get branch protection", "description": "Protected branches are available in public repositories with GitHub Free and GitHub Free for organizations, and in public and private repositories with GitHub Pro, GitHub Team, GitHub Enterprise Cloud, and GitHub Enterprise Server. For more information, see [GitHub's products](https://docs.github.com/github/getting-started-with-github/githubs-products) in the GitHub Help documentation.", "tags": [ "repos" ], "operationId": "repos/get-branch-protection", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/repos#get-branch-protection" }, "parameters": [ { "$ref": "#/components/parameters/owner" }, { "$ref": "#/components/parameters/repo" }, { "$ref": "#/components/parameters/branch" } ], "responses": { "200": { "description": "Response", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/branch-protection" }, "examples": { "default": { "$ref": "#/components/examples/branch-protection" } } } } }, "404": { "$ref": "#/components/responses/not_found" } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": true, "category": "repos", "subcategory": "branches", "previews": [ { "required": false, "name": "luke-cage", "note": "The Protected Branches API now has a setting for requiring a specified number of approving pull request reviews before merging. This feature is currently available for developers to preview. See the [blog post](https://developer.github.com/changes/2018-03-16-protected-branches-required-approving-reviews) for full details. To access the API during the preview period, you must provide a custom [media type](https://docs.github.com/enterprise-server@3.0/rest/overview/media-types) in the `Accept` header:\n```shell\napplication/vnd.github.luke-cage-preview+json\n```" } ] } }, "put": { "summary": "Update branch protection", "description": "Protected branches are available in public repositories with GitHub Free and GitHub Free for organizations, and in public and private repositories with GitHub Pro, GitHub Team, GitHub Enterprise Cloud, and GitHub Enterprise Server. For more information, see [GitHub's products](https://docs.github.com/github/getting-started-with-github/githubs-products) in the GitHub Help documentation.\n\nProtecting a branch requires admin or owner permissions to the repository.\n\n**Note**: Passing new arrays of `users` and `teams` replaces their previous values.\n\n**Note**: The list of users, apps, and teams in total is limited to 100 items.", "tags": [ "repos" ], "operationId": "repos/update-branch-protection", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/repos#update-branch-protection" }, "parameters": [ { "$ref": "#/components/parameters/owner" }, { "$ref": "#/components/parameters/repo" }, { "$ref": "#/components/parameters/branch" } ], "requestBody": { "required": true, "content": { "application/json": { "schema": { "type": "object", "properties": { "required_status_checks": { "type": [ "object", "null" ], "description": "Require status checks to pass before merging. Set to `null` to disable.", "properties": { "strict": { "type": "boolean", "description": "Require branches to be up to date before merging." }, "contexts": { "type": "array", "deprecated": true, "description": "**Deprecated**: The list of status checks to require in order to merge into this branch. If any of these checks have recently been set by a particular GitHub App, they will be required to come from that app in future for the branch to merge. Use `checks` instead of `contexts` for more fine-grained control.\n", "items": { "type": "string" } }, "checks": { "type": "array", "description": "The list of status checks to require in order to merge into this branch.", "items": { "type": "object", "required": [ "context" ], "properties": { "context": { "type": "string", "description": "The name of the required check" }, "app_id": { "type": "integer", "description": "The ID of the GitHub App that must provide this check. Omit this field to automatically select the GitHub App that has recently provided this check, or any app if it was not set by a GitHub App. Pass -1 to explicitly allow any app to set the status." } } } } }, "required": [ "strict", "contexts" ] }, "enforce_admins": { "type": [ "boolean", "null" ], "description": "Enforce all configured restrictions for administrators. Set to `true` to enforce required status checks for repository administrators. Set to `null` to disable." }, "required_pull_request_reviews": { "type": [ "object", "null" ], "description": "Require at least one approving review on a pull request, before merging. Set to `null` to disable.", "properties": { "dismissal_restrictions": { "type": "object", "description": "Specify which users and teams can dismiss pull request reviews. Pass an empty `dismissal_restrictions` object to disable. User and team `dismissal_restrictions` are only available for organization-owned repositories. Omit this parameter for personal repositories.", "properties": { "users": { "type": "array", "description": "The list of user `login`s with dismissal access", "items": { "type": "string" } }, "teams": { "type": "array", "description": "The list of team `slug`s with dismissal access", "items": { "type": "string" } } } }, "dismiss_stale_reviews": { "type": "boolean", "description": "Set to `true` if you want to automatically dismiss approving reviews when someone pushes a new commit." }, "require_code_owner_reviews": { "type": "boolean", "description": "Blocks merging pull requests until [code owners](https://docs.github.com/articles/about-code-owners/) review them." }, "required_approving_review_count": { "type": "integer", "description": "Specify the number of reviewers required to approve pull requests. Use a number between 1 and 6." } } }, "restrictions": { "type": [ "object", "null" ], "description": "Restrict who can push to the protected branch. User, app, and team `restrictions` are only available for organization-owned repositories. Set to `null` to disable.", "properties": { "users": { "type": "array", "description": "The list of user `login`s with push access", "items": { "type": "string" } }, "teams": { "type": "array", "description": "The list of team `slug`s with push access", "items": { "type": "string" } }, "apps": { "type": "array", "description": "The list of app `slug`s with push access", "items": { "type": "string" } } }, "required": [ "users", "teams" ] }, "required_linear_history": { "type": "boolean", "description": "Enforces a linear commit Git history, which prevents anyone from pushing merge commits to a branch. Set to `true` to enforce a linear commit history. Set to `false` to disable a linear commit Git history. Your repository must allow squash merging or rebase merging before you can enable a linear commit history. Default: `false`. For more information, see \"[Requiring a linear commit history](https://docs.github.com/github/administering-a-repository/requiring-a-linear-commit-history)\" in the GitHub Help documentation." }, "allow_force_pushes": { "type": [ "boolean", "null" ], "description": "Permits force pushes to the protected branch by anyone with write access to the repository. Set to `true` to allow force pushes. Set to `false` or `null` to block force pushes. Default: `false`. For more information, see \"[Enabling force pushes to a protected branch](https://docs.github.com/en/github/administering-a-repository/enabling-force-pushes-to-a-protected-branch)\" in the GitHub Help documentation.\"" }, "allow_deletions": { "type": "boolean", "description": "Allows deletion of the protected branch by anyone with write access to the repository. Set to `false` to prevent deletion of the protected branch. Default: `false`. For more information, see \"[Enabling force pushes to a protected branch](https://docs.github.com/en/github/administering-a-repository/enabling-force-pushes-to-a-protected-branch)\" in the GitHub Help documentation." }, "required_conversation_resolution": { "type": "boolean", "description": "Requires all conversations on code to be resolved before a pull request can be merged into a branch that matches this rule. Set to `false` to disable. Default: `false`." }, "contexts": { "type": "array", "description": "The list of status checks to require in order to merge into this branch.", "items": { "type": "string" } } }, "required": [ "required_status_checks", "enforce_admins", "required_pull_request_reviews", "restrictions" ] }, "example": { "required_status_checks": { "strict": true, "contexts": [ "continuous-integration/travis-ci" ] }, "enforce_admins": true, "required_pull_request_reviews": { "dismissal_restrictions": { "users": [ "octocat" ], "teams": [ "justice-league" ] }, "dismiss_stale_reviews": true, "require_code_owner_reviews": true, "required_approving_review_count": 2, "bypass_pull_request_allowances": { "users": [ "octocat" ], "teams": [ "justice-league" ] } }, "restrictions": { "users": [ "octocat" ], "teams": [ "justice-league" ], "apps": [ "super-ci" ] }, "required_linear_history": true, "allow_force_pushes": true, "allow_deletions": true, "required_conversation_resolution": true } } } }, "responses": { "200": { "description": "Response", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/protected-branch" } } } }, "403": { "$ref": "#/components/responses/forbidden" }, "422": { "$ref": "#/components/responses/validation_failed_simple" }, "404": { "$ref": "#/components/responses/not_found" } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": true, "category": "repos", "subcategory": "branches", "previews": [ { "required": false, "name": "luke-cage", "note": "The Protected Branches API now has a setting for requiring a specified number of approving pull request reviews before merging. This feature is currently available for developers to preview. See the [blog post](https://developer.github.com/changes/2018-03-16-protected-branches-required-approving-reviews) for full details. To access the API during the preview period, you must provide a custom [media type](https://docs.github.com/enterprise-server@3.0/rest/overview/media-types) in the `Accept` header:\n```shell\napplication/vnd.github.luke-cage-preview+json\n```" } ] } }, "delete": { "summary": "Delete branch protection", "description": "Protected branches are available in public repositories with GitHub Free and GitHub Free for organizations, and in public and private repositories with GitHub Pro, GitHub Team, GitHub Enterprise Cloud, and GitHub Enterprise Server. For more information, see [GitHub's products](https://docs.github.com/github/getting-started-with-github/githubs-products) in the GitHub Help documentation.", "tags": [ "repos" ], "operationId": "repos/delete-branch-protection", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/repos#delete-branch-protection" }, "parameters": [ { "$ref": "#/components/parameters/owner" }, { "$ref": "#/components/parameters/repo" }, { "$ref": "#/components/parameters/branch" } ], "responses": { "204": { "description": "Response" }, "403": { "$ref": "#/components/responses/forbidden" } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": true, "category": "repos", "subcategory": "branches" } } }, "/repos/{owner}/{repo}/branches/{branch}/protection/enforce_admins": { "get": { "summary": "Get admin branch protection", "description": "Protected branches are available in public repositories with GitHub Free and GitHub Free for organizations, and in public and private repositories with GitHub Pro, GitHub Team, GitHub Enterprise Cloud, and GitHub Enterprise Server. For more information, see [GitHub's products](https://docs.github.com/github/getting-started-with-github/githubs-products) in the GitHub Help documentation.", "tags": [ "repos" ], "operationId": "repos/get-admin-branch-protection", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/repos#get-admin-branch-protection" }, "parameters": [ { "$ref": "#/components/parameters/owner" }, { "$ref": "#/components/parameters/repo" }, { "$ref": "#/components/parameters/branch" } ], "responses": { "200": { "description": "Response", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/protected-branch-admin-enforced" }, "examples": { "default": { "$ref": "#/components/examples/protected-branch-admin-enforced-2" } } } } } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": true, "category": "repos", "subcategory": "branches" } }, "post": { "summary": "Set admin branch protection", "description": "Protected branches are available in public repositories with GitHub Free and GitHub Free for organizations, and in public and private repositories with GitHub Pro, GitHub Team, GitHub Enterprise Cloud, and GitHub Enterprise Server. For more information, see [GitHub's products](https://docs.github.com/github/getting-started-with-github/githubs-products) in the GitHub Help documentation.\n\nAdding admin enforcement requires admin or owner permissions to the repository and branch protection to be enabled.", "tags": [ "repos" ], "operationId": "repos/set-admin-branch-protection", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/repos#set-admin-branch-protection" }, "parameters": [ { "$ref": "#/components/parameters/owner" }, { "$ref": "#/components/parameters/repo" }, { "$ref": "#/components/parameters/branch" } ], "responses": { "200": { "description": "Response", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/protected-branch-admin-enforced" }, "examples": { "default": { "$ref": "#/components/examples/protected-branch-admin-enforced-2" } } } } } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": true, "category": "repos", "subcategory": "branches" } }, "delete": { "summary": "Delete admin branch protection", "description": "Protected branches are available in public repositories with GitHub Free and GitHub Free for organizations, and in public and private repositories with GitHub Pro, GitHub Team, GitHub Enterprise Cloud, and GitHub Enterprise Server. For more information, see [GitHub's products](https://docs.github.com/github/getting-started-with-github/githubs-products) in the GitHub Help documentation.\n\nRemoving admin enforcement requires admin or owner permissions to the repository and branch protection to be enabled.", "tags": [ "repos" ], "operationId": "repos/delete-admin-branch-protection", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/repos#delete-admin-branch-protection" }, "parameters": [ { "$ref": "#/components/parameters/owner" }, { "$ref": "#/components/parameters/repo" }, { "$ref": "#/components/parameters/branch" } ], "responses": { "204": { "description": "Response" }, "404": { "$ref": "#/components/responses/not_found" } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": true, "category": "repos", "subcategory": "branches" } } }, "/repos/{owner}/{repo}/branches/{branch}/protection/required_pull_request_reviews": { "get": { "summary": "Get pull request review protection", "description": "Protected branches are available in public repositories with GitHub Free and GitHub Free for organizations, and in public and private repositories with GitHub Pro, GitHub Team, GitHub Enterprise Cloud, and GitHub Enterprise Server. For more information, see [GitHub's products](https://docs.github.com/github/getting-started-with-github/githubs-products) in the GitHub Help documentation.", "tags": [ "repos" ], "operationId": "repos/get-pull-request-review-protection", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/repos#get-pull-request-review-protection" }, "parameters": [ { "$ref": "#/components/parameters/owner" }, { "$ref": "#/components/parameters/repo" }, { "$ref": "#/components/parameters/branch" } ], "responses": { "200": { "description": "Response", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/protected-branch-pull-request-review" }, "examples": { "default": { "$ref": "#/components/examples/protected-branch-pull-request-review" } } } } } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": true, "category": "repos", "subcategory": "branches", "previews": [ { "required": false, "name": "luke-cage", "note": "The Protected Branches API now has a setting for requiring a specified number of approving pull request reviews before merging. This feature is currently available for developers to preview. See the [blog post](https://developer.github.com/changes/2018-03-16-protected-branches-required-approving-reviews) for full details. To access the API during the preview period, you must provide a custom [media type](https://docs.github.com/enterprise-server@3.0/rest/overview/media-types) in the `Accept` header:\n```shell\napplication/vnd.github.luke-cage-preview+json\n```" } ] } }, "patch": { "summary": "Update pull request review protection", "description": "Protected branches are available in public repositories with GitHub Free and GitHub Free for organizations, and in public and private repositories with GitHub Pro, GitHub Team, GitHub Enterprise Cloud, and GitHub Enterprise Server. For more information, see [GitHub's products](https://docs.github.com/github/getting-started-with-github/githubs-products) in the GitHub Help documentation.\n\nUpdating pull request review enforcement requires admin or owner permissions to the repository and branch protection to be enabled.\n\n**Note**: Passing new arrays of `users` and `teams` replaces their previous values.", "tags": [ "repos" ], "operationId": "repos/update-pull-request-review-protection", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/repos#update-pull-request-review-protection" }, "parameters": [ { "$ref": "#/components/parameters/owner" }, { "$ref": "#/components/parameters/repo" }, { "$ref": "#/components/parameters/branch" } ], "requestBody": { "required": false, "content": { "application/json": { "schema": { "type": "object", "properties": { "dismissal_restrictions": { "type": "object", "description": "Specify which users and teams can dismiss pull request reviews. Pass an empty `dismissal_restrictions` object to disable. User and team `dismissal_restrictions` are only available for organization-owned repositories. Omit this parameter for personal repositories.", "properties": { "users": { "type": "array", "description": "The list of user `login`s with dismissal access", "items": { "type": "string" } }, "teams": { "type": "array", "description": "The list of team `slug`s with dismissal access", "items": { "type": "string" } } } }, "dismiss_stale_reviews": { "type": "boolean", "description": "Set to `true` if you want to automatically dismiss approving reviews when someone pushes a new commit." }, "require_code_owner_reviews": { "type": "boolean", "description": "Blocks merging pull requests until [code owners](https://docs.github.com/articles/about-code-owners/) have reviewed." }, "required_approving_review_count": { "type": "integer", "description": "Specifies the number of reviewers required to approve pull requests. Use a number between 1 and 6." } } }, "example": { "dismissal_restrictions": { "users": [ "octocat" ], "teams": [ "justice-league" ] }, "bypass_pull_request_allowances": { "users": [ "octocat" ], "teams": [ "justice-league" ] }, "dismiss_stale_reviews": true, "require_code_owner_reviews": true, "required_approving_review_count": 2 } } } }, "responses": { "200": { "description": "Response", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/protected-branch-pull-request-review" }, "examples": { "default": { "$ref": "#/components/examples/protected-branch-pull-request-review" } } } } }, "422": { "$ref": "#/components/responses/validation_failed" } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": true, "category": "repos", "subcategory": "branches", "previews": [ { "required": false, "name": "luke-cage", "note": "The Protected Branches API now has a setting for requiring a specified number of approving pull request reviews before merging. This feature is currently available for developers to preview. See the [blog post](https://developer.github.com/changes/2018-03-16-protected-branches-required-approving-reviews) for full details. To access the API during the preview period, you must provide a custom [media type](https://docs.github.com/enterprise-server@3.0/rest/overview/media-types) in the `Accept` header:\n```shell\napplication/vnd.github.luke-cage-preview+json\n```" } ] } }, "delete": { "summary": "Delete pull request review protection", "description": "Protected branches are available in public repositories with GitHub Free and GitHub Free for organizations, and in public and private repositories with GitHub Pro, GitHub Team, GitHub Enterprise Cloud, and GitHub Enterprise Server. For more information, see [GitHub's products](https://docs.github.com/github/getting-started-with-github/githubs-products) in the GitHub Help documentation.", "tags": [ "repos" ], "operationId": "repos/delete-pull-request-review-protection", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/repos#delete-pull-request-review-protection" }, "parameters": [ { "$ref": "#/components/parameters/owner" }, { "$ref": "#/components/parameters/repo" }, { "$ref": "#/components/parameters/branch" } ], "responses": { "204": { "description": "Response" }, "404": { "$ref": "#/components/responses/not_found" } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": true, "category": "repos", "subcategory": "branches" } } }, "/repos/{owner}/{repo}/branches/{branch}/protection/required_signatures": { "get": { "summary": "Get commit signature protection", "description": "Protected branches are available in public repositories with GitHub Free and GitHub Free for organizations, and in public and private repositories with GitHub Pro, GitHub Team, GitHub Enterprise Cloud, and GitHub Enterprise Server. For more information, see [GitHub's products](https://docs.github.com/github/getting-started-with-github/githubs-products) in the GitHub Help documentation.\n\nWhen authenticated with admin or owner permissions to the repository, you can use this endpoint to check whether a branch requires signed commits. An enabled status of `true` indicates you must sign commits on this branch. For more information, see [Signing commits with GPG](https://docs.github.com/articles/signing-commits-with-gpg) in GitHub Help.\n\n**Note**: You must enable branch protection to require signed commits.", "tags": [ "repos" ], "operationId": "repos/get-commit-signature-protection", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/repos#get-commit-signature-protection" }, "parameters": [ { "$ref": "#/components/parameters/owner" }, { "$ref": "#/components/parameters/repo" }, { "$ref": "#/components/parameters/branch" } ], "responses": { "200": { "description": "Response", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/protected-branch-admin-enforced" }, "examples": { "default": { "$ref": "#/components/examples/protected-branch-admin-enforced" } } } } }, "404": { "$ref": "#/components/responses/not_found" } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": true, "category": "repos", "subcategory": "branches", "previews": [ { "required": true, "name": "zzzax", "note": "Protected Branches API can now manage a setting for requiring signed commits. This feature is currently available for developers to preview. See the [blog post](https://developer.github.com/changes/2018-02-22-protected-branches-required-signatures) for full details. To access the API during the preview period, you must provide a custom [media type](https://docs.github.com/enterprise-server@3.0/rest/overview/media-types) in the `Accept` header:\n```shell\napplication/vnd.github.zzzax-preview+json\n```" } ] } }, "post": { "summary": "Create commit signature protection", "description": "Protected branches are available in public repositories with GitHub Free and GitHub Free for organizations, and in public and private repositories with GitHub Pro, GitHub Team, GitHub Enterprise Cloud, and GitHub Enterprise Server. For more information, see [GitHub's products](https://docs.github.com/github/getting-started-with-github/githubs-products) in the GitHub Help documentation.\n\nWhen authenticated with admin or owner permissions to the repository, you can use this endpoint to require signed commits on a branch. You must enable branch protection to require signed commits.", "tags": [ "repos" ], "operationId": "repos/create-commit-signature-protection", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/repos#create-commit-signature-protection" }, "parameters": [ { "$ref": "#/components/parameters/owner" }, { "$ref": "#/components/parameters/repo" }, { "$ref": "#/components/parameters/branch" } ], "responses": { "200": { "description": "Response", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/protected-branch-admin-enforced" }, "examples": { "default": { "$ref": "#/components/examples/protected-branch-admin-enforced" } } } } }, "404": { "$ref": "#/components/responses/not_found" } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": true, "category": "repos", "subcategory": "branches", "previews": [ { "required": true, "name": "zzzax", "note": "Protected Branches API can now manage a setting for requiring signed commits. This feature is currently available for developers to preview. See the [blog post](https://developer.github.com/changes/2018-02-22-protected-branches-required-signatures) for full details. To access the API during the preview period, you must provide a custom [media type](https://docs.github.com/enterprise-server@3.0/rest/overview/media-types) in the `Accept` header:\n```shell\napplication/vnd.github.zzzax-preview+json\n```" } ] } }, "delete": { "summary": "Delete commit signature protection", "description": "Protected branches are available in public repositories with GitHub Free and GitHub Free for organizations, and in public and private repositories with GitHub Pro, GitHub Team, GitHub Enterprise Cloud, and GitHub Enterprise Server. For more information, see [GitHub's products](https://docs.github.com/github/getting-started-with-github/githubs-products) in the GitHub Help documentation.\n\nWhen authenticated with admin or owner permissions to the repository, you can use this endpoint to disable required signed commits on a branch. You must enable branch protection to require signed commits.", "tags": [ "repos" ], "operationId": "repos/delete-commit-signature-protection", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/repos#delete-commit-signature-protection" }, "parameters": [ { "$ref": "#/components/parameters/owner" }, { "$ref": "#/components/parameters/repo" }, { "$ref": "#/components/parameters/branch" } ], "responses": { "204": { "description": "Response" }, "404": { "$ref": "#/components/responses/not_found" } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": true, "category": "repos", "subcategory": "branches", "previews": [ { "required": true, "name": "zzzax", "note": "Protected Branches API can now manage a setting for requiring signed commits. This feature is currently available for developers to preview. See the [blog post](https://developer.github.com/changes/2018-02-22-protected-branches-required-signatures) for full details. To access the API during the preview period, you must provide a custom [media type](https://docs.github.com/enterprise-server@3.0/rest/overview/media-types) in the `Accept` header:\n```shell\napplication/vnd.github.zzzax-preview+json\n```" } ] } } }, "/repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks": { "get": { "summary": "Get status checks protection", "description": "Protected branches are available in public repositories with GitHub Free and GitHub Free for organizations, and in public and private repositories with GitHub Pro, GitHub Team, GitHub Enterprise Cloud, and GitHub Enterprise Server. For more information, see [GitHub's products](https://docs.github.com/github/getting-started-with-github/githubs-products) in the GitHub Help documentation.", "tags": [ "repos" ], "operationId": "repos/get-status-checks-protection", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/repos#get-status-checks-protection" }, "parameters": [ { "$ref": "#/components/parameters/owner" }, { "$ref": "#/components/parameters/repo" }, { "$ref": "#/components/parameters/branch" } ], "responses": { "200": { "description": "Response", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/status-check-policy" }, "examples": { "default": { "$ref": "#/components/examples/status-check-policy" } } } } }, "404": { "$ref": "#/components/responses/not_found" } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": true, "category": "repos", "subcategory": "branches" } }, "patch": { "summary": "Update status check protection", "description": "Protected branches are available in public repositories with GitHub Free and GitHub Free for organizations, and in public and private repositories with GitHub Pro, GitHub Team, GitHub Enterprise Cloud, and GitHub Enterprise Server. For more information, see [GitHub's products](https://docs.github.com/github/getting-started-with-github/githubs-products) in the GitHub Help documentation.\n\nUpdating required status checks requires admin or owner permissions to the repository and branch protection to be enabled.", "tags": [ "repos" ], "operationId": "repos/update-status-check-protection", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/repos#update-status-check-protection" }, "parameters": [ { "$ref": "#/components/parameters/owner" }, { "$ref": "#/components/parameters/repo" }, { "$ref": "#/components/parameters/branch" } ], "requestBody": { "required": false, "content": { "application/json": { "schema": { "type": "object", "properties": { "strict": { "type": "boolean", "description": "Require branches to be up to date before merging." }, "contexts": { "type": "array", "deprecated": true, "description": "The list of status checks to require in order to merge into this branch", "items": { "type": "string" } } } }, "example": { "strict": true, "contexts": [ "continuous-integration/travis-ci" ] } } } }, "responses": { "200": { "description": "Response", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/status-check-policy" }, "examples": { "default": { "$ref": "#/components/examples/status-check-policy" } } } } }, "404": { "$ref": "#/components/responses/not_found" }, "422": { "$ref": "#/components/responses/validation_failed" } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": true, "category": "repos", "subcategory": "branches" } }, "delete": { "summary": "Remove status check protection", "description": "Protected branches are available in public repositories with GitHub Free and GitHub Free for organizations, and in public and private repositories with GitHub Pro, GitHub Team, GitHub Enterprise Cloud, and GitHub Enterprise Server. For more information, see [GitHub's products](https://docs.github.com/github/getting-started-with-github/githubs-products) in the GitHub Help documentation.", "tags": [ "repos" ], "operationId": "repos/remove-status-check-protection", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/repos#remove-status-check-protection" }, "parameters": [ { "$ref": "#/components/parameters/owner" }, { "$ref": "#/components/parameters/repo" }, { "$ref": "#/components/parameters/branch" } ], "responses": { "204": { "description": "Response" } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": true, "category": "repos", "subcategory": "branches" } } }, "/repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks/contexts": { "get": { "summary": "Get all status check contexts", "description": "Protected branches are available in public repositories with GitHub Free and GitHub Free for organizations, and in public and private repositories with GitHub Pro, GitHub Team, GitHub Enterprise Cloud, and GitHub Enterprise Server. For more information, see [GitHub's products](https://docs.github.com/github/getting-started-with-github/githubs-products) in the GitHub Help documentation.", "tags": [ "repos" ], "operationId": "repos/get-all-status-check-contexts", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/repos#get-all-status-check-contexts" }, "parameters": [ { "$ref": "#/components/parameters/owner" }, { "$ref": "#/components/parameters/repo" }, { "$ref": "#/components/parameters/branch" } ], "responses": { "200": { "description": "Response", "content": { "application/json": { "schema": { "type": "array", "items": { "type": "string" } }, "example": [ "continuous-integration/travis-ci" ] } } }, "404": { "$ref": "#/components/responses/not_found" } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": true, "category": "repos", "subcategory": "branches" } }, "post": { "summary": "Add status check contexts", "description": "Protected branches are available in public repositories with GitHub Free and GitHub Free for organizations, and in public and private repositories with GitHub Pro, GitHub Team, GitHub Enterprise Cloud, and GitHub Enterprise Server. For more information, see [GitHub's products](https://docs.github.com/github/getting-started-with-github/githubs-products) in the GitHub Help documentation.", "tags": [ "repos" ], "operationId": "repos/add-status-check-contexts", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/repos#add-status-check-contexts" }, "parameters": [ { "$ref": "#/components/parameters/owner" }, { "$ref": "#/components/parameters/repo" }, { "$ref": "#/components/parameters/branch" } ], "requestBody": { "required": false, "content": { "application/json": { "schema": { "oneOf": [ { "type": "object", "properties": { "contexts": { "type": "array", "description": "contexts parameter", "items": { "type": "string" } } }, "required": [ "contexts" ], "example": { "contexts": [ "contexts" ] } }, { "type": "array", "description": "contexts parameter", "items": { "type": "string" } } ] } } } }, "responses": { "200": { "description": "Response", "content": { "application/json": { "schema": { "type": "array", "items": { "type": "string" } }, "example": [ "continuous-integration/travis-ci", "continuous-integration/jenkins" ] } } }, "422": { "$ref": "#/components/responses/validation_failed" }, "403": { "$ref": "#/components/responses/forbidden" }, "404": { "$ref": "#/components/responses/not_found" } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": true, "requestBodyParameterName": "contexts", "category": "repos", "subcategory": "branches" } }, "put": { "summary": "Set status check contexts", "description": "Protected branches are available in public repositories with GitHub Free and GitHub Free for organizations, and in public and private repositories with GitHub Pro, GitHub Team, GitHub Enterprise Cloud, and GitHub Enterprise Server. For more information, see [GitHub's products](https://docs.github.com/github/getting-started-with-github/githubs-products) in the GitHub Help documentation.", "tags": [ "repos" ], "operationId": "repos/set-status-check-contexts", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/repos#set-status-check-contexts" }, "parameters": [ { "$ref": "#/components/parameters/owner" }, { "$ref": "#/components/parameters/repo" }, { "$ref": "#/components/parameters/branch" } ], "requestBody": { "required": false, "content": { "application/json": { "schema": { "oneOf": [ { "type": "object", "properties": { "contexts": { "type": "array", "description": "contexts parameter", "items": { "type": "string" } } }, "required": [ "contexts" ], "example": { "contexts": [ "contexts" ] } }, { "type": "array", "description": "contexts parameter", "items": { "type": "string" } } ] } } } }, "responses": { "200": { "description": "Response", "content": { "application/json": { "schema": { "type": "array", "items": { "type": "string" } }, "example": [ "continuous-integration/travis-ci" ] } } }, "422": { "$ref": "#/components/responses/validation_failed" }, "404": { "$ref": "#/components/responses/not_found" } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": true, "requestBodyParameterName": "contexts", "category": "repos", "subcategory": "branches" } }, "delete": { "summary": "Remove status check contexts", "description": "Protected branches are available in public repositories with GitHub Free and GitHub Free for organizations, and in public and private repositories with GitHub Pro, GitHub Team, GitHub Enterprise Cloud, and GitHub Enterprise Server. For more information, see [GitHub's products](https://docs.github.com/github/getting-started-with-github/githubs-products) in the GitHub Help documentation.", "tags": [ "repos" ], "operationId": "repos/remove-status-check-contexts", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/repos#remove-status-check-contexts" }, "parameters": [ { "$ref": "#/components/parameters/owner" }, { "$ref": "#/components/parameters/repo" }, { "$ref": "#/components/parameters/branch" } ], "requestBody": { "content": { "application/json": { "schema": { "oneOf": [ { "type": "object", "properties": { "contexts": { "type": "array", "description": "contexts parameter", "items": { "type": "string" } } }, "required": [ "contexts" ], "example": { "contexts": [ "contexts" ] } }, { "type": "array", "description": "contexts parameter", "items": { "type": "string" } } ] } } } }, "responses": { "200": { "description": "Response", "content": { "application/json": { "schema": { "type": "array", "items": { "type": "string" } }, "example": [ "continuous-integration/travis-ci" ] } } }, "404": { "$ref": "#/components/responses/not_found" }, "422": { "$ref": "#/components/responses/validation_failed" } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": true, "requestBodyParameterName": "contexts", "category": "repos", "subcategory": "branches" } } }, "/repos/{owner}/{repo}/branches/{branch}/protection/restrictions": { "get": { "summary": "Get access restrictions", "description": "Protected branches are available in public repositories with GitHub Free and GitHub Free for organizations, and in public and private repositories with GitHub Pro, GitHub Team, GitHub Enterprise Cloud, and GitHub Enterprise Server. For more information, see [GitHub's products](https://docs.github.com/github/getting-started-with-github/githubs-products) in the GitHub Help documentation.\n\nLists who has access to this protected branch.\n\n**Note**: Users, apps, and teams `restrictions` are only available for organization-owned repositories.", "tags": [ "repos" ], "operationId": "repos/get-access-restrictions", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/repos#get-access-restrictions" }, "parameters": [ { "$ref": "#/components/parameters/owner" }, { "$ref": "#/components/parameters/repo" }, { "$ref": "#/components/parameters/branch" } ], "responses": { "200": { "description": "Response", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/branch-restriction-policy" }, "examples": { "default": { "$ref": "#/components/examples/branch-restriction-policy" } } } } }, "404": { "$ref": "#/components/responses/not_found" } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": true, "category": "repos", "subcategory": "branches" } }, "delete": { "summary": "Delete access restrictions", "description": "Protected branches are available in public repositories with GitHub Free and GitHub Free for organizations, and in public and private repositories with GitHub Pro, GitHub Team, GitHub Enterprise Cloud, and GitHub Enterprise Server. For more information, see [GitHub's products](https://docs.github.com/github/getting-started-with-github/githubs-products) in the GitHub Help documentation.\n\nDisables the ability to restrict who can push to this branch.", "tags": [ "repos" ], "operationId": "repos/delete-access-restrictions", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/repos#delete-access-restrictions" }, "parameters": [ { "$ref": "#/components/parameters/owner" }, { "$ref": "#/components/parameters/repo" }, { "$ref": "#/components/parameters/branch" } ], "responses": { "204": { "description": "Response" } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": true, "category": "repos", "subcategory": "branches" } } }, "/repos/{owner}/{repo}/branches/{branch}/protection/restrictions/apps": { "get": { "summary": "Get apps with access to the protected branch", "description": "Protected branches are available in public repositories with GitHub Free and GitHub Free for organizations, and in public and private repositories with GitHub Pro, GitHub Team, GitHub Enterprise Cloud, and GitHub Enterprise Server. For more information, see [GitHub's products](https://docs.github.com/github/getting-started-with-github/githubs-products) in the GitHub Help documentation.\n\nLists the GitHub Apps that have push access to this branch. Only installed GitHub Apps with `write` access to the `contents` permission can be added as authorized actors on a protected branch.", "tags": [ "repos" ], "operationId": "repos/get-apps-with-access-to-protected-branch", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/repos#list-apps-with-access-to-the-protected-branch" }, "parameters": [ { "$ref": "#/components/parameters/owner" }, { "$ref": "#/components/parameters/repo" }, { "$ref": "#/components/parameters/branch" } ], "responses": { "200": { "description": "Response", "content": { "application/json": { "schema": { "type": "array", "items": { "$ref": "#/components/schemas/integration" } }, "examples": { "default": { "$ref": "#/components/examples/integration-items" } } } } }, "404": { "$ref": "#/components/responses/not_found" } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": true, "category": "repos", "subcategory": "branches" } }, "post": { "summary": "Add app access restrictions", "description": "Protected branches are available in public repositories with GitHub Free and GitHub Free for organizations, and in public and private repositories with GitHub Pro, GitHub Team, GitHub Enterprise Cloud, and GitHub Enterprise Server. For more information, see [GitHub's products](https://docs.github.com/github/getting-started-with-github/githubs-products) in the GitHub Help documentation.\n\nGrants the specified apps push access for this branch. Only installed GitHub Apps with `write` access to the `contents` permission can be added as authorized actors on a protected branch.\n\n| Type | Description |\n| ------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------- |\n| `array` | The GitHub Apps that have push access to this branch. Use the app's `slug`. **Note**: The list of users, apps, and teams in total is limited to 100 items. |", "tags": [ "repos" ], "operationId": "repos/add-app-access-restrictions", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/repos#add-app-access-restrictions" }, "parameters": [ { "$ref": "#/components/parameters/owner" }, { "$ref": "#/components/parameters/repo" }, { "$ref": "#/components/parameters/branch" } ], "requestBody": { "required": false, "content": { "application/json": { "schema": { "oneOf": [ { "type": "object", "properties": { "apps": { "type": "array", "description": "apps parameter", "items": { "type": "string" } } }, "required": [ "apps" ], "example": { "apps": [ "my-app" ] } }, { "type": "array", "items": { "type": "string" } } ] } } } }, "responses": { "200": { "description": "Response", "content": { "application/json": { "schema": { "type": "array", "items": { "$ref": "#/components/schemas/integration" } }, "examples": { "default": { "$ref": "#/components/examples/integration-items" } } } } }, "422": { "$ref": "#/components/responses/validation_failed" } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": true, "requestBodyParameterName": "apps", "category": "repos", "subcategory": "branches" } }, "put": { "summary": "Set app access restrictions", "description": "Protected branches are available in public repositories with GitHub Free and GitHub Free for organizations, and in public and private repositories with GitHub Pro, GitHub Team, GitHub Enterprise Cloud, and GitHub Enterprise Server. For more information, see [GitHub's products](https://docs.github.com/github/getting-started-with-github/githubs-products) in the GitHub Help documentation.\n\nReplaces the list of apps that have push access to this branch. This removes all apps that previously had push access and grants push access to the new list of apps. Only installed GitHub Apps with `write` access to the `contents` permission can be added as authorized actors on a protected branch.\n\n| Type | Description |\n| ------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------- |\n| `array` | The GitHub Apps that have push access to this branch. Use the app's `slug`. **Note**: The list of users, apps, and teams in total is limited to 100 items. |", "tags": [ "repos" ], "operationId": "repos/set-app-access-restrictions", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/repos#set-app-access-restrictions" }, "parameters": [ { "$ref": "#/components/parameters/owner" }, { "$ref": "#/components/parameters/repo" }, { "$ref": "#/components/parameters/branch" } ], "requestBody": { "required": false, "content": { "application/json": { "schema": { "oneOf": [ { "type": "object", "properties": { "apps": { "type": "array", "description": "apps parameter", "items": { "type": "string" } } }, "required": [ "apps" ], "example": { "apps": [ "my-app" ] } }, { "type": "array", "items": { "type": "string" } } ] } } } }, "responses": { "200": { "description": "Response", "content": { "application/json": { "schema": { "type": "array", "items": { "$ref": "#/components/schemas/integration" } }, "examples": { "default": { "$ref": "#/components/examples/integration-items" } } } } }, "422": { "$ref": "#/components/responses/validation_failed" } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": true, "requestBodyParameterName": "apps", "category": "repos", "subcategory": "branches" } }, "delete": { "summary": "Remove app access restrictions", "description": "Protected branches are available in public repositories with GitHub Free and GitHub Free for organizations, and in public and private repositories with GitHub Pro, GitHub Team, GitHub Enterprise Cloud, and GitHub Enterprise Server. For more information, see [GitHub's products](https://docs.github.com/github/getting-started-with-github/githubs-products) in the GitHub Help documentation.\n\nRemoves the ability of an app to push to this branch. Only installed GitHub Apps with `write` access to the `contents` permission can be added as authorized actors on a protected branch.\n\n| Type | Description |\n| ------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------- |\n| `array` | The GitHub Apps that have push access to this branch. Use the app's `slug`. **Note**: The list of users, apps, and teams in total is limited to 100 items. |", "tags": [ "repos" ], "operationId": "repos/remove-app-access-restrictions", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/repos#remove-app-access-restrictions" }, "parameters": [ { "$ref": "#/components/parameters/owner" }, { "$ref": "#/components/parameters/repo" }, { "$ref": "#/components/parameters/branch" } ], "requestBody": { "content": { "application/json": { "schema": { "oneOf": [ { "type": "object", "properties": { "apps": { "type": "array", "description": "apps parameter", "items": { "type": "string" } } }, "required": [ "apps" ], "example": { "apps": [ "my-app" ] } }, { "type": "array", "items": { "type": "string" } } ] } } } }, "responses": { "200": { "description": "Response", "content": { "application/json": { "schema": { "type": "array", "items": { "$ref": "#/components/schemas/integration" } }, "examples": { "default": { "$ref": "#/components/examples/integration-items" } } } } }, "422": { "$ref": "#/components/responses/validation_failed" } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": true, "requestBodyParameterName": "apps", "category": "repos", "subcategory": "branches" } } }, "/repos/{owner}/{repo}/branches/{branch}/protection/restrictions/teams": { "get": { "summary": "Get teams with access to the protected branch", "description": "Protected branches are available in public repositories with GitHub Free and GitHub Free for organizations, and in public and private repositories with GitHub Pro, GitHub Team, GitHub Enterprise Cloud, and GitHub Enterprise Server. For more information, see [GitHub's products](https://docs.github.com/github/getting-started-with-github/githubs-products) in the GitHub Help documentation.\n\nLists the teams who have push access to this branch. The list includes child teams.", "tags": [ "repos" ], "operationId": "repos/get-teams-with-access-to-protected-branch", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/repos#list-teams-with-access-to-the-protected-branch" }, "parameters": [ { "$ref": "#/components/parameters/owner" }, { "$ref": "#/components/parameters/repo" }, { "$ref": "#/components/parameters/branch" } ], "responses": { "200": { "description": "Response", "content": { "application/json": { "schema": { "type": "array", "items": { "$ref": "#/components/schemas/team" } }, "examples": { "default": { "$ref": "#/components/examples/team-items" } } } } }, "404": { "$ref": "#/components/responses/not_found" } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": true, "category": "repos", "subcategory": "branches" } }, "post": { "summary": "Add team access restrictions", "description": "Protected branches are available in public repositories with GitHub Free and GitHub Free for organizations, and in public and private repositories with GitHub Pro, GitHub Team, GitHub Enterprise Cloud, and GitHub Enterprise Server. For more information, see [GitHub's products](https://docs.github.com/github/getting-started-with-github/githubs-products) in the GitHub Help documentation.\n\nGrants the specified teams push access for this branch. You can also give push access to child teams.\n\n| Type | Description |\n| ------- | ------------------------------------------------------------------------------------------------------------------------------------------ |\n| `array` | The teams that can have push access. Use the team's `slug`. **Note**: The list of users, apps, and teams in total is limited to 100 items. |", "tags": [ "repos" ], "operationId": "repos/add-team-access-restrictions", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/repos#add-team-access-restrictions" }, "parameters": [ { "$ref": "#/components/parameters/owner" }, { "$ref": "#/components/parameters/repo" }, { "$ref": "#/components/parameters/branch" } ], "requestBody": { "required": false, "content": { "application/json": { "schema": { "oneOf": [ { "type": "object", "properties": { "teams": { "type": "array", "description": "teams parameter", "items": { "type": "string" } } }, "required": [ "teams" ], "example": { "teams": [ "my-team" ] } }, { "type": "array", "description": "teams parameter", "items": { "type": "string" } } ] } } } }, "responses": { "200": { "description": "Response", "content": { "application/json": { "schema": { "type": "array", "items": { "$ref": "#/components/schemas/team" } }, "examples": { "default": { "$ref": "#/components/examples/team-items" } } } } }, "422": { "$ref": "#/components/responses/validation_failed" } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": true, "requestBodyParameterName": "teams", "category": "repos", "subcategory": "branches" } }, "put": { "summary": "Set team access restrictions", "description": "Protected branches are available in public repositories with GitHub Free and GitHub Free for organizations, and in public and private repositories with GitHub Pro, GitHub Team, GitHub Enterprise Cloud, and GitHub Enterprise Server. For more information, see [GitHub's products](https://docs.github.com/github/getting-started-with-github/githubs-products) in the GitHub Help documentation.\n\nReplaces the list of teams that have push access to this branch. This removes all teams that previously had push access and grants push access to the new list of teams. Team restrictions include child teams.\n\n| Type | Description |\n| ------- | ------------------------------------------------------------------------------------------------------------------------------------------ |\n| `array` | The teams that can have push access. Use the team's `slug`. **Note**: The list of users, apps, and teams in total is limited to 100 items. |", "tags": [ "repos" ], "operationId": "repos/set-team-access-restrictions", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/repos#set-team-access-restrictions" }, "parameters": [ { "$ref": "#/components/parameters/owner" }, { "$ref": "#/components/parameters/repo" }, { "$ref": "#/components/parameters/branch" } ], "requestBody": { "required": false, "content": { "application/json": { "schema": { "oneOf": [ { "type": "object", "properties": { "teams": { "type": "array", "description": "teams parameter", "items": { "type": "string" } } }, "required": [ "teams" ], "example": { "teams": [ "my-team" ] } }, { "type": "array", "description": "teams parameter", "items": { "type": "string" } } ] } } } }, "responses": { "200": { "description": "Response", "content": { "application/json": { "schema": { "type": "array", "items": { "$ref": "#/components/schemas/team" } }, "examples": { "default": { "$ref": "#/components/examples/team-items" } } } } }, "422": { "$ref": "#/components/responses/validation_failed" } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": true, "requestBodyParameterName": "teams", "category": "repos", "subcategory": "branches" } }, "delete": { "summary": "Remove team access restrictions", "description": "Protected branches are available in public repositories with GitHub Free and GitHub Free for organizations, and in public and private repositories with GitHub Pro, GitHub Team, GitHub Enterprise Cloud, and GitHub Enterprise Server. For more information, see [GitHub's products](https://docs.github.com/github/getting-started-with-github/githubs-products) in the GitHub Help documentation.\n\nRemoves the ability of a team to push to this branch. You can also remove push access for child teams.\n\n| Type | Description |\n| ------- | --------------------------------------------------------------------------------------------------------------------------------------------------- |\n| `array` | Teams that should no longer have push access. Use the team's `slug`. **Note**: The list of users, apps, and teams in total is limited to 100 items. |", "tags": [ "repos" ], "operationId": "repos/remove-team-access-restrictions", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/repos#remove-team-access-restrictions" }, "parameters": [ { "$ref": "#/components/parameters/owner" }, { "$ref": "#/components/parameters/repo" }, { "$ref": "#/components/parameters/branch" } ], "requestBody": { "content": { "application/json": { "schema": { "oneOf": [ { "type": "object", "properties": { "teams": { "type": "array", "description": "teams parameter", "items": { "type": "string" } } }, "required": [ "teams" ], "example": { "teams": [ "my-team" ] } }, { "type": "array", "description": "teams parameter", "items": { "type": "string" } } ] } } } }, "responses": { "200": { "description": "Response", "content": { "application/json": { "schema": { "type": "array", "items": { "$ref": "#/components/schemas/team" } }, "examples": { "default": { "$ref": "#/components/examples/team-items" } } } } }, "422": { "$ref": "#/components/responses/validation_failed" } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": true, "requestBodyParameterName": "teams", "category": "repos", "subcategory": "branches" } } }, "/repos/{owner}/{repo}/branches/{branch}/protection/restrictions/users": { "get": { "summary": "Get users with access to the protected branch", "description": "Protected branches are available in public repositories with GitHub Free and GitHub Free for organizations, and in public and private repositories with GitHub Pro, GitHub Team, GitHub Enterprise Cloud, and GitHub Enterprise Server. For more information, see [GitHub's products](https://docs.github.com/github/getting-started-with-github/githubs-products) in the GitHub Help documentation.\n\nLists the people who have push access to this branch.", "tags": [ "repos" ], "operationId": "repos/get-users-with-access-to-protected-branch", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/repos#list-users-with-access-to-the-protected-branch" }, "parameters": [ { "$ref": "#/components/parameters/owner" }, { "$ref": "#/components/parameters/repo" }, { "$ref": "#/components/parameters/branch" } ], "responses": { "200": { "description": "Response", "content": { "application/json": { "schema": { "type": "array", "items": { "$ref": "#/components/schemas/simple-user" } }, "examples": { "default": { "$ref": "#/components/examples/simple-user-items" } } } } }, "404": { "$ref": "#/components/responses/not_found" } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": true, "category": "repos", "subcategory": "branches" } }, "post": { "summary": "Add user access restrictions", "description": "Protected branches are available in public repositories with GitHub Free and GitHub Free for organizations, and in public and private repositories with GitHub Pro, GitHub Team, GitHub Enterprise Cloud, and GitHub Enterprise Server. For more information, see [GitHub's products](https://docs.github.com/github/getting-started-with-github/githubs-products) in the GitHub Help documentation.\n\nGrants the specified people push access for this branch.\n\n| Type | Description |\n| ------- | ----------------------------------------------------------------------------------------------------------------------------- |\n| `array` | Usernames for people who can have push access. **Note**: The list of users, apps, and teams in total is limited to 100 items. |", "tags": [ "repos" ], "operationId": "repos/add-user-access-restrictions", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/repos#add-user-access-restrictions" }, "parameters": [ { "$ref": "#/components/parameters/owner" }, { "$ref": "#/components/parameters/repo" }, { "$ref": "#/components/parameters/branch" } ], "requestBody": { "required": false, "content": { "application/json": { "schema": { "oneOf": [ { "type": "object", "properties": { "users": { "type": "array", "description": "users parameter", "items": { "type": "string" } } }, "required": [ "users" ], "example": { "users": [ "mona" ] } }, { "type": "array", "items": { "type": "string" } } ] } } } }, "responses": { "200": { "description": "Response", "content": { "application/json": { "schema": { "type": "array", "items": { "$ref": "#/components/schemas/simple-user" } }, "examples": { "default": { "$ref": "#/components/examples/simple-user-items" } } } } }, "422": { "$ref": "#/components/responses/validation_failed" } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": true, "requestBodyParameterName": "users", "category": "repos", "subcategory": "branches" } }, "put": { "summary": "Set user access restrictions", "description": "Protected branches are available in public repositories with GitHub Free and GitHub Free for organizations, and in public and private repositories with GitHub Pro, GitHub Team, GitHub Enterprise Cloud, and GitHub Enterprise Server. For more information, see [GitHub's products](https://docs.github.com/github/getting-started-with-github/githubs-products) in the GitHub Help documentation.\n\nReplaces the list of people that have push access to this branch. This removes all people that previously had push access and grants push access to the new list of people.\n\n| Type | Description |\n| ------- | ----------------------------------------------------------------------------------------------------------------------------- |\n| `array` | Usernames for people who can have push access. **Note**: The list of users, apps, and teams in total is limited to 100 items. |", "tags": [ "repos" ], "operationId": "repos/set-user-access-restrictions", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/repos#set-user-access-restrictions" }, "parameters": [ { "$ref": "#/components/parameters/owner" }, { "$ref": "#/components/parameters/repo" }, { "$ref": "#/components/parameters/branch" } ], "requestBody": { "required": false, "content": { "application/json": { "schema": { "oneOf": [ { "type": "object", "properties": { "users": { "type": "array", "description": "users parameter", "items": { "type": "string" } } }, "required": [ "users" ], "example": { "users": [ "mona" ] } }, { "type": "array", "items": { "type": "string" } } ] } } } }, "responses": { "200": { "description": "Response", "content": { "application/json": { "schema": { "type": "array", "items": { "$ref": "#/components/schemas/simple-user" } }, "examples": { "default": { "$ref": "#/components/examples/simple-user-items" } } } } }, "422": { "$ref": "#/components/responses/validation_failed" } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": true, "requestBodyParameterName": "users", "category": "repos", "subcategory": "branches" } }, "delete": { "summary": "Remove user access restrictions", "description": "Protected branches are available in public repositories with GitHub Free and GitHub Free for organizations, and in public and private repositories with GitHub Pro, GitHub Team, GitHub Enterprise Cloud, and GitHub Enterprise Server. For more information, see [GitHub's products](https://docs.github.com/github/getting-started-with-github/githubs-products) in the GitHub Help documentation.\n\nRemoves the ability of a user to push to this branch.\n\n| Type | Description |\n| ------- | --------------------------------------------------------------------------------------------------------------------------------------------- |\n| `array` | Usernames of the people who should no longer have push access. **Note**: The list of users, apps, and teams in total is limited to 100 items. |", "tags": [ "repos" ], "operationId": "repos/remove-user-access-restrictions", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/repos#remove-user-access-restrictions" }, "parameters": [ { "$ref": "#/components/parameters/owner" }, { "$ref": "#/components/parameters/repo" }, { "$ref": "#/components/parameters/branch" } ], "requestBody": { "content": { "application/json": { "schema": { "oneOf": [ { "type": "object", "properties": { "users": { "type": "array", "description": "users parameter", "items": { "type": "string" } } }, "required": [ "users" ], "example": { "users": [ "mona" ] } }, { "type": "array", "items": { "type": "string" } } ] } } } }, "responses": { "200": { "description": "Response", "content": { "application/json": { "schema": { "type": "array", "items": { "$ref": "#/components/schemas/simple-user" } }, "examples": { "default": { "$ref": "#/components/examples/simple-user-items" } } } } }, "422": { "$ref": "#/components/responses/validation_failed" } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": true, "requestBodyParameterName": "users", "category": "repos", "subcategory": "branches" } } }, "/repos/{owner}/{repo}/check-runs": { "post": { "summary": "Create a check run", "description": "**Note:** The Checks API only looks for pushes in the repository where the check suite or check run were created. Pushes to a branch in a forked repository are not detected and return an empty `pull_requests` array.\n\nCreates a new check run for a specific commit in a repository. Your GitHub App must have the `checks:write` permission to create check runs.\n\nIn a check suite, GitHub limits the number of check runs with the same name to 1000. Once these check runs exceed 1000, GitHub will start to automatically delete older check runs.", "tags": [ "checks" ], "operationId": "checks/create", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/checks#create-a-check-run" }, "parameters": [ { "$ref": "#/components/parameters/owner" }, { "$ref": "#/components/parameters/repo" } ], "requestBody": { "required": true, "content": { "application/json": { "schema": { "type": "object", "properties": { "name": { "type": "string", "description": "The name of the check. For example, \"code-coverage\"." }, "head_sha": { "type": "string", "description": "The SHA of the commit." }, "details_url": { "type": "string", "description": "The URL of the integrator's site that has the full details of the check. If the integrator does not provide this, then the homepage of the GitHub app is used." }, "external_id": { "type": "string", "description": "A reference for the run on the integrator's system." }, "status": { "type": "string", "description": "The current status. Can be one of `queued`, `in_progress`, or `completed`.", "enum": [ "queued", "in_progress", "completed" ], "default": "queued" }, "started_at": { "type": "string", "format": "date-time", "description": "The time that the check run began. This is a timestamp in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format: `YYYY-MM-DDTHH:MM:SSZ`." }, "conclusion": { "type": "string", "description": "**Required if you provide `completed_at` or a `status` of `completed`**. The final conclusion of the check. Can be one of `action_required`, `cancelled`, `failure`, `neutral`, `success`, `skipped`, `stale`, or `timed_out`. When the conclusion is `action_required`, additional details should be provided on the site specified by `details_url`. \n**Note:** Providing `conclusion` will automatically set the `status` parameter to `completed`. You cannot change a check run conclusion to `stale`, only GitHub can set this.", "enum": [ "action_required", "cancelled", "failure", "neutral", "success", "skipped", "stale", "timed_out" ] }, "completed_at": { "type": "string", "format": "date-time", "description": "The time the check completed. This is a timestamp in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format: `YYYY-MM-DDTHH:MM:SSZ`." }, "output": { "type": "object", "description": "Check runs can accept a variety of data in the `output` object, including a `title` and `summary` and can optionally provide descriptive details about the run. See the [`output` object](https://docs.github.com/enterprise-server@3.0/rest/reference/checks#output-object) description.", "properties": { "title": { "type": "string", "description": "The title of the check run." }, "summary": { "type": "string", "maxLength": 65535, "description": "The summary of the check run. This parameter supports Markdown." }, "text": { "type": "string", "maxLength": 65535, "description": "The details of the check run. This parameter supports Markdown." }, "annotations": { "type": "array", "description": "Adds information from your analysis to specific lines of code. Annotations are visible on GitHub in the **Checks** and **Files changed** tab of the pull request. The Checks API limits the number of annotations to a maximum of 50 per API request. To create more than 50 annotations, you have to make multiple requests to the [Update a check run](https://docs.github.com/enterprise-server@3.0/rest/reference/checks#update-a-check-run) endpoint. Each time you update the check run, annotations are appended to the list of annotations that already exist for the check run. For details about how you can view annotations on GitHub, see \"[About status checks](https://docs.github.com/articles/about-status-checks#checks)\". See the [`annotations` object](https://docs.github.com/enterprise-server@3.0/rest/reference/checks#annotations-object) description for details about how to use this parameter.", "maxItems": 50, "items": { "type": "object", "properties": { "path": { "type": "string", "description": "The path of the file to add an annotation to. For example, `assets/css/main.css`." }, "start_line": { "type": "integer", "description": "The start line of the annotation." }, "end_line": { "type": "integer", "description": "The end line of the annotation." }, "start_column": { "type": "integer", "description": "The start column of the annotation. Annotations only support `start_column` and `end_column` on the same line. Omit this parameter if `start_line` and `end_line` have different values." }, "end_column": { "type": "integer", "description": "The end column of the annotation. Annotations only support `start_column` and `end_column` on the same line. Omit this parameter if `start_line` and `end_line` have different values." }, "annotation_level": { "type": "string", "description": "The level of the annotation. Can be one of `notice`, `warning`, or `failure`.", "enum": [ "notice", "warning", "failure" ] }, "message": { "type": "string", "description": "A short description of the feedback for these lines of code. The maximum size is 64 KB." }, "title": { "type": "string", "description": "The title that represents the annotation. The maximum size is 255 characters." }, "raw_details": { "type": "string", "description": "Details about this annotation. The maximum size is 64 KB." } }, "required": [ "path", "start_line", "end_line", "annotation_level", "message" ] } }, "images": { "type": "array", "description": "Adds images to the output displayed in the GitHub pull request UI. See the [`images` object](https://docs.github.com/enterprise-server@3.0/rest/reference/checks#images-object) description for details.", "items": { "type": "object", "properties": { "alt": { "type": "string", "description": "The alternative text for the image." }, "image_url": { "type": "string", "description": "The full URL of the image." }, "caption": { "type": "string", "description": "A short image description." } }, "required": [ "alt", "image_url" ] } } }, "required": [ "title", "summary" ] }, "actions": { "type": "array", "description": "Displays a button on GitHub that can be clicked to alert your app to do additional tasks. For example, a code linting app can display a button that automatically fixes detected errors. The button created in this object is displayed after the check run completes. When a user clicks the button, GitHub sends the [`check_run.requested_action` webhook](https://docs.github.com/enterprise-server@3.0/webhooks/event-payloads/#check_run) to your app. Each action includes a `label`, `identifier` and `description`. A maximum of three actions are accepted. See the [`actions` object](https://docs.github.com/enterprise-server@3.0/rest/reference/checks#actions-object) description. To learn more about check runs and requested actions, see \"[Check runs and requested actions](https://docs.github.com/enterprise-server@3.0/rest/reference/checks#check-runs-and-requested-actions).\"", "maxItems": 3, "items": { "type": "object", "properties": { "label": { "type": "string", "maxLength": 20, "description": "The text to be displayed on a button in the web UI. The maximum size is 20 characters." }, "description": { "type": "string", "maxLength": 40, "description": "A short explanation of what this action would do. The maximum size is 40 characters." }, "identifier": { "type": "string", "maxLength": 20, "description": "A reference for the action on the integrator's system. The maximum size is 20 characters." } }, "required": [ "label", "description", "identifier" ] } } }, "required": [ "name", "head_sha" ], "oneOf": [ { "properties": { "status": { "enum": [ "completed" ] } }, "required": [ "status", "conclusion" ], "additionalProperties": true }, { "properties": { "status": { "enum": [ "queued", "in_progress" ] } }, "additionalProperties": true } ] }, "examples": { "example-of-in-progress-conclusion": { "summary": "Response for in_progress conclusion", "value": { "name": "mighty_readme", "head_sha": "ce587453ced02b1526dfb4cb910479d431683101", "status": "in_progress", "external_id": "42", "started_at": "2018-05-04T01:14:52Z", "output": { "title": "Mighty Readme report", "summary": "", "text": "" } } }, "example-of-completed-conclusion": { "summary": "Response for completed conclusion", "value": { "name": "mighty_readme", "head_sha": "ce587453ced02b1526dfb4cb910479d431683101", "status": "completed", "started_at": "2017-11-30T19:39:10Z", "conclusion": "success", "completed_at": "2017-11-30T19:49:10Z", "output": { "title": "Mighty Readme report", "summary": "There are 0 failures, 2 warnings, and 1 notices.", "text": "You may have some misspelled words on lines 2 and 4. You also may want to add a section in your README about how to install your app.", "annotations": [ { "path": "README.md", "annotation_level": "warning", "title": "Spell Checker", "message": "Check your spelling for 'banaas'.", "raw_details": "Do you mean 'bananas' or 'banana'?", "start_line": 2, "end_line": 2 }, { "path": "README.md", "annotation_level": "warning", "title": "Spell Checker", "message": "Check your spelling for 'aples'", "raw_details": "Do you mean 'apples' or 'Naples'", "start_line": 4, "end_line": 4 } ], "images": [ { "alt": "Super bananas", "image_url": "http://example.com/images/42" } ] }, "actions": [ { "label": "Fix", "identifier": "fix_errors", "description": "Allow us to fix these errors for you" } ] } } } } } }, "responses": { "201": { "description": "Response", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/check-run" }, "examples": { "example-of-completed-conclusion": { "$ref": "#/components/examples/check-run-example-of-completed-conclusion" } } } } } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": true, "category": "checks", "subcategory": "runs" } } }, "/repos/{owner}/{repo}/check-runs/{check_run_id}": { "get": { "summary": "Get a check run", "description": "**Note:** The Checks API only looks for pushes in the repository where the check suite or check run were created. Pushes to a branch in a forked repository are not detected and return an empty `pull_requests` array.\n\nGets a single check run using its `id`. GitHub Apps must have the `checks:read` permission on a private repository or pull access to a public repository to get check runs. OAuth Apps and authenticated users must have the `repo` scope to get check runs in a private repository.", "tags": [ "checks" ], "operationId": "checks/get", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/checks#get-a-check-run" }, "parameters": [ { "$ref": "#/components/parameters/owner" }, { "$ref": "#/components/parameters/repo" }, { "$ref": "#/components/parameters/check-run-id" } ], "responses": { "200": { "description": "Response", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/check-run" }, "examples": { "default": { "$ref": "#/components/examples/check-run" } } } } } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": true, "category": "checks", "subcategory": "runs" } }, "patch": { "summary": "Update a check run", "description": "**Note:** The Checks API only looks for pushes in the repository where the check suite or check run were created. Pushes to a branch in a forked repository are not detected and return an empty `pull_requests` array.\n\nUpdates a check run for a specific commit in a repository. Your GitHub App must have the `checks:write` permission to edit check runs.", "tags": [ "checks" ], "operationId": "checks/update", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/checks#update-a-check-run" }, "parameters": [ { "$ref": "#/components/parameters/owner" }, { "$ref": "#/components/parameters/repo" }, { "$ref": "#/components/parameters/check-run-id" } ], "requestBody": { "required": true, "content": { "application/json": { "schema": { "type": "object", "properties": { "name": { "type": "string", "description": "The name of the check. For example, \"code-coverage\"." }, "details_url": { "type": "string", "description": "The URL of the integrator's site that has the full details of the check." }, "external_id": { "type": "string", "description": "A reference for the run on the integrator's system." }, "started_at": { "type": "string", "format": "date-time", "description": "This is a timestamp in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format: `YYYY-MM-DDTHH:MM:SSZ`." }, "status": { "type": "string", "description": "The current status. Can be one of `queued`, `in_progress`, or `completed`.", "enum": [ "queued", "in_progress", "completed" ] }, "conclusion": { "type": "string", "description": "**Required if you provide `completed_at` or a `status` of `completed`**. The final conclusion of the check. Can be one of `action_required`, `cancelled`, `failure`, `neutral`, `success`, `skipped`, `stale`, or `timed_out`. \n**Note:** Providing `conclusion` will automatically set the `status` parameter to `completed`. You cannot change a check run conclusion to `stale`, only GitHub can set this.", "enum": [ "action_required", "cancelled", "failure", "neutral", "success", "skipped", "stale", "timed_out" ] }, "completed_at": { "type": "string", "format": "date-time", "description": "The time the check completed. This is a timestamp in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format: `YYYY-MM-DDTHH:MM:SSZ`." }, "output": { "type": "object", "description": "Check runs can accept a variety of data in the `output` object, including a `title` and `summary` and can optionally provide descriptive details about the run. See the [`output` object](https://docs.github.com/enterprise-server@3.0/rest/reference/checks#output-object-1) description.", "properties": { "title": { "type": "string", "description": "**Required**." }, "summary": { "type": "string", "description": "Can contain Markdown.", "maxLength": 65535 }, "text": { "type": "string", "description": "Can contain Markdown.", "maxLength": 65535 }, "annotations": { "type": "array", "description": "Adds information from your analysis to specific lines of code. Annotations are visible in GitHub's pull request UI. Annotations are visible in GitHub's pull request UI. The Checks API limits the number of annotations to a maximum of 50 per API request. To create more than 50 annotations, you have to make multiple requests to the [Update a check run](https://docs.github.com/enterprise-server@3.0/rest/reference/checks#update-a-check-run) endpoint. Each time you update the check run, annotations are appended to the list of annotations that already exist for the check run. For details about annotations in the UI, see \"[About status checks](https://docs.github.com/articles/about-status-checks#checks)\". See the [`annotations` object](https://docs.github.com/enterprise-server@3.0/rest/reference/checks#annotations-object-1) description for details.", "maxItems": 50, "items": { "type": "object", "properties": { "path": { "type": "string", "description": "The path of the file to add an annotation to. For example, `assets/css/main.css`." }, "start_line": { "type": "integer", "description": "The start line of the annotation." }, "end_line": { "type": "integer", "description": "The end line of the annotation." }, "start_column": { "type": "integer", "description": "The start column of the annotation. Annotations only support `start_column` and `end_column` on the same line. Omit this parameter if `start_line` and `end_line` have different values." }, "end_column": { "type": "integer", "description": "The end column of the annotation. Annotations only support `start_column` and `end_column` on the same line. Omit this parameter if `start_line` and `end_line` have different values." }, "annotation_level": { "type": "string", "description": "The level of the annotation. Can be one of `notice`, `warning`, or `failure`.", "enum": [ "notice", "warning", "failure" ] }, "message": { "type": "string", "description": "A short description of the feedback for these lines of code. The maximum size is 64 KB." }, "title": { "type": "string", "description": "The title that represents the annotation. The maximum size is 255 characters." }, "raw_details": { "type": "string", "description": "Details about this annotation. The maximum size is 64 KB." } }, "required": [ "path", "start_line", "end_line", "annotation_level", "message" ] } }, "images": { "type": "array", "description": "Adds images to the output displayed in the GitHub pull request UI. See the [`images` object](https://docs.github.com/enterprise-server@3.0/rest/reference/checks#annotations-object-1) description for details.", "items": { "type": "object", "properties": { "alt": { "type": "string", "description": "The alternative text for the image." }, "image_url": { "type": "string", "description": "The full URL of the image." }, "caption": { "type": "string", "description": "A short image description." } }, "required": [ "alt", "image_url" ] } } }, "required": [ "summary" ] }, "actions": { "type": "array", "description": "Possible further actions the integrator can perform, which a user may trigger. Each action includes a `label`, `identifier` and `description`. A maximum of three actions are accepted. See the [`actions` object](https://docs.github.com/enterprise-server@3.0/rest/reference/checks#actions-object) description. To learn more about check runs and requested actions, see \"[Check runs and requested actions](https://docs.github.com/enterprise-server@3.0/rest/reference/checks#check-runs-and-requested-actions).\"", "maxItems": 3, "items": { "type": "object", "properties": { "label": { "type": "string", "maxLength": 20, "description": "The text to be displayed on a button in the web UI. The maximum size is 20 characters." }, "description": { "type": "string", "maxLength": 40, "description": "A short explanation of what this action would do. The maximum size is 40 characters." }, "identifier": { "type": "string", "maxLength": 20, "description": "A reference for the action on the integrator's system. The maximum size is 20 characters." } }, "required": [ "label", "description", "identifier" ] } } }, "anyOf": [ { "properties": { "status": { "enum": [ "completed" ] } }, "required": [ "conclusion" ], "additionalProperties": true }, { "properties": { "status": { "enum": [ "queued", "in_progress" ] } }, "additionalProperties": true } ] }, "example": { "name": "mighty_readme", "started_at": "2018-05-04T01:14:52Z", "status": "completed", "conclusion": "success", "completed_at": "2018-05-04T01:14:52Z", "output": { "title": "Mighty Readme report", "summary": "There are 0 failures, 2 warnings, and 1 notices.", "text": "You may have some misspelled words on lines 2 and 4. You also may want to add a section in your README about how to install your app.", "annotations": [ { "path": "README.md", "annotation_level": "warning", "title": "Spell Checker", "message": "Check your spelling for 'banaas'.", "raw_details": "Do you mean 'bananas' or 'banana'?", "start_line": 2, "end_line": 2 }, { "path": "README.md", "annotation_level": "warning", "title": "Spell Checker", "message": "Check your spelling for 'aples'", "raw_details": "Do you mean 'apples' or 'Naples'", "start_line": 4, "end_line": 4 } ], "images": [ { "alt": "Super bananas", "image_url": "http://example.com/images/42" } ] } } } } }, "responses": { "200": { "description": "Response", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/check-run" }, "examples": { "default": { "$ref": "#/components/examples/check-run" } } } } } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": true, "category": "checks", "subcategory": "runs" } } }, "/repos/{owner}/{repo}/check-runs/{check_run_id}/annotations": { "get": { "summary": "List check run annotations", "description": "Lists annotations for a check run using the annotation `id`. GitHub Apps must have the `checks:read` permission on a private repository or pull access to a public repository to get annotations for a check run. OAuth Apps and authenticated users must have the `repo` scope to get annotations for a check run in a private repository.", "tags": [ "checks" ], "operationId": "checks/list-annotations", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/checks#list-check-run-annotations" }, "parameters": [ { "$ref": "#/components/parameters/owner" }, { "$ref": "#/components/parameters/repo" }, { "$ref": "#/components/parameters/check-run-id" }, { "$ref": "#/components/parameters/per-page" }, { "$ref": "#/components/parameters/page" } ], "responses": { "200": { "description": "Response", "content": { "application/json": { "schema": { "type": "array", "items": { "$ref": "#/components/schemas/check-annotation" } }, "examples": { "default": { "$ref": "#/components/examples/check-annotation-items" } } } }, "headers": { "Link": { "$ref": "#/components/headers/link" } } } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": true, "category": "checks", "subcategory": "runs" } } }, "/repos/{owner}/{repo}/check-suites": { "post": { "summary": "Create a check suite", "description": "**Note:** The Checks API only looks for pushes in the repository where the check suite or check run were created. Pushes to a branch in a forked repository are not detected and return an empty `pull_requests` array and a `null` value for `head_branch`.\n\nBy default, check suites are automatically created when you create a [check run](https://docs.github.com/enterprise-server@3.0/rest/reference/checks#check-runs). You only need to use this endpoint for manually creating check suites when you've disabled automatic creation using \"[Update repository preferences for check suites](https://docs.github.com/enterprise-server@3.0/rest/reference/checks#update-repository-preferences-for-check-suites)\". Your GitHub App must have the `checks:write` permission to create check suites.", "tags": [ "checks" ], "operationId": "checks/create-suite", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/checks#create-a-check-suite" }, "parameters": [ { "$ref": "#/components/parameters/owner" }, { "$ref": "#/components/parameters/repo" } ], "requestBody": { "required": true, "content": { "application/json": { "schema": { "type": "object", "properties": { "head_sha": { "type": "string", "description": "The sha of the head commit." } }, "required": [ "head_sha" ] }, "example": { "head_sha": "d6fde92930d4715a2b49857d24b940956b26d2d3" } } } }, "responses": { "200": { "description": "when the suite already existed", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/check-suite" }, "examples": { "default": { "$ref": "#/components/examples/check-suite" } } } } }, "201": { "description": "Response when the suite was created", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/check-suite" }, "examples": { "default": { "$ref": "#/components/examples/check-suite" } } } } } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": true, "category": "checks", "subcategory": "suites" } } }, "/repos/{owner}/{repo}/check-suites/preferences": { "patch": { "summary": "Update repository preferences for check suites", "description": "Changes the default automatic flow when creating check suites. By default, a check suite is automatically created each time code is pushed to a repository. When you disable the automatic creation of check suites, you can manually [Create a check suite](https://docs.github.com/enterprise-server@3.0/rest/reference/checks#create-a-check-suite). You must have admin permissions in the repository to set preferences for check suites.", "tags": [ "checks" ], "operationId": "checks/set-suites-preferences", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/checks#update-repository-preferences-for-check-suites" }, "parameters": [ { "$ref": "#/components/parameters/owner" }, { "$ref": "#/components/parameters/repo" } ], "requestBody": { "required": true, "content": { "application/json": { "schema": { "type": "object", "properties": { "auto_trigger_checks": { "type": "array", "description": "Enables or disables automatic creation of CheckSuite events upon pushes to the repository. Enabled by default. See the [`auto_trigger_checks` object](https://docs.github.com/enterprise-server@3.0/rest/reference/checks#auto_trigger_checks-object) description for details.", "items": { "type": "object", "properties": { "app_id": { "type": "integer", "description": "The `id` of the GitHub App." }, "setting": { "type": "boolean", "description": "Set to `true` to enable automatic creation of CheckSuite events upon pushes to the repository, or `false` to disable them.", "default": true } }, "required": [ "app_id", "setting" ] } } } }, "example": { "auto_trigger_checks": [ { "app_id": 4, "setting": false } ] } } } }, "responses": { "200": { "description": "Response", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/check-suite-preference" }, "examples": { "default": { "$ref": "#/components/examples/check-suite-preference" } } } } } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": true, "category": "checks", "subcategory": "suites" } } }, "/repos/{owner}/{repo}/check-suites/{check_suite_id}": { "get": { "summary": "Get a check suite", "description": "**Note:** The Checks API only looks for pushes in the repository where the check suite or check run were created. Pushes to a branch in a forked repository are not detected and return an empty `pull_requests` array and a `null` value for `head_branch`.\n\nGets a single check suite using its `id`. GitHub Apps must have the `checks:read` permission on a private repository or pull access to a public repository to get check suites. OAuth Apps and authenticated users must have the `repo` scope to get check suites in a private repository.", "tags": [ "checks" ], "operationId": "checks/get-suite", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/checks#get-a-check-suite" }, "parameters": [ { "$ref": "#/components/parameters/owner" }, { "$ref": "#/components/parameters/repo" }, { "$ref": "#/components/parameters/check-suite-id" } ], "responses": { "200": { "description": "Response", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/check-suite" }, "examples": { "default": { "$ref": "#/components/examples/check-suite" } } } } } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": true, "category": "checks", "subcategory": "suites" } } }, "/repos/{owner}/{repo}/check-suites/{check_suite_id}/check-runs": { "get": { "summary": "List check runs in a check suite", "description": "**Note:** The Checks API only looks for pushes in the repository where the check suite or check run were created. Pushes to a branch in a forked repository are not detected and return an empty `pull_requests` array.\n\nLists check runs for a check suite using its `id`. GitHub Apps must have the `checks:read` permission on a private repository or pull access to a public repository to get check runs. OAuth Apps and authenticated users must have the `repo` scope to get check runs in a private repository.", "tags": [ "checks" ], "operationId": "checks/list-for-suite", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/checks#list-check-runs-in-a-check-suite" }, "parameters": [ { "$ref": "#/components/parameters/owner" }, { "$ref": "#/components/parameters/repo" }, { "$ref": "#/components/parameters/check-suite-id" }, { "$ref": "#/components/parameters/check-name" }, { "$ref": "#/components/parameters/status" }, { "name": "filter", "description": "Filters check runs by their `completed_at` timestamp. Can be one of `latest` (returning the most recent check runs) or `all`.", "in": "query", "required": false, "schema": { "type": "string", "enum": [ "latest", "all" ], "default": "latest" } }, { "$ref": "#/components/parameters/per-page" }, { "$ref": "#/components/parameters/page" } ], "responses": { "200": { "description": "Response", "content": { "application/json": { "schema": { "type": "object", "required": [ "total_count", "check_runs" ], "properties": { "total_count": { "type": "integer" }, "check_runs": { "type": "array", "items": { "$ref": "#/components/schemas/check-run" } } } }, "examples": { "default": { "$ref": "#/components/examples/check-run-paginated" } } } }, "headers": { "Link": { "$ref": "#/components/headers/link" } } } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": true, "category": "checks", "subcategory": "runs" } } }, "/repos/{owner}/{repo}/check-suites/{check_suite_id}/rerequest": { "post": { "summary": "Rerequest a check suite", "description": "Triggers GitHub to rerequest an existing check suite, without pushing new code to a repository. This endpoint will trigger the [`check_suite` webhook](https://docs.github.com/enterprise-server@3.0/webhooks/event-payloads/#check_suite) event with the action `rerequested`. When a check suite is `rerequested`, its `status` is reset to `queued` and the `conclusion` is cleared.\n\nTo rerequest a check suite, your GitHub App must have the `checks:read` permission on a private repository or pull access to a public repository.", "tags": [ "checks" ], "operationId": "checks/rerequest-suite", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/checks#rerequest-a-check-suite" }, "parameters": [ { "$ref": "#/components/parameters/owner" }, { "$ref": "#/components/parameters/repo" }, { "$ref": "#/components/parameters/check-suite-id" } ], "responses": { "201": { "description": "Response", "content": { "application/json": { "schema": { "type": "object", "properties": { }, "additionalProperties": false } } } } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": true, "category": "checks", "subcategory": "suites" } } }, "/repos/{owner}/{repo}/code-scanning/alerts": { "get": { "summary": "List code scanning alerts for a repository", "description": "Lists all open code scanning alerts for the default branch (usually `main`\nor `master`). You must use an access token with the `security_events` scope to use\nthis endpoint. GitHub Apps must have the `security_events` read permission to use\nthis endpoint.\n\nThe response includes a `most_recent_instance` object.\nThis provides details of the most recent instance of this alert\nfor the default branch or for the specified Git reference\n(if you used `ref` in the request).", "tags": [ "code-scanning" ], "operationId": "code-scanning/list-alerts-for-repo", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/code-scanning#list-code-scanning-alerts-for-a-repository" }, "parameters": [ { "$ref": "#/components/parameters/owner" }, { "$ref": "#/components/parameters/repo" }, { "$ref": "#/components/parameters/tool-name" }, { "$ref": "#/components/parameters/tool-guid" }, { "$ref": "#/components/parameters/page" }, { "$ref": "#/components/parameters/per-page" }, { "$ref": "#/components/parameters/git-ref" }, { "name": "state", "description": "Set to `open`, `fixed`, or `dismissed` to list code scanning alerts in a specific state.", "in": "query", "required": false, "schema": { "$ref": "#/components/schemas/code-scanning-alert-state" } } ], "responses": { "200": { "description": "Response", "content": { "application/json": { "schema": { "type": "array", "items": { "$ref": "#/components/schemas/code-scanning-alert-items" } }, "examples": { "default": { "$ref": "#/components/examples/code-scanning-alert-items" } } } } }, "403": { "$ref": "#/components/responses/code_scanning_forbidden_read" }, "404": { "$ref": "#/components/responses/not_found" }, "503": { "$ref": "#/components/responses/service_unavailable" } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": true, "category": "code-scanning", "subcategory": null } } }, "/repos/{owner}/{repo}/code-scanning/alerts/{alert_number}": { "get": { "summary": "Get a code scanning alert", "description": "Gets a single code scanning alert. You must use an access token with the `security_events` scope to use this endpoint. GitHub Apps must have the `security_events` read permission to use this endpoint.\n\n**Deprecation notice**:\nThe instances field is deprecated and will, in future, not be included in the response for this endpoint. The example response reflects this change. The same information can now be retrieved via a GET request to the URL specified by `instances_url`.", "tags": [ "code-scanning" ], "operationId": "code-scanning/get-alert", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/code-scanning#get-a-code-scanning-alert" }, "parameters": [ { "$ref": "#/components/parameters/owner" }, { "$ref": "#/components/parameters/repo" }, { "$ref": "#/components/parameters/alert-number" } ], "responses": { "200": { "description": "Response", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/code-scanning-alert" }, "examples": { "default": { "$ref": "#/components/examples/code-scanning-alert" } } } } }, "403": { "$ref": "#/components/responses/code_scanning_forbidden_read" }, "404": { "$ref": "#/components/responses/not_found" }, "503": { "$ref": "#/components/responses/service_unavailable" } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": true, "category": "code-scanning", "subcategory": null } }, "patch": { "summary": "Update a code scanning alert", "description": "Updates the status of a single code scanning alert. You must use an access token with the `security_events` scope to use this endpoint. GitHub Apps must have the `security_events` write permission to use this endpoint.", "operationId": "code-scanning/update-alert", "tags": [ "code-scanning" ], "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/code-scanning#update-a-code-scanning-alert" }, "parameters": [ { "$ref": "#/components/parameters/owner" }, { "$ref": "#/components/parameters/repo" }, { "$ref": "#/components/parameters/alert-number" } ], "requestBody": { "required": true, "content": { "application/json": { "schema": { "type": "object", "properties": { "state": { "$ref": "#/components/schemas/code-scanning-alert-set-state" }, "dismissed_reason": { "$ref": "#/components/schemas/code-scanning-alert-dismissed-reason" } }, "required": [ "state" ] }, "example": { "state": "dismissed", "dismissed_reason": "false positive" } } } }, "responses": { "200": { "description": "Response", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/code-scanning-alert" }, "examples": { "default": { "$ref": "#/components/examples/code-scanning-alert-dismissed" } } } } }, "403": { "$ref": "#/components/responses/code_scanning_forbidden_write" }, "404": { "$ref": "#/components/responses/not_found" }, "503": { "$ref": "#/components/responses/service_unavailable" } }, "x-github": { "enabledForGitHubApps": true, "githubCloudOnly": false, "category": "code-scanning" } } }, "/repos/{owner}/{repo}/code-scanning/analyses": { "get": { "summary": "List code scanning analyses for a repository", "description": "Lists the details of all code scanning analyses for a repository,\nstarting with the most recent.\nThe response is paginated and you can use the `page` and `per_page` parameters\nto list the analyses you're interested in.\nBy default 30 analyses are listed per page.\n\nThe `rules_count` field in the response give the number of rules\nthat were run in the analysis.\nFor very old analyses this data is not available,\nand `0` is returned in this field.\n\nYou must use an access token with the `security_events` scope to use this endpoint.\nGitHub Apps must have the `security_events` read permission to use this endpoint.\n\n**Deprecation notice**:\nThe `tool_name` field is deprecated and will, in future, not be included in the response for this endpoint. The example response reflects this change. The tool name can now be found inside the `tool` field.", "operationId": "code-scanning/list-recent-analyses", "tags": [ "code-scanning" ], "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/code-scanning#list-code-scanning-analyses-for-a-repository" }, "parameters": [ { "$ref": "#/components/parameters/owner" }, { "$ref": "#/components/parameters/repo" }, { "$ref": "#/components/parameters/tool-name" }, { "$ref": "#/components/parameters/tool-guid" }, { "$ref": "#/components/parameters/page" }, { "$ref": "#/components/parameters/per-page" }, { "name": "ref", "in": "query", "description": "The Git reference for the analyses you want to list. The `ref` for a branch can be formatted either as `refs/heads/` or simply ``. To reference a pull request use `refs/pull//merge`.", "required": false, "schema": { "$ref": "#/components/schemas/code-scanning-ref" } }, { "name": "sarif_id", "in": "query", "description": "Filter analyses belonging to the same SARIF upload.", "required": false, "schema": { "$ref": "#/components/schemas/code-scanning-analysis-sarif-id" } } ], "responses": { "200": { "description": "Response", "content": { "application/json": { "schema": { "type": "array", "items": { "$ref": "#/components/schemas/code-scanning-analysis" } }, "examples": { "default": { "$ref": "#/components/examples/code-scanning-analysis-items" } } } } }, "403": { "$ref": "#/components/responses/code_scanning_forbidden_read" }, "404": { "$ref": "#/components/responses/not_found" }, "503": { "$ref": "#/components/responses/service_unavailable" } }, "x-github": { "enabledForGitHubApps": true, "githubCloudOnly": false, "category": "code-scanning" } } }, "/repos/{owner}/{repo}/code-scanning/sarifs": { "post": { "summary": "Upload an analysis as SARIF data", "description": "Uploads SARIF data containing the results of a code scanning analysis to make the results available in a repository. You must use an access token with the `security_events` scope to use this endpoint. GitHub Apps must have the `security_events` write permission to use this endpoint.\n\nThere are two places where you can upload code scanning results.\n - If you upload to a pull request, for example `--ref refs/pull/42/merge` or `--ref refs/pull/42/head`, then the results appear as alerts in a pull request check. For more information, see \"[Triaging code scanning alerts in pull requests](/code-security/secure-coding/triaging-code-scanning-alerts-in-pull-requests).\"\n - If you upload to a branch, for example `--ref refs/heads/my-branch`, then the results appear in the **Security** tab for your repository. For more information, see \"[Managing code scanning alerts for your repository](/code-security/secure-coding/managing-code-scanning-alerts-for-your-repository#viewing-the-alerts-for-a-repository).\"\n\nYou must compress the SARIF-formatted analysis data that you want to upload, using `gzip`, and then encode it as a Base64 format string. For example:\n\n```\ngzip -c analysis-data.sarif | base64 -w0\n```\n\nSARIF upload supports a maximum of 1000 results per analysis run. Any results over this limit are ignored. Typically, but not necessarily, a SARIF file contains a single run of a single tool. If a code scanning tool generates too many results, you should update the analysis configuration to run only the most important rules or queries.\n\nThe `202 Accepted`, response includes an `id` value.\nYou can use this ID to check the status of the upload by using this for the `/sarifs/{sarif_id}` endpoint.\nFor more information, see \"[Get information about a SARIF upload](/rest/reference/code-scanning#get-information-about-a-sarif-upload).\"", "operationId": "code-scanning/upload-sarif", "tags": [ "code-scanning" ], "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/code-scanning#upload-a-sarif-file" }, "parameters": [ { "$ref": "#/components/parameters/owner" }, { "$ref": "#/components/parameters/repo" } ], "requestBody": { "required": true, "content": { "application/json": { "schema": { "type": "object", "properties": { "commit_sha": { "$ref": "#/components/schemas/code-scanning-analysis-commit-sha" }, "ref": { "$ref": "#/components/schemas/code-scanning-ref" }, "sarif": { "$ref": "#/components/schemas/code-scanning-analysis-sarif-file" }, "checkout_uri": { "description": "The base directory used in the analysis, as it appears in the SARIF file.\nThis property is used to convert file paths from absolute to relative, so that alerts can be mapped to their correct location in the repository.", "type": "string", "format": "uri", "examples": [ "file:///github/workspace/" ] }, "started_at": { "description": "The time that the analysis run began. This is a timestamp in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format: `YYYY-MM-DDTHH:MM:SSZ`.", "format": "date-time", "type": "string" }, "tool_name": { "description": "The name of the tool used to generate the code scanning analysis. If this parameter is not used, the tool name defaults to \"API\". If the uploaded SARIF contains a tool GUID, this will be available for filtering using the `tool_guid` parameter of operations such as `GET /repos/{owner}/{repo}/code-scanning/alerts`.", "type": "string" } }, "required": [ "commit_sha", "ref", "sarif" ] } } } }, "responses": { "202": { "description": "Response", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/code-scanning-sarifs-receipt" }, "examples": { "default": { "$ref": "#/components/examples/code-scanning-sarif-upload" } } } } }, "400": { "description": "Bad Request if the sarif field is invalid" }, "403": { "$ref": "#/components/responses/code_scanning_forbidden_write" }, "404": { "$ref": "#/components/responses/not_found" }, "413": { "description": "Payload Too Large if the sarif field is too large" }, "503": { "$ref": "#/components/responses/service_unavailable" } }, "x-github": { "enabledForGitHubApps": true, "githubCloudOnly": false, "category": "code-scanning" } } }, "/repos/{owner}/{repo}/collaborators": { "get": { "summary": "List repository collaborators", "description": "For organization-owned repositories, the list of collaborators includes outside collaborators, organization members that are direct collaborators, organization members with access through team memberships, organization members with access through default organization permissions, and organization owners.\n\nTeam members will include the members of child teams.\n\nYou must authenticate using an access token with the `read:org` and `repo` scopes with push access to use this\nendpoint. GitHub Apps must have the `members` organization permission and `metadata` repository permission to use this\nendpoint.", "tags": [ "repos" ], "operationId": "repos/list-collaborators", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/repos#list-repository-collaborators" }, "parameters": [ { "$ref": "#/components/parameters/owner" }, { "$ref": "#/components/parameters/repo" }, { "name": "affiliation", "description": "Filter collaborators returned by their affiliation. Can be one of: \n\\* `outside`: All outside collaborators of an organization-owned repository. \n\\* `direct`: All collaborators with permissions to an organization-owned repository, regardless of organization membership status. \n\\* `all`: All collaborators the authenticated user can see.", "in": "query", "required": false, "schema": { "type": "string", "enum": [ "outside", "direct", "all" ], "default": "all" } }, { "$ref": "#/components/parameters/per-page" }, { "$ref": "#/components/parameters/page" } ], "responses": { "200": { "description": "Response", "content": { "application/json": { "schema": { "type": "array", "items": { "$ref": "#/components/schemas/collaborator" } }, "examples": { "default": { "$ref": "#/components/examples/collaborator-items" } } } }, "headers": { "Link": { "$ref": "#/components/headers/link" } } }, "404": { "$ref": "#/components/responses/not_found" } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": true, "category": "repos", "subcategory": "collaborators" } } }, "/repos/{owner}/{repo}/collaborators/{username}": { "get": { "summary": "Check if a user is a repository collaborator", "description": "For organization-owned repositories, the list of collaborators includes outside collaborators, organization members that are direct collaborators, organization members with access through team memberships, organization members with access through default organization permissions, and organization owners.\n\nTeam members will include the members of child teams.\n\nYou must authenticate using an access token with the `read:org` and `repo` scopes with push access to use this\nendpoint. GitHub Apps must have the `members` organization permission and `metadata` repository permission to use this\nendpoint.", "tags": [ "repos" ], "operationId": "repos/check-collaborator", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/repos#check-if-a-user-is-a-repository-collaborator" }, "parameters": [ { "$ref": "#/components/parameters/owner" }, { "$ref": "#/components/parameters/repo" }, { "$ref": "#/components/parameters/username" } ], "responses": { "204": { "description": "Response if user is a collaborator" }, "404": { "description": "Not Found if user is not a collaborator" } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": true, "category": "repos", "subcategory": "collaborators" } }, "put": { "summary": "Add a repository collaborator", "description": "This endpoint triggers [notifications](https://docs.github.com/en/github/managing-subscriptions-and-notifications-on-github/about-notifications). Creating content too quickly using this endpoint may result in secondary rate limiting. See \"[Secondary rate limits](https://docs.github.com/enterprise-server@3.0/rest/overview/resources-in-the-rest-api#secondary-rate-limits)\" and \"[Dealing with secondary rate limits](https://docs.github.com/enterprise-server@3.0/rest/guides/best-practices-for-integrators#dealing-with-secondary-rate-limits)\" for details.\n\nFor more information on permission levels, see \"[Repository permission levels for an organization](https://docs.github.com/en/github/setting-up-and-managing-organizations-and-teams/repository-permission-levels-for-an-organization#permission-levels-for-repositories-owned-by-an-organization)\". There are restrictions on which permissions can be granted to organization members when an organization base role is in place. In this case, the permission being given must be equal to or higher than the org base permission. Otherwise, the request will fail with:\n\n```\nCannot assign {member} permission of {role name}\n```\n\nNote that, if you choose not to pass any parameters, you'll need to set `Content-Length` to zero when calling out to this endpoint. For more information, see \"[HTTP verbs](https://docs.github.com/enterprise-server@3.0/rest/overview/resources-in-the-rest-api#http-verbs).\"\n\nThe invitee will receive a notification that they have been invited to the repository, which they must accept or decline. They may do this via the notifications page, the email they receive, or by using the [repository invitations API endpoints](https://docs.github.com/enterprise-server@3.0/rest/reference/repos#invitations).\n\n**Rate limits**\n\nYou are limited to sending 50 invitations to a repository per 24 hour period. Note there is no limit if you are inviting organization members to an organization repository.", "tags": [ "repos" ], "operationId": "repos/add-collaborator", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/repos#add-a-repository-collaborator" }, "parameters": [ { "$ref": "#/components/parameters/owner" }, { "$ref": "#/components/parameters/repo" }, { "$ref": "#/components/parameters/username" } ], "requestBody": { "required": false, "content": { "application/json": { "schema": { "type": "object", "properties": { "permission": { "type": "string", "description": "The permission to grant the collaborator. **Only valid on organization-owned repositories.** Can be one of: \n\\* `pull` - can pull, but not push to or administer this repository. \n\\* `push` - can pull and push, but not administer this repository. \n\\* `admin` - can pull, push and administer this repository. \n\\* `maintain` - Recommended for project managers who need to manage the repository without access to sensitive or destructive actions. \n\\* `triage` - Recommended for contributors who need to proactively manage issues and pull requests without write access.", "enum": [ "pull", "push", "admin", "maintain", "triage" ], "default": "push" }, "permissions": { "type": "string", "examples": [ "\"push\"" ] } } } } } }, "responses": { "201": { "description": "Response when a new invitation is created", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/repository-invitation" }, "examples": { "response-when-a-new-invitation-is-created": { "$ref": "#/components/examples/repository-invitation-response-when-a-new-invitation-is-created" } } } } }, "204": { "description": "Response when person is already a collaborator" }, "422": { "$ref": "#/components/responses/validation_failed" }, "403": { "$ref": "#/components/responses/forbidden" } }, "x-github": { "triggersNotification": true, "githubCloudOnly": false, "enabledForGitHubApps": true, "category": "repos", "subcategory": "collaborators" } }, "delete": { "summary": "Remove a repository collaborator", "description": "", "tags": [ "repos" ], "operationId": "repos/remove-collaborator", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/repos#remove-a-repository-collaborator" }, "parameters": [ { "$ref": "#/components/parameters/owner" }, { "$ref": "#/components/parameters/repo" }, { "$ref": "#/components/parameters/username" } ], "responses": { "204": { "description": "Response" } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": true, "category": "repos", "subcategory": "collaborators" } } }, "/repos/{owner}/{repo}/collaborators/{username}/permission": { "get": { "summary": "Get repository permissions for a user", "description": "Checks the repository permission of a collaborator. The possible repository permissions are `admin`, `write`, `read`, and `none`.", "tags": [ "repos" ], "operationId": "repos/get-collaborator-permission-level", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/repos#get-repository-permissions-for-a-user" }, "parameters": [ { "$ref": "#/components/parameters/owner" }, { "$ref": "#/components/parameters/repo" }, { "$ref": "#/components/parameters/username" } ], "responses": { "200": { "description": "if user has admin permissions", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/repository-collaborator-permission" }, "examples": { "response-if-user-has-admin-permissions": { "$ref": "#/components/examples/repository-collaborator-permission-response-if-user-has-admin-permissions" } } } } }, "404": { "$ref": "#/components/responses/not_found" } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": true, "category": "repos", "subcategory": "collaborators" } } }, "/repos/{owner}/{repo}/comments": { "get": { "summary": "List commit comments for a repository", "description": "Commit Comments use [these custom media types](https://docs.github.com/enterprise-server@3.0/rest/reference/repos#custom-media-types). You can read more about the use of media types in the API [here](https://docs.github.com/enterprise-server@3.0/rest/overview/media-types/).\n\nComments are ordered by ascending ID.", "tags": [ "repos" ], "operationId": "repos/list-commit-comments-for-repo", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/repos#list-commit-comments-for-a-repository" }, "parameters": [ { "$ref": "#/components/parameters/owner" }, { "$ref": "#/components/parameters/repo" }, { "$ref": "#/components/parameters/per-page" }, { "$ref": "#/components/parameters/page" } ], "responses": { "200": { "description": "Response", "content": { "application/json": { "schema": { "type": "array", "items": { "$ref": "#/components/schemas/commit-comment" } }, "examples": { "default": { "$ref": "#/components/examples/commit-comment-items" } } } }, "headers": { "Link": { "$ref": "#/components/headers/link" } } } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": true, "category": "repos", "subcategory": "comments", "previews": [ { "required": false, "name": "squirrel-girl", "note": "An additional `reactions` object in the issue comment payload is currently available for developers to preview. During the preview period, the APIs may change without advance notice. Please see the [blog post](https://developer.github.com/changes/2016-05-12-reactions-api-preview) for full details.\n\nTo access the API you must provide a custom [media type](https://docs.github.com/enterprise-server@3.0/rest/overview/media-types) in the `Accept` header:\n```shell\napplication/vnd.github.squirrel-girl-preview\n```\nThe `reactions` key will have the following payload where `url` can be used to construct the API location for [listing and creating](https://docs.github.com/enterprise-server@3.0/rest/reference/reactions) reactions." } ] } } }, "/repos/{owner}/{repo}/comments/{comment_id}": { "get": { "summary": "Get a commit comment", "description": "", "tags": [ "repos" ], "operationId": "repos/get-commit-comment", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/repos#get-a-commit-comment" }, "parameters": [ { "$ref": "#/components/parameters/owner" }, { "$ref": "#/components/parameters/repo" }, { "$ref": "#/components/parameters/comment-id" } ], "responses": { "200": { "description": "Response", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/commit-comment" }, "examples": { "default": { "$ref": "#/components/examples/commit-comment" } } } } }, "404": { "$ref": "#/components/responses/not_found" } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": true, "category": "repos", "subcategory": "comments", "previews": [ { "required": false, "name": "squirrel-girl", "note": "An additional `reactions` object in the issue comment payload is currently available for developers to preview. During the preview period, the APIs may change without advance notice. Please see the [blog post](https://developer.github.com/changes/2016-05-12-reactions-api-preview) for full details.\n\nTo access the API you must provide a custom [media type](https://docs.github.com/enterprise-server@3.0/rest/overview/media-types) in the `Accept` header:\n```shell\napplication/vnd.github.squirrel-girl-preview\n```\nThe `reactions` key will have the following payload where `url` can be used to construct the API location for [listing and creating](https://docs.github.com/enterprise-server@3.0/rest/reference/reactions) reactions." } ] } }, "patch": { "summary": "Update a commit comment", "description": "", "tags": [ "repos" ], "operationId": "repos/update-commit-comment", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/repos#update-a-commit-comment" }, "parameters": [ { "$ref": "#/components/parameters/owner" }, { "$ref": "#/components/parameters/repo" }, { "$ref": "#/components/parameters/comment-id" } ], "requestBody": { "required": true, "content": { "application/json": { "schema": { "type": "object", "properties": { "body": { "type": "string", "description": "The contents of the comment" } }, "required": [ "body" ] }, "example": { "body": "Nice change" } } } }, "responses": { "200": { "description": "Response", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/commit-comment" }, "examples": { "default": { "$ref": "#/components/examples/commit-comment-2" } } } } }, "404": { "$ref": "#/components/responses/not_found" } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": true, "category": "repos", "subcategory": "comments" } }, "delete": { "summary": "Delete a commit comment", "description": "", "tags": [ "repos" ], "operationId": "repos/delete-commit-comment", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/repos#delete-a-commit-comment" }, "parameters": [ { "$ref": "#/components/parameters/owner" }, { "$ref": "#/components/parameters/repo" }, { "$ref": "#/components/parameters/comment-id" } ], "responses": { "204": { "description": "Response" }, "404": { "$ref": "#/components/responses/not_found" } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": true, "category": "repos", "subcategory": "comments" } } }, "/repos/{owner}/{repo}/comments/{comment_id}/reactions": { "get": { "summary": "List reactions for a commit comment", "description": "List the reactions to a [commit comment](https://docs.github.com/enterprise-server@3.0/rest/reference/repos#comments).", "tags": [ "reactions" ], "operationId": "reactions/list-for-commit-comment", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/reactions#list-reactions-for-a-commit-comment" }, "parameters": [ { "$ref": "#/components/parameters/owner" }, { "$ref": "#/components/parameters/repo" }, { "$ref": "#/components/parameters/comment-id" }, { "name": "content", "description": "Returns a single [reaction type](https://docs.github.com/enterprise-server@3.0/rest/reference/reactions#reaction-types). Omit this parameter to list all reactions to a commit comment.", "in": "query", "required": false, "schema": { "type": "string", "enum": [ "+1", "-1", "laugh", "confused", "heart", "hooray", "rocket", "eyes" ] } }, { "$ref": "#/components/parameters/per-page" }, { "$ref": "#/components/parameters/page" } ], "responses": { "200": { "description": "Response", "content": { "application/json": { "schema": { "type": "array", "items": { "$ref": "#/components/schemas/reaction" } }, "examples": { "default": { "$ref": "#/components/examples/reaction-items" } } } }, "headers": { "Link": { "$ref": "#/components/headers/link" } } }, "404": { "$ref": "#/components/responses/not_found" } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": true, "category": "reactions", "previews": [ { "required": true, "name": "squirrel-girl", "note": "An additional `reactions` object in the issue comment payload is currently available for developers to preview. During the preview period, the APIs may change without advance notice. Please see the [blog post](https://developer.github.com/changes/2016-05-12-reactions-api-preview) for full details.\n\nTo access the API you must provide a custom [media type](https://docs.github.com/enterprise-server@3.0/rest/overview/media-types) in the `Accept` header:\n```shell\napplication/vnd.github.squirrel-girl-preview\n```\nThe `reactions` key will have the following payload where `url` can be used to construct the API location for [listing and creating](https://docs.github.com/enterprise-server@3.0/rest/reference/reactions) reactions." } ] } }, "post": { "summary": "Create reaction for a commit comment", "description": "Create a reaction to a [commit comment](https://docs.github.com/enterprise-server@3.0/rest/reference/repos#comments). A response with an HTTP `200` status means that you already added the reaction type to this commit comment.", "tags": [ "reactions" ], "operationId": "reactions/create-for-commit-comment", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/reactions#create-reaction-for-a-commit-comment" }, "parameters": [ { "$ref": "#/components/parameters/owner" }, { "$ref": "#/components/parameters/repo" }, { "$ref": "#/components/parameters/comment-id" } ], "requestBody": { "required": true, "content": { "application/json": { "schema": { "type": "object", "properties": { "content": { "type": "string", "description": "The [reaction type](https://docs.github.com/enterprise-server@3.0/rest/reference/reactions#reaction-types) to add to the commit comment.", "enum": [ "+1", "-1", "laugh", "confused", "heart", "hooray", "rocket", "eyes" ] } }, "required": [ "content" ] }, "example": { "content": "heart" } } } }, "responses": { "200": { "description": "Reaction exists", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/reaction" }, "examples": { "default": { "$ref": "#/components/examples/reaction" } } } } }, "201": { "description": "Reaction created", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/reaction" }, "examples": { "default": { "$ref": "#/components/examples/reaction" } } } } }, "415": { "$ref": "#/components/responses/preview_header_missing" }, "422": { "$ref": "#/components/responses/validation_failed" } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": true, "category": "reactions", "previews": [ { "required": true, "name": "squirrel-girl", "note": "An additional `reactions` object in the issue comment payload is currently available for developers to preview. During the preview period, the APIs may change without advance notice. Please see the [blog post](https://developer.github.com/changes/2016-05-12-reactions-api-preview) for full details.\n\nTo access the API you must provide a custom [media type](https://docs.github.com/enterprise-server@3.0/rest/overview/media-types) in the `Accept` header:\n```shell\napplication/vnd.github.squirrel-girl-preview\n```\nThe `reactions` key will have the following payload where `url` can be used to construct the API location for [listing and creating](https://docs.github.com/enterprise-server@3.0/rest/reference/reactions) reactions." } ] } } }, "/repos/{owner}/{repo}/comments/{comment_id}/reactions/{reaction_id}": { "delete": { "summary": "Delete a commit comment reaction", "description": "**Note:** You can also specify a repository by `repository_id` using the route `DELETE /repositories/:repository_id/comments/:comment_id/reactions/:reaction_id`.\n\nDelete a reaction to a [commit comment](https://docs.github.com/enterprise-server@3.0/rest/reference/repos#comments).", "tags": [ "reactions" ], "operationId": "reactions/delete-for-commit-comment", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/reactions#delete-a-commit-comment-reaction" }, "parameters": [ { "$ref": "#/components/parameters/owner" }, { "$ref": "#/components/parameters/repo" }, { "$ref": "#/components/parameters/comment-id" }, { "$ref": "#/components/parameters/reaction-id" } ], "responses": { "204": { "description": "Response" } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": true, "category": "reactions", "previews": [ { "required": true, "name": "squirrel-girl", "note": "An additional `reactions` object in the issue comment payload is currently available for developers to preview. During the preview period, the APIs may change without advance notice. Please see the [blog post](https://developer.github.com/changes/2016-05-12-reactions-api-preview) for full details.\n\nTo access the API you must provide a custom [media type](https://docs.github.com/enterprise-server@3.0/rest/overview/media-types) in the `Accept` header:\n```shell\napplication/vnd.github.squirrel-girl-preview\n```\nThe `reactions` key will have the following payload where `url` can be used to construct the API location for [listing and creating](https://docs.github.com/enterprise-server@3.0/rest/reference/reactions) reactions." } ] } } }, "/repos/{owner}/{repo}/commits": { "get": { "summary": "List commits", "description": "**Signature verification object**\n\nThe response will include a `verification` object that describes the result of verifying the commit's signature. The following fields are included in the `verification` object:\n\n| Name | Type | Description |\n| ---- | ---- | ----------- |\n| `verified` | `boolean` | Indicates whether GitHub considers the signature in this commit to be verified. |\n| `reason` | `string` | The reason for verified value. Possible values and their meanings are enumerated in table below. |\n| `signature` | `string` | The signature that was extracted from the commit. |\n| `payload` | `string` | The value that was signed. |\n\nThese are the possible values for `reason` in the `verification` object:\n\n| Value | Description |\n| ----- | ----------- |\n| `expired_key` | The key that made the signature is expired. |\n| `not_signing_key` | The \"signing\" flag is not among the usage flags in the GPG key that made the signature. |\n| `gpgverify_error` | There was an error communicating with the signature verification service. |\n| `gpgverify_unavailable` | The signature verification service is currently unavailable. |\n| `unsigned` | The object does not include a signature. |\n| `unknown_signature_type` | A non-PGP signature was found in the commit. |\n| `no_user` | No user was associated with the `committer` email address in the commit. |\n| `unverified_email` | The `committer` email address in the commit was associated with a user, but the email address is not verified on her/his account. |\n| `bad_email` | The `committer` email address in the commit is not included in the identities of the PGP key that made the signature. |\n| `unknown_key` | The key that made the signature has not been registered with any user's account. |\n| `malformed_signature` | There was an error parsing the signature. |\n| `invalid` | The signature could not be cryptographically verified using the key whose key-id was found in the signature. |\n| `valid` | None of the above errors applied, so the signature is considered to be verified. |", "tags": [ "repos" ], "operationId": "repos/list-commits", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/repos#list-commits" }, "parameters": [ { "$ref": "#/components/parameters/owner" }, { "$ref": "#/components/parameters/repo" }, { "name": "sha", "description": "SHA or branch to start listing commits from. Default: the repository’s default branch (usually `master`).", "in": "query", "required": false, "schema": { "type": "string" } }, { "name": "path", "description": "Only commits containing this file path will be returned.", "in": "query", "required": false, "schema": { "type": "string" } }, { "name": "author", "description": "GitHub login or email address by which to filter by commit author.", "in": "query", "required": false, "schema": { "type": "string" } }, { "$ref": "#/components/parameters/since" }, { "name": "until", "description": "Only commits before this date will be returned. This is a timestamp in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format: `YYYY-MM-DDTHH:MM:SSZ`.", "in": "query", "required": false, "schema": { "type": "string", "format": "date-time" } }, { "$ref": "#/components/parameters/per-page" }, { "$ref": "#/components/parameters/page" } ], "responses": { "200": { "description": "Response", "content": { "application/json": { "schema": { "type": "array", "items": { "$ref": "#/components/schemas/commit" } }, "examples": { "default": { "$ref": "#/components/examples/commit-items" } } } }, "headers": { "Link": { "$ref": "#/components/headers/link" } } }, "500": { "$ref": "#/components/responses/internal_error" }, "400": { "$ref": "#/components/responses/bad_request" }, "404": { "$ref": "#/components/responses/not_found" }, "409": { "$ref": "#/components/responses/conflict" } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": true, "category": "repos", "subcategory": "commits" } } }, "/repos/{owner}/{repo}/commits/{commit_sha}/branches-where-head": { "get": { "summary": "List branches for HEAD commit", "description": "Protected branches are available in public repositories with GitHub Free and GitHub Free for organizations, and in public and private repositories with GitHub Pro, GitHub Team, GitHub Enterprise Cloud, and GitHub Enterprise Server. For more information, see [GitHub's products](https://docs.github.com/github/getting-started-with-github/githubs-products) in the GitHub Help documentation.\n\nReturns all branches where the given commit SHA is the HEAD, or latest commit for the branch.", "tags": [ "repos" ], "operationId": "repos/list-branches-for-head-commit", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/repos#list-branches-for-head-commit" }, "parameters": [ { "$ref": "#/components/parameters/owner" }, { "$ref": "#/components/parameters/repo" }, { "$ref": "#/components/parameters/commit-sha" } ], "responses": { "200": { "description": "Response", "content": { "application/json": { "schema": { "type": "array", "items": { "$ref": "#/components/schemas/branch-short" } }, "examples": { "default": { "$ref": "#/components/examples/branch-short-items" } } } } }, "422": { "$ref": "#/components/responses/validation_failed" } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": true, "category": "repos", "subcategory": "commits", "previews": [ { "required": true, "name": "groot", "note": "Listing branches or pull requests for a commit in the Commits API is currently available for developers to preview. See the [blog post](https://developer.github.com/changes/2019-04-11-pulls-branches-for-commit/) for more details. To access the new endpoints during the preview period, you must provide a custom [media type](https://docs.github.com/enterprise-server@3.0/rest/overview/media-types) in the `Accept` header:\n```shell\napplication/vnd.github.groot-preview+json\n```" } ] } } }, "/repos/{owner}/{repo}/commits/{commit_sha}/comments": { "get": { "summary": "List commit comments", "description": "Use the `:commit_sha` to specify the commit that will have its comments listed.", "tags": [ "repos" ], "operationId": "repos/list-comments-for-commit", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/repos#list-commit-comments" }, "parameters": [ { "$ref": "#/components/parameters/owner" }, { "$ref": "#/components/parameters/repo" }, { "$ref": "#/components/parameters/commit-sha" }, { "$ref": "#/components/parameters/per-page" }, { "$ref": "#/components/parameters/page" } ], "responses": { "200": { "description": "Response", "content": { "application/json": { "schema": { "type": "array", "items": { "$ref": "#/components/schemas/commit-comment" } }, "examples": { "default": { "$ref": "#/components/examples/commit-comment-items" } } } }, "headers": { "Link": { "$ref": "#/components/headers/link" } } } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": true, "category": "repos", "subcategory": "comments", "previews": [ { "required": false, "name": "squirrel-girl", "note": "An additional `reactions` object in the issue comment payload is currently available for developers to preview. During the preview period, the APIs may change without advance notice. Please see the [blog post](https://developer.github.com/changes/2016-05-12-reactions-api-preview) for full details.\n\nTo access the API you must provide a custom [media type](https://docs.github.com/enterprise-server@3.0/rest/overview/media-types) in the `Accept` header:\n```shell\napplication/vnd.github.squirrel-girl-preview\n```\nThe `reactions` key will have the following payload where `url` can be used to construct the API location for [listing and creating](https://docs.github.com/enterprise-server@3.0/rest/reference/reactions) reactions." } ] } }, "post": { "summary": "Create a commit comment", "description": "Create a comment for a commit using its `:commit_sha`.\n\nThis endpoint triggers [notifications](https://docs.github.com/en/github/managing-subscriptions-and-notifications-on-github/about-notifications). Creating content too quickly using this endpoint may result in secondary rate limiting. See \"[Secondary rate limits](https://docs.github.com/enterprise-server@3.0/rest/overview/resources-in-the-rest-api#secondary-rate-limits)\" and \"[Dealing with secondary rate limits](https://docs.github.com/enterprise-server@3.0/rest/guides/best-practices-for-integrators#dealing-with-secondary-rate-limits)\" for details.", "tags": [ "repos" ], "operationId": "repos/create-commit-comment", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/repos#create-a-commit-comment" }, "parameters": [ { "$ref": "#/components/parameters/owner" }, { "$ref": "#/components/parameters/repo" }, { "$ref": "#/components/parameters/commit-sha" } ], "requestBody": { "required": true, "content": { "application/json": { "schema": { "type": "object", "properties": { "body": { "type": "string", "description": "The contents of the comment." }, "path": { "type": "string", "description": "Relative path of the file to comment on." }, "position": { "type": "integer", "description": "Line index in the diff to comment on." }, "line": { "type": "integer", "description": "**Deprecated**. Use **position** parameter instead. Line number in the file to comment on." } }, "required": [ "body" ] }, "example": { "body": "Great stuff", "path": "file1.txt", "position": 4, "line": 1 } } } }, "responses": { "201": { "description": "Response", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/commit-comment" }, "examples": { "default": { "$ref": "#/components/examples/commit-comment" } } } }, "headers": { "Location": { "example": "https://api.github.com/repos/octocat/Hello-World/comments/1", "schema": { "type": "string" } } } }, "403": { "$ref": "#/components/responses/forbidden" }, "422": { "$ref": "#/components/responses/validation_failed" } }, "x-github": { "triggersNotification": true, "githubCloudOnly": false, "enabledForGitHubApps": true, "category": "repos", "subcategory": "comments" } } }, "/repos/{owner}/{repo}/commits/{commit_sha}/pulls": { "get": { "summary": "List pull requests associated with a commit", "description": "Lists the merged pull request that introduced the commit to the repository. If the commit is not present in the default branch, additionally returns open pull requests associated with the commit. The results may include open and closed pull requests. Additional preview headers may be required to see certain details for associated pull requests, such as whether a pull request is in a draft state. For more information about previews that might affect this endpoint, see the [List pull requests](https://docs.github.com/enterprise-server@3.0/rest/reference/pulls#list-pull-requests) endpoint.", "tags": [ "repos" ], "operationId": "repos/list-pull-requests-associated-with-commit", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/repos#list-pull-requests-associated-with-a-commit" }, "parameters": [ { "$ref": "#/components/parameters/owner" }, { "$ref": "#/components/parameters/repo" }, { "$ref": "#/components/parameters/commit-sha" }, { "$ref": "#/components/parameters/per-page" }, { "$ref": "#/components/parameters/page" } ], "responses": { "200": { "description": "Response", "content": { "application/json": { "schema": { "type": "array", "items": { "$ref": "#/components/schemas/pull-request-simple" } }, "examples": { "default": { "$ref": "#/components/examples/pull-request-simple-items" } } } }, "headers": { "Link": { "$ref": "#/components/headers/link" } } } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": true, "category": "repos", "subcategory": "commits", "previews": [ { "required": true, "name": "groot", "note": "Listing branches or pull requests for a commit in the Commits API is currently available for developers to preview. See the [blog post](https://developer.github.com/changes/2019-04-11-pulls-branches-for-commit/) for more details. To access the new endpoints during the preview period, you must provide a custom [media type](https://docs.github.com/enterprise-server@3.0/rest/overview/media-types) in the `Accept` header:\n```shell\napplication/vnd.github.groot-preview+json\n```" } ] } } }, "/repos/{owner}/{repo}/commits/{ref}": { "get": { "summary": "Get a commit", "description": "Returns the contents of a single commit reference. You must have `read` access for the repository to use this endpoint.\n\n**Note:** If there are more than 300 files in the commit diff, the response will include pagination link headers for the remaining files, up to a limit of 3000 files. Each page contains the static commit information, and the only changes are to the file listing.\n\nYou can pass the appropriate [media type](https://docs.github.com/enterprise-server@3.0/rest/overview/media-types/#commits-commit-comparison-and-pull-requests) to fetch `diff` and `patch` formats. Diffs with binary data will have no `patch` property.\n\nTo return only the SHA-1 hash of the commit reference, you can provide the `sha` custom [media type](https://docs.github.com/enterprise-server@3.0/rest/overview/media-types/#commits-commit-comparison-and-pull-requests) in the `Accept` header. You can use this endpoint to check if a remote reference's SHA-1 hash is the same as your local reference's SHA-1 hash by providing the local SHA-1 reference as the ETag.\n\n**Signature verification object**\n\nThe response will include a `verification` object that describes the result of verifying the commit's signature. The following fields are included in the `verification` object:\n\n| Name | Type | Description |\n| ---- | ---- | ----------- |\n| `verified` | `boolean` | Indicates whether GitHub considers the signature in this commit to be verified. |\n| `reason` | `string` | The reason for verified value. Possible values and their meanings are enumerated in table below. |\n| `signature` | `string` | The signature that was extracted from the commit. |\n| `payload` | `string` | The value that was signed. |\n\nThese are the possible values for `reason` in the `verification` object:\n\n| Value | Description |\n| ----- | ----------- |\n| `expired_key` | The key that made the signature is expired. |\n| `not_signing_key` | The \"signing\" flag is not among the usage flags in the GPG key that made the signature. |\n| `gpgverify_error` | There was an error communicating with the signature verification service. |\n| `gpgverify_unavailable` | The signature verification service is currently unavailable. |\n| `unsigned` | The object does not include a signature. |\n| `unknown_signature_type` | A non-PGP signature was found in the commit. |\n| `no_user` | No user was associated with the `committer` email address in the commit. |\n| `unverified_email` | The `committer` email address in the commit was associated with a user, but the email address is not verified on her/his account. |\n| `bad_email` | The `committer` email address in the commit is not included in the identities of the PGP key that made the signature. |\n| `unknown_key` | The key that made the signature has not been registered with any user's account. |\n| `malformed_signature` | There was an error parsing the signature. |\n| `invalid` | The signature could not be cryptographically verified using the key whose key-id was found in the signature. |\n| `valid` | None of the above errors applied, so the signature is considered to be verified. |", "tags": [ "repos" ], "operationId": "repos/get-commit", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/repos#get-a-commit" }, "parameters": [ { "$ref": "#/components/parameters/owner" }, { "$ref": "#/components/parameters/repo" }, { "$ref": "#/components/parameters/page" }, { "$ref": "#/components/parameters/per-page" }, { "name": "ref", "description": "ref parameter", "in": "path", "required": true, "schema": { "type": "string" }, "x-multi-segment": true } ], "responses": { "200": { "description": "Response", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/commit" }, "examples": { "default": { "$ref": "#/components/examples/commit" } } } } }, "422": { "$ref": "#/components/responses/validation_failed" }, "404": { "$ref": "#/components/responses/not_found" }, "500": { "$ref": "#/components/responses/internal_error" } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": true, "category": "repos", "subcategory": "commits" } } }, "/repos/{owner}/{repo}/commits/{ref}/check-runs": { "get": { "summary": "List check runs for a Git reference", "description": "**Note:** The Checks API only looks for pushes in the repository where the check suite or check run were created. Pushes to a branch in a forked repository are not detected and return an empty `pull_requests` array.\n\nLists check runs for a commit ref. The `ref` can be a SHA, branch name, or a tag name. GitHub Apps must have the `checks:read` permission on a private repository or pull access to a public repository to get check runs. OAuth Apps and authenticated users must have the `repo` scope to get check runs in a private repository.", "tags": [ "checks" ], "operationId": "checks/list-for-ref", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/checks#list-check-runs-for-a-git-reference" }, "parameters": [ { "$ref": "#/components/parameters/owner" }, { "$ref": "#/components/parameters/repo" }, { "name": "ref", "description": "ref parameter", "in": "path", "required": true, "schema": { "type": "string" }, "x-multi-segment": true }, { "$ref": "#/components/parameters/check-name" }, { "$ref": "#/components/parameters/status" }, { "name": "filter", "description": "Filters check runs by their `completed_at` timestamp. Can be one of `latest` (returning the most recent check runs) or `all`.", "in": "query", "required": false, "schema": { "type": "string", "enum": [ "latest", "all" ], "default": "latest" } }, { "$ref": "#/components/parameters/per-page" }, { "$ref": "#/components/parameters/page" }, { "name": "app_id", "in": "query", "required": false, "schema": { "type": "integer" } } ], "responses": { "200": { "description": "Response", "content": { "application/json": { "schema": { "type": "object", "required": [ "total_count", "check_runs" ], "properties": { "total_count": { "type": "integer" }, "check_runs": { "type": "array", "items": { "$ref": "#/components/schemas/check-run" } } } }, "examples": { "default": { "$ref": "#/components/examples/check-run-paginated" } } } }, "headers": { "Link": { "$ref": "#/components/headers/link" } } } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": true, "category": "checks", "subcategory": "runs" } } }, "/repos/{owner}/{repo}/commits/{ref}/check-suites": { "get": { "summary": "List check suites for a Git reference", "description": "**Note:** The Checks API only looks for pushes in the repository where the check suite or check run were created. Pushes to a branch in a forked repository are not detected and return an empty `pull_requests` array and a `null` value for `head_branch`.\n\nLists check suites for a commit `ref`. The `ref` can be a SHA, branch name, or a tag name. GitHub Apps must have the `checks:read` permission on a private repository or pull access to a public repository to list check suites. OAuth Apps and authenticated users must have the `repo` scope to get check suites in a private repository.", "tags": [ "checks" ], "operationId": "checks/list-suites-for-ref", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/checks#list-check-suites-for-a-git-reference" }, "parameters": [ { "$ref": "#/components/parameters/owner" }, { "$ref": "#/components/parameters/repo" }, { "name": "ref", "description": "ref parameter", "in": "path", "required": true, "schema": { "type": "string" }, "x-multi-segment": true }, { "name": "app_id", "description": "Filters check suites by GitHub App `id`.", "in": "query", "required": false, "schema": { "type": "integer" }, "example": 1 }, { "$ref": "#/components/parameters/check-name" }, { "$ref": "#/components/parameters/per-page" }, { "$ref": "#/components/parameters/page" } ], "responses": { "200": { "description": "Response", "content": { "application/json": { "schema": { "type": "object", "required": [ "total_count", "check_suites" ], "properties": { "total_count": { "type": "integer" }, "check_suites": { "type": "array", "items": { "$ref": "#/components/schemas/check-suite" } } } }, "examples": { "default": { "$ref": "#/components/examples/check-suite-paginated" } } } }, "headers": { "Link": { "$ref": "#/components/headers/link" } } } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": true, "category": "checks", "subcategory": "suites" } } }, "/repos/{owner}/{repo}/commits/{ref}/status": { "get": { "summary": "Get the combined status for a specific reference", "description": "Users with pull access in a repository can access a combined view of commit statuses for a given ref. The ref can be a SHA, a branch name, or a tag name.\n\n\nAdditionally, a combined `state` is returned. The `state` is one of:\n\n* **failure** if any of the contexts report as `error` or `failure`\n* **pending** if there are no statuses or a context is `pending`\n* **success** if the latest status for all contexts is `success`", "tags": [ "repos" ], "operationId": "repos/get-combined-status-for-ref", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/repos#get-the-combined-status-for-a-specific-reference" }, "parameters": [ { "$ref": "#/components/parameters/owner" }, { "$ref": "#/components/parameters/repo" }, { "name": "ref", "description": "ref parameter", "in": "path", "required": true, "schema": { "type": "string" }, "x-multi-segment": true }, { "$ref": "#/components/parameters/per-page" }, { "$ref": "#/components/parameters/page" } ], "responses": { "200": { "description": "Response", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/combined-commit-status" }, "examples": { "default": { "$ref": "#/components/examples/combined-commit-status" } } } } }, "404": { "$ref": "#/components/responses/not_found" } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": true, "category": "repos", "subcategory": "statuses" } } }, "/repos/{owner}/{repo}/commits/{ref}/statuses": { "get": { "summary": "List commit statuses for a reference", "description": "Users with pull access in a repository can view commit statuses for a given ref. The ref can be a SHA, a branch name, or a tag name. Statuses are returned in reverse chronological order. The first status in the list will be the latest one.\n\nThis resource is also available via a legacy route: `GET /repos/:owner/:repo/statuses/:ref`.", "tags": [ "repos" ], "operationId": "repos/list-commit-statuses-for-ref", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/repos#list-commit-statuses-for-a-reference" }, "parameters": [ { "$ref": "#/components/parameters/owner" }, { "$ref": "#/components/parameters/repo" }, { "name": "ref", "description": "ref parameter", "in": "path", "required": true, "schema": { "type": "string" }, "x-multi-segment": true }, { "$ref": "#/components/parameters/per-page" }, { "$ref": "#/components/parameters/page" } ], "responses": { "200": { "description": "Response", "content": { "application/json": { "schema": { "type": "array", "items": { "$ref": "#/components/schemas/status" } }, "examples": { "default": { "$ref": "#/components/examples/status-items" } } } }, "headers": { "Link": { "$ref": "#/components/headers/link" } } }, "301": { "$ref": "#/components/responses/moved_permanently" } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": true, "category": "repos", "subcategory": "statuses" } } }, "/repos/{owner}/{repo}/compare/{basehead}": { "get": { "summary": "Compare two commits", "description": "The `basehead` param is comprised of two parts: `base` and `head`. Both must be branch names in `repo`. To compare branches across other repositories in the same network as `repo`, use the format `:branch`.\n\nThe response from the API is equivalent to running the `git log base..head` command; however, commits are returned in chronological order. Pass the appropriate [media type](https://docs.github.com/enterprise-server@3.0/rest/overview/media-types/#commits-commit-comparison-and-pull-requests) to fetch diff and patch formats.\n\nThe response also includes details on the files that were changed between the two commits. This includes the status of the change (for example, if a file was added, removed, modified, or renamed), and details of the change itself. For example, files with a `renamed` status have a `previous_filename` field showing the previous filename of the file, and files with a `modified` status have a `patch` field showing the changes made to the file.\n\n**Working with large comparisons**\n\nThe response will include a comparison of up to 250 commits. If you are working with a larger commit range, you can use the [List commits](https://docs.github.com/enterprise-server@3.0/rest/reference/repos#list-commits) to enumerate all commits in the range.\n\nFor comparisons with extremely large diffs, you may receive an error response indicating that the diff took too long\nto generate. You can typically resolve this error by using a smaller commit range.\n\n**Signature verification object**\n\nThe response will include a `verification` object that describes the result of verifying the commit's signature. The following fields are included in the `verification` object:\n\n| Name | Type | Description |\n| ---- | ---- | ----------- |\n| `verified` | `boolean` | Indicates whether GitHub considers the signature in this commit to be verified. |\n| `reason` | `string` | The reason for verified value. Possible values and their meanings are enumerated in table below. |\n| `signature` | `string` | The signature that was extracted from the commit. |\n| `payload` | `string` | The value that was signed. |\n\nThese are the possible values for `reason` in the `verification` object:\n\n| Value | Description |\n| ----- | ----------- |\n| `expired_key` | The key that made the signature is expired. |\n| `not_signing_key` | The \"signing\" flag is not among the usage flags in the GPG key that made the signature. |\n| `gpgverify_error` | There was an error communicating with the signature verification service. |\n| `gpgverify_unavailable` | The signature verification service is currently unavailable. |\n| `unsigned` | The object does not include a signature. |\n| `unknown_signature_type` | A non-PGP signature was found in the commit. |\n| `no_user` | No user was associated with the `committer` email address in the commit. |\n| `unverified_email` | The `committer` email address in the commit was associated with a user, but the email address is not verified on her/his account. |\n| `bad_email` | The `committer` email address in the commit is not included in the identities of the PGP key that made the signature. |\n| `unknown_key` | The key that made the signature has not been registered with any user's account. |\n| `malformed_signature` | There was an error parsing the signature. |\n| `invalid` | The signature could not be cryptographically verified using the key whose key-id was found in the signature. |\n| `valid` | None of the above errors applied, so the signature is considered to be verified. |", "tags": [ "repos" ], "operationId": "repos/compare-commits", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/repos#compare-two-commits" }, "parameters": [ { "$ref": "#/components/parameters/owner" }, { "$ref": "#/components/parameters/repo" }, { "name": "basehead", "description": "The base branch and head branch to compare. This parameter expects the format `{base}...{head}`.", "in": "path", "required": true, "schema": { "type": "string" } } ], "responses": { "200": { "description": "Response", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/commit-comparison" }, "examples": { "default": { "$ref": "#/components/examples/commit-comparison" } } } } }, "500": { "$ref": "#/components/responses/internal_error" }, "404": { "$ref": "#/components/responses/not_found" } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": true, "category": "repos", "subcategory": "commits" } } }, "/repos/{owner}/{repo}/content_references/{content_reference_id}/attachments": { "post": { "summary": "Create a content attachment", "description": "Creates an attachment under a content reference URL in the body or comment of an issue or pull request. Use the `id` and `repository` `full_name` of the content reference from the [`content_reference` event](https://docs.github.com/enterprise-server@3.0/webhooks/event-payloads/#content_reference) to create an attachment.\n\nThe app must create a content attachment within six hours of the content reference URL being posted. See \"[Using content attachments](https://docs.github.com/enterprise-server@3.0/apps/using-content-attachments/)\" for details about content attachments.\n\nYou must use an [installation access token](https://docs.github.com/enterprise-server@3.0/apps/building-github-apps/authenticating-with-github-apps/#authenticating-as-an-installation) to access this endpoint.", "tags": [ "apps" ], "operationId": "apps/create-content-attachment", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/apps#create-a-content-attachment" }, "parameters": [ { "name": "owner", "description": "The owner of the repository. Determined from the `repository` `full_name` of the `content_reference` event.", "in": "path", "required": true, "schema": { "type": "string" } }, { "name": "repo", "description": "The name of the repository. Determined from the `repository` `full_name` of the `content_reference` event.", "in": "path", "required": true, "schema": { "type": "string" } }, { "name": "content_reference_id", "description": "The `id` of the `content_reference` event.", "in": "path", "required": true, "schema": { "type": "integer" } } ], "requestBody": { "required": true, "content": { "application/json": { "schema": { "properties": { "title": { "description": "The title of the attachment", "type": "string", "maxLength": 1024, "examples": [ "Title of the attachment" ] }, "body": { "description": "The body of the attachment", "type": "string", "maxLength": 262144, "examples": [ "Body of the attachment" ] } }, "required": [ "title", "body" ], "type": "object" } } } }, "responses": { "200": { "description": "Response", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/content-reference-attachment" }, "examples": { "default": { "$ref": "#/components/examples/content-reference-attachment" } } } } }, "422": { "$ref": "#/components/responses/validation_failed" }, "404": { "$ref": "#/components/responses/not_found" }, "410": { "$ref": "#/components/responses/gone" }, "415": { "$ref": "#/components/responses/preview_header_missing" }, "304": { "$ref": "#/components/responses/not_modified" }, "403": { "$ref": "#/components/responses/forbidden" } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": true, "previews": [ { "required": true, "name": "corsair", "note": "To access the Content Attachments API during the preview period, you must provide a custom [media type](https://docs.github.com/enterprise-server@3.0/rest/overview/media-types) in the `Accept` header:\n```shell\napplication/vnd.github.corsair-preview+json\n```" } ], "category": "apps", "subcategory": "installations" } } }, "/repos/{owner}/{repo}/contents/{path}": { "get": { "summary": "Get repository content", "description": "Gets the contents of a file or directory in a repository. Specify the file path or directory in `:path`. If you omit\n`:path`, you will receive the contents of the repository's root directory. See the description below regarding what the API response includes for directories. \n\nFiles and symlinks support [a custom media type](https://docs.github.com/enterprise-server@3.0/rest/reference/repos#custom-media-types) for\nretrieving the raw content or rendered HTML (when supported). All content types support [a custom media\ntype](https://docs.github.com/enterprise-server@3.0/rest/reference/repos#custom-media-types) to ensure the content is returned in a consistent\nobject format.\n\n**Note**:\n* To get a repository's contents recursively, you can [recursively get the tree](https://docs.github.com/enterprise-server@3.0/rest/reference/git#trees).\n* This API has an upper limit of 1,000 files for a directory. If you need to retrieve more files, use the [Git Trees\nAPI](https://docs.github.com/enterprise-server@3.0/rest/reference/git#get-a-tree).\n* This API supports files up to 1 megabyte in size.\n\n#### If the content is a directory\nThe response will be an array of objects, one object for each item in the directory.\nWhen listing the contents of a directory, submodules have their \"type\" specified as \"file\". Logically, the value\n_should_ be \"submodule\". This behavior exists in API v3 [for backwards compatibility purposes](https://git.io/v1YCW).\nIn the next major version of the API, the type will be returned as \"submodule\".\n\n#### If the content is a symlink \nIf the requested `:path` points to a symlink, and the symlink's target is a normal file in the repository, then the\nAPI responds with the content of the file (in the format shown in the example. Otherwise, the API responds with an object \ndescribing the symlink itself.\n\n#### If the content is a submodule\nThe `submodule_git_url` identifies the location of the submodule repository, and the `sha` identifies a specific\ncommit within the submodule repository. Git uses the given URL when cloning the submodule repository, and checks out\nthe submodule at that specific commit.\n\nIf the submodule repository is not hosted on github.com, the Git URLs (`git_url` and `_links[\"git\"]`) and the\ngithub.com URLs (`html_url` and `_links[\"html\"]`) will have null values.", "tags": [ "repos" ], "operationId": "repos/get-content", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/repos#get-repository-content" }, "parameters": [ { "$ref": "#/components/parameters/owner" }, { "$ref": "#/components/parameters/repo" }, { "name": "path", "description": "path parameter", "in": "path", "required": true, "schema": { "type": "string" }, "x-multi-segment": true }, { "name": "ref", "description": "The name of the commit/branch/tag. Default: the repository’s default branch (usually `master`)", "in": "query", "required": false, "schema": { "type": "string" } } ], "responses": { "200": { "description": "Response", "content": { "application/vnd.github.v3.object": { "schema": { "$ref": "#/components/schemas/content-tree" } }, "application/json": { "schema": { "oneOf": [ { "$ref": "#/components/schemas/content-directory" }, { "$ref": "#/components/schemas/content-file" }, { "$ref": "#/components/schemas/content-symlink" }, { "$ref": "#/components/schemas/content-submodule" } ] }, "examples": { "response-if-content-is-a-file": { "$ref": "#/components/examples/content-file-response-if-content-is-a-file" }, "response-if-content-is-a-directory": { "$ref": "#/components/examples/content-file-response-if-content-is-a-directory" }, "response-if-content-is-a-symlink": { "$ref": "#/components/examples/content-file-response-if-content-is-a-symlink" }, "response-if-content-is-a-submodule": { "$ref": "#/components/examples/content-file-response-if-content-is-a-submodule" } } } } }, "404": { "$ref": "#/components/responses/not_found" }, "403": { "$ref": "#/components/responses/forbidden" }, "302": { "$ref": "#/components/responses/found" } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": true, "category": "repos", "subcategory": "contents" } }, "put": { "summary": "Create or update file contents", "description": "Creates a new file or replaces an existing file in a repository.", "tags": [ "repos" ], "operationId": "repos/create-or-update-file-contents", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/repos#create-or-update-file-contents" }, "parameters": [ { "$ref": "#/components/parameters/owner" }, { "$ref": "#/components/parameters/repo" }, { "name": "path", "description": "path parameter", "in": "path", "required": true, "schema": { "type": "string" }, "x-multi-segment": true } ], "requestBody": { "required": true, "content": { "application/json": { "schema": { "type": "object", "properties": { "message": { "type": "string", "description": "The commit message." }, "content": { "type": "string", "description": "The new file content, using Base64 encoding." }, "sha": { "type": "string", "description": "**Required if you are updating a file**. The blob SHA of the file being replaced." }, "branch": { "type": "string", "description": "The branch name. Default: the repository’s default branch (usually `master`)" }, "committer": { "type": "object", "description": "The person that committed the file. Default: the authenticated user.", "properties": { "name": { "type": "string", "description": "The name of the author or committer of the commit. You'll receive a `422` status code if `name` is omitted." }, "email": { "type": "string", "description": "The email of the author or committer of the commit. You'll receive a `422` status code if `email` is omitted." }, "date": { "type": "string", "examples": [ "\"2013-01-05T13:13:22+05:00\"" ] } }, "required": [ "name", "email" ] }, "author": { "type": "object", "description": "The author of the file. Default: The `committer` or the authenticated user if you omit `committer`.", "properties": { "name": { "type": "string", "description": "The name of the author or committer of the commit. You'll receive a `422` status code if `name` is omitted." }, "email": { "type": "string", "description": "The email of the author or committer of the commit. You'll receive a `422` status code if `email` is omitted." }, "date": { "type": "string", "examples": [ "\"2013-01-15T17:13:22+05:00\"" ] } }, "required": [ "name", "email" ] } }, "required": [ "message", "content" ] }, "examples": { "example-for-creating-a-file": { "summary": "Example for creating a file", "value": { "message": "my commit message", "committer": { "name": "Monalisa Octocat", "email": "octocat@github.com" }, "content": "bXkgbmV3IGZpbGUgY29udGVudHM=" } }, "example-for-updating-a-file": { "summary": "Example for updating a file", "value": { "message": "a new commit message", "committer": { "name": "Monalisa Octocat", "email": "octocat@github.com" }, "content": "bXkgdXBkYXRlZCBmaWxlIGNvbnRlbnRz", "sha": "95b966ae1c166bd92f8ae7d1c313e738c731dfc3" } } } } } }, "responses": { "200": { "description": "Response", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/file-commit" }, "examples": { "example-for-updating-a-file": { "$ref": "#/components/examples/file-commit-example-for-updating-a-file" } } } } }, "201": { "description": "Response", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/file-commit" }, "examples": { "example-for-creating-a-file": { "$ref": "#/components/examples/file-commit-example-for-creating-a-file" } } } } }, "404": { "$ref": "#/components/responses/not_found" }, "422": { "$ref": "#/components/responses/validation_failed" }, "409": { "$ref": "#/components/responses/conflict" } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": true, "category": "repos", "subcategory": "contents" } }, "delete": { "summary": "Delete a file", "description": "Deletes a file in a repository.\n\nYou can provide an additional `committer` parameter, which is an object containing information about the committer. Or, you can provide an `author` parameter, which is an object containing information about the author.\n\nThe `author` section is optional and is filled in with the `committer` information if omitted. If the `committer` information is omitted, the authenticated user's information is used.\n\nYou must provide values for both `name` and `email`, whether you choose to use `author` or `committer`. Otherwise, you'll receive a `422` status code.", "tags": [ "repos" ], "operationId": "repos/delete-file", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/repos#delete-a-file" }, "parameters": [ { "$ref": "#/components/parameters/owner" }, { "$ref": "#/components/parameters/repo" }, { "name": "path", "description": "path parameter", "in": "path", "required": true, "schema": { "type": "string" }, "x-multi-segment": true } ], "requestBody": { "required": true, "content": { "application/json": { "schema": { "type": "object", "properties": { "message": { "type": "string", "description": "The commit message." }, "sha": { "type": "string", "description": "The blob SHA of the file being replaced." }, "branch": { "type": "string", "description": "The branch name. Default: the repository’s default branch (usually `master`)" }, "committer": { "type": "object", "description": "object containing information about the committer.", "properties": { "name": { "type": "string", "description": "The name of the author (or committer) of the commit" }, "email": { "type": "string", "description": "The email of the author (or committer) of the commit" } } }, "author": { "type": "object", "description": "object containing information about the author.", "properties": { "name": { "type": "string", "description": "The name of the author (or committer) of the commit" }, "email": { "type": "string", "description": "The email of the author (or committer) of the commit" } } } }, "required": [ "message", "sha" ] }, "example": { "message": "my commit message", "committer": { "name": "Monalisa Octocat", "email": "octocat@github.com" }, "sha": "329688480d39049927147c162b9d2deaf885005f" } } } }, "responses": { "200": { "description": "Response", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/file-commit" }, "examples": { "default": { "$ref": "#/components/examples/file-commit" } } } } }, "422": { "$ref": "#/components/responses/validation_failed" }, "404": { "$ref": "#/components/responses/not_found" }, "409": { "$ref": "#/components/responses/conflict" }, "503": { "$ref": "#/components/responses/service_unavailable" } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": true, "category": "repos", "subcategory": "contents" } } }, "/repos/{owner}/{repo}/contributors": { "get": { "summary": "List repository contributors", "description": "Lists contributors to the specified repository and sorts them by the number of commits per contributor in descending order. This endpoint may return information that is a few hours old because the GitHub REST API v3 caches contributor data to improve performance.\n\nGitHub identifies contributors by author email address. This endpoint groups contribution counts by GitHub user, which includes all associated email addresses. To improve performance, only the first 500 author email addresses in the repository link to GitHub users. The rest will appear as anonymous contributors without associated GitHub user information.", "tags": [ "repos" ], "operationId": "repos/list-contributors", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/repos#list-repository-contributors" }, "parameters": [ { "$ref": "#/components/parameters/owner" }, { "$ref": "#/components/parameters/repo" }, { "name": "anon", "description": "Set to `1` or `true` to include anonymous contributors in results.", "in": "query", "required": false, "schema": { "type": "string" } }, { "$ref": "#/components/parameters/per-page" }, { "$ref": "#/components/parameters/page" } ], "responses": { "200": { "description": "if repository contains content", "content": { "application/json": { "schema": { "type": "array", "items": { "$ref": "#/components/schemas/contributor" } }, "examples": { "response-if-repository-contains-content": { "$ref": "#/components/examples/contributor-items-response-if-repository-contains-content" } } } }, "headers": { "Link": { "$ref": "#/components/headers/link" } } }, "204": { "description": "Response if repository is empty" }, "403": { "$ref": "#/components/responses/forbidden" }, "404": { "$ref": "#/components/responses/not_found" } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": true, "category": "repos", "subcategory": null } } }, "/repos/{owner}/{repo}/deployments": { "get": { "summary": "List deployments", "description": "Simple filtering of deployments is available via query parameters:", "tags": [ "repos" ], "operationId": "repos/list-deployments", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/repos#list-deployments" }, "parameters": [ { "$ref": "#/components/parameters/owner" }, { "$ref": "#/components/parameters/repo" }, { "name": "sha", "description": "The SHA recorded at creation time.", "in": "query", "required": false, "schema": { "type": "string", "default": "none" } }, { "name": "ref", "description": "The name of the ref. This can be a branch, tag, or SHA.", "in": "query", "required": false, "schema": { "type": "string", "default": "none" } }, { "name": "task", "description": "The name of the task for the deployment (e.g., `deploy` or `deploy:migrations`).", "in": "query", "required": false, "schema": { "type": "string", "default": "none" } }, { "name": "environment", "description": "The name of the environment that was deployed to (e.g., `staging` or `production`).", "in": "query", "required": false, "schema": { "type": [ "string", "null" ], "default": "none" } }, { "$ref": "#/components/parameters/per-page" }, { "$ref": "#/components/parameters/page" } ], "responses": { "200": { "description": "Response", "content": { "application/json": { "schema": { "type": "array", "items": { "$ref": "#/components/schemas/deployment" } }, "examples": { "default": { "$ref": "#/components/examples/deployment-items" } } } }, "headers": { "Link": { "$ref": "#/components/headers/link" } } } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": true, "category": "repos", "subcategory": "deployments", "previews": [ { "required": false, "name": "ant-man", "note": "The `inactive` state and the `log_url`, `environment_url`, and `auto_inactive` parameters are currently available for developers to preview. Please see the [blog post](https://developer.github.com/changes/2016-04-06-deployment-and-deployment-status-enhancements) for full details.\n\nTo access the API during the preview period, you must provide a custom [media type](https://docs.github.com/enterprise-server@3.0/rest/overview/media-types) in the `Accept` header:\n```shell\napplication/vnd.github.ant-man-preview+json\n```" } ] } }, "post": { "summary": "Create a deployment", "description": "Deployments offer a few configurable parameters with certain defaults.\n\nThe `ref` parameter can be any named branch, tag, or SHA. At GitHub Enterprise Server we often deploy branches and verify them\nbefore we merge a pull request.\n\nThe `environment` parameter allows deployments to be issued to different runtime environments. Teams often have\nmultiple environments for verifying their applications, such as `production`, `staging`, and `qa`. This parameter\nmakes it easier to track which environments have requested deployments. The default environment is `production`.\n\nThe `auto_merge` parameter is used to ensure that the requested ref is not behind the repository's default branch. If\nthe ref _is_ behind the default branch for the repository, we will attempt to merge it for you. If the merge succeeds,\nthe API will return a successful merge commit. If merge conflicts prevent the merge from succeeding, the API will\nreturn a failure response.\n\nBy default, [commit statuses](https://docs.github.com/enterprise-server@3.0/rest/reference/commits#commit-statuses) for every submitted context must be in a `success`\nstate. The `required_contexts` parameter allows you to specify a subset of contexts that must be `success`, or to\nspecify contexts that have not yet been submitted. You are not required to use commit statuses to deploy. If you do\nnot require any contexts or create any commit statuses, the deployment will always succeed.\n\nThe `payload` parameter is available for any extra information that a deployment system might need. It is a JSON text\nfield that will be passed on when a deployment event is dispatched.\n\nThe `task` parameter is used by the deployment system to allow different execution paths. In the web world this might\nbe `deploy:migrations` to run schema changes on the system. In the compiled world this could be a flag to compile an\napplication with debugging enabled.\n\nUsers with `repo` or `repo_deployment` scopes can create a deployment for a given ref.\n\n#### Merged branch response\nYou will see this response when GitHub automatically merges the base branch into the topic branch instead of creating\na deployment. This auto-merge happens when:\n* Auto-merge option is enabled in the repository\n* Topic branch does not include the latest changes on the base branch, which is `master` in the response example\n* There are no merge conflicts\n\nIf there are no new commits in the base branch, a new request to create a deployment should give a successful\nresponse.\n\n#### Merge conflict response\nThis error happens when the `auto_merge` option is enabled and when the default branch (in this case `master`), can't\nbe merged into the branch that's being deployed (in this case `topic-branch`), due to merge conflicts.\n\n#### Failed commit status checks\nThis error happens when the `required_contexts` parameter indicates that one or more contexts need to have a `success`\nstatus for the commit to be deployed, but one or more of the required contexts do not have a state of `success`.", "tags": [ "repos" ], "operationId": "repos/create-deployment", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/repos#create-a-deployment" }, "parameters": [ { "$ref": "#/components/parameters/owner" }, { "$ref": "#/components/parameters/repo" } ], "requestBody": { "required": true, "content": { "application/json": { "schema": { "type": "object", "properties": { "ref": { "type": "string", "description": "The ref to deploy. This can be a branch, tag, or SHA." }, "task": { "type": "string", "description": "Specifies a task to execute (e.g., `deploy` or `deploy:migrations`).", "default": "deploy" }, "auto_merge": { "type": "boolean", "description": "Attempts to automatically merge the default branch into the requested ref, if it's behind the default branch.", "default": true }, "required_contexts": { "type": "array", "description": "The [status](https://docs.github.com/enterprise-server@3.0/rest/reference/commits#commit-statuses) contexts to verify against commit status checks. If you omit this parameter, GitHub verifies all unique contexts before creating a deployment. To bypass checking entirely, pass an empty array. Defaults to all unique contexts.", "items": { "type": "string" } }, "payload": { "oneOf": [ { "type": "object", "additionalProperties": true }, { "type": "string", "description": "JSON payload with extra information about the deployment.", "default": "" } ] }, "environment": { "type": "string", "description": "Name for the target deployment environment (e.g., `production`, `staging`, `qa`).", "default": "production" }, "description": { "type": [ "string", "null" ], "description": "Short description of the deployment.", "default": "" }, "transient_environment": { "type": "boolean", "description": "Specifies if the given environment is specific to the deployment and will no longer exist at some point in the future. Default: `false` \n**Note:** This parameter requires you to use the [`application/vnd.github.ant-man-preview+json`](https://docs.github.com/enterprise-server@3.0/rest/overview/api-previews#enhanced-deployments) custom media type.", "default": false }, "production_environment": { "type": "boolean", "description": "Specifies if the given environment is one that end-users directly interact with. Default: `true` when `environment` is `production` and `false` otherwise. \n**Note:** This parameter requires you to use the [`application/vnd.github.ant-man-preview+json`](https://docs.github.com/enterprise-server@3.0/rest/overview/api-previews#enhanced-deployments) custom media type." } }, "required": [ "ref" ] }, "examples": { "simple-example": { "summary": "Simple example", "value": { "ref": "topic-branch", "payload": "{ \"deploy\": \"migrate\" }", "description": "Deploy request from hubot" } }, "advanced-example": { "summary": "Advanced example", "value": { "ref": "topic-branch", "auto_merge": false, "payload": "{ \"deploy\": \"migrate\" }", "description": "Deploy request from hubot", "required_contexts": [ "ci/janky", "security/brakeman" ] } } } } } }, "responses": { "201": { "description": "Response", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/deployment" }, "examples": { "simple-example": { "$ref": "#/components/examples/deployment-simple-example" } } } } }, "202": { "description": "Merged branch response", "content": { "application/json": { "schema": { "type": "object", "properties": { "message": { "type": "string" } } }, "examples": { "merged-branch-response": { "value": { "message": "Auto-merged master into topic-branch on deployment." } } } } } }, "409": { "description": "Conflict when there is a merge conflict or the commit's status checks failed" }, "422": { "$ref": "#/components/responses/validation_failed" } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": true, "category": "repos", "subcategory": "deployments", "previews": [ { "required": false, "name": "ant-man", "note": "The `inactive` state and the `log_url`, `environment_url`, and `auto_inactive` parameters are currently available for developers to preview. Please see the [blog post](https://developer.github.com/changes/2016-04-06-deployment-and-deployment-status-enhancements) for full details.\n\nTo access the API during the preview period, you must provide a custom [media type](https://docs.github.com/enterprise-server@3.0/rest/overview/media-types) in the `Accept` header:\n```shell\napplication/vnd.github.ant-man-preview+json\n```" } ] } } }, "/repos/{owner}/{repo}/deployments/{deployment_id}": { "get": { "summary": "Get a deployment", "description": "", "tags": [ "repos" ], "operationId": "repos/get-deployment", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/repos#get-a-deployment" }, "parameters": [ { "$ref": "#/components/parameters/owner" }, { "$ref": "#/components/parameters/repo" }, { "$ref": "#/components/parameters/deployment-id" } ], "responses": { "200": { "description": "Response", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/deployment" }, "examples": { "default": { "$ref": "#/components/examples/deployment" } } } } }, "404": { "$ref": "#/components/responses/not_found" } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": true, "category": "repos", "subcategory": "deployments", "previews": [ { "required": false, "name": "flash", "note": "New features in the Deployments API on GitHub are currently available during a public beta. Please see the [blog post](https://developer.github.com/changes/2018-10-16-deployments-environments-states-and-auto-inactive-updates/) for full details.\n\nTo access the new `environment` parameter, the two new values for the `state` parameter (`in_progress` and `queued`), and use `auto_inactive` on production deployments during the public beta period, you must provide the following custom [media type](https://docs.github.com/enterprise-server@3.0/rest/overview/media-types) in the `Accept` header:\n```shell\napplication/vnd.github.flash-preview+json\n```" }, { "required": false, "name": "ant-man", "note": "The `inactive` state and the `log_url`, `environment_url`, and `auto_inactive` parameters are currently available for developers to preview. Please see the [blog post](https://developer.github.com/changes/2016-04-06-deployment-and-deployment-status-enhancements) for full details.\n\nTo access the API during the preview period, you must provide a custom [media type](https://docs.github.com/enterprise-server@3.0/rest/overview/media-types) in the `Accept` header:\n```shell\napplication/vnd.github.ant-man-preview+json\n```" } ] } }, "delete": { "summary": "Delete a deployment", "description": "If the repository only has one deployment, you can delete the deployment regardless of its status. If the repository has more than one deployment, you can only delete inactive deployments. This ensures that repositories with multiple deployments will always have an active deployment. Anyone with `repo` or `repo_deployment` scopes can delete a deployment.\n\nTo set a deployment as inactive, you must:\n\n* Create a new deployment that is active so that the system has a record of the current state, then delete the previously active deployment.\n* Mark the active deployment as inactive by adding any non-successful deployment status.\n\nFor more information, see \"[Create a deployment](https://docs.github.com/enterprise-server@3.0/rest/reference/repos/#create-a-deployment)\" and \"[Create a deployment status](https://docs.github.com/enterprise-server@3.0/rest/reference/repos#create-a-deployment-status).\"", "tags": [ "repos" ], "operationId": "repos/delete-deployment", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/repos#delete-a-deployment" }, "parameters": [ { "$ref": "#/components/parameters/owner" }, { "$ref": "#/components/parameters/repo" }, { "$ref": "#/components/parameters/deployment-id" } ], "responses": { "204": { "description": "Response" }, "404": { "$ref": "#/components/responses/not_found" }, "422": { "$ref": "#/components/responses/validation_failed_simple" } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": true, "category": "repos", "subcategory": "deployments" } } }, "/repos/{owner}/{repo}/deployments/{deployment_id}/statuses": { "get": { "summary": "List deployment statuses", "description": "Users with pull access can view deployment statuses for a deployment:", "tags": [ "repos" ], "operationId": "repos/list-deployment-statuses", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/repos#list-deployment-statuses" }, "parameters": [ { "$ref": "#/components/parameters/owner" }, { "$ref": "#/components/parameters/repo" }, { "$ref": "#/components/parameters/deployment-id" }, { "$ref": "#/components/parameters/per-page" }, { "$ref": "#/components/parameters/page" } ], "responses": { "200": { "description": "Response", "content": { "application/json": { "schema": { "type": "array", "items": { "$ref": "#/components/schemas/deployment-status" } }, "examples": { "default": { "$ref": "#/components/examples/deployment-status-items" } } } }, "headers": { "Link": { "$ref": "#/components/headers/link" } } }, "404": { "$ref": "#/components/responses/not_found" } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": true, "category": "repos", "subcategory": "deployments", "previews": [ { "required": false, "name": "flash", "note": "New features in the Deployments API on GitHub are currently available during a public beta. Please see the [blog post](https://developer.github.com/changes/2018-10-16-deployments-environments-states-and-auto-inactive-updates/) for full details.\n\nTo access the new `environment` parameter, the two new values for the `state` parameter (`in_progress` and `queued`), and use `auto_inactive` on production deployments during the public beta period, you must provide the following custom [media type](https://docs.github.com/enterprise-server@3.0/rest/overview/media-types) in the `Accept` header:\n```shell\napplication/vnd.github.flash-preview+json\n```" }, { "required": false, "name": "ant-man", "note": "The `inactive` state and the `log_url`, `environment_url`, and `auto_inactive` parameters are currently available for developers to preview. Please see the [blog post](https://developer.github.com/changes/2016-04-06-deployment-and-deployment-status-enhancements) for full details.\n\nTo access the API during the preview period, you must provide a custom [media type](https://docs.github.com/enterprise-server@3.0/rest/overview/media-types) in the `Accept` header:\n```shell\napplication/vnd.github.ant-man-preview+json\n```" } ] } }, "post": { "summary": "Create a deployment status", "description": "Users with `push` access can create deployment statuses for a given deployment.\n\nGitHub Apps require `read & write` access to \"Deployments\" and `read-only` access to \"Repo contents\" (for private repos). OAuth Apps require the `repo_deployment` scope.", "tags": [ "repos" ], "operationId": "repos/create-deployment-status", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/repos#create-a-deployment-status" }, "parameters": [ { "$ref": "#/components/parameters/owner" }, { "$ref": "#/components/parameters/repo" }, { "$ref": "#/components/parameters/deployment-id" } ], "requestBody": { "required": true, "content": { "application/json": { "schema": { "type": "object", "properties": { "state": { "type": "string", "description": "The state of the status. Can be one of `error`, `failure`, `inactive`, `in_progress`, `queued`, `pending`, or `success`. **Note:** To use the `inactive` state, you must provide the [`application/vnd.github.ant-man-preview+json`](https://docs.github.com/enterprise-server@3.0/rest/overview/api-previews#enhanced-deployments) custom media type. When you set a transient deployment to `inactive`, the deployment will be shown as `destroyed` in GitHub.", "enum": [ "error", "failure", "inactive", "in_progress", "queued", "pending", "success" ] }, "target_url": { "type": "string", "description": "The target URL to associate with this status. This URL should contain output to keep the user updated while the task is running or serve as historical information for what happened in the deployment. **Note:** It's recommended to use the `log_url` parameter, which replaces `target_url`.", "default": "" }, "log_url": { "type": "string", "description": "The full URL of the deployment's output. This parameter replaces `target_url`. We will continue to accept `target_url` to support legacy uses, but we recommend replacing `target_url` with `log_url`. Setting `log_url` will automatically set `target_url` to the same value. Default: `\"\"` \n**Note:** This parameter requires you to use the [`application/vnd.github.ant-man-preview+json`](https://docs.github.com/enterprise-server@3.0/rest/overview/api-previews#enhanced-deployments) custom media type.", "default": "" }, "description": { "type": "string", "description": "A short description of the status. The maximum description length is 140 characters.", "default": "" }, "environment": { "type": "string", "description": "Name for the target deployment environment, which can be changed when setting a deploy status. For example, `production`, `staging`, or `qa`.", "enum": [ "production", "staging", "qa" ] }, "environment_url": { "type": "string", "description": "Sets the URL for accessing your environment. Default: `\"\"` \n**Note:** This parameter requires you to use the [`application/vnd.github.ant-man-preview+json`](https://docs.github.com/enterprise-server@3.0/rest/overview/api-previews#enhanced-deployments) custom media type.", "default": "" }, "auto_inactive": { "type": "boolean", "description": "Adds a new `inactive` status to all prior non-transient, non-production environment deployments with the same repository and `environment` name as the created status's deployment. An `inactive` status is only added to deployments that had a `success` state. Default: `true` \n**Note:** This parameter requires you to use the [`application/vnd.github.ant-man-preview+json`](https://docs.github.com/enterprise-server@3.0/rest/overview/api-previews#enhanced-deployments) custom media type." } }, "required": [ "state" ] }, "example": { "environment": "production", "state": "success", "log_url": "https://example.com/deployment/42/output", "description": "Deployment finished successfully." } } } }, "responses": { "201": { "description": "Response", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/deployment-status" }, "examples": { "default": { "$ref": "#/components/examples/deployment-status" } } } }, "headers": { "Location": { "example": "https://api.github.com/repos/octocat/example/deployments/42/statuses/1", "schema": { "type": "string" } } } }, "422": { "$ref": "#/components/responses/validation_failed" } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": true, "category": "repos", "subcategory": "deployments", "previews": [ { "required": false, "name": "flash", "note": "New features in the Deployments API on GitHub are currently available during a public beta. Please see the [blog post](https://developer.github.com/changes/2018-10-16-deployments-environments-states-and-auto-inactive-updates/) for full details.\n\nTo access the new `environment` parameter, the two new values for the `state` parameter (`in_progress` and `queued`), and use `auto_inactive` on production deployments during the public beta period, you must provide the following custom [media type](https://docs.github.com/enterprise-server@3.0/rest/overview/media-types) in the `Accept` header:\n```shell\napplication/vnd.github.flash-preview+json\n```" }, { "required": false, "name": "ant-man", "note": "The `inactive` state and the `log_url`, `environment_url`, and `auto_inactive` parameters are currently available for developers to preview. Please see the [blog post](https://developer.github.com/changes/2016-04-06-deployment-and-deployment-status-enhancements) for full details.\n\nTo access the API during the preview period, you must provide a custom [media type](https://docs.github.com/enterprise-server@3.0/rest/overview/media-types) in the `Accept` header:\n```shell\napplication/vnd.github.ant-man-preview+json\n```" } ] } } }, "/repos/{owner}/{repo}/deployments/{deployment_id}/statuses/{status_id}": { "get": { "summary": "Get a deployment status", "description": "Users with pull access can view a deployment status for a deployment:", "tags": [ "repos" ], "operationId": "repos/get-deployment-status", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/repos#get-a-deployment-status" }, "parameters": [ { "$ref": "#/components/parameters/owner" }, { "$ref": "#/components/parameters/repo" }, { "$ref": "#/components/parameters/deployment-id" }, { "name": "status_id", "in": "path", "required": true, "schema": { "type": "integer" } } ], "responses": { "200": { "description": "Response", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/deployment-status" }, "examples": { "default": { "$ref": "#/components/examples/deployment-status" } } } } }, "404": { "$ref": "#/components/responses/not_found" } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": true, "category": "repos", "subcategory": "deployments", "previews": [ { "required": false, "name": "flash", "note": "New features in the Deployments API on GitHub are currently available during a public beta. Please see the [blog post](https://developer.github.com/changes/2018-10-16-deployments-environments-states-and-auto-inactive-updates/) for full details.\n\nTo access the new `environment` parameter, the two new values for the `state` parameter (`in_progress` and `queued`), and use `auto_inactive` on production deployments during the public beta period, you must provide the following custom [media type](https://docs.github.com/enterprise-server@3.0/rest/overview/media-types) in the `Accept` header:\n```shell\napplication/vnd.github.flash-preview+json\n```" }, { "required": false, "name": "ant-man", "note": "The `inactive` state and the `log_url`, `environment_url`, and `auto_inactive` parameters are currently available for developers to preview. Please see the [blog post](https://developer.github.com/changes/2016-04-06-deployment-and-deployment-status-enhancements) for full details.\n\nTo access the API during the preview period, you must provide a custom [media type](https://docs.github.com/enterprise-server@3.0/rest/overview/media-types) in the `Accept` header:\n```shell\napplication/vnd.github.ant-man-preview+json\n```" } ] } } }, "/repos/{owner}/{repo}/dispatches": { "post": { "summary": "Create a repository dispatch event", "description": "You can use this endpoint to trigger a webhook event called `repository_dispatch` when you want activity that happens outside of GitHub Enterprise Server to trigger a GitHub Actions workflow or GitHub App webhook. You must configure your GitHub Actions workflow or GitHub App to run when the `repository_dispatch` event occurs. For an example `repository_dispatch` webhook payload, see \"[RepositoryDispatchEvent](https://docs.github.com/enterprise-server@3.0/webhooks/event-payloads/#repository_dispatch).\"\n\nThe `client_payload` parameter is available for any extra information that your workflow might need. This parameter is a JSON payload that will be passed on when the webhook event is dispatched. For example, the `client_payload` can include a message that a user would like to send using a GitHub Actions workflow. Or the `client_payload` can be used as a test to debug your workflow.\n\nThis endpoint requires write access to the repository by providing either:\n\n - Personal access tokens with `repo` scope. For more information, see \"[Creating a personal access token for the command line](https://docs.github.com/articles/creating-a-personal-access-token-for-the-command-line)\" in the GitHub Help documentation.\n - GitHub Apps with both `metadata:read` and `contents:read&write` permissions.\n\nThis input example shows how you can use the `client_payload` as a test to debug your workflow.", "tags": [ "repos" ], "operationId": "repos/create-dispatch-event", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/repos#create-a-repository-dispatch-event" }, "parameters": [ { "$ref": "#/components/parameters/owner" }, { "$ref": "#/components/parameters/repo" } ], "requestBody": { "required": true, "content": { "application/json": { "schema": { "type": "object", "required": [ "event_type" ], "properties": { "event_type": { "type": "string", "description": "A custom webhook event name.", "minLength": 1, "maxLength": 100 }, "client_payload": { "type": "object", "description": "JSON payload with extra information about the webhook event that your action or worklow may use.", "additionalProperties": true, "maxProperties": 10 } } }, "example": { "event_type": "on-demand-test", "client_payload": { "unit": false, "integration": true } } } } }, "responses": { "204": { "description": "Response" }, "422": { "$ref": "#/components/responses/validation_failed" } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": true, "category": "repos", "subcategory": null } } }, "/repos/{owner}/{repo}/events": { "get": { "summary": "List repository events", "description": "", "tags": [ "activity" ], "operationId": "activity/list-repo-events", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/activity#list-repository-events" }, "parameters": [ { "$ref": "#/components/parameters/owner" }, { "$ref": "#/components/parameters/repo" }, { "$ref": "#/components/parameters/per-page" }, { "$ref": "#/components/parameters/page" } ], "responses": { "200": { "description": "Response", "content": { "application/json": { "schema": { "type": "array", "items": { "$ref": "#/components/schemas/event" } } } } } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": true, "category": "activity", "subcategory": "events" } } }, "/repos/{owner}/{repo}/forks": { "get": { "summary": "List forks", "description": "", "tags": [ "repos" ], "operationId": "repos/list-forks", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/repos#list-forks" }, "parameters": [ { "$ref": "#/components/parameters/owner" }, { "$ref": "#/components/parameters/repo" }, { "name": "sort", "description": "The sort order. Can be either `newest`, `oldest`, or `stargazers`.", "in": "query", "required": false, "schema": { "type": "string", "enum": [ "newest", "oldest", "stargazers", "watchers" ], "default": "newest" } }, { "$ref": "#/components/parameters/per-page" }, { "$ref": "#/components/parameters/page" } ], "responses": { "200": { "description": "Response", "content": { "application/json": { "schema": { "type": "array", "items": { "$ref": "#/components/schemas/minimal-repository" } }, "examples": { "default": { "$ref": "#/components/examples/minimal-repository-items-2" } } } }, "headers": { "Link": { "$ref": "#/components/headers/link" } } }, "400": { "$ref": "#/components/responses/bad_request" } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": true, "category": "repos", "subcategory": "forks" } }, "post": { "summary": "Create a fork", "description": "Create a fork for the authenticated user.\n\n**Note**: Forking a Repository happens asynchronously. You may have to wait a short period of time before you can access the git objects. If this takes longer than 5 minutes, be sure to contact [GitHub Enterprise Server Support](https://support.github.com/contact?tags=dotcom-rest-api).", "tags": [ "repos" ], "operationId": "repos/create-fork", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/repos#create-a-fork" }, "parameters": [ { "$ref": "#/components/parameters/owner" }, { "$ref": "#/components/parameters/repo" } ], "requestBody": { "required": false, "content": { "application/json": { "schema": { "type": [ "object", "null" ], "properties": { "organization": { "type": "string", "description": "Optional parameter to specify the organization name if forking into an organization." } } } } } }, "responses": { "202": { "description": "Response", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/full-repository" }, "examples": { "default": { "$ref": "#/components/examples/full-repository" } } } } }, "400": { "$ref": "#/components/responses/bad_request" }, "422": { "$ref": "#/components/responses/validation_failed" }, "403": { "$ref": "#/components/responses/forbidden" }, "404": { "$ref": "#/components/responses/not_found" } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": true, "category": "repos", "subcategory": "forks" } } }, "/repos/{owner}/{repo}/git/blobs": { "post": { "summary": "Create a blob", "description": "", "tags": [ "git" ], "operationId": "git/create-blob", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/git#create-a-blob" }, "parameters": [ { "$ref": "#/components/parameters/owner" }, { "$ref": "#/components/parameters/repo" } ], "requestBody": { "required": true, "content": { "application/json": { "schema": { "type": "object", "properties": { "content": { "type": "string", "description": "The new blob's content." }, "encoding": { "type": "string", "description": "The encoding used for `content`. Currently, `\"utf-8\"` and `\"base64\"` are supported.", "default": "utf-8" } }, "required": [ "content" ] }, "example": { "content": "Content of the blob", "encoding": "utf-8" } } } }, "responses": { "201": { "description": "Response", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/short-blob" }, "examples": { "default": { "$ref": "#/components/examples/short-blob" } } } }, "headers": { "Location": { "example": "https://api.github.com/repos/octocat/example/git/blobs/3a0f86fb8db8eea7ccbb9a95f325ddbedfb25e15", "schema": { "type": "string" } } } }, "404": { "$ref": "#/components/responses/not_found" }, "409": { "$ref": "#/components/responses/conflict" }, "403": { "$ref": "#/components/responses/forbidden" }, "422": { "$ref": "#/components/responses/validation_failed" } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": true, "category": "git", "subcategory": "blobs" } } }, "/repos/{owner}/{repo}/git/blobs/{file_sha}": { "get": { "summary": "Get a blob", "description": "The `content` in the response will always be Base64 encoded.\n\n_Note_: This API supports blobs up to 100 megabytes in size.", "tags": [ "git" ], "operationId": "git/get-blob", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/git#get-a-blob" }, "parameters": [ { "$ref": "#/components/parameters/owner" }, { "$ref": "#/components/parameters/repo" }, { "name": "file_sha", "in": "path", "required": true, "schema": { "type": "string" } } ], "responses": { "200": { "description": "Response", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/blob" }, "examples": { "default": { "$ref": "#/components/examples/blob" } } } } }, "404": { "$ref": "#/components/responses/not_found" }, "422": { "$ref": "#/components/responses/validation_failed" }, "403": { "$ref": "#/components/responses/forbidden" } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": true, "category": "git", "subcategory": "blobs" } } }, "/repos/{owner}/{repo}/git/commits": { "post": { "summary": "Create a commit", "description": "Creates a new Git [commit object](https://git-scm.com/book/en/v1/Git-Internals-Git-Objects#Commit-Objects).\n\n**Signature verification object**\n\nThe response will include a `verification` object that describes the result of verifying the commit's signature. The following fields are included in the `verification` object:\n\n| Name | Type | Description |\n| ---- | ---- | ----------- |\n| `verified` | `boolean` | Indicates whether GitHub considers the signature in this commit to be verified. |\n| `reason` | `string` | The reason for verified value. Possible values and their meanings are enumerated in table below. |\n| `signature` | `string` | The signature that was extracted from the commit. |\n| `payload` | `string` | The value that was signed. |\n\nThese are the possible values for `reason` in the `verification` object:\n\n| Value | Description |\n| ----- | ----------- |\n| `expired_key` | The key that made the signature is expired. |\n| `not_signing_key` | The \"signing\" flag is not among the usage flags in the GPG key that made the signature. |\n| `gpgverify_error` | There was an error communicating with the signature verification service. |\n| `gpgverify_unavailable` | The signature verification service is currently unavailable. |\n| `unsigned` | The object does not include a signature. |\n| `unknown_signature_type` | A non-PGP signature was found in the commit. |\n| `no_user` | No user was associated with the `committer` email address in the commit. |\n| `unverified_email` | The `committer` email address in the commit was associated with a user, but the email address is not verified on her/his account. |\n| `bad_email` | The `committer` email address in the commit is not included in the identities of the PGP key that made the signature. |\n| `unknown_key` | The key that made the signature has not been registered with any user's account. |\n| `malformed_signature` | There was an error parsing the signature. |\n| `invalid` | The signature could not be cryptographically verified using the key whose key-id was found in the signature. |\n| `valid` | None of the above errors applied, so the signature is considered to be verified. |", "tags": [ "git" ], "operationId": "git/create-commit", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/git#create-a-commit" }, "parameters": [ { "$ref": "#/components/parameters/owner" }, { "$ref": "#/components/parameters/repo" } ], "requestBody": { "required": true, "content": { "application/json": { "schema": { "type": "object", "properties": { "message": { "type": "string", "description": "The commit message" }, "tree": { "type": "string", "description": "The SHA of the tree object this commit points to" }, "parents": { "type": "array", "description": "The SHAs of the commits that were the parents of this commit. If omitted or empty, the commit will be written as a root commit. For a single parent, an array of one SHA should be provided; for a merge commit, an array of more than one should be provided.", "items": { "type": "string" } }, "author": { "type": "object", "description": "Information about the author of the commit. By default, the `author` will be the authenticated user and the current date. See the `author` and `committer` object below for details.", "properties": { "name": { "type": "string", "description": "The name of the author (or committer) of the commit" }, "email": { "type": "string", "description": "The email of the author (or committer) of the commit" }, "date": { "type": "string", "format": "date-time", "description": "Indicates when this commit was authored (or committed). This is a timestamp in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format: `YYYY-MM-DDTHH:MM:SSZ`." } }, "required": [ "name", "email" ] }, "committer": { "type": "object", "description": "Information about the person who is making the commit. By default, `committer` will use the information set in `author`. See the `author` and `committer` object below for details.", "properties": { "name": { "type": "string", "description": "The name of the author (or committer) of the commit" }, "email": { "type": "string", "description": "The email of the author (or committer) of the commit" }, "date": { "type": "string", "format": "date-time", "description": "Indicates when this commit was authored (or committed). This is a timestamp in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format: `YYYY-MM-DDTHH:MM:SSZ`." } } }, "signature": { "type": "string", "description": "The [PGP signature](https://en.wikipedia.org/wiki/Pretty_Good_Privacy) of the commit. GitHub adds the signature to the `gpgsig` header of the created commit. For a commit signature to be verifiable by Git or GitHub, it must be an ASCII-armored detached PGP signature over the string commit as it would be written to the object database. To pass a `signature` parameter, you need to first manually create a valid PGP signature, which can be complicated. You may find it easier to [use the command line](https://git-scm.com/book/id/v2/Git-Tools-Signing-Your-Work) to create signed commits." } }, "required": [ "message", "tree" ] }, "example": { "message": "my commit message", "author": { "name": "Mona Octocat", "email": "octocat@github.com", "date": "2008-07-09T16:13:30+12:00" }, "parents": [ "7d1b31e74ee336d15cbd21741bc88a537ed063a0" ], "tree": "827efc6d56897b048c772eb4087f854f46256132", "signature": "-----BEGIN PGP SIGNATURE-----\n\niQIzBAABAQAdFiEESn/54jMNIrGSE6Tp6cQjvhfv7nAFAlnT71cACgkQ6cQjvhfv\n7nCWwA//XVqBKWO0zF+bZl6pggvky3Oc2j1pNFuRWZ29LXpNuD5WUGXGG209B0hI\nDkmcGk19ZKUTnEUJV2Xd0R7AW01S/YSub7OYcgBkI7qUE13FVHN5ln1KvH2all2n\n2+JCV1HcJLEoTjqIFZSSu/sMdhkLQ9/NsmMAzpf/iIM0nQOyU4YRex9eD1bYj6nA\nOQPIDdAuaTQj1gFPHYLzM4zJnCqGdRlg0sOM/zC5apBNzIwlgREatOYQSCfCKV7k\nnrU34X8b9BzQaUx48Qa+Dmfn5KQ8dl27RNeWAqlkuWyv3pUauH9UeYW+KyuJeMkU\n+NyHgAsWFaCFl23kCHThbLStMZOYEnGagrd0hnm1TPS4GJkV4wfYMwnI4KuSlHKB\njHl3Js9vNzEUQipQJbgCgTiWvRJoK3ENwBTMVkKHaqT4x9U4Jk/XZB6Q8MA09ezJ\n3QgiTjTAGcum9E9QiJqMYdWQPWkaBIRRz5cET6HPB48YNXAAUsfmuYsGrnVLYbG+\nUpC6I97VybYHTy2O9XSGoaLeMI9CsFn38ycAxxbWagk5mhclNTP5mezIq6wKSwmr\nX11FW3n1J23fWZn5HJMBsRnUCgzqzX3871IqLYHqRJ/bpZ4h20RhTyPj5c/z7QXp\neSakNQMfbbMcljkha+ZMuVQX1K9aRlVqbmv3ZMWh+OijLYVU2bc=\n=5Io4\n-----END PGP SIGNATURE-----\n" } } } }, "responses": { "201": { "description": "Response", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/git-commit" }, "examples": { "default": { "$ref": "#/components/examples/git-commit" } } } }, "headers": { "Location": { "example": "https://api.github.com/repos/octocat/Hello-World/git/commits/7638417db6d59f3c431d3e1f261cc637155684cd", "schema": { "type": "string" } } } }, "422": { "$ref": "#/components/responses/validation_failed" }, "404": { "$ref": "#/components/responses/not_found" } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": true, "category": "git", "subcategory": "commits" } } }, "/repos/{owner}/{repo}/git/commits/{commit_sha}": { "get": { "summary": "Get a commit", "description": "Gets a Git [commit object](https://git-scm.com/book/en/v1/Git-Internals-Git-Objects#Commit-Objects).\n\n**Signature verification object**\n\nThe response will include a `verification` object that describes the result of verifying the commit's signature. The following fields are included in the `verification` object:\n\n| Name | Type | Description |\n| ---- | ---- | ----------- |\n| `verified` | `boolean` | Indicates whether GitHub considers the signature in this commit to be verified. |\n| `reason` | `string` | The reason for verified value. Possible values and their meanings are enumerated in table below. |\n| `signature` | `string` | The signature that was extracted from the commit. |\n| `payload` | `string` | The value that was signed. |\n\nThese are the possible values for `reason` in the `verification` object:\n\n| Value | Description |\n| ----- | ----------- |\n| `expired_key` | The key that made the signature is expired. |\n| `not_signing_key` | The \"signing\" flag is not among the usage flags in the GPG key that made the signature. |\n| `gpgverify_error` | There was an error communicating with the signature verification service. |\n| `gpgverify_unavailable` | The signature verification service is currently unavailable. |\n| `unsigned` | The object does not include a signature. |\n| `unknown_signature_type` | A non-PGP signature was found in the commit. |\n| `no_user` | No user was associated with the `committer` email address in the commit. |\n| `unverified_email` | The `committer` email address in the commit was associated with a user, but the email address is not verified on her/his account. |\n| `bad_email` | The `committer` email address in the commit is not included in the identities of the PGP key that made the signature. |\n| `unknown_key` | The key that made the signature has not been registered with any user's account. |\n| `malformed_signature` | There was an error parsing the signature. |\n| `invalid` | The signature could not be cryptographically verified using the key whose key-id was found in the signature. |\n| `valid` | None of the above errors applied, so the signature is considered to be verified. |", "tags": [ "git" ], "operationId": "git/get-commit", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/git#get-a-commit" }, "parameters": [ { "$ref": "#/components/parameters/owner" }, { "$ref": "#/components/parameters/repo" }, { "$ref": "#/components/parameters/commit-sha" } ], "responses": { "200": { "description": "Response", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/git-commit" }, "examples": { "default": { "$ref": "#/components/examples/git-commit-2" } } } } }, "404": { "$ref": "#/components/responses/not_found" } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": true, "category": "git", "subcategory": "commits" } } }, "/repos/{owner}/{repo}/git/matching-refs/{ref}": { "get": { "summary": "List matching references", "description": "Returns an array of references from your Git database that match the supplied name. The `:ref` in the URL must be formatted as `heads/` for branches and `tags/` for tags. If the `:ref` doesn't exist in the repository, but existing refs start with `:ref`, they will be returned as an array.\n\nWhen you use this endpoint without providing a `:ref`, it will return an array of all the references from your Git database, including notes and stashes if they exist on the server. Anything in the namespace is returned, not just `heads` and `tags`.\n\n**Note:** You need to explicitly [request a pull request](https://docs.github.com/enterprise-server@3.0/rest/reference/pulls#get-a-pull-request) to trigger a test merge commit, which checks the mergeability of pull requests. For more information, see \"[Checking mergeability of pull requests](https://docs.github.com/enterprise-server@3.0/rest/guides/getting-started-with-the-git-database-api#checking-mergeability-of-pull-requests)\".\n\nIf you request matching references for a branch named `feature` but the branch `feature` doesn't exist, the response can still include other matching head refs that start with the word `feature`, such as `featureA` and `featureB`.", "tags": [ "git" ], "operationId": "git/list-matching-refs", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/git#list-matching-references" }, "parameters": [ { "$ref": "#/components/parameters/owner" }, { "$ref": "#/components/parameters/repo" }, { "name": "ref", "description": "ref parameter", "in": "path", "required": true, "schema": { "type": "string" }, "x-multi-segment": true }, { "$ref": "#/components/parameters/per-page" }, { "$ref": "#/components/parameters/page" } ], "responses": { "200": { "description": "Response", "content": { "application/json": { "schema": { "type": "array", "items": { "$ref": "#/components/schemas/git-ref" } }, "examples": { "default": { "$ref": "#/components/examples/git-ref-items" } } } }, "headers": { "Link": { "$ref": "#/components/headers/link" } } } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": true, "category": "git", "subcategory": "refs" } } }, "/repos/{owner}/{repo}/git/ref/{ref}": { "get": { "summary": "Get a reference", "description": "Returns a single reference from your Git database. The `:ref` in the URL must be formatted as `heads/` for branches and `tags/` for tags. If the `:ref` doesn't match an existing ref, a `404` is returned.\n\n**Note:** You need to explicitly [request a pull request](https://docs.github.com/enterprise-server@3.0/rest/reference/pulls#get-a-pull-request) to trigger a test merge commit, which checks the mergeability of pull requests. For more information, see \"[Checking mergeability of pull requests](https://docs.github.com/enterprise-server@3.0/rest/guides/getting-started-with-the-git-database-api#checking-mergeability-of-pull-requests)\".", "tags": [ "git" ], "operationId": "git/get-ref", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/git#get-a-reference" }, "parameters": [ { "$ref": "#/components/parameters/owner" }, { "$ref": "#/components/parameters/repo" }, { "name": "ref", "description": "ref parameter", "in": "path", "required": true, "schema": { "type": "string" }, "x-multi-segment": true } ], "responses": { "200": { "description": "Response", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/git-ref" }, "examples": { "default": { "$ref": "#/components/examples/git-ref" } } } } }, "404": { "$ref": "#/components/responses/not_found" } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": true, "category": "git", "subcategory": "refs" } } }, "/repos/{owner}/{repo}/git/refs": { "post": { "summary": "Create a reference", "description": "Creates a reference for your repository. You are unable to create new references for empty repositories, even if the commit SHA-1 hash used exists. Empty repositories are repositories without branches.", "tags": [ "git" ], "operationId": "git/create-ref", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/git#create-a-reference" }, "parameters": [ { "$ref": "#/components/parameters/owner" }, { "$ref": "#/components/parameters/repo" } ], "requestBody": { "required": true, "content": { "application/json": { "schema": { "type": "object", "properties": { "ref": { "type": "string", "description": "The name of the fully qualified reference (ie: `refs/heads/master`). If it doesn't start with 'refs' and have at least two slashes, it will be rejected." }, "sha": { "type": "string", "description": "The SHA1 value for this reference." }, "key": { "type": "string", "examples": [ "\"refs/heads/newbranch\"" ] } }, "required": [ "ref", "sha" ] }, "example": { "ref": "refs/heads/featureA", "sha": "aa218f56b14c9653891f9e74264a383fa43fefbd" } } } }, "responses": { "201": { "description": "Response", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/git-ref" }, "examples": { "default": { "$ref": "#/components/examples/git-ref" } } } }, "headers": { "Location": { "example": "https://api.github.com/repos/octocat/Hello-World/git/refs/heads/featureA", "schema": { "type": "string" } } } }, "422": { "$ref": "#/components/responses/validation_failed" } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": true, "category": "git", "subcategory": "refs" } } }, "/repos/{owner}/{repo}/git/refs/{ref}": { "patch": { "summary": "Update a reference", "description": "", "tags": [ "git" ], "operationId": "git/update-ref", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/git#update-a-reference" }, "parameters": [ { "$ref": "#/components/parameters/owner" }, { "$ref": "#/components/parameters/repo" }, { "name": "ref", "description": "ref parameter", "in": "path", "required": true, "schema": { "type": "string" }, "x-multi-segment": true } ], "requestBody": { "required": true, "content": { "application/json": { "schema": { "type": "object", "properties": { "sha": { "type": "string", "description": "The SHA1 value to set this reference to" }, "force": { "type": "boolean", "description": "Indicates whether to force the update or to make sure the update is a fast-forward update. Leaving this out or setting it to `false` will make sure you're not overwriting work.", "default": false } }, "required": [ "sha" ] }, "example": { "sha": "aa218f56b14c9653891f9e74264a383fa43fefbd", "force": true } } } }, "responses": { "200": { "description": "Response", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/git-ref" }, "examples": { "default": { "$ref": "#/components/examples/git-ref" } } } } }, "422": { "$ref": "#/components/responses/validation_failed" } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": true, "category": "git", "subcategory": "refs" } }, "delete": { "summary": "Delete a reference", "description": "", "tags": [ "git" ], "operationId": "git/delete-ref", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/git#delete-a-reference" }, "parameters": [ { "$ref": "#/components/parameters/owner" }, { "$ref": "#/components/parameters/repo" }, { "name": "ref", "description": "ref parameter", "in": "path", "required": true, "schema": { "type": "string" }, "x-multi-segment": true } ], "responses": { "204": { "description": "Response" }, "422": { "$ref": "#/components/responses/validation_failed" } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": true, "category": "git", "subcategory": "refs" } } }, "/repos/{owner}/{repo}/git/tags": { "post": { "summary": "Create a tag object", "description": "Note that creating a tag object does not create the reference that makes a tag in Git. If you want to create an annotated tag in Git, you have to do this call to create the tag object, and then [create](https://docs.github.com/enterprise-server@3.0/rest/reference/git#create-a-reference) the `refs/tags/[tag]` reference. If you want to create a lightweight tag, you only have to [create](https://docs.github.com/enterprise-server@3.0/rest/reference/git#create-a-reference) the tag reference - this call would be unnecessary.\n\n**Signature verification object**\n\nThe response will include a `verification` object that describes the result of verifying the commit's signature. The following fields are included in the `verification` object:\n\n| Name | Type | Description |\n| ---- | ---- | ----------- |\n| `verified` | `boolean` | Indicates whether GitHub considers the signature in this commit to be verified. |\n| `reason` | `string` | The reason for verified value. Possible values and their meanings are enumerated in table below. |\n| `signature` | `string` | The signature that was extracted from the commit. |\n| `payload` | `string` | The value that was signed. |\n\nThese are the possible values for `reason` in the `verification` object:\n\n| Value | Description |\n| ----- | ----------- |\n| `expired_key` | The key that made the signature is expired. |\n| `not_signing_key` | The \"signing\" flag is not among the usage flags in the GPG key that made the signature. |\n| `gpgverify_error` | There was an error communicating with the signature verification service. |\n| `gpgverify_unavailable` | The signature verification service is currently unavailable. |\n| `unsigned` | The object does not include a signature. |\n| `unknown_signature_type` | A non-PGP signature was found in the commit. |\n| `no_user` | No user was associated with the `committer` email address in the commit. |\n| `unverified_email` | The `committer` email address in the commit was associated with a user, but the email address is not verified on her/his account. |\n| `bad_email` | The `committer` email address in the commit is not included in the identities of the PGP key that made the signature. |\n| `unknown_key` | The key that made the signature has not been registered with any user's account. |\n| `malformed_signature` | There was an error parsing the signature. |\n| `invalid` | The signature could not be cryptographically verified using the key whose key-id was found in the signature. |\n| `valid` | None of the above errors applied, so the signature is considered to be verified. |", "tags": [ "git" ], "operationId": "git/create-tag", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/git#create-a-tag-object" }, "parameters": [ { "$ref": "#/components/parameters/owner" }, { "$ref": "#/components/parameters/repo" } ], "requestBody": { "required": true, "content": { "application/json": { "schema": { "type": "object", "properties": { "tag": { "type": "string", "description": "The tag's name. This is typically a version (e.g., \"v0.0.1\")." }, "message": { "type": "string", "description": "The tag message." }, "object": { "type": "string", "description": "The SHA of the git object this is tagging." }, "type": { "type": "string", "description": "The type of the object we're tagging. Normally this is a `commit` but it can also be a `tree` or a `blob`.", "enum": [ "commit", "tree", "blob" ] }, "tagger": { "type": "object", "description": "An object with information about the individual creating the tag.", "properties": { "name": { "type": "string", "description": "The name of the author of the tag" }, "email": { "type": "string", "description": "The email of the author of the tag" }, "date": { "type": "string", "format": "date-time", "description": "When this object was tagged. This is a timestamp in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format: `YYYY-MM-DDTHH:MM:SSZ`." } }, "required": [ "name", "email" ] } }, "required": [ "tag", "message", "object", "type" ] }, "example": { "tag": "v0.0.1", "message": "initial version", "object": "c3d0be41ecbe669545ee3e94d31ed9a4bc91ee3c", "type": "commit", "tagger": { "name": "Monalisa Octocat", "email": "octocat@github.com", "date": "2011-06-17T14:53:35-07:00" } } } } }, "responses": { "201": { "description": "Response", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/git-tag" }, "examples": { "default": { "$ref": "#/components/examples/git-tag" } } } }, "headers": { "Location": { "example": "https://api.github.com/repos/octocat/Hello-World/git/tags/940bd336248efae0f9ee5bc7b2d5c985887b16ac", "schema": { "type": "string" } } } }, "422": { "$ref": "#/components/responses/validation_failed" } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": true, "category": "git", "subcategory": "tags" } } }, "/repos/{owner}/{repo}/git/tags/{tag_sha}": { "get": { "summary": "Get a tag", "description": "**Signature verification object**\n\nThe response will include a `verification` object that describes the result of verifying the commit's signature. The following fields are included in the `verification` object:\n\n| Name | Type | Description |\n| ---- | ---- | ----------- |\n| `verified` | `boolean` | Indicates whether GitHub considers the signature in this commit to be verified. |\n| `reason` | `string` | The reason for verified value. Possible values and their meanings are enumerated in table below. |\n| `signature` | `string` | The signature that was extracted from the commit. |\n| `payload` | `string` | The value that was signed. |\n\nThese are the possible values for `reason` in the `verification` object:\n\n| Value | Description |\n| ----- | ----------- |\n| `expired_key` | The key that made the signature is expired. |\n| `not_signing_key` | The \"signing\" flag is not among the usage flags in the GPG key that made the signature. |\n| `gpgverify_error` | There was an error communicating with the signature verification service. |\n| `gpgverify_unavailable` | The signature verification service is currently unavailable. |\n| `unsigned` | The object does not include a signature. |\n| `unknown_signature_type` | A non-PGP signature was found in the commit. |\n| `no_user` | No user was associated with the `committer` email address in the commit. |\n| `unverified_email` | The `committer` email address in the commit was associated with a user, but the email address is not verified on her/his account. |\n| `bad_email` | The `committer` email address in the commit is not included in the identities of the PGP key that made the signature. |\n| `unknown_key` | The key that made the signature has not been registered with any user's account. |\n| `malformed_signature` | There was an error parsing the signature. |\n| `invalid` | The signature could not be cryptographically verified using the key whose key-id was found in the signature. |\n| `valid` | None of the above errors applied, so the signature is considered to be verified. |", "tags": [ "git" ], "operationId": "git/get-tag", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/git#get-a-tag" }, "parameters": [ { "$ref": "#/components/parameters/owner" }, { "$ref": "#/components/parameters/repo" }, { "name": "tag_sha", "in": "path", "required": true, "schema": { "type": "string" } } ], "responses": { "200": { "description": "Response", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/git-tag" }, "examples": { "default": { "$ref": "#/components/examples/git-tag" } } } } }, "404": { "$ref": "#/components/responses/not_found" } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": true, "category": "git", "subcategory": "tags" } } }, "/repos/{owner}/{repo}/git/trees": { "post": { "summary": "Create a tree", "description": "The tree creation API accepts nested entries. If you specify both a tree and a nested path modifying that tree, this endpoint will overwrite the contents of the tree with the new path contents, and create a new tree structure.\n\nIf you use this endpoint to add, delete, or modify the file contents in a tree, you will need to commit the tree and then update a branch to point to the commit. For more information see \"[Create a commit](https://docs.github.com/enterprise-server@3.0/rest/reference/git#create-a-commit)\" and \"[Update a reference](https://docs.github.com/enterprise-server@3.0/rest/reference/git#update-a-reference).\"", "tags": [ "git" ], "operationId": "git/create-tree", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/git#create-a-tree" }, "parameters": [ { "$ref": "#/components/parameters/owner" }, { "$ref": "#/components/parameters/repo" } ], "requestBody": { "required": true, "content": { "application/json": { "schema": { "type": "object", "properties": { "tree": { "type": "array", "description": "Objects (of `path`, `mode`, `type`, and `sha`) specifying a tree structure.", "items": { "type": "object", "properties": { "path": { "type": "string", "description": "The file referenced in the tree." }, "mode": { "type": "string", "description": "The file mode; one of `100644` for file (blob), `100755` for executable (blob), `040000` for subdirectory (tree), `160000` for submodule (commit), or `120000` for a blob that specifies the path of a symlink.", "enum": [ "100644", "100755", "040000", "160000", "120000" ] }, "type": { "type": "string", "description": "Either `blob`, `tree`, or `commit`.", "enum": [ "blob", "tree", "commit" ] }, "sha": { "type": [ "string", "null" ], "description": "The SHA1 checksum ID of the object in the tree. Also called `tree.sha`. If the value is `null` then the file will be deleted. \n \n**Note:** Use either `tree.sha` or `content` to specify the contents of the entry. Using both `tree.sha` and `content` will return an error." }, "content": { "type": "string", "description": "The content you want this file to have. GitHub will write this blob out and use that SHA for this entry. Use either this, or `tree.sha`. \n \n**Note:** Use either `tree.sha` or `content` to specify the contents of the entry. Using both `tree.sha` and `content` will return an error." } } } }, "base_tree": { "type": "string", "description": "The SHA1 of an existing Git tree object which will be used as the base for the new tree. If provided, a new Git tree object will be created from entries in the Git tree object pointed to by `base_tree` and entries defined in the `tree` parameter. Entries defined in the `tree` parameter will overwrite items from `base_tree` with the same `path`. If you're creating new changes on a branch, then normally you'd set `base_tree` to the SHA1 of the Git tree object of the current latest commit on the branch you're working on.\nIf not provided, GitHub will create a new Git tree object from only the entries defined in the `tree` parameter. If you create a new commit pointing to such a tree, then all files which were a part of the parent commit's tree and were not defined in the `tree` parameter will be listed as deleted by the new commit.\n" } }, "required": [ "tree" ] }, "example": { "base_tree": "9fb037999f264ba9a7fc6274d15fa3ae2ab98312", "tree": [ { "path": "file.rb", "mode": "100644", "type": "blob", "sha": "44b4fc6d56897b048c772eb4087f854f46256132" } ] } } } }, "responses": { "201": { "description": "Response", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/git-tree" }, "examples": { "default": { "$ref": "#/components/examples/git-tree" } } } }, "headers": { "Location": { "example": "https://api.github.com/repos/octocat/Hello-World/trees/cd8274d15fa3ae2ab983129fb037999f264ba9a7", "schema": { "type": "string" } } } }, "422": { "$ref": "#/components/responses/validation_failed" }, "404": { "$ref": "#/components/responses/not_found" }, "403": { "$ref": "#/components/responses/forbidden" } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": true, "category": "git", "subcategory": "trees" } } }, "/repos/{owner}/{repo}/git/trees/{tree_sha}": { "get": { "summary": "Get a tree", "description": "Returns a single tree using the SHA1 value for that tree.\n\nIf `truncated` is `true` in the response then the number of items in the `tree` array exceeded our maximum limit. If you need to fetch more items, use the non-recursive method of fetching trees, and fetch one sub-tree at a time.", "tags": [ "git" ], "operationId": "git/get-tree", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/git#get-a-tree" }, "parameters": [ { "$ref": "#/components/parameters/owner" }, { "$ref": "#/components/parameters/repo" }, { "name": "tree_sha", "in": "path", "required": true, "schema": { "type": "string" }, "x-multi-segment": true }, { "name": "recursive", "description": "Setting this parameter to any value returns the objects or subtrees referenced by the tree specified in `:tree_sha`. For example, setting `recursive` to any of the following will enable returning objects or subtrees: `0`, `1`, `\"true\"`, and `\"false\"`. Omit this parameter to prevent recursively returning objects or subtrees.", "in": "query", "required": false, "schema": { "type": "string" } } ], "responses": { "200": { "description": "Response", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/git-tree" }, "examples": { "default-response": { "$ref": "#/components/examples/git-tree-default-response" }, "response-recursively-retrieving-a-tree": { "$ref": "#/components/examples/git-tree-response-recursively-retrieving-a-tree" } } } } }, "422": { "$ref": "#/components/responses/validation_failed" }, "404": { "$ref": "#/components/responses/not_found" } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": true, "category": "git", "subcategory": "trees" } } }, "/repos/{owner}/{repo}/hooks": { "get": { "summary": "List repository webhooks", "description": "", "tags": [ "repos" ], "operationId": "repos/list-webhooks", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/repos#list-repository-webhooks" }, "parameters": [ { "$ref": "#/components/parameters/owner" }, { "$ref": "#/components/parameters/repo" }, { "$ref": "#/components/parameters/per-page" }, { "$ref": "#/components/parameters/page" } ], "responses": { "200": { "description": "Response", "content": { "application/json": { "schema": { "type": "array", "items": { "$ref": "#/components/schemas/hook" } }, "examples": { "default": { "$ref": "#/components/examples/hook-items" } } } }, "headers": { "Link": { "$ref": "#/components/headers/link" } } }, "404": { "$ref": "#/components/responses/not_found" } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": true, "category": "repos", "subcategory": "webhooks" } }, "post": { "summary": "Create a repository webhook", "description": "Repositories can have multiple webhooks installed. Each webhook should have a unique `config`. Multiple webhooks can\nshare the same `config` as long as those webhooks do not have any `events` that overlap.", "tags": [ "repos" ], "operationId": "repos/create-webhook", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/repos#create-a-repository-webhook" }, "parameters": [ { "$ref": "#/components/parameters/owner" }, { "$ref": "#/components/parameters/repo" } ], "requestBody": { "required": false, "content": { "application/json": { "schema": { "type": [ "object", "null" ], "properties": { "name": { "type": "string", "description": "Use `web` to create a webhook. Default: `web`. This parameter only accepts the value `web`." }, "config": { "type": "object", "description": "Key/value pairs to provide settings for this webhook. [These are defined below](https://docs.github.com/enterprise-server@3.0/rest/reference/repos#create-hook-config-params).", "properties": { "url": { "$ref": "#/components/schemas/webhook-config-url" }, "content_type": { "$ref": "#/components/schemas/webhook-config-content-type" }, "secret": { "$ref": "#/components/schemas/webhook-config-secret" }, "insecure_ssl": { "$ref": "#/components/schemas/webhook-config-insecure-ssl" }, "token": { "type": "string", "examples": [ "\"abc\"" ] }, "digest": { "type": "string", "examples": [ "\"sha256\"" ] } } }, "events": { "type": "array", "description": "Determines what [events](https://docs.github.com/enterprise-server@3.0/webhooks/event-payloads) the hook is triggered for.", "default": [ "push" ], "items": { "type": "string" } }, "active": { "type": "boolean", "description": "Determines if notifications are sent when the webhook is triggered. Set to `true` to send notifications.", "default": true } }, "additionalProperties": false }, "example": { "name": "web", "active": true, "events": [ "push", "pull_request" ], "config": { "url": "https://example.com/webhook", "content_type": "json", "insecure_ssl": "0" } } } } }, "responses": { "201": { "description": "Response", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/hook" }, "examples": { "default": { "$ref": "#/components/examples/hook" } } } }, "headers": { "Location": { "example": "https://api.github.com/repos/octocat/Hello-World/hooks/12345678", "schema": { "type": "string" } } } }, "404": { "$ref": "#/components/responses/not_found" }, "422": { "$ref": "#/components/responses/validation_failed" }, "403": { "$ref": "#/components/responses/forbidden" } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": true, "category": "repos", "subcategory": "webhooks" } } }, "/repos/{owner}/{repo}/hooks/{hook_id}": { "get": { "summary": "Get a repository webhook", "description": "Returns a webhook configured in a repository. To get only the webhook `config` properties, see \"[Get a webhook configuration for a repository](/rest/reference/repos#get-a-webhook-configuration-for-a-repository).\"", "tags": [ "repos" ], "operationId": "repos/get-webhook", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/repos#get-a-repository-webhook" }, "parameters": [ { "$ref": "#/components/parameters/owner" }, { "$ref": "#/components/parameters/repo" }, { "$ref": "#/components/parameters/hook-id" } ], "responses": { "200": { "description": "Response", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/hook" }, "examples": { "default": { "$ref": "#/components/examples/hook" } } } } }, "404": { "$ref": "#/components/responses/not_found" } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": true, "category": "repos", "subcategory": "webhooks" } }, "patch": { "summary": "Update a repository webhook", "description": "Updates a webhook configured in a repository. If you previously had a `secret` set, you must provide the same `secret` or set a new `secret` or the secret will be removed. If you are only updating individual webhook `config` properties, use \"[Update a webhook configuration for a repository](/rest/reference/repos#update-a-webhook-configuration-for-a-repository).\"", "tags": [ "repos" ], "operationId": "repos/update-webhook", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/repos#update-a-repository-webhook" }, "parameters": [ { "$ref": "#/components/parameters/owner" }, { "$ref": "#/components/parameters/repo" }, { "$ref": "#/components/parameters/hook-id" } ], "requestBody": { "required": true, "content": { "application/json": { "schema": { "type": "object", "properties": { "config": { "type": "object", "description": "Key/value pairs to provide settings for this webhook. [These are defined below](https://docs.github.com/enterprise-server@3.0/rest/reference/repos#create-hook-config-params).", "properties": { "url": { "$ref": "#/components/schemas/webhook-config-url" }, "content_type": { "$ref": "#/components/schemas/webhook-config-content-type" }, "secret": { "$ref": "#/components/schemas/webhook-config-secret" }, "insecure_ssl": { "$ref": "#/components/schemas/webhook-config-insecure-ssl" }, "address": { "type": "string", "examples": [ "\"bar@example.com\"" ] }, "room": { "type": "string", "examples": [ "\"The Serious Room\"" ] } }, "required": [ "url" ] }, "events": { "type": "array", "description": "Determines what [events](https://docs.github.com/enterprise-server@3.0/webhooks/event-payloads) the hook is triggered for. This replaces the entire array of events.", "default": [ "push" ], "items": { "type": "string" } }, "add_events": { "type": "array", "description": "Determines a list of events to be added to the list of events that the Hook triggers for.", "items": { "type": "string" } }, "remove_events": { "type": "array", "description": "Determines a list of events to be removed from the list of events that the Hook triggers for.", "items": { "type": "string" } }, "active": { "type": "boolean", "description": "Determines if notifications are sent when the webhook is triggered. Set to `true` to send notifications.", "default": true } } }, "example": { "active": true, "add_events": [ "pull_request" ] } } } }, "responses": { "200": { "description": "Response", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/hook" }, "examples": { "default": { "$ref": "#/components/examples/hook" } } } } }, "422": { "$ref": "#/components/responses/validation_failed" }, "404": { "$ref": "#/components/responses/not_found" } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": true, "category": "repos", "subcategory": "webhooks" } }, "delete": { "summary": "Delete a repository webhook", "description": "", "tags": [ "repos" ], "operationId": "repos/delete-webhook", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/repos#delete-a-repository-webhook" }, "parameters": [ { "$ref": "#/components/parameters/owner" }, { "$ref": "#/components/parameters/repo" }, { "$ref": "#/components/parameters/hook-id" } ], "responses": { "204": { "description": "Response" }, "404": { "$ref": "#/components/responses/not_found" } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": true, "category": "repos", "subcategory": "webhooks" } } }, "/repos/{owner}/{repo}/hooks/{hook_id}/config": { "get": { "summary": "Get a webhook configuration for a repository", "description": "Returns the webhook configuration for a repository. To get more information about the webhook, including the `active` state and `events`, use \"[Get a repository webhook](/rest/reference/orgs#get-a-repository-webhook).\"\n\nAccess tokens must have the `read:repo_hook` or `repo` scope, and GitHub Apps must have the `repository_hooks:read` permission.", "tags": [ "repos" ], "operationId": "repos/get-webhook-config-for-repo", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/repos#get-a-webhook-configuration-for-a-repository" }, "parameters": [ { "$ref": "#/components/parameters/owner" }, { "$ref": "#/components/parameters/repo" }, { "$ref": "#/components/parameters/hook-id" } ], "responses": { "200": { "description": "Response", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/webhook-config" }, "examples": { "default": { "$ref": "#/components/examples/webhook-config" } } } } } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": true, "category": "repos", "subcategory": "webhooks" } }, "patch": { "summary": "Update a webhook configuration for a repository", "description": "Updates the webhook configuration for a repository. To update more information about the webhook, including the `active` state and `events`, use \"[Update a repository webhook](/rest/reference/orgs#update-a-repository-webhook).\"\n\nAccess tokens must have the `write:repo_hook` or `repo` scope, and GitHub Apps must have the `repository_hooks:write` permission.", "tags": [ "repos" ], "operationId": "repos/update-webhook-config-for-repo", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/repos#update-a-webhook-configuration-for-a-repository" }, "parameters": [ { "$ref": "#/components/parameters/owner" }, { "$ref": "#/components/parameters/repo" }, { "$ref": "#/components/parameters/hook-id" } ], "requestBody": { "required": false, "content": { "application/json": { "schema": { "type": "object", "additionalProperties": false, "properties": { "url": { "$ref": "#/components/schemas/webhook-config-url" }, "content_type": { "$ref": "#/components/schemas/webhook-config-content-type" }, "secret": { "$ref": "#/components/schemas/webhook-config-secret" }, "insecure_ssl": { "$ref": "#/components/schemas/webhook-config-insecure-ssl" } }, "example": { "content_type": "json", "insecure_ssl": "0", "secret": "********", "url": "https://example.com/webhook" } } } } }, "responses": { "200": { "description": "Response", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/webhook-config" }, "examples": { "default": { "$ref": "#/components/examples/webhook-config" } } } } } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": true, "category": "repos", "subcategory": "webhooks" } } }, "/repos/{owner}/{repo}/hooks/{hook_id}/pings": { "post": { "summary": "Ping a repository webhook", "description": "This will trigger a [ping event](https://docs.github.com/enterprise-server@3.0/webhooks/#ping-event) to be sent to the hook.", "tags": [ "repos" ], "operationId": "repos/ping-webhook", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/repos#ping-a-repository-webhook" }, "parameters": [ { "$ref": "#/components/parameters/owner" }, { "$ref": "#/components/parameters/repo" }, { "$ref": "#/components/parameters/hook-id" } ], "responses": { "204": { "description": "Response" }, "404": { "$ref": "#/components/responses/not_found" } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": true, "category": "repos", "subcategory": "webhooks" } } }, "/repos/{owner}/{repo}/hooks/{hook_id}/tests": { "post": { "summary": "Test the push repository webhook", "description": "This will trigger the hook with the latest push to the current repository if the hook is subscribed to `push` events. If the hook is not subscribed to `push` events, the server will respond with 204 but no test POST will be generated.\n\n**Note**: Previously `/repos/:owner/:repo/hooks/:hook_id/test`", "tags": [ "repos" ], "operationId": "repos/test-push-webhook", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/repos#test-the-push-repository-webhook" }, "parameters": [ { "$ref": "#/components/parameters/owner" }, { "$ref": "#/components/parameters/repo" }, { "$ref": "#/components/parameters/hook-id" } ], "responses": { "204": { "description": "Response" }, "404": { "$ref": "#/components/responses/not_found" } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": true, "category": "repos", "subcategory": "webhooks" } } }, "/repos/{owner}/{repo}/installation": { "get": { "summary": "Get a repository installation for the authenticated app", "description": "Enables an authenticated GitHub App to find the repository's installation information. The installation's account type will be either an organization or a user account, depending which account the repository belongs to.\n\nYou must use a [JWT](https://docs.github.com/enterprise-server@3.0/apps/building-github-apps/authenticating-with-github-apps/#authenticating-as-a-github-app) to access this endpoint.", "tags": [ "apps" ], "operationId": "apps/get-repo-installation", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/apps#get-a-repository-installation-for-the-authenticated-app" }, "parameters": [ { "$ref": "#/components/parameters/owner" }, { "$ref": "#/components/parameters/repo" } ], "responses": { "200": { "description": "Response", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/installation" }, "examples": { "default": { "$ref": "#/components/examples/installation" } } } } }, "301": { "$ref": "#/components/responses/moved_permanently" }, "404": { "$ref": "#/components/responses/not_found" } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": false, "category": "apps", "subcategory": null } } }, "/repos/{owner}/{repo}/invitations": { "get": { "summary": "List repository invitations", "description": "When authenticating as a user with admin rights to a repository, this endpoint will list all currently open repository invitations.", "tags": [ "repos" ], "operationId": "repos/list-invitations", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/repos#list-repository-invitations" }, "parameters": [ { "$ref": "#/components/parameters/owner" }, { "$ref": "#/components/parameters/repo" }, { "$ref": "#/components/parameters/per-page" }, { "$ref": "#/components/parameters/page" } ], "responses": { "200": { "description": "Response", "content": { "application/json": { "schema": { "type": "array", "items": { "$ref": "#/components/schemas/repository-invitation" } }, "examples": { "default": { "$ref": "#/components/examples/repository-invitation-items" } } } }, "headers": { "Link": { "$ref": "#/components/headers/link" } } } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": true, "category": "repos", "subcategory": "invitations" } } }, "/repos/{owner}/{repo}/invitations/{invitation_id}": { "patch": { "summary": "Update a repository invitation", "description": "", "tags": [ "repos" ], "operationId": "repos/update-invitation", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/repos#update-a-repository-invitation" }, "parameters": [ { "$ref": "#/components/parameters/owner" }, { "$ref": "#/components/parameters/repo" }, { "$ref": "#/components/parameters/invitation-id" } ], "requestBody": { "required": false, "content": { "application/json": { "schema": { "type": "object", "properties": { "permissions": { "type": "string", "description": "The permissions that the associated user will have on the repository. Valid values are `read`, `write`, `maintain`, `triage`, and `admin`.", "enum": [ "read", "write", "maintain", "triage", "admin" ] } } } } } }, "responses": { "200": { "description": "Response", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/repository-invitation" }, "examples": { "default": { "$ref": "#/components/examples/repository-invitation" } } } } } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": true, "category": "repos", "subcategory": "invitations" } }, "delete": { "summary": "Delete a repository invitation", "description": "", "tags": [ "repos" ], "operationId": "repos/delete-invitation", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/repos#delete-a-repository-invitation" }, "parameters": [ { "$ref": "#/components/parameters/owner" }, { "$ref": "#/components/parameters/repo" }, { "$ref": "#/components/parameters/invitation-id" } ], "responses": { "204": { "description": "Response" } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": true, "category": "repos", "subcategory": "invitations" } } }, "/repos/{owner}/{repo}/issues": { "get": { "summary": "List repository issues", "description": "List issues in a repository.\n\n**Note**: GitHub's REST API v3 considers every pull request an issue, but not every issue is a pull request. For this\nreason, \"Issues\" endpoints may return both issues and pull requests in the response. You can identify pull requests by\nthe `pull_request` key. Be aware that the `id` of a pull request returned from \"Issues\" endpoints will be an _issue id_. To find out the pull\nrequest id, use the \"[List pull requests](https://docs.github.com/enterprise-server@3.0/rest/reference/pulls#list-pull-requests)\" endpoint.", "tags": [ "issues" ], "operationId": "issues/list-for-repo", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/issues#list-repository-issues" }, "parameters": [ { "$ref": "#/components/parameters/owner" }, { "$ref": "#/components/parameters/repo" }, { "name": "milestone", "description": "If an `integer` is passed, it should refer to a milestone by its `number` field. If the string `*` is passed, issues with any milestone are accepted. If the string `none` is passed, issues without milestones are returned.", "in": "query", "required": false, "schema": { "type": "string" } }, { "name": "state", "description": "Indicates the state of the issues to return. Can be either `open`, `closed`, or `all`.", "in": "query", "required": false, "schema": { "type": "string", "enum": [ "open", "closed", "all" ], "default": "open" } }, { "name": "assignee", "description": "Can be the name of a user. Pass in `none` for issues with no assigned user, and `*` for issues assigned to any user.", "in": "query", "required": false, "schema": { "type": "string" } }, { "name": "creator", "description": "The user that created the issue.", "in": "query", "required": false, "schema": { "type": "string" } }, { "name": "mentioned", "description": "A user that's mentioned in the issue.", "in": "query", "required": false, "schema": { "type": "string" } }, { "$ref": "#/components/parameters/labels" }, { "name": "sort", "description": "What to sort results by. Can be either `created`, `updated`, `comments`.", "in": "query", "required": false, "schema": { "type": "string", "enum": [ "created", "updated", "comments" ], "default": "created" } }, { "$ref": "#/components/parameters/direction" }, { "$ref": "#/components/parameters/since" }, { "$ref": "#/components/parameters/per-page" }, { "$ref": "#/components/parameters/page" } ], "responses": { "200": { "description": "Response", "content": { "application/json": { "schema": { "type": "array", "items": { "$ref": "#/components/schemas/issue" } }, "examples": { "default": { "$ref": "#/components/examples/issue-items" } } } }, "headers": { "Link": { "$ref": "#/components/headers/link" } } }, "301": { "$ref": "#/components/responses/moved_permanently" }, "422": { "$ref": "#/components/responses/validation_failed" }, "404": { "$ref": "#/components/responses/not_found" } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": true, "category": "issues", "previews": [ { "required": false, "name": "machine-man", "note": "If an issue event is created via a GitHub App, the response will include the `performed_via_github_app` object with\tinformation about the GitHub App. For more information, see the [related blog\tpost](https://developer.github.com/changes/2016-09-14-Integrations-Early-Access).\nTo receive the `performed_via_github_app` object in the response, you must provide a custom [media type](https://docs.github.com/enterprise-server@3.0/rest/overview/media-types) in the `Accept` header:\n```shell\napplication/vnd.github.machine-man-preview\n```" }, { "required": false, "name": "squirrel-girl", "note": "An additional `reactions` object in the issue comment payload is currently available for developers to preview. During the preview period, the APIs may change without advance notice. Please see the [blog post](https://developer.github.com/changes/2016-05-12-reactions-api-preview) for full details.\n\nTo access the API you must provide a custom [media type](https://docs.github.com/enterprise-server@3.0/rest/overview/media-types) in the `Accept` header:\n```shell\napplication/vnd.github.squirrel-girl-preview\n```\nThe `reactions` key will have the following payload where `url` can be used to construct the API location for [listing and creating](https://docs.github.com/enterprise-server@3.0/rest/reference/reactions) reactions." } ] } }, "post": { "summary": "Create an issue", "description": "Any user with pull access to a repository can create an issue. If [issues are disabled in the repository](https://docs.github.com/articles/disabling-issues/), the API returns a `410 Gone` status.\n\nThis endpoint triggers [notifications](https://docs.github.com/enterprise-server@3.0/github/managing-subscriptions-and-notifications-on-github/about-notifications). Creating content too quickly using this endpoint may result in secondary rate limiting. See \"[Secondary rate limits](https://docs.github.com/enterprise-server@3.0/rest/overview/resources-in-the-rest-api#secondary-rate-limits)\" and \"[Dealing with secondary rate limits](https://docs.github.com/enterprise-server@3.0/rest/guides/best-practices-for-integrators#dealing-with-secondary-rate-limits)\" for details.", "tags": [ "issues" ], "operationId": "issues/create", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/issues#create-an-issue" }, "parameters": [ { "$ref": "#/components/parameters/owner" }, { "$ref": "#/components/parameters/repo" } ], "requestBody": { "required": true, "content": { "application/json": { "schema": { "type": "object", "properties": { "title": { "oneOf": [ { "type": "string" }, { "type": "integer" } ], "description": "The title of the issue." }, "body": { "type": "string", "description": "The contents of the issue." }, "assignee": { "type": [ "string", "null" ], "description": "Login for the user that this issue should be assigned to. _NOTE: Only users with push access can set the assignee for new issues. The assignee is silently dropped otherwise. **This field is deprecated.**_" }, "milestone": { "oneOf": [ { "type": "string" }, { "type": "integer", "description": "The `number` of the milestone to associate this issue with. _NOTE: Only users with push access can set the milestone for new issues. The milestone is silently dropped otherwise._" } ], "type": [ "null", "string", "integer" ] }, "labels": { "type": "array", "description": "Labels to associate with this issue. _NOTE: Only users with push access can set labels for new issues. Labels are silently dropped otherwise._", "items": { "oneOf": [ { "type": "string" }, { "type": "object", "properties": { "id": { "type": "integer" }, "name": { "type": "string" }, "description": { "type": [ "string", "null" ] }, "color": { "type": [ "string", "null" ] } } } ] } }, "assignees": { "type": "array", "description": "Logins for Users to assign to this issue. _NOTE: Only users with push access can set assignees for new issues. Assignees are silently dropped otherwise._", "items": { "type": "string" } } }, "required": [ "title" ] }, "example": { "title": "Found a bug", "body": "I'm having a problem with this.", "assignees": [ "octocat" ], "milestone": 1, "labels": [ "bug" ] } } } }, "responses": { "201": { "description": "Response", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/issue" }, "examples": { "default": { "$ref": "#/components/examples/issue" } } } }, "headers": { "Location": { "example": "https://api.github.com/repos/octocat/Hello-World/issues/1347", "schema": { "type": "string" } } } }, "403": { "$ref": "#/components/responses/forbidden" }, "422": { "$ref": "#/components/responses/validation_failed" }, "503": { "$ref": "#/components/responses/service_unavailable" }, "404": { "$ref": "#/components/responses/not_found" }, "410": { "$ref": "#/components/responses/gone" } }, "x-github": { "triggersNotification": true, "githubCloudOnly": false, "enabledForGitHubApps": true, "category": "issues", "subcategory": null } } }, "/repos/{owner}/{repo}/issues/comments": { "get": { "summary": "List issue comments for a repository", "description": "By default, Issue Comments are ordered by ascending ID.", "tags": [ "issues" ], "operationId": "issues/list-comments-for-repo", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/issues#list-issue-comments-for-a-repository" }, "parameters": [ { "$ref": "#/components/parameters/owner" }, { "$ref": "#/components/parameters/repo" }, { "$ref": "#/components/parameters/sort" }, { "name": "direction", "description": "Either `asc` or `desc`. Ignored without the `sort` parameter.", "in": "query", "required": false, "schema": { "type": "string", "enum": [ "asc", "desc" ] } }, { "$ref": "#/components/parameters/since" }, { "$ref": "#/components/parameters/per-page" }, { "$ref": "#/components/parameters/page" } ], "responses": { "200": { "description": "Response", "content": { "application/json": { "schema": { "type": "array", "items": { "$ref": "#/components/schemas/issue-comment" } }, "examples": { "default": { "$ref": "#/components/examples/issue-comment-items" } } } }, "headers": { "Link": { "$ref": "#/components/headers/link" } } }, "422": { "$ref": "#/components/responses/validation_failed" }, "404": { "$ref": "#/components/responses/not_found" } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": true, "category": "issues", "subcategory": "comments", "previews": [ { "required": false, "name": "squirrel-girl", "note": "An additional `reactions` object in the issue comment payload is currently available for developers to preview. During the preview period, the APIs may change without advance notice. Please see the [blog post](https://developer.github.com/changes/2016-05-12-reactions-api-preview) for full details.\n\nTo access the API you must provide a custom [media type](https://docs.github.com/enterprise-server@3.0/rest/overview/media-types) in the `Accept` header:\n```shell\napplication/vnd.github.squirrel-girl-preview\n```\nThe `reactions` key will have the following payload where `url` can be used to construct the API location for [listing and creating](https://docs.github.com/enterprise-server@3.0/rest/reference/reactions) reactions." } ] } } }, "/repos/{owner}/{repo}/issues/comments/{comment_id}": { "get": { "summary": "Get an issue comment", "description": "", "tags": [ "issues" ], "operationId": "issues/get-comment", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/issues#get-an-issue-comment" }, "parameters": [ { "$ref": "#/components/parameters/owner" }, { "$ref": "#/components/parameters/repo" }, { "$ref": "#/components/parameters/comment-id" } ], "responses": { "200": { "description": "Response", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/issue-comment" }, "examples": { "default": { "$ref": "#/components/examples/issue-comment" } } } } }, "404": { "$ref": "#/components/responses/not_found" } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": true, "category": "issues", "subcategory": "comments", "previews": [ { "required": false, "name": "machine-man", "note": "If an issue event is created via a GitHub App, the response will include the `performed_via_github_app` object with\tinformation about the GitHub App. For more information, see the [related blog\tpost](https://developer.github.com/changes/2016-09-14-Integrations-Early-Access).\nTo receive the `performed_via_github_app` object in the response, you must provide a custom [media type](https://docs.github.com/enterprise-server@3.0/rest/overview/media-types) in the `Accept` header:\n```shell\napplication/vnd.github.machine-man-preview\n```" }, { "required": false, "name": "squirrel-girl", "note": "An additional `reactions` object in the issue comment payload is currently available for developers to preview. During the preview period, the APIs may change without advance notice. Please see the [blog post](https://developer.github.com/changes/2016-05-12-reactions-api-preview) for full details.\n\nTo access the API you must provide a custom [media type](https://docs.github.com/enterprise-server@3.0/rest/overview/media-types) in the `Accept` header:\n```shell\napplication/vnd.github.squirrel-girl-preview\n```\nThe `reactions` key will have the following payload where `url` can be used to construct the API location for [listing and creating](https://docs.github.com/enterprise-server@3.0/rest/reference/reactions) reactions." } ] } }, "patch": { "summary": "Update an issue comment", "description": "", "tags": [ "issues" ], "operationId": "issues/update-comment", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/issues#update-an-issue-comment" }, "parameters": [ { "$ref": "#/components/parameters/owner" }, { "$ref": "#/components/parameters/repo" }, { "$ref": "#/components/parameters/comment-id" } ], "requestBody": { "required": true, "content": { "application/json": { "schema": { "type": "object", "properties": { "body": { "type": "string", "description": "The contents of the comment." } }, "required": [ "body" ] }, "example": { "body": "Me too" } } } }, "responses": { "200": { "description": "Response", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/issue-comment" }, "examples": { "default": { "$ref": "#/components/examples/issue-comment" } } } } }, "422": { "$ref": "#/components/responses/validation_failed" } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": true, "category": "issues", "subcategory": "comments" } }, "delete": { "summary": "Delete an issue comment", "description": "", "tags": [ "issues" ], "operationId": "issues/delete-comment", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/issues#delete-an-issue-comment" }, "parameters": [ { "$ref": "#/components/parameters/owner" }, { "$ref": "#/components/parameters/repo" }, { "$ref": "#/components/parameters/comment-id" } ], "responses": { "204": { "description": "Response" } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": true, "category": "issues", "subcategory": "comments" } } }, "/repos/{owner}/{repo}/issues/comments/{comment_id}/reactions": { "get": { "summary": "List reactions for an issue comment", "description": "List the reactions to an [issue comment](https://docs.github.com/enterprise-server@3.0/rest/reference/issues#comments).", "tags": [ "reactions" ], "operationId": "reactions/list-for-issue-comment", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/reactions#list-reactions-for-an-issue-comment" }, "parameters": [ { "$ref": "#/components/parameters/owner" }, { "$ref": "#/components/parameters/repo" }, { "$ref": "#/components/parameters/comment-id" }, { "name": "content", "description": "Returns a single [reaction type](https://docs.github.com/enterprise-server@3.0/rest/reference/reactions#reaction-types). Omit this parameter to list all reactions to an issue comment.", "in": "query", "required": false, "schema": { "type": "string", "enum": [ "+1", "-1", "laugh", "confused", "heart", "hooray", "rocket", "eyes" ] } }, { "$ref": "#/components/parameters/per-page" }, { "$ref": "#/components/parameters/page" } ], "responses": { "200": { "description": "Response", "content": { "application/json": { "schema": { "type": "array", "items": { "$ref": "#/components/schemas/reaction" } }, "examples": { "default": { "$ref": "#/components/examples/reaction-items" } } } }, "headers": { "Link": { "$ref": "#/components/headers/link" } } }, "404": { "$ref": "#/components/responses/not_found" } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": true, "category": "reactions", "previews": [ { "required": true, "name": "squirrel-girl", "note": "An additional `reactions` object in the issue comment payload is currently available for developers to preview. During the preview period, the APIs may change without advance notice. Please see the [blog post](https://developer.github.com/changes/2016-05-12-reactions-api-preview) for full details.\n\nTo access the API you must provide a custom [media type](https://docs.github.com/enterprise-server@3.0/rest/overview/media-types) in the `Accept` header:\n```shell\napplication/vnd.github.squirrel-girl-preview\n```\nThe `reactions` key will have the following payload where `url` can be used to construct the API location for [listing and creating](https://docs.github.com/enterprise-server@3.0/rest/reference/reactions) reactions." } ] } }, "post": { "summary": "Create reaction for an issue comment", "description": "Create a reaction to an [issue comment](https://docs.github.com/enterprise-server@3.0/rest/reference/issues#comments). A response with an HTTP `200` status means that you already added the reaction type to this issue comment.", "tags": [ "reactions" ], "operationId": "reactions/create-for-issue-comment", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/reactions#create-reaction-for-an-issue-comment" }, "parameters": [ { "$ref": "#/components/parameters/owner" }, { "$ref": "#/components/parameters/repo" }, { "$ref": "#/components/parameters/comment-id" } ], "requestBody": { "required": true, "content": { "application/json": { "schema": { "type": "object", "properties": { "content": { "type": "string", "description": "The [reaction type](https://docs.github.com/enterprise-server@3.0/rest/reference/reactions#reaction-types) to add to the issue comment.", "enum": [ "+1", "-1", "laugh", "confused", "heart", "hooray", "rocket", "eyes" ] } }, "required": [ "content" ] }, "example": { "content": "heart" } } } }, "responses": { "200": { "description": "Reaction exists", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/reaction" }, "examples": { "default": { "$ref": "#/components/examples/reaction" } } } } }, "201": { "description": "Reaction created", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/reaction" }, "examples": { "default": { "$ref": "#/components/examples/reaction" } } } } }, "422": { "$ref": "#/components/responses/validation_failed" } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": true, "category": "reactions", "previews": [ { "required": true, "name": "squirrel-girl", "note": "An additional `reactions` object in the issue comment payload is currently available for developers to preview. During the preview period, the APIs may change without advance notice. Please see the [blog post](https://developer.github.com/changes/2016-05-12-reactions-api-preview) for full details.\n\nTo access the API you must provide a custom [media type](https://docs.github.com/enterprise-server@3.0/rest/overview/media-types) in the `Accept` header:\n```shell\napplication/vnd.github.squirrel-girl-preview\n```\nThe `reactions` key will have the following payload where `url` can be used to construct the API location for [listing and creating](https://docs.github.com/enterprise-server@3.0/rest/reference/reactions) reactions." } ] } } }, "/repos/{owner}/{repo}/issues/comments/{comment_id}/reactions/{reaction_id}": { "delete": { "summary": "Delete an issue comment reaction", "description": "**Note:** You can also specify a repository by `repository_id` using the route `DELETE delete /repositories/:repository_id/issues/comments/:comment_id/reactions/:reaction_id`.\n\nDelete a reaction to an [issue comment](https://docs.github.com/enterprise-server@3.0/rest/reference/issues#comments).", "tags": [ "reactions" ], "operationId": "reactions/delete-for-issue-comment", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/reactions#delete-an-issue-comment-reaction" }, "parameters": [ { "$ref": "#/components/parameters/owner" }, { "$ref": "#/components/parameters/repo" }, { "$ref": "#/components/parameters/comment-id" }, { "$ref": "#/components/parameters/reaction-id" } ], "responses": { "204": { "description": "Response" } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": true, "category": "reactions", "previews": [ { "required": true, "name": "squirrel-girl", "note": "An additional `reactions` object in the issue comment payload is currently available for developers to preview. During the preview period, the APIs may change without advance notice. Please see the [blog post](https://developer.github.com/changes/2016-05-12-reactions-api-preview) for full details.\n\nTo access the API you must provide a custom [media type](https://docs.github.com/enterprise-server@3.0/rest/overview/media-types) in the `Accept` header:\n```shell\napplication/vnd.github.squirrel-girl-preview\n```\nThe `reactions` key will have the following payload where `url` can be used to construct the API location for [listing and creating](https://docs.github.com/enterprise-server@3.0/rest/reference/reactions) reactions." } ] } } }, "/repos/{owner}/{repo}/issues/events": { "get": { "summary": "List issue events for a repository", "description": "", "tags": [ "issues" ], "operationId": "issues/list-events-for-repo", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/issues#list-issue-events-for-a-repository" }, "parameters": [ { "$ref": "#/components/parameters/owner" }, { "$ref": "#/components/parameters/repo" }, { "$ref": "#/components/parameters/per-page" }, { "$ref": "#/components/parameters/page" } ], "responses": { "200": { "description": "Response", "content": { "application/json": { "schema": { "type": "array", "items": { "$ref": "#/components/schemas/issue-event" } }, "examples": { "default": { "$ref": "#/components/examples/issue-event-items" } } } }, "headers": { "Link": { "$ref": "#/components/headers/link" } } }, "422": { "$ref": "#/components/responses/validation_failed" } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": true, "category": "issues", "subcategory": "events", "previews": [ { "required": false, "name": "starfox", "note": "Project card details are now shown in REST API v3 responses for project-related issue and timeline events. This feature is now available for developers to preview. For details, see the [blog post](https://developer.github.com/changes/2018-09-05-project-card-events).\n\nTo receive the `project_card` attribute, project boards must be [enabled](https://docs.github.com/articles/disabling-project-boards-in-a-repository) for a repository, and you must provide a custom [media type](https://docs.github.com/enterprise-server@3.0/rest/overview/media-types) in the `Accept` header:\n```shell\napplication/vnd.github.starfox-preview+json\n```" } ] } } }, "/repos/{owner}/{repo}/issues/events/{event_id}": { "get": { "summary": "Get an issue event", "description": "", "tags": [ "issues" ], "operationId": "issues/get-event", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/issues#get-an-issue-event" }, "parameters": [ { "$ref": "#/components/parameters/owner" }, { "$ref": "#/components/parameters/repo" }, { "name": "event_id", "in": "path", "required": true, "schema": { "type": "integer" } } ], "responses": { "200": { "description": "Response", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/issue-event" }, "examples": { "default": { "$ref": "#/components/examples/issue-event" } } } } }, "404": { "$ref": "#/components/responses/not_found" }, "410": { "$ref": "#/components/responses/gone" }, "403": { "$ref": "#/components/responses/forbidden" } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": true, "category": "issues", "subcategory": "events", "previews": [ { "required": false, "name": "starfox", "note": "Project card details are now shown in REST API v3 responses for project-related issue and timeline events. This feature is now available for developers to preview. For details, see the [blog post](https://developer.github.com/changes/2018-09-05-project-card-events).\n\nTo receive the `project_card` attribute, project boards must be [enabled](https://docs.github.com/articles/disabling-project-boards-in-a-repository) for a repository, and you must provide a custom [media type](https://docs.github.com/enterprise-server@3.0/rest/overview/media-types) in the `Accept` header:\n```shell\napplication/vnd.github.starfox-preview+json\n```" } ] } } }, "/repos/{owner}/{repo}/issues/{issue_number}": { "get": { "summary": "Get an issue", "description": "The API returns a [`301 Moved Permanently` status](https://docs.github.com/enterprise-server@3.0/rest/overview/resources-in-the-rest-api#http-redirects-redirects) if the issue was\n[transferred](https://docs.github.com/articles/transferring-an-issue-to-another-repository/) to another repository. If\nthe issue was transferred to or deleted from a repository where the authenticated user lacks read access, the API\nreturns a `404 Not Found` status. If the issue was deleted from a repository where the authenticated user has read\naccess, the API returns a `410 Gone` status. To receive webhook events for transferred and deleted issues, subscribe\nto the [`issues`](https://docs.github.com/enterprise-server@3.0/webhooks/event-payloads/#issues) webhook.\n\n**Note**: GitHub's REST API v3 considers every pull request an issue, but not every issue is a pull request. For this\nreason, \"Issues\" endpoints may return both issues and pull requests in the response. You can identify pull requests by\nthe `pull_request` key. Be aware that the `id` of a pull request returned from \"Issues\" endpoints will be an _issue id_. To find out the pull\nrequest id, use the \"[List pull requests](https://docs.github.com/enterprise-server@3.0/rest/reference/pulls#list-pull-requests)\" endpoint.", "tags": [ "issues" ], "operationId": "issues/get", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/issues#get-an-issue" }, "parameters": [ { "$ref": "#/components/parameters/owner" }, { "$ref": "#/components/parameters/repo" }, { "$ref": "#/components/parameters/issue-number" } ], "responses": { "200": { "description": "Response", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/issue" }, "examples": { "default": { "$ref": "#/components/examples/issue" } } } } }, "301": { "$ref": "#/components/responses/moved_permanently" }, "404": { "$ref": "#/components/responses/not_found" }, "410": { "$ref": "#/components/responses/gone" }, "304": { "$ref": "#/components/responses/not_modified" } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": true, "category": "issues", "previews": [ { "required": false, "name": "squirrel-girl", "note": "An additional `reactions` object in the issue comment payload is currently available for developers to preview. During the preview period, the APIs may change without advance notice. Please see the [blog post](https://developer.github.com/changes/2016-05-12-reactions-api-preview) for full details.\n\nTo access the API you must provide a custom [media type](https://docs.github.com/enterprise-server@3.0/rest/overview/media-types) in the `Accept` header:\n```shell\napplication/vnd.github.squirrel-girl-preview\n```\nThe `reactions` key will have the following payload where `url` can be used to construct the API location for [listing and creating](https://docs.github.com/enterprise-server@3.0/rest/reference/reactions) reactions." } ] } }, "patch": { "summary": "Update an issue", "description": "Issue owners and users with push access can edit an issue.", "tags": [ "issues" ], "operationId": "issues/update", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/issues/#update-an-issue" }, "parameters": [ { "$ref": "#/components/parameters/owner" }, { "$ref": "#/components/parameters/repo" }, { "$ref": "#/components/parameters/issue-number" } ], "requestBody": { "required": false, "content": { "application/json": { "schema": { "type": "object", "properties": { "title": { "oneOf": [ { "type": "string" }, { "type": "integer" } ], "description": "The title of the issue.", "type": [ "null", "string", "integer" ] }, "body": { "type": [ "string", "null" ], "description": "The contents of the issue." }, "assignee": { "type": [ "string", "null" ], "description": "Login for the user that this issue should be assigned to. **This field is deprecated.**" }, "state": { "type": "string", "description": "State of the issue. Either `open` or `closed`.", "enum": [ "open", "closed" ] }, "milestone": { "oneOf": [ { "type": "string" }, { "type": "integer", "description": "The `number` of the milestone to associate this issue with or `null` to remove current. _NOTE: Only users with push access can set the milestone for issues. The milestone is silently dropped otherwise._" } ], "type": [ "null", "string", "integer" ] }, "labels": { "type": "array", "description": "Labels to associate with this issue. Pass one or more Labels to _replace_ the set of Labels on this Issue. Send an empty array (`[]`) to clear all Labels from the Issue. _NOTE: Only users with push access can set labels for issues. Labels are silently dropped otherwise._", "items": { "oneOf": [ { "type": "string" }, { "type": "object", "properties": { "id": { "type": "integer" }, "name": { "type": "string" }, "description": { "type": [ "string", "null" ] }, "color": { "type": [ "string", "null" ] } } } ] } }, "assignees": { "type": "array", "description": "Logins for Users to assign to this issue. Pass one or more user logins to _replace_ the set of assignees on this Issue. Send an empty array (`[]`) to clear all assignees from the Issue. _NOTE: Only users with push access can set assignees for new issues. Assignees are silently dropped otherwise._", "items": { "type": "string" } } } }, "example": { "title": "Found a bug", "body": "I'm having a problem with this.", "assignees": [ "octocat" ], "milestone": 1, "state": "open", "labels": [ "bug" ] } } } }, "responses": { "200": { "description": "Response", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/issue" }, "examples": { "default": { "$ref": "#/components/examples/issue" } } } } }, "422": { "$ref": "#/components/responses/validation_failed" }, "503": { "$ref": "#/components/responses/service_unavailable" }, "403": { "$ref": "#/components/responses/forbidden" }, "301": { "$ref": "#/components/responses/moved_permanently" }, "404": { "$ref": "#/components/responses/not_found" }, "410": { "$ref": "#/components/responses/gone" } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": true, "category": "issues", "subcategory": null } } }, "/repos/{owner}/{repo}/issues/{issue_number}/assignees": { "post": { "summary": "Add assignees to an issue", "description": "Adds up to 10 assignees to an issue. Users already assigned to an issue are not replaced.", "tags": [ "issues" ], "operationId": "issues/add-assignees", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/issues#add-assignees-to-an-issue" }, "parameters": [ { "$ref": "#/components/parameters/owner" }, { "$ref": "#/components/parameters/repo" }, { "$ref": "#/components/parameters/issue-number" } ], "requestBody": { "required": false, "content": { "application/json": { "schema": { "type": "object", "properties": { "assignees": { "type": "array", "description": "Usernames of people to assign this issue to. _NOTE: Only users with push access can add assignees to an issue. Assignees are silently ignored otherwise._", "items": { "type": "string" } } } }, "example": { "assignees": [ "hubot", "other_user" ] } } } }, "responses": { "201": { "description": "Response", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/issue" }, "examples": { "default": { "$ref": "#/components/examples/issue" } } } } } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": true, "category": "issues", "subcategory": "assignees" } }, "delete": { "summary": "Remove assignees from an issue", "description": "Removes one or more assignees from an issue.", "tags": [ "issues" ], "operationId": "issues/remove-assignees", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/issues#remove-assignees-from-an-issue" }, "parameters": [ { "$ref": "#/components/parameters/owner" }, { "$ref": "#/components/parameters/repo" }, { "$ref": "#/components/parameters/issue-number" } ], "requestBody": { "content": { "application/json": { "schema": { "type": "object", "properties": { "assignees": { "type": "array", "description": "Usernames of assignees to remove from an issue. _NOTE: Only users with push access can remove assignees from an issue. Assignees are silently ignored otherwise._", "items": { "type": "string" } } } }, "example": { "assignees": [ "hubot", "other_user" ] } } } }, "responses": { "200": { "description": "Response", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/issue" }, "examples": { "default": { "$ref": "#/components/examples/issue" } } } } } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": true, "category": "issues", "subcategory": "assignees" } } }, "/repos/{owner}/{repo}/issues/{issue_number}/comments": { "get": { "summary": "List issue comments", "description": "Issue Comments are ordered by ascending ID.", "tags": [ "issues" ], "operationId": "issues/list-comments", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/issues#list-issue-comments" }, "parameters": [ { "$ref": "#/components/parameters/owner" }, { "$ref": "#/components/parameters/repo" }, { "$ref": "#/components/parameters/issue-number" }, { "$ref": "#/components/parameters/since" }, { "$ref": "#/components/parameters/per-page" }, { "$ref": "#/components/parameters/page" } ], "responses": { "200": { "description": "Response", "content": { "application/json": { "schema": { "type": "array", "items": { "$ref": "#/components/schemas/issue-comment" } }, "examples": { "default": { "$ref": "#/components/examples/issue-comment-items" } } } }, "headers": { "Link": { "$ref": "#/components/headers/link" } } }, "404": { "$ref": "#/components/responses/not_found" }, "410": { "$ref": "#/components/responses/gone" } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": true, "category": "issues", "subcategory": "comments", "previews": [ { "required": false, "name": "squirrel-girl", "note": "An additional `reactions` object in the issue comment payload is currently available for developers to preview. During the preview period, the APIs may change without advance notice. Please see the [blog post](https://developer.github.com/changes/2016-05-12-reactions-api-preview) for full details.\n\nTo access the API you must provide a custom [media type](https://docs.github.com/enterprise-server@3.0/rest/overview/media-types) in the `Accept` header:\n```shell\napplication/vnd.github.squirrel-girl-preview\n```\nThe `reactions` key will have the following payload where `url` can be used to construct the API location for [listing and creating](https://docs.github.com/enterprise-server@3.0/rest/reference/reactions) reactions." } ] } }, "post": { "summary": "Create an issue comment", "description": "This endpoint triggers [notifications](https://docs.github.com/enterprise-server@3.0/github/managing-subscriptions-and-notifications-on-github/about-notifications). Creating content too quickly using this endpoint may result in secondary rate limiting. See \"[Secondary rate limits](https://docs.github.com/enterprise-server@3.0/rest/overview/resources-in-the-rest-api#secondary-rate-limits)\" and \"[Dealing with secondary rate limits](https://docs.github.com/enterprise-server@3.0/rest/guides/best-practices-for-integrators#dealing-with-secondary-rate-limits)\" for details.", "tags": [ "issues" ], "operationId": "issues/create-comment", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/issues#create-an-issue-comment" }, "parameters": [ { "$ref": "#/components/parameters/owner" }, { "$ref": "#/components/parameters/repo" }, { "$ref": "#/components/parameters/issue-number" } ], "requestBody": { "required": true, "content": { "application/json": { "schema": { "type": "object", "properties": { "body": { "type": "string", "description": "The contents of the comment." } }, "required": [ "body" ] }, "example": { "body": "Me too" } } } }, "responses": { "201": { "description": "Response", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/issue-comment" }, "examples": { "default": { "$ref": "#/components/examples/issue-comment" } } } }, "headers": { "Location": { "example": "https://api.github.com/repos/octocat/Hello-World/issues/comments/1", "schema": { "type": "string" } } } }, "403": { "$ref": "#/components/responses/forbidden" }, "410": { "$ref": "#/components/responses/gone" }, "422": { "$ref": "#/components/responses/validation_failed" }, "404": { "$ref": "#/components/responses/not_found" } }, "x-github": { "triggersNotification": true, "githubCloudOnly": false, "enabledForGitHubApps": true, "category": "issues", "subcategory": "comments" } } }, "/repos/{owner}/{repo}/issues/{issue_number}/events": { "get": { "summary": "List issue events", "description": "", "tags": [ "issues" ], "operationId": "issues/list-events", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/issues#list-issue-events" }, "parameters": [ { "$ref": "#/components/parameters/owner" }, { "$ref": "#/components/parameters/repo" }, { "$ref": "#/components/parameters/issue-number" }, { "$ref": "#/components/parameters/per-page" }, { "$ref": "#/components/parameters/page" } ], "responses": { "200": { "description": "Response", "content": { "application/json": { "schema": { "type": "array", "items": { "$ref": "#/components/schemas/issue-event-for-issue" } }, "examples": { "default": { "$ref": "#/components/examples/issue-event-for-issue-items" } } } }, "headers": { "Link": { "$ref": "#/components/headers/link" } } }, "410": { "$ref": "#/components/responses/gone" } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": true, "category": "issues", "subcategory": "events", "previews": [ { "required": false, "name": "starfox", "note": "Project card details are now shown in REST API v3 responses for project-related issue and timeline events. This feature is now available for developers to preview. For details, see the [blog post](https://developer.github.com/changes/2018-09-05-project-card-events).\n\nTo receive the `project_card` attribute, project boards must be [enabled](https://docs.github.com/articles/disabling-project-boards-in-a-repository) for a repository, and you must provide a custom [media type](https://docs.github.com/enterprise-server@3.0/rest/overview/media-types) in the `Accept` header:\n```shell\napplication/vnd.github.starfox-preview+json\n```" } ] } } }, "/repos/{owner}/{repo}/issues/{issue_number}/labels": { "get": { "summary": "List labels for an issue", "description": "", "tags": [ "issues" ], "operationId": "issues/list-labels-on-issue", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/issues#list-labels-for-an-issue" }, "parameters": [ { "$ref": "#/components/parameters/owner" }, { "$ref": "#/components/parameters/repo" }, { "$ref": "#/components/parameters/issue-number" }, { "$ref": "#/components/parameters/per-page" }, { "$ref": "#/components/parameters/page" } ], "responses": { "200": { "description": "Response", "content": { "application/json": { "schema": { "type": "array", "items": { "$ref": "#/components/schemas/label" } }, "examples": { "default": { "$ref": "#/components/examples/label-items" } } } }, "headers": { "Link": { "$ref": "#/components/headers/link" } } }, "410": { "$ref": "#/components/responses/gone" } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": true, "category": "issues", "subcategory": "labels" } }, "post": { "summary": "Add labels to an issue", "description": "", "tags": [ "issues" ], "operationId": "issues/add-labels", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/issues#add-labels-to-an-issue" }, "parameters": [ { "$ref": "#/components/parameters/owner" }, { "$ref": "#/components/parameters/repo" }, { "$ref": "#/components/parameters/issue-number" } ], "requestBody": { "required": false, "content": { "application/json": { "schema": { "oneOf": [ { "type": "object", "properties": { "labels": { "type": "array", "minItems": 1, "description": "The names of the labels to add to the issue's existing labels. You can pass an empty array to remove all labels. Alternatively, you can pass a single label as a `string` or an `array` of labels directly, but GitHub recommends passing an object with the `labels` key. You can also replace all of the labels for an issue. For more information, see \"[Set labels for an issue](https://docs.github.com/enterprise-server@3.0/rest/reference/issues#set-labels-for-an-issue).\"", "items": { "type": "string" } } } }, { "type": "array", "minItems": 1, "items": { "type": "string" } }, { "type": "object", "properties": { "labels": { "type": "array", "minItems": 1, "items": { "type": "object", "properties": { "name": { "type": "string" } }, "required": [ "name" ] } } } }, { "type": "array", "minItems": 1, "items": { "type": "object", "properties": { "name": { "type": "string" } }, "required": [ "name" ] } }, { "type": "string" } ] }, "example": { "labels": [ "bug", "enhancement" ] } } } }, "responses": { "200": { "description": "Response", "content": { "application/json": { "schema": { "type": "array", "items": { "$ref": "#/components/schemas/label" } }, "examples": { "default": { "$ref": "#/components/examples/label-items" } } } } }, "410": { "$ref": "#/components/responses/gone" }, "422": { "$ref": "#/components/responses/validation_failed" } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": true, "category": "issues", "subcategory": "labels" } }, "put": { "summary": "Set labels for an issue", "description": "Removes any previous labels and sets the new labels for an issue.", "tags": [ "issues" ], "operationId": "issues/set-labels", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/issues#set-labels-for-an-issue" }, "parameters": [ { "$ref": "#/components/parameters/owner" }, { "$ref": "#/components/parameters/repo" }, { "$ref": "#/components/parameters/issue-number" } ], "requestBody": { "required": false, "content": { "application/json": { "schema": { "oneOf": [ { "type": "object", "properties": { "labels": { "type": "array", "minItems": 1, "description": "The names of the labels to set for the issue. The labels you set replace any existing labels. You can pass an empty array to remove all labels. Alternatively, you can pass a single label as a `string` or an `array` of labels directly, but GitHub recommends passing an object with the `labels` key. You can also add labels to the existing labels for an issue. For more information, see \"[Add labels to an issue](https://docs.github.com/enterprise-server@3.0/rest/reference/issues#add-labels-to-an-issue).\"", "items": { "type": "string" } } } }, { "type": "array", "minItems": 1, "items": { "type": "string" } }, { "type": "object", "properties": { "labels": { "type": "array", "minItems": 1, "items": { "type": "object", "properties": { "name": { "type": "string" } }, "required": [ "name" ] } } } }, { "type": "array", "minItems": 1, "items": { "type": "object", "properties": { "name": { "type": "string" } }, "required": [ "name" ] } }, { "type": "string" } ] }, "example": { "labels": [ "bug", "enhancement" ] } } } }, "responses": { "200": { "description": "Response", "content": { "application/json": { "schema": { "type": "array", "items": { "$ref": "#/components/schemas/label" } }, "examples": { "default": { "$ref": "#/components/examples/label-items" } } } } }, "410": { "$ref": "#/components/responses/gone" }, "422": { "$ref": "#/components/responses/validation_failed" } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": true, "category": "issues", "subcategory": "labels" } }, "delete": { "summary": "Remove all labels from an issue", "description": "", "tags": [ "issues" ], "operationId": "issues/remove-all-labels", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/issues#remove-all-labels-from-an-issue" }, "parameters": [ { "$ref": "#/components/parameters/owner" }, { "$ref": "#/components/parameters/repo" }, { "$ref": "#/components/parameters/issue-number" } ], "responses": { "204": { "description": "Response" }, "410": { "$ref": "#/components/responses/gone" } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": true, "category": "issues", "subcategory": "labels" } } }, "/repos/{owner}/{repo}/issues/{issue_number}/labels/{name}": { "delete": { "summary": "Remove a label from an issue", "description": "Removes the specified label from the issue, and returns the remaining labels on the issue. This endpoint returns a `404 Not Found` status if the label does not exist.", "tags": [ "issues" ], "operationId": "issues/remove-label", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/issues#remove-a-label-from-an-issue" }, "parameters": [ { "$ref": "#/components/parameters/owner" }, { "$ref": "#/components/parameters/repo" }, { "$ref": "#/components/parameters/issue-number" }, { "name": "name", "in": "path", "required": true, "schema": { "type": "string" } } ], "responses": { "200": { "description": "Response", "content": { "application/json": { "schema": { "type": "array", "items": { "$ref": "#/components/schemas/label" } }, "examples": { "default": { "$ref": "#/components/examples/label-items-2" } } } } }, "404": { "$ref": "#/components/responses/not_found" }, "410": { "$ref": "#/components/responses/gone" } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": true, "category": "issues", "subcategory": "labels" } } }, "/repos/{owner}/{repo}/issues/{issue_number}/lock": { "put": { "summary": "Lock an issue", "description": "Users with push access can lock an issue or pull request's conversation.\n\nNote that, if you choose not to pass any parameters, you'll need to set `Content-Length` to zero when calling out to this endpoint. For more information, see \"[HTTP verbs](https://docs.github.com/enterprise-server@3.0/rest/overview/resources-in-the-rest-api#http-verbs).\"", "tags": [ "issues" ], "operationId": "issues/lock", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/issues#lock-an-issue" }, "parameters": [ { "$ref": "#/components/parameters/owner" }, { "$ref": "#/components/parameters/repo" }, { "$ref": "#/components/parameters/issue-number" } ], "requestBody": { "required": false, "content": { "application/json": { "schema": { "type": [ "object", "null" ], "properties": { "lock_reason": { "type": "string", "description": "The reason for locking the issue or pull request conversation. Lock will fail if you don't use one of these reasons: \n\\* `off-topic` \n\\* `too heated` \n\\* `resolved` \n\\* `spam`", "enum": [ "off-topic", "too heated", "resolved", "spam" ] } } } } } }, "responses": { "204": { "description": "Response" }, "403": { "$ref": "#/components/responses/forbidden" }, "410": { "$ref": "#/components/responses/gone" }, "404": { "$ref": "#/components/responses/not_found" }, "422": { "$ref": "#/components/responses/validation_failed" } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": true, "category": "issues", "subcategory": null } }, "delete": { "summary": "Unlock an issue", "description": "Users with push access can unlock an issue's conversation.", "tags": [ "issues" ], "operationId": "issues/unlock", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/issues#unlock-an-issue" }, "parameters": [ { "$ref": "#/components/parameters/owner" }, { "$ref": "#/components/parameters/repo" }, { "$ref": "#/components/parameters/issue-number" } ], "responses": { "204": { "description": "Response" }, "403": { "$ref": "#/components/responses/forbidden" }, "404": { "$ref": "#/components/responses/not_found" } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": true, "category": "issues", "subcategory": null } } }, "/repos/{owner}/{repo}/issues/{issue_number}/reactions": { "get": { "summary": "List reactions for an issue", "description": "List the reactions to an [issue](https://docs.github.com/enterprise-server@3.0/rest/reference/issues).", "tags": [ "reactions" ], "operationId": "reactions/list-for-issue", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/reactions#list-reactions-for-an-issue" }, "parameters": [ { "$ref": "#/components/parameters/owner" }, { "$ref": "#/components/parameters/repo" }, { "$ref": "#/components/parameters/issue-number" }, { "name": "content", "description": "Returns a single [reaction type](https://docs.github.com/enterprise-server@3.0/rest/reference/reactions#reaction-types). Omit this parameter to list all reactions to an issue.", "in": "query", "required": false, "schema": { "type": "string", "enum": [ "+1", "-1", "laugh", "confused", "heart", "hooray", "rocket", "eyes" ] } }, { "$ref": "#/components/parameters/per-page" }, { "$ref": "#/components/parameters/page" } ], "responses": { "200": { "description": "Response", "content": { "application/json": { "schema": { "type": "array", "items": { "$ref": "#/components/schemas/reaction" } }, "examples": { "default": { "$ref": "#/components/examples/reaction-items" } } } }, "headers": { "Link": { "$ref": "#/components/headers/link" } } }, "404": { "$ref": "#/components/responses/not_found" }, "410": { "$ref": "#/components/responses/gone" } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": true, "category": "reactions", "previews": [ { "required": true, "name": "squirrel-girl", "note": "An additional `reactions` object in the issue comment payload is currently available for developers to preview. During the preview period, the APIs may change without advance notice. Please see the [blog post](https://developer.github.com/changes/2016-05-12-reactions-api-preview) for full details.\n\nTo access the API you must provide a custom [media type](https://docs.github.com/enterprise-server@3.0/rest/overview/media-types) in the `Accept` header:\n```shell\napplication/vnd.github.squirrel-girl-preview\n```\nThe `reactions` key will have the following payload where `url` can be used to construct the API location for [listing and creating](https://docs.github.com/enterprise-server@3.0/rest/reference/reactions) reactions." } ] } }, "post": { "summary": "Create reaction for an issue", "description": "Create a reaction to an [issue](https://docs.github.com/enterprise-server@3.0/rest/reference/issues/). A response with an HTTP `200` status means that you already added the reaction type to this issue.", "tags": [ "reactions" ], "operationId": "reactions/create-for-issue", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/reactions#create-reaction-for-an-issue" }, "parameters": [ { "$ref": "#/components/parameters/owner" }, { "$ref": "#/components/parameters/repo" }, { "$ref": "#/components/parameters/issue-number" } ], "requestBody": { "required": true, "content": { "application/json": { "schema": { "type": "object", "properties": { "content": { "type": "string", "description": "The [reaction type](https://docs.github.com/enterprise-server@3.0/rest/reference/reactions#reaction-types) to add to the issue.", "enum": [ "+1", "-1", "laugh", "confused", "heart", "hooray", "rocket", "eyes" ] } }, "required": [ "content" ] }, "example": { "content": "heart" } } } }, "responses": { "200": { "description": "Response", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/reaction" }, "examples": { "default": { "$ref": "#/components/examples/reaction" } } } } }, "201": { "description": "Response", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/reaction" }, "examples": { "default": { "$ref": "#/components/examples/reaction" } } } } }, "422": { "$ref": "#/components/responses/validation_failed" } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": false, "category": "reactions", "previews": [ { "required": true, "name": "squirrel-girl", "note": "An additional `reactions` object in the issue comment payload is currently available for developers to preview. During the preview period, the APIs may change without advance notice. Please see the [blog post](https://developer.github.com/changes/2016-05-12-reactions-api-preview) for full details.\n\nTo access the API you must provide a custom [media type](https://docs.github.com/enterprise-server@3.0/rest/overview/media-types) in the `Accept` header:\n```shell\napplication/vnd.github.squirrel-girl-preview\n```\nThe `reactions` key will have the following payload where `url` can be used to construct the API location for [listing and creating](https://docs.github.com/enterprise-server@3.0/rest/reference/reactions) reactions." } ] } } }, "/repos/{owner}/{repo}/issues/{issue_number}/reactions/{reaction_id}": { "delete": { "summary": "Delete an issue reaction", "description": "**Note:** You can also specify a repository by `repository_id` using the route `DELETE /repositories/:repository_id/issues/:issue_number/reactions/:reaction_id`.\n\nDelete a reaction to an [issue](https://docs.github.com/enterprise-server@3.0/rest/reference/issues/).", "tags": [ "reactions" ], "operationId": "reactions/delete-for-issue", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/reactions#delete-an-issue-reaction" }, "parameters": [ { "$ref": "#/components/parameters/owner" }, { "$ref": "#/components/parameters/repo" }, { "$ref": "#/components/parameters/issue-number" }, { "$ref": "#/components/parameters/reaction-id" } ], "responses": { "204": { "description": "Response" } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": true, "category": "reactions", "previews": [ { "required": true, "name": "squirrel-girl", "note": "An additional `reactions` object in the issue comment payload is currently available for developers to preview. During the preview period, the APIs may change without advance notice. Please see the [blog post](https://developer.github.com/changes/2016-05-12-reactions-api-preview) for full details.\n\nTo access the API you must provide a custom [media type](https://docs.github.com/enterprise-server@3.0/rest/overview/media-types) in the `Accept` header:\n```shell\napplication/vnd.github.squirrel-girl-preview\n```\nThe `reactions` key will have the following payload where `url` can be used to construct the API location for [listing and creating](https://docs.github.com/enterprise-server@3.0/rest/reference/reactions) reactions." } ] } } }, "/repos/{owner}/{repo}/issues/{issue_number}/timeline": { "get": { "summary": "List timeline events for an issue", "description": "", "tags": [ "issues" ], "operationId": "issues/list-events-for-timeline", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/issues#list-timeline-events-for-an-issue" }, "parameters": [ { "$ref": "#/components/parameters/owner" }, { "$ref": "#/components/parameters/repo" }, { "$ref": "#/components/parameters/issue-number" }, { "$ref": "#/components/parameters/per-page" }, { "$ref": "#/components/parameters/page" } ], "responses": { "200": { "description": "Response", "content": { "application/json": { "schema": { "type": "array", "items": { "$ref": "#/components/schemas/timeline-issue-events" } } } }, "headers": { "Link": { "$ref": "#/components/headers/link" } } }, "404": { "$ref": "#/components/responses/not_found" }, "410": { "$ref": "#/components/responses/gone" } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": true, "category": "issues", "subcategory": "timeline", "previews": [ { "required": true, "name": "mockingbird", "note": "The API to get issue timeline events is currently available for developers to preview. During the preview period, the APIs may change without advance notice. Please see the [blog post](https://developer.github.com/changes/2016-05-23-timeline-preview-api/) for full details. To access the API you must provide a custom [media type](https://docs.github.com/enterprise-server@3.0/rest/overview/media-types) in the `Accept` header:\n```shell\napplication/vnd.github.mockingbird-preview\n```" }, { "required": false, "name": "starfox", "note": "Project card details are now shown in REST API v3 responses for project-related issue and timeline events. This feature is now available for developers to preview. For details, see the [blog post](https://developer.github.com/changes/2018-09-05-project-card-events).\n\nTo receive the `project_card` attribute, project boards must be [enabled](https://docs.github.com/articles/disabling-project-boards-in-a-repository) for a repository, and you must provide a custom [media type](https://docs.github.com/enterprise-server@3.0/rest/overview/media-types) in the `Accept` header:\n```shell\napplication/vnd.github.starfox-preview+json\n```" } ] } } }, "/repos/{owner}/{repo}/keys": { "get": { "summary": "List deploy keys", "description": "", "tags": [ "repos" ], "operationId": "repos/list-deploy-keys", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/repos#list-deploy-keys" }, "parameters": [ { "$ref": "#/components/parameters/owner" }, { "$ref": "#/components/parameters/repo" }, { "$ref": "#/components/parameters/per-page" }, { "$ref": "#/components/parameters/page" } ], "responses": { "200": { "description": "Response", "content": { "application/json": { "schema": { "type": "array", "items": { "$ref": "#/components/schemas/deploy-key" } }, "examples": { "default": { "$ref": "#/components/examples/deploy-key-items" } } } }, "headers": { "Link": { "$ref": "#/components/headers/link" } } } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": true, "category": "repos", "subcategory": "keys" } }, "post": { "summary": "Create a deploy key", "description": "You can create a read-only deploy key.", "tags": [ "repos" ], "operationId": "repos/create-deploy-key", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/repos#create-a-deploy-key" }, "parameters": [ { "$ref": "#/components/parameters/owner" }, { "$ref": "#/components/parameters/repo" } ], "requestBody": { "required": true, "content": { "application/json": { "schema": { "type": "object", "properties": { "title": { "type": "string", "description": "A name for the key." }, "key": { "type": "string", "description": "The contents of the key." }, "read_only": { "type": "boolean", "description": "If `true`, the key will only be able to read repository contents. Otherwise, the key will be able to read and write. \n \nDeploy keys with write access can perform the same actions as an organization member with admin access, or a collaborator on a personal repository. For more information, see \"[Repository permission levels for an organization](https://docs.github.com/articles/repository-permission-levels-for-an-organization/)\" and \"[Permission levels for a user account repository](https://docs.github.com/articles/permission-levels-for-a-user-account-repository/).\"" } }, "required": [ "key" ] }, "example": { "title": "octocat@octomac", "key": "ssh-rsa AAA...", "read_only": true } } } }, "responses": { "201": { "description": "Response", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/deploy-key" }, "examples": { "default": { "$ref": "#/components/examples/deploy-key" } } } }, "headers": { "Location": { "example": "https://api.github.com/repos/octocat/Hello-World/keys/1", "schema": { "type": "string" } } } }, "422": { "$ref": "#/components/responses/validation_failed" } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": true, "category": "repos", "subcategory": "keys" } } }, "/repos/{owner}/{repo}/keys/{key_id}": { "get": { "summary": "Get a deploy key", "description": "", "tags": [ "repos" ], "operationId": "repos/get-deploy-key", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/repos#get-a-deploy-key" }, "parameters": [ { "$ref": "#/components/parameters/owner" }, { "$ref": "#/components/parameters/repo" }, { "$ref": "#/components/parameters/key-id" } ], "responses": { "200": { "description": "Response", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/deploy-key" }, "examples": { "default": { "$ref": "#/components/examples/deploy-key" } } } } }, "404": { "$ref": "#/components/responses/not_found" } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": true, "category": "repos", "subcategory": "keys" } }, "delete": { "summary": "Delete a deploy key", "description": "Deploy keys are immutable. If you need to update a key, remove the key and create a new one instead.", "tags": [ "repos" ], "operationId": "repos/delete-deploy-key", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/repos#delete-a-deploy-key" }, "parameters": [ { "$ref": "#/components/parameters/owner" }, { "$ref": "#/components/parameters/repo" }, { "$ref": "#/components/parameters/key-id" } ], "responses": { "204": { "description": "Response" } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": true, "category": "repos", "subcategory": "keys" } } }, "/repos/{owner}/{repo}/labels": { "get": { "summary": "List labels for a repository", "description": "", "tags": [ "issues" ], "operationId": "issues/list-labels-for-repo", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/issues#list-labels-for-a-repository" }, "parameters": [ { "$ref": "#/components/parameters/owner" }, { "$ref": "#/components/parameters/repo" }, { "$ref": "#/components/parameters/per-page" }, { "$ref": "#/components/parameters/page" } ], "responses": { "200": { "description": "Response", "content": { "application/json": { "schema": { "type": "array", "items": { "$ref": "#/components/schemas/label" } }, "examples": { "default": { "$ref": "#/components/examples/label-items" } } } }, "headers": { "Link": { "$ref": "#/components/headers/link" } } }, "404": { "$ref": "#/components/responses/not_found" } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": true, "category": "issues", "subcategory": "labels" } }, "post": { "summary": "Create a label", "description": "", "tags": [ "issues" ], "operationId": "issues/create-label", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/issues#create-a-label" }, "parameters": [ { "$ref": "#/components/parameters/owner" }, { "$ref": "#/components/parameters/repo" } ], "requestBody": { "required": true, "content": { "application/json": { "schema": { "type": "object", "properties": { "name": { "type": "string", "description": "The name of the label. Emoji can be added to label names, using either native emoji or colon-style markup. For example, typing `:strawberry:` will render the emoji ![:strawberry:](https://github.githubassets.com/images/icons/emoji/unicode/1f353.png \":strawberry:\"). For a full list of available emoji and codes, see \"[Emoji cheat sheet](https://github.com/ikatyang/emoji-cheat-sheet).\"" }, "color": { "type": "string", "description": "The [hexadecimal color code](http://www.color-hex.com/) for the label, without the leading `#`." }, "description": { "type": "string", "description": "A short description of the label. Must be 100 characters or fewer." } }, "required": [ "name" ] }, "example": { "name": "bug", "description": "Something isn't working", "color": "f29513" } } } }, "responses": { "201": { "description": "Response", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/label" }, "examples": { "default": { "$ref": "#/components/examples/label" } } } }, "headers": { "Location": { "example": "https://api.github.com/repos/octocat/Hello-World/labels/bug", "schema": { "type": "string" } } } }, "422": { "$ref": "#/components/responses/validation_failed" }, "404": { "$ref": "#/components/responses/not_found" } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": true, "category": "issues", "subcategory": "labels" } } }, "/repos/{owner}/{repo}/labels/{name}": { "get": { "summary": "Get a label", "description": "", "tags": [ "issues" ], "operationId": "issues/get-label", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/issues#get-a-label" }, "parameters": [ { "$ref": "#/components/parameters/owner" }, { "$ref": "#/components/parameters/repo" }, { "name": "name", "in": "path", "required": true, "schema": { "type": "string" } } ], "responses": { "200": { "description": "Response", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/label" }, "examples": { "default": { "$ref": "#/components/examples/label" } } } } }, "404": { "$ref": "#/components/responses/not_found" } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": true, "category": "issues", "subcategory": "labels" } }, "patch": { "summary": "Update a label", "description": "", "tags": [ "issues" ], "operationId": "issues/update-label", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/issues#update-a-label" }, "parameters": [ { "$ref": "#/components/parameters/owner" }, { "$ref": "#/components/parameters/repo" }, { "name": "name", "in": "path", "required": true, "schema": { "type": "string" } } ], "requestBody": { "required": false, "content": { "application/json": { "schema": { "type": "object", "properties": { "new_name": { "type": "string", "description": "The new name of the label. Emoji can be added to label names, using either native emoji or colon-style markup. For example, typing `:strawberry:` will render the emoji ![:strawberry:](https://github.githubassets.com/images/icons/emoji/unicode/1f353.png \":strawberry:\"). For a full list of available emoji and codes, see \"[Emoji cheat sheet](https://github.com/ikatyang/emoji-cheat-sheet).\"" }, "color": { "type": "string", "description": "The [hexadecimal color code](http://www.color-hex.com/) for the label, without the leading `#`." }, "description": { "type": "string", "description": "A short description of the label. Must be 100 characters or fewer." } } }, "example": { "new_name": "bug :bug:", "description": "Small bug fix required", "color": "b01f26" } } } }, "responses": { "200": { "description": "Response", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/label" }, "examples": { "default": { "$ref": "#/components/examples/label-2" } } } } } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": true, "category": "issues", "subcategory": "labels" } }, "delete": { "summary": "Delete a label", "description": "", "tags": [ "issues" ], "operationId": "issues/delete-label", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/issues#delete-a-label" }, "parameters": [ { "$ref": "#/components/parameters/owner" }, { "$ref": "#/components/parameters/repo" }, { "name": "name", "in": "path", "required": true, "schema": { "type": "string" } } ], "responses": { "204": { "description": "Response" } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": true, "category": "issues", "subcategory": "labels" } } }, "/repos/{owner}/{repo}/languages": { "get": { "summary": "List repository languages", "description": "Lists languages for the specified repository. The value shown for each language is the number of bytes of code written in that language.", "tags": [ "repos" ], "operationId": "repos/list-languages", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/repos#list-repository-languages" }, "parameters": [ { "$ref": "#/components/parameters/owner" }, { "$ref": "#/components/parameters/repo" } ], "responses": { "200": { "description": "Response", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/language" }, "examples": { "default": { "$ref": "#/components/examples/language" } } } } } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": true, "category": "repos", "subcategory": null } } }, "/repos/{owner}/{repo}/license": { "get": { "summary": "Get the license for a repository", "description": "This method returns the contents of the repository's license file, if one is detected.\n\nSimilar to [Get repository content](https://docs.github.com/enterprise-server@3.0/rest/reference/repos#get-repository-content), this method also supports [custom media types](https://docs.github.com/enterprise-server@3.0/rest/overview/media-types) for retrieving the raw license content or rendered license HTML.", "tags": [ "licenses" ], "operationId": "licenses/get-for-repo", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/licenses/#get-the-license-for-a-repository" }, "parameters": [ { "$ref": "#/components/parameters/owner" }, { "$ref": "#/components/parameters/repo" } ], "responses": { "200": { "description": "Response", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/license-content" }, "examples": { "default": { "$ref": "#/components/examples/license-content" } } } } } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": true, "category": "licenses", "subcategory": null } } }, "/repos/{owner}/{repo}/merges": { "post": { "summary": "Merge a branch", "description": "", "tags": [ "repos" ], "operationId": "repos/merge", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/repos#merge-a-branch" }, "parameters": [ { "$ref": "#/components/parameters/owner" }, { "$ref": "#/components/parameters/repo" } ], "requestBody": { "required": true, "content": { "application/json": { "schema": { "type": "object", "properties": { "base": { "type": "string", "description": "The name of the base branch that the head will be merged into." }, "head": { "type": "string", "description": "The head to merge. This can be a branch name or a commit SHA1." }, "commit_message": { "type": "string", "description": "Commit message to use for the merge commit. If omitted, a default message will be used." } }, "required": [ "base", "head" ] }, "example": { "base": "master", "head": "cool_feature", "commit_message": "Shipped cool_feature!" } } } }, "responses": { "201": { "description": "Successful Response (The resulting merge commit)", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/commit" }, "examples": { "default": { "$ref": "#/components/examples/commit" } } } } }, "204": { "description": "Response when already merged" }, "404": { "description": "Not Found when the base or head does not exist" }, "409": { "description": "Conflict when there is a merge conflict" }, "403": { "$ref": "#/components/responses/forbidden" }, "422": { "$ref": "#/components/responses/validation_failed" } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": true, "category": "repos", "subcategory": "merging" } } }, "/repos/{owner}/{repo}/milestones": { "get": { "summary": "List milestones", "description": "", "tags": [ "issues" ], "operationId": "issues/list-milestones", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/issues#list-milestones" }, "parameters": [ { "$ref": "#/components/parameters/owner" }, { "$ref": "#/components/parameters/repo" }, { "name": "state", "description": "The state of the milestone. Either `open`, `closed`, or `all`.", "in": "query", "required": false, "schema": { "type": "string", "enum": [ "open", "closed", "all" ], "default": "open" } }, { "name": "sort", "description": "What to sort results by. Either `due_on` or `completeness`.", "in": "query", "required": false, "schema": { "type": "string", "enum": [ "due_on", "completeness" ], "default": "due_on" } }, { "name": "direction", "description": "The direction of the sort. Either `asc` or `desc`.", "in": "query", "required": false, "schema": { "type": "string", "enum": [ "asc", "desc" ], "default": "asc" } }, { "$ref": "#/components/parameters/per-page" }, { "$ref": "#/components/parameters/page" } ], "responses": { "200": { "description": "Response", "content": { "application/json": { "schema": { "type": "array", "items": { "$ref": "#/components/schemas/milestone" } }, "examples": { "default": { "$ref": "#/components/examples/milestone-items" } } } }, "headers": { "Link": { "$ref": "#/components/headers/link" } } }, "404": { "$ref": "#/components/responses/not_found" } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": true, "category": "issues", "subcategory": "milestones" } }, "post": { "summary": "Create a milestone", "description": "", "tags": [ "issues" ], "operationId": "issues/create-milestone", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/issues#create-a-milestone" }, "parameters": [ { "$ref": "#/components/parameters/owner" }, { "$ref": "#/components/parameters/repo" } ], "requestBody": { "required": true, "content": { "application/json": { "schema": { "type": "object", "properties": { "title": { "type": "string", "description": "The title of the milestone." }, "state": { "type": "string", "description": "The state of the milestone. Either `open` or `closed`.", "enum": [ "open", "closed" ], "default": "open" }, "description": { "type": "string", "description": "A description of the milestone." }, "due_on": { "type": "string", "format": "date-time", "description": "The milestone due date. This is a timestamp in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format: `YYYY-MM-DDTHH:MM:SSZ`." } }, "required": [ "title" ] }, "example": { "title": "v1.0", "state": "open", "description": "Tracking milestone for version 1.0", "due_on": "2012-10-09T23:39:01Z" } } } }, "responses": { "201": { "description": "Response", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/milestone" }, "examples": { "default": { "$ref": "#/components/examples/milestone" } } } }, "headers": { "Location": { "example": "https://api.github.com/repos/octocat/Hello-World/milestones/1", "schema": { "type": "string" } } } }, "404": { "$ref": "#/components/responses/not_found" }, "422": { "$ref": "#/components/responses/validation_failed" } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": true, "category": "issues", "subcategory": "milestones" } } }, "/repos/{owner}/{repo}/milestones/{milestone_number}": { "get": { "summary": "Get a milestone", "description": "", "tags": [ "issues" ], "operationId": "issues/get-milestone", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/issues#get-a-milestone" }, "parameters": [ { "$ref": "#/components/parameters/owner" }, { "$ref": "#/components/parameters/repo" }, { "$ref": "#/components/parameters/milestone-number" } ], "responses": { "200": { "description": "Response", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/milestone" }, "examples": { "default": { "$ref": "#/components/examples/milestone" } } } } }, "404": { "$ref": "#/components/responses/not_found" } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": true, "category": "issues", "subcategory": "milestones" } }, "patch": { "summary": "Update a milestone", "description": "", "tags": [ "issues" ], "operationId": "issues/update-milestone", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/issues#update-a-milestone" }, "parameters": [ { "$ref": "#/components/parameters/owner" }, { "$ref": "#/components/parameters/repo" }, { "$ref": "#/components/parameters/milestone-number" } ], "requestBody": { "required": false, "content": { "application/json": { "schema": { "type": "object", "properties": { "title": { "type": "string", "description": "The title of the milestone." }, "state": { "type": "string", "description": "The state of the milestone. Either `open` or `closed`.", "enum": [ "open", "closed" ], "default": "open" }, "description": { "type": "string", "description": "A description of the milestone." }, "due_on": { "type": "string", "format": "date-time", "description": "The milestone due date. This is a timestamp in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format: `YYYY-MM-DDTHH:MM:SSZ`." } } }, "example": { "title": "v1.0", "state": "open", "description": "Tracking milestone for version 1.0", "due_on": "2012-10-09T23:39:01Z" } } } }, "responses": { "200": { "description": "Response", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/milestone" }, "examples": { "default": { "$ref": "#/components/examples/milestone" } } } } } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": true, "category": "issues", "subcategory": "milestones" } }, "delete": { "summary": "Delete a milestone", "description": "", "tags": [ "issues" ], "operationId": "issues/delete-milestone", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/issues#delete-a-milestone" }, "parameters": [ { "$ref": "#/components/parameters/owner" }, { "$ref": "#/components/parameters/repo" }, { "$ref": "#/components/parameters/milestone-number" } ], "responses": { "204": { "description": "Response" }, "404": { "$ref": "#/components/responses/not_found" } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": true, "category": "issues", "subcategory": "milestones" } } }, "/repos/{owner}/{repo}/milestones/{milestone_number}/labels": { "get": { "summary": "List labels for issues in a milestone", "description": "", "tags": [ "issues" ], "operationId": "issues/list-labels-for-milestone", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/issues#list-labels-for-issues-in-a-milestone" }, "parameters": [ { "$ref": "#/components/parameters/owner" }, { "$ref": "#/components/parameters/repo" }, { "$ref": "#/components/parameters/milestone-number" }, { "$ref": "#/components/parameters/per-page" }, { "$ref": "#/components/parameters/page" } ], "responses": { "200": { "description": "Response", "content": { "application/json": { "schema": { "type": "array", "items": { "$ref": "#/components/schemas/label" } }, "examples": { "default": { "$ref": "#/components/examples/label-items" } } } }, "headers": { "Link": { "$ref": "#/components/headers/link" } } } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": true, "category": "issues", "subcategory": "labels" } } }, "/repos/{owner}/{repo}/notifications": { "get": { "summary": "List repository notifications for the authenticated user", "description": "List all notifications for the current user.", "tags": [ "activity" ], "operationId": "activity/list-repo-notifications-for-authenticated-user", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/activity#list-repository-notifications-for-the-authenticated-user" }, "parameters": [ { "$ref": "#/components/parameters/owner" }, { "$ref": "#/components/parameters/repo" }, { "$ref": "#/components/parameters/all" }, { "$ref": "#/components/parameters/participating" }, { "$ref": "#/components/parameters/since" }, { "$ref": "#/components/parameters/before" }, { "$ref": "#/components/parameters/per-page" }, { "$ref": "#/components/parameters/page" } ], "responses": { "200": { "description": "Response", "content": { "application/json": { "schema": { "type": "array", "items": { "$ref": "#/components/schemas/thread" } }, "examples": { "default": { "$ref": "#/components/examples/thread-items" } } } }, "headers": { "Link": { "$ref": "#/components/headers/link" } } } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": false, "category": "activity", "subcategory": "notifications" } }, "put": { "summary": "Mark repository notifications as read", "description": "Marks all notifications in a repository as \"read\" removes them from the [default view on GitHub Enterprise Server](https://github.com/notifications). If the number of notifications is too large to complete in one request, you will receive a `202 Accepted` status and GitHub Enterprise Server will run an asynchronous process to mark notifications as \"read.\" To check whether any \"unread\" notifications remain, you can use the [List repository notifications for the authenticated user](https://docs.github.com/enterprise-server@3.0/rest/reference/activity#list-repository-notifications-for-the-authenticated-user) endpoint and pass the query parameter `all=false`.", "tags": [ "activity" ], "operationId": "activity/mark-repo-notifications-as-read", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/activity#mark-repository-notifications-as-read" }, "parameters": [ { "$ref": "#/components/parameters/owner" }, { "$ref": "#/components/parameters/repo" } ], "requestBody": { "required": false, "content": { "application/json": { "schema": { "type": "object", "properties": { "last_read_at": { "type": "string", "format": "date-time", "description": "Describes the last point that notifications were checked. Anything updated since this time will not be marked as read. If you omit this parameter, all notifications are marked as read. This is a timestamp in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format: `YYYY-MM-DDTHH:MM:SSZ`. Default: The current timestamp." } } } } } }, "responses": { "202": { "description": "Response", "content": { "application/json": { "schema": { "type": "object", "properties": { "message": { "type": "string" }, "url": { "type": "string" } } } } } }, "205": { "description": "Reset Content" } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": false, "category": "activity", "subcategory": "notifications" } } }, "/repos/{owner}/{repo}/pages": { "get": { "summary": "Get a GitHub Enterprise Server Pages site", "description": "", "tags": [ "repos" ], "operationId": "repos/get-pages", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/repos#get-a-github-pages-site" }, "parameters": [ { "$ref": "#/components/parameters/owner" }, { "$ref": "#/components/parameters/repo" } ], "responses": { "200": { "description": "Response", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/page" }, "examples": { "default": { "$ref": "#/components/examples/page" } } } } }, "404": { "$ref": "#/components/responses/not_found" } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": true, "category": "repos", "subcategory": "pages" } }, "post": { "summary": "Create a GitHub Enterprise Server Pages site", "description": "Configures a GitHub Enterprise Server Pages site. For more information, see \"[About GitHub Pages](/github/working-with-github-pages/about-github-pages).\"", "tags": [ "repos" ], "operationId": "repos/create-pages-site", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/repos#create-a-github-pages-site" }, "parameters": [ { "$ref": "#/components/parameters/owner" }, { "$ref": "#/components/parameters/repo" } ], "requestBody": { "required": true, "content": { "application/json": { "schema": { "type": [ "object", "null" ], "description": "The source branch and directory used to publish your Pages site.", "properties": { "source": { "type": "object", "description": "The source branch and directory used to publish your Pages site.", "properties": { "branch": { "type": "string", "description": "The repository branch used to publish your site's source files." }, "path": { "type": "string", "description": "The repository directory that includes the source files for the Pages site. Allowed paths are `/` or `/docs`. Default: `/`", "enum": [ "/", "/docs" ], "default": "/" } }, "required": [ "branch" ] } }, "required": [ "source" ] }, "example": { "source": { "branch": "main", "path": "/docs" } } } } }, "responses": { "201": { "description": "Response", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/page" }, "examples": { "default": { "$ref": "#/components/examples/page" } } } } }, "422": { "$ref": "#/components/responses/validation_failed" }, "409": { "$ref": "#/components/responses/conflict" } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": true, "category": "repos", "subcategory": "pages", "previews": [ { "required": true, "name": "switcheroo", "note": "Enabling and disabling Pages in the Pages API is currently available for developers to preview. See the [blog post](https://developer.github.com/changes/2019-03-14-enabling-disabling-pages/) preview for more details. To access the new endpoints during the preview period, you must provide a custom [media type](https://docs.github.com/enterprise-server@3.0/rest/overview/media-types) in the `Accept` header:\n```shell\napplication/vnd.github.switcheroo-preview+json\n```" } ] } }, "put": { "summary": "Update information about a GitHub Enterprise Server Pages site", "description": "Updates information for a GitHub Enterprise Server Pages site. For more information, see \"[About GitHub Pages](/github/working-with-github-pages/about-github-pages).", "tags": [ "repos" ], "operationId": "repos/update-information-about-pages-site", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/repos#update-information-about-a-github-pages-site" }, "parameters": [ { "$ref": "#/components/parameters/owner" }, { "$ref": "#/components/parameters/repo" } ], "requestBody": { "required": true, "content": { "application/json": { "schema": { "type": "object", "properties": { "cname": { "type": [ "string", "null" ], "description": "Specify a custom domain for the repository. Sending a `null` value will remove the custom domain. For more about custom domains, see \"[Using a custom domain with GitHub Pages](https://docs.github.com/articles/using-a-custom-domain-with-github-pages/).\"" }, "https_enforced": { "type": "boolean", "description": "Specify whether HTTPS should be enforced for the repository." }, "public": { "type": "boolean", "description": "Configures access controls for the GitHub Pages site. If public is set to `true`, the site is accessible to anyone on the internet. If set to `false`, the site will only be accessible to users who have at least `read` access to the repository that published the site. This includes anyone in your Enterprise if the repository is set to `internal` visibility. This feature is only available to repositories in an organization on an Enterprise plan." }, "source": { "anyOf": [ { "type": "string", "description": "Update the source for the repository. Must include the branch name, and may optionally specify the subdirectory `/docs`. Possible values are `\"gh-pages\"`, `\"master\"`, and `\"master /docs\"`.", "enum": [ "gh-pages", "master", "master /docs" ] }, { "type": "object", "description": "Update the source for the repository. Must include the branch name and path.", "properties": { "branch": { "type": "string", "description": "The repository branch used to publish your site's source files." }, "path": { "type": "string", "description": "The repository directory that includes the source files for the Pages site. Allowed paths are `/` or `/docs`.", "enum": [ "/", "/docs" ] } }, "required": [ "branch", "path" ] } ] } }, "anyOf": [ { "required": [ "source" ] }, { "required": [ "cname" ] }, { "required": [ "public" ] }, { "required": [ "https_enforced" ] } ] }, "example": { "cname": "octocatblog.com", "source": { "branch": "main", "path": "/" } } } } }, "responses": { "204": { "description": "Response" }, "422": { "$ref": "#/components/responses/validation_failed" }, "400": { "$ref": "#/components/responses/bad_request" } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": true, "category": "repos", "subcategory": "pages" } }, "delete": { "summary": "Delete a GitHub Enterprise Server Pages site", "description": "", "tags": [ "repos" ], "operationId": "repos/delete-pages-site", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/repos#delete-a-github-pages-site" }, "parameters": [ { "$ref": "#/components/parameters/owner" }, { "$ref": "#/components/parameters/repo" } ], "responses": { "204": { "description": "Response" }, "422": { "$ref": "#/components/responses/validation_failed" }, "404": { "$ref": "#/components/responses/not_found" } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": true, "category": "repos", "subcategory": "pages", "previews": [ { "required": true, "name": "switcheroo", "note": "Enabling and disabling Pages in the Pages API is currently available for developers to preview. See the [blog post](https://developer.github.com/changes/2019-03-14-enabling-disabling-pages/) preview for more details. To access the new endpoints during the preview period, you must provide a custom [media type](https://docs.github.com/enterprise-server@3.0/rest/overview/media-types) in the `Accept` header:\n```shell\napplication/vnd.github.switcheroo-preview+json\n```" } ] } } }, "/repos/{owner}/{repo}/pages/builds": { "get": { "summary": "List GitHub Enterprise Server Pages builds", "description": "", "tags": [ "repos" ], "operationId": "repos/list-pages-builds", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/repos#list-github-pages-builds" }, "parameters": [ { "$ref": "#/components/parameters/owner" }, { "$ref": "#/components/parameters/repo" }, { "$ref": "#/components/parameters/per-page" }, { "$ref": "#/components/parameters/page" } ], "responses": { "200": { "description": "Response", "content": { "application/json": { "schema": { "type": "array", "items": { "$ref": "#/components/schemas/page-build" } }, "examples": { "default": { "$ref": "#/components/examples/page-build-items" } } } }, "headers": { "Link": { "$ref": "#/components/headers/link" } } } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": true, "category": "repos", "subcategory": "pages" } }, "post": { "summary": "Request a GitHub Enterprise Server Pages build", "description": "You can request that your site be built from the latest revision on the default branch. This has the same effect as pushing a commit to your default branch, but does not require an additional commit. Manually triggering page builds can be helpful when diagnosing build warnings and failures.\n\nBuild requests are limited to one concurrent build per repository and one concurrent build per requester. If you request a build while another is still in progress, the second request will be queued until the first completes.", "tags": [ "repos" ], "operationId": "repos/request-pages-build", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/repos#request-a-github-pages-build" }, "parameters": [ { "$ref": "#/components/parameters/owner" }, { "$ref": "#/components/parameters/repo" } ], "responses": { "201": { "description": "Response", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/page-build-status" }, "examples": { "default": { "$ref": "#/components/examples/page-build-status" } } } } } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": true, "category": "repos", "subcategory": "pages" } } }, "/repos/{owner}/{repo}/pages/builds/latest": { "get": { "summary": "Get latest Pages build", "description": "", "tags": [ "repos" ], "operationId": "repos/get-latest-pages-build", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/repos#get-latest-pages-build" }, "parameters": [ { "$ref": "#/components/parameters/owner" }, { "$ref": "#/components/parameters/repo" } ], "responses": { "200": { "description": "Response", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/page-build" }, "examples": { "default": { "$ref": "#/components/examples/page-build" } } } } } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": true, "category": "repos", "subcategory": "pages" } } }, "/repos/{owner}/{repo}/pages/builds/{build_id}": { "get": { "summary": "Get GitHub Enterprise Server Pages build", "description": "", "tags": [ "repos" ], "operationId": "repos/get-pages-build", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/repos#get-github-pages-build" }, "parameters": [ { "$ref": "#/components/parameters/owner" }, { "$ref": "#/components/parameters/repo" }, { "name": "build_id", "in": "path", "required": true, "schema": { "type": "integer" } } ], "responses": { "200": { "description": "Response", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/page-build" }, "examples": { "default": { "$ref": "#/components/examples/page-build" } } } } } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": true, "category": "repos", "subcategory": "pages" } } }, "/repos/{owner}/{repo}/pre-receive-hooks": { "get": { "summary": "List pre-receive hooks for a repository", "description": "List all pre-receive hooks that are enabled or testing for this repository as well as any disabled hooks that are allowed to be enabled at the repository level. Pre-receive hooks that are disabled at a higher level and are not configurable will not be listed.", "operationId": "enterprise-admin/list-pre-receive-hooks-for-repo", "tags": [ "enterprise-admin" ], "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/enterprise-admin#list-pre-receive-hooks-for-a-repository" }, "parameters": [ { "$ref": "#/components/parameters/owner" }, { "$ref": "#/components/parameters/repo" }, { "$ref": "#/components/parameters/per-page" }, { "$ref": "#/components/parameters/page" }, { "$ref": "#/components/parameters/direction" }, { "name": "sort", "in": "query", "required": false, "schema": { "type": "string", "enum": [ "created", "updated", "name" ], "default": "created" } } ], "responses": { "200": { "description": "Response", "content": { "application/json": { "schema": { "type": "array", "items": { "$ref": "#/components/schemas/repository-pre-receive-hook" } }, "examples": { "default": { "$ref": "#/components/examples/repository-pre-receive-hook-items" } } } } } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": true, "category": "enterprise-admin", "subcategory": "repo-pre-receive-hooks", "previews": [ { "required": true, "name": "eye-scream", "note": "APIs for managing pre-receive hooks are currently available for developers to preview. During the preview period, the APIs may change without advance notice.\n\nTo access the API you must provide a custom [media type](/rest/overview/media-types) in the `Accept` header:\n\n```shell\napplication/vnd.github.eye-scream-preview\n```" } ] } } }, "/repos/{owner}/{repo}/pre-receive-hooks/{pre_receive_hook_id}": { "get": { "summary": "Get a pre-receive hook for a repository", "description": "", "operationId": "enterprise-admin/get-pre-receive-hook-for-repo", "tags": [ "enterprise-admin" ], "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/enterprise-admin#get-a-pre-receive-hook-for-a-repository" }, "parameters": [ { "$ref": "#/components/parameters/owner" }, { "$ref": "#/components/parameters/repo" }, { "$ref": "#/components/parameters/pre-receive-hook-id" } ], "responses": { "200": { "description": "Response", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/repository-pre-receive-hook" }, "examples": { "default": { "$ref": "#/components/examples/repository-pre-receive-hook" } } } } } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": true, "category": "enterprise-admin", "subcategory": "repo-pre-receive-hooks", "previews": [ { "required": true, "name": "eye-scream", "note": "APIs for managing pre-receive hooks are currently available for developers to preview. During the preview period, the APIs may change without advance notice.\n\nTo access the API you must provide a custom [media type](/rest/overview/media-types) in the `Accept` header:\n\n```shell\napplication/vnd.github.eye-scream-preview\n```" } ] } }, "patch": { "summary": "Update pre-receive hook enforcement for a repository", "description": "For pre-receive hooks which are allowed to be configured at the repo level, you can set `enforcement`", "operationId": "enterprise-admin/update-pre-receive-hook-enforcement-for-repo", "tags": [ "enterprise-admin" ], "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/enterprise-admin#update-pre-receive-hook-enforcement-for-a-repository" }, "parameters": [ { "$ref": "#/components/parameters/owner" }, { "$ref": "#/components/parameters/repo" }, { "$ref": "#/components/parameters/pre-receive-hook-id" } ], "responses": { "200": { "description": "Response", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/repository-pre-receive-hook" }, "examples": { "default": { "$ref": "#/components/examples/repository-pre-receive-hook-2" } } } } } }, "requestBody": { "content": { "application/json": { "schema": { "type": "object", "properties": { "enforcement": { "description": "The state of enforcement for the hook on this repository.", "type": "string", "enum": [ "enabled", "disabled", "testing" ] } } }, "example": { "enforcement": "enabled" } } } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": true, "category": "enterprise-admin", "subcategory": "repo-pre-receive-hooks", "previews": [ { "required": true, "name": "eye-scream", "note": "APIs for managing pre-receive hooks are currently available for developers to preview. During the preview period, the APIs may change without advance notice.\n\nTo access the API you must provide a custom [media type](/rest/overview/media-types) in the `Accept` header:\n\n```shell\napplication/vnd.github.eye-scream-preview\n```" } ] } }, "delete": { "summary": "Remove pre-receive hook enforcement for a repository", "description": "Deletes any overridden enforcement on this repository for the specified hook.\n\nResponds with effective values inherited from owner and/or global level.", "operationId": "enterprise-admin/remove-pre-receive-hook-enforcement-for-repo", "tags": [ "enterprise-admin" ], "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/enterprise-admin#remove-pre-receive-hook-enforcement-for-a-repository" }, "parameters": [ { "$ref": "#/components/parameters/owner" }, { "$ref": "#/components/parameters/repo" }, { "$ref": "#/components/parameters/pre-receive-hook-id" } ], "responses": { "200": { "description": "Responds with effective values inherited from owner and/or global level.", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/repository-pre-receive-hook" }, "examples": { "default": { "$ref": "#/components/examples/repository-pre-receive-hook" } } } } } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": true, "category": "enterprise-admin", "subcategory": "repo-pre-receive-hooks", "previews": [ { "required": true, "name": "eye-scream", "note": "APIs for managing pre-receive hooks are currently available for developers to preview. During the preview period, the APIs may change without advance notice.\n\nTo access the API you must provide a custom [media type](/rest/overview/media-types) in the `Accept` header:\n\n```shell\napplication/vnd.github.eye-scream-preview\n```" } ] } } }, "/repos/{owner}/{repo}/projects": { "get": { "summary": "List repository projects", "description": "Lists the projects in a repository. Returns a `404 Not Found` status if projects are disabled in the repository. If you do not have sufficient privileges to perform this action, a `401 Unauthorized` or `410 Gone` status is returned.", "tags": [ "projects" ], "operationId": "projects/list-for-repo", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/projects#list-repository-projects" }, "parameters": [ { "$ref": "#/components/parameters/owner" }, { "$ref": "#/components/parameters/repo" }, { "name": "state", "description": "Indicates the state of the projects to return. Can be either `open`, `closed`, or `all`.", "in": "query", "required": false, "schema": { "type": "string", "enum": [ "open", "closed", "all" ], "default": "open" } }, { "$ref": "#/components/parameters/per-page" }, { "$ref": "#/components/parameters/page" } ], "responses": { "200": { "description": "Response", "content": { "application/json": { "schema": { "type": "array", "items": { "$ref": "#/components/schemas/project" } }, "examples": { "default": { "$ref": "#/components/examples/project-items-2" } } } }, "headers": { "Link": { "$ref": "#/components/headers/link" } } }, "401": { "$ref": "#/components/responses/requires_authentication" }, "403": { "$ref": "#/components/responses/forbidden" }, "404": { "$ref": "#/components/responses/not_found" }, "410": { "$ref": "#/components/responses/gone" }, "422": { "$ref": "#/components/responses/validation_failed_simple" } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": true, "category": "projects", "previews": [ { "required": true, "name": "inertia", "note": "The Projects API is currently available for developers to preview. During the preview period, the API may change without advance notice. Please see the [blog post](https://developer.github.com/changes/2016-10-27-changes-to-projects-api) for full details. To access the API during the preview period, you must provide a custom [media type](https://docs.github.com/enterprise-server@3.0/rest/overview/media-types) in the `Accept` header:\n```shell\napplication/vnd.github.inertia-preview+json\n```" } ] } }, "post": { "summary": "Create a repository project", "description": "Creates a repository project board. Returns a `404 Not Found` status if projects are disabled in the repository. If you do not have sufficient privileges to perform this action, a `401 Unauthorized` or `410 Gone` status is returned.", "tags": [ "projects" ], "operationId": "projects/create-for-repo", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/projects#create-a-repository-project" }, "parameters": [ { "$ref": "#/components/parameters/owner" }, { "$ref": "#/components/parameters/repo" } ], "requestBody": { "required": true, "content": { "application/json": { "schema": { "type": "object", "properties": { "name": { "type": "string", "description": "The name of the project." }, "body": { "type": "string", "description": "The description of the project." } }, "required": [ "name" ] }, "example": { "name": "Projects Documentation", "body": "Developer documentation project for the developer site." } } } }, "responses": { "201": { "description": "Response", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/project" }, "examples": { "default": { "$ref": "#/components/examples/project-3" } } } } }, "401": { "$ref": "#/components/responses/requires_authentication" }, "403": { "$ref": "#/components/responses/forbidden" }, "404": { "$ref": "#/components/responses/not_found" }, "410": { "$ref": "#/components/responses/gone" }, "422": { "$ref": "#/components/responses/validation_failed_simple" } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": true, "category": "projects", "previews": [ { "required": true, "name": "inertia", "note": "The Projects API is currently available for developers to preview. During the preview period, the API may change without advance notice. Please see the [blog post](https://developer.github.com/changes/2016-10-27-changes-to-projects-api) for full details. To access the API during the preview period, you must provide a custom [media type](https://docs.github.com/enterprise-server@3.0/rest/overview/media-types) in the `Accept` header:\n```shell\napplication/vnd.github.inertia-preview+json\n```" } ] } } }, "/repos/{owner}/{repo}/pulls": { "get": { "summary": "List pull requests", "description": "Draft pull requests are available in public repositories with GitHub Free and GitHub Free for organizations, GitHub Pro, and legacy per-repository billing plans, and in public and private repositories with GitHub Team and GitHub Enterprise Cloud. For more information, see [GitHub's products](https://docs.github.com/github/getting-started-with-github/githubs-products) in the GitHub Help documentation.", "tags": [ "pulls" ], "operationId": "pulls/list", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/pulls#list-pull-requests" }, "parameters": [ { "$ref": "#/components/parameters/owner" }, { "$ref": "#/components/parameters/repo" }, { "name": "state", "description": "Either `open`, `closed`, or `all` to filter by state.", "in": "query", "required": false, "schema": { "type": "string", "enum": [ "open", "closed", "all" ], "default": "open" } }, { "name": "head", "description": "Filter pulls by head user or head organization and branch name in the format of `user:ref-name` or `organization:ref-name`. For example: `github:new-script-format` or `octocat:test-branch`.", "in": "query", "required": false, "schema": { "type": "string" } }, { "name": "base", "description": "Filter pulls by base branch name. Example: `gh-pages`.", "in": "query", "required": false, "schema": { "type": "string" } }, { "name": "sort", "description": "What to sort results by. Can be either `created`, `updated`, `popularity` (comment count) or `long-running` (age, filtering by pulls updated in the last month).", "in": "query", "required": false, "schema": { "type": "string", "enum": [ "created", "updated", "popularity", "long-running" ], "default": "created" } }, { "name": "direction", "description": "The direction of the sort. Can be either `asc` or `desc`. Default: `desc` when sort is `created` or sort is not specified, otherwise `asc`.", "in": "query", "required": false, "schema": { "type": "string", "enum": [ "asc", "desc" ] } }, { "$ref": "#/components/parameters/per-page" }, { "$ref": "#/components/parameters/page" } ], "responses": { "200": { "description": "Response", "content": { "application/json": { "schema": { "type": "array", "items": { "$ref": "#/components/schemas/pull-request-simple" } }, "examples": { "default": { "$ref": "#/components/examples/pull-request-simple-items" } } } }, "headers": { "Link": { "$ref": "#/components/headers/link" } } }, "304": { "$ref": "#/components/responses/not_modified" }, "422": { "$ref": "#/components/responses/validation_failed" } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": true, "category": "pulls", "subcategory": null } }, "post": { "summary": "Create a pull request", "description": "Draft pull requests are available in public repositories with GitHub Free and GitHub Free for organizations, GitHub Pro, and legacy per-repository billing plans, and in public and private repositories with GitHub Team and GitHub Enterprise Cloud. For more information, see [GitHub's products](https://docs.github.com/github/getting-started-with-github/githubs-products) in the GitHub Help documentation.\n\nTo open or update a pull request in a public repository, you must have write access to the head or the source branch. For organization-owned repositories, you must be a member of the organization that owns the repository to open or update a pull request.\n\nYou can create a new pull request.\n\nThis endpoint triggers [notifications](https://docs.github.com/en/github/managing-subscriptions-and-notifications-on-github/about-notifications). Creating content too quickly using this endpoint may result in secondary rate limiting. See \"[Secondary rate limits](https://docs.github.com/enterprise-server@3.0/rest/overview/resources-in-the-rest-api#secondary-rate-limits)\" and \"[Dealing with secondary rate limits](https://docs.github.com/enterprise-server@3.0/rest/guides/best-practices-for-integrators#dealing-with-rate-limits)\" for details.", "tags": [ "pulls" ], "operationId": "pulls/create", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/pulls#create-a-pull-request" }, "parameters": [ { "$ref": "#/components/parameters/owner" }, { "$ref": "#/components/parameters/repo" } ], "requestBody": { "required": true, "content": { "application/json": { "schema": { "type": "object", "properties": { "title": { "type": "string", "description": "The title of the new pull request." }, "head": { "type": "string", "description": "The name of the branch where your changes are implemented. For cross-repository pull requests in the same network, namespace `head` with a user like this: `username:branch`." }, "base": { "type": "string", "description": "The name of the branch you want the changes pulled into. This should be an existing branch on the current repository. You cannot submit a pull request to one repository that requests a merge to a base of another repository." }, "body": { "type": "string", "description": "The contents of the pull request." }, "maintainer_can_modify": { "type": "boolean", "description": "Indicates whether [maintainers can modify](https://docs.github.com/articles/allowing-changes-to-a-pull-request-branch-created-from-a-fork/) the pull request." }, "draft": { "type": "boolean", "description": "Indicates whether the pull request is a draft. See \"[Draft Pull Requests](https://docs.github.com/en/articles/about-pull-requests#draft-pull-requests)\" in the GitHub Help documentation to learn more." }, "issue": { "type": "integer", "examples": [ 1 ] } }, "required": [ "head", "base" ] }, "example": { "title": "Amazing new feature", "body": "Please pull these awesome changes in!", "head": "octocat:new-feature", "base": "master" } } } }, "responses": { "201": { "description": "Response", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/pull-request" }, "examples": { "default": { "$ref": "#/components/examples/pull-request" } } } }, "headers": { "Location": { "example": "https://api.github.com/repos/octocat/Hello-World/pulls/1347", "schema": { "type": "string" } } } }, "403": { "$ref": "#/components/responses/forbidden" }, "422": { "$ref": "#/components/responses/validation_failed" } }, "x-github": { "triggersNotification": true, "githubCloudOnly": false, "enabledForGitHubApps": true, "category": "pulls", "subcategory": null } } }, "/repos/{owner}/{repo}/pulls/comments": { "get": { "summary": "List review comments in a repository", "description": "Lists review comments for all pull requests in a repository. By default, review comments are in ascending order by ID.", "tags": [ "pulls" ], "operationId": "pulls/list-review-comments-for-repo", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/pulls#list-review-comments-in-a-repository" }, "parameters": [ { "$ref": "#/components/parameters/owner" }, { "$ref": "#/components/parameters/repo" }, { "name": "sort", "in": "query", "required": false, "schema": { "type": "string", "enum": [ "created", "updated", "created_at" ] } }, { "name": "direction", "description": "Can be either `asc` or `desc`. Ignored without `sort` parameter.", "in": "query", "required": false, "schema": { "type": "string", "enum": [ "asc", "desc" ] } }, { "$ref": "#/components/parameters/since" }, { "$ref": "#/components/parameters/per-page" }, { "$ref": "#/components/parameters/page" } ], "responses": { "200": { "description": "Response", "content": { "application/json": { "schema": { "type": "array", "items": { "$ref": "#/components/schemas/pull-request-review-comment" } }, "examples": { "default": { "$ref": "#/components/examples/pull-request-review-comment-items" } } } }, "headers": { "Link": { "$ref": "#/components/headers/link" } } } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": true, "category": "pulls", "subcategory": "comments", "previews": [ { "required": false, "name": "squirrel-girl", "note": "An additional `reactions` object in the issue comment payload is currently available for developers to preview. During the preview period, the APIs may change without advance notice. Please see the [blog post](https://developer.github.com/changes/2016-05-12-reactions-api-preview) for full details.\n\nTo access the API you must provide a custom [media type](https://docs.github.com/enterprise-server@3.0/rest/overview/media-types) in the `Accept` header:\n```shell\napplication/vnd.github.squirrel-girl-preview\n```\nThe `reactions` key will have the following payload where `url` can be used to construct the API location for [listing and creating](https://docs.github.com/enterprise-server@3.0/rest/reference/reactions) reactions." }, { "required": false, "name": "comfort-fade", "note": "Multi-line comments in a pull request diff is currently available for developers to preview. During the preview period, these response fields may change without advance notice. See the [blog post](https://developer.github.com/changes/2019-10-03-multi-line-comments) for more information.\n\nTo create multi-line comments or see multi-line comments with the new supported fields during the preview period, you must provide a custom [media type](https://docs.github.com/enterprise-server@3.0/rest/overview/media-types) in the `Accept` header:\n```shell\napplication/vnd.github.comfort-fade-preview+json\n```\n\nTo show multi-line comment-supported fields in the response, use the `comfort-fade` preview header and the `line` parameter.\n\nIf you use the `comfort-fade` preview header, your response will show:\n\n* For multi-line comments, values for `start_line`, `original_start_line`, `start_side`, `line`, `original_line`, and `side`.\n* For single-line comments, values for `line`, `original_line`, and `side` and a `null` value for `start_line`, `original_start_line`, and `start_side`.\n\nIf you don't use the `comfort-fade` preview header, multi-line and single-line comments will appear the same way in the response with a single `position` attribute. Your response will show:\n\n* For multi-line comments, the last line of the comment range for the `position` attribute.\n* For single-line comments, the diff-positioned way of referencing comments for the `position` attribute." } ] } } }, "/repos/{owner}/{repo}/pulls/comments/{comment_id}": { "get": { "summary": "Get a review comment for a pull request", "description": "Provides details for a review comment.", "tags": [ "pulls" ], "operationId": "pulls/get-review-comment", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/pulls#get-a-review-comment-for-a-pull-request" }, "parameters": [ { "$ref": "#/components/parameters/owner" }, { "$ref": "#/components/parameters/repo" }, { "$ref": "#/components/parameters/comment-id" } ], "responses": { "200": { "description": "Response", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/pull-request-review-comment" }, "examples": { "default": { "$ref": "#/components/examples/pull-request-review-comment-2" } } } } }, "404": { "$ref": "#/components/responses/not_found" } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": true, "category": "pulls", "subcategory": "comments", "previews": [ { "required": false, "name": "squirrel-girl", "note": "An additional `reactions` object in the issue comment payload is currently available for developers to preview. During the preview period, the APIs may change without advance notice. Please see the [blog post](https://developer.github.com/changes/2016-05-12-reactions-api-preview) for full details.\n\nTo access the API you must provide a custom [media type](https://docs.github.com/enterprise-server@3.0/rest/overview/media-types) in the `Accept` header:\n```shell\napplication/vnd.github.squirrel-girl-preview\n```\nThe `reactions` key will have the following payload where `url` can be used to construct the API location for [listing and creating](https://docs.github.com/enterprise-server@3.0/rest/reference/reactions) reactions." }, { "required": false, "name": "comfort-fade", "note": "Multi-line comments in a pull request diff is currently available for developers to preview. During the preview period, these response fields may change without advance notice. See the [blog post](https://developer.github.com/changes/2019-10-03-multi-line-comments) for more information.\n\nTo create multi-line comments or see multi-line comments with the new supported fields during the preview period, you must provide a custom [media type](https://docs.github.com/enterprise-server@3.0/rest/overview/media-types) in the `Accept` header:\n```shell\napplication/vnd.github.comfort-fade-preview+json\n```\n\nTo show multi-line comment-supported fields in the response, use the `comfort-fade` preview header and the `line` parameter.\n\nIf you use the `comfort-fade` preview header, your response will show:\n\n* For multi-line comments, values for `start_line`, `original_start_line`, `start_side`, `line`, `original_line`, and `side`.\n* For single-line comments, values for `line`, `original_line`, and `side` and a `null` value for `start_line`, `original_start_line`, and `start_side`.\n\nIf you don't use the `comfort-fade` preview header, multi-line and single-line comments will appear the same way in the response with a single `position` attribute. Your response will show:\n\n* For multi-line comments, the last line of the comment range for the `position` attribute.\n* For single-line comments, the diff-positioned way of referencing comments for the `position` attribute." } ] } }, "patch": { "summary": "Update a review comment for a pull request", "description": "Enables you to edit a review comment.", "tags": [ "pulls" ], "operationId": "pulls/update-review-comment", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/pulls#update-a-review-comment-for-a-pull-request" }, "parameters": [ { "$ref": "#/components/parameters/owner" }, { "$ref": "#/components/parameters/repo" }, { "$ref": "#/components/parameters/comment-id" } ], "requestBody": { "required": true, "content": { "application/json": { "schema": { "type": "object", "properties": { "body": { "type": "string", "description": "The text of the reply to the review comment." } }, "required": [ "body" ] }, "example": { "body": "I like this too!" } } } }, "responses": { "200": { "description": "Response", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/pull-request-review-comment" }, "examples": { "default": { "$ref": "#/components/examples/pull-request-review-comment-2" } } } } } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": true, "category": "pulls", "subcategory": "comments", "previews": [ { "required": false, "name": "comfort-fade", "note": "Multi-line comments in a pull request diff is currently available for developers to preview. During the preview period, these response fields may change without advance notice. See the [blog post](https://developer.github.com/changes/2019-10-03-multi-line-comments) for more information.\n\nTo create multi-line comments or see multi-line comments with the new supported fields during the preview period, you must provide a custom [media type](https://docs.github.com/enterprise-server@3.0/rest/overview/media-types) in the `Accept` header:\n```shell\napplication/vnd.github.comfort-fade-preview+json\n```\n\nTo show multi-line comment-supported fields in the response, use the `comfort-fade` preview header and the `line` parameter.\n\nIf you use the `comfort-fade` preview header, your response will show:\n\n* For multi-line comments, values for `start_line`, `original_start_line`, `start_side`, `line`, `original_line`, and `side`.\n* For single-line comments, values for `line`, `original_line`, and `side` and a `null` value for `start_line`, `original_start_line`, and `start_side`.\n\nIf you don't use the `comfort-fade` preview header, multi-line and single-line comments will appear the same way in the response with a single `position` attribute. Your response will show:\n\n* For multi-line comments, the last line of the comment range for the `position` attribute.\n* For single-line comments, the diff-positioned way of referencing comments for the `position` attribute." } ] } }, "delete": { "summary": "Delete a review comment for a pull request", "description": "Deletes a review comment.", "tags": [ "pulls" ], "operationId": "pulls/delete-review-comment", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/pulls#delete-a-review-comment-for-a-pull-request" }, "parameters": [ { "$ref": "#/components/parameters/owner" }, { "$ref": "#/components/parameters/repo" }, { "$ref": "#/components/parameters/comment-id" } ], "responses": { "204": { "description": "Response" }, "404": { "$ref": "#/components/responses/not_found" } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": true, "category": "pulls", "subcategory": "comments" } } }, "/repos/{owner}/{repo}/pulls/comments/{comment_id}/reactions": { "get": { "summary": "List reactions for a pull request review comment", "description": "List the reactions to a [pull request review comment](https://docs.github.com/enterprise-server@3.0/rest/reference/pulls#review-comments).", "tags": [ "reactions" ], "operationId": "reactions/list-for-pull-request-review-comment", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/reactions#list-reactions-for-a-pull-request-review-comment" }, "parameters": [ { "$ref": "#/components/parameters/owner" }, { "$ref": "#/components/parameters/repo" }, { "$ref": "#/components/parameters/comment-id" }, { "name": "content", "description": "Returns a single [reaction type](https://docs.github.com/enterprise-server@3.0/rest/reference/reactions#reaction-types). Omit this parameter to list all reactions to a pull request review comment.", "in": "query", "required": false, "schema": { "type": "string", "enum": [ "+1", "-1", "laugh", "confused", "heart", "hooray", "rocket", "eyes" ] } }, { "$ref": "#/components/parameters/per-page" }, { "$ref": "#/components/parameters/page" } ], "responses": { "200": { "description": "Response", "content": { "application/json": { "schema": { "type": "array", "items": { "$ref": "#/components/schemas/reaction" } }, "examples": { "default": { "$ref": "#/components/examples/reaction-items" } } } }, "headers": { "Link": { "$ref": "#/components/headers/link" } } }, "404": { "$ref": "#/components/responses/not_found" } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": true, "category": "reactions", "previews": [ { "required": true, "name": "squirrel-girl", "note": "An additional `reactions` object in the issue comment payload is currently available for developers to preview. During the preview period, the APIs may change without advance notice. Please see the [blog post](https://developer.github.com/changes/2016-05-12-reactions-api-preview) for full details.\n\nTo access the API you must provide a custom [media type](https://docs.github.com/enterprise-server@3.0/rest/overview/media-types) in the `Accept` header:\n```shell\napplication/vnd.github.squirrel-girl-preview\n```\nThe `reactions` key will have the following payload where `url` can be used to construct the API location for [listing and creating](https://docs.github.com/enterprise-server@3.0/rest/reference/reactions) reactions." } ] } }, "post": { "summary": "Create reaction for a pull request review comment", "description": "Create a reaction to a [pull request review comment](https://docs.github.com/enterprise-server@3.0/rest/reference/pulls#comments). A response with an HTTP `200` status means that you already added the reaction type to this pull request review comment.", "tags": [ "reactions" ], "operationId": "reactions/create-for-pull-request-review-comment", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/reactions#create-reaction-for-a-pull-request-review-comment" }, "parameters": [ { "$ref": "#/components/parameters/owner" }, { "$ref": "#/components/parameters/repo" }, { "$ref": "#/components/parameters/comment-id" } ], "requestBody": { "required": true, "content": { "application/json": { "schema": { "type": "object", "properties": { "content": { "type": "string", "description": "The [reaction type](https://docs.github.com/enterprise-server@3.0/rest/reference/reactions#reaction-types) to add to the pull request review comment.", "enum": [ "+1", "-1", "laugh", "confused", "heart", "hooray", "rocket", "eyes" ] } }, "required": [ "content" ] }, "example": { "content": "heart" } } } }, "responses": { "200": { "description": "Reaction exists", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/reaction" }, "examples": { "default": { "$ref": "#/components/examples/reaction" } } } } }, "201": { "description": "Reaction created", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/reaction" }, "examples": { "default": { "$ref": "#/components/examples/reaction" } } } } }, "422": { "$ref": "#/components/responses/validation_failed" } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": true, "category": "reactions", "previews": [ { "required": true, "name": "squirrel-girl", "note": "An additional `reactions` object in the issue comment payload is currently available for developers to preview. During the preview period, the APIs may change without advance notice. Please see the [blog post](https://developer.github.com/changes/2016-05-12-reactions-api-preview) for full details.\n\nTo access the API you must provide a custom [media type](https://docs.github.com/enterprise-server@3.0/rest/overview/media-types) in the `Accept` header:\n```shell\napplication/vnd.github.squirrel-girl-preview\n```\nThe `reactions` key will have the following payload where `url` can be used to construct the API location for [listing and creating](https://docs.github.com/enterprise-server@3.0/rest/reference/reactions) reactions." } ] } } }, "/repos/{owner}/{repo}/pulls/comments/{comment_id}/reactions/{reaction_id}": { "delete": { "summary": "Delete a pull request comment reaction", "description": "**Note:** You can also specify a repository by `repository_id` using the route `DELETE /repositories/:repository_id/pulls/comments/:comment_id/reactions/:reaction_id.`\n\nDelete a reaction to a [pull request review comment](https://docs.github.com/enterprise-server@3.0/rest/reference/pulls#review-comments).", "tags": [ "reactions" ], "operationId": "reactions/delete-for-pull-request-comment", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/reactions#delete-a-pull-request-comment-reaction" }, "parameters": [ { "$ref": "#/components/parameters/owner" }, { "$ref": "#/components/parameters/repo" }, { "$ref": "#/components/parameters/comment-id" }, { "$ref": "#/components/parameters/reaction-id" } ], "responses": { "204": { "description": "Response" } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": true, "category": "reactions", "previews": [ { "required": true, "name": "squirrel-girl", "note": "An additional `reactions` object in the issue comment payload is currently available for developers to preview. During the preview period, the APIs may change without advance notice. Please see the [blog post](https://developer.github.com/changes/2016-05-12-reactions-api-preview) for full details.\n\nTo access the API you must provide a custom [media type](https://docs.github.com/enterprise-server@3.0/rest/overview/media-types) in the `Accept` header:\n```shell\napplication/vnd.github.squirrel-girl-preview\n```\nThe `reactions` key will have the following payload where `url` can be used to construct the API location for [listing and creating](https://docs.github.com/enterprise-server@3.0/rest/reference/reactions) reactions." } ] } } }, "/repos/{owner}/{repo}/pulls/{pull_number}": { "get": { "summary": "Get a pull request", "description": "Draft pull requests are available in public repositories with GitHub Free and GitHub Free for organizations, GitHub Pro, and legacy per-repository billing plans, and in public and private repositories with GitHub Team and GitHub Enterprise Cloud. For more information, see [GitHub's products](https://docs.github.com/github/getting-started-with-github/githubs-products) in the GitHub Help documentation.\n\nLists details of a pull request by providing its number.\n\nWhen you get, [create](https://docs.github.com/enterprise-server@3.0/rest/reference/pulls/#create-a-pull-request), or [edit](https://docs.github.com/enterprise-server@3.0/rest/reference/pulls#update-a-pull-request) a pull request, GitHub Enterprise Server creates a merge commit to test whether the pull request can be automatically merged into the base branch. This test commit is not added to the base branch or the head branch. You can review the status of the test commit using the `mergeable` key. For more information, see \"[Checking mergeability of pull requests](https://docs.github.com/enterprise-server@3.0/rest/guides/getting-started-with-the-git-database-api#checking-mergeability-of-pull-requests)\".\n\nThe value of the `mergeable` attribute can be `true`, `false`, or `null`. If the value is `null`, then GitHub Enterprise Server has started a background job to compute the mergeability. After giving the job time to complete, resubmit the request. When the job finishes, you will see a non-`null` value for the `mergeable` attribute in the response. If `mergeable` is `true`, then `merge_commit_sha` will be the SHA of the _test_ merge commit.\n\nThe value of the `merge_commit_sha` attribute changes depending on the state of the pull request. Before merging a pull request, the `merge_commit_sha` attribute holds the SHA of the _test_ merge commit. After merging a pull request, the `merge_commit_sha` attribute changes depending on how you merged the pull request:\n\n* If merged as a [merge commit](https://docs.github.com/articles/about-merge-methods-on-github/), `merge_commit_sha` represents the SHA of the merge commit.\n* If merged via a [squash](https://docs.github.com/articles/about-merge-methods-on-github/#squashing-your-merge-commits), `merge_commit_sha` represents the SHA of the squashed commit on the base branch.\n* If [rebased](https://docs.github.com/articles/about-merge-methods-on-github/#rebasing-and-merging-your-commits), `merge_commit_sha` represents the commit that the base branch was updated to.\n\nPass the appropriate [media type](https://docs.github.com/enterprise-server@3.0/rest/overview/media-types/#commits-commit-comparison-and-pull-requests) to fetch diff and patch formats.", "tags": [ "pulls" ], "operationId": "pulls/get", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/pulls#get-a-pull-request" }, "parameters": [ { "$ref": "#/components/parameters/owner" }, { "$ref": "#/components/parameters/repo" }, { "$ref": "#/components/parameters/pull-number" } ], "responses": { "200": { "description": "Pass the appropriate [media type](https://docs.github.com/enterprise-server@3.0/rest/overview/media-types/#commits-commit-comparison-and-pull-requests) to fetch diff and patch formats.", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/pull-request" }, "examples": { "default": { "$ref": "#/components/examples/pull-request" } } } } }, "304": { "$ref": "#/components/responses/not_modified" }, "500": { "$ref": "#/components/responses/internal_error" }, "404": { "$ref": "#/components/responses/not_found" } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": true, "category": "pulls", "subcategory": null } }, "patch": { "summary": "Update a pull request", "description": "Draft pull requests are available in public repositories with GitHub Free and GitHub Free for organizations, GitHub Pro, and legacy per-repository billing plans, and in public and private repositories with GitHub Team and GitHub Enterprise Cloud. For more information, see [GitHub's products](https://docs.github.com/github/getting-started-with-github/githubs-products) in the GitHub Help documentation.\n\nTo open or update a pull request in a public repository, you must have write access to the head or the source branch. For organization-owned repositories, you must be a member of the organization that owns the repository to open or update a pull request.", "tags": [ "pulls" ], "operationId": "pulls/update", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/pulls/#update-a-pull-request" }, "parameters": [ { "$ref": "#/components/parameters/owner" }, { "$ref": "#/components/parameters/repo" }, { "$ref": "#/components/parameters/pull-number" } ], "requestBody": { "required": false, "content": { "application/json": { "schema": { "type": "object", "properties": { "title": { "type": "string", "description": "The title of the pull request." }, "body": { "type": "string", "description": "The contents of the pull request." }, "state": { "type": "string", "description": "State of this Pull Request. Either `open` or `closed`.", "enum": [ "open", "closed" ] }, "base": { "type": "string", "description": "The name of the branch you want your changes pulled into. This should be an existing branch on the current repository. You cannot update the base branch on a pull request to point to another repository." }, "maintainer_can_modify": { "type": "boolean", "description": "Indicates whether [maintainers can modify](https://docs.github.com/articles/allowing-changes-to-a-pull-request-branch-created-from-a-fork/) the pull request." } } }, "example": { "title": "new title", "body": "updated body", "state": "open", "base": "master" } } } }, "responses": { "200": { "description": "Response", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/pull-request" }, "examples": { "default": { "$ref": "#/components/examples/pull-request" } } } } }, "422": { "$ref": "#/components/responses/validation_failed" }, "403": { "$ref": "#/components/responses/forbidden" } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": true, "category": "pulls", "subcategory": null } } }, "/repos/{owner}/{repo}/pulls/{pull_number}/comments": { "get": { "summary": "List review comments on a pull request", "description": "Lists all review comments for a pull request. By default, review comments are in ascending order by ID.", "tags": [ "pulls" ], "operationId": "pulls/list-review-comments", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/pulls#list-review-comments-on-a-pull-request" }, "parameters": [ { "$ref": "#/components/parameters/owner" }, { "$ref": "#/components/parameters/repo" }, { "$ref": "#/components/parameters/pull-number" }, { "$ref": "#/components/parameters/sort" }, { "name": "direction", "description": "Can be either `asc` or `desc`. Ignored without `sort` parameter.", "in": "query", "required": false, "schema": { "type": "string", "enum": [ "asc", "desc" ] } }, { "$ref": "#/components/parameters/since" }, { "$ref": "#/components/parameters/per-page" }, { "$ref": "#/components/parameters/page" } ], "responses": { "200": { "description": "Response", "content": { "application/json": { "schema": { "type": "array", "items": { "$ref": "#/components/schemas/pull-request-review-comment" } }, "examples": { "default": { "$ref": "#/components/examples/pull-request-review-comment-items" } } } }, "headers": { "Link": { "$ref": "#/components/headers/link" } } } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": true, "category": "pulls", "subcategory": "comments", "previews": [ { "required": false, "name": "squirrel-girl", "note": "An additional `reactions` object in the issue comment payload is currently available for developers to preview. During the preview period, the APIs may change without advance notice. Please see the [blog post](https://developer.github.com/changes/2016-05-12-reactions-api-preview) for full details.\n\nTo access the API you must provide a custom [media type](https://docs.github.com/enterprise-server@3.0/rest/overview/media-types) in the `Accept` header:\n```shell\napplication/vnd.github.squirrel-girl-preview\n```\nThe `reactions` key will have the following payload where `url` can be used to construct the API location for [listing and creating](https://docs.github.com/enterprise-server@3.0/rest/reference/reactions) reactions." }, { "required": false, "name": "comfort-fade", "note": "Multi-line comments in a pull request diff is currently available for developers to preview. During the preview period, these response fields may change without advance notice. See the [blog post](https://developer.github.com/changes/2019-10-03-multi-line-comments) for more information.\n\nTo create multi-line comments or see multi-line comments with the new supported fields during the preview period, you must provide a custom [media type](https://docs.github.com/enterprise-server@3.0/rest/overview/media-types) in the `Accept` header:\n```shell\napplication/vnd.github.comfort-fade-preview+json\n```\n\nTo show multi-line comment-supported fields in the response, use the `comfort-fade` preview header and the `line` parameter.\n\nIf you use the `comfort-fade` preview header, your response will show:\n\n* For multi-line comments, values for `start_line`, `original_start_line`, `start_side`, `line`, `original_line`, and `side`.\n* For single-line comments, values for `line`, `original_line`, and `side` and a `null` value for `start_line`, `original_start_line`, and `start_side`.\n\nIf you don't use the `comfort-fade` preview header, multi-line and single-line comments will appear the same way in the response with a single `position` attribute. Your response will show:\n\n* For multi-line comments, the last line of the comment range for the `position` attribute.\n* For single-line comments, the diff-positioned way of referencing comments for the `position` attribute." } ] } }, "post": { "summary": "Create a review comment for a pull request", "description": "\nCreates a review comment in the pull request diff. To add a regular comment to a pull request timeline, see \"[Create an issue comment](https://docs.github.com/enterprise-server@3.0/rest/reference/issues#create-an-issue-comment).\" We recommend creating a review comment using `line`, `side`, and optionally `start_line` and `start_side` if your comment applies to more than one line in the pull request diff.\n\nYou can still create a review comment using the `position` parameter. When you use `position`, the `line`, `side`, `start_line`, and `start_side` parameters are not required. For more information, see the [`comfort-fade` preview notice](https://docs.github.com/enterprise-server@3.0/rest/reference/pulls#create-a-review-comment-for-a-pull-request-preview-notices).\n\n**Note:** The position value equals the number of lines down from the first \"@@\" hunk header in the file you want to add a comment. The line just below the \"@@\" line is position 1, the next line is position 2, and so on. The position in the diff continues to increase through lines of whitespace and additional hunks until the beginning of a new file.\n\nThis endpoint triggers [notifications](https://docs.github.com/en/github/managing-subscriptions-and-notifications-on-github/about-notifications). Creating content too quickly using this endpoint may result in secondary rate limiting. See \"[Secondary rate limits](https://docs.github.com/enterprise-server@3.0/rest/overview/resources-in-the-rest-api#secondary-rate-limits)\" and \"[Dealing with secondary rate limits](https://docs.github.com/enterprise-server@3.0/rest/guides/best-practices-for-integrators#dealing-with-secondary-rate-limits)\" for details.", "tags": [ "pulls" ], "operationId": "pulls/create-review-comment", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/pulls#create-a-review-comment-for-a-pull-request" }, "parameters": [ { "$ref": "#/components/parameters/owner" }, { "$ref": "#/components/parameters/repo" }, { "$ref": "#/components/parameters/pull-number" } ], "requestBody": { "required": true, "content": { "application/json": { "schema": { "type": "object", "properties": { "body": { "type": "string", "description": "The text of the review comment." }, "commit_id": { "type": "string", "description": "The SHA of the commit needing a comment. Not using the latest commit SHA may render your comment outdated if a subsequent commit modifies the line you specify as the `position`." }, "path": { "type": "string", "description": "The relative path to the file that necessitates a comment." }, "position": { "type": "integer", "description": "**Required without `comfort-fade` preview**. The position in the diff where you want to add a review comment. Note this value is not the same as the line number in the file. For help finding the position value, read the note above." }, "side": { "type": "string", "description": "**Required with `comfort-fade` preview**. In a split diff view, the side of the diff that the pull request's changes appear on. Can be `LEFT` or `RIGHT`. Use `LEFT` for deletions that appear in red. Use `RIGHT` for additions that appear in green or unchanged lines that appear in white and are shown for context. For a multi-line comment, side represents whether the last line of the comment range is a deletion or addition. For more information, see \"[Diff view options](https://docs.github.com/en/articles/about-comparing-branches-in-pull-requests#diff-view-options)\" in the GitHub Help documentation.", "enum": [ "LEFT", "RIGHT" ] }, "line": { "type": "integer", "description": "**Required with `comfort-fade` preview**. The line of the blob in the pull request diff that the comment applies to. For a multi-line comment, the last line of the range that your comment applies to." }, "start_line": { "type": "integer", "description": "**Required when using multi-line comments**. To create multi-line comments, you must use the `comfort-fade` preview header. The `start_line` is the first line in the pull request diff that your multi-line comment applies to. To learn more about multi-line comments, see \"[Commenting on a pull request](https://docs.github.com/en/articles/commenting-on-a-pull-request#adding-line-comments-to-a-pull-request)\" in the GitHub Help documentation." }, "start_side": { "type": "string", "description": "**Required when using multi-line comments**. To create multi-line comments, you must use the `comfort-fade` preview header. The `start_side` is the starting side of the diff that the comment applies to. Can be `LEFT` or `RIGHT`. To learn more about multi-line comments, see \"[Commenting on a pull request](https://docs.github.com/en/articles/commenting-on-a-pull-request#adding-line-comments-to-a-pull-request)\" in the GitHub Help documentation. See `side` in this table for additional context.", "enum": [ "LEFT", "RIGHT", "side" ] }, "in_reply_to": { "type": "integer", "description": "The ID of the review comment to reply to. To find the ID of a review comment with [\"List review comments on a pull request\"](#list-review-comments-on-a-pull-request). When specified, all parameters other than `body` in the request body are ignored.", "examples": [ 2 ] } }, "required": [ "body" ] }, "examples": { "example-for-a-single-line-comment": { "summary": "Example for a single-line comment", "value": { "body": "Let's add this deleted line back.", "commit_id": "6dcb09b5b57875f334f61aebed695e2e4193db5e", "path": "file1.txt", "line": 5, "side": "LEFT" } }, "example-for-a-multi-line-comment": { "summary": "Example for a multi-line comment", "value": { "body": "Great stuff!", "commit_id": "6dcb09b5b57875f334f61aebed695e2e4193db5e", "path": "file1.txt", "start_line": 1, "start_side": "RIGHT", "line": 2, "side": "RIGHT" } } } } } }, "responses": { "201": { "description": "Response", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/pull-request-review-comment" }, "examples": { "example-for-a-multi-line-comment": { "$ref": "#/components/examples/pull-request-review-comment-example-for-a-multi-line-comment" } } } }, "headers": { "Location": { "example": "https://api.github.com/repos/octocat/Hello-World/pulls/comments/1", "schema": { "type": "string" } } } }, "422": { "$ref": "#/components/responses/validation_failed" }, "403": { "$ref": "#/components/responses/forbidden" } }, "x-github": { "triggersNotification": true, "githubCloudOnly": false, "enabledForGitHubApps": true, "category": "pulls", "subcategory": "comments", "previews": [ { "required": false, "name": "comfort-fade", "note": "Multi-line comments in a pull request diff is currently available for developers to preview. During the preview period, these response fields may change without advance notice. See the [blog post](https://developer.github.com/changes/2019-10-03-multi-line-comments) for more information.\n\nTo create multi-line comments or see multi-line comments with the new supported fields during the preview period, you must provide a custom [media type](https://docs.github.com/enterprise-server@3.0/rest/overview/media-types) in the `Accept` header:\n```shell\napplication/vnd.github.comfort-fade-preview+json\n```\n\nTo show multi-line comment-supported fields in the response, use the `comfort-fade` preview header and the `line` parameter.\n\nIf you use the `comfort-fade` preview header, your response will show:\n\n* For multi-line comments, values for `start_line`, `original_start_line`, `start_side`, `line`, `original_line`, and `side`.\n* For single-line comments, values for `line`, `original_line`, and `side` and a `null` value for `start_line`, `original_start_line`, and `start_side`.\n\nIf you don't use the `comfort-fade` preview header, multi-line and single-line comments will appear the same way in the response with a single `position` attribute. Your response will show:\n\n* For multi-line comments, the last line of the comment range for the `position` attribute.\n* For single-line comments, the diff-positioned way of referencing comments for the `position` attribute." } ] } } }, "/repos/{owner}/{repo}/pulls/{pull_number}/comments/{comment_id}/replies": { "post": { "summary": "Create a reply for a review comment", "description": "Creates a reply to a review comment for a pull request. For the `comment_id`, provide the ID of the review comment you are replying to. This must be the ID of a _top-level review comment_, not a reply to that comment. Replies to replies are not supported.\n\nThis endpoint triggers [notifications](https://docs.github.com/en/github/managing-subscriptions-and-notifications-on-github/about-notifications). Creating content too quickly using this endpoint may result in secondary rate limiting. See \"[Secondary rate limits](https://docs.github.com/enterprise-server@3.0/rest/overview/resources-in-the-rest-api#secondary-rate-limits)\" and \"[Dealing with secondary rate limits](https://docs.github.com/enterprise-server@3.0/rest/guides/best-practices-for-integrators#dealing-with-secondary-rate-limits)\" for details.", "tags": [ "pulls" ], "operationId": "pulls/create-reply-for-review-comment", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/pulls#create-a-reply-for-a-review-comment" }, "parameters": [ { "$ref": "#/components/parameters/owner" }, { "$ref": "#/components/parameters/repo" }, { "$ref": "#/components/parameters/pull-number" }, { "$ref": "#/components/parameters/comment-id" } ], "requestBody": { "required": true, "content": { "application/json": { "schema": { "type": "object", "properties": { "body": { "type": "string", "description": "The text of the review comment." } }, "required": [ "body" ] }, "example": { "body": "Great stuff!" } } } }, "responses": { "201": { "description": "Response", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/pull-request-review-comment" }, "examples": { "default": { "$ref": "#/components/examples/pull-request-review-comment" } } } }, "headers": { "Location": { "example": "https://api.github.com/repos/octocat/Hello-World/pulls/comments/1", "schema": { "type": "string" } } } }, "404": { "$ref": "#/components/responses/not_found" } }, "x-github": { "triggersNotification": true, "githubCloudOnly": false, "enabledForGitHubApps": false, "category": "pulls", "subcategory": "comments" } } }, "/repos/{owner}/{repo}/pulls/{pull_number}/commits": { "get": { "summary": "List commits on a pull request", "description": "Lists a maximum of 250 commits for a pull request. To receive a complete commit list for pull requests with more than 250 commits, use the [List commits](https://docs.github.com/enterprise-server@3.0/rest/reference/repos#list-commits) endpoint.", "tags": [ "pulls" ], "operationId": "pulls/list-commits", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/pulls#list-commits-on-a-pull-request" }, "parameters": [ { "$ref": "#/components/parameters/owner" }, { "$ref": "#/components/parameters/repo" }, { "$ref": "#/components/parameters/pull-number" }, { "$ref": "#/components/parameters/per-page" }, { "$ref": "#/components/parameters/page" } ], "responses": { "200": { "description": "Response", "content": { "application/json": { "schema": { "type": "array", "items": { "$ref": "#/components/schemas/commit" } }, "examples": { "default": { "$ref": "#/components/examples/commit-items" } } } }, "headers": { "Link": { "$ref": "#/components/headers/link" } } } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": true, "category": "pulls", "subcategory": null } } }, "/repos/{owner}/{repo}/pulls/{pull_number}/files": { "get": { "summary": "List pull requests files", "description": "**Note:** Responses include a maximum of 3000 files. The paginated response returns 30 files per page by default.", "tags": [ "pulls" ], "operationId": "pulls/list-files", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/pulls#list-pull-requests-files" }, "parameters": [ { "$ref": "#/components/parameters/owner" }, { "$ref": "#/components/parameters/repo" }, { "$ref": "#/components/parameters/pull-number" }, { "$ref": "#/components/parameters/per-page" }, { "$ref": "#/components/parameters/page" } ], "responses": { "200": { "description": "Response", "content": { "application/json": { "schema": { "type": "array", "items": { "$ref": "#/components/schemas/diff-entry" } }, "examples": { "default": { "$ref": "#/components/examples/diff-entry-items" } } } }, "headers": { "Link": { "$ref": "#/components/headers/link" } } }, "422": { "$ref": "#/components/responses/validation_failed" }, "500": { "$ref": "#/components/responses/internal_error" } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": true, "category": "pulls", "subcategory": null } } }, "/repos/{owner}/{repo}/pulls/{pull_number}/merge": { "get": { "summary": "Check if a pull request has been merged", "description": "", "tags": [ "pulls" ], "operationId": "pulls/check-if-merged", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/pulls#check-if-a-pull-request-has-been-merged" }, "parameters": [ { "$ref": "#/components/parameters/owner" }, { "$ref": "#/components/parameters/repo" }, { "$ref": "#/components/parameters/pull-number" } ], "responses": { "204": { "description": "Response if pull request has been merged" }, "404": { "description": "Not Found if pull request has not been merged" } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": true, "category": "pulls", "subcategory": null } }, "put": { "summary": "Merge a pull request", "description": "This endpoint triggers [notifications](https://docs.github.com/enterprise-server@3.0/github/managing-subscriptions-and-notifications-on-github/about-notifications). Creating content too quickly using this endpoint may result in secondary rate limiting. See \"[Secondary rate limits](https://docs.github.com/enterprise-server@3.0/rest/overview/resources-in-the-rest-api#secondary-rate-limits)\" and \"[Dealing with secondary rate limits](https://docs.github.com/enterprise-server@3.0/rest/guides/best-practices-for-integrators#dealing-with-secondary-rate-limits)\" for details.", "tags": [ "pulls" ], "operationId": "pulls/merge", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/pulls#merge-a-pull-request" }, "parameters": [ { "$ref": "#/components/parameters/owner" }, { "$ref": "#/components/parameters/repo" }, { "$ref": "#/components/parameters/pull-number" } ], "requestBody": { "required": false, "content": { "application/json": { "schema": { "type": [ "object", "null" ], "properties": { "commit_title": { "type": "string", "description": "Title for the automatic commit message." }, "commit_message": { "type": "string", "description": "Extra detail to append to automatic commit message." }, "sha": { "type": "string", "description": "SHA that pull request head must match to allow merge." }, "merge_method": { "type": "string", "description": "Merge method to use. Possible values are `merge`, `squash` or `rebase`. Default is `merge`.", "enum": [ "merge", "squash", "rebase" ] } } } } } }, "responses": { "200": { "description": "if merge was successful", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/pull-request-merge-result" }, "examples": { "response-if-merge-was-successful": { "$ref": "#/components/examples/pull-request-merge-result-response-if-merge-was-successful" } } } } }, "405": { "description": "Method Not Allowed if merge cannot be performed", "content": { "application/json": { "schema": { "type": "object", "properties": { "message": { "type": "string" }, "documentation_url": { "type": "string" } } }, "examples": { "response-if-merge-cannot-be-performed": { "value": { "message": "Pull Request is not mergeable" } } } } } }, "409": { "description": "Conflict if sha was provided and pull request head did not match", "content": { "application/json": { "schema": { "type": "object", "properties": { "message": { "type": "string" }, "documentation_url": { "type": "string" } } }, "examples": { "response-if-sha-was-provided-and-pull-request-head-did-not-match": { "value": { "message": "Head branch was modified. Review and try the merge again." } } } } } }, "422": { "$ref": "#/components/responses/validation_failed" }, "403": { "$ref": "#/components/responses/forbidden" }, "404": { "$ref": "#/components/responses/not_found" } }, "x-github": { "triggersNotification": true, "githubCloudOnly": false, "enabledForGitHubApps": true, "category": "pulls", "subcategory": null } } }, "/repos/{owner}/{repo}/pulls/{pull_number}/requested_reviewers": { "get": { "summary": "List requested reviewers for a pull request", "description": "", "tags": [ "pulls" ], "operationId": "pulls/list-requested-reviewers", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/pulls#list-requested-reviewers-for-a-pull-request" }, "parameters": [ { "$ref": "#/components/parameters/owner" }, { "$ref": "#/components/parameters/repo" }, { "$ref": "#/components/parameters/pull-number" }, { "$ref": "#/components/parameters/per-page" }, { "$ref": "#/components/parameters/page" } ], "responses": { "200": { "description": "Response", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/pull-request-review-request" }, "examples": { "default": { "$ref": "#/components/examples/simple-pull-request-review-request" } } } }, "headers": { "Link": { "$ref": "#/components/headers/link" } } } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": true, "category": "pulls", "subcategory": "review-requests" } }, "post": { "summary": "Request reviewers for a pull request", "description": "This endpoint triggers [notifications](https://docs.github.com/enterprise-server@3.0/github/managing-subscriptions-and-notifications-on-github/about-notifications). Creating content too quickly using this endpoint may result in secondary rate limiting. See \"[Secondary rate limits](https://docs.github.com/enterprise-server@3.0/rest/overview/resources-in-the-rest-api#secondary-rate-limits)\" and \"[Dealing with secondary rate limits](https://docs.github.com/enterprise-server@3.0/rest/guides/best-practices-for-integrators#dealing-with-secondary-rate-limits)\" for details.", "tags": [ "pulls" ], "operationId": "pulls/request-reviewers", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/pulls#request-reviewers-for-a-pull-request" }, "parameters": [ { "$ref": "#/components/parameters/owner" }, { "$ref": "#/components/parameters/repo" }, { "$ref": "#/components/parameters/pull-number" } ], "requestBody": { "required": false, "content": { "application/json": { "schema": { "type": "object", "properties": { "reviewers": { "type": "array", "description": "An array of user `login`s that will be requested.", "items": { "type": "string" } }, "team_reviewers": { "type": "array", "description": "An array of team `slug`s that will be requested.", "items": { "type": "string" } } }, "anyOf": [ { "required": [ "reviewers" ] }, { "required": [ "team_reviewers" ] } ] }, "example": { "reviewers": [ "octocat", "hubot", "other_user" ], "team_reviewers": [ "justice-league" ] } } } }, "responses": { "201": { "description": "Response", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/pull-request-simple" }, "examples": { "default": { "$ref": "#/components/examples/pull-request-review-request" } } } } }, "422": { "description": "Unprocessable Entity if user is not a collaborator" }, "403": { "$ref": "#/components/responses/forbidden" } }, "x-github": { "triggersNotification": true, "githubCloudOnly": false, "enabledForGitHubApps": true, "category": "pulls", "subcategory": "review-requests" } }, "delete": { "summary": "Remove requested reviewers from a pull request", "description": "", "tags": [ "pulls" ], "operationId": "pulls/remove-requested-reviewers", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/pulls#remove-requested-reviewers-from-a-pull-request" }, "parameters": [ { "$ref": "#/components/parameters/owner" }, { "$ref": "#/components/parameters/repo" }, { "$ref": "#/components/parameters/pull-number" } ], "requestBody": { "required": true, "content": { "application/json": { "schema": { "type": "object", "properties": { "reviewers": { "type": "array", "description": "An array of user `login`s that will be removed.", "items": { "type": "string" } }, "team_reviewers": { "type": "array", "description": "An array of team `slug`s that will be removed.", "items": { "type": "string" } } }, "required": [ "reviewers" ] }, "example": { "reviewers": [ "octocat", "hubot", "other_user" ], "team_reviewers": [ "justice-league" ] } } } }, "responses": { "200": { "description": "Response", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/pull-request-simple" } } } }, "422": { "$ref": "#/components/responses/validation_failed" } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": true, "category": "pulls", "subcategory": "review-requests" } } }, "/repos/{owner}/{repo}/pulls/{pull_number}/reviews": { "get": { "summary": "List reviews for a pull request", "description": "The list of reviews returns in chronological order.", "tags": [ "pulls" ], "operationId": "pulls/list-reviews", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/pulls#list-reviews-for-a-pull-request" }, "parameters": [ { "$ref": "#/components/parameters/owner" }, { "$ref": "#/components/parameters/repo" }, { "$ref": "#/components/parameters/pull-number" }, { "$ref": "#/components/parameters/per-page" }, { "$ref": "#/components/parameters/page" } ], "responses": { "200": { "description": "The list of reviews returns in chronological order.", "content": { "application/json": { "schema": { "type": "array", "items": { "$ref": "#/components/schemas/pull-request-review" } }, "examples": { "default": { "$ref": "#/components/examples/pull-request-review-items" } } } }, "headers": { "Link": { "$ref": "#/components/headers/link" } } } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": true, "category": "pulls", "subcategory": "reviews" } }, "post": { "summary": "Create a review for a pull request", "description": "This endpoint triggers [notifications](https://docs.github.com/en/github/managing-subscriptions-and-notifications-on-github/about-notifications). Creating content too quickly using this endpoint may result in secondary rate limiting. See \"[Secondary rate limits](https://docs.github.com/enterprise-server@3.0/rest/overview/resources-in-the-rest-api#secondary-rate-limits)\" and \"[Dealing with secondary rate limits](https://docs.github.com/enterprise-server@3.0/rest/guides/best-practices-for-integrators#dealing-with-secondary-rate-limits)\" for details.\n\nPull request reviews created in the `PENDING` state do not include the `submitted_at` property in the response.\n\n**Note:** To comment on a specific line in a file, you need to first determine the _position_ of that line in the diff. The GitHub REST API v3 offers the `application/vnd.github.v3.diff` [media type](https://docs.github.com/enterprise-server@3.0/rest/overview/media-types#commits-commit-comparison-and-pull-requests). To see a pull request diff, add this media type to the `Accept` header of a call to the [single pull request](https://docs.github.com/enterprise-server@3.0/rest/reference/pulls#get-a-pull-request) endpoint.\n\nThe `position` value equals the number of lines down from the first \"@@\" hunk header in the file you want to add a comment. The line just below the \"@@\" line is position 1, the next line is position 2, and so on. The position in the diff continues to increase through lines of whitespace and additional hunks until the beginning of a new file.", "tags": [ "pulls" ], "operationId": "pulls/create-review", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/pulls#create-a-review-for-a-pull-request" }, "parameters": [ { "$ref": "#/components/parameters/owner" }, { "$ref": "#/components/parameters/repo" }, { "$ref": "#/components/parameters/pull-number" } ], "requestBody": { "required": false, "content": { "application/json": { "schema": { "type": "object", "properties": { "commit_id": { "type": "string", "description": "The SHA of the commit that needs a review. Not using the latest commit SHA may render your review comment outdated if a subsequent commit modifies the line you specify as the `position`. Defaults to the most recent commit in the pull request when you do not specify a value." }, "body": { "type": "string", "description": "**Required** when using `REQUEST_CHANGES` or `COMMENT` for the `event` parameter. The body text of the pull request review." }, "event": { "type": "string", "description": "The review action you want to perform. The review actions include: `APPROVE`, `REQUEST_CHANGES`, or `COMMENT`. By leaving this blank, you set the review action state to `PENDING`, which means you will need to [submit the pull request review](https://docs.github.com/enterprise-server@3.0/rest/reference/pulls#submit-a-review-for-a-pull-request) when you are ready.", "enum": [ "APPROVE", "REQUEST_CHANGES", "COMMENT" ] }, "comments": { "type": "array", "description": "Use the following table to specify the location, destination, and contents of the draft review comment.", "items": { "type": "object", "properties": { "path": { "type": "string", "description": "The relative path to the file that necessitates a review comment." }, "position": { "type": "integer", "description": "The position in the diff where you want to add a review comment. Note this value is not the same as the line number in the file. For help finding the position value, read the note below." }, "body": { "type": "string", "description": "Text of the review comment." }, "line": { "type": "integer", "examples": [ 28 ] }, "side": { "type": "string", "examples": [ "RIGHT" ] }, "start_line": { "type": "integer", "examples": [ 26 ] }, "start_side": { "type": "string", "examples": [ "LEFT" ] } }, "required": [ "path", "body" ] } } } }, "example": { "commit_id": "ecdd80bb57125d7ba9641ffaa4d7d2c19d3f3091", "body": "This is close to perfect! Please address the suggested inline change.", "event": "REQUEST_CHANGES", "comments": [ { "path": "file.md", "position": 6, "body": "Please add more information here, and fix this typo." } ] } } } }, "responses": { "200": { "description": "Response", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/pull-request-review" }, "examples": { "default": { "$ref": "#/components/examples/pull-request-review" } } } } }, "422": { "$ref": "#/components/responses/validation_failed_simple" }, "403": { "$ref": "#/components/responses/forbidden" } }, "x-github": { "triggersNotification": true, "githubCloudOnly": false, "enabledForGitHubApps": true, "category": "pulls", "subcategory": "reviews" } } }, "/repos/{owner}/{repo}/pulls/{pull_number}/reviews/{review_id}": { "get": { "summary": "Get a review for a pull request", "description": "", "tags": [ "pulls" ], "operationId": "pulls/get-review", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/pulls#get-a-review-for-a-pull-request" }, "parameters": [ { "$ref": "#/components/parameters/owner" }, { "$ref": "#/components/parameters/repo" }, { "$ref": "#/components/parameters/pull-number" }, { "$ref": "#/components/parameters/review-id" } ], "responses": { "200": { "description": "Response", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/pull-request-review" }, "examples": { "default": { "$ref": "#/components/examples/pull-request-review-4" } } } } }, "404": { "$ref": "#/components/responses/not_found" } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": true, "category": "pulls", "subcategory": "reviews" } }, "put": { "summary": "Update a review for a pull request", "description": "Update the review summary comment with new text.", "tags": [ "pulls" ], "operationId": "pulls/update-review", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/pulls#update-a-review-for-a-pull-request" }, "parameters": [ { "$ref": "#/components/parameters/owner" }, { "$ref": "#/components/parameters/repo" }, { "$ref": "#/components/parameters/pull-number" }, { "$ref": "#/components/parameters/review-id" } ], "requestBody": { "required": true, "content": { "application/json": { "schema": { "type": "object", "properties": { "body": { "type": "string", "description": "The body text of the pull request review." } }, "required": [ "body" ] }, "example": { "body": "This is close to perfect! Please address the suggested inline change. And add more about this." } } } }, "responses": { "200": { "description": "Response", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/pull-request-review" }, "examples": { "default": { "$ref": "#/components/examples/pull-request-review-5" } } } } }, "422": { "$ref": "#/components/responses/validation_failed_simple" } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": true, "category": "pulls", "subcategory": "reviews" } }, "delete": { "summary": "Delete a pending review for a pull request", "description": "", "tags": [ "pulls" ], "operationId": "pulls/delete-pending-review", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/pulls#delete-a-pending-review-for-a-pull-request" }, "parameters": [ { "$ref": "#/components/parameters/owner" }, { "$ref": "#/components/parameters/repo" }, { "$ref": "#/components/parameters/pull-number" }, { "$ref": "#/components/parameters/review-id" } ], "responses": { "200": { "description": "Response", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/pull-request-review" }, "examples": { "default": { "$ref": "#/components/examples/pull-request-review" } } } } }, "422": { "$ref": "#/components/responses/validation_failed_simple" }, "404": { "$ref": "#/components/responses/not_found" } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": true, "category": "pulls", "subcategory": "reviews" } } }, "/repos/{owner}/{repo}/pulls/{pull_number}/reviews/{review_id}/comments": { "get": { "summary": "List comments for a pull request review", "description": "List comments for a specific pull request review.", "tags": [ "pulls" ], "operationId": "pulls/list-comments-for-review", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/pulls#list-comments-for-a-pull-request-review" }, "parameters": [ { "$ref": "#/components/parameters/owner" }, { "$ref": "#/components/parameters/repo" }, { "$ref": "#/components/parameters/pull-number" }, { "$ref": "#/components/parameters/review-id" }, { "$ref": "#/components/parameters/per-page" }, { "$ref": "#/components/parameters/page" } ], "responses": { "200": { "description": "Response", "content": { "application/json": { "schema": { "type": "array", "items": { "$ref": "#/components/schemas/review-comment" } }, "examples": { "default": { "$ref": "#/components/examples/review-comment-items" } } } }, "headers": { "Link": { "$ref": "#/components/headers/link" } } }, "404": { "$ref": "#/components/responses/not_found" } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": true, "category": "pulls", "subcategory": "reviews" } } }, "/repos/{owner}/{repo}/pulls/{pull_number}/reviews/{review_id}/dismissals": { "put": { "summary": "Dismiss a review for a pull request", "description": "**Note:** To dismiss a pull request review on a [protected branch](https://docs.github.com/enterprise-server@3.0/rest/reference/repos#branches), you must be a repository administrator or be included in the list of people or teams who can dismiss pull request reviews.", "tags": [ "pulls" ], "operationId": "pulls/dismiss-review", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/pulls#dismiss-a-review-for-a-pull-request" }, "parameters": [ { "$ref": "#/components/parameters/owner" }, { "$ref": "#/components/parameters/repo" }, { "$ref": "#/components/parameters/pull-number" }, { "$ref": "#/components/parameters/review-id" } ], "requestBody": { "required": true, "content": { "application/json": { "schema": { "type": "object", "properties": { "message": { "type": "string", "description": "The message for the pull request review dismissal" }, "event": { "type": "string", "examples": [ "\"APPROVE\"" ] } }, "required": [ "message" ] } } } }, "responses": { "200": { "description": "Response", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/pull-request-review" }, "examples": { "default": { "$ref": "#/components/examples/pull-request-review-3" } } } } }, "404": { "$ref": "#/components/responses/not_found" }, "422": { "$ref": "#/components/responses/validation_failed_simple" } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": true, "category": "pulls", "subcategory": "reviews" } } }, "/repos/{owner}/{repo}/pulls/{pull_number}/reviews/{review_id}/events": { "post": { "summary": "Submit a review for a pull request", "description": "", "tags": [ "pulls" ], "operationId": "pulls/submit-review", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/pulls#submit-a-review-for-a-pull-request" }, "parameters": [ { "$ref": "#/components/parameters/owner" }, { "$ref": "#/components/parameters/repo" }, { "$ref": "#/components/parameters/pull-number" }, { "$ref": "#/components/parameters/review-id" } ], "requestBody": { "required": true, "content": { "application/json": { "schema": { "type": "object", "properties": { "body": { "type": "string", "description": "The body text of the pull request review" }, "event": { "type": "string", "description": "The review action you want to perform. The review actions include: `APPROVE`, `REQUEST_CHANGES`, or `COMMENT`. When you leave this blank, the API returns _HTTP 422 (Unrecognizable entity)_ and sets the review action state to `PENDING`, which means you will need to re-submit the pull request review using a review action.", "enum": [ "APPROVE", "REQUEST_CHANGES", "COMMENT" ] } }, "required": [ "event" ] } } } }, "responses": { "200": { "description": "Response", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/pull-request-review" }, "examples": { "default": { "$ref": "#/components/examples/pull-request-review-4" } } } } }, "404": { "$ref": "#/components/responses/not_found" }, "422": { "$ref": "#/components/responses/validation_failed_simple" }, "403": { "$ref": "#/components/responses/forbidden" } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": true, "category": "pulls", "subcategory": "reviews" } } }, "/repos/{owner}/{repo}/pulls/{pull_number}/update-branch": { "put": { "summary": "Update a pull request branch", "description": "Updates the pull request branch with the latest upstream changes by merging HEAD from the base branch into the pull request branch.", "tags": [ "pulls" ], "operationId": "pulls/update-branch", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/pulls#update-a-pull-request-branch" }, "parameters": [ { "$ref": "#/components/parameters/owner" }, { "$ref": "#/components/parameters/repo" }, { "$ref": "#/components/parameters/pull-number" } ], "requestBody": { "required": false, "content": { "application/json": { "schema": { "type": [ "object", "null" ], "properties": { "expected_head_sha": { "type": "string", "description": "The expected SHA of the pull request's HEAD ref. This is the most recent commit on the pull request's branch. If the expected SHA does not match the pull request's HEAD, you will receive a `422 Unprocessable Entity` status. You can use the \"[List commits](https://docs.github.com/enterprise-server@3.0/rest/reference/repos#list-commits)\" endpoint to find the most recent commit SHA. Default: SHA of the pull request's current HEAD ref." } } }, "example": { "expected_head_sha": "6dcb09b5b57875f334f61aebed695e2e4193db5e" } } } }, "responses": { "202": { "description": "Response", "content": { "application/json": { "schema": { "type": "object", "properties": { "message": { "type": "string" }, "url": { "type": "string" } } }, "example": { "message": "Updating pull request branch.", "url": "https://github.com/repos/octocat/Hello-World/pulls/53" } } } }, "422": { "$ref": "#/components/responses/validation_failed" }, "403": { "$ref": "#/components/responses/forbidden" } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": false, "category": "pulls", "previews": [ { "required": true, "name": "lydian", "note": "Updating the pull request branch with latest upstream changes is currently available for developers to preview. To access this new endpoint during the preview period, you must provide a custom [media type](https://docs.github.com/enterprise-server@3.0/rest/overview/media-types) in the `Accept` header:\n```shell\napplication/vnd.github.lydian-preview+json\n```" } ] } } }, "/repos/{owner}/{repo}/readme": { "get": { "summary": "Get a repository README", "description": "Gets the preferred README for a repository.\n\nREADMEs support [custom media types](https://docs.github.com/enterprise-server@3.0/rest/reference/repos#custom-media-types) for retrieving the raw content or rendered HTML.", "tags": [ "repos" ], "operationId": "repos/get-readme", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/repos#get-a-repository-readme" }, "parameters": [ { "$ref": "#/components/parameters/owner" }, { "$ref": "#/components/parameters/repo" }, { "name": "ref", "description": "The name of the commit/branch/tag. Default: the repository’s default branch (usually `master`)", "in": "query", "required": false, "schema": { "type": "string" } } ], "responses": { "200": { "description": "Response", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/content-file" }, "examples": { "default": { "$ref": "#/components/examples/content-file" } } } } }, "404": { "$ref": "#/components/responses/not_found" }, "422": { "$ref": "#/components/responses/validation_failed" } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": true, "category": "repos", "subcategory": "contents" } } }, "/repos/{owner}/{repo}/readme/{dir}": { "get": { "summary": "Get a repository README for a directory", "description": "Gets the README from a repository directory.\n\nREADMEs support [custom media types](https://docs.github.com/enterprise-server@3.0/rest/reference/repos#custom-media-types) for retrieving the raw content or rendered HTML.", "tags": [ "repos" ], "operationId": "repos/get-readme-in-directory", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/repos#get-a-repository-directory-readme" }, "parameters": [ { "$ref": "#/components/parameters/owner" }, { "$ref": "#/components/parameters/repo" }, { "name": "dir", "description": "The alternate path to look for a README file", "in": "path", "required": true, "schema": { "type": "string" }, "x-multi-segment": true }, { "name": "ref", "description": "The name of the commit/branch/tag. Default: the repository’s default branch (usually `master`)", "in": "query", "required": false, "schema": { "type": "string" } } ], "responses": { "200": { "description": "Response", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/content-file" }, "examples": { "default": { "$ref": "#/components/examples/content-file" } } } } }, "404": { "$ref": "#/components/responses/not_found" }, "422": { "$ref": "#/components/responses/validation_failed" } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": true, "category": "repos", "subcategory": "contents" } } }, "/repos/{owner}/{repo}/releases": { "get": { "summary": "List releases", "description": "This returns a list of releases, which does not include regular Git tags that have not been associated with a release. To get a list of Git tags, use the [Repository Tags API](https://docs.github.com/enterprise-server@3.0/rest/reference/repos#list-repository-tags).\n\nInformation about published releases are available to everyone. Only users with push access will receive listings for draft releases.", "tags": [ "repos" ], "operationId": "repos/list-releases", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/repos#list-releases" }, "parameters": [ { "$ref": "#/components/parameters/owner" }, { "$ref": "#/components/parameters/repo" }, { "$ref": "#/components/parameters/per-page" }, { "$ref": "#/components/parameters/page" } ], "responses": { "200": { "description": "Response", "content": { "application/json": { "schema": { "type": "array", "items": { "$ref": "#/components/schemas/release" } }, "examples": { "default": { "$ref": "#/components/examples/release-items" } } } }, "headers": { "Link": { "$ref": "#/components/headers/link" } } }, "404": { "$ref": "#/components/responses/not_found" } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": true, "category": "repos", "subcategory": "releases" } }, "post": { "summary": "Create a release", "description": "Users with push access to the repository can create a release.\n\nThis endpoint triggers [notifications](https://docs.github.com/en/github/managing-subscriptions-and-notifications-on-github/about-notifications). Creating content too quickly using this endpoint may result in secondary rate limiting. See \"[Secondary rate limits](https://docs.github.com/enterprise-server@3.0/rest/overview/resources-in-the-rest-api#secondary-rate-limits)\" and \"[Dealing with secondary rate limits](https://docs.github.com/enterprise-server@3.0/rest/guides/best-practices-for-integrators#dealing-with-secondary-rate-limits)\" for details.", "tags": [ "repos" ], "operationId": "repos/create-release", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/repos#create-a-release" }, "parameters": [ { "$ref": "#/components/parameters/owner" }, { "$ref": "#/components/parameters/repo" } ], "requestBody": { "required": true, "content": { "application/json": { "schema": { "type": "object", "properties": { "tag_name": { "type": "string", "description": "The name of the tag." }, "target_commitish": { "type": "string", "description": "Specifies the commitish value that determines where the Git tag is created from. Can be any branch or commit SHA. Unused if the Git tag already exists. Default: the repository's default branch (usually `master`)." }, "name": { "type": "string", "description": "The name of the release." }, "body": { "type": "string", "description": "Text describing the contents of the tag." }, "draft": { "type": "boolean", "description": "`true` to create a draft (unpublished) release, `false` to create a published one.", "default": false }, "prerelease": { "type": "boolean", "description": "`true` to identify the release as a prerelease. `false` to identify the release as a full release.", "default": false } }, "required": [ "tag_name" ] }, "example": { "tag_name": "v1.0.0", "target_commitish": "master", "name": "v1.0.0", "body": "Description of the release", "draft": false, "prerelease": false } } } }, "responses": { "201": { "description": "Response", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/release" }, "examples": { "default": { "$ref": "#/components/examples/release" } } } }, "headers": { "Location": { "example": "https://api.github.com/repos/octocat/Hello-World/releases/1", "schema": { "type": "string" } } } }, "422": { "$ref": "#/components/responses/validation_failed" } }, "x-github": { "triggersNotification": true, "githubCloudOnly": false, "enabledForGitHubApps": true, "category": "repos", "subcategory": "releases" } } }, "/repos/{owner}/{repo}/releases/assets/{asset_id}": { "get": { "summary": "Get a release asset", "description": "To download the asset's binary content, set the `Accept` header of the request to [`application/octet-stream`](https://docs.github.com/enterprise-server@3.0/rest/overview/media-types). The API will either redirect the client to the location, or stream it directly if possible. API clients should handle both a `200` or `302` response.", "tags": [ "repos" ], "operationId": "repos/get-release-asset", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/repos#get-a-release-asset" }, "parameters": [ { "$ref": "#/components/parameters/owner" }, { "$ref": "#/components/parameters/repo" }, { "$ref": "#/components/parameters/asset-id" } ], "responses": { "200": { "description": "To download the asset's binary content, set the `Accept` header of the request to [`application/octet-stream`](https://docs.github.com/enterprise-server@3.0/rest/overview/media-types). The API will either redirect the client to the location, or stream it directly if possible. API clients should handle both a `200` or `302` response.", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/release-asset" }, "examples": { "default": { "$ref": "#/components/examples/release-asset" } } } } }, "404": { "$ref": "#/components/responses/not_found" }, "415": { "$ref": "#/components/responses/preview_header_missing" }, "302": { "$ref": "#/components/responses/found" } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": true, "category": "repos", "subcategory": "releases" } }, "patch": { "summary": "Update a release asset", "description": "Users with push access to the repository can edit a release asset.", "tags": [ "repos" ], "operationId": "repos/update-release-asset", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/repos#update-a-release-asset" }, "parameters": [ { "$ref": "#/components/parameters/owner" }, { "$ref": "#/components/parameters/repo" }, { "$ref": "#/components/parameters/asset-id" } ], "requestBody": { "required": false, "content": { "application/json": { "schema": { "type": "object", "properties": { "name": { "type": "string", "description": "The file name of the asset." }, "label": { "type": "string", "description": "An alternate short description of the asset. Used in place of the filename." }, "state": { "type": "string", "examples": [ "\"uploaded\"" ] } } }, "example": { "name": "foo-1.0.0-osx.zip", "label": "Mac binary" } } } }, "responses": { "200": { "description": "Response", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/release-asset" }, "examples": { "default": { "$ref": "#/components/examples/release-asset" } } } } } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": true, "category": "repos", "subcategory": "releases" } }, "delete": { "summary": "Delete a release asset", "description": "", "tags": [ "repos" ], "operationId": "repos/delete-release-asset", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/repos#delete-a-release-asset" }, "parameters": [ { "$ref": "#/components/parameters/owner" }, { "$ref": "#/components/parameters/repo" }, { "$ref": "#/components/parameters/asset-id" } ], "responses": { "204": { "description": "Response" } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": true, "category": "repos", "subcategory": "releases" } } }, "/repos/{owner}/{repo}/releases/latest": { "get": { "summary": "Get the latest release", "description": "View the latest published full release for the repository.\n\nThe latest release is the most recent non-prerelease, non-draft release, sorted by the `created_at` attribute. The `created_at` attribute is the date of the commit used for the release, and not the date when the release was drafted or published.", "tags": [ "repos" ], "operationId": "repos/get-latest-release", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/repos#get-the-latest-release" }, "parameters": [ { "$ref": "#/components/parameters/owner" }, { "$ref": "#/components/parameters/repo" } ], "responses": { "200": { "description": "Response", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/release" }, "examples": { "default": { "$ref": "#/components/examples/release" } } } } } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": true, "category": "repos", "subcategory": "releases" } } }, "/repos/{owner}/{repo}/releases/tags/{tag}": { "get": { "summary": "Get a release by tag name", "description": "Get a published release with the specified tag.", "tags": [ "repos" ], "operationId": "repos/get-release-by-tag", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/repos#get-a-release-by-tag-name" }, "parameters": [ { "$ref": "#/components/parameters/owner" }, { "$ref": "#/components/parameters/repo" }, { "name": "tag", "description": "tag parameter", "in": "path", "required": true, "schema": { "type": "string" }, "x-multi-segment": true } ], "responses": { "200": { "description": "Response", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/release" }, "examples": { "default": { "$ref": "#/components/examples/release" } } } } }, "404": { "$ref": "#/components/responses/not_found" } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": true, "category": "repos", "subcategory": "releases" } } }, "/repos/{owner}/{repo}/releases/{release_id}": { "get": { "summary": "Get a release", "description": "**Note:** This returns an `upload_url` key corresponding to the endpoint for uploading release assets. This key is a [hypermedia resource](https://docs.github.com/enterprise-server@3.0/rest/overview/resources-in-the-rest-api#hypermedia).", "tags": [ "repos" ], "operationId": "repos/get-release", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/repos#get-a-release" }, "parameters": [ { "$ref": "#/components/parameters/owner" }, { "$ref": "#/components/parameters/repo" }, { "$ref": "#/components/parameters/release-id" } ], "responses": { "200": { "description": "**Note:** This returns an `upload_url` key corresponding to the endpoint for uploading release assets. This key is a [hypermedia resource](https://docs.github.com/enterprise-server@3.0/rest/overview/resources-in-the-rest-api#hypermedia).", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/release" }, "examples": { "default": { "$ref": "#/components/examples/release" } } } } }, "404": { "$ref": "#/components/responses/not_found" } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": true, "category": "repos", "subcategory": "releases" } }, "patch": { "summary": "Update a release", "description": "Users with push access to the repository can edit a release.", "tags": [ "repos" ], "operationId": "repos/update-release", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/repos#update-a-release" }, "parameters": [ { "$ref": "#/components/parameters/owner" }, { "$ref": "#/components/parameters/repo" }, { "$ref": "#/components/parameters/release-id" } ], "requestBody": { "required": false, "content": { "application/json": { "schema": { "type": "object", "properties": { "tag_name": { "type": "string", "description": "The name of the tag." }, "target_commitish": { "type": "string", "description": "Specifies the commitish value that determines where the Git tag is created from. Can be any branch or commit SHA. Unused if the Git tag already exists. Default: the repository's default branch (usually `master`)." }, "name": { "type": "string", "description": "The name of the release." }, "body": { "type": "string", "description": "Text describing the contents of the tag." }, "draft": { "type": "boolean", "description": "`true` makes the release a draft, and `false` publishes the release." }, "prerelease": { "type": "boolean", "description": "`true` to identify the release as a prerelease, `false` to identify the release as a full release." } } }, "example": { "tag_name": "v1.0.0", "target_commitish": "master", "name": "v1.0.0", "body": "Description of the release", "draft": false, "prerelease": false } } } }, "responses": { "200": { "description": "Response", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/release" }, "examples": { "default": { "$ref": "#/components/examples/release" } } } } } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": true, "category": "repos", "subcategory": "releases" } }, "delete": { "summary": "Delete a release", "description": "Users with push access to the repository can delete a release.", "tags": [ "repos" ], "operationId": "repos/delete-release", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/repos#delete-a-release" }, "parameters": [ { "$ref": "#/components/parameters/owner" }, { "$ref": "#/components/parameters/repo" }, { "$ref": "#/components/parameters/release-id" } ], "responses": { "204": { "description": "Response" } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": true, "category": "repos", "subcategory": "releases" } } }, "/repos/{owner}/{repo}/releases/{release_id}/assets": { "get": { "summary": "List release assets", "description": "", "tags": [ "repos" ], "operationId": "repos/list-release-assets", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/repos#list-release-assets" }, "parameters": [ { "$ref": "#/components/parameters/owner" }, { "$ref": "#/components/parameters/repo" }, { "$ref": "#/components/parameters/release-id" }, { "$ref": "#/components/parameters/per-page" }, { "$ref": "#/components/parameters/page" } ], "responses": { "200": { "description": "Response", "content": { "application/json": { "schema": { "type": "array", "items": { "$ref": "#/components/schemas/release-asset" } }, "examples": { "default": { "$ref": "#/components/examples/release-asset-items" } } } }, "headers": { "Link": { "$ref": "#/components/headers/link" } } } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": true, "category": "repos", "subcategory": "releases" } }, "post": { "summary": "Upload a release asset", "description": "This endpoint makes use of [a Hypermedia relation](https://docs.github.com/enterprise-server@3.0/rest/overview/resources-in-the-rest-api#hypermedia) to determine which URL to access. The endpoint you call to upload release assets is specific to your release. Use the `upload_url` returned in\nthe response of the [Create a release endpoint](https://docs.github.com/enterprise-server@3.0/rest/reference/repos#create-a-release) to upload a release asset.\n\nYou need to use an HTTP client which supports [SNI](http://en.wikipedia.org/wiki/Server_Name_Indication) to make calls to this endpoint.\n\nMost libraries will set the required `Content-Length` header automatically. Use the required `Content-Type` header to provide the media type of the asset. For a list of media types, see [Media Types](https://www.iana.org/assignments/media-types/media-types.xhtml). For example: \n\n`application/zip`\n\nGitHub Enterprise Server expects the asset data in its raw binary form, rather than JSON. You will send the raw binary content of the asset as the request body. Everything else about the endpoint is the same as the rest of the API. For example,\nyou'll still need to pass your authentication to be able to upload an asset.\n\nWhen an upstream failure occurs, you will receive a `502 Bad Gateway` status. This may leave an empty asset with a state of `starter`. It can be safely deleted.\n\n**Notes:**\n* GitHub Enterprise Server renames asset filenames that have special characters, non-alphanumeric characters, and leading or trailing periods. The \"[List assets for a release](https://docs.github.com/enterprise-server@3.0/rest/reference/repos#list-assets-for-a-release)\"\nendpoint lists the renamed filenames. For more information and help, contact [GitHub Enterprise Server Support](https://support.github.com/contact?tags=dotcom-rest-api).\n* If you upload an asset with the same filename as another uploaded asset, you'll receive an error and must delete the old file before you can re-upload the new asset.", "tags": [ "repos" ], "operationId": "repos/upload-release-asset", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/repos#upload-a-release-asset" }, "servers": [ { "url": "{origin}", "variables": { "origin": { "default": "https://uploads.github.com", "description": "The URL origin (protocol + host name + port) is included in `upload_url` returned in the response of the \"Create a release\" endpoint" } } } ], "parameters": [ { "$ref": "#/components/parameters/owner" }, { "$ref": "#/components/parameters/repo" }, { "$ref": "#/components/parameters/release-id" }, { "name": "name", "in": "query", "required": true, "schema": { "type": "string" } }, { "name": "label", "in": "query", "schema": { "type": "string" } } ], "requestBody": { "required": false, "content": { "*/*": { "schema": { "type": "string", "description": "The raw file data" } } } }, "responses": { "201": { "description": "Response for successful upload", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/release-asset" }, "examples": { "response-for-successful-upload": { "$ref": "#/components/examples/release-asset-response-for-successful-upload" } } } } }, "422": { "description": "Response if you upload an asset with the same filename as another uploaded asset" } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": true, "category": "repos", "subcategory": "releases" } } }, "/repos/{owner}/{repo}/stargazers": { "get": { "summary": "List stargazers", "description": "Lists the people that have starred the repository.\n\nYou can also find out _when_ stars were created by passing the following custom [media type](https://docs.github.com/enterprise-server@3.0/rest/overview/media-types/) via the `Accept` header:", "tags": [ "activity" ], "operationId": "activity/list-stargazers-for-repo", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/activity#list-stargazers" }, "parameters": [ { "$ref": "#/components/parameters/owner" }, { "$ref": "#/components/parameters/repo" }, { "$ref": "#/components/parameters/per-page" }, { "$ref": "#/components/parameters/page" } ], "responses": { "200": { "description": "Response", "content": { "application/json": { "schema": { "anyOf": [ { "type": "array", "items": { "$ref": "#/components/schemas/simple-user" } }, { "type": "array", "items": { "$ref": "#/components/schemas/stargazer" } } ] }, "examples": { "default-response": { "$ref": "#/components/examples/simple-user-items-default-response" }, "alternative-response-with-star-creation-timestamps": { "$ref": "#/components/examples/stargazer-items-alternative-response-with-star-creation-timestamps" } } } }, "headers": { "Link": { "$ref": "#/components/headers/link" } } }, "422": { "$ref": "#/components/responses/validation_failed" } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": true, "category": "activity", "subcategory": "starring" } } }, "/repos/{owner}/{repo}/stats/code_frequency": { "get": { "summary": "Get the weekly commit activity", "description": "Returns a weekly aggregate of the number of additions and deletions pushed to a repository.", "tags": [ "repos" ], "operationId": "repos/get-code-frequency-stats", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/repos#get-the-weekly-commit-activity" }, "parameters": [ { "$ref": "#/components/parameters/owner" }, { "$ref": "#/components/parameters/repo" } ], "responses": { "200": { "description": "Returns a weekly aggregate of the number of additions and deletions pushed to a repository.", "content": { "application/json": { "schema": { "type": "array", "items": { "$ref": "#/components/schemas/code-frequency-stat" } }, "examples": { "default": { "$ref": "#/components/examples/code-frequency-stat-items" } } } } }, "202": { "$ref": "#/components/responses/accepted" }, "204": { "$ref": "#/components/responses/no_content" } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": true, "category": "repos", "subcategory": "statistics" } } }, "/repos/{owner}/{repo}/stats/commit_activity": { "get": { "summary": "Get the last year of commit activity", "description": "Returns the last year of commit activity grouped by week. The `days` array is a group of commits per day, starting on `Sunday`.", "tags": [ "repos" ], "operationId": "repos/get-commit-activity-stats", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/repos#get-the-last-year-of-commit-activity" }, "parameters": [ { "$ref": "#/components/parameters/owner" }, { "$ref": "#/components/parameters/repo" } ], "responses": { "200": { "description": "Response", "content": { "application/json": { "schema": { "type": "array", "items": { "$ref": "#/components/schemas/commit-activity" } }, "examples": { "default": { "$ref": "#/components/examples/commit-activity-items" } } } } }, "202": { "$ref": "#/components/responses/accepted" }, "204": { "$ref": "#/components/responses/no_content" } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": true, "category": "repos", "subcategory": "statistics" } } }, "/repos/{owner}/{repo}/stats/contributors": { "get": { "summary": "Get all contributor commit activity", "description": "\nReturns the `total` number of commits authored by the contributor. In addition, the response includes a Weekly Hash (`weeks` array) with the following information:\n\n* `w` - Start of the week, given as a [Unix timestamp](http://en.wikipedia.org/wiki/Unix_time).\n* `a` - Number of additions\n* `d` - Number of deletions\n* `c` - Number of commits", "tags": [ "repos" ], "operationId": "repos/get-contributors-stats", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/repos#get-all-contributor-commit-activity" }, "parameters": [ { "$ref": "#/components/parameters/owner" }, { "$ref": "#/components/parameters/repo" } ], "responses": { "200": { "description": "* `w` - Start of the week, given as a [Unix timestamp](http://en.wikipedia.org/wiki/Unix_time).\n* `a` - Number of additions\n* `d` - Number of deletions\n* `c` - Number of commits", "content": { "application/json": { "schema": { "type": "array", "items": { "$ref": "#/components/schemas/contributor-activity" } }, "examples": { "default": { "$ref": "#/components/examples/contributor-activity-items" } } } } }, "202": { "$ref": "#/components/responses/accepted" }, "204": { "$ref": "#/components/responses/no_content" } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": true, "category": "repos", "subcategory": "statistics" } } }, "/repos/{owner}/{repo}/stats/participation": { "get": { "summary": "Get the weekly commit count", "description": "Returns the total commit counts for the `owner` and total commit counts in `all`. `all` is everyone combined, including the `owner` in the last 52 weeks. If you'd like to get the commit counts for non-owners, you can subtract `owner` from `all`.\n\nThe array order is oldest week (index 0) to most recent week.", "tags": [ "repos" ], "operationId": "repos/get-participation-stats", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/repos#get-the-weekly-commit-count" }, "parameters": [ { "$ref": "#/components/parameters/owner" }, { "$ref": "#/components/parameters/repo" } ], "responses": { "200": { "description": "The array order is oldest week (index 0) to most recent week.", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/participation-stats" }, "examples": { "default": { "$ref": "#/components/examples/participation-stats" } } } } }, "404": { "$ref": "#/components/responses/not_found" } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": true, "category": "repos", "subcategory": "statistics" } } }, "/repos/{owner}/{repo}/stats/punch_card": { "get": { "summary": "Get the hourly commit count for each day", "description": "Each array contains the day number, hour number, and number of commits:\n\n* `0-6`: Sunday - Saturday\n* `0-23`: Hour of day\n* Number of commits\n\nFor example, `[2, 14, 25]` indicates that there were 25 total commits, during the 2:00pm hour on Tuesdays. All times are based on the time zone of individual commits.", "tags": [ "repos" ], "operationId": "repos/get-punch-card-stats", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/repos#get-the-hourly-commit-count-for-each-day" }, "parameters": [ { "$ref": "#/components/parameters/owner" }, { "$ref": "#/components/parameters/repo" } ], "responses": { "200": { "description": "For example, `[2, 14, 25]` indicates that there were 25 total commits, during the 2:00pm hour on Tuesdays. All times are based on the time zone of individual commits.", "content": { "application/json": { "schema": { "type": "array", "items": { "$ref": "#/components/schemas/code-frequency-stat" } }, "examples": { "default": { "$ref": "#/components/examples/code-frequency-stat-items-2" } } } } }, "204": { "$ref": "#/components/responses/no_content" } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": true, "category": "repos", "subcategory": "statistics" } } }, "/repos/{owner}/{repo}/statuses/{sha}": { "post": { "summary": "Create a commit status", "description": "Users with push access in a repository can create commit statuses for a given SHA.\n\nNote: there is a limit of 1000 statuses per `sha` and `context` within a repository. Attempts to create more than 1000 statuses will result in a validation error.", "tags": [ "repos" ], "operationId": "repos/create-commit-status", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/repos#create-a-commit-status" }, "parameters": [ { "$ref": "#/components/parameters/owner" }, { "$ref": "#/components/parameters/repo" }, { "name": "sha", "in": "path", "required": true, "schema": { "type": "string" }, "x-multi-segment": true } ], "requestBody": { "required": true, "content": { "application/json": { "schema": { "type": "object", "properties": { "state": { "type": "string", "description": "The state of the status. Can be one of `error`, `failure`, `pending`, or `success`.", "enum": [ "error", "failure", "pending", "success" ] }, "target_url": { "type": "string", "description": "The target URL to associate with this status. This URL will be linked from the GitHub UI to allow users to easily see the source of the status. \nFor example, if your continuous integration system is posting build status, you would want to provide the deep link for the build output for this specific SHA: \n`http://ci.example.com/user/repo/build/sha`" }, "description": { "type": "string", "description": "A short description of the status." }, "context": { "type": "string", "description": "A string label to differentiate this status from the status of other systems. This field is case-insensitive.", "default": "default" } }, "required": [ "state" ] }, "example": { "state": "success", "target_url": "https://example.com/build/status", "description": "The build succeeded!", "context": "continuous-integration/jenkins" } } } }, "responses": { "201": { "description": "Response", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/status" }, "examples": { "default": { "$ref": "#/components/examples/status" } } } }, "headers": { "Location": { "example": "https://api.github.com/repos/octocat/Hello-World/statuses/6dcb09b5b57875f334f61aebed695e2e4193db5e", "schema": { "type": "string" } } } } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": true, "category": "repos", "subcategory": "statuses" } } }, "/repos/{owner}/{repo}/subscribers": { "get": { "summary": "List watchers", "description": "Lists the people watching the specified repository.", "tags": [ "activity" ], "operationId": "activity/list-watchers-for-repo", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/activity#list-watchers" }, "parameters": [ { "$ref": "#/components/parameters/owner" }, { "$ref": "#/components/parameters/repo" }, { "$ref": "#/components/parameters/per-page" }, { "$ref": "#/components/parameters/page" } ], "responses": { "200": { "description": "Response", "content": { "application/json": { "schema": { "type": "array", "items": { "$ref": "#/components/schemas/simple-user" } }, "examples": { "default": { "$ref": "#/components/examples/simple-user-items" } } } }, "headers": { "Link": { "$ref": "#/components/headers/link" } } } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": true, "category": "activity", "subcategory": "watching" } } }, "/repos/{owner}/{repo}/subscription": { "get": { "summary": "Get a repository subscription", "description": "", "tags": [ "activity" ], "operationId": "activity/get-repo-subscription", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/activity#get-a-repository-subscription" }, "parameters": [ { "$ref": "#/components/parameters/owner" }, { "$ref": "#/components/parameters/repo" } ], "responses": { "200": { "description": "if you subscribe to the repository", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/repository-subscription" }, "examples": { "response-if-you-subscribe-to-the-repository": { "$ref": "#/components/examples/repository-subscription-response-if-you-subscribe-to-the-repository" } } } } }, "404": { "description": "Not Found if you don't subscribe to the repository" }, "403": { "$ref": "#/components/responses/forbidden" } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": false, "category": "activity", "subcategory": "watching" } }, "put": { "summary": "Set a repository subscription", "description": "If you would like to watch a repository, set `subscribed` to `true`. If you would like to ignore notifications made within a repository, set `ignored` to `true`. If you would like to stop watching a repository, [delete the repository's subscription](https://docs.github.com/enterprise-server@3.0/rest/reference/activity#delete-a-repository-subscription) completely.", "tags": [ "activity" ], "operationId": "activity/set-repo-subscription", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/activity#set-a-repository-subscription" }, "parameters": [ { "$ref": "#/components/parameters/owner" }, { "$ref": "#/components/parameters/repo" } ], "requestBody": { "required": false, "content": { "application/json": { "schema": { "type": "object", "properties": { "subscribed": { "type": "boolean", "description": "Determines if notifications should be received from this repository." }, "ignored": { "type": "boolean", "description": "Determines if all notifications should be blocked from this repository." } } } } } }, "responses": { "200": { "description": "Response", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/repository-subscription" }, "examples": { "default": { "$ref": "#/components/examples/repository-subscription" } } } } } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": false, "category": "activity", "subcategory": "watching" } }, "delete": { "summary": "Delete a repository subscription", "description": "This endpoint should only be used to stop watching a repository. To control whether or not you wish to receive notifications from a repository, [set the repository's subscription manually](https://docs.github.com/enterprise-server@3.0/rest/reference/activity#set-a-repository-subscription).", "tags": [ "activity" ], "operationId": "activity/delete-repo-subscription", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/activity#delete-a-repository-subscription" }, "parameters": [ { "$ref": "#/components/parameters/owner" }, { "$ref": "#/components/parameters/repo" } ], "responses": { "204": { "description": "Response" } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": false, "category": "activity", "subcategory": "watching" } } }, "/repos/{owner}/{repo}/tags": { "get": { "summary": "List repository tags", "description": "", "tags": [ "repos" ], "operationId": "repos/list-tags", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/repos#list-repository-tags" }, "parameters": [ { "$ref": "#/components/parameters/owner" }, { "$ref": "#/components/parameters/repo" }, { "$ref": "#/components/parameters/per-page" }, { "$ref": "#/components/parameters/page" } ], "responses": { "200": { "description": "Response", "content": { "application/json": { "schema": { "type": "array", "items": { "$ref": "#/components/schemas/tag" } }, "examples": { "default": { "$ref": "#/components/examples/tag-items" } } } }, "headers": { "Link": { "$ref": "#/components/headers/link" } } } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": true, "category": "repos", "subcategory": null } } }, "/repos/{owner}/{repo}/tarball/{ref}": { "get": { "summary": "Download a repository archive (tar)", "description": "Gets a redirect URL to download a tar archive for a repository. If you omit `:ref`, the repository’s default branch (usually\n`master`) will be used. Please make sure your HTTP framework is configured to follow redirects or you will need to use\nthe `Location` header to make a second `GET` request.\n**Note**: For private repositories, these links are temporary and expire after five minutes.", "tags": [ "repos" ], "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/repos#download-a-repository-archive" }, "operationId": "repos/download-tarball-archive", "parameters": [ { "$ref": "#/components/parameters/owner" }, { "$ref": "#/components/parameters/repo" }, { "name": "ref", "in": "path", "required": true, "schema": { "type": "string" } } ], "responses": { "302": { "description": "Response", "headers": { "Location": { "example": "https://codeload.github.com/me/myprivate/legacy.zip/master?login=me&token=thistokenexpires", "schema": { "type": "string" } } } } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": true, "category": "repos", "subcategory": "contents" } } }, "/repos/{owner}/{repo}/teams": { "get": { "summary": "List repository teams", "description": "", "tags": [ "repos" ], "operationId": "repos/list-teams", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/repos#list-repository-teams" }, "parameters": [ { "$ref": "#/components/parameters/owner" }, { "$ref": "#/components/parameters/repo" }, { "$ref": "#/components/parameters/per-page" }, { "$ref": "#/components/parameters/page" } ], "responses": { "200": { "description": "Response", "content": { "application/json": { "schema": { "type": "array", "items": { "$ref": "#/components/schemas/team" } }, "examples": { "default": { "$ref": "#/components/examples/team-items" } } } }, "headers": { "Link": { "$ref": "#/components/headers/link" } } } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": true, "category": "repos", "subcategory": null } } }, "/repos/{owner}/{repo}/topics": { "get": { "summary": "Get all repository topics", "description": "", "tags": [ "repos" ], "operationId": "repos/get-all-topics", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/repos#get-all-repository-topics" }, "parameters": [ { "$ref": "#/components/parameters/owner" }, { "$ref": "#/components/parameters/repo" }, { "$ref": "#/components/parameters/page" }, { "$ref": "#/components/parameters/per-page" } ], "responses": { "200": { "description": "Response", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/topic" }, "examples": { "default": { "$ref": "#/components/examples/topic" } } } } }, "404": { "$ref": "#/components/responses/not_found" }, "415": { "$ref": "#/components/responses/preview_header_missing" } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": true, "category": "repos", "previews": [ { "required": true, "name": "mercy", "note": "The `topics` property for repositories on GitHub is currently available for developers to preview. To view the `topics` property in calls that return repository results, you must provide a custom [media type](https://docs.github.com/enterprise-server@3.0/rest/overview/media-types) in the `Accept` header:\n```shell\napplication/vnd.github.mercy-preview+json\n```" } ] } }, "put": { "summary": "Replace all repository topics", "description": "", "tags": [ "repos" ], "operationId": "repos/replace-all-topics", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/repos#replace-all-repository-topics" }, "parameters": [ { "$ref": "#/components/parameters/owner" }, { "$ref": "#/components/parameters/repo" } ], "requestBody": { "required": true, "content": { "application/json": { "schema": { "type": "object", "properties": { "names": { "type": "array", "description": "An array of topics to add to the repository. Pass one or more topics to _replace_ the set of existing topics. Send an empty array (`[]`) to clear all topics from the repository. **Note:** Topic `names` cannot contain uppercase letters.", "items": { "type": "string" } } }, "required": [ "names" ] }, "example": { "names": [ "octocat", "atom", "electron", "api" ] } } } }, "responses": { "200": { "description": "Response", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/topic" }, "examples": { "default": { "$ref": "#/components/examples/topic" } } } } }, "404": { "$ref": "#/components/responses/not_found" }, "422": { "$ref": "#/components/responses/validation_failed_simple" }, "415": { "$ref": "#/components/responses/preview_header_missing" } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": true, "category": "repos", "previews": [ { "required": true, "name": "mercy", "note": "The `topics` property for repositories on GitHub is currently available for developers to preview. To view the `topics` property in calls that return repository results, you must provide a custom [media type](https://docs.github.com/enterprise-server@3.0/rest/overview/media-types) in the `Accept` header:\n```shell\napplication/vnd.github.mercy-preview+json\n```" } ] } } }, "/repos/{owner}/{repo}/transfer": { "post": { "summary": "Transfer a repository", "description": "A transfer request will need to be accepted by the new owner when transferring a personal repository to another user. The response will contain the original `owner`, and the transfer will continue asynchronously. For more details on the requirements to transfer personal and organization-owned repositories, see [about repository transfers](https://docs.github.com/articles/about-repository-transfers/).", "tags": [ "repos" ], "operationId": "repos/transfer", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/repos#transfer-a-repository" }, "parameters": [ { "$ref": "#/components/parameters/owner" }, { "$ref": "#/components/parameters/repo" } ], "requestBody": { "required": true, "content": { "application/json": { "schema": { "type": "object", "properties": { "new_owner": { "type": "string", "description": "The username or organization name the repository will be transferred to." }, "team_ids": { "type": "array", "description": "ID of the team or teams to add to the repository. Teams can only be added to organization-owned repositories.", "items": { "type": "integer" } } }, "required": [ "new_owner" ] }, "example": { "new_owner": "github", "team_ids": [ 12, 345 ] } } } }, "responses": { "202": { "description": "Response", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/minimal-repository" }, "examples": { "default": { "$ref": "#/components/examples/minimal-repository" } } } } } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": true, "category": "repos", "subcategory": null } } }, "/repos/{owner}/{repo}/zipball/{ref}": { "get": { "summary": "Download a repository archive (zip)", "description": "Gets a redirect URL to download a zip archive for a repository. If you omit `:ref`, the repository’s default branch (usually\n`master`) will be used. Please make sure your HTTP framework is configured to follow redirects or you will need to use\nthe `Location` header to make a second `GET` request.\n**Note**: For private repositories, these links are temporary and expire after five minutes.", "tags": [ "repos" ], "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/repos#download-a-repository-archive" }, "operationId": "repos/download-zipball-archive", "parameters": [ { "$ref": "#/components/parameters/owner" }, { "$ref": "#/components/parameters/repo" }, { "name": "ref", "in": "path", "required": true, "schema": { "type": "string" } } ], "responses": { "302": { "description": "Response", "headers": { "Location": { "example": "https://codeload.github.com/me/myprivate/legacy.zip/master?login=me&token=thistokenexpires", "schema": { "type": "string" } } } } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": true, "category": "repos", "subcategory": "contents" } } }, "/repos/{template_owner}/{template_repo}/generate": { "post": { "summary": "Create a repository using a template", "description": "Creates a new repository using a repository template. Use the `template_owner` and `template_repo` route parameters to specify the repository to use as the template. The authenticated user must own or be a member of an organization that owns the repository. To check if a repository is available to use as a template, get the repository's information using the [Get a repository](https://docs.github.com/enterprise-server@3.0/rest/reference/repos#get-a-repository) endpoint and check that the `is_template` key is `true`.\n\n**OAuth scope requirements**\n\nWhen using [OAuth](https://docs.github.com/enterprise-server@3.0/apps/building-oauth-apps/understanding-scopes-for-oauth-apps/), authorizations must include:\n\n* `public_repo` scope or `repo` scope to create a public repository. Note: For GitHub AE, use `repo` scope to create an internal repository.\n* `repo` scope to create a private repository", "tags": [ "repos" ], "operationId": "repos/create-using-template", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/repos#create-a-repository-using-a-template" }, "parameters": [ { "name": "template_owner", "in": "path", "required": true, "schema": { "type": "string" } }, { "name": "template_repo", "in": "path", "required": true, "schema": { "type": "string" } } ], "requestBody": { "required": true, "content": { "application/json": { "schema": { "type": "object", "properties": { "owner": { "type": "string", "description": "The organization or person who will own the new repository. To create a new repository in an organization, the authenticated user must be a member of the specified organization." }, "name": { "type": "string", "description": "The name of the new repository." }, "description": { "type": "string", "description": "A short description of the new repository." }, "include_all_branches": { "type": "boolean", "description": "Set to `true` to include the directory structure and files from all branches in the template repository, and not just the default branch. Default: `false`.", "default": false }, "private": { "type": "boolean", "description": "Either `true` to create a new private repository or `false` to create a new public one.", "default": false } }, "required": [ "name" ] }, "example": { "owner": "octocat", "name": "Hello-World", "description": "This is your first repository", "include_all_branches": false, "private": false } } } }, "responses": { "201": { "description": "Response", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/repository" }, "examples": { "default": { "$ref": "#/components/examples/repository-3" } } } }, "headers": { "Location": { "example": "https://api.github.com/repos/octocat/Hello-World", "schema": { "type": "string" } } } } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": false, "category": "repos", "previews": [ { "required": true, "name": "baptiste", "note": "Creating and using repository templates is currently available for developers to preview. To access this new endpoint during the preview period, you must provide a custom [media type](https://docs.github.com/enterprise-server@3.0/rest/overview/media-types) in the `Accept` header:\n\n```shell\napplication/vnd.github.baptiste-preview+json\n```" } ] } } }, "/repositories": { "get": { "summary": "List public repositories", "description": "Lists all public repositories in the order that they were created.\n\nNote:\n- For GitHub Enterprise Server, this endpoint will only list repositories available to all users on the enterprise.\n- Pagination is powered exclusively by the `since` parameter. Use the [Link header](https://docs.github.com/enterprise-server@3.0/rest/overview/resources-in-the-rest-api#link-header) to get the URL for the next page of repositories.", "tags": [ "repos" ], "operationId": "repos/list-public", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/repos#list-public-repositories" }, "parameters": [ { "$ref": "#/components/parameters/since-repo" }, { "name": "visibility", "description": "Specifies the types of repositories to return. Can be one of `all` or `public`. Default: `public`. Note: For GitHub Enterprise Server and GitHub AE, this endpoint will only list repositories available to all users on the enterprise.", "in": "query", "required": false, "schema": { "type": "string", "default": "public", "enum": [ "all", "public" ], "examples": [ "all" ] } } ], "responses": { "200": { "description": "Response", "content": { "application/json": { "schema": { "type": "array", "items": { "$ref": "#/components/schemas/minimal-repository" } }, "examples": { "default": { "$ref": "#/components/examples/public-repository-items" } } } }, "headers": { "Link": { "example": "; rel=\"next\"", "schema": { "type": "string" } } } }, "422": { "$ref": "#/components/responses/validation_failed" }, "304": { "$ref": "#/components/responses/not_modified" } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": true, "category": "repos", "subcategory": null } } }, "/search/code": { "get": { "summary": "Search code", "description": "Searches for query terms inside of a file. This method returns up to 100 results [per page](https://docs.github.com/enterprise-server@3.0/rest/overview/resources-in-the-rest-api#pagination).\n\nWhen searching for code, you can get text match metadata for the file **content** and file **path** fields when you pass the `text-match` media type. For more details about how to receive highlighted search results, see [Text match metadata](https://docs.github.com/enterprise-server@3.0/rest/reference/search#text-match-metadata).\n\nFor example, if you want to find the definition of the `addClass` function inside [jQuery](https://github.com/jquery/jquery) repository, your query would look something like this:\n\n`q=addClass+in:file+language:js+repo:jquery/jquery`\n\nThis query searches for the keyword `addClass` within a file's contents. The query limits the search to files where the language is JavaScript in the `jquery/jquery` repository.\n\n#### Considerations for code search\n\nDue to the complexity of searching code, there are a few restrictions on how searches are performed:\n\n* Only the _default branch_ is considered. In most cases, this will be the `master` branch.\n* Only files smaller than 384 KB are searchable.\n* You must always include at least one search term when searching source code. For example, searching for [`language:go`](https://github.com/search?utf8=%E2%9C%93&q=language%3Ago&type=Code) is not valid, while [`amazing\nlanguage:go`](https://github.com/search?utf8=%E2%9C%93&q=amazing+language%3Ago&type=Code) is.", "tags": [ "search" ], "operationId": "search/code", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/search#search-code" }, "parameters": [ { "name": "q", "description": "The query contains one or more search keywords and qualifiers. Qualifiers allow you to limit your search to specific areas of GitHub. The REST API supports the same qualifiers as GitHub.com. To learn more about the format of the query, see [Constructing a search query](https://docs.github.com/enterprise-server@3.0/rest/reference/search#constructing-a-search-query). See \"[Searching code](https://docs.github.com/articles/searching-code/)\" for a detailed list of qualifiers.", "in": "query", "required": true, "schema": { "type": "string" } }, { "name": "sort", "description": "Sorts the results of your query. Can only be `indexed`, which indicates how recently a file has been indexed by the GitHub Enterprise Server search infrastructure. Default: [best match](https://docs.github.com/enterprise-server@3.0/rest/reference/search#ranking-search-results)", "in": "query", "required": false, "schema": { "type": "string", "enum": [ "indexed" ] } }, { "$ref": "#/components/parameters/order" }, { "$ref": "#/components/parameters/per-page" }, { "$ref": "#/components/parameters/page" } ], "responses": { "200": { "description": "Response", "content": { "application/json": { "schema": { "type": "object", "required": [ "total_count", "incomplete_results", "items" ], "properties": { "total_count": { "type": "integer" }, "incomplete_results": { "type": "boolean" }, "items": { "type": "array", "items": { "$ref": "#/components/schemas/code-search-result-item" } } } }, "examples": { "default": { "$ref": "#/components/examples/code-search-result-item-paginated" } } } } }, "304": { "$ref": "#/components/responses/not_modified" }, "503": { "$ref": "#/components/responses/service_unavailable" }, "422": { "$ref": "#/components/responses/validation_failed" }, "403": { "$ref": "#/components/responses/forbidden" } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": true, "category": "search", "subcategory": null } } }, "/search/commits": { "get": { "summary": "Search commits", "description": "Find commits via various criteria on the default branch (usually `master`). This method returns up to 100 results [per page](https://docs.github.com/enterprise-server@3.0/rest/overview/resources-in-the-rest-api#pagination).\n\nWhen searching for commits, you can get text match metadata for the **message** field when you provide the `text-match` media type. For more details about how to receive highlighted search results, see [Text match\nmetadata](https://docs.github.com/enterprise-server@3.0/rest/reference/search#text-match-metadata).\n\nFor example, if you want to find commits related to CSS in the [octocat/Spoon-Knife](https://github.com/octocat/Spoon-Knife) repository. Your query would look something like this:\n\n`q=repo:octocat/Spoon-Knife+css`", "tags": [ "search" ], "operationId": "search/commits", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/search#search-commits" }, "parameters": [ { "name": "q", "description": "The query contains one or more search keywords and qualifiers. Qualifiers allow you to limit your search to specific areas of GitHub. The REST API supports the same qualifiers as GitHub.com. To learn more about the format of the query, see [Constructing a search query](https://docs.github.com/enterprise-server@3.0/rest/reference/search#constructing-a-search-query). See \"[Searching commits](https://docs.github.com/articles/searching-commits/)\" for a detailed list of qualifiers.", "in": "query", "required": true, "schema": { "type": "string" } }, { "name": "sort", "description": "Sorts the results of your query by `author-date` or `committer-date`. Default: [best match](https://docs.github.com/enterprise-server@3.0/rest/reference/search#ranking-search-results)", "in": "query", "required": false, "schema": { "type": "string", "enum": [ "author-date", "committer-date" ] } }, { "$ref": "#/components/parameters/order" }, { "$ref": "#/components/parameters/per-page" }, { "$ref": "#/components/parameters/page" } ], "responses": { "200": { "description": "Response", "content": { "application/json": { "schema": { "type": "object", "required": [ "total_count", "incomplete_results", "items" ], "properties": { "total_count": { "type": "integer" }, "incomplete_results": { "type": "boolean" }, "items": { "type": "array", "items": { "$ref": "#/components/schemas/commit-search-result-item" } } } }, "examples": { "default": { "$ref": "#/components/examples/commit-search-result-item-paginated" } } } } }, "304": { "$ref": "#/components/responses/not_modified" } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": true, "category": "search", "previews": [ { "required": true, "name": "cloak", "note": "The Commit Search API is currently available for developers to preview. During the preview period, the APIs may change without advance notice. Please see the [blog post](https://developer.github.com/changes/2017-01-05-commit-search-api/) for full details.\n\nTo access the API you must provide a custom [media type](https://docs.github.com/enterprise-server@3.0/rest/overview/media-types) in the `Accept` header:\n```shell\napplication/vnd.github.cloak-preview\n```" } ] } } }, "/search/issues": { "get": { "summary": "Search issues and pull requests", "description": "Find issues by state and keyword. This method returns up to 100 results [per page](https://docs.github.com/enterprise-server@3.0/rest/overview/resources-in-the-rest-api#pagination).\n\nWhen searching for issues, you can get text match metadata for the issue **title**, issue **body**, and issue **comment body** fields when you pass the `text-match` media type. For more details about how to receive highlighted\nsearch results, see [Text match metadata](https://docs.github.com/enterprise-server@3.0/rest/reference/search#text-match-metadata).\n\nFor example, if you want to find the oldest unresolved Python bugs on Windows. Your query might look something like this.\n\n`q=windows+label:bug+language:python+state:open&sort=created&order=asc`\n\nThis query searches for the keyword `windows`, within any open issue that is labeled as `bug`. The search runs across repositories whose primary language is Python. The results are sorted by creation date in ascending order, which means the oldest issues appear first in the search results.\n\n**Note:** For [user-to-server](https://docs.github.com/developers/apps/identifying-and-authorizing-users-for-github-apps#user-to-server-requests) GitHub App requests, you can't retrieve a combination of issues and pull requests in a single query. Requests that don't include the `is:issue` or `is:pull-request` qualifier will receive an HTTP `422 Unprocessable Entity` response. To get results for both issues and pull requests, you must send separate queries for issues and pull requests. For more information about the `is` qualifier, see \"[Searching only issues or pull requests](https://docs.github.com/github/searching-for-information-on-github/searching-issues-and-pull-requests#search-only-issues-or-pull-requests).\"", "tags": [ "search" ], "operationId": "search/issues-and-pull-requests", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/search#search-issues-and-pull-requests" }, "parameters": [ { "name": "q", "description": "The query contains one or more search keywords and qualifiers. Qualifiers allow you to limit your search to specific areas of GitHub. The REST API supports the same qualifiers as GitHub.com. To learn more about the format of the query, see [Constructing a search query](https://docs.github.com/enterprise-server@3.0/rest/reference/search#constructing-a-search-query). See \"[Searching issues and pull requests](https://docs.github.com/articles/searching-issues-and-pull-requests/)\" for a detailed list of qualifiers.", "in": "query", "required": true, "schema": { "type": "string" } }, { "name": "sort", "description": "Sorts the results of your query by the number of `comments`, `reactions`, `reactions-+1`, `reactions--1`, `reactions-smile`, `reactions-thinking_face`, `reactions-heart`, `reactions-tada`, or `interactions`. You can also sort results by how recently the items were `created` or `updated`, Default: [best match](https://docs.github.com/enterprise-server@3.0/rest/reference/search#ranking-search-results)", "in": "query", "required": false, "schema": { "type": "string", "enum": [ "comments", "reactions", "reactions-+1", "reactions--1", "reactions-smile", "reactions-thinking_face", "reactions-heart", "reactions-tada", "interactions", "created", "updated" ] } }, { "$ref": "#/components/parameters/order" }, { "$ref": "#/components/parameters/per-page" }, { "$ref": "#/components/parameters/page" } ], "responses": { "200": { "description": "Response", "content": { "application/json": { "schema": { "type": "object", "required": [ "total_count", "incomplete_results", "items" ], "properties": { "total_count": { "type": "integer" }, "incomplete_results": { "type": "boolean" }, "items": { "type": "array", "items": { "$ref": "#/components/schemas/issue-search-result-item" } } } }, "examples": { "default": { "$ref": "#/components/examples/issue-search-result-item-paginated" } } } } }, "503": { "$ref": "#/components/responses/service_unavailable" }, "422": { "$ref": "#/components/responses/validation_failed" }, "304": { "$ref": "#/components/responses/not_modified" }, "403": { "$ref": "#/components/responses/forbidden" } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": true, "category": "search", "subcategory": null } } }, "/search/labels": { "get": { "summary": "Search labels", "description": "Find labels in a repository with names or descriptions that match search keywords. Returns up to 100 results [per page](https://docs.github.com/enterprise-server@3.0/rest/overview/resources-in-the-rest-api#pagination).\n\nWhen searching for labels, you can get text match metadata for the label **name** and **description** fields when you pass the `text-match` media type. For more details about how to receive highlighted search results, see [Text match metadata](https://docs.github.com/enterprise-server@3.0/rest/reference/search#text-match-metadata).\n\nFor example, if you want to find labels in the `linguist` repository that match `bug`, `defect`, or `enhancement`. Your query might look like this:\n\n`q=bug+defect+enhancement&repository_id=64778136`\n\nThe labels that best match the query appear first in the search results.", "tags": [ "search" ], "operationId": "search/labels", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/search#search-labels" }, "parameters": [ { "name": "repository_id", "description": "The id of the repository.", "in": "query", "required": true, "schema": { "type": "integer" } }, { "name": "q", "description": "The search keywords. This endpoint does not accept qualifiers in the query. To learn more about the format of the query, see [Constructing a search query](https://docs.github.com/enterprise-server@3.0/rest/reference/search#constructing-a-search-query).", "in": "query", "required": true, "schema": { "type": "string" } }, { "name": "sort", "description": "Sorts the results of your query by when the label was `created` or `updated`. Default: [best match](https://docs.github.com/enterprise-server@3.0/rest/reference/search#ranking-search-results)", "in": "query", "required": false, "schema": { "type": "string", "enum": [ "created", "updated" ] } }, { "$ref": "#/components/parameters/order" }, { "$ref": "#/components/parameters/per-page" }, { "$ref": "#/components/parameters/page" } ], "responses": { "200": { "description": "Response", "content": { "application/json": { "schema": { "type": "object", "required": [ "total_count", "incomplete_results", "items" ], "properties": { "total_count": { "type": "integer" }, "incomplete_results": { "type": "boolean" }, "items": { "type": "array", "items": { "$ref": "#/components/schemas/label-search-result-item" } } } }, "examples": { "default": { "$ref": "#/components/examples/label-search-result-item-paginated" } } } } }, "304": { "$ref": "#/components/responses/not_modified" }, "404": { "$ref": "#/components/responses/not_found" }, "403": { "$ref": "#/components/responses/forbidden" }, "422": { "$ref": "#/components/responses/validation_failed" } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": true, "category": "search", "subcategory": null } } }, "/search/repositories": { "get": { "summary": "Search repositories", "description": "Find repositories via various criteria. This method returns up to 100 results [per page](https://docs.github.com/enterprise-server@3.0/rest/overview/resources-in-the-rest-api#pagination).\n\nWhen searching for repositories, you can get text match metadata for the **name** and **description** fields when you pass the `text-match` media type. For more details about how to receive highlighted search results, see [Text match metadata](https://docs.github.com/enterprise-server@3.0/rest/reference/search#text-match-metadata).\n\nFor example, if you want to search for popular Tetris repositories written in assembly code, your query might look like this:\n\n`q=tetris+language:assembly&sort=stars&order=desc`\n\nThis query searches for repositories with the word `tetris` in the name, the description, or the README. The results are limited to repositories where the primary language is assembly. The results are sorted by stars in descending order, so that the most popular repositories appear first in the search results.\n\nWhen you include the `mercy` preview header, you can also search for multiple topics by adding more `topic:` instances. For example, your query might look like this:\n\n`q=topic:ruby+topic:rails`", "tags": [ "search" ], "operationId": "search/repos", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/search#search-repositories" }, "parameters": [ { "name": "q", "description": "The query contains one or more search keywords and qualifiers. Qualifiers allow you to limit your search to specific areas of GitHub. The REST API supports the same qualifiers as GitHub.com. To learn more about the format of the query, see [Constructing a search query](https://docs.github.com/enterprise-server@3.0/rest/reference/search#constructing-a-search-query). See \"[Searching for repositories](https://docs.github.com/articles/searching-for-repositories/)\" for a detailed list of qualifiers.", "in": "query", "required": true, "schema": { "type": "string" } }, { "name": "sort", "description": "Sorts the results of your query by number of `stars`, `forks`, or `help-wanted-issues` or how recently the items were `updated`. Default: [best match](https://docs.github.com/enterprise-server@3.0/rest/reference/search#ranking-search-results)", "in": "query", "required": false, "schema": { "type": "string", "enum": [ "stars", "forks", "help-wanted-issues", "updated" ] } }, { "$ref": "#/components/parameters/order" }, { "$ref": "#/components/parameters/per-page" }, { "$ref": "#/components/parameters/page" } ], "responses": { "200": { "description": "Response", "content": { "application/json": { "schema": { "type": "object", "required": [ "total_count", "incomplete_results", "items" ], "properties": { "total_count": { "type": "integer" }, "incomplete_results": { "type": "boolean" }, "items": { "type": "array", "items": { "$ref": "#/components/schemas/repo-search-result-item" } } } }, "examples": { "default": { "$ref": "#/components/examples/repo-search-result-item-paginated" } } } } }, "503": { "$ref": "#/components/responses/service_unavailable" }, "422": { "$ref": "#/components/responses/validation_failed" }, "304": { "$ref": "#/components/responses/not_modified" } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": true, "category": "search", "previews": [ { "required": false, "name": "mercy", "note": "The `topics` property for repositories on GitHub is currently available for developers to preview. To view the `topics` property in calls that return repository results, you must provide a custom [media type](https://docs.github.com/enterprise-server@3.0/rest/overview/media-types) in the `Accept` header:\n```shell\napplication/vnd.github.mercy-preview+json\n```" } ] } } }, "/search/topics": { "get": { "summary": "Search topics", "description": "Find topics via various criteria. Results are sorted by best match. This method returns up to 100 results [per page](https://docs.github.com/enterprise-server@3.0/rest/overview/resources-in-the-rest-api#pagination). See \"[Searching topics](https://docs.github.com/articles/searching-topics/)\" for a detailed list of qualifiers.\n\nWhen searching for topics, you can get text match metadata for the topic's **short\\_description**, **description**, **name**, or **display\\_name** field when you pass the `text-match` media type. For more details about how to receive highlighted search results, see [Text match metadata](https://docs.github.com/enterprise-server@3.0/rest/reference/search#text-match-metadata).\n\nFor example, if you want to search for topics related to Ruby that are featured on https://github.com/topics. Your query might look like this:\n\n`q=ruby+is:featured`\n\nThis query searches for topics with the keyword `ruby` and limits the results to find only topics that are featured. The topics that are the best match for the query appear first in the search results.", "tags": [ "search" ], "operationId": "search/topics", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/search#search-topics" }, "parameters": [ { "name": "q", "description": "The query contains one or more search keywords and qualifiers. Qualifiers allow you to limit your search to specific areas of GitHub. The REST API supports the same qualifiers as GitHub.com. To learn more about the format of the query, see [Constructing a search query](https://docs.github.com/enterprise-server@3.0/rest/reference/search#constructing-a-search-query).", "in": "query", "required": true, "schema": { "type": "string" } }, { "$ref": "#/components/parameters/per-page" }, { "$ref": "#/components/parameters/page" } ], "responses": { "200": { "description": "Response", "content": { "application/json": { "schema": { "type": "object", "required": [ "total_count", "incomplete_results", "items" ], "properties": { "total_count": { "type": "integer" }, "incomplete_results": { "type": "boolean" }, "items": { "type": "array", "items": { "$ref": "#/components/schemas/topic-search-result-item" } } } }, "examples": { "default": { "$ref": "#/components/examples/topic-search-result-item-paginated" } } } } }, "304": { "$ref": "#/components/responses/not_modified" }, "415": { "$ref": "#/components/responses/preview_header_missing" } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": true, "category": "search", "previews": [ { "required": true, "name": "mercy", "note": "The `topics` property for repositories on GitHub is currently available for developers to preview. To view the `topics` property in calls that return repository results, you must provide a custom [media type](https://docs.github.com/enterprise-server@3.0/rest/overview/media-types) in the `Accept` header:\n```shell\napplication/vnd.github.mercy-preview+json\n```" } ] } } }, "/search/users": { "get": { "summary": "Search users", "description": "Find users via various criteria. This method returns up to 100 results [per page](https://docs.github.com/enterprise-server@3.0/rest/overview/resources-in-the-rest-api#pagination).\n\nWhen searching for users, you can get text match metadata for the issue **login**, **email**, and **name** fields when you pass the `text-match` media type. For more details about highlighting search results, see [Text match metadata](https://docs.github.com/enterprise-server@3.0/rest/reference/search#text-match-metadata). For more details about how to receive highlighted search results, see [Text match metadata](https://docs.github.com/enterprise-server@3.0/rest/reference/search#text-match-metadata).\n\nFor example, if you're looking for a list of popular users, you might try this query:\n\n`q=tom+repos:%3E42+followers:%3E1000`\n\nThis query searches for users with the name `tom`. The results are restricted to users with more than 42 repositories and over 1,000 followers.", "tags": [ "search" ], "operationId": "search/users", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/search#search-users" }, "parameters": [ { "name": "q", "description": "The query contains one or more search keywords and qualifiers. Qualifiers allow you to limit your search to specific areas of GitHub. The REST API supports the same qualifiers as GitHub.com. To learn more about the format of the query, see [Constructing a search query](https://docs.github.com/enterprise-server@3.0/rest/reference/search#constructing-a-search-query). See \"[Searching users](https://docs.github.com/articles/searching-users/)\" for a detailed list of qualifiers.", "in": "query", "required": true, "schema": { "type": "string" } }, { "name": "sort", "description": "Sorts the results of your query by number of `followers` or `repositories`, or when the person `joined` GitHub Enterprise Server. Default: [best match](https://docs.github.com/enterprise-server@3.0/rest/reference/search#ranking-search-results)", "in": "query", "required": false, "schema": { "type": "string", "enum": [ "followers", "repositories", "joined" ] } }, { "$ref": "#/components/parameters/order" }, { "$ref": "#/components/parameters/per-page" }, { "$ref": "#/components/parameters/page" } ], "responses": { "200": { "description": "Response", "content": { "application/json": { "schema": { "type": "object", "required": [ "total_count", "incomplete_results", "items" ], "properties": { "total_count": { "type": "integer" }, "incomplete_results": { "type": "boolean" }, "items": { "type": "array", "items": { "$ref": "#/components/schemas/user-search-result-item" } } } }, "examples": { "default": { "$ref": "#/components/examples/user-search-result-item-paginated" } } } } }, "304": { "$ref": "#/components/responses/not_modified" }, "503": { "$ref": "#/components/responses/service_unavailable" }, "422": { "$ref": "#/components/responses/validation_failed" } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": true, "category": "search", "subcategory": null } } }, "/setup/api/configcheck": { "get": { "summary": "Get the configuration status", "description": "This endpoint allows you to check the status of the most recent configuration process:\n\nNote that you may need to wait several seconds after you start a process before you can check its status.\n\nThe different statuses are:\n\n| Status | Description |\n| ------------- | --------------------------------- |\n| `PENDING` | The job has not started yet |\n| `CONFIGURING` | The job is running |\n| `DONE` | The job has finished correctly |\n| `FAILED` | The job has finished unexpectedly |", "operationId": "enterprise-admin/get-configuration-status", "tags": [ "enterprise-admin" ], "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/enterprise-admin#get-the-configuration-status" }, "responses": { "200": { "description": "Response", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/configuration-status" }, "examples": { "default": { "$ref": "#/components/examples/configuration-status" } } } } } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": false, "category": "enterprise-admin", "subcategory": "management-console" } } }, "/setup/api/configure": { "post": { "summary": "Start a configuration process", "description": "This endpoint allows you to start a configuration process at any time for your updated settings to take effect:", "operationId": "enterprise-admin/start-configuration-process", "tags": [ "enterprise-admin" ], "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/enterprise-admin#start-a-configuration-process" }, "responses": { "202": { "description": "Response" } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": false, "category": "enterprise-admin", "subcategory": "management-console" } } }, "/setup/api/maintenance": { "get": { "summary": "Get the maintenance status", "description": "Check your installation's maintenance status:", "operationId": "enterprise-admin/get-maintenance-status", "tags": [ "enterprise-admin" ], "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/enterprise-admin#get-the-maintenance-status" }, "responses": { "200": { "description": "Response", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/maintenance-status" }, "examples": { "default": { "$ref": "#/components/examples/maintenance-status" } } } } } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": false, "category": "enterprise-admin", "subcategory": "management-console" } }, "post": { "summary": "Enable or disable maintenance mode", "description": "**Note:** The request body for this operation must be submitted as `application/x-www-form-urlencoded` data. You can submit a parameter value as a string, or you can use a tool such as `curl` to submit a parameter value as the contents of a text file. For more information, see the [`curl` documentation](https://curl.se/docs/manpage.html#--data-urlencode).", "operationId": "enterprise-admin/enable-or-disable-maintenance-mode", "tags": [ "enterprise-admin" ], "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/enterprise-admin#enable-or-disable-maintenance-mode" }, "responses": { "200": { "description": "Response", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/maintenance-status" }, "examples": { "default": { "$ref": "#/components/examples/maintenance-status" } } } } } }, "requestBody": { "required": true, "content": { "application/x-www-form-urlencoded": { "schema": { "type": "object", "properties": { "maintenance": { "type": "string", "description": "A JSON string with the attributes `enabled` and `when`.\n\nThe possible values for `enabled` are `true` and `false`. When it's `false`, the attribute `when` is ignored and the maintenance mode is turned off. `when` defines the time period when the maintenance was enabled.\n\nThe possible values for `when` are `now` or any date parseable by [mojombo/chronic](https://github.com/mojombo/chronic)." } }, "required": [ "maintenance" ] }, "example": { "maintenance": "{\"enabled\":true, \"when\":\"now\"}" } } } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": false, "category": "enterprise-admin", "subcategory": "management-console" } } }, "/setup/api/settings": { "get": { "summary": "Get settings", "description": "", "operationId": "enterprise-admin/get-settings", "tags": [ "enterprise-admin" ], "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/enterprise-admin#get-settings" }, "responses": { "200": { "description": "Response", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/enterprise-settings" }, "examples": { "default": { "$ref": "#/components/examples/enterprise-settings" } } } } } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": false, "category": "enterprise-admin", "subcategory": "management-console" } }, "put": { "summary": "Set settings", "description": "For a list of the available settings, see the [Get settings endpoint](https://docs.github.com/enterprise-server@3.0/rest/reference/enterprise-admin#get-settings).\n\n**Note:** The request body for this operation must be submitted as `application/x-www-form-urlencoded` data. You can submit a parameter value as a string, or you can use a tool such as `curl` to submit a parameter value as the contents of a text file. For more information, see the [`curl` documentation](https://curl.se/docs/manpage.html#--data-urlencode).", "operationId": "enterprise-admin/set-settings", "tags": [ "enterprise-admin" ], "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/enterprise-admin#set-settings" }, "responses": { "204": { "description": "Response" } }, "requestBody": { "required": true, "content": { "application/x-www-form-urlencoded": { "schema": { "type": "object", "properties": { "settings": { "type": "string", "description": "A JSON string with the new settings. Note that you only need to pass the specific settings you want to modify. For a list of the available settings, see the [Get settings endpoint](https://docs.github.com/enterprise-server@3.0/rest/reference/enterprise-admin#get-settings)." } }, "required": [ "settings" ] }, "example": { "settings": "{ \"enterprise\": { \"public_pages\": true }}" } } } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": false, "category": "enterprise-admin", "subcategory": "management-console" } } }, "/setup/api/settings/authorized-keys": { "get": { "summary": "Get all authorized SSH keys", "description": "", "operationId": "enterprise-admin/get-all-authorized-ssh-keys", "tags": [ "enterprise-admin" ], "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/enterprise-admin#get-all-authorized-ssh-keys" }, "responses": { "200": { "description": "Response", "content": { "application/json": { "schema": { "type": "array", "items": { "$ref": "#/components/schemas/ssh-key" } }, "examples": { "default": { "$ref": "#/components/examples/ssh-key-items" } } } } } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": false, "category": "enterprise-admin", "subcategory": "management-console" } }, "post": { "summary": "Add an authorized SSH key", "description": "**Note:** The request body for this operation must be submitted as `application/x-www-form-urlencoded` data. You can submit a parameter value as a string, or you can use a tool such as `curl` to submit a parameter value as the contents of a text file. For more information, see the [`curl` documentation](https://curl.se/docs/manpage.html#--data-urlencode).", "operationId": "enterprise-admin/add-authorized-ssh-key", "tags": [ "enterprise-admin" ], "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/enterprise-admin#add-an-authorized-ssh-key" }, "responses": { "201": { "description": "Response", "content": { "application/json": { "schema": { "type": "array", "items": { "$ref": "#/components/schemas/ssh-key" } }, "examples": { "default": { "$ref": "#/components/examples/ssh-key-items" } } } } } }, "requestBody": { "required": true, "content": { "application/x-www-form-urlencoded": { "schema": { "type": "object", "properties": { "authorized_key": { "type": "string", "description": "The public SSH key." } }, "required": [ "authorized_key" ] }, "example": { "authorized_key": "ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAAAgQCssTL/Vtu/ODLTj0VtZoRAbvf7uiv5997GyDq0MoAZUjb5jmA5wYe2/wF6sFuhiZTnZoF1ZtCHunPp0hM/GHrn6VySBhNncx14YO8FPt1CIhEeRMSEjUK9cY3xAbS365oXY8vnUHJsS9+1tr/2bx/+4NJfcUt/Ezf1OR/0LStQXw==" } } } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": false, "category": "enterprise-admin", "subcategory": "management-console" } }, "delete": { "summary": "Remove an authorized SSH key", "description": "**Note:** The request body for this operation must be submitted as `application/x-www-form-urlencoded` data. You can submit a parameter value as a string, or you can use a tool such as `curl` to submit a parameter value as the contents of a text file. For more information, see the [`curl` documentation](https://curl.se/docs/manpage.html#--data-urlencode).", "operationId": "enterprise-admin/remove-authorized-ssh-key", "tags": [ "enterprise-admin" ], "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/enterprise-admin#remove-an-authorized-ssh-key" }, "responses": { "200": { "description": "Response", "content": { "application/json": { "schema": { "type": "array", "items": { "$ref": "#/components/schemas/ssh-key" } }, "examples": { "default": { "$ref": "#/components/examples/ssh-key-items" } } } } } }, "requestBody": { "required": true, "content": { "application/x-www-form-urlencoded": { "schema": { "type": "object", "properties": { "authorized_key": { "type": "string", "description": "The public SSH key." } }, "required": [ "authorized_key" ] }, "example": { "authorized_key": "ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAAAgQCssTL/Vtu/ODLTj0VtZoRAbvf7uiv5997GyDq0MoAZUjb5jmA5wYe2/wF6sFuhiZTnZoF1ZtCHunPp0hM/GHrn6VySBhNncx14YO8FPt1CIhEeRMSEjUK9cY3xAbS365oXY8vnUHJsS9+1tr/2bx/+4NJfcUt/Ezf1OR/0LStQXw==" } } } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": false, "category": "enterprise-admin", "subcategory": "management-console" } } }, "/setup/api/start": { "post": { "summary": "Create a GitHub license", "description": "When you boot a GitHub instance for the first time, you can use the following endpoint to upload a license.\n\nNote that you need to `POST` to [`/setup/api/configure`](https://docs.github.com/enterprise-server@3.0/rest/reference/enterprise-admin#start-a-configuration-process) to start the actual configuration process.\n\nWhen using this endpoint, your GitHub instance must have a password set. This can be accomplished two ways:\n\n1. If you're working directly with the API before accessing the web interface, you must pass in the password parameter to set your password.\n2. If you set up your instance via the web interface before accessing the API, your calls to this endpoint do not need the password parameter.\n\n**Note:** The request body for this operation must be submitted as `application/x-www-form-urlencoded` data. You can submit a parameter value as a string, or you can use a tool such as `curl` to submit a parameter value as the contents of a text file. For more information, see the [`curl` documentation](https://curl.se/docs/manpage.html#--data-urlencode).", "operationId": "enterprise-admin/create-enterprise-server-license", "tags": [ "enterprise-admin" ], "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/enterprise-admin#create-a-github-enterprise-server-license" }, "responses": { "202": { "description": "Response" } }, "requestBody": { "required": true, "content": { "application/x-www-form-urlencoded": { "schema": { "type": "object", "properties": { "license": { "type": "string", "description": "The content of your _.ghl_ license file." }, "password": { "type": "string", "description": "You **must** provide a password _only if_ you are uploading your license for the first time. If you previously set a password through the web interface, you don't need this parameter." }, "settings": { "type": "string", "description": "An optional JSON string containing the installation settings. For a list of the available settings, see the [Get settings endpoint](https://docs.github.com/enterprise-server@3.0/rest/reference/enterprise-admin#get-settings)." } }, "required": [ "license" ] } } } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": false, "category": "enterprise-admin", "subcategory": "management-console" } } }, "/setup/api/upgrade": { "post": { "summary": "Upgrade a license", "description": "This API upgrades your license and also triggers the configuration process.\n\n**Note:** The request body for this operation must be submitted as `application/x-www-form-urlencoded` data. You can submit a parameter value as a string, or you can use a tool such as `curl` to submit a parameter value as the contents of a text file. For more information, see the [`curl` documentation](https://curl.se/docs/manpage.html#--data-urlencode).", "operationId": "enterprise-admin/upgrade-license", "tags": [ "enterprise-admin" ], "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/enterprise-admin#upgrade-a-license" }, "responses": { "202": { "description": "Response" } }, "requestBody": { "content": { "application/x-www-form-urlencoded": { "schema": { "type": "object", "properties": { "license": { "type": "string", "description": "The content of your new _.ghl_ license file." } } } } } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": false, "category": "enterprise-admin", "subcategory": "management-console" } } }, "/teams/{team_id}": { "get": { "summary": "Get a team (Legacy)", "description": "**Deprecation Notice:** This endpoint route is deprecated and will be removed from the Teams API. We recommend migrating your existing code to use the [Get a team by name](https://docs.github.com/enterprise-server@3.0/rest/reference/teams#get-a-team-by-name) endpoint.", "tags": [ "teams" ], "operationId": "teams/get-legacy", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/teams/#get-a-team-legacy" }, "parameters": [ { "$ref": "#/components/parameters/team-id" } ], "responses": { "200": { "description": "Response", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/team-full" }, "examples": { "default": { "$ref": "#/components/examples/team-full" } } } } }, "404": { "$ref": "#/components/responses/not_found" } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": true, "removalDate": "2021-02-01", "deprecationDate": "2020-01-21", "category": "teams", "subcategory": null }, "deprecated": true }, "patch": { "summary": "Update a team (Legacy)", "description": "**Deprecation Notice:** This endpoint route is deprecated and will be removed from the Teams API. We recommend migrating your existing code to use the new [Update a team](https://docs.github.com/enterprise-server@3.0/rest/reference/teams#update-a-team) endpoint.\n\nTo edit a team, the authenticated user must either be an organization owner or a team maintainer.\n\n**Note:** With nested teams, the `privacy` for parent teams cannot be `secret`.", "tags": [ "teams" ], "operationId": "teams/update-legacy", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/teams/#update-a-team-legacy" }, "parameters": [ { "$ref": "#/components/parameters/team-id" } ], "requestBody": { "required": true, "content": { "application/json": { "schema": { "type": "object", "properties": { "name": { "type": "string", "description": "The name of the team." }, "description": { "type": "string", "description": "The description of the team." }, "privacy": { "type": "string", "description": "The level of privacy this team should have. Editing teams without specifying this parameter leaves `privacy` intact. The options are: \n**For a non-nested team:** \n\\* `secret` - only visible to organization owners and members of this team. \n\\* `closed` - visible to all members of this organization. \n**For a parent or child team:** \n\\* `closed` - visible to all members of this organization.", "enum": [ "secret", "closed" ] }, "permission": { "type": "string", "description": "**Deprecated**. The permission that new repositories will be added to the team with when none is specified. Can be one of: \n\\* `pull` - team members can pull, but not push to or administer newly-added repositories. \n\\* `push` - team members can pull and push, but not administer newly-added repositories. \n\\* `admin` - team members can pull, push and administer newly-added repositories.", "enum": [ "pull", "push", "admin" ], "default": "pull" }, "parent_team_id": { "type": [ "integer", "null" ], "description": "The ID of a team to set as the parent team." } }, "required": [ "name" ] }, "example": { "name": "new team name", "description": "new team description", "privacy": "closed" } } } }, "responses": { "200": { "description": "Response", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/team-full" }, "examples": { "default": { "$ref": "#/components/examples/team-full" } } } } }, "201": { "description": "Response", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/team-full" }, "examples": { "default": { "$ref": "#/components/examples/team-full" } } } } }, "404": { "$ref": "#/components/responses/not_found" }, "422": { "$ref": "#/components/responses/validation_failed" }, "403": { "$ref": "#/components/responses/forbidden" } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": true, "removalDate": "2021-02-01", "deprecationDate": "2020-01-21", "category": "teams", "subcategory": null }, "deprecated": true }, "delete": { "summary": "Delete a team (Legacy)", "description": "**Deprecation Notice:** This endpoint route is deprecated and will be removed from the Teams API. We recommend migrating your existing code to use the new [Delete a team](https://docs.github.com/enterprise-server@3.0/rest/reference/teams#delete-a-team) endpoint.\n\nTo delete a team, the authenticated user must be an organization owner or team maintainer.\n\nIf you are an organization owner, deleting a parent team will delete all of its child teams as well.", "tags": [ "teams" ], "operationId": "teams/delete-legacy", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/teams/#delete-a-team-legacy" }, "parameters": [ { "$ref": "#/components/parameters/team-id" } ], "responses": { "204": { "description": "Response" }, "404": { "$ref": "#/components/responses/not_found" }, "422": { "$ref": "#/components/responses/validation_failed" } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": true, "removalDate": "2021-02-01", "deprecationDate": "2020-01-21", "category": "teams", "subcategory": null }, "deprecated": true } }, "/teams/{team_id}/discussions": { "get": { "summary": "List discussions (Legacy)", "description": "**Deprecation Notice:** This endpoint route is deprecated and will be removed from the Teams API. We recommend migrating your existing code to use the new [`List discussions`](https://docs.github.com/enterprise-server@3.0/rest/reference/teams#list-discussions) endpoint.\n\nList all discussions on a team's page. OAuth access tokens require the `read:discussion` [scope](https://docs.github.com/enterprise-server@3.0/apps/building-oauth-apps/understanding-scopes-for-oauth-apps/).", "tags": [ "teams" ], "operationId": "teams/list-discussions-legacy", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/teams#list-discussions-legacy" }, "parameters": [ { "$ref": "#/components/parameters/team-id" }, { "$ref": "#/components/parameters/direction" }, { "$ref": "#/components/parameters/per-page" }, { "$ref": "#/components/parameters/page" } ], "responses": { "200": { "description": "Response", "content": { "application/json": { "schema": { "type": "array", "items": { "$ref": "#/components/schemas/team-discussion" } }, "examples": { "default": { "$ref": "#/components/examples/team-discussion-items" } } } }, "headers": { "Link": { "$ref": "#/components/headers/link" } } } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": true, "removalDate": "2021-02-01", "deprecationDate": "2020-01-21", "category": "teams", "subcategory": "discussions", "previews": [ { "required": false, "name": "squirrel-girl", "note": "An additional `reactions` object in the issue comment payload is currently available for developers to preview. During the preview period, the APIs may change without advance notice. Please see the [blog post](https://developer.github.com/changes/2016-05-12-reactions-api-preview) for full details.\n\nTo access the API you must provide a custom [media type](https://docs.github.com/enterprise-server@3.0/rest/overview/media-types) in the `Accept` header:\n```shell\napplication/vnd.github.squirrel-girl-preview\n```\nThe `reactions` key will have the following payload where `url` can be used to construct the API location for [listing and creating](https://docs.github.com/enterprise-server@3.0/rest/reference/reactions) reactions." } ] }, "deprecated": true }, "post": { "summary": "Create a discussion (Legacy)", "description": "**Deprecation Notice:** This endpoint route is deprecated and will be removed from the Teams API. We recommend migrating your existing code to use the new [`Create a discussion`](https://docs.github.com/enterprise-server@3.0/rest/reference/teams#create-a-discussion) endpoint.\n\nCreates a new discussion post on a team's page. OAuth access tokens require the `write:discussion` [scope](https://docs.github.com/enterprise-server@3.0/apps/building-oauth-apps/understanding-scopes-for-oauth-apps/).\n\nThis endpoint triggers [notifications](https://docs.github.com/en/github/managing-subscriptions-and-notifications-on-github/about-notifications). Creating content too quickly using this endpoint may result in secondary rate limiting. See \"[Secondary rate limits](https://docs.github.com/enterprise-server@3.0/rest/overview/resources-in-the-rest-api#secondary-rate-limits)\" and \"[Dealing with secondary rate limits](https://docs.github.com/enterprise-server@3.0/rest/guides/best-practices-for-integrators#dealing-with-secondary-rate-limits)\" for details.", "tags": [ "teams" ], "operationId": "teams/create-discussion-legacy", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/teams#create-a-discussion-legacy" }, "parameters": [ { "$ref": "#/components/parameters/team-id" } ], "requestBody": { "required": true, "content": { "application/json": { "schema": { "type": "object", "properties": { "title": { "type": "string", "description": "The discussion post's title." }, "body": { "type": "string", "description": "The discussion post's body text." }, "private": { "type": "boolean", "description": "Private posts are only visible to team members, organization owners, and team maintainers. Public posts are visible to all members of the organization. Set to `true` to create a private post.", "default": false } }, "required": [ "title", "body" ] }, "example": { "title": "Our first team post", "body": "Hi! This is an area for us to collaborate as a team." } } } }, "responses": { "201": { "description": "Response", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/team-discussion" }, "examples": { "default": { "$ref": "#/components/examples/team-discussion" } } } } } }, "x-github": { "triggersNotification": true, "githubCloudOnly": false, "enabledForGitHubApps": true, "removalDate": "2021-02-01", "deprecationDate": "2020-01-21", "category": "teams", "subcategory": "discussions", "previews": [ { "required": false, "name": "squirrel-girl", "note": "An additional `reactions` object in the issue comment payload is currently available for developers to preview. During the preview period, the APIs may change without advance notice. Please see the [blog post](https://developer.github.com/changes/2016-05-12-reactions-api-preview) for full details.\n\nTo access the API you must provide a custom [media type](https://docs.github.com/enterprise-server@3.0/rest/overview/media-types) in the `Accept` header:\n```shell\napplication/vnd.github.squirrel-girl-preview\n```\nThe `reactions` key will have the following payload where `url` can be used to construct the API location for [listing and creating](https://docs.github.com/enterprise-server@3.0/rest/reference/reactions) reactions." } ] }, "deprecated": true } }, "/teams/{team_id}/discussions/{discussion_number}": { "get": { "summary": "Get a discussion (Legacy)", "description": "**Deprecation Notice:** This endpoint route is deprecated and will be removed from the Teams API. We recommend migrating your existing code to use the new [Get a discussion](https://docs.github.com/enterprise-server@3.0/rest/reference/teams#get-a-discussion) endpoint.\n\nGet a specific discussion on a team's page. OAuth access tokens require the `read:discussion` [scope](https://docs.github.com/enterprise-server@3.0/apps/building-oauth-apps/understanding-scopes-for-oauth-apps/).", "tags": [ "teams" ], "operationId": "teams/get-discussion-legacy", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/teams#get-a-discussion-legacy" }, "parameters": [ { "$ref": "#/components/parameters/team-id" }, { "$ref": "#/components/parameters/discussion-number" } ], "responses": { "200": { "description": "Response", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/team-discussion" }, "examples": { "default": { "$ref": "#/components/examples/team-discussion" } } } } } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": true, "removalDate": "2021-02-01", "deprecationDate": "2020-01-21", "category": "teams", "subcategory": "discussions", "previews": [ { "required": false, "name": "squirrel-girl", "note": "An additional `reactions` object in the issue comment payload is currently available for developers to preview. During the preview period, the APIs may change without advance notice. Please see the [blog post](https://developer.github.com/changes/2016-05-12-reactions-api-preview) for full details.\n\nTo access the API you must provide a custom [media type](https://docs.github.com/enterprise-server@3.0/rest/overview/media-types) in the `Accept` header:\n```shell\napplication/vnd.github.squirrel-girl-preview\n```\nThe `reactions` key will have the following payload where `url` can be used to construct the API location for [listing and creating](https://docs.github.com/enterprise-server@3.0/rest/reference/reactions) reactions." } ] }, "deprecated": true }, "patch": { "summary": "Update a discussion (Legacy)", "description": "**Deprecation Notice:** This endpoint route is deprecated and will be removed from the Teams API. We recommend migrating your existing code to use the new [Update a discussion](https://docs.github.com/enterprise-server@3.0/rest/reference/teams#update-a-discussion) endpoint.\n\nEdits the title and body text of a discussion post. Only the parameters you provide are updated. OAuth access tokens require the `write:discussion` [scope](https://docs.github.com/enterprise-server@3.0/apps/building-oauth-apps/understanding-scopes-for-oauth-apps/).", "tags": [ "teams" ], "operationId": "teams/update-discussion-legacy", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/teams#update-a-discussion-legacy" }, "parameters": [ { "$ref": "#/components/parameters/team-id" }, { "$ref": "#/components/parameters/discussion-number" } ], "requestBody": { "required": false, "content": { "application/json": { "schema": { "type": "object", "properties": { "title": { "type": "string", "description": "The discussion post's title." }, "body": { "type": "string", "description": "The discussion post's body text." } } }, "example": { "title": "Welcome to our first team post" } } } }, "responses": { "200": { "description": "Response", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/team-discussion" }, "examples": { "default": { "$ref": "#/components/examples/team-discussion-2" } } } } } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": true, "removalDate": "2021-02-01", "deprecationDate": "2020-01-21", "category": "teams", "subcategory": "discussions", "previews": [ { "required": false, "name": "squirrel-girl", "note": "An additional `reactions` object in the issue comment payload is currently available for developers to preview. During the preview period, the APIs may change without advance notice. Please see the [blog post](https://developer.github.com/changes/2016-05-12-reactions-api-preview) for full details.\n\nTo access the API you must provide a custom [media type](https://docs.github.com/enterprise-server@3.0/rest/overview/media-types) in the `Accept` header:\n```shell\napplication/vnd.github.squirrel-girl-preview\n```\nThe `reactions` key will have the following payload where `url` can be used to construct the API location for [listing and creating](https://docs.github.com/enterprise-server@3.0/rest/reference/reactions) reactions." } ] }, "deprecated": true }, "delete": { "summary": "Delete a discussion (Legacy)", "description": "**Deprecation Notice:** This endpoint route is deprecated and will be removed from the Teams API. We recommend migrating your existing code to use the new [`Delete a discussion`](https://docs.github.com/enterprise-server@3.0/rest/reference/teams#delete-a-discussion) endpoint.\n\nDelete a discussion from a team's page. OAuth access tokens require the `write:discussion` [scope](https://docs.github.com/enterprise-server@3.0/apps/building-oauth-apps/understanding-scopes-for-oauth-apps/).", "tags": [ "teams" ], "operationId": "teams/delete-discussion-legacy", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/teams#delete-a-discussion-legacy" }, "parameters": [ { "$ref": "#/components/parameters/team-id" }, { "$ref": "#/components/parameters/discussion-number" } ], "responses": { "204": { "description": "Response" } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": true, "removalDate": "2021-02-01", "deprecationDate": "2020-01-21", "category": "teams", "subcategory": "discussions" }, "deprecated": true } }, "/teams/{team_id}/discussions/{discussion_number}/comments": { "get": { "summary": "List discussion comments (Legacy)", "description": "**Deprecation Notice:** This endpoint route is deprecated and will be removed from the Teams API. We recommend migrating your existing code to use the new [List discussion comments](https://docs.github.com/enterprise-server@3.0/rest/reference/teams#list-discussion-comments) endpoint.\n\nList all comments on a team discussion. OAuth access tokens require the `read:discussion` [scope](https://docs.github.com/enterprise-server@3.0/apps/building-oauth-apps/understanding-scopes-for-oauth-apps/).", "tags": [ "teams" ], "operationId": "teams/list-discussion-comments-legacy", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/teams#list-discussion-comments-legacy" }, "parameters": [ { "$ref": "#/components/parameters/team-id" }, { "$ref": "#/components/parameters/discussion-number" }, { "$ref": "#/components/parameters/direction" }, { "$ref": "#/components/parameters/per-page" }, { "$ref": "#/components/parameters/page" } ], "responses": { "200": { "description": "Response", "content": { "application/json": { "schema": { "type": "array", "items": { "$ref": "#/components/schemas/team-discussion-comment" } }, "examples": { "default": { "$ref": "#/components/examples/team-discussion-comment-items" } } } }, "headers": { "Link": { "$ref": "#/components/headers/link" } } } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": true, "removalDate": "2021-02-01", "deprecationDate": "2020-01-21", "category": "teams", "subcategory": "discussion-comments", "previews": [ { "required": false, "name": "squirrel-girl", "note": "An additional `reactions` object in the issue comment payload is currently available for developers to preview. During the preview period, the APIs may change without advance notice. Please see the [blog post](https://developer.github.com/changes/2016-05-12-reactions-api-preview) for full details.\n\nTo access the API you must provide a custom [media type](https://docs.github.com/enterprise-server@3.0/rest/overview/media-types) in the `Accept` header:\n```shell\napplication/vnd.github.squirrel-girl-preview\n```\nThe `reactions` key will have the following payload where `url` can be used to construct the API location for [listing and creating](https://docs.github.com/enterprise-server@3.0/rest/reference/reactions) reactions." } ] }, "deprecated": true }, "post": { "summary": "Create a discussion comment (Legacy)", "description": "**Deprecation Notice:** This endpoint route is deprecated and will be removed from the Teams API. We recommend migrating your existing code to use the new [Create a discussion comment](https://docs.github.com/enterprise-server@3.0/rest/reference/teams#create-a-discussion-comment) endpoint.\n\nCreates a new comment on a team discussion. OAuth access tokens require the `write:discussion` [scope](https://docs.github.com/enterprise-server@3.0/apps/building-oauth-apps/understanding-scopes-for-oauth-apps/).\n\nThis endpoint triggers [notifications](https://docs.github.com/en/github/managing-subscriptions-and-notifications-on-github/about-notifications). Creating content too quickly using this endpoint may result in secondary rate limiting. See \"[Secondary rate limits](https://docs.github.com/enterprise-server@3.0/rest/overview/resources-in-the-rest-api#secondary-rate-limits)\" and \"[Dealing with secondary rate limits](https://docs.github.com/enterprise-server@3.0/rest/guides/best-practices-for-integrators#dealing-with-secondary-rate-limits)\" for details.", "tags": [ "teams" ], "operationId": "teams/create-discussion-comment-legacy", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/teams#create-a-discussion-comment-legacy" }, "parameters": [ { "$ref": "#/components/parameters/team-id" }, { "$ref": "#/components/parameters/discussion-number" } ], "requestBody": { "required": true, "content": { "application/json": { "schema": { "type": "object", "properties": { "body": { "type": "string", "description": "The discussion comment's body text." } }, "required": [ "body" ] }, "example": { "body": "Do you like apples?" } } } }, "responses": { "201": { "description": "Response", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/team-discussion-comment" }, "examples": { "default": { "$ref": "#/components/examples/team-discussion-comment" } } } } } }, "x-github": { "triggersNotification": true, "githubCloudOnly": false, "enabledForGitHubApps": true, "removalDate": "2021-02-01", "deprecationDate": "2020-01-21", "category": "teams", "subcategory": "discussion-comments", "previews": [ { "required": false, "name": "squirrel-girl", "note": "An additional `reactions` object in the issue comment payload is currently available for developers to preview. During the preview period, the APIs may change without advance notice. Please see the [blog post](https://developer.github.com/changes/2016-05-12-reactions-api-preview) for full details.\n\nTo access the API you must provide a custom [media type](https://docs.github.com/enterprise-server@3.0/rest/overview/media-types) in the `Accept` header:\n```shell\napplication/vnd.github.squirrel-girl-preview\n```\nThe `reactions` key will have the following payload where `url` can be used to construct the API location for [listing and creating](https://docs.github.com/enterprise-server@3.0/rest/reference/reactions) reactions." } ] }, "deprecated": true } }, "/teams/{team_id}/discussions/{discussion_number}/comments/{comment_number}": { "get": { "summary": "Get a discussion comment (Legacy)", "description": "**Deprecation Notice:** This endpoint route is deprecated and will be removed from the Teams API. We recommend migrating your existing code to use the new [Get a discussion comment](https://docs.github.com/enterprise-server@3.0/rest/reference/teams#get-a-discussion-comment) endpoint.\n\nGet a specific comment on a team discussion. OAuth access tokens require the `read:discussion` [scope](https://docs.github.com/enterprise-server@3.0/apps/building-oauth-apps/understanding-scopes-for-oauth-apps/).", "tags": [ "teams" ], "operationId": "teams/get-discussion-comment-legacy", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/teams#get-a-discussion-comment-legacy" }, "parameters": [ { "$ref": "#/components/parameters/team-id" }, { "$ref": "#/components/parameters/discussion-number" }, { "$ref": "#/components/parameters/comment-number" } ], "responses": { "200": { "description": "Response", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/team-discussion-comment" }, "examples": { "default": { "$ref": "#/components/examples/team-discussion-comment" } } } } } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": true, "removalDate": "2021-02-01", "deprecationDate": "2020-01-21", "category": "teams", "subcategory": "discussion-comments", "previews": [ { "required": false, "name": "squirrel-girl", "note": "An additional `reactions` object in the issue comment payload is currently available for developers to preview. During the preview period, the APIs may change without advance notice. Please see the [blog post](https://developer.github.com/changes/2016-05-12-reactions-api-preview) for full details.\n\nTo access the API you must provide a custom [media type](https://docs.github.com/enterprise-server@3.0/rest/overview/media-types) in the `Accept` header:\n```shell\napplication/vnd.github.squirrel-girl-preview\n```\nThe `reactions` key will have the following payload where `url` can be used to construct the API location for [listing and creating](https://docs.github.com/enterprise-server@3.0/rest/reference/reactions) reactions." } ] }, "deprecated": true }, "patch": { "summary": "Update a discussion comment (Legacy)", "description": "**Deprecation Notice:** This endpoint route is deprecated and will be removed from the Teams API. We recommend migrating your existing code to use the new [Update a discussion comment](https://docs.github.com/enterprise-server@3.0/rest/reference/teams#update-a-discussion-comment) endpoint.\n\nEdits the body text of a discussion comment. OAuth access tokens require the `write:discussion` [scope](https://docs.github.com/enterprise-server@3.0/apps/building-oauth-apps/understanding-scopes-for-oauth-apps/).", "tags": [ "teams" ], "operationId": "teams/update-discussion-comment-legacy", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/teams#update-a-discussion-comment-legacy" }, "parameters": [ { "$ref": "#/components/parameters/team-id" }, { "$ref": "#/components/parameters/discussion-number" }, { "$ref": "#/components/parameters/comment-number" } ], "requestBody": { "required": true, "content": { "application/json": { "schema": { "type": "object", "properties": { "body": { "type": "string", "description": "The discussion comment's body text." } }, "required": [ "body" ] }, "example": { "body": "Do you like pineapples?" } } } }, "responses": { "200": { "description": "Response", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/team-discussion-comment" }, "examples": { "default": { "$ref": "#/components/examples/team-discussion-comment-2" } } } } } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": true, "removalDate": "2021-02-01", "deprecationDate": "2020-01-21", "category": "teams", "subcategory": "discussion-comments", "previews": [ { "required": false, "name": "squirrel-girl", "note": "An additional `reactions` object in the issue comment payload is currently available for developers to preview. During the preview period, the APIs may change without advance notice. Please see the [blog post](https://developer.github.com/changes/2016-05-12-reactions-api-preview) for full details.\n\nTo access the API you must provide a custom [media type](https://docs.github.com/enterprise-server@3.0/rest/overview/media-types) in the `Accept` header:\n```shell\napplication/vnd.github.squirrel-girl-preview\n```\nThe `reactions` key will have the following payload where `url` can be used to construct the API location for [listing and creating](https://docs.github.com/enterprise-server@3.0/rest/reference/reactions) reactions." } ] }, "deprecated": true }, "delete": { "summary": "Delete a discussion comment (Legacy)", "description": "**Deprecation Notice:** This endpoint route is deprecated and will be removed from the Teams API. We recommend migrating your existing code to use the new [Delete a discussion comment](https://docs.github.com/enterprise-server@3.0/rest/reference/teams#delete-a-discussion-comment) endpoint.\n\nDeletes a comment on a team discussion. OAuth access tokens require the `write:discussion` [scope](https://docs.github.com/enterprise-server@3.0/apps/building-oauth-apps/understanding-scopes-for-oauth-apps/).", "tags": [ "teams" ], "operationId": "teams/delete-discussion-comment-legacy", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/teams#delete-a-discussion-comment-legacy" }, "parameters": [ { "$ref": "#/components/parameters/team-id" }, { "$ref": "#/components/parameters/discussion-number" }, { "$ref": "#/components/parameters/comment-number" } ], "responses": { "204": { "description": "Response" } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": true, "removalDate": "2021-02-01", "deprecationDate": "2020-01-21", "category": "teams", "subcategory": "discussion-comments" }, "deprecated": true } }, "/teams/{team_id}/discussions/{discussion_number}/comments/{comment_number}/reactions": { "get": { "summary": "List reactions for a team discussion comment (Legacy)", "description": "**Deprecation Notice:** This endpoint route is deprecated and will be removed from the Teams API. We recommend migrating your existing code to use the new [`List reactions for a team discussion comment`](https://docs.github.com/enterprise-server@3.0/rest/reference/reactions#list-reactions-for-a-team-discussion-comment) endpoint.\n\nList the reactions to a [team discussion comment](https://docs.github.com/enterprise-server@3.0/rest/reference/teams#discussion-comments). OAuth access tokens require the `read:discussion` [scope](https://docs.github.com/enterprise-server@3.0/apps/building-oauth-apps/understanding-scopes-for-oauth-apps/).", "tags": [ "reactions" ], "operationId": "reactions/list-for-team-discussion-comment-legacy", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/reactions/#list-reactions-for-a-team-discussion-comment-legacy" }, "parameters": [ { "$ref": "#/components/parameters/team-id" }, { "$ref": "#/components/parameters/discussion-number" }, { "$ref": "#/components/parameters/comment-number" }, { "name": "content", "description": "Returns a single [reaction type](https://docs.github.com/enterprise-server@3.0/rest/reference/reactions#reaction-types). Omit this parameter to list all reactions to a team discussion comment.", "in": "query", "required": false, "schema": { "type": "string", "enum": [ "+1", "-1", "laugh", "confused", "heart", "hooray", "rocket", "eyes" ] } }, { "$ref": "#/components/parameters/per-page" }, { "$ref": "#/components/parameters/page" } ], "responses": { "200": { "description": "Response", "content": { "application/json": { "schema": { "type": "array", "items": { "$ref": "#/components/schemas/reaction" } }, "examples": { "default": { "$ref": "#/components/examples/reaction-items" } } } }, "headers": { "Link": { "$ref": "#/components/headers/link" } } } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": true, "removalDate": "2021-02-21", "deprecationDate": "2020-02-26", "category": "reactions", "previews": [ { "required": true, "name": "squirrel-girl", "note": "An additional `reactions` object in the issue comment payload is currently available for developers to preview. During the preview period, the APIs may change without advance notice. Please see the [blog post](https://developer.github.com/changes/2016-05-12-reactions-api-preview) for full details.\n\nTo access the API you must provide a custom [media type](https://docs.github.com/enterprise-server@3.0/rest/overview/media-types) in the `Accept` header:\n```shell\napplication/vnd.github.squirrel-girl-preview\n```\nThe `reactions` key will have the following payload where `url` can be used to construct the API location for [listing and creating](https://docs.github.com/enterprise-server@3.0/rest/reference/reactions) reactions." } ] }, "deprecated": true }, "post": { "summary": "Create reaction for a team discussion comment (Legacy)", "description": "**Deprecation Notice:** This endpoint route is deprecated and will be removed from the Teams API. We recommend migrating your existing code to use the new \"[Create reaction for a team discussion comment](https://docs.github.com/enterprise-server@3.0/rest/reference/reactions#create-reaction-for-a-team-discussion-comment)\" endpoint.\n\nCreate a reaction to a [team discussion comment](https://docs.github.com/enterprise-server@3.0/rest/reference/teams#discussion-comments). OAuth access tokens require the `write:discussion` [scope](https://docs.github.com/enterprise-server@3.0/apps/building-oauth-apps/understanding-scopes-for-oauth-apps/). A response with an HTTP `200` status means that you already added the reaction type to this team discussion comment.", "tags": [ "reactions" ], "operationId": "reactions/create-for-team-discussion-comment-legacy", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/reactions/#create-reaction-for-a-team-discussion-comment-legacy" }, "parameters": [ { "$ref": "#/components/parameters/team-id" }, { "$ref": "#/components/parameters/discussion-number" }, { "$ref": "#/components/parameters/comment-number" } ], "requestBody": { "required": true, "content": { "application/json": { "schema": { "type": "object", "properties": { "content": { "type": "string", "description": "The [reaction type](https://docs.github.com/enterprise-server@3.0/rest/reference/reactions#reaction-types) to add to the team discussion comment.", "enum": [ "+1", "-1", "laugh", "confused", "heart", "hooray", "rocket", "eyes" ] } }, "required": [ "content" ] }, "example": { "content": "heart" } } } }, "responses": { "201": { "description": "Response", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/reaction" }, "examples": { "default": { "$ref": "#/components/examples/reaction" } } } } } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": true, "removalDate": "2021-02-21", "deprecationDate": "2020-02-26", "category": "reactions", "previews": [ { "required": true, "name": "squirrel-girl", "note": "An additional `reactions` object in the issue comment payload is currently available for developers to preview. During the preview period, the APIs may change without advance notice. Please see the [blog post](https://developer.github.com/changes/2016-05-12-reactions-api-preview) for full details.\n\nTo access the API you must provide a custom [media type](https://docs.github.com/enterprise-server@3.0/rest/overview/media-types) in the `Accept` header:\n```shell\napplication/vnd.github.squirrel-girl-preview\n```\nThe `reactions` key will have the following payload where `url` can be used to construct the API location for [listing and creating](https://docs.github.com/enterprise-server@3.0/rest/reference/reactions) reactions." } ] }, "deprecated": true } }, "/teams/{team_id}/discussions/{discussion_number}/reactions": { "get": { "summary": "List reactions for a team discussion (Legacy)", "description": "**Deprecation Notice:** This endpoint route is deprecated and will be removed from the Teams API. We recommend migrating your existing code to use the new [`List reactions for a team discussion`](https://docs.github.com/enterprise-server@3.0/rest/reference/reactions#list-reactions-for-a-team-discussion) endpoint.\n\nList the reactions to a [team discussion](https://docs.github.com/enterprise-server@3.0/rest/reference/teams#discussions). OAuth access tokens require the `read:discussion` [scope](https://docs.github.com/enterprise-server@3.0/apps/building-oauth-apps/understanding-scopes-for-oauth-apps/).", "tags": [ "reactions" ], "operationId": "reactions/list-for-team-discussion-legacy", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/reactions/#list-reactions-for-a-team-discussion-legacy" }, "parameters": [ { "$ref": "#/components/parameters/team-id" }, { "$ref": "#/components/parameters/discussion-number" }, { "name": "content", "description": "Returns a single [reaction type](https://docs.github.com/enterprise-server@3.0/rest/reference/reactions#reaction-types). Omit this parameter to list all reactions to a team discussion.", "in": "query", "required": false, "schema": { "type": "string", "enum": [ "+1", "-1", "laugh", "confused", "heart", "hooray", "rocket", "eyes" ] } }, { "$ref": "#/components/parameters/per-page" }, { "$ref": "#/components/parameters/page" } ], "responses": { "200": { "description": "Response", "content": { "application/json": { "schema": { "type": "array", "items": { "$ref": "#/components/schemas/reaction" } }, "examples": { "default": { "$ref": "#/components/examples/reaction-items" } } } }, "headers": { "Link": { "$ref": "#/components/headers/link" } } } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": true, "removalDate": "2021-02-21", "deprecationDate": "2020-02-26", "category": "reactions", "previews": [ { "required": true, "name": "squirrel-girl", "note": "An additional `reactions` object in the issue comment payload is currently available for developers to preview. During the preview period, the APIs may change without advance notice. Please see the [blog post](https://developer.github.com/changes/2016-05-12-reactions-api-preview) for full details.\n\nTo access the API you must provide a custom [media type](https://docs.github.com/enterprise-server@3.0/rest/overview/media-types) in the `Accept` header:\n```shell\napplication/vnd.github.squirrel-girl-preview\n```\nThe `reactions` key will have the following payload where `url` can be used to construct the API location for [listing and creating](https://docs.github.com/enterprise-server@3.0/rest/reference/reactions) reactions." } ] }, "deprecated": true }, "post": { "summary": "Create reaction for a team discussion (Legacy)", "description": "**Deprecation Notice:** This endpoint route is deprecated and will be removed from the Teams API. We recommend migrating your existing code to use the new [`Create reaction for a team discussion`](https://docs.github.com/enterprise-server@3.0/rest/reference/reactions#create-reaction-for-a-team-discussion) endpoint.\n\nCreate a reaction to a [team discussion](https://docs.github.com/enterprise-server@3.0/rest/reference/teams#discussions). OAuth access tokens require the `write:discussion` [scope](https://docs.github.com/enterprise-server@3.0/apps/building-oauth-apps/understanding-scopes-for-oauth-apps/). A response with an HTTP `200` status means that you already added the reaction type to this team discussion.", "tags": [ "reactions" ], "operationId": "reactions/create-for-team-discussion-legacy", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/reactions/#create-reaction-for-a-team-discussion-legacy" }, "parameters": [ { "$ref": "#/components/parameters/team-id" }, { "$ref": "#/components/parameters/discussion-number" } ], "requestBody": { "required": true, "content": { "application/json": { "schema": { "type": "object", "properties": { "content": { "type": "string", "description": "The [reaction type](https://docs.github.com/enterprise-server@3.0/rest/reference/reactions#reaction-types) to add to the team discussion.", "enum": [ "+1", "-1", "laugh", "confused", "heart", "hooray", "rocket", "eyes" ] } }, "required": [ "content" ] }, "example": { "content": "heart" } } } }, "responses": { "201": { "description": "Response", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/reaction" }, "examples": { "default": { "$ref": "#/components/examples/reaction" } } } } } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": false, "removalDate": "2021-02-21", "deprecationDate": "2020-02-26", "category": "reactions", "previews": [ { "required": true, "name": "squirrel-girl", "note": "An additional `reactions` object in the issue comment payload is currently available for developers to preview. During the preview period, the APIs may change without advance notice. Please see the [blog post](https://developer.github.com/changes/2016-05-12-reactions-api-preview) for full details.\n\nTo access the API you must provide a custom [media type](https://docs.github.com/enterprise-server@3.0/rest/overview/media-types) in the `Accept` header:\n```shell\napplication/vnd.github.squirrel-girl-preview\n```\nThe `reactions` key will have the following payload where `url` can be used to construct the API location for [listing and creating](https://docs.github.com/enterprise-server@3.0/rest/reference/reactions) reactions." } ] }, "deprecated": true } }, "/teams/{team_id}/members": { "get": { "summary": "List team members (Legacy)", "description": "**Deprecation Notice:** This endpoint route is deprecated and will be removed from the Teams API. We recommend migrating your existing code to use the new [`List team members`](https://docs.github.com/enterprise-server@3.0/rest/reference/teams#list-team-members) endpoint.\n\nTeam members will include the members of child teams.", "tags": [ "teams" ], "operationId": "teams/list-members-legacy", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/teams#list-team-members-legacy" }, "parameters": [ { "$ref": "#/components/parameters/team-id" }, { "name": "role", "description": "Filters members returned by their role in the team. Can be one of: \n\\* `member` - normal members of the team. \n\\* `maintainer` - team maintainers. \n\\* `all` - all members of the team.", "in": "query", "required": false, "schema": { "type": "string", "enum": [ "member", "maintainer", "all" ], "default": "all" } }, { "$ref": "#/components/parameters/per-page" }, { "$ref": "#/components/parameters/page" } ], "responses": { "200": { "description": "Response", "content": { "application/json": { "schema": { "type": "array", "items": { "$ref": "#/components/schemas/simple-user" } }, "examples": { "default": { "$ref": "#/components/examples/simple-user-items" } } } }, "headers": { "Link": { "$ref": "#/components/headers/link" } } }, "404": { "$ref": "#/components/responses/not_found" } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": true, "removalDate": "2021-02-01", "deprecationDate": "2020-01-21", "category": "teams", "subcategory": "members" }, "deprecated": true } }, "/teams/{team_id}/members/{username}": { "get": { "summary": "Get team member (Legacy)", "description": "The \"Get team member\" endpoint (described below) is deprecated.\n\nWe recommend using the [Get team membership for a user](https://docs.github.com/enterprise-server@3.0/rest/reference/teams#get-team-membership-for-a-user) endpoint instead. It allows you to get both active and pending memberships.\n\nTo list members in a team, the team must be visible to the authenticated user.", "tags": [ "teams" ], "operationId": "teams/get-member-legacy", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/teams#get-team-member-legacy" }, "parameters": [ { "$ref": "#/components/parameters/team-id" }, { "$ref": "#/components/parameters/username" } ], "responses": { "204": { "description": "if user is a member" }, "404": { "description": "if user is not a member" } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": true, "removalDate": "2021-02-01", "deprecationDate": "2020-01-21", "category": "teams", "subcategory": "members" }, "deprecated": true }, "put": { "summary": "Add team member (Legacy)", "description": "The \"Add team member\" endpoint (described below) is deprecated.\n\nWe recommend using the [Add or update team membership for a user](https://docs.github.com/enterprise-server@3.0/rest/reference/teams#add-or-update-team-membership-for-a-user) endpoint instead. It allows you to invite new organization members to your teams.\n\nTeam synchronization is available for organizations using GitHub Enterprise Cloud. For more information, see [GitHub's products](https://docs.github.com/github/getting-started-with-github/githubs-products) in the GitHub Help documentation.\n\nTo add someone to a team, the authenticated user must be an organization owner or a team maintainer in the team they're changing. The person being added to the team must be a member of the team's organization.\n\n**Note:** When you have team synchronization set up for a team with your organization's identity provider (IdP), you will see an error if you attempt to use the API for making changes to the team's membership. If you have access to manage group membership in your IdP, you can manage GitHub Enterprise Server team membership through your identity provider, which automatically adds and removes team members in an organization. For more information, see \"[Synchronizing teams between your identity provider and GitHub Enterprise Server](https://docs.github.com/articles/synchronizing-teams-between-your-identity-provider-and-github/).\"\n\nNote that you'll need to set `Content-Length` to zero when calling out to this endpoint. For more information, see \"[HTTP verbs](https://docs.github.com/enterprise-server@3.0/rest/overview/resources-in-the-rest-api#http-verbs).\"", "tags": [ "teams" ], "operationId": "teams/add-member-legacy", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/teams#add-team-member-legacy" }, "parameters": [ { "$ref": "#/components/parameters/team-id" }, { "$ref": "#/components/parameters/username" } ], "responses": { "204": { "description": "Response" }, "404": { "description": "Not Found if team synchronization is set up" }, "422": { "description": "Unprocessable Entity if you attempt to add an organization to a team or you attempt to add a user to a team when they are not a member of at least one other team in the same organization" }, "403": { "$ref": "#/components/responses/forbidden" } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": true, "removalDate": "2021-02-01", "deprecationDate": "2020-01-21", "category": "teams", "subcategory": "members" }, "deprecated": true }, "delete": { "summary": "Remove team member (Legacy)", "description": "The \"Remove team member\" endpoint (described below) is deprecated.\n\nWe recommend using the [Remove team membership for a user](https://docs.github.com/enterprise-server@3.0/rest/reference/teams#remove-team-membership-for-a-user) endpoint instead. It allows you to remove both active and pending memberships.\n\nTeam synchronization is available for organizations using GitHub Enterprise Cloud. For more information, see [GitHub's products](https://docs.github.com/github/getting-started-with-github/githubs-products) in the GitHub Help documentation.\n\nTo remove a team member, the authenticated user must have 'admin' permissions to the team or be an owner of the org that the team is associated with. Removing a team member does not delete the user, it just removes them from the team.\n\n**Note:** When you have team synchronization set up for a team with your organization's identity provider (IdP), you will see an error if you attempt to use the API for making changes to the team's membership. If you have access to manage group membership in your IdP, you can manage GitHub Enterprise Server team membership through your identity provider, which automatically adds and removes team members in an organization. For more information, see \"[Synchronizing teams between your identity provider and GitHub Enterprise Server](https://docs.github.com/articles/synchronizing-teams-between-your-identity-provider-and-github/).\"", "tags": [ "teams" ], "operationId": "teams/remove-member-legacy", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/teams#remove-team-member-legacy" }, "parameters": [ { "$ref": "#/components/parameters/team-id" }, { "$ref": "#/components/parameters/username" } ], "responses": { "204": { "description": "Response" }, "404": { "description": "Not Found if team synchronization is setup" } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": true, "removalDate": "2021-02-01", "deprecationDate": "2020-01-21", "category": "teams", "subcategory": "members" }, "deprecated": true } }, "/teams/{team_id}/memberships/{username}": { "get": { "summary": "Get team membership for a user (Legacy)", "description": "**Deprecation Notice:** This endpoint route is deprecated and will be removed from the Teams API. We recommend migrating your existing code to use the new [Get team membership for a user](https://docs.github.com/enterprise-server@3.0/rest/reference/teams#get-team-membership-for-a-user) endpoint.\n\nTeam members will include the members of child teams.\n\nTo get a user's membership with a team, the team must be visible to the authenticated user.\n\n**Note:**\nThe response contains the `state` of the membership and the member's `role`.\n\nThe `role` for organization owners is set to `maintainer`. For more information about `maintainer` roles, see [Create a team](https://docs.github.com/enterprise-server@3.0/rest/reference/teams#create-a-team).", "tags": [ "teams" ], "operationId": "teams/get-membership-for-user-legacy", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/teams#get-team-membership-for-a-user-legacy" }, "parameters": [ { "$ref": "#/components/parameters/team-id" }, { "$ref": "#/components/parameters/username" } ], "responses": { "200": { "description": "Response", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/team-membership" }, "examples": { "response-if-user-is-a-team-maintainer": { "$ref": "#/components/examples/team-membership-response-if-user-is-a-team-maintainer" } } } } }, "404": { "$ref": "#/components/responses/not_found" } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": true, "removalDate": "2021-02-01", "deprecationDate": "2020-01-21", "category": "teams", "subcategory": "members" }, "deprecated": true }, "put": { "summary": "Add or update team membership for a user (Legacy)", "description": "**Deprecation Notice:** This endpoint route is deprecated and will be removed from the Teams API. We recommend migrating your existing code to use the new [Add or update team membership for a user](https://docs.github.com/enterprise-server@3.0/rest/reference/teams#add-or-update-team-membership-for-a-user) endpoint.\n\nTeam synchronization is available for organizations using GitHub Enterprise Cloud. For more information, see [GitHub's products](https://docs.github.com/github/getting-started-with-github/githubs-products) in the GitHub Help documentation.\n\nIf the user is already a member of the team's organization, this endpoint will add the user to the team. To add a membership between an organization member and a team, the authenticated user must be an organization owner or a team maintainer.\n\n**Note:** When you have team synchronization set up for a team with your organization's identity provider (IdP), you will see an error if you attempt to use the API for making changes to the team's membership. If you have access to manage group membership in your IdP, you can manage GitHub Enterprise Server team membership through your identity provider, which automatically adds and removes team members in an organization. For more information, see \"[Synchronizing teams between your identity provider and GitHub Enterprise Server](https://docs.github.com/articles/synchronizing-teams-between-your-identity-provider-and-github/).\"\n\nIf the user is unaffiliated with the team's organization, this endpoint will send an invitation to the user via email. This newly-created membership will be in the \"pending\" state until the user accepts the invitation, at which point the membership will transition to the \"active\" state and the user will be added as a member of the team. To add a membership between an unaffiliated user and a team, the authenticated user must be an organization owner.\n\nIf the user is already a member of the team, this endpoint will update the role of the team member's role. To update the membership of a team member, the authenticated user must be an organization owner or a team maintainer.", "tags": [ "teams" ], "operationId": "teams/add-or-update-membership-for-user-legacy", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/teams#add-or-update-team-membership-for-a-user-legacy" }, "parameters": [ { "$ref": "#/components/parameters/team-id" }, { "$ref": "#/components/parameters/username" } ], "requestBody": { "required": false, "content": { "application/json": { "schema": { "type": "object", "properties": { "role": { "type": "string", "description": "The role that this user should have in the team. Can be one of: \n\\* `member` - a normal member of the team. \n\\* `maintainer` - a team maintainer. Able to add/remove other team members, promote other team members to team maintainer, and edit the team's name and description.", "enum": [ "member", "maintainer" ], "default": "member" } } } } } }, "responses": { "200": { "description": "Response", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/team-membership" }, "examples": { "response-if-users-membership-with-team-is-now-pending": { "$ref": "#/components/examples/team-membership-response-if-users-membership-with-team-is-now-pending" } } } } }, "403": { "description": "Forbidden if team synchronization is set up" }, "422": { "description": "Unprocessable Entity if you attempt to add an organization to a team" }, "404": { "$ref": "#/components/responses/not_found" } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": true, "removalDate": "2021-02-01", "deprecationDate": "2020-01-21", "category": "teams", "subcategory": "members" }, "deprecated": true }, "delete": { "summary": "Remove team membership for a user (Legacy)", "description": "**Deprecation Notice:** This endpoint route is deprecated and will be removed from the Teams API. We recommend migrating your existing code to use the new [Remove team membership for a user](https://docs.github.com/enterprise-server@3.0/rest/reference/teams#remove-team-membership-for-a-user) endpoint.\n\nTeam synchronization is available for organizations using GitHub Enterprise Cloud. For more information, see [GitHub's products](https://docs.github.com/github/getting-started-with-github/githubs-products) in the GitHub Help documentation.\n\nTo remove a membership between a user and a team, the authenticated user must have 'admin' permissions to the team or be an owner of the organization that the team is associated with. Removing team membership does not delete the user, it just removes their membership from the team.\n\n**Note:** When you have team synchronization set up for a team with your organization's identity provider (IdP), you will see an error if you attempt to use the API for making changes to the team's membership. If you have access to manage group membership in your IdP, you can manage GitHub Enterprise Server team membership through your identity provider, which automatically adds and removes team members in an organization. For more information, see \"[Synchronizing teams between your identity provider and GitHub Enterprise Server](https://docs.github.com/articles/synchronizing-teams-between-your-identity-provider-and-github/).\"", "tags": [ "teams" ], "operationId": "teams/remove-membership-for-user-legacy", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/teams#remove-team-membership-for-a-user-legacy" }, "parameters": [ { "$ref": "#/components/parameters/team-id" }, { "$ref": "#/components/parameters/username" } ], "responses": { "204": { "description": "Response" }, "403": { "description": "if team synchronization is set up" } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": true, "removalDate": "2021-02-01", "deprecationDate": "2020-01-21", "category": "teams", "subcategory": "members" }, "deprecated": true } }, "/teams/{team_id}/projects": { "get": { "summary": "List team projects (Legacy)", "description": "**Deprecation Notice:** This endpoint route is deprecated and will be removed from the Teams API. We recommend migrating your existing code to use the new [`List team projects`](https://docs.github.com/enterprise-server@3.0/rest/reference/teams#list-team-projects) endpoint.\n\nLists the organization projects for a team.", "tags": [ "teams" ], "operationId": "teams/list-projects-legacy", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/teams/#list-team-projects-legacy" }, "parameters": [ { "$ref": "#/components/parameters/team-id" }, { "$ref": "#/components/parameters/per-page" }, { "$ref": "#/components/parameters/page" } ], "responses": { "200": { "description": "Response", "content": { "application/json": { "schema": { "type": "array", "items": { "$ref": "#/components/schemas/team-project" } }, "examples": { "default": { "$ref": "#/components/examples/team-project-items" } } } }, "headers": { "Link": { "$ref": "#/components/headers/link" } } }, "404": { "$ref": "#/components/responses/not_found" } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": true, "removalDate": "2021-02-01", "deprecationDate": "2020-01-21", "category": "teams", "previews": [ { "required": true, "name": "inertia", "note": "The Projects API is currently available for developers to preview. During the preview period, the API may change without advance notice. Please see the [blog post](https://developer.github.com/changes/2016-10-27-changes-to-projects-api) for full details. To access the API during the preview period, you must provide a custom [media type](https://docs.github.com/enterprise-server@3.0/rest/overview/media-types) in the `Accept` header:\n```shell\napplication/vnd.github.inertia-preview+json\n```" } ] }, "deprecated": true } }, "/teams/{team_id}/projects/{project_id}": { "get": { "summary": "Check team permissions for a project (Legacy)", "description": "**Deprecation Notice:** This endpoint route is deprecated and will be removed from the Teams API. We recommend migrating your existing code to use the new [Check team permissions for a project](https://docs.github.com/enterprise-server@3.0/rest/reference/teams#check-team-permissions-for-a-project) endpoint.\n\nChecks whether a team has `read`, `write`, or `admin` permissions for an organization project. The response includes projects inherited from a parent team.", "tags": [ "teams" ], "operationId": "teams/check-permissions-for-project-legacy", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/teams/#check-team-permissions-for-a-project-legacy" }, "parameters": [ { "$ref": "#/components/parameters/team-id" }, { "$ref": "#/components/parameters/project-id" } ], "responses": { "200": { "description": "Response", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/team-project" }, "examples": { "default": { "$ref": "#/components/examples/team-project" } } } } }, "404": { "description": "Not Found if project is not managed by this team" } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": true, "removalDate": "2021-02-01", "deprecationDate": "2020-01-21", "category": "teams", "previews": [ { "required": true, "name": "inertia", "note": "The Projects API is currently available for developers to preview. During the preview period, the API may change without advance notice. Please see the [blog post](https://developer.github.com/changes/2016-10-27-changes-to-projects-api) for full details. To access the API during the preview period, you must provide a custom [media type](https://docs.github.com/enterprise-server@3.0/rest/overview/media-types) in the `Accept` header:\n```shell\napplication/vnd.github.inertia-preview+json\n```" } ] }, "deprecated": true }, "put": { "summary": "Add or update team project permissions (Legacy)", "description": "**Deprecation Notice:** This endpoint route is deprecated and will be removed from the Teams API. We recommend migrating your existing code to use the new [Add or update team project permissions](https://docs.github.com/enterprise-server@3.0/rest/reference/teams#add-or-update-team-project-permissions) endpoint.\n\nAdds an organization project to a team. To add a project to a team or update the team's permission on a project, the authenticated user must have `admin` permissions for the project. The project and team must be part of the same organization.", "tags": [ "teams" ], "operationId": "teams/add-or-update-project-permissions-legacy", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/teams/#add-or-update-team-project-permissions-legacy" }, "parameters": [ { "$ref": "#/components/parameters/team-id" }, { "$ref": "#/components/parameters/project-id" } ], "requestBody": { "required": false, "content": { "application/json": { "schema": { "type": "object", "properties": { "permission": { "type": "string", "description": "The permission to grant to the team for this project. Can be one of: \n\\* `read` - team members can read, but not write to or administer this project. \n\\* `write` - team members can read and write, but not administer this project. \n\\* `admin` - team members can read, write and administer this project. \nDefault: the team's `permission` attribute will be used to determine what permission to grant the team on this project. Note that, if you choose not to pass any parameters, you'll need to set `Content-Length` to zero when calling out to this endpoint. For more information, see \"[HTTP verbs](https://docs.github.com/enterprise-server@3.0/rest/overview/resources-in-the-rest-api#http-verbs).\"", "enum": [ "read", "write", "admin" ] } } } } } }, "responses": { "204": { "description": "Response" }, "403": { "description": "Forbidden if the project is not owned by the organization", "content": { "application/json": { "schema": { "type": "object", "properties": { "message": { "type": "string" }, "documentation_url": { "type": "string" } } }, "examples": { "response-if-the-project-is-not-owned-by-the-organization": { "value": { "message": "Must have admin rights to Repository.", "documentation_url": "https://docs.github.com/enterprise-server@3.0/rest/reference/teams#add-or-update-team-project-permissions" } } } } } }, "404": { "$ref": "#/components/responses/not_found" }, "422": { "$ref": "#/components/responses/validation_failed" } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": true, "removalDate": "2021-02-01", "deprecationDate": "2020-01-21", "category": "teams", "previews": [ { "required": true, "name": "inertia", "note": "The Projects API is currently available for developers to preview. During the preview period, the API may change without advance notice. Please see the [blog post](https://developer.github.com/changes/2016-10-27-changes-to-projects-api) for full details. To access the API during the preview period, you must provide a custom [media type](https://docs.github.com/enterprise-server@3.0/rest/overview/media-types) in the `Accept` header:\n```shell\napplication/vnd.github.inertia-preview+json\n```" } ] }, "deprecated": true }, "delete": { "summary": "Remove a project from a team (Legacy)", "description": "**Deprecation Notice:** This endpoint route is deprecated and will be removed from the Teams API. We recommend migrating your existing code to use the new [Remove a project from a team](https://docs.github.com/enterprise-server@3.0/rest/reference/teams#remove-a-project-from-a-team) endpoint.\n\nRemoves an organization project from a team. An organization owner or a team maintainer can remove any project from the team. To remove a project from a team as an organization member, the authenticated user must have `read` access to both the team and project, or `admin` access to the team or project. **Note:** This endpoint removes the project from the team, but does not delete it.", "tags": [ "teams" ], "operationId": "teams/remove-project-legacy", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/teams/#remove-a-project-from-a-team-legacy" }, "parameters": [ { "$ref": "#/components/parameters/team-id" }, { "$ref": "#/components/parameters/project-id" } ], "responses": { "204": { "description": "Response" }, "404": { "$ref": "#/components/responses/not_found" }, "415": { "$ref": "#/components/responses/preview_header_missing" }, "422": { "$ref": "#/components/responses/validation_failed" } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": true, "removalDate": "2021-02-01", "deprecationDate": "2020-01-21", "category": "teams", "subcategory": null }, "deprecated": true } }, "/teams/{team_id}/repos": { "get": { "summary": "List team repositories (Legacy)", "description": "**Deprecation Notice:** This endpoint route is deprecated and will be removed from the Teams API. We recommend migrating your existing code to use the new [List team repositories](https://docs.github.com/enterprise-server@3.0/rest/reference/teams#list-team-repositories) endpoint.", "tags": [ "teams" ], "operationId": "teams/list-repos-legacy", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/teams/#list-team-repositories-legacy" }, "parameters": [ { "$ref": "#/components/parameters/team-id" }, { "$ref": "#/components/parameters/per-page" }, { "$ref": "#/components/parameters/page" } ], "responses": { "200": { "description": "Response", "content": { "application/json": { "schema": { "type": "array", "items": { "$ref": "#/components/schemas/minimal-repository" } }, "examples": { "default": { "$ref": "#/components/examples/minimal-repository-items" } } } }, "headers": { "Link": { "$ref": "#/components/headers/link" } } }, "404": { "$ref": "#/components/responses/not_found" } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": true, "removalDate": "2021-02-01", "deprecationDate": "2020-01-21", "category": "teams", "subcategory": null }, "deprecated": true } }, "/teams/{team_id}/repos/{owner}/{repo}": { "get": { "summary": "Check team permissions for a repository (Legacy)", "description": "**Note**: Repositories inherited through a parent team will also be checked.\n\n**Deprecation Notice:** This endpoint route is deprecated and will be removed from the Teams API. We recommend migrating your existing code to use the new [Check team permissions for a repository](https://docs.github.com/enterprise-server@3.0/rest/reference/teams#check-team-permissions-for-a-repository) endpoint.\n\nYou can also get information about the specified repository, including what permissions the team grants on it, by passing the following custom [media type](https://docs.github.com/enterprise-server@3.0/rest/overview/media-types/) via the `Accept` header:", "tags": [ "teams" ], "operationId": "teams/check-permissions-for-repo-legacy", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/teams/#check-team-permissions-for-a-repository-legacy" }, "parameters": [ { "$ref": "#/components/parameters/team-id" }, { "$ref": "#/components/parameters/owner" }, { "$ref": "#/components/parameters/repo" } ], "responses": { "200": { "description": "Alternative response with extra repository information", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/team-repository" }, "examples": { "alternative-response-with-extra-repository-information": { "$ref": "#/components/examples/team-repository-alternative-response-with-extra-repository-information" } } } } }, "204": { "description": "Response if repository is managed by this team" }, "404": { "description": "Not Found if repository is not managed by this team" } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": true, "removalDate": "2021-02-01", "deprecationDate": "2020-01-21", "category": "teams", "subcategory": null }, "deprecated": true }, "put": { "summary": "Add or update team repository permissions (Legacy)", "description": "**Deprecation Notice:** This endpoint route is deprecated and will be removed from the Teams API. We recommend migrating your existing code to use the new \"[Add or update team repository permissions](https://docs.github.com/enterprise-server@3.0/rest/reference/teams#add-or-update-team-repository-permissions)\" endpoint.\n\nTo add a repository to a team or update the team's permission on a repository, the authenticated user must have admin access to the repository, and must be able to see the team. The repository must be owned by the organization, or a direct fork of a repository owned by the organization. You will get a `422 Unprocessable Entity` status if you attempt to add a repository to a team that is not owned by the organization.\n\nNote that, if you choose not to pass any parameters, you'll need to set `Content-Length` to zero when calling out to this endpoint. For more information, see \"[HTTP verbs](https://docs.github.com/enterprise-server@3.0/rest/overview/resources-in-the-rest-api#http-verbs).\"", "tags": [ "teams" ], "operationId": "teams/add-or-update-repo-permissions-legacy", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/teams/#add-or-update-team-repository-permissions-legacy" }, "parameters": [ { "$ref": "#/components/parameters/team-id" }, { "$ref": "#/components/parameters/owner" }, { "$ref": "#/components/parameters/repo" } ], "requestBody": { "required": false, "content": { "application/json": { "schema": { "type": "object", "properties": { "permission": { "type": "string", "description": "The permission to grant the team on this repository. Can be one of: \n\\* `pull` - team members can pull, but not push to or administer this repository. \n\\* `push` - team members can pull and push, but not administer this repository. \n\\* `admin` - team members can pull, push and administer this repository. \n \nIf no permission is specified, the team's `permission` attribute will be used to determine what permission to grant the team on this repository.", "enum": [ "pull", "push", "admin" ] } } } } } }, "responses": { "204": { "description": "Response" }, "403": { "$ref": "#/components/responses/forbidden" }, "422": { "$ref": "#/components/responses/validation_failed" } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": true, "removalDate": "2021-02-01", "deprecationDate": "2020-01-21", "category": "teams", "subcategory": null }, "deprecated": true }, "delete": { "summary": "Remove a repository from a team (Legacy)", "description": "**Deprecation Notice:** This endpoint route is deprecated and will be removed from the Teams API. We recommend migrating your existing code to use the new [Remove a repository from a team](https://docs.github.com/enterprise-server@3.0/rest/reference/teams#remove-a-repository-from-a-team) endpoint.\n\nIf the authenticated user is an organization owner or a team maintainer, they can remove any repositories from the team. To remove a repository from a team as an organization member, the authenticated user must have admin access to the repository and must be able to see the team. NOTE: This does not delete the repository, it just removes it from the team.", "tags": [ "teams" ], "operationId": "teams/remove-repo-legacy", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/teams/#remove-a-repository-from-a-team-legacy" }, "parameters": [ { "$ref": "#/components/parameters/team-id" }, { "$ref": "#/components/parameters/owner" }, { "$ref": "#/components/parameters/repo" } ], "responses": { "204": { "description": "Response" } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": true, "removalDate": "2021-02-01", "deprecationDate": "2020-01-21", "category": "teams", "subcategory": null }, "deprecated": true } }, "/teams/{team_id}/teams": { "get": { "summary": "List child teams (Legacy)", "description": "**Deprecation Notice:** This endpoint route is deprecated and will be removed from the Teams API. We recommend migrating your existing code to use the new [`List child teams`](https://docs.github.com/enterprise-server@3.0/rest/reference/teams#list-child-teams) endpoint.", "tags": [ "teams" ], "operationId": "teams/list-child-legacy", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/teams/#list-child-teams-legacy" }, "parameters": [ { "$ref": "#/components/parameters/team-id" }, { "$ref": "#/components/parameters/per-page" }, { "$ref": "#/components/parameters/page" } ], "responses": { "200": { "description": "if child teams exist", "content": { "application/json": { "schema": { "type": "array", "items": { "$ref": "#/components/schemas/team" } }, "examples": { "response-if-child-teams-exist": { "$ref": "#/components/examples/team-items-response-if-child-teams-exist" } } } }, "headers": { "Link": { "$ref": "#/components/headers/link" } } }, "404": { "$ref": "#/components/responses/not_found" }, "403": { "$ref": "#/components/responses/forbidden" }, "422": { "$ref": "#/components/responses/validation_failed" } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": true, "removalDate": "2021-02-01", "deprecationDate": "2020-01-21", "category": "teams", "subcategory": null }, "deprecated": true } }, "/user": { "get": { "summary": "Get the authenticated user", "description": "If the authenticated user is authenticated through basic authentication or OAuth with the `user` scope, then the response lists public and private profile information.\n\nIf the authenticated user is authenticated through OAuth without the `user` scope, then the response lists only public profile information.", "tags": [ "users" ], "operationId": "users/get-authenticated", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/users#get-the-authenticated-user" }, "parameters": [ ], "responses": { "200": { "description": "Response", "content": { "application/json": { "schema": { "oneOf": [ { "$ref": "#/components/schemas/private-user" }, { "$ref": "#/components/schemas/public-user" } ] }, "examples": { "response-with-public-and-private-profile-information": { "$ref": "#/components/examples/private-user-response-with-public-and-private-profile-information" }, "response-with-public-profile-information": { "$ref": "#/components/examples/private-user-response-with-public-profile-information" } } } } }, "304": { "$ref": "#/components/responses/not_modified" }, "403": { "$ref": "#/components/responses/forbidden" }, "401": { "$ref": "#/components/responses/requires_authentication" } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": false, "category": "users", "subcategory": null } }, "patch": { "summary": "Update the authenticated user", "description": "**Note:** If your email is set to private and you send an `email` parameter as part of this request to update your profile, your privacy settings are still enforced: the email address will not be displayed on your public profile or via the API.", "tags": [ "users" ], "operationId": "users/update-authenticated", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/users/#update-the-authenticated-user" }, "parameters": [ ], "requestBody": { "required": false, "content": { "application/json": { "schema": { "type": "object", "properties": { "name": { "description": "The new name of the user.", "type": "string", "examples": [ "Omar Jahandar" ] }, "email": { "description": "The publicly visible email address of the user.", "type": "string", "examples": [ "omar@example.com" ] }, "blog": { "description": "The new blog URL of the user.", "type": "string", "examples": [ "blog.example.com" ] }, "twitter_username": { "description": "The new Twitter username of the user.", "type": [ "string", "null" ], "examples": [ "therealomarj" ] }, "company": { "description": "The new company of the user.", "type": "string", "examples": [ "Acme corporation" ] }, "location": { "description": "The new location of the user.", "type": "string", "examples": [ "Berlin, Germany" ] }, "hireable": { "description": "The new hiring availability of the user.", "type": "boolean" }, "bio": { "description": "The new short biography of the user.", "type": "string" } } } } } }, "responses": { "200": { "description": "Response", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/private-user" }, "examples": { "default": { "$ref": "#/components/examples/private-user" } } } } }, "304": { "$ref": "#/components/responses/not_modified" }, "404": { "$ref": "#/components/responses/not_found" }, "403": { "$ref": "#/components/responses/forbidden" }, "401": { "$ref": "#/components/responses/requires_authentication" }, "422": { "$ref": "#/components/responses/validation_failed" } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": false, "category": "users", "subcategory": null } } }, "/user/emails": { "get": { "summary": "List email addresses for the authenticated user", "description": "Lists all of your email addresses, and specifies which one is visible to the public. This endpoint is accessible with the `user:email` scope.", "tags": [ "users" ], "operationId": "users/list-emails-for-authenticated-user", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/users#list-email-addresses-for-the-authenticated-user" }, "parameters": [ { "$ref": "#/components/parameters/per-page" }, { "$ref": "#/components/parameters/page" } ], "responses": { "200": { "description": "Response", "content": { "application/json": { "schema": { "type": "array", "items": { "$ref": "#/components/schemas/email" } }, "examples": { "default": { "$ref": "#/components/examples/email-items-2" } } } }, "headers": { "Link": { "$ref": "#/components/headers/link" } } }, "304": { "$ref": "#/components/responses/not_modified" }, "404": { "$ref": "#/components/responses/not_found" }, "403": { "$ref": "#/components/responses/forbidden" }, "401": { "$ref": "#/components/responses/requires_authentication" } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": false, "category": "users", "subcategory": "emails" } }, "post": { "summary": "Add an email address for the authenticated user", "description": "This endpoint is accessible with the `user` scope.", "tags": [ "users" ], "operationId": "users/add-email-for-authenticated-user", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/users#add-an-email-address-for-the-authenticated-user" }, "parameters": [ ], "requestBody": { "required": false, "content": { "application/json": { "schema": { "oneOf": [ { "type": "object", "properties": { "emails": { "description": "Adds one or more email addresses to your GitHub account. Must contain at least one email address. **Note:** Alternatively, you can pass a single email address or an `array` of emails addresses directly, but we recommend that you pass an object using the `emails` key.", "type": "array", "items": { "type": "string", "minItems": 1, "examples": [ "username@example.com" ] }, "examples": [ ] } }, "required": [ "emails" ], "example": { "emails": [ "octocat@github.com", "mona@github.com" ] } }, { "type": "array", "items": { "type": "string", "minItems": 1, "examples": [ "username@example.com" ] } }, { "type": "string" } ] } } } }, "responses": { "201": { "description": "Response", "content": { "application/json": { "schema": { "type": "array", "items": { "$ref": "#/components/schemas/email" } }, "examples": { "default": { "$ref": "#/components/examples/email-items" } } } } }, "422": { "$ref": "#/components/responses/validation_failed" }, "304": { "$ref": "#/components/responses/not_modified" }, "404": { "$ref": "#/components/responses/not_found" }, "403": { "$ref": "#/components/responses/forbidden" }, "401": { "$ref": "#/components/responses/requires_authentication" } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": false, "category": "users", "subcategory": "emails" } }, "delete": { "summary": "Delete an email address for the authenticated user", "description": "This endpoint is accessible with the `user` scope.", "tags": [ "users" ], "operationId": "users/delete-email-for-authenticated-user", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/users#delete-an-email-address-for-the-authenticated-user" }, "parameters": [ ], "requestBody": { "content": { "application/json": { "schema": { "oneOf": [ { "type": "object", "description": "Deletes one or more email addresses from your GitHub account. Must contain at least one email address. **Note:** Alternatively, you can pass a single email address or an `array` of emails addresses directly, but we recommend that you pass an object using the `emails` key.", "properties": { "emails": { "description": "Email addresses associated with the GitHub user account.", "type": "array", "items": { "type": "string", "minItems": 1, "examples": [ "username@example.com" ] } } }, "example": { "emails": [ "octocat@github.com", "mona@github.com" ] }, "required": [ "emails" ] }, { "type": "array", "items": { "type": "string", "minItems": 1, "examples": [ "username@example.com" ] } }, { "type": "string" } ] } } } }, "responses": { "204": { "description": "Response" }, "304": { "$ref": "#/components/responses/not_modified" }, "404": { "$ref": "#/components/responses/not_found" }, "403": { "$ref": "#/components/responses/forbidden" }, "401": { "$ref": "#/components/responses/requires_authentication" }, "422": { "$ref": "#/components/responses/validation_failed" } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": false, "category": "users", "subcategory": "emails" } } }, "/user/followers": { "get": { "summary": "List followers of the authenticated user", "description": "Lists the people following the authenticated user.", "tags": [ "users" ], "operationId": "users/list-followers-for-authenticated-user", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/users#list-followers-of-the-authenticated-user" }, "parameters": [ { "$ref": "#/components/parameters/per-page" }, { "$ref": "#/components/parameters/page" } ], "responses": { "200": { "description": "Response", "content": { "application/json": { "schema": { "type": "array", "items": { "$ref": "#/components/schemas/simple-user" } }, "examples": { "default": { "$ref": "#/components/examples/simple-user-items" } } } }, "headers": { "Link": { "$ref": "#/components/headers/link" } } }, "304": { "$ref": "#/components/responses/not_modified" }, "403": { "$ref": "#/components/responses/forbidden" }, "401": { "$ref": "#/components/responses/requires_authentication" } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": false, "category": "users", "subcategory": "followers" } } }, "/user/following": { "get": { "summary": "List the people the authenticated user follows", "description": "Lists the people who the authenticated user follows.", "tags": [ "users" ], "operationId": "users/list-followed-by-authenticated-user", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/users#list-the-people-the-authenticated-user-follows" }, "parameters": [ { "$ref": "#/components/parameters/per-page" }, { "$ref": "#/components/parameters/page" } ], "responses": { "200": { "description": "Response", "content": { "application/json": { "schema": { "type": "array", "items": { "$ref": "#/components/schemas/simple-user" } }, "examples": { "default": { "$ref": "#/components/examples/simple-user-items" } } } }, "headers": { "Link": { "$ref": "#/components/headers/link" } } }, "304": { "$ref": "#/components/responses/not_modified" }, "403": { "$ref": "#/components/responses/forbidden" }, "401": { "$ref": "#/components/responses/requires_authentication" } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": false, "category": "users", "subcategory": "followers" } } }, "/user/following/{username}": { "get": { "summary": "Check if a person is followed by the authenticated user", "description": "", "tags": [ "users" ], "operationId": "users/check-person-is-followed-by-authenticated", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/users#check-if-a-person-is-followed-by-the-authenticated-user" }, "parameters": [ { "$ref": "#/components/parameters/username" } ], "responses": { "204": { "description": "if the person is followed by the authenticated user" }, "404": { "description": "if the person is not followed by the authenticated user", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/basic-error" } } } }, "304": { "$ref": "#/components/responses/not_modified" }, "403": { "$ref": "#/components/responses/forbidden" }, "401": { "$ref": "#/components/responses/requires_authentication" } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": false, "category": "users", "subcategory": "followers" } }, "put": { "summary": "Follow a user", "description": "Note that you'll need to set `Content-Length` to zero when calling out to this endpoint. For more information, see \"[HTTP verbs](https://docs.github.com/enterprise-server@3.0/rest/overview/resources-in-the-rest-api#http-verbs).\"\n\nFollowing a user requires the user to be logged in and authenticated with basic auth or OAuth with the `user:follow` scope.", "tags": [ "users" ], "operationId": "users/follow", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/users#follow-a-user" }, "parameters": [ { "$ref": "#/components/parameters/username" } ], "responses": { "204": { "description": "Response" }, "304": { "$ref": "#/components/responses/not_modified" }, "404": { "$ref": "#/components/responses/not_found" }, "403": { "$ref": "#/components/responses/forbidden" }, "401": { "$ref": "#/components/responses/requires_authentication" } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": false, "category": "users", "subcategory": "followers" } }, "delete": { "summary": "Unfollow a user", "description": "Unfollowing a user requires the user to be logged in and authenticated with basic auth or OAuth with the `user:follow` scope.", "tags": [ "users" ], "operationId": "users/unfollow", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/users#unfollow-a-user" }, "parameters": [ { "$ref": "#/components/parameters/username" } ], "responses": { "204": { "description": "Response" }, "304": { "$ref": "#/components/responses/not_modified" }, "404": { "$ref": "#/components/responses/not_found" }, "403": { "$ref": "#/components/responses/forbidden" }, "401": { "$ref": "#/components/responses/requires_authentication" } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": false, "category": "users", "subcategory": "followers" } } }, "/user/gpg_keys": { "get": { "summary": "List GPG keys for the authenticated user", "description": "Lists the current user's GPG keys. Requires that you are authenticated via Basic Auth or via OAuth with at least `read:gpg_key` [scope](https://docs.github.com/enterprise-server@3.0/apps/building-oauth-apps/understanding-scopes-for-oauth-apps/).", "tags": [ "users" ], "operationId": "users/list-gpg-keys-for-authenticated-user", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/users#list-gpg-keys-for-the-authenticated-user" }, "parameters": [ { "$ref": "#/components/parameters/per-page" }, { "$ref": "#/components/parameters/page" } ], "responses": { "200": { "description": "Response", "content": { "application/json": { "schema": { "type": "array", "items": { "$ref": "#/components/schemas/gpg-key" } }, "examples": { "default": { "$ref": "#/components/examples/gpg-key-items" } } } }, "headers": { "Link": { "$ref": "#/components/headers/link" } } }, "304": { "$ref": "#/components/responses/not_modified" }, "404": { "$ref": "#/components/responses/not_found" }, "403": { "$ref": "#/components/responses/forbidden" }, "401": { "$ref": "#/components/responses/requires_authentication" } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": false, "category": "users", "subcategory": "gpg-keys" } }, "post": { "summary": "Create a GPG key for the authenticated user", "description": "Adds a GPG key to the authenticated user's GitHub account. Requires that you are authenticated via Basic Auth, or OAuth with at least `write:gpg_key` [scope](https://docs.github.com/enterprise-server@3.0/apps/building-oauth-apps/understanding-scopes-for-oauth-apps/).", "operationId": "users/create-gpg-key-for-authenticated-user", "tags": [ "users" ], "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/users#create-a-gpg-key-for-the-authenticated-user" }, "parameters": [ ], "requestBody": { "required": true, "content": { "application/json": { "schema": { "properties": { "armored_public_key": { "description": "A GPG key in ASCII-armored format.", "type": "string" } }, "type": "object", "required": [ "armored_public_key" ] } } } }, "responses": { "201": { "description": "Response", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/gpg-key" }, "examples": { "default": { "$ref": "#/components/examples/gpg-key" } } } } }, "422": { "$ref": "#/components/responses/validation_failed" }, "304": { "$ref": "#/components/responses/not_modified" }, "404": { "$ref": "#/components/responses/not_found" }, "403": { "$ref": "#/components/responses/forbidden" }, "401": { "$ref": "#/components/responses/requires_authentication" } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": false, "category": "users", "subcategory": "gpg-keys" } } }, "/user/gpg_keys/{gpg_key_id}": { "get": { "summary": "Get a GPG key for the authenticated user", "description": "View extended details for a single GPG key. Requires that you are authenticated via Basic Auth or via OAuth with at least `read:gpg_key` [scope](https://docs.github.com/enterprise-server@3.0/apps/building-oauth-apps/understanding-scopes-for-oauth-apps/).", "tags": [ "users" ], "operationId": "users/get-gpg-key-for-authenticated-user", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/users#get-a-gpg-key-for-the-authenticated-user" }, "parameters": [ { "$ref": "#/components/parameters/gpg-key-id" } ], "responses": { "200": { "description": "Response", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/gpg-key" }, "examples": { "default": { "$ref": "#/components/examples/gpg-key" } } } } }, "404": { "$ref": "#/components/responses/not_found" }, "304": { "$ref": "#/components/responses/not_modified" }, "403": { "$ref": "#/components/responses/forbidden" }, "401": { "$ref": "#/components/responses/requires_authentication" } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": false, "category": "users", "subcategory": "gpg-keys" } }, "delete": { "summary": "Delete a GPG key for the authenticated user", "description": "Removes a GPG key from the authenticated user's GitHub account. Requires that you are authenticated via Basic Auth or via OAuth with at least `admin:gpg_key` [scope](https://docs.github.com/enterprise-server@3.0/apps/building-oauth-apps/understanding-scopes-for-oauth-apps/).", "tags": [ "users" ], "operationId": "users/delete-gpg-key-for-authenticated-user", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/users#delete-a-gpg-key-for-the-authenticated-user" }, "parameters": [ { "$ref": "#/components/parameters/gpg-key-id" } ], "responses": { "204": { "description": "Response" }, "404": { "$ref": "#/components/responses/not_found" }, "422": { "$ref": "#/components/responses/validation_failed" }, "304": { "$ref": "#/components/responses/not_modified" }, "403": { "$ref": "#/components/responses/forbidden" }, "401": { "$ref": "#/components/responses/requires_authentication" } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": false, "category": "users", "subcategory": "gpg-keys" } } }, "/user/installations": { "get": { "summary": "List app installations accessible to the user access token", "description": "Lists installations of your GitHub App that the authenticated user has explicit permission (`:read`, `:write`, or `:admin`) to access.\n\nYou must use a [user-to-server OAuth access token](https://docs.github.com/enterprise-server@3.0/apps/building-github-apps/identifying-and-authorizing-users-for-github-apps/#identifying-users-on-your-site), created for a user who has authorized your GitHub App, to access this endpoint.\n\nThe authenticated user has explicit permission to access repositories they own, repositories where they are a collaborator, and repositories that they can access through an organization membership.\n\nYou can find the permissions for the installation under the `permissions` key.", "tags": [ "apps" ], "operationId": "apps/list-installations-for-authenticated-user", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/apps#list-app-installations-accessible-to-the-user-access-token" }, "parameters": [ { "$ref": "#/components/parameters/per-page" }, { "$ref": "#/components/parameters/page" } ], "responses": { "200": { "description": "You can find the permissions for the installation under the `permissions` key.", "content": { "application/json": { "schema": { "type": "object", "required": [ "total_count", "installations" ], "properties": { "total_count": { "type": "integer" }, "installations": { "type": "array", "items": { "$ref": "#/components/schemas/installation" } } } }, "examples": { "default": { "$ref": "#/components/examples/base-installation-for-auth-user-paginated" } } } }, "headers": { "Link": { "$ref": "#/components/headers/link" } } }, "304": { "$ref": "#/components/responses/not_modified" }, "403": { "$ref": "#/components/responses/forbidden" }, "401": { "$ref": "#/components/responses/requires_authentication" }, "415": { "$ref": "#/components/responses/preview_header_missing" } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": false, "category": "apps", "subcategory": "installations" } } }, "/user/installations/{installation_id}/repositories": { "get": { "summary": "List repositories accessible to the user access token", "description": "List repositories that the authenticated user has explicit permission (`:read`, `:write`, or `:admin`) to access for an installation.\n\nThe authenticated user has explicit permission to access repositories they own, repositories where they are a collaborator, and repositories that they can access through an organization membership.\n\nYou must use a [user-to-server OAuth access token](https://docs.github.com/enterprise-server@3.0/apps/building-github-apps/identifying-and-authorizing-users-for-github-apps/#identifying-users-on-your-site), created for a user who has authorized your GitHub App, to access this endpoint.\n\nThe access the user has to each repository is included in the hash under the `permissions` key.", "tags": [ "apps" ], "operationId": "apps/list-installation-repos-for-authenticated-user", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/apps#list-repositories-accessible-to-the-user-access-token" }, "parameters": [ { "$ref": "#/components/parameters/installation-id" }, { "$ref": "#/components/parameters/per-page" }, { "$ref": "#/components/parameters/page" } ], "responses": { "200": { "description": "The access the user has to each repository is included in the hash under the `permissions` key.", "content": { "application/json": { "schema": { "type": "object", "required": [ "total_count", "repositories" ], "properties": { "total_count": { "type": "integer" }, "repository_selection": { "type": "string" }, "repositories": { "type": "array", "items": { "$ref": "#/components/schemas/repository" } } } }, "examples": { "default": { "$ref": "#/components/examples/repository-paginated" } } } }, "headers": { "Link": { "$ref": "#/components/headers/link" } } }, "404": { "$ref": "#/components/responses/not_found" }, "403": { "$ref": "#/components/responses/forbidden" }, "304": { "$ref": "#/components/responses/not_modified" } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": false, "category": "apps", "subcategory": "installations", "previews": [ { "required": false, "name": "mercy", "note": "The `topics` property for repositories on GitHub is currently available for developers to preview. To view the `topics` property in calls that return repository results, you must provide a custom [media type](https://docs.github.com/enterprise-server@3.0/rest/overview/media-types) in the `Accept` header:\n```shell\napplication/vnd.github.mercy-preview+json\n```" } ] } } }, "/user/installations/{installation_id}/repositories/{repository_id}": { "put": { "summary": "Add a repository to an app installation", "description": "Add a single repository to an installation. The authenticated user must have admin access to the repository.\n\nYou must use a personal access token (which you can create via the [command line](https://docs.github.com/enterprise-server@3.0/github/authenticating-to-github/creating-a-personal-access-token) or [Basic Authentication](https://docs.github.com/enterprise-server@3.0/rest/overview/other-authentication-methods#basic-authentication)) to access this endpoint.", "tags": [ "apps" ], "operationId": "apps/add-repo-to-installation-for-authenticated-user", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/apps#add-a-repository-to-an-app-installation" }, "parameters": [ { "$ref": "#/components/parameters/installation-id" }, { "$ref": "#/components/parameters/repository-id" } ], "responses": { "204": { "description": "Response" }, "403": { "$ref": "#/components/responses/forbidden" }, "304": { "$ref": "#/components/responses/not_modified" }, "404": { "$ref": "#/components/responses/not_found" } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": false, "category": "apps", "subcategory": "installations" } }, "delete": { "summary": "Remove a repository from an app installation", "description": "Remove a single repository from an installation. The authenticated user must have admin access to the repository.\n\nYou must use a personal access token (which you can create via the [command line](https://docs.github.com/enterprise-server@3.0/github/authenticating-to-github/creating-a-personal-access-token) or [Basic Authentication](https://docs.github.com/enterprise-server@3.0/rest/overview/other-authentication-methods#basic-authentication)) to access this endpoint.", "tags": [ "apps" ], "operationId": "apps/remove-repo-from-installation-for-authenticated-user", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/apps#remove-a-repository-from-an-app-installation" }, "parameters": [ { "$ref": "#/components/parameters/installation-id" }, { "$ref": "#/components/parameters/repository-id" } ], "responses": { "204": { "description": "Response" }, "403": { "$ref": "#/components/responses/forbidden" }, "304": { "$ref": "#/components/responses/not_modified" }, "404": { "$ref": "#/components/responses/not_found" } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": false, "category": "apps", "subcategory": "installations" } } }, "/user/issues": { "get": { "summary": "List user account issues assigned to the authenticated user", "description": "List issues across owned and member repositories assigned to the authenticated user.\n\n**Note**: GitHub's REST API v3 considers every pull request an issue, but not every issue is a pull request. For this\nreason, \"Issues\" endpoints may return both issues and pull requests in the response. You can identify pull requests by\nthe `pull_request` key. Be aware that the `id` of a pull request returned from \"Issues\" endpoints will be an _issue id_. To find out the pull\nrequest id, use the \"[List pull requests](https://docs.github.com/enterprise-server@3.0/rest/reference/pulls#list-pull-requests)\" endpoint.", "tags": [ "issues" ], "operationId": "issues/list-for-authenticated-user", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/issues#list-user-account-issues-assigned-to-the-authenticated-user" }, "parameters": [ { "name": "filter", "description": "Indicates which sorts of issues to return. Can be one of: \n\\* `assigned`: Issues assigned to you \n\\* `created`: Issues created by you \n\\* `mentioned`: Issues mentioning you \n\\* `subscribed`: Issues you're subscribed to updates for \n\\* `all` or `repos`: All issues the authenticated user can see, regardless of participation or creation", "in": "query", "required": false, "schema": { "type": "string", "enum": [ "assigned", "created", "mentioned", "subscribed", "repos", "all" ], "default": "assigned" } }, { "name": "state", "description": "Indicates the state of the issues to return. Can be either `open`, `closed`, or `all`.", "in": "query", "required": false, "schema": { "type": "string", "enum": [ "open", "closed", "all" ], "default": "open" } }, { "$ref": "#/components/parameters/labels" }, { "name": "sort", "description": "What to sort results by. Can be either `created`, `updated`, `comments`.", "in": "query", "required": false, "schema": { "type": "string", "enum": [ "created", "updated", "comments" ], "default": "created" } }, { "$ref": "#/components/parameters/direction" }, { "$ref": "#/components/parameters/since" }, { "$ref": "#/components/parameters/per-page" }, { "$ref": "#/components/parameters/page" } ], "responses": { "200": { "description": "Response", "content": { "application/json": { "schema": { "type": "array", "items": { "$ref": "#/components/schemas/issue" } }, "examples": { "default": { "$ref": "#/components/examples/issue-with-repo-items" } } } }, "headers": { "Link": { "$ref": "#/components/headers/link" } } }, "404": { "$ref": "#/components/responses/not_found" }, "304": { "$ref": "#/components/responses/not_modified" } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": false, "category": "issues", "previews": [ { "required": false, "name": "machine-man", "note": "If an issue event is created via a GitHub App, the response will include the `performed_via_github_app` object with\tinformation about the GitHub App. For more information, see the [related blog\tpost](https://developer.github.com/changes/2016-09-14-Integrations-Early-Access).\nTo receive the `performed_via_github_app` object in the response, you must provide a custom [media type](https://docs.github.com/enterprise-server@3.0/rest/overview/media-types) in the `Accept` header:\n```shell\napplication/vnd.github.machine-man-preview\n```" }, { "required": false, "name": "squirrel-girl", "note": "An additional `reactions` object in the issue comment payload is currently available for developers to preview. During the preview period, the APIs may change without advance notice. Please see the [blog post](https://developer.github.com/changes/2016-05-12-reactions-api-preview) for full details.\n\nTo access the API you must provide a custom [media type](https://docs.github.com/enterprise-server@3.0/rest/overview/media-types) in the `Accept` header:\n```shell\napplication/vnd.github.squirrel-girl-preview\n```\nThe `reactions` key will have the following payload where `url` can be used to construct the API location for [listing and creating](https://docs.github.com/enterprise-server@3.0/rest/reference/reactions) reactions." } ] } } }, "/user/keys": { "get": { "summary": "List public SSH keys for the authenticated user", "description": "Lists the public SSH keys for the authenticated user's GitHub account. Requires that you are authenticated via Basic Auth or via OAuth with at least `read:public_key` [scope](https://docs.github.com/enterprise-server@3.0/apps/building-oauth-apps/understanding-scopes-for-oauth-apps/).", "tags": [ "users" ], "operationId": "users/list-public-ssh-keys-for-authenticated-user", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/users#list-public-ssh-keys-for-the-authenticated-user" }, "parameters": [ { "$ref": "#/components/parameters/per-page" }, { "$ref": "#/components/parameters/page" } ], "responses": { "200": { "description": "Response", "content": { "application/json": { "schema": { "type": "array", "items": { "$ref": "#/components/schemas/key" } }, "examples": { "default": { "$ref": "#/components/examples/key-items" } } } }, "headers": { "Link": { "$ref": "#/components/headers/link" } } }, "304": { "$ref": "#/components/responses/not_modified" }, "404": { "$ref": "#/components/responses/not_found" }, "403": { "$ref": "#/components/responses/forbidden" }, "401": { "$ref": "#/components/responses/requires_authentication" } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": false, "category": "users", "subcategory": "keys" } }, "post": { "summary": "Create a public SSH key for the authenticated user", "description": "Adds a public SSH key to the authenticated user's GitHub account. Requires that you are authenticated via Basic Auth, or OAuth with at least `write:public_key` [scope](https://docs.github.com/enterprise-server@3.0/apps/building-oauth-apps/understanding-scopes-for-oauth-apps/).", "operationId": "users/create-public-ssh-key-for-authenticated-user", "tags": [ "users" ], "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/users#create-a-public-ssh-key-for-the-authenticated-user" }, "parameters": [ ], "requestBody": { "required": true, "content": { "application/json": { "schema": { "properties": { "title": { "description": "A descriptive name for the new key.", "type": "string", "examples": [ "Personal MacBook Air" ] }, "key": { "description": "The public SSH key to add to your GitHub account.", "type": "string", "pattern": "^ssh-(rsa|dss|ed25519) |^ecdsa-sha2-nistp(256|384|521) " } }, "required": [ "key" ], "type": "object" } } } }, "responses": { "201": { "description": "Response", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/key" }, "examples": { "default": { "$ref": "#/components/examples/key" } } } } }, "422": { "$ref": "#/components/responses/validation_failed" }, "304": { "$ref": "#/components/responses/not_modified" }, "404": { "$ref": "#/components/responses/not_found" }, "403": { "$ref": "#/components/responses/forbidden" }, "401": { "$ref": "#/components/responses/requires_authentication" } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": false, "category": "users", "subcategory": "keys" } } }, "/user/keys/{key_id}": { "get": { "summary": "Get a public SSH key for the authenticated user", "description": "View extended details for a single public SSH key. Requires that you are authenticated via Basic Auth or via OAuth with at least `read:public_key` [scope](https://docs.github.com/enterprise-server@3.0/apps/building-oauth-apps/understanding-scopes-for-oauth-apps/).", "tags": [ "users" ], "operationId": "users/get-public-ssh-key-for-authenticated-user", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/users#get-a-public-ssh-key-for-the-authenticated-user" }, "parameters": [ { "$ref": "#/components/parameters/key-id" } ], "responses": { "200": { "description": "Response", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/key" }, "examples": { "default": { "$ref": "#/components/examples/key" } } } } }, "404": { "$ref": "#/components/responses/not_found" }, "304": { "$ref": "#/components/responses/not_modified" }, "403": { "$ref": "#/components/responses/forbidden" }, "401": { "$ref": "#/components/responses/requires_authentication" } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": false, "category": "users", "subcategory": "keys" } }, "delete": { "summary": "Delete a public SSH key for the authenticated user", "description": "Removes a public SSH key from the authenticated user's GitHub account. Requires that you are authenticated via Basic Auth or via OAuth with at least `admin:public_key` [scope](https://docs.github.com/enterprise-server@3.0/apps/building-oauth-apps/understanding-scopes-for-oauth-apps/).", "tags": [ "users" ], "operationId": "users/delete-public-ssh-key-for-authenticated-user", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/users#delete-a-public-ssh-key-for-the-authenticated-user" }, "parameters": [ { "$ref": "#/components/parameters/key-id" } ], "responses": { "204": { "description": "Response" }, "304": { "$ref": "#/components/responses/not_modified" }, "404": { "$ref": "#/components/responses/not_found" }, "403": { "$ref": "#/components/responses/forbidden" }, "401": { "$ref": "#/components/responses/requires_authentication" } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": false, "category": "users", "subcategory": "keys" } } }, "/user/memberships/orgs": { "get": { "summary": "List organization memberships for the authenticated user", "description": "", "tags": [ "orgs" ], "operationId": "orgs/list-memberships-for-authenticated-user", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/orgs#list-organization-memberships-for-the-authenticated-user" }, "parameters": [ { "name": "state", "description": "Indicates the state of the memberships to return. Can be either `active` or `pending`. If not specified, the API returns both active and pending memberships.", "in": "query", "required": false, "schema": { "type": "string", "enum": [ "active", "pending" ] } }, { "$ref": "#/components/parameters/per-page" }, { "$ref": "#/components/parameters/page" } ], "responses": { "200": { "description": "Response", "content": { "application/json": { "schema": { "type": "array", "items": { "$ref": "#/components/schemas/org-membership" } }, "examples": { "default": { "$ref": "#/components/examples/org-membership-items" } } } }, "headers": { "Link": { "$ref": "#/components/headers/link" } } }, "304": { "$ref": "#/components/responses/not_modified" }, "403": { "$ref": "#/components/responses/forbidden" }, "401": { "$ref": "#/components/responses/requires_authentication" }, "422": { "$ref": "#/components/responses/validation_failed" } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": false, "category": "orgs", "subcategory": "members" } } }, "/user/memberships/orgs/{org}": { "get": { "summary": "Get an organization membership for the authenticated user", "description": "", "tags": [ "orgs" ], "operationId": "orgs/get-membership-for-authenticated-user", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/orgs#get-an-organization-membership-for-the-authenticated-user" }, "parameters": [ { "$ref": "#/components/parameters/org" } ], "responses": { "200": { "description": "Response", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/org-membership" }, "examples": { "default": { "$ref": "#/components/examples/org-membership" } } } } }, "403": { "$ref": "#/components/responses/forbidden" }, "404": { "$ref": "#/components/responses/not_found" } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": false, "category": "orgs", "subcategory": "members" } }, "patch": { "summary": "Update an organization membership for the authenticated user", "description": "", "tags": [ "orgs" ], "operationId": "orgs/update-membership-for-authenticated-user", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/orgs#update-an-organization-membership-for-the-authenticated-user" }, "parameters": [ { "$ref": "#/components/parameters/org" } ], "requestBody": { "required": true, "content": { "application/json": { "schema": { "type": "object", "properties": { "state": { "type": "string", "description": "The state that the membership should be in. Only `\"active\"` will be accepted.", "enum": [ "active" ] } }, "required": [ "state" ] }, "example": { "state": "active" } } } }, "responses": { "200": { "description": "Response", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/org-membership" }, "examples": { "default": { "$ref": "#/components/examples/org-membership-2" } } } } }, "403": { "$ref": "#/components/responses/forbidden" }, "404": { "$ref": "#/components/responses/not_found" }, "422": { "$ref": "#/components/responses/validation_failed" } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": false, "category": "orgs", "subcategory": "members" } } }, "/user/orgs": { "get": { "summary": "List organizations for the authenticated user", "description": "List organizations for the authenticated user.\n\n**OAuth scope requirements**\n\nThis only lists organizations that your authorization allows you to operate on in some way (e.g., you can list teams with `read:org` scope, you can publicize your organization membership with `user` scope, etc.). Therefore, this API requires at least `user` or `read:org` scope. OAuth requests with insufficient scope receive a `403 Forbidden` response.", "tags": [ "orgs" ], "operationId": "orgs/list-for-authenticated-user", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/orgs#list-organizations-for-the-authenticated-user" }, "parameters": [ { "$ref": "#/components/parameters/per-page" }, { "$ref": "#/components/parameters/page" } ], "responses": { "200": { "description": "Response", "content": { "application/json": { "schema": { "type": "array", "items": { "$ref": "#/components/schemas/organization-simple" } }, "examples": { "default": { "$ref": "#/components/examples/organization-simple-items" } } } }, "headers": { "Link": { "$ref": "#/components/headers/link" } } }, "304": { "$ref": "#/components/responses/not_modified" }, "403": { "$ref": "#/components/responses/forbidden" }, "401": { "$ref": "#/components/responses/requires_authentication" } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": false, "category": "orgs", "subcategory": null } } }, "/user/projects": { "post": { "summary": "Create a user project", "description": "", "tags": [ "projects" ], "operationId": "projects/create-for-authenticated-user", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/projects#create-a-user-project" }, "parameters": [ ], "requestBody": { "required": true, "content": { "application/json": { "schema": { "properties": { "name": { "description": "Name of the project", "type": "string", "examples": [ "Week One Sprint" ] }, "body": { "description": "Body of the project", "type": [ "string", "null" ], "examples": [ "This project represents the sprint of the first week in January" ] } }, "required": [ "name" ], "type": "object" } } } }, "responses": { "201": { "description": "Response", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/project" }, "examples": { "default": { "$ref": "#/components/examples/project" } } } } }, "304": { "$ref": "#/components/responses/not_modified" }, "403": { "$ref": "#/components/responses/forbidden" }, "401": { "$ref": "#/components/responses/requires_authentication" }, "415": { "$ref": "#/components/responses/preview_header_missing" }, "422": { "$ref": "#/components/responses/validation_failed_simple" } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": true, "category": "projects", "previews": [ { "required": true, "name": "inertia", "note": "The Projects API is currently available for developers to preview. During the preview period, the API may change without advance notice. Please see the [blog post](https://developer.github.com/changes/2016-10-27-changes-to-projects-api) for full details. To access the API during the preview period, you must provide a custom [media type](https://docs.github.com/enterprise-server@3.0/rest/overview/media-types) in the `Accept` header:\n```shell\napplication/vnd.github.inertia-preview+json\n```" } ] } } }, "/user/public_emails": { "get": { "summary": "List public email addresses for the authenticated user", "description": "Lists your publicly visible email address, which you can set with the [Set primary email visibility for the authenticated user](https://docs.github.com/enterprise-server@3.0/rest/reference/users#set-primary-email-visibility-for-the-authenticated-user) endpoint. This endpoint is accessible with the `user:email` scope.", "tags": [ "users" ], "operationId": "users/list-public-emails-for-authenticated-user", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/users#list-public-email-addresses-for-the-authenticated-user" }, "parameters": [ { "$ref": "#/components/parameters/per-page" }, { "$ref": "#/components/parameters/page" } ], "responses": { "200": { "description": "Response", "content": { "application/json": { "schema": { "type": "array", "items": { "$ref": "#/components/schemas/email" } }, "examples": { "default": { "$ref": "#/components/examples/email-items-2" } } } }, "headers": { "Link": { "$ref": "#/components/headers/link" } } }, "304": { "$ref": "#/components/responses/not_modified" }, "404": { "$ref": "#/components/responses/not_found" }, "403": { "$ref": "#/components/responses/forbidden" }, "401": { "$ref": "#/components/responses/requires_authentication" } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": false, "category": "users", "subcategory": "emails" } } }, "/user/repos": { "get": { "summary": "List repositories for the authenticated user", "description": "Lists repositories that the authenticated user has explicit permission (`:read`, `:write`, or `:admin`) to access.\n\nThe authenticated user has explicit permission to access repositories they own, repositories where they are a collaborator, and repositories that they can access through an organization membership.", "tags": [ "repos" ], "operationId": "repos/list-for-authenticated-user", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/repos#list-repositories-for-the-authenticated-user" }, "parameters": [ { "name": "visibility", "description": "Can be one of `all`, `public`, or `private`. Note: For GitHub AE, can be one of `all`, `internal`, or `private`.", "in": "query", "required": false, "schema": { "type": "string", "enum": [ "all", "public", "private" ], "default": "all" } }, { "name": "affiliation", "description": "Comma-separated list of values. Can include: \n\\* `owner`: Repositories that are owned by the authenticated user. \n\\* `collaborator`: Repositories that the user has been added to as a collaborator. \n\\* `organization_member`: Repositories that the user has access to through being a member of an organization. This includes every repository on every team that the user is on.", "in": "query", "required": false, "schema": { "type": "string", "default": "owner,collaborator,organization_member" } }, { "name": "type", "description": "Can be one of `all`, `owner`, `public`, `private`, `member`. Note: For GitHub AE, can be one of `all`, `owner`, `internal`, `private`, `member`. Default: `all` \n \nWill cause a `422` error if used in the same request as **visibility** or **affiliation**. Will cause a `422` error if used in the same request as **visibility** or **affiliation**.", "in": "query", "required": false, "schema": { "type": "string", "enum": [ "all", "owner", "public", "private", "member" ], "default": "all" } }, { "name": "sort", "description": "Can be one of `created`, `updated`, `pushed`, `full_name`.", "in": "query", "required": false, "schema": { "type": "string", "enum": [ "created", "updated", "pushed", "full_name" ], "default": "full_name" } }, { "name": "direction", "description": "Can be one of `asc` or `desc`. Default: `asc` when using `full_name`, otherwise `desc`", "in": "query", "required": false, "schema": { "type": "string", "enum": [ "asc", "desc" ] } }, { "$ref": "#/components/parameters/per-page" }, { "$ref": "#/components/parameters/page" }, { "$ref": "#/components/parameters/since" }, { "$ref": "#/components/parameters/before" } ], "responses": { "200": { "description": "Response", "content": { "application/json": { "schema": { "type": "array", "items": { "$ref": "#/components/schemas/repository" } }, "examples": { "default": { "$ref": "#/components/examples/repository-items-default-response" } } } } }, "422": { "$ref": "#/components/responses/validation_failed" }, "304": { "$ref": "#/components/responses/not_modified" }, "403": { "$ref": "#/components/responses/forbidden" }, "401": { "$ref": "#/components/responses/requires_authentication" } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": false, "category": "repos", "subcategory": null } }, "post": { "summary": "Create a repository for the authenticated user", "description": "Creates a new repository for the authenticated user.\n\n**OAuth scope requirements**\n\nWhen using [OAuth](https://docs.github.com/enterprise-server@3.0/apps/building-oauth-apps/understanding-scopes-for-oauth-apps/), authorizations must include:\n\n* `public_repo` scope or `repo` scope to create a public repository. Note: For GitHub AE, use `repo` scope to create an internal repository.\n* `repo` scope to create a private repository.", "tags": [ "repos" ], "operationId": "repos/create-for-authenticated-user", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/repos#create-a-repository-for-the-authenticated-user" }, "parameters": [ ], "requestBody": { "required": true, "content": { "application/json": { "schema": { "properties": { "name": { "description": "The name of the repository.", "type": "string", "examples": [ "Team Environment" ] }, "description": { "description": "A short description of the repository.", "type": "string" }, "homepage": { "description": "A URL with more information about the repository.", "type": "string" }, "private": { "description": "Whether the repository is private.", "default": false, "type": "boolean" }, "has_issues": { "description": "Whether issues are enabled.", "default": true, "type": "boolean", "examples": [ true ] }, "has_projects": { "description": "Whether projects are enabled.", "default": true, "type": "boolean", "examples": [ true ] }, "has_wiki": { "description": "Whether the wiki is enabled.", "default": true, "type": "boolean", "examples": [ true ] }, "team_id": { "description": "The id of the team that will be granted access to this repository. This is only valid when creating a repository in an organization.", "type": "integer" }, "auto_init": { "description": "Whether the repository is initialized with a minimal README.", "default": false, "type": "boolean" }, "gitignore_template": { "description": "The desired language or platform to apply to the .gitignore.", "type": "string", "examples": [ "Haskell" ] }, "license_template": { "description": "The license keyword of the open source license for this repository.", "type": "string", "examples": [ "mit" ] }, "allow_squash_merge": { "description": "Whether to allow squash merges for pull requests.", "default": true, "type": "boolean", "examples": [ true ] }, "allow_merge_commit": { "description": "Whether to allow merge commits for pull requests.", "default": true, "type": "boolean", "examples": [ true ] }, "allow_rebase_merge": { "description": "Whether to allow rebase merges for pull requests.", "default": true, "type": "boolean", "examples": [ true ] }, "delete_branch_on_merge": { "description": "Whether to delete head branches when pull requests are merged", "default": false, "type": "boolean", "examples": [ false ] }, "has_downloads": { "description": "Whether downloads are enabled.", "default": true, "type": "boolean", "examples": [ true ] }, "is_template": { "description": "Whether this repository acts as a template that can be used to generate new repositories.", "default": false, "type": "boolean", "examples": [ true ] } }, "required": [ "name" ], "type": "object" } } } }, "responses": { "201": { "description": "Response", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/repository" }, "examples": { "default": { "$ref": "#/components/examples/repository" } } } }, "headers": { "Location": { "example": "https://api.github.com/repos/octocat/Hello-World", "schema": { "type": "string" } } } }, "401": { "$ref": "#/components/responses/requires_authentication" }, "304": { "$ref": "#/components/responses/not_modified" }, "404": { "$ref": "#/components/responses/not_found" }, "403": { "$ref": "#/components/responses/forbidden" }, "422": { "$ref": "#/components/responses/validation_failed" }, "400": { "$ref": "#/components/responses/bad_request" } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": false, "category": "repos", "previews": [ { "required": false, "name": "nebula", "note": "You can set the visibility of a repository using the new `visibility` parameter in the [Repositories API](https://docs.github.com/enterprise-server@3.0/rest/reference/repos/), and get a repository's visibility with a new response key. For more information, see the [blog post](https://developer.github.com/changes/2019-12-03-internal-visibility-changes/).\n\nTo access repository visibility during the preview period, you must provide a custom [media type](https://docs.github.com/enterprise-server@3.0/rest/overview/media-types) in the `Accept` header:\n```shell\napplication/vnd.github.nebula-preview+json\n```" }, { "required": false, "name": "baptiste", "note": "The `is_template` and `template_repository` keys are currently available for developer to preview. See [Create a repository using a template](https://docs.github.com/enterprise-server@3.0/rest/reference/repos#create-a-repository-using-a-template) to learn how to create template repositories. To access these new response keys during the preview period, you must provide a custom [media type](https://docs.github.com/enterprise-server@3.0/rest/overview/media-types) in the `Accept` header:\n\n```shell\napplication/vnd.github.baptiste-preview+json\n```" } ] } } }, "/user/repository_invitations": { "get": { "summary": "List repository invitations for the authenticated user", "description": "When authenticating as a user, this endpoint will list all currently open repository invitations for that user.", "tags": [ "repos" ], "operationId": "repos/list-invitations-for-authenticated-user", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/repos#list-repository-invitations-for-the-authenticated-user" }, "parameters": [ { "$ref": "#/components/parameters/per-page" }, { "$ref": "#/components/parameters/page" } ], "responses": { "200": { "description": "Response", "content": { "application/json": { "schema": { "type": "array", "items": { "$ref": "#/components/schemas/repository-invitation" } }, "examples": { "default": { "$ref": "#/components/examples/repository-invitation-items" } } } }, "headers": { "Link": { "$ref": "#/components/headers/link" } } }, "304": { "$ref": "#/components/responses/not_modified" }, "404": { "$ref": "#/components/responses/not_found" }, "403": { "$ref": "#/components/responses/forbidden" }, "401": { "$ref": "#/components/responses/requires_authentication" } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": false, "category": "repos", "subcategory": "invitations" } } }, "/user/repository_invitations/{invitation_id}": { "patch": { "summary": "Accept a repository invitation", "description": "", "tags": [ "repos" ], "operationId": "repos/accept-invitation-for-authenticated-user", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/repos#accept-a-repository-invitation" }, "parameters": [ { "$ref": "#/components/parameters/invitation-id" } ], "responses": { "204": { "description": "Response" }, "403": { "$ref": "#/components/responses/forbidden" }, "409": { "$ref": "#/components/responses/conflict" }, "404": { "$ref": "#/components/responses/not_found" }, "304": { "$ref": "#/components/responses/not_modified" } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": false, "category": "repos", "subcategory": "invitations" } }, "delete": { "summary": "Decline a repository invitation", "description": "", "tags": [ "repos" ], "operationId": "repos/decline-invitation-for-authenticated-user", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/repos#decline-a-repository-invitation" }, "parameters": [ { "$ref": "#/components/parameters/invitation-id" } ], "responses": { "204": { "description": "Response" }, "409": { "$ref": "#/components/responses/conflict" }, "304": { "$ref": "#/components/responses/not_modified" }, "404": { "$ref": "#/components/responses/not_found" }, "403": { "$ref": "#/components/responses/forbidden" } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": false, "category": "repos", "subcategory": "invitations" } } }, "/user/starred": { "get": { "summary": "List repositories starred by the authenticated user", "description": "Lists repositories the authenticated user has starred.\n\nYou can also find out _when_ stars were created by passing the following custom [media type](https://docs.github.com/enterprise-server@3.0/rest/overview/media-types/) via the `Accept` header:", "tags": [ "activity" ], "operationId": "activity/list-repos-starred-by-authenticated-user", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/activity#list-repositories-starred-by-the-authenticated-user" }, "parameters": [ { "$ref": "#/components/parameters/sort" }, { "$ref": "#/components/parameters/direction" }, { "$ref": "#/components/parameters/per-page" }, { "$ref": "#/components/parameters/page" } ], "responses": { "200": { "description": "Response", "content": { "application/json": { "schema": { "type": "array", "items": { "$ref": "#/components/schemas/repository" } }, "examples": { "default-response": { "$ref": "#/components/examples/repository-items-default-response" } } }, "application/vnd.github.v3.star+json": { "schema": { "type": "array", "items": { "$ref": "#/components/schemas/starred-repository" } }, "examples": { "alternative-response-with-star-creation-timestamps": { "$ref": "#/components/examples/starred-repository-items-alternative-response-with-star-creation-timestamps" } } } }, "headers": { "Link": { "$ref": "#/components/headers/link" } } }, "304": { "$ref": "#/components/responses/not_modified" }, "403": { "$ref": "#/components/responses/forbidden" }, "401": { "$ref": "#/components/responses/requires_authentication" } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": false, "category": "activity", "subcategory": "starring" } } }, "/user/starred/{owner}/{repo}": { "get": { "summary": "Check if a repository is starred by the authenticated user", "description": "", "tags": [ "activity" ], "operationId": "activity/check-repo-is-starred-by-authenticated-user", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/activity#check-if-a-repository-is-starred-by-the-authenticated-user" }, "parameters": [ { "$ref": "#/components/parameters/owner" }, { "$ref": "#/components/parameters/repo" } ], "responses": { "204": { "description": "Response if this repository is starred by you" }, "404": { "description": "Not Found if this repository is not starred by you", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/basic-error" } } } }, "401": { "$ref": "#/components/responses/requires_authentication" }, "304": { "$ref": "#/components/responses/not_modified" }, "403": { "$ref": "#/components/responses/forbidden" } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": false, "category": "activity", "subcategory": "starring" } }, "put": { "summary": "Star a repository for the authenticated user", "description": "Note that you'll need to set `Content-Length` to zero when calling out to this endpoint. For more information, see \"[HTTP verbs](https://docs.github.com/enterprise-server@3.0/rest/overview/resources-in-the-rest-api#http-verbs).\"", "tags": [ "activity" ], "operationId": "activity/star-repo-for-authenticated-user", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/activity#star-a-repository-for-the-authenticated-user" }, "parameters": [ { "$ref": "#/components/parameters/owner" }, { "$ref": "#/components/parameters/repo" } ], "responses": { "204": { "description": "Response" }, "403": { "$ref": "#/components/responses/forbidden" }, "404": { "$ref": "#/components/responses/not_found" }, "401": { "$ref": "#/components/responses/requires_authentication" }, "304": { "$ref": "#/components/responses/not_modified" } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": false, "category": "activity", "subcategory": "starring" } }, "delete": { "summary": "Unstar a repository for the authenticated user", "description": "", "tags": [ "activity" ], "operationId": "activity/unstar-repo-for-authenticated-user", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/activity#unstar-a-repository-for-the-authenticated-user" }, "parameters": [ { "$ref": "#/components/parameters/owner" }, { "$ref": "#/components/parameters/repo" } ], "responses": { "204": { "description": "Response" }, "404": { "$ref": "#/components/responses/not_found" }, "401": { "$ref": "#/components/responses/requires_authentication" }, "304": { "$ref": "#/components/responses/not_modified" }, "403": { "$ref": "#/components/responses/forbidden" } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": false, "category": "activity", "subcategory": "starring" } } }, "/user/subscriptions": { "get": { "summary": "List repositories watched by the authenticated user", "description": "Lists repositories the authenticated user is watching.", "tags": [ "activity" ], "operationId": "activity/list-watched-repos-for-authenticated-user", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/activity#list-repositories-watched-by-the-authenticated-user" }, "parameters": [ { "$ref": "#/components/parameters/per-page" }, { "$ref": "#/components/parameters/page" } ], "responses": { "200": { "description": "Response", "content": { "application/json": { "schema": { "type": "array", "items": { "$ref": "#/components/schemas/minimal-repository" } }, "examples": { "default": { "$ref": "#/components/examples/minimal-repository-items" } } } }, "headers": { "Link": { "$ref": "#/components/headers/link" } } }, "304": { "$ref": "#/components/responses/not_modified" }, "403": { "$ref": "#/components/responses/forbidden" }, "401": { "$ref": "#/components/responses/requires_authentication" } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": false, "category": "activity", "subcategory": "watching" } } }, "/user/teams": { "get": { "summary": "List teams for the authenticated user", "description": "List all of the teams across all of the organizations to which the authenticated user belongs. This method requires `user`, `repo`, or `read:org` [scope](https://docs.github.com/enterprise-server@3.0/apps/building-oauth-apps/understanding-scopes-for-oauth-apps/) when authenticating via [OAuth](https://docs.github.com/enterprise-server@3.0/apps/building-oauth-apps/).", "tags": [ "teams" ], "operationId": "teams/list-for-authenticated-user", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/teams#list-teams-for-the-authenticated-user" }, "parameters": [ { "$ref": "#/components/parameters/per-page" }, { "$ref": "#/components/parameters/page" } ], "responses": { "200": { "description": "Response", "content": { "application/json": { "schema": { "type": "array", "items": { "$ref": "#/components/schemas/team-full" } }, "examples": { "default": { "$ref": "#/components/examples/team-full-items" } } } }, "headers": { "Link": { "$ref": "#/components/headers/link" } } }, "304": { "$ref": "#/components/responses/not_modified" }, "404": { "$ref": "#/components/responses/not_found" }, "403": { "$ref": "#/components/responses/forbidden" } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": false, "category": "teams", "subcategory": null } } }, "/users": { "get": { "summary": "List users", "description": "Lists all users, in the order that they signed up on GitHub Enterprise Server. This list includes personal user accounts and organization accounts.\n\nNote: Pagination is powered exclusively by the `since` parameter. Use the [Link header](https://docs.github.com/enterprise-server@3.0/rest/overview/resources-in-the-rest-api#link-header) to get the URL for the next page of users.", "tags": [ "users" ], "operationId": "users/list", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/users#list-users" }, "parameters": [ { "$ref": "#/components/parameters/since-user" }, { "$ref": "#/components/parameters/per-page" } ], "responses": { "200": { "description": "Response", "content": { "application/json": { "schema": { "type": "array", "items": { "$ref": "#/components/schemas/simple-user" } }, "examples": { "default": { "$ref": "#/components/examples/simple-user-items" } } } }, "headers": { "Link": { "example": "; rel=\"next\"", "schema": { "type": "string" } } } }, "304": { "$ref": "#/components/responses/not_modified" } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": true, "category": "users", "subcategory": null } } }, "/users/{username}": { "get": { "summary": "Get a user", "description": "Provides publicly available information about someone with a GitHub account.\n\nGitHub Apps with the `Plan` user permission can use this endpoint to retrieve information about a user's GitHub Enterprise Server plan. The GitHub App must be authenticated as a user. See \"[Identifying and authorizing users for GitHub Apps](https://docs.github.com/enterprise-server@3.0/apps/building-github-apps/identifying-and-authorizing-users-for-github-apps/)\" for details about authentication. For an example response, see 'Response with GitHub Enterprise Server plan information' below\"\n\nThe `email` key in the following response is the publicly visible email address from your GitHub Enterprise Server [profile page](https://github.com/settings/profile). When setting up your profile, you can select a primary email address to be “public” which provides an email entry for this endpoint. If you do not set a public email address for `email`, then it will have a value of `null`. You only see publicly visible email addresses when authenticated with GitHub Enterprise Server. For more information, see [Authentication](https://docs.github.com/enterprise-server@3.0/rest/overview/resources-in-the-rest-api#authentication).\n\nThe Emails API enables you to list all of your email addresses, and toggle a primary email to be visible publicly. For more information, see \"[Emails API](https://docs.github.com/enterprise-server@3.0/rest/reference/users#emails)\".", "tags": [ "users" ], "operationId": "users/get-by-username", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/users#get-a-user" }, "parameters": [ { "$ref": "#/components/parameters/username" } ], "responses": { "200": { "description": "Response", "content": { "application/json": { "schema": { "oneOf": [ { "$ref": "#/components/schemas/private-user" }, { "$ref": "#/components/schemas/public-user" } ] }, "examples": { "default-response": { "$ref": "#/components/examples/public-user-default-response" }, "response-with-git-hub-plan-information": { "$ref": "#/components/examples/public-user-response-with-git-hub-plan-information" } } } } }, "404": { "$ref": "#/components/responses/not_found" } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": true, "category": "users", "subcategory": null } } }, "/users/{username}/events": { "get": { "summary": "List events for the authenticated user", "description": "If you are authenticated as the given user, you will see your private events. Otherwise, you'll only see public events.", "tags": [ "activity" ], "operationId": "activity/list-events-for-authenticated-user", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/activity#list-events-for-the-authenticated-user" }, "parameters": [ { "$ref": "#/components/parameters/username" }, { "$ref": "#/components/parameters/per-page" }, { "$ref": "#/components/parameters/page" } ], "responses": { "200": { "description": "Response", "content": { "application/json": { "schema": { "type": "array", "items": { "$ref": "#/components/schemas/event" } } } } } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": true, "category": "activity", "subcategory": "events" } } }, "/users/{username}/events/orgs/{org}": { "get": { "summary": "List organization events for the authenticated user", "description": "This is the user's organization dashboard. You must be authenticated as the user to view this.", "tags": [ "activity" ], "operationId": "activity/list-org-events-for-authenticated-user", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/activity#list-organization-events-for-the-authenticated-user" }, "parameters": [ { "$ref": "#/components/parameters/username" }, { "$ref": "#/components/parameters/org" }, { "$ref": "#/components/parameters/per-page" }, { "$ref": "#/components/parameters/page" } ], "responses": { "200": { "description": "Response", "content": { "application/json": { "schema": { "type": "array", "items": { "$ref": "#/components/schemas/event" } } } } } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": false, "category": "activity", "subcategory": "events" } } }, "/users/{username}/events/public": { "get": { "summary": "List public events for a user", "description": "", "tags": [ "activity" ], "operationId": "activity/list-public-events-for-user", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/activity#list-public-events-for-a-user" }, "parameters": [ { "$ref": "#/components/parameters/username" }, { "$ref": "#/components/parameters/per-page" }, { "$ref": "#/components/parameters/page" } ], "responses": { "200": { "description": "Response", "content": { "application/json": { "schema": { "type": "array", "items": { "$ref": "#/components/schemas/event" } } } } } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": true, "category": "activity", "subcategory": "events" } } }, "/users/{username}/followers": { "get": { "summary": "List followers of a user", "description": "Lists the people following the specified user.", "tags": [ "users" ], "operationId": "users/list-followers-for-user", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/users#list-followers-of-a-user" }, "parameters": [ { "$ref": "#/components/parameters/username" }, { "$ref": "#/components/parameters/per-page" }, { "$ref": "#/components/parameters/page" } ], "responses": { "200": { "description": "Response", "content": { "application/json": { "schema": { "type": "array", "items": { "$ref": "#/components/schemas/simple-user" } }, "examples": { "default": { "$ref": "#/components/examples/simple-user-items" } } } }, "headers": { "Link": { "$ref": "#/components/headers/link" } } } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": true, "category": "users", "subcategory": "followers" } } }, "/users/{username}/following": { "get": { "summary": "List the people a user follows", "description": "Lists the people who the specified user follows.", "tags": [ "users" ], "operationId": "users/list-following-for-user", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/users#list-the-people-a-user-follows" }, "parameters": [ { "$ref": "#/components/parameters/username" }, { "$ref": "#/components/parameters/per-page" }, { "$ref": "#/components/parameters/page" } ], "responses": { "200": { "description": "Response", "content": { "application/json": { "schema": { "type": "array", "items": { "$ref": "#/components/schemas/simple-user" } }, "examples": { "default": { "$ref": "#/components/examples/simple-user-items" } } } }, "headers": { "Link": { "$ref": "#/components/headers/link" } } } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": true, "category": "users", "subcategory": "followers" } } }, "/users/{username}/following/{target_user}": { "get": { "summary": "Check if a user follows another user", "description": "", "tags": [ "users" ], "operationId": "users/check-following-for-user", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/users#check-if-a-user-follows-another-user" }, "parameters": [ { "$ref": "#/components/parameters/username" }, { "name": "target_user", "in": "path", "required": true, "schema": { "type": "string" } } ], "responses": { "204": { "description": "if the user follows the target user" }, "404": { "description": "if the user does not follow the target user" } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": true, "category": "users", "subcategory": "followers" } } }, "/users/{username}/gists": { "get": { "summary": "List gists for a user", "description": "Lists public gists for the specified user:", "tags": [ "gists" ], "operationId": "gists/list-for-user", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/gists#list-gists-for-a-user" }, "parameters": [ { "$ref": "#/components/parameters/username" }, { "$ref": "#/components/parameters/since" }, { "$ref": "#/components/parameters/per-page" }, { "$ref": "#/components/parameters/page" } ], "responses": { "200": { "description": "Response", "content": { "application/json": { "schema": { "type": "array", "items": { "$ref": "#/components/schemas/base-gist" } }, "examples": { "default": { "$ref": "#/components/examples/base-gist-items" } } } }, "headers": { "Link": { "$ref": "#/components/headers/link" } } }, "422": { "$ref": "#/components/responses/validation_failed" } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": false, "category": "gists", "subcategory": null } } }, "/users/{username}/gpg_keys": { "get": { "summary": "List GPG keys for a user", "description": "Lists the GPG keys for a user. This information is accessible by anyone.", "tags": [ "users" ], "operationId": "users/list-gpg-keys-for-user", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/users#list-gpg-keys-for-a-user" }, "parameters": [ { "$ref": "#/components/parameters/username" }, { "$ref": "#/components/parameters/per-page" }, { "$ref": "#/components/parameters/page" } ], "responses": { "200": { "description": "Response", "content": { "application/json": { "schema": { "type": "array", "items": { "$ref": "#/components/schemas/gpg-key" } }, "examples": { "default": { "$ref": "#/components/examples/gpg-key-items" } } } }, "headers": { "Link": { "$ref": "#/components/headers/link" } } } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": true, "category": "users", "subcategory": "gpg-keys" } } }, "/users/{username}/hovercard": { "get": { "summary": "Get contextual information for a user", "description": "Provides hovercard information when authenticated through basic auth or OAuth with the `repo` scope. You can find out more about someone in relation to their pull requests, issues, repositories, and organizations.\n\nThe `subject_type` and `subject_id` parameters provide context for the person's hovercard, which returns more information than without the parameters. For example, if you wanted to find out more about `octocat` who owns the `Spoon-Knife` repository via cURL, it would look like this:\n\n```shell\n curl -u username:token\n https://api.github.com/users/octocat/hovercard?subject_type=repository&subject_id=1300192\n```", "tags": [ "users" ], "operationId": "users/get-context-for-user", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/users#get-contextual-information-for-a-user" }, "parameters": [ { "$ref": "#/components/parameters/username" }, { "name": "subject_type", "description": "Identifies which additional information you'd like to receive about the person's hovercard. Can be `organization`, `repository`, `issue`, `pull_request`. **Required** when using `subject_id`.", "in": "query", "required": false, "schema": { "type": "string", "enum": [ "organization", "repository", "issue", "pull_request" ] } }, { "name": "subject_id", "description": "Uses the ID for the `subject_type` you specified. **Required** when using `subject_type`.", "in": "query", "required": false, "schema": { "type": "string" } } ], "responses": { "200": { "description": "Response", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/hovercard" }, "examples": { "default": { "$ref": "#/components/examples/hovercard" } } } } }, "404": { "$ref": "#/components/responses/not_found" }, "422": { "$ref": "#/components/responses/validation_failed" } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": false, "category": "users", "subcategory": null } } }, "/users/{username}/installation": { "get": { "summary": "Get a user installation for the authenticated app", "description": "Enables an authenticated GitHub App to find the user’s installation information.\n\nYou must use a [JWT](https://docs.github.com/enterprise-server@3.0/apps/building-github-apps/authenticating-with-github-apps/#authenticating-as-a-github-app) to access this endpoint.", "tags": [ "apps" ], "operationId": "apps/get-user-installation", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/apps#get-a-user-installation-for-the-authenticated-app" }, "parameters": [ { "$ref": "#/components/parameters/username" } ], "responses": { "200": { "description": "Response", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/installation" }, "examples": { "default": { "$ref": "#/components/examples/installation" } } } } } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": false, "category": "apps", "subcategory": null } } }, "/users/{username}/keys": { "get": { "summary": "List public keys for a user", "description": "Lists the _verified_ public SSH keys for a user. This is accessible by anyone.", "tags": [ "users" ], "operationId": "users/list-public-keys-for-user", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/users#list-public-keys-for-a-user" }, "parameters": [ { "$ref": "#/components/parameters/username" }, { "$ref": "#/components/parameters/per-page" }, { "$ref": "#/components/parameters/page" } ], "responses": { "200": { "description": "Response", "content": { "application/json": { "schema": { "type": "array", "items": { "$ref": "#/components/schemas/key-simple" } }, "examples": { "default": { "$ref": "#/components/examples/key-simple-items" } } } }, "headers": { "Link": { "$ref": "#/components/headers/link" } } } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": true, "category": "users", "subcategory": "keys" } } }, "/users/{username}/orgs": { "get": { "summary": "List organizations for a user", "description": "List [public organization memberships](https://docs.github.com/articles/publicizing-or-concealing-organization-membership) for the specified user.\n\nThis method only lists _public_ memberships, regardless of authentication. If you need to fetch all of the organization memberships (public and private) for the authenticated user, use the [List organizations for the authenticated user](https://docs.github.com/enterprise-server@3.0/rest/reference/orgs#list-organizations-for-the-authenticated-user) API instead.", "tags": [ "orgs" ], "operationId": "orgs/list-for-user", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/orgs#list-organizations-for-a-user" }, "parameters": [ { "$ref": "#/components/parameters/username" }, { "$ref": "#/components/parameters/per-page" }, { "$ref": "#/components/parameters/page" } ], "responses": { "200": { "description": "Response", "content": { "application/json": { "schema": { "type": "array", "items": { "$ref": "#/components/schemas/organization-simple" } }, "examples": { "default": { "$ref": "#/components/examples/organization-simple-items" } } } }, "headers": { "Link": { "$ref": "#/components/headers/link" } } } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": true, "category": "orgs", "subcategory": null } } }, "/users/{username}/projects": { "get": { "summary": "List user projects", "description": "", "tags": [ "projects" ], "operationId": "projects/list-for-user", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/projects#list-user-projects" }, "parameters": [ { "$ref": "#/components/parameters/username" }, { "name": "state", "description": "Indicates the state of the projects to return. Can be either `open`, `closed`, or `all`.", "in": "query", "required": false, "schema": { "type": "string", "enum": [ "open", "closed", "all" ], "default": "open" } }, { "$ref": "#/components/parameters/per-page" }, { "$ref": "#/components/parameters/page" } ], "responses": { "200": { "description": "Response", "content": { "application/json": { "schema": { "type": "array", "items": { "$ref": "#/components/schemas/project" } }, "examples": { "default": { "$ref": "#/components/examples/project-items-3" } } } }, "headers": { "Link": { "$ref": "#/components/headers/link" } } }, "422": { "$ref": "#/components/responses/validation_failed" } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": false, "category": "projects", "previews": [ { "required": true, "name": "inertia", "note": "The Projects API is currently available for developers to preview. During the preview period, the API may change without advance notice. Please see the [blog post](https://developer.github.com/changes/2016-10-27-changes-to-projects-api) for full details. To access the API during the preview period, you must provide a custom [media type](https://docs.github.com/enterprise-server@3.0/rest/overview/media-types) in the `Accept` header:\n```shell\napplication/vnd.github.inertia-preview+json\n```" } ] } } }, "/users/{username}/received_events": { "get": { "summary": "List events received by the authenticated user", "description": "These are events that you've received by watching repos and following users. If you are authenticated as the given user, you will see private events. Otherwise, you'll only see public events.", "tags": [ "activity" ], "operationId": "activity/list-received-events-for-user", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/activity#list-events-received-by-the-authenticated-user" }, "parameters": [ { "$ref": "#/components/parameters/username" }, { "$ref": "#/components/parameters/per-page" }, { "$ref": "#/components/parameters/page" } ], "responses": { "200": { "description": "Response", "content": { "application/json": { "schema": { "type": "array", "items": { "$ref": "#/components/schemas/event" } } } } } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": true, "category": "activity", "subcategory": "events" } } }, "/users/{username}/received_events/public": { "get": { "summary": "List public events received by a user", "description": "", "tags": [ "activity" ], "operationId": "activity/list-received-public-events-for-user", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/activity#list-public-events-received-by-a-user" }, "parameters": [ { "$ref": "#/components/parameters/username" }, { "$ref": "#/components/parameters/per-page" }, { "$ref": "#/components/parameters/page" } ], "responses": { "200": { "description": "Response", "content": { "application/json": { "schema": { "type": "array", "items": { "$ref": "#/components/schemas/event" } } } } } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": true, "category": "activity", "subcategory": "events" } } }, "/users/{username}/repos": { "get": { "summary": "List repositories for a user", "description": "Lists public repositories for the specified user. Note: For GitHub AE, this endpoint will list internal repositories for the specified user.", "tags": [ "repos" ], "operationId": "repos/list-for-user", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/repos#list-repositories-for-a-user" }, "parameters": [ { "$ref": "#/components/parameters/username" }, { "name": "type", "description": "Can be one of `all`, `owner`, `member`.", "in": "query", "required": false, "schema": { "type": "string", "enum": [ "all", "owner", "member" ], "default": "owner" } }, { "name": "sort", "description": "Can be one of `created`, `updated`, `pushed`, `full_name`.", "in": "query", "required": false, "schema": { "type": "string", "enum": [ "created", "updated", "pushed", "full_name" ], "default": "full_name" } }, { "name": "direction", "description": "Can be one of `asc` or `desc`. Default: `asc` when using `full_name`, otherwise `desc`", "in": "query", "required": false, "schema": { "type": "string", "enum": [ "asc", "desc" ] } }, { "$ref": "#/components/parameters/per-page" }, { "$ref": "#/components/parameters/page" } ], "responses": { "200": { "description": "Response", "content": { "application/json": { "schema": { "type": "array", "items": { "$ref": "#/components/schemas/minimal-repository" } }, "examples": { "default": { "$ref": "#/components/examples/minimal-repository-items" } } } }, "headers": { "Link": { "$ref": "#/components/headers/link" } } } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": true, "category": "repos", "previews": [ { "required": false, "name": "nebula", "note": "You can set the visibility of a repository using the new `visibility` parameter in the [Repositories API](https://docs.github.com/enterprise-server@3.0/rest/reference/repos/), and get a repository's visibility with a new response key. For more information, see the [blog post](https://developer.github.com/changes/2019-12-03-internal-visibility-changes/).\n\nTo access repository visibility during the preview period, you must provide a custom [media type](https://docs.github.com/enterprise-server@3.0/rest/overview/media-types) in the `Accept` header:\n```shell\napplication/vnd.github.nebula-preview+json\n```" } ] } } }, "/users/{username}/site_admin": { "put": { "summary": "Promote a user to be a site administrator", "description": "Note that you'll need to set `Content-Length` to zero when calling out to this endpoint. For more information, see \"[HTTP verbs](https://docs.github.com/enterprise-server@3.0/rest/overview/resources-in-the-rest-api#http-verbs).\"", "operationId": "enterprise-admin/promote-user-to-be-site-administrator", "tags": [ "enterprise-admin" ], "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/enterprise-admin#promote-a-user-to-be-a-site-administrator" }, "parameters": [ { "$ref": "#/components/parameters/username" } ], "responses": { "204": { "description": "Response" } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": false, "category": "enterprise-admin", "subcategory": "users" } }, "delete": { "summary": "Demote a site administrator", "description": "You can demote any user account except your own.", "operationId": "enterprise-admin/demote-site-administrator", "tags": [ "enterprise-admin" ], "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/enterprise-admin#demote-a-site-administrator" }, "parameters": [ { "$ref": "#/components/parameters/username" } ], "responses": { "204": { "description": "Response" } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": false, "category": "enterprise-admin", "subcategory": "users" } } }, "/users/{username}/starred": { "get": { "summary": "List repositories starred by a user", "description": "Lists repositories a user has starred.\n\nYou can also find out _when_ stars were created by passing the following custom [media type](https://docs.github.com/enterprise-server@3.0/rest/overview/media-types/) via the `Accept` header:", "tags": [ "activity" ], "operationId": "activity/list-repos-starred-by-user", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/activity#list-repositories-starred-by-a-user" }, "parameters": [ { "$ref": "#/components/parameters/username" }, { "$ref": "#/components/parameters/sort" }, { "$ref": "#/components/parameters/direction" }, { "$ref": "#/components/parameters/per-page" }, { "$ref": "#/components/parameters/page" } ], "responses": { "200": { "description": "Response", "content": { "application/json": { "schema": { "anyOf": [ { "type": "array", "items": { "$ref": "#/components/schemas/starred-repository" } }, { "type": "array", "items": { "$ref": "#/components/schemas/repository" } } ] }, "examples": { "default-response": { "$ref": "#/components/examples/repository-items-default-response" } } } }, "headers": { "Link": { "$ref": "#/components/headers/link" } } } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": true, "category": "activity", "subcategory": "starring" } } }, "/users/{username}/subscriptions": { "get": { "summary": "List repositories watched by a user", "description": "Lists repositories a user is watching.", "tags": [ "activity" ], "operationId": "activity/list-repos-watched-by-user", "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/activity#list-repositories-watched-by-a-user" }, "parameters": [ { "$ref": "#/components/parameters/username" }, { "$ref": "#/components/parameters/per-page" }, { "$ref": "#/components/parameters/page" } ], "responses": { "200": { "description": "Response", "content": { "application/json": { "schema": { "type": "array", "items": { "$ref": "#/components/schemas/minimal-repository" } }, "examples": { "default": { "$ref": "#/components/examples/minimal-repository-items" } } } }, "headers": { "Link": { "$ref": "#/components/headers/link" } } } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": true, "category": "activity", "subcategory": "watching" } } }, "/users/{username}/suspended": { "put": { "summary": "Suspend a user", "description": "If your GitHub instance uses [LDAP Sync with Active Directory LDAP servers](https://docs.github.com/enterprise/admin/guides/user-management/using-ldap), Active Directory LDAP-authenticated users cannot be suspended through this API. If you attempt to suspend an Active Directory LDAP-authenticated user through this API, it will return a `403` response.\n\nYou can suspend any user account except your own.\n\nNote that, if you choose not to pass any parameters, you'll need to set `Content-Length` to zero when calling out to this endpoint. For more information, see \"[HTTP verbs](https://docs.github.com/enterprise-server@3.0/rest/overview/resources-in-the-rest-api#http-verbs).\"", "operationId": "enterprise-admin/suspend-user", "tags": [ "enterprise-admin" ], "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/enterprise-admin#suspend-a-user" }, "parameters": [ { "$ref": "#/components/parameters/username" } ], "responses": { "204": { "description": "Response" } }, "requestBody": { "content": { "application/json": { "schema": { "type": [ "object", "null" ], "properties": { "reason": { "type": "string", "description": "The reason the user is being suspended. This message will be logged in the [audit log](https://docs.github.com/enterprise/admin/articles/audit-logging/). If you don't provide a `reason`, it will default to \"Suspended via API by _SITE\\_ADMINISTRATOR_\", where _SITE\\_ADMINISTRATOR_ is the person who performed the action." } } } } } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": false, "category": "enterprise-admin", "subcategory": "users" } }, "delete": { "summary": "Unsuspend a user", "description": "If your GitHub instance uses [LDAP Sync with Active Directory LDAP servers](https://docs.github.com/enterprise/admin/guides/user-management/using-ldap), this API is disabled and will return a `403` response. Active Directory LDAP-authenticated users cannot be unsuspended using the API.", "operationId": "enterprise-admin/unsuspend-user", "tags": [ "enterprise-admin" ], "externalDocs": { "description": "API method documentation", "url": "https://docs.github.com/enterprise-server@3.0/rest/reference/enterprise-admin#unsuspend-a-user" }, "parameters": [ { "$ref": "#/components/parameters/username" } ], "responses": { "204": { "description": "Response" } }, "requestBody": { "content": { "application/json": { "schema": { "type": [ "object", "null" ], "properties": { "reason": { "type": "string", "description": "The reason the user is being unsuspended. This message will be logged in the [audit log](https://docs.github.com/enterprise/admin/articles/audit-logging/). If you don't provide a `reason`, it will default to \"Unsuspended via API by _SITE\\_ADMINISTRATOR_\", where _SITE\\_ADMINISTRATOR_ is the person who performed the action." } } } } } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": false, "category": "enterprise-admin", "subcategory": "users" } } }, "/zen": { "get": { "summary": "Get the Zen of GitHub", "description": "Get a random sentence from the Zen of GitHub", "tags": [ "meta" ], "operationId": "meta/get-zen", "responses": { "200": { "description": "Response", "content": { "text/plain": { "schema": { "type": "string" } } } } }, "x-github": { "githubCloudOnly": false, "enabledForGitHubApps": true, "category": "meta" } } } }, "components": { "parameters": { "per-page": { "name": "per_page", "description": "Results per page (max 100)", "in": "query", "schema": { "type": "integer", "default": 30 } }, "page": { "name": "page", "description": "Page number of the results to fetch.", "in": "query", "schema": { "type": "integer", "default": 1 } }, "hook-id": { "name": "hook_id", "in": "path", "required": true, "schema": { "type": "integer" } }, "direction": { "name": "direction", "description": "One of `asc` (ascending) or `desc` (descending).", "in": "query", "required": false, "schema": { "type": "string", "enum": [ "asc", "desc" ], "default": "desc" } }, "key-ids": { "name": "key_ids", "in": "path", "required": true, "schema": { "type": "string" } }, "team-id": { "name": "team_id", "in": "path", "required": true, "schema": { "type": "integer" } }, "username": { "name": "username", "in": "path", "required": true, "schema": { "type": "string" } }, "org": { "name": "org", "in": "path", "required": true, "schema": { "type": "string" } }, "pre-receive-environment-id": { "name": "pre_receive_environment_id", "in": "path", "required": true, "schema": { "type": "integer" } }, "pre-receive-hook-id": { "name": "pre_receive_hook_id", "description": "pre_receive_hook_id parameter", "in": "path", "required": true, "schema": { "type": "integer" } }, "token-id": { "name": "token_id", "in": "path", "required": true, "schema": { "type": "integer" } }, "since": { "name": "since", "description": "Only show notifications updated after the given time. This is a timestamp in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format: `YYYY-MM-DDTHH:MM:SSZ`.", "in": "query", "required": false, "schema": { "type": "string", "format": "date-time" } }, "installation-id": { "name": "installation_id", "description": "installation_id parameter", "in": "path", "required": true, "schema": { "type": "integer" } }, "grant-id": { "name": "grant_id", "description": "grant_id parameter", "in": "path", "required": true, "schema": { "type": "integer" } }, "client-id": { "name": "client_id", "in": "path", "required": true, "description": "The client ID of your GitHub app.", "schema": { "type": "string" } }, "access-token": { "name": "access_token", "in": "path", "required": true, "schema": { "type": "string" } }, "app-slug": { "name": "app_slug", "in": "path", "required": true, "schema": { "type": "string" } }, "authorization-id": { "name": "authorization_id", "description": "authorization_id parameter", "in": "path", "required": true, "schema": { "type": "integer" } }, "enterprise": { "name": "enterprise", "description": "The slug version of the enterprise name. You can also substitute this value with the enterprise id.", "in": "path", "required": true, "schema": { "type": "string" } }, "org-id": { "name": "org_id", "description": "Unique identifier of an organization.", "in": "path", "required": true, "schema": { "type": "integer" } }, "runner-group-id": { "name": "runner_group_id", "description": "Unique identifier of the self-hosted runner group.", "in": "path", "required": true, "schema": { "type": "integer" } }, "runner-id": { "name": "runner_id", "description": "Unique identifier of the self-hosted runner.", "in": "path", "required": true, "schema": { "type": "integer" } }, "gist-id": { "name": "gist_id", "description": "gist_id parameter", "in": "path", "required": true, "schema": { "type": "string" } }, "comment-id": { "name": "comment_id", "description": "comment_id parameter", "in": "path", "required": true, "schema": { "type": "integer" } }, "labels": { "name": "labels", "description": "A list of comma separated label names. Example: `bug,ui,@high`", "in": "query", "required": false, "schema": { "type": "string" } }, "owner": { "name": "owner", "in": "path", "required": true, "schema": { "type": "string" } }, "repo": { "name": "repo", "in": "path", "required": true, "schema": { "type": "string" } }, "all": { "name": "all", "description": "If `true`, show notifications marked as read.", "in": "query", "required": false, "schema": { "type": "boolean", "default": false } }, "participating": { "name": "participating", "description": "If `true`, only shows notifications in which the user is directly participating or mentioned.", "in": "query", "required": false, "schema": { "type": "boolean", "default": false } }, "before": { "name": "before", "description": "Only show notifications updated before the given time. This is a timestamp in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format: `YYYY-MM-DDTHH:MM:SSZ`.", "in": "query", "required": false, "schema": { "type": "string", "format": "date-time" } }, "thread-id": { "name": "thread_id", "description": "thread_id parameter", "in": "path", "required": true, "schema": { "type": "integer" } }, "since-org": { "name": "since", "description": "An organization ID. Only return organizations with an ID greater than this ID.", "in": "query", "required": false, "schema": { "type": "integer" } }, "repository-id": { "name": "repository_id", "in": "path", "required": true, "schema": { "type": "integer" } }, "secret-name": { "name": "secret_name", "description": "secret_name parameter", "in": "path", "required": true, "schema": { "type": "string" } }, "team-slug": { "name": "team_slug", "description": "team_slug parameter", "in": "path", "required": true, "schema": { "type": "string" } }, "discussion-number": { "name": "discussion_number", "in": "path", "required": true, "schema": { "type": "integer" } }, "comment-number": { "name": "comment_number", "in": "path", "required": true, "schema": { "type": "integer" } }, "reaction-id": { "name": "reaction_id", "in": "path", "required": true, "schema": { "type": "integer" } }, "project-id": { "name": "project_id", "in": "path", "required": true, "schema": { "type": "integer" } }, "card-id": { "name": "card_id", "description": "card_id parameter", "in": "path", "required": true, "schema": { "type": "integer" } }, "column-id": { "name": "column_id", "description": "column_id parameter", "in": "path", "required": true, "schema": { "type": "integer" } }, "artifact-id": { "name": "artifact_id", "description": "artifact_id parameter", "in": "path", "required": true, "schema": { "type": "integer" } }, "job-id": { "name": "job_id", "description": "job_id parameter", "in": "path", "required": true, "schema": { "type": "integer" } }, "actor": { "name": "actor", "description": "Returns someone's workflow runs. Use the login for the user who created the `push` associated with the check suite or workflow run.", "in": "query", "required": false, "schema": { "type": "string" } }, "workflow-run-branch": { "name": "branch", "description": "Returns workflow runs associated with a branch. Use the name of the branch of the `push`.", "in": "query", "required": false, "schema": { "type": "string" } }, "event": { "name": "event", "description": "Returns workflow run triggered by the event you specify. For example, `push`, `pull_request` or `issue`. For more information, see \"[Events that trigger workflows](https://docs.github.com/en/actions/automating-your-workflow-with-github-actions/events-that-trigger-workflows).\"", "in": "query", "required": false, "schema": { "type": "string" } }, "workflow-run-status": { "name": "status", "description": "Returns workflow runs with the check run `status` or `conclusion` that you specify. For example, a conclusion can be `success` or a status can be `in_progress`. Only GitHub can set a status of `waiting` or `requested`. For a list of the possible `status` and `conclusion` options, see \"[Create a check run](https://docs.github.com/enterprise-server@3.0/rest/reference/checks#create-a-check-run).\"", "in": "query", "required": false, "schema": { "type": "string", "enum": [ "completed", "action_required", "cancelled", "failure", "neutral", "skipped", "stale", "success", "timed_out", "in_progress", "queued", "requested", "waiting" ] } }, "created": { "name": "created", "description": "Returns workflow runs created within the given date-time range. For more information on the syntax, see \"[Understanding the search syntax](https://docs.github.com/enterprise-server@3.0/search-github/getting-started-with-searching-on-github/understanding-the-search-syntax#query-for-dates).\"", "in": "query", "required": false, "schema": { "type": "string", "format": "date-time" } }, "exclude-pull-requests": { "name": "exclude_pull_requests", "description": "If `true` pull requests are omitted from the response (empty array).", "in": "query", "required": false, "schema": { "type": "boolean", "default": false } }, "run-id": { "name": "run_id", "description": "The id of the workflow run.", "in": "path", "required": true, "schema": { "type": "integer" } }, "workflow-id": { "name": "workflow_id", "in": "path", "description": "The ID of the workflow. You can also pass the workflow file name as a string.", "required": true, "schema": { "oneOf": [ { "type": "integer" }, { "type": "string" } ] } }, "branch": { "name": "branch", "description": "The name of the branch.", "in": "path", "required": true, "schema": { "type": "string" }, "x-multi-segment": true }, "check-run-id": { "name": "check_run_id", "description": "check_run_id parameter", "in": "path", "required": true, "schema": { "type": "integer" } }, "check-suite-id": { "name": "check_suite_id", "description": "check_suite_id parameter", "in": "path", "required": true, "schema": { "type": "integer" } }, "check-name": { "name": "check_name", "description": "Returns check runs with the specified `name`.", "in": "query", "required": false, "schema": { "type": "string" } }, "status": { "name": "status", "description": "Returns check runs with the specified `status`. Can be one of `queued`, `in_progress`, or `completed`.", "in": "query", "required": false, "schema": { "type": "string", "enum": [ "queued", "in_progress", "completed" ] } }, "tool-name": { "name": "tool_name", "description": "The name of a code scanning tool. Only results by this tool will be listed. You can specify the tool by using either `tool_name` or `tool_guid`, but not both.", "in": "query", "required": false, "schema": { "$ref": "#/components/schemas/code-scanning-analysis-tool-name" } }, "tool-guid": { "name": "tool_guid", "description": "The GUID of a code scanning tool. Only results by this tool will be listed. Note that some code scanning tools may not include a GUID in their analysis data. You can specify the tool by using either `tool_guid` or `tool_name`, but not both.", "in": "query", "required": false, "schema": { "$ref": "#/components/schemas/code-scanning-analysis-tool-guid" } }, "git-ref": { "name": "ref", "description": "The Git reference for the results you want to list. The `ref` for a branch can be formatted either as `refs/heads/` or simply ``. To reference a pull request use `refs/pull//merge`.", "in": "query", "required": false, "schema": { "$ref": "#/components/schemas/code-scanning-ref" } }, "alert-number": { "name": "alert_number", "in": "path", "description": "The number that identifies an alert. You can find this at the end of the URL for a code scanning alert within GitHub, and in the `number` field in the response from the `GET /repos/{owner}/{repo}/code-scanning/alerts` operation.", "required": true, "schema": { "$ref": "#/components/schemas/alert-number" } }, "commit-sha": { "name": "commit_sha", "description": "commit_sha parameter", "in": "path", "required": true, "schema": { "type": "string" }, "x-multi-segment": true }, "deployment-id": { "name": "deployment_id", "description": "deployment_id parameter", "in": "path", "required": true, "schema": { "type": "integer" } }, "invitation-id": { "name": "invitation_id", "description": "invitation_id parameter", "in": "path", "required": true, "schema": { "type": "integer" } }, "sort": { "name": "sort", "description": "One of `created` (when the repository was starred) or `updated` (when it was last pushed to).", "in": "query", "required": false, "schema": { "type": "string", "enum": [ "created", "updated" ], "default": "created" } }, "issue-number": { "name": "issue_number", "description": "issue_number parameter", "in": "path", "required": true, "schema": { "type": "integer" } }, "key-id": { "name": "key_id", "description": "key_id parameter", "in": "path", "required": true, "schema": { "type": "integer" } }, "milestone-number": { "name": "milestone_number", "description": "milestone_number parameter", "in": "path", "required": true, "schema": { "type": "integer" } }, "pull-number": { "name": "pull_number", "in": "path", "required": true, "schema": { "type": "integer" } }, "review-id": { "name": "review_id", "description": "review_id parameter", "in": "path", "required": true, "schema": { "type": "integer" } }, "asset-id": { "name": "asset_id", "description": "asset_id parameter", "in": "path", "required": true, "schema": { "type": "integer" } }, "release-id": { "name": "release_id", "description": "release_id parameter", "in": "path", "required": true, "schema": { "type": "integer" } }, "since-repo": { "name": "since", "description": "A repository ID. Only return repositories with an ID greater than this ID.", "in": "query", "required": false, "schema": { "type": "integer" } }, "order": { "name": "order", "description": "Determines whether the first search result returned is the highest number of matches (`desc`) or lowest number of matches (`asc`). This parameter is ignored unless you provide `sort`.", "in": "query", "required": false, "schema": { "type": "string", "enum": [ "desc", "asc" ], "default": "desc" } }, "gpg-key-id": { "name": "gpg_key_id", "description": "gpg_key_id parameter", "in": "path", "required": true, "schema": { "type": "integer" } }, "since-user": { "name": "since", "description": "A user ID. Only return users with an ID greater than this ID.", "in": "query", "required": false, "schema": { "type": "integer" } } }, "schemas": { "global-hook": { "type": "object", "properties": { "type": { "type": "string" }, "id": { "type": "integer" }, "name": { "type": "string" }, "active": { "type": "boolean" }, "events": { "type": "array", "items": { "type": "string" } }, "config": { "type": "object", "properties": { "url": { "type": "string" }, "content_type": { "type": "string" }, "insecure_ssl": { "type": "string" }, "secret": { "type": "string" } } }, "updated_at": { "type": "string" }, "created_at": { "type": "string" }, "url": { "type": "string" }, "ping_url": { "type": "string" } } }, "global-hook-2": { "type": "object", "properties": { "type": { "type": "string" }, "id": { "type": "integer" }, "name": { "type": "string" }, "active": { "type": "boolean" }, "events": { "type": "array", "items": { "type": "string" } }, "config": { "type": "object", "properties": { "url": { "type": "string" }, "content_type": { "type": "string" }, "insecure_ssl": { "type": "string" } } }, "updated_at": { "type": "string" }, "created_at": { "type": "string" }, "url": { "type": "string" }, "ping_url": { "type": "string" } } }, "public-key-full": { "type": "object", "properties": { "id": { "type": "integer" }, "key": { "type": "string" }, "user_id": { "type": [ "integer", "null" ] }, "repository_id": { "type": [ "integer", "null" ] }, "url": { "type": "string" }, "title": { "type": "string" }, "read_only": { "type": "boolean" }, "verified": { "type": "boolean" }, "created_at": { "type": "string", "format": "date-time" }, "last_used": { "type": [ "string", "null" ], "format": "date-time" } }, "required": [ "id", "key", "url", "title", "verified", "created_at", "read_only", "last_used", "user_id", "repository_id" ] }, "ldap-mapping-team": { "type": "object", "properties": { "ldap_dn": { "type": "string" }, "id": { "type": "integer" }, "node_id": { "type": "string" }, "url": { "type": "string" }, "html_url": { "type": "string" }, "name": { "type": "string" }, "slug": { "type": "string" }, "description": { "type": [ "string", "null" ] }, "privacy": { "type": "string" }, "permission": { "type": "string" }, "members_url": { "type": "string" }, "repositories_url": { "type": "string" }, "parent": { "type": [ "null" ] } } }, "ldap-mapping-user": { "title": "Ldap Private User", "description": "Ldap Private User", "type": "object", "properties": { "ldap_dn": { "type": "string" }, "login": { "type": "string", "examples": [ "octocat" ] }, "id": { "type": "integer", "examples": [ 1 ] }, "node_id": { "type": "string", "examples": [ "MDQ6VXNlcjE=" ] }, "avatar_url": { "type": "string", "format": "uri", "examples": [ "https://github.com/images/error/octocat_happy.gif" ] }, "gravatar_id": { "type": [ "string", "null" ], "examples": [ "41d064eb2195891e12d0413f63227ea7" ] }, "url": { "type": "string", "format": "uri", "examples": [ "https://api.github.com/users/octocat" ] }, "html_url": { "type": "string", "format": "uri", "examples": [ "https://github.com/octocat" ] }, "followers_url": { "type": "string", "format": "uri", "examples": [ "https://api.github.com/users/octocat/followers" ] }, "following_url": { "type": "string", "examples": [ "https://api.github.com/users/octocat/following{/other_user}" ] }, "gists_url": { "type": "string", "examples": [ "https://api.github.com/users/octocat/gists{/gist_id}" ] }, "starred_url": { "type": "string", "examples": [ "https://api.github.com/users/octocat/starred{/owner}{/repo}" ] }, "subscriptions_url": { "type": "string", "format": "uri", "examples": [ "https://api.github.com/users/octocat/subscriptions" ] }, "organizations_url": { "type": "string", "format": "uri", "examples": [ "https://api.github.com/users/octocat/orgs" ] }, "repos_url": { "type": "string", "format": "uri", "examples": [ "https://api.github.com/users/octocat/repos" ] }, "events_url": { "type": "string", "examples": [ "https://api.github.com/users/octocat/events{/privacy}" ] }, "received_events_url": { "type": "string", "format": "uri", "examples": [ "https://api.github.com/users/octocat/received_events" ] }, "type": { "type": "string", "examples": [ "User" ] }, "site_admin": { "type": "boolean" }, "name": { "type": [ "string", "null" ], "examples": [ "monalisa octocat" ] }, "company": { "type": [ "string", "null" ], "examples": [ "GitHub" ] }, "blog": { "type": [ "string", "null" ], "examples": [ "https://github.com/blog" ] }, "location": { "type": [ "string", "null" ], "examples": [ "San Francisco" ] }, "email": { "type": [ "string", "null" ], "format": "email", "examples": [ "octocat@github.com" ] }, "hireable": { "type": [ "boolean", "null" ] }, "bio": { "type": [ "string", "null" ], "examples": [ "There once was..." ] }, "twitter_username": { "type": [ "string", "null" ], "examples": [ "monalisa" ] }, "public_repos": { "type": "integer", "examples": [ 2 ] }, "public_gists": { "type": "integer", "examples": [ 1 ] }, "followers": { "type": "integer", "examples": [ 20 ] }, "following": { "type": "integer", "examples": [ 0 ] }, "created_at": { "type": "string", "format": "date-time", "examples": [ "2008-01-14T04:33:35Z" ] }, "updated_at": { "type": "string", "format": "date-time", "examples": [ "2008-01-14T04:33:35Z" ] }, "private_gists": { "type": "integer", "examples": [ 81 ] }, "total_private_repos": { "type": "integer", "examples": [ 100 ] }, "owned_private_repos": { "type": "integer", "examples": [ 100 ] }, "disk_usage": { "type": "integer", "examples": [ 10000 ] }, "collaborators": { "type": "integer", "examples": [ 8 ] }, "two_factor_authentication": { "type": "boolean", "examples": [ true ] }, "plan": { "type": "object", "properties": { "collaborators": { "type": "integer" }, "name": { "type": "string" }, "space": { "type": "integer" }, "private_repos": { "type": "integer" } }, "required": [ "collaborators", "name", "space", "private_repos" ] }, "suspended_at": { "type": "string", "format": "date-time" }, "business_plus": { "type": "boolean" } }, "required": [ "avatar_url", "events_url", "followers_url", "following_url", "gists_url", "gravatar_id", "html_url", "id", "node_id", "login", "organizations_url", "received_events_url", "repos_url", "site_admin", "starred_url", "subscriptions_url", "type", "url", "bio", "blog", "company", "email", "followers", "following", "hireable", "location", "name", "public_gists", "public_repos", "created_at", "updated_at", "collaborators", "disk_usage", "owned_private_repos", "private_gists", "total_private_repos", "two_factor_authentication" ] }, "organization-simple": { "title": "Organization Simple", "description": "Organization Simple", "type": "object", "properties": { "login": { "type": "string", "examples": [ "github" ] }, "id": { "type": "integer", "examples": [ 1 ] }, "node_id": { "type": "string", "examples": [ "MDEyOk9yZ2FuaXphdGlvbjE=" ] }, "url": { "type": "string", "format": "uri", "examples": [ "https://api.github.com/orgs/github" ] }, "repos_url": { "type": "string", "format": "uri", "examples": [ "https://api.github.com/orgs/github/repos" ] }, "events_url": { "type": "string", "format": "uri", "examples": [ "https://api.github.com/orgs/github/events" ] }, "hooks_url": { "type": "string", "examples": [ "https://api.github.com/orgs/github/hooks" ] }, "issues_url": { "type": "string", "examples": [ "https://api.github.com/orgs/github/issues" ] }, "members_url": { "type": "string", "examples": [ "https://api.github.com/orgs/github/members{/member}" ] }, "public_members_url": { "type": "string", "examples": [ "https://api.github.com/orgs/github/public_members{/member}" ] }, "avatar_url": { "type": "string", "examples": [ "https://github.com/images/error/octocat_happy.gif" ] }, "description": { "type": [ "string", "null" ], "examples": [ "A great organization" ] } }, "required": [ "login", "url", "id", "node_id", "repos_url", "events_url", "hooks_url", "issues_url", "members_url", "public_members_url", "avatar_url", "description" ] }, "pre-receive-environment": { "type": "object", "properties": { "id": { "type": "integer" }, "name": { "type": "string" }, "image_url": { "type": "string" }, "url": { "type": "string" }, "html_url": { "type": "string" }, "default_environment": { "type": "boolean" }, "created_at": { "type": "string" }, "hooks_count": { "type": "integer" }, "download": { "type": "object", "properties": { "url": { "type": "string" }, "state": { "type": "string" }, "downloaded_at": { "type": [ "string", "null" ] }, "message": { "type": [ "string", "null" ] } } } } }, "pre-receive-environment-download-status": { "type": "object", "properties": { "url": { "type": "string" }, "state": { "type": "string" }, "downloaded_at": { "type": [ "string", "null" ] }, "message": { "type": [ "string", "null" ] } } }, "pre-receive-hook": { "type": "object", "properties": { "id": { "type": "integer" }, "name": { "type": "string" }, "enforcement": { "type": "string" }, "script": { "type": "string" }, "script_repository": { "type": "object", "properties": { "id": { "type": "integer" }, "full_name": { "type": "string" }, "url": { "type": "string" }, "html_url": { "type": "string" } } }, "environment": { "type": "object", "properties": { "id": { "type": "integer" }, "name": { "type": "string" }, "image_url": { "type": "string" }, "url": { "type": "string" }, "html_url": { "type": "string" }, "default_environment": { "type": "boolean" }, "created_at": { "type": "string" }, "hooks_count": { "type": "integer" }, "download": { "type": "object", "properties": { "url": { "type": "string" }, "state": { "type": "string" }, "downloaded_at": { "type": [ "string", "null" ] }, "message": { "type": [ "string", "null" ] } } } } }, "allow_downstream_configuration": { "type": "boolean" } } }, "simple-user": { "title": "Simple User", "description": "Simple User", "type": "object", "properties": { "name": { "type": [ "string", "null" ] }, "email": { "type": [ "string", "null" ] }, "login": { "type": "string", "examples": [ "octocat" ] }, "id": { "type": "integer", "examples": [ 1 ] }, "node_id": { "type": "string", "examples": [ "MDQ6VXNlcjE=" ] }, "avatar_url": { "type": "string", "format": "uri", "examples": [ "https://github.com/images/error/octocat_happy.gif" ] }, "gravatar_id": { "type": [ "string", "null" ], "examples": [ "41d064eb2195891e12d0413f63227ea7" ] }, "url": { "type": "string", "format": "uri", "examples": [ "https://api.github.com/users/octocat" ] }, "html_url": { "type": "string", "format": "uri", "examples": [ "https://github.com/octocat" ] }, "followers_url": { "type": "string", "format": "uri", "examples": [ "https://api.github.com/users/octocat/followers" ] }, "following_url": { "type": "string", "examples": [ "https://api.github.com/users/octocat/following{/other_user}" ] }, "gists_url": { "type": "string", "examples": [ "https://api.github.com/users/octocat/gists{/gist_id}" ] }, "starred_url": { "type": "string", "examples": [ "https://api.github.com/users/octocat/starred{/owner}{/repo}" ] }, "subscriptions_url": { "type": "string", "format": "uri", "examples": [ "https://api.github.com/users/octocat/subscriptions" ] }, "organizations_url": { "type": "string", "format": "uri", "examples": [ "https://api.github.com/users/octocat/orgs" ] }, "repos_url": { "type": "string", "format": "uri", "examples": [ "https://api.github.com/users/octocat/repos" ] }, "events_url": { "type": "string", "examples": [ "https://api.github.com/users/octocat/events{/privacy}" ] }, "received_events_url": { "type": "string", "format": "uri", "examples": [ "https://api.github.com/users/octocat/received_events" ] }, "type": { "type": "string", "examples": [ "User" ] }, "site_admin": { "type": "boolean" }, "starred_at": { "type": "string", "examples": [ "\"2020-07-09T00:17:55Z\"" ] } }, "required": [ "avatar_url", "events_url", "followers_url", "following_url", "gists_url", "gravatar_id", "html_url", "id", "node_id", "login", "organizations_url", "received_events_url", "repos_url", "site_admin", "starred_url", "subscriptions_url", "type", "url" ] }, "app-permissions": { "title": "App Permissions", "type": "object", "description": "The permissions granted to the user-to-server access token.", "properties": { "actions": { "type": "string", "description": "The level of permission to grant the access token for GitHub Actions workflows, workflow runs, and artifacts. Can be one of: `read` or `write`.", "enum": [ "read", "write" ] }, "administration": { "type": "string", "description": "The level of permission to grant the access token for repository creation, deletion, settings, teams, and collaborators creation. Can be one of: `read` or `write`.", "enum": [ "read", "write" ] }, "checks": { "type": "string", "description": "The level of permission to grant the access token for checks on code. Can be one of: `read` or `write`.", "enum": [ "read", "write" ] }, "contents": { "type": "string", "description": "The level of permission to grant the access token for repository contents, commits, branches, downloads, releases, and merges. Can be one of: `read` or `write`.", "enum": [ "read", "write" ] }, "deployments": { "type": "string", "description": "The level of permission to grant the access token for deployments and deployment statuses. Can be one of: `read` or `write`.", "enum": [ "read", "write" ] }, "environments": { "type": "string", "description": "The level of permission to grant the access token for managing repository environments. Can be one of: `read` or `write`.", "enum": [ "read", "write" ] }, "issues": { "type": "string", "description": "The level of permission to grant the access token for issues and related comments, assignees, labels, and milestones. Can be one of: `read` or `write`.", "enum": [ "read", "write" ] }, "metadata": { "type": "string", "description": "The level of permission to grant the access token to search repositories, list collaborators, and access repository metadata. Can be one of: `read` or `write`.", "enum": [ "read", "write" ] }, "packages": { "type": "string", "description": "The level of permission to grant the access token for packages published to GitHub Packages. Can be one of: `read` or `write`.", "enum": [ "read", "write" ] }, "pages": { "type": "string", "description": "The level of permission to grant the access token to retrieve Pages statuses, configuration, and builds, as well as create new builds. Can be one of: `read` or `write`.", "enum": [ "read", "write" ] }, "pull_requests": { "type": "string", "description": "The level of permission to grant the access token for pull requests and related comments, assignees, labels, milestones, and merges. Can be one of: `read` or `write`.", "enum": [ "read", "write" ] }, "repository_hooks": { "type": "string", "description": "The level of permission to grant the access token to manage the post-receive hooks for a repository. Can be one of: `read` or `write`.", "enum": [ "read", "write" ] }, "repository_projects": { "type": "string", "description": "The level of permission to grant the access token to manage repository projects, columns, and cards. Can be one of: `read`, `write`, or `admin`.", "enum": [ "read", "write", "admin" ] }, "secret_scanning_alerts": { "type": "string", "description": "The level of permission to grant the access token to view and manage secret scanning alerts. Can be one of: `read` or `write`.", "enum": [ "read", "write" ] }, "secrets": { "type": "string", "description": "The level of permission to grant the access token to manage repository secrets. Can be one of: `read` or `write`.", "enum": [ "read", "write" ] }, "security_events": { "type": "string", "description": "The level of permission to grant the access token to view and manage security events like code scanning alerts. Can be one of: `read` or `write`.", "enum": [ "read", "write" ] }, "single_file": { "type": "string", "description": "The level of permission to grant the access token to manage just a single file. Can be one of: `read` or `write`.", "enum": [ "read", "write" ] }, "statuses": { "type": "string", "description": "The level of permission to grant the access token for commit statuses. Can be one of: `read` or `write`.", "enum": [ "read", "write" ] }, "vulnerability_alerts": { "type": "string", "description": "The level of permission to grant the access token to manage Dependabot alerts. Can be one of: `read` or `write`.", "enum": [ "read", "write" ] }, "workflows": { "type": "string", "description": "The level of permission to grant the access token to update GitHub Actions workflow files. Can be one of: `write`.", "enum": [ "write" ] }, "members": { "type": "string", "description": "The level of permission to grant the access token for organization teams and members. Can be one of: `read` or `write`.", "enum": [ "read", "write" ] }, "organization_administration": { "type": "string", "description": "The level of permission to grant the access token to manage access to an organization. Can be one of: `read` or `write`.", "enum": [ "read", "write" ] }, "organization_hooks": { "type": "string", "description": "The level of permission to grant the access token to manage the post-receive hooks for an organization. Can be one of: `read` or `write`.", "enum": [ "read", "write" ] }, "organization_plan": { "type": "string", "description": "The level of permission to grant the access token for viewing an organization's plan. Can be one of: `read`.", "enum": [ "read" ] }, "organization_projects": { "type": "string", "description": "The level of permission to grant the access token to manage organization projects and projects beta (where available). Can be one of: `read`, `write`, or `admin`.", "enum": [ "read", "write", "admin" ] }, "organization_packages": { "type": "string", "description": "The level of permission to grant the access token for organization packages published to GitHub Packages. Can be one of: `read` or `write`.", "enum": [ "read", "write" ] }, "organization_secrets": { "type": "string", "description": "The level of permission to grant the access token to manage organization secrets. Can be one of: `read` or `write`.", "enum": [ "read", "write" ] }, "organization_self_hosted_runners": { "type": "string", "description": "The level of permission to grant the access token to view and manage GitHub Actions self-hosted runners available to an organization. Can be one of: `read` or `write`.", "enum": [ "read", "write" ] }, "organization_user_blocking": { "type": "string", "description": "The level of permission to grant the access token to view and manage users blocked by the organization. Can be one of: `read` or `write`.", "enum": [ "read", "write" ] }, "team_discussions": { "type": "string", "description": "The level of permission to grant the access token to manage team discussions and related comments. Can be one of: `read` or `write`.", "enum": [ "read", "write" ] }, "content_references": { "type": "string", "description": "The level of permission to grant the access token for notification of content references and creation content attachments. Can be one of: `read` or `write`.", "enum": [ "read", "write" ] } }, "example": { "contents": "read", "issues": "read", "deployments": "write", "single_file": "read" } }, "scoped-installation": { "title": "Scoped Installation", "type": "object", "properties": { "permissions": { "$ref": "#/components/schemas/app-permissions" }, "repository_selection": { "description": "Describe whether all repositories have been selected or there's a selection involved", "type": "string", "enum": [ "all", "selected" ] }, "single_file_name": { "type": [ "string", "null" ], "examples": [ "config.yaml" ] }, "has_multiple_single_files": { "type": "boolean", "examples": [ true ] }, "single_file_paths": { "type": "array", "items": { "type": "string" }, "examples": [ "config.yml", ".github/issue_TEMPLATE.md" ] }, "repositories_url": { "type": "string", "format": "uri", "examples": [ "https://api.github.com/users/octocat/repos" ] }, "account": { "$ref": "#/components/schemas/simple-user" } }, "required": [ "permissions", "repository_selection", "single_file_name", "repositories_url", "account" ] }, "authorization": { "title": "Authorization", "description": "The authorization for an OAuth app, GitHub App, or a Personal Access Token.", "type": "object", "properties": { "id": { "type": "integer" }, "url": { "type": "string", "format": "uri" }, "scopes": { "description": "A list of scopes that this authorization is in.", "type": [ "array", "null" ], "items": { "type": "string" } }, "token": { "type": "string" }, "token_last_eight": { "type": [ "string", "null" ] }, "hashed_token": { "type": [ "string", "null" ] }, "app": { "type": "object", "properties": { "client_id": { "type": "string" }, "name": { "type": "string" }, "url": { "type": "string", "format": "uri" } }, "required": [ "client_id", "name", "url" ] }, "note": { "type": [ "string", "null" ] }, "note_url": { "type": [ "string", "null" ], "format": "uri" }, "updated_at": { "type": "string", "format": "date-time" }, "created_at": { "type": "string", "format": "date-time" }, "fingerprint": { "type": [ "string", "null" ] }, "user": { "anyOf": [ { "type": "null" }, { "$ref": "#/components/schemas/simple-user" } ] }, "installation": { "anyOf": [ { "type": "null" }, { "$ref": "#/components/schemas/scoped-installation" } ] } }, "required": [ "app", "id", "note", "note_url", "scopes", "token", "hashed_token", "token_last_eight", "fingerprint", "url", "created_at", "updated_at", "expires_at" ] }, "integration": { "title": "GitHub app", "description": "GitHub apps are a new way to extend GitHub. They can be installed directly on organizations and user accounts and granted access to specific repositories. They come with granular permissions and built-in webhooks. GitHub apps are first class actors within GitHub.", "type": "object", "properties": { "id": { "description": "Unique identifier of the GitHub app", "type": "integer", "examples": [ 37 ] }, "slug": { "description": "The slug name of the GitHub app", "type": "string", "examples": [ "probot-owners" ] }, "node_id": { "type": "string", "examples": [ "MDExOkludGVncmF0aW9uMQ==" ] }, "owner": { "anyOf": [ { "type": "null" }, { "$ref": "#/components/schemas/simple-user" } ] }, "name": { "description": "The name of the GitHub app", "type": "string", "examples": [ "Probot Owners" ] }, "description": { "type": [ "string", "null" ], "examples": [ "The description of the app." ] }, "external_url": { "type": "string", "format": "uri", "examples": [ "https://example.com" ] }, "html_url": { "type": "string", "format": "uri", "examples": [ "https://github.com/apps/super-ci" ] }, "created_at": { "type": "string", "format": "date-time", "examples": [ "2017-07-08T16:18:44-04:00" ] }, "updated_at": { "type": "string", "format": "date-time", "examples": [ "2017-07-08T16:18:44-04:00" ] }, "permissions": { "description": "The set of permissions for the GitHub app", "type": "object", "properties": { "issues": { "type": "string" }, "checks": { "type": "string" }, "metadata": { "type": "string" }, "contents": { "type": "string" }, "deployments": { "type": "string" } }, "additionalProperties": { "type": "string" }, "example": { "issues": "read", "deployments": "write" } }, "events": { "description": "The list of events for the GitHub app", "type": "array", "items": { "type": "string" }, "examples": [ "label", "deployment" ] }, "installations_count": { "description": "The number of installations associated with the GitHub app", "type": "integer", "examples": [ 5 ] }, "client_id": { "type": "string", "examples": [ "\"Iv1.25b5d1e65ffc4022\"" ] }, "client_secret": { "type": "string", "examples": [ "\"1d4b2097ac622ba702d19de498f005747a8b21d3\"" ] }, "webhook_secret": { "type": [ "string", "null" ], "examples": [ "\"6fba8f2fc8a7e8f2cca5577eddd82ca7586b3b6b\"" ] }, "pem": { "type": "string", "examples": [ "\"-----BEGIN RSA PRIVATE KEY-----\\nMIIEogIBAAKCAQEArYxrNYD/iT5CZVpRJu4rBKmmze3PVmT/gCo2ATUvDvZTPTey\\nxcGJ3vvrJXazKk06pN05TN29o98jrYz4cengG3YGsXPNEpKsIrEl8NhbnxapEnM9\\nJCMRe0P5JcPsfZlX6hmiT7136GRWiGOUba2X9+HKh8QJVLG5rM007TBER9/z9mWm\\nrJuNh+m5l320oBQY/Qq3A7wzdEfZw8qm/mIN0FCeoXH1L6B8xXWaAYBwhTEh6SSn\\nZHlO1Xu1JWDmAvBCi0RO5aRSKM8q9QEkvvHP4yweAtK3N8+aAbZ7ovaDhyGz8r6r\\nzhU1b8Uo0Z2ysf503WqzQgIajr7Fry7/kUwpgQIDAQABAoIBADwJp80Ko1xHPZDy\\nfcCKBDfIuPvkmSW6KumbsLMaQv1aGdHDwwTGv3t0ixSay8CGlxMRtRDyZPib6SvQ\\n6OH/lpfpbMdW2ErkksgtoIKBVrDilfrcAvrNZu7NxRNbhCSvN8q0s4ICecjbbVQh\\nnueSdlA6vGXbW58BHMq68uRbHkP+k+mM9U0mDJ1HMch67wlg5GbayVRt63H7R2+r\\nVxcna7B80J/lCEjIYZznawgiTvp3MSanTglqAYi+m1EcSsP14bJIB9vgaxS79kTu\\noiSo93leJbBvuGo8QEiUqTwMw4tDksmkLsoqNKQ1q9P7LZ9DGcujtPy4EZsamSJT\\ny8OJt0ECgYEA2lxOxJsQk2kI325JgKFjo92mQeUObIvPfSNWUIZQDTjniOI6Gv63\\nGLWVFrZcvQBWjMEQraJA9xjPbblV8PtfO87MiJGLWCHFxmPz2dzoedN+2Coxom8m\\nV95CLz8QUShuao6u/RYcvUaZEoYs5bHcTmy5sBK80JyEmafJPtCQVxMCgYEAy3ar\\nZr3yv4xRPEPMat4rseswmuMooSaK3SKub19WFI5IAtB/e7qR1Rj9JhOGcZz+OQrl\\nT78O2OFYlgOIkJPvRMrPpK5V9lslc7tz1FSh3BZMRGq5jSyD7ETSOQ0c8T2O/s7v\\nbeEPbVbDe4mwvM24XByH0GnWveVxaDl51ABD65sCgYB3ZAspUkOA5egVCh8kNpnd\\nSd6SnuQBE3ySRlT2WEnCwP9Ph6oPgn+oAfiPX4xbRqkL8q/k0BdHQ4h+zNwhk7+h\\nWtPYRAP1Xxnc/F+jGjb+DVaIaKGU18MWPg7f+FI6nampl3Q0KvfxwX0GdNhtio8T\\nTj1E+SnFwh56SRQuxSh2gwKBgHKjlIO5NtNSflsUYFM+hyQiPiqnHzddfhSG+/3o\\nm5nNaSmczJesUYreH5San7/YEy2UxAugvP7aSY2MxB+iGsiJ9WD2kZzTUlDZJ7RV\\nUzWsoqBR+eZfVJ2FUWWvy8TpSG6trh4dFxImNtKejCR1TREpSiTV3Zb1dmahK9GV\\nrK9NAoGAbBxRLoC01xfxCTgt5BDiBcFVh4fp5yYKwavJPLzHSpuDOrrI9jDn1oKN\\nonq5sDU1i391zfQvdrbX4Ova48BN+B7p63FocP/MK5tyyBoT8zQEk2+vWDOw7H/Z\\nu5dTCPxTIsoIwUw1I+7yIxqJzLPFgR2gVBwY1ra/8iAqCj+zeBw=\\n-----END RSA PRIVATE KEY-----\\n\"" ] } }, "required": [ "id", "node_id", "owner", "name", "description", "external_url", "html_url", "created_at", "updated_at", "permissions", "events" ] }, "basic-error": { "title": "Basic Error", "description": "Basic Error", "type": "object", "properties": { "message": { "type": "string" }, "documentation_url": { "type": "string" }, "url": { "type": "string" }, "status": { "type": "string" } } }, "validation-error-simple": { "title": "Validation Error Simple", "description": "Validation Error Simple", "type": "object", "required": [ "message", "documentation_url" ], "properties": { "message": { "type": "string" }, "documentation_url": { "type": "string" }, "errors": { "type": "array", "items": { "type": "string" } } } }, "webhook-config-url": { "type": "string", "description": "The URL to which the payloads will be delivered.", "format": "uri", "examples": [ "https://example.com/webhook" ] }, "webhook-config-content-type": { "type": "string", "description": "The media type used to serialize the payloads. Supported values include `json` and `form`. The default is `form`.", "examples": [ "\"json\"" ] }, "webhook-config-secret": { "type": "string", "description": "If provided, the `secret` will be used as the `key` to generate the HMAC hex digest value for [delivery signature headers](https://docs.github.com/enterprise-server@3.0/webhooks/event-payloads/#delivery-headers).", "examples": [ "\"********\"" ] }, "webhook-config-insecure-ssl": { "oneOf": [ { "type": "string", "description": "Determines whether the SSL certificate of the host for `url` will be verified when delivering payloads. Supported values include `0` (verification is performed) and `1` (verification is not performed). The default is `0`. **We strongly recommend not setting this to `1` as you are subject to man-in-the-middle and other attacks.**", "examples": [ "\"0\"" ] }, { "type": "number" } ] }, "webhook-config": { "title": "Webhook Configuration", "description": "Configuration object of the webhook", "type": "object", "properties": { "url": { "$ref": "#/components/schemas/webhook-config-url" }, "content_type": { "$ref": "#/components/schemas/webhook-config-content-type" }, "secret": { "$ref": "#/components/schemas/webhook-config-secret" }, "insecure_ssl": { "$ref": "#/components/schemas/webhook-config-insecure-ssl" } } }, "enterprise": { "title": "Enterprise", "description": "An enterprise account", "type": "object", "properties": { "description": { "description": "A short description of the enterprise.", "type": [ "string", "null" ] }, "html_url": { "type": "string", "format": "uri", "examples": [ "https://github.com/enterprises/octo-business" ] }, "website_url": { "description": "The enterprise's website URL.", "type": [ "string", "null" ], "format": "uri" }, "id": { "description": "Unique identifier of the enterprise", "type": "integer", "examples": [ 42 ] }, "node_id": { "type": "string", "examples": [ "MDEwOlJlcG9zaXRvcnkxMjk2MjY5" ] }, "name": { "description": "The name of the enterprise.", "type": "string", "examples": [ "Octo Business" ] }, "slug": { "description": "The slug url identifier for the enterprise.", "type": "string", "examples": [ "octo-business" ] }, "created_at": { "type": [ "string", "null" ], "format": "date-time", "examples": [ "2019-01-26T19:01:12Z" ] }, "updated_at": { "type": [ "string", "null" ], "format": "date-time", "examples": [ "2019-01-26T19:14:43Z" ] }, "avatar_url": { "type": "string", "format": "uri" } }, "required": [ "id", "node_id", "name", "slug", "html_url", "created_at", "updated_at", "avatar_url" ] }, "installation": { "title": "Installation", "description": "Installation", "type": "object", "properties": { "id": { "description": "The ID of the installation.", "type": "integer", "examples": [ 1 ] }, "account": { "anyOf": [ { "$ref": "#/components/schemas/simple-user" }, { "$ref": "#/components/schemas/enterprise" } ], "type": [ "null", "object" ] }, "repository_selection": { "description": "Describe whether all repositories have been selected or there's a selection involved", "type": "string", "enum": [ "all", "selected" ] }, "access_tokens_url": { "type": "string", "format": "uri", "examples": [ "https://api.github.com/installations/1/access_tokens" ] }, "repositories_url": { "type": "string", "format": "uri", "examples": [ "https://api.github.com/installation/repositories" ] }, "html_url": { "type": "string", "format": "uri", "examples": [ "https://github.com/organizations/github/settings/installations/1" ] }, "app_id": { "type": "integer", "examples": [ 1 ] }, "target_id": { "description": "The ID of the user or organization this token is being scoped to.", "type": "integer" }, "target_type": { "type": "string", "examples": [ "Organization" ] }, "permissions": { "$ref": "#/components/schemas/app-permissions" }, "events": { "type": "array", "items": { "type": "string" } }, "created_at": { "type": "string", "format": "date-time" }, "updated_at": { "type": "string", "format": "date-time" }, "single_file_name": { "type": [ "string", "null" ], "examples": [ "config.yaml" ] }, "has_multiple_single_files": { "type": "boolean", "examples": [ true ] }, "single_file_paths": { "type": "array", "items": { "type": "string" }, "examples": [ "config.yml", ".github/issue_TEMPLATE.md" ] }, "app_slug": { "type": "string", "examples": [ "github-actions" ] }, "suspended_by": { "anyOf": [ { "type": "null" }, { "$ref": "#/components/schemas/simple-user" } ] }, "suspended_at": { "type": [ "string", "null" ], "format": "date-time" }, "contact_email": { "type": [ "string", "null" ], "examples": [ "\"test_13f1e99741e3e004@d7e1eb0bc0a1ba12.com\"" ] } }, "required": [ "id", "app_id", "app_slug", "target_id", "target_type", "single_file_name", "repository_selection", "access_tokens_url", "html_url", "repositories_url", "events", "account", "permissions", "created_at", "updated_at", "suspended_by", "suspended_at" ] }, "license-simple": { "title": "License Simple", "description": "License Simple", "type": "object", "properties": { "key": { "type": "string", "examples": [ "mit" ] }, "name": { "type": "string", "examples": [ "MIT License" ] }, "url": { "type": [ "string", "null" ], "format": "uri", "examples": [ "https://api.github.com/licenses/mit" ] }, "spdx_id": { "type": [ "string", "null" ], "examples": [ "MIT" ] }, "node_id": { "type": "string", "examples": [ "MDc6TGljZW5zZW1pdA==" ] }, "html_url": { "type": "string", "format": "uri" } }, "required": [ "key", "name", "url", "spdx_id", "node_id" ] }, "repository": { "title": "Repository", "description": "A git repository", "type": "object", "properties": { "id": { "description": "Unique identifier of the repository", "type": "integer", "examples": [ 42 ] }, "node_id": { "type": "string", "examples": [ "MDEwOlJlcG9zaXRvcnkxMjk2MjY5" ] }, "name": { "description": "The name of the repository.", "type": "string", "examples": [ "Team Environment" ] }, "full_name": { "type": "string", "examples": [ "octocat/Hello-World" ] }, "license": { "anyOf": [ { "type": "null" }, { "$ref": "#/components/schemas/license-simple" } ] }, "organization": { "anyOf": [ { "type": "null" }, { "$ref": "#/components/schemas/simple-user" } ] }, "forks": { "type": "integer" }, "permissions": { "type": "object", "properties": { "admin": { "type": "boolean" }, "pull": { "type": "boolean" }, "triage": { "type": "boolean" }, "push": { "type": "boolean" }, "maintain": { "type": "boolean" } }, "required": [ "admin", "pull", "push" ] }, "owner": { "$ref": "#/components/schemas/simple-user" }, "private": { "description": "Whether the repository is private or public.", "default": false, "type": "boolean" }, "html_url": { "type": "string", "format": "uri", "examples": [ "https://github.com/octocat/Hello-World" ] }, "description": { "type": [ "string", "null" ], "examples": [ "This your first repo!" ] }, "fork": { "type": "boolean" }, "url": { "type": "string", "format": "uri", "examples": [ "https://api.github.com/repos/octocat/Hello-World" ] }, "archive_url": { "type": "string", "examples": [ "http://api.github.com/repos/octocat/Hello-World/{archive_format}{/ref}" ] }, "assignees_url": { "type": "string", "examples": [ "http://api.github.com/repos/octocat/Hello-World/assignees{/user}" ] }, "blobs_url": { "type": "string", "examples": [ "http://api.github.com/repos/octocat/Hello-World/git/blobs{/sha}" ] }, "branches_url": { "type": "string", "examples": [ "http://api.github.com/repos/octocat/Hello-World/branches{/branch}" ] }, "collaborators_url": { "type": "string", "examples": [ "http://api.github.com/repos/octocat/Hello-World/collaborators{/collaborator}" ] }, "comments_url": { "type": "string", "examples": [ "http://api.github.com/repos/octocat/Hello-World/comments{/number}" ] }, "commits_url": { "type": "string", "examples": [ "http://api.github.com/repos/octocat/Hello-World/commits{/sha}" ] }, "compare_url": { "type": "string", "examples": [ "http://api.github.com/repos/octocat/Hello-World/compare/{base}...{head}" ] }, "contents_url": { "type": "string", "examples": [ "http://api.github.com/repos/octocat/Hello-World/contents/{+path}" ] }, "contributors_url": { "type": "string", "format": "uri", "examples": [ "http://api.github.com/repos/octocat/Hello-World/contributors" ] }, "deployments_url": { "type": "string", "format": "uri", "examples": [ "http://api.github.com/repos/octocat/Hello-World/deployments" ] }, "downloads_url": { "type": "string", "format": "uri", "examples": [ "http://api.github.com/repos/octocat/Hello-World/downloads" ] }, "events_url": { "type": "string", "format": "uri", "examples": [ "http://api.github.com/repos/octocat/Hello-World/events" ] }, "forks_url": { "type": "string", "format": "uri", "examples": [ "http://api.github.com/repos/octocat/Hello-World/forks" ] }, "git_commits_url": { "type": "string", "examples": [ "http://api.github.com/repos/octocat/Hello-World/git/commits{/sha}" ] }, "git_refs_url": { "type": "string", "examples": [ "http://api.github.com/repos/octocat/Hello-World/git/refs{/sha}" ] }, "git_tags_url": { "type": "string", "examples": [ "http://api.github.com/repos/octocat/Hello-World/git/tags{/sha}" ] }, "git_url": { "type": "string", "examples": [ "git:github.com/octocat/Hello-World.git" ] }, "issue_comment_url": { "type": "string", "examples": [ "http://api.github.com/repos/octocat/Hello-World/issues/comments{/number}" ] }, "issue_events_url": { "type": "string", "examples": [ "http://api.github.com/repos/octocat/Hello-World/issues/events{/number}" ] }, "issues_url": { "type": "string", "examples": [ "http://api.github.com/repos/octocat/Hello-World/issues{/number}" ] }, "keys_url": { "type": "string", "examples": [ "http://api.github.com/repos/octocat/Hello-World/keys{/key_id}" ] }, "labels_url": { "type": "string", "examples": [ "http://api.github.com/repos/octocat/Hello-World/labels{/name}" ] }, "languages_url": { "type": "string", "format": "uri", "examples": [ "http://api.github.com/repos/octocat/Hello-World/languages" ] }, "merges_url": { "type": "string", "format": "uri", "examples": [ "http://api.github.com/repos/octocat/Hello-World/merges" ] }, "milestones_url": { "type": "string", "examples": [ "http://api.github.com/repos/octocat/Hello-World/milestones{/number}" ] }, "notifications_url": { "type": "string", "examples": [ "http://api.github.com/repos/octocat/Hello-World/notifications{?since,all,participating}" ] }, "pulls_url": { "type": "string", "examples": [ "http://api.github.com/repos/octocat/Hello-World/pulls{/number}" ] }, "releases_url": { "type": "string", "examples": [ "http://api.github.com/repos/octocat/Hello-World/releases{/id}" ] }, "ssh_url": { "type": "string", "examples": [ "git@github.com:octocat/Hello-World.git" ] }, "stargazers_url": { "type": "string", "format": "uri", "examples": [ "http://api.github.com/repos/octocat/Hello-World/stargazers" ] }, "statuses_url": { "type": "string", "examples": [ "http://api.github.com/repos/octocat/Hello-World/statuses/{sha}" ] }, "subscribers_url": { "type": "string", "format": "uri", "examples": [ "http://api.github.com/repos/octocat/Hello-World/subscribers" ] }, "subscription_url": { "type": "string", "format": "uri", "examples": [ "http://api.github.com/repos/octocat/Hello-World/subscription" ] }, "tags_url": { "type": "string", "format": "uri", "examples": [ "http://api.github.com/repos/octocat/Hello-World/tags" ] }, "teams_url": { "type": "string", "format": "uri", "examples": [ "http://api.github.com/repos/octocat/Hello-World/teams" ] }, "trees_url": { "type": "string", "examples": [ "http://api.github.com/repos/octocat/Hello-World/git/trees{/sha}" ] }, "clone_url": { "type": "string", "examples": [ "https://github.com/octocat/Hello-World.git" ] }, "mirror_url": { "type": [ "string", "null" ], "format": "uri", "examples": [ "git:git.example.com/octocat/Hello-World" ] }, "hooks_url": { "type": "string", "format": "uri", "examples": [ "http://api.github.com/repos/octocat/Hello-World/hooks" ] }, "svn_url": { "type": "string", "format": "uri", "examples": [ "https://svn.github.com/octocat/Hello-World" ] }, "homepage": { "type": [ "string", "null" ], "format": "uri", "examples": [ "https://github.com" ] }, "language": { "type": [ "string", "null" ] }, "forks_count": { "type": "integer", "examples": [ 9 ] }, "stargazers_count": { "type": "integer", "examples": [ 80 ] }, "watchers_count": { "type": "integer", "examples": [ 80 ] }, "size": { "type": "integer", "examples": [ 108 ] }, "default_branch": { "description": "The default branch of the repository.", "type": "string", "examples": [ "master" ] }, "open_issues_count": { "type": "integer", "examples": [ 0 ] }, "is_template": { "description": "Whether this repository acts as a template that can be used to generate new repositories.", "default": false, "type": "boolean", "examples": [ true ] }, "topics": { "type": "array", "items": { "type": "string" } }, "has_issues": { "description": "Whether issues are enabled.", "default": true, "type": "boolean", "examples": [ true ] }, "has_projects": { "description": "Whether projects are enabled.", "default": true, "type": "boolean", "examples": [ true ] }, "has_wiki": { "description": "Whether the wiki is enabled.", "default": true, "type": "boolean", "examples": [ true ] }, "has_pages": { "type": "boolean" }, "has_downloads": { "description": "Whether downloads are enabled.", "default": true, "type": "boolean", "examples": [ true ] }, "archived": { "description": "Whether the repository is archived.", "default": false, "type": "boolean" }, "disabled": { "type": "boolean", "description": "Returns whether or not this repository disabled." }, "visibility": { "description": "The repository visibility: public, private, or internal.", "default": "public", "type": "string" }, "pushed_at": { "type": [ "string", "null" ], "format": "date-time", "examples": [ "2011-01-26T19:06:43Z" ] }, "created_at": { "type": [ "string", "null" ], "format": "date-time", "examples": [ "2011-01-26T19:01:12Z" ] }, "updated_at": { "type": [ "string", "null" ], "format": "date-time", "examples": [ "2011-01-26T19:14:43Z" ] }, "allow_rebase_merge": { "description": "Whether to allow rebase merges for pull requests.", "default": true, "type": "boolean", "examples": [ true ] }, "template_repository": { "type": [ "object", "null" ], "properties": { "id": { "type": "integer" }, "node_id": { "type": "string" }, "name": { "type": "string" }, "full_name": { "type": "string" }, "owner": { "type": "object", "properties": { "login": { "type": "string" }, "id": { "type": "integer" }, "node_id": { "type": "string" }, "avatar_url": { "type": "string" }, "gravatar_id": { "type": "string" }, "url": { "type": "string" }, "html_url": { "type": "string" }, "followers_url": { "type": "string" }, "following_url": { "type": "string" }, "gists_url": { "type": "string" }, "starred_url": { "type": "string" }, "subscriptions_url": { "type": "string" }, "organizations_url": { "type": "string" }, "repos_url": { "type": "string" }, "events_url": { "type": "string" }, "received_events_url": { "type": "string" }, "type": { "type": "string" }, "site_admin": { "type": "boolean" } } }, "private": { "type": "boolean" }, "html_url": { "type": "string" }, "description": { "type": "string" }, "fork": { "type": "boolean" }, "url": { "type": "string" }, "archive_url": { "type": "string" }, "assignees_url": { "type": "string" }, "blobs_url": { "type": "string" }, "branches_url": { "type": "string" }, "collaborators_url": { "type": "string" }, "comments_url": { "type": "string" }, "commits_url": { "type": "string" }, "compare_url": { "type": "string" }, "contents_url": { "type": "string" }, "contributors_url": { "type": "string" }, "deployments_url": { "type": "string" }, "downloads_url": { "type": "string" }, "events_url": { "type": "string" }, "forks_url": { "type": "string" }, "git_commits_url": { "type": "string" }, "git_refs_url": { "type": "string" }, "git_tags_url": { "type": "string" }, "git_url": { "type": "string" }, "issue_comment_url": { "type": "string" }, "issue_events_url": { "type": "string" }, "issues_url": { "type": "string" }, "keys_url": { "type": "string" }, "labels_url": { "type": "string" }, "languages_url": { "type": "string" }, "merges_url": { "type": "string" }, "milestones_url": { "type": "string" }, "notifications_url": { "type": "string" }, "pulls_url": { "type": "string" }, "releases_url": { "type": "string" }, "ssh_url": { "type": "string" }, "stargazers_url": { "type": "string" }, "statuses_url": { "type": "string" }, "subscribers_url": { "type": "string" }, "subscription_url": { "type": "string" }, "tags_url": { "type": "string" }, "teams_url": { "type": "string" }, "trees_url": { "type": "string" }, "clone_url": { "type": "string" }, "mirror_url": { "type": "string" }, "hooks_url": { "type": "string" }, "svn_url": { "type": "string" }, "homepage": { "type": "string" }, "language": { "type": "string" }, "forks_count": { "type": "integer" }, "stargazers_count": { "type": "integer" }, "watchers_count": { "type": "integer" }, "size": { "type": "integer" }, "default_branch": { "type": "string" }, "open_issues_count": { "type": "integer" }, "is_template": { "type": "boolean" }, "topics": { "type": "array", "items": { "type": "string" } }, "has_issues": { "type": "boolean" }, "has_projects": { "type": "boolean" }, "has_wiki": { "type": "boolean" }, "has_pages": { "type": "boolean" }, "has_downloads": { "type": "boolean" }, "archived": { "type": "boolean" }, "disabled": { "type": "boolean" }, "visibility": { "type": "string" }, "pushed_at": { "type": "string" }, "created_at": { "type": "string" }, "updated_at": { "type": "string" }, "permissions": { "type": "object", "properties": { "admin": { "type": "boolean" }, "maintain": { "type": "boolean" }, "push": { "type": "boolean" }, "triage": { "type": "boolean" }, "pull": { "type": "boolean" } } }, "allow_rebase_merge": { "type": "boolean" }, "temp_clone_token": { "type": "string" }, "allow_squash_merge": { "type": "boolean" }, "delete_branch_on_merge": { "type": "boolean" }, "allow_update_branch": { "type": "boolean" }, "allow_merge_commit": { "type": "boolean" }, "subscribers_count": { "type": "integer" }, "network_count": { "type": "integer" } } }, "temp_clone_token": { "type": "string" }, "allow_squash_merge": { "description": "Whether to allow squash merges for pull requests.", "default": true, "type": "boolean", "examples": [ true ] }, "delete_branch_on_merge": { "description": "Whether to delete head branches when pull requests are merged", "default": false, "type": "boolean", "examples": [ false ] }, "allow_merge_commit": { "description": "Whether to allow merge commits for pull requests.", "default": true, "type": "boolean", "examples": [ true ] }, "allow_forking": { "description": "Whether to allow forking this repo", "type": "boolean" }, "subscribers_count": { "type": "integer" }, "network_count": { "type": "integer" }, "open_issues": { "type": "integer" }, "watchers": { "type": "integer" }, "master_branch": { "type": "string" }, "starred_at": { "type": "string", "examples": [ "\"2020-07-09T00:17:42Z\"" ] } }, "required": [ "archive_url", "assignees_url", "blobs_url", "branches_url", "collaborators_url", "comments_url", "commits_url", "compare_url", "contents_url", "contributors_url", "deployments_url", "description", "downloads_url", "events_url", "fork", "forks_url", "full_name", "git_commits_url", "git_refs_url", "git_tags_url", "hooks_url", "html_url", "id", "node_id", "issue_comment_url", "issue_events_url", "issues_url", "keys_url", "labels_url", "languages_url", "merges_url", "milestones_url", "name", "notifications_url", "owner", "private", "pulls_url", "releases_url", "stargazers_url", "statuses_url", "subscribers_url", "subscription_url", "tags_url", "teams_url", "trees_url", "url", "clone_url", "default_branch", "forks", "forks_count", "git_url", "has_downloads", "has_issues", "has_projects", "has_wiki", "has_pages", "homepage", "language", "archived", "disabled", "mirror_url", "open_issues", "open_issues_count", "license", "pushed_at", "size", "ssh_url", "stargazers_count", "svn_url", "watchers", "watchers_count", "created_at", "updated_at" ] }, "installation-token": { "title": "Installation Token", "description": "Authentication token for a GitHub App installed on a user or org.", "type": "object", "properties": { "token": { "type": "string" }, "expires_at": { "type": "string" }, "permissions": { "$ref": "#/components/schemas/app-permissions" }, "repository_selection": { "type": "string", "enum": [ "all", "selected" ] }, "repositories": { "type": "array", "items": { "$ref": "#/components/schemas/repository" } }, "single_file": { "type": "string", "examples": [ "README.md" ] }, "has_multiple_single_files": { "type": "boolean", "examples": [ true ] }, "single_file_paths": { "type": "array", "items": { "type": "string" }, "examples": [ "config.yml", ".github/issue_TEMPLATE.md" ] } }, "required": [ "token", "expires_at" ] }, "validation-error": { "title": "Validation Error", "description": "Validation Error", "type": "object", "required": [ "message", "documentation_url" ], "properties": { "message": { "type": "string" }, "documentation_url": { "type": "string" }, "errors": { "type": "array", "items": { "type": "object", "required": [ "code" ], "properties": { "resource": { "type": "string" }, "field": { "type": "string" }, "message": { "type": "string" }, "code": { "type": "string" }, "index": { "type": "integer" }, "value": { "oneOf": [ { "type": [ "string", "null" ] }, { "type": [ "integer", "null" ] }, { "type": [ "array", "null" ], "items": { "type": "string" } } ] } } } } } }, "application-grant": { "title": "Application Grant", "description": "The authorization associated with an OAuth Access.", "type": "object", "properties": { "id": { "type": "integer", "examples": [ 1 ] }, "url": { "type": "string", "format": "uri", "examples": [ "https://api.github.com/applications/grants/1" ] }, "app": { "type": "object", "properties": { "client_id": { "type": "string" }, "name": { "type": "string" }, "url": { "type": "string", "format": "uri" } }, "required": [ "client_id", "name", "url" ] }, "created_at": { "type": "string", "format": "date-time", "examples": [ "2011-09-06T17:26:27Z" ] }, "updated_at": { "type": "string", "format": "date-time", "examples": [ "2011-09-06T20:39:23Z" ] }, "scopes": { "type": "array", "items": { "type": "string" }, "examples": [ "public_repo" ] }, "user": { "anyOf": [ { "type": "null" }, { "$ref": "#/components/schemas/simple-user" } ] } }, "required": [ "app", "id", "scopes", "url", "created_at", "updated_at" ] }, "code-of-conduct": { "title": "Code Of Conduct", "description": "Code Of Conduct", "type": "object", "properties": { "key": { "type": "string", "examples": [ "contributor_covenant" ] }, "name": { "type": "string", "examples": [ "Contributor Covenant" ] }, "url": { "type": "string", "format": "uri", "examples": [ "https://api.github.com/codes_of_conduct/contributor_covenant" ] }, "body": { "type": "string", "examples": [ "# Contributor Covenant Code of Conduct\n\n## Our Pledge\n\nIn the interest of fostering an open and welcoming environment, we as contributors and maintainers pledge to making participation in our project and our community a harassment-free experience for everyone, regardless of age, body size, disability, ethnicity, gender identity and expression, level of experience, nationality, personal appearance, race, religion, or sexual identity and orientation.\n\n## Our Standards\n\nExamples of behavior that contributes to creating a positive environment include:\n\n* Using welcoming and inclusive language\n* Being respectful of differing viewpoints and experiences\n* Gracefully accepting constructive criticism\n* Focusing on what is best for the community\n* Showing empathy towards other community members\n\nExamples of unacceptable behavior by participants include:\n\n* The use of sexualized language or imagery and unwelcome sexual attention or advances\n* Trolling, insulting/derogatory comments, and personal or political attacks\n* Public or private harassment\n* Publishing others' private information, such as a physical or electronic address, without explicit permission\n* Other conduct which could reasonably be considered inappropriate in a professional setting\n\n## Our Responsibilities\n\nProject maintainers are responsible for clarifying the standards of acceptable behavior and are expected to take appropriate and fair corrective action in response\n to any instances of unacceptable behavior.\n\nProject maintainers have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, or to ban temporarily or permanently any contributor for other behaviors that they deem inappropriate, threatening, offensive, or harmful.\n\n## Scope\n\nThis Code of Conduct applies both within project spaces and in public spaces when an individual is representing the project or its community. Examples of representing a project or community include using an official project e-mail address,\n posting via an official social media account, or acting as an appointed representative at an online or offline event. Representation of a project may be further defined and clarified by project maintainers.\n\n## Enforcement\n\nInstances of abusive, harassing, or otherwise unacceptable behavior may be reported by contacting the project team at [EMAIL]. The project team will review and investigate all complaints, and will respond in a way that it deems appropriate to the circumstances. The project team is obligated to maintain confidentiality with regard to the reporter of an incident. Further details of specific enforcement policies may be posted separately.\n\nProject maintainers who do not follow or enforce the Code of Conduct in good faith may face temporary or permanent repercussions as determined by other members of the project's leadership.\n\n## Attribution\n\nThis Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, available at [http://contributor-covenant.org/version/1/4][version]\n\n[homepage]: http://contributor-covenant.org\n[version]: http://contributor-covenant.org/version/1/4/\n" ] }, "html_url": { "type": [ "string", "null" ], "format": "uri" } }, "required": [ "url", "html_url", "key", "name" ] }, "announcement-message": { "type": "string", "description": "The announcement text in GitHub Flavored Markdown. For more information about GitHub Flavored Markdown, see \"[Basic writing and formatting syntax](https://docs.github.com/enterprise-server@3.0/github/writing-on-github/getting-started-with-writing-and-formatting-on-github/basic-writing-and-formatting-syntax).\"", "examples": [ "Very **important** announcement about _nothing_." ] }, "announcement-expiration": { "type": [ "string", "null" ], "format": "date-time", "description": "The time at which the announcement expires. This is a timestamp in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format: `YYYY-MM-DDTHH:MM:SSZ`. To set an announcement that never expires, omit this parameter, set it to `null`, or set it to an empty string.", "examples": [ "\"2021-01-01T00:00:00.000-07:00\"" ] }, "announcement": { "title": "Enterprise Announcement", "description": "Enterprise global announcement", "type": "object", "properties": { "announcement": { "$ref": "#/components/schemas/announcement-message" }, "expires_at": { "$ref": "#/components/schemas/announcement-expiration" } }, "required": [ "announcement" ] }, "license-info": { "type": "object", "properties": { "seats": { "oneOf": [ { "type": "string" }, { "type": "integer" } ] }, "seats_used": { "type": "integer" }, "seats_available": { "oneOf": [ { "type": "string" }, { "type": "integer" } ] }, "kind": { "type": "string" }, "days_until_expiration": { "type": "integer" }, "expire_at": { "type": "string" } } }, "enterprise-repository-overview": { "title": "Repository Enterprise Stats", "type": "object", "properties": { "total_repos": { "type": "integer" }, "root_repos": { "type": "integer" }, "fork_repos": { "type": "integer" }, "org_repos": { "type": "integer" }, "total_pushes": { "type": "integer" }, "total_wikis": { "type": "integer" } }, "required": [ "total_repos", "root_repos", "fork_repos", "org_repos", "total_pushes", "total_wikis" ] }, "enterprise-hook-overview": { "title": "Hooks Enterprise Stats", "type": "object", "properties": { "total_hooks": { "type": "integer" }, "active_hooks": { "type": "integer" }, "inactive_hooks": { "type": "integer" } }, "required": [ "total_hooks", "active_hooks", "inactive_hooks" ] }, "enterprise-page-overview": { "title": "Enterprise Pages Stats", "type": "object", "properties": { "total_pages": { "type": "integer" } }, "required": [ "total_pages" ] }, "enterprise-organization-overview": { "title": "Enterprise Organization Stats", "type": "object", "properties": { "total_orgs": { "type": "integer" }, "disabled_orgs": { "type": "integer" }, "total_teams": { "type": "integer" }, "total_team_members": { "type": "integer" } }, "required": [ "total_orgs", "disabled_orgs", "total_teams", "total_team_members" ] }, "enterprise-user-overview": { "title": "Enterprise User Stats", "type": "object", "properties": { "total_users": { "type": "integer" }, "admin_users": { "type": "integer" }, "suspended_users": { "type": "integer" } }, "required": [ "total_users", "admin_users", "suspended_users" ] }, "enterprise-pull-request-overview": { "title": "Enterprise Pull Request Stats", "type": "object", "properties": { "total_pulls": { "type": "integer" }, "merged_pulls": { "type": "integer" }, "mergeable_pulls": { "type": "integer" }, "unmergeable_pulls": { "type": "integer" } }, "required": [ "total_pulls", "merged_pulls", "mergeable_pulls", "unmergeable_pulls" ] }, "enterprise-issue-overview": { "title": "Enterprise Issue Stats", "type": "object", "properties": { "total_issues": { "type": "integer" }, "open_issues": { "type": "integer" }, "closed_issues": { "type": "integer" } }, "required": [ "total_issues", "open_issues", "closed_issues" ] }, "enterprise-milestone-overview": { "title": "Enterprise Milestone Stats", "type": "object", "properties": { "total_milestones": { "type": "integer" }, "open_milestones": { "type": "integer" }, "closed_milestones": { "type": "integer" } }, "required": [ "total_milestones", "open_milestones", "closed_milestones" ] }, "enterprise-gist-overview": { "title": "Enterprise Gist Stats", "type": "object", "properties": { "total_gists": { "type": "integer" }, "private_gists": { "type": "integer" }, "public_gists": { "type": "integer" } }, "required": [ "total_gists", "private_gists", "public_gists" ] }, "enterprise-comment-overview": { "title": "Enterprise Comment Stats", "type": "object", "properties": { "total_commit_comments": { "type": "integer" }, "total_gist_comments": { "type": "integer" }, "total_issue_comments": { "type": "integer" }, "total_pull_request_comments": { "type": "integer" } }, "required": [ "total_commit_comments", "total_gist_comments", "total_issue_comments", "total_pull_request_comments" ] }, "enterprise-overview": { "type": "object", "properties": { "repos": { "$ref": "#/components/schemas/enterprise-repository-overview" }, "hooks": { "$ref": "#/components/schemas/enterprise-hook-overview" }, "pages": { "$ref": "#/components/schemas/enterprise-page-overview" }, "orgs": { "$ref": "#/components/schemas/enterprise-organization-overview" }, "users": { "$ref": "#/components/schemas/enterprise-user-overview" }, "pulls": { "$ref": "#/components/schemas/enterprise-pull-request-overview" }, "issues": { "$ref": "#/components/schemas/enterprise-issue-overview" }, "milestones": { "$ref": "#/components/schemas/enterprise-milestone-overview" }, "gists": { "$ref": "#/components/schemas/enterprise-gist-overview" }, "comments": { "$ref": "#/components/schemas/enterprise-comment-overview" } } }, "enabled-organizations": { "type": "string", "description": "The policy that controls the organizations in the enterprise that are allowed to run GitHub Actions. Can be one of: `all`, `none`, or `selected`.", "enum": [ "all", "none", "selected" ] }, "allowed-actions": { "type": "string", "description": "The permissions policy that controls the actions that are allowed to run. Can be one of: `all`, `local_only`, or `selected`.", "enum": [ "all", "local_only", "selected" ] }, "selected-actions-url": { "type": "string", "description": "The API URL to use to get or set the actions that are allowed to run, when `allowed_actions` is set to `selected`." }, "actions-enterprise-permissions": { "type": "object", "properties": { "enabled_organizations": { "$ref": "#/components/schemas/enabled-organizations" }, "selected_organizations_url": { "type": "string", "description": "The API URL to use to get or set the selected organizations that are allowed to run GitHub Actions, when `enabled_organizations` is set to `selected`." }, "allowed_actions": { "$ref": "#/components/schemas/allowed-actions" }, "selected_actions_url": { "$ref": "#/components/schemas/selected-actions-url" } }, "required": [ "enabled_organizations" ] }, "selected-actions": { "type": "object", "properties": { "github_owned_allowed": { "type": "boolean", "description": "Whether GitHub-owned actions are allowed. For example, this includes the actions in the `actions` organization." }, "patterns_allowed": { "type": "array", "description": "Specifies a list of string-matching patterns to allow specific action(s). Wildcards, tags, and SHAs are allowed. For example, `monalisa/octocat@*`, `monalisa/octocat@v2`, `monalisa/*`.\"", "items": { "type": "string" } } }, "required": [ "github_owned_allowed", "patterns_allowed" ] }, "runner-groups-enterprise": { "type": "object", "properties": { "id": { "type": "number" }, "name": { "type": "string" }, "visibility": { "type": "string" }, "default": { "type": "boolean" }, "selected_organizations_url": { "type": "string" }, "runners_url": { "type": "string" }, "allows_public_repositories": { "type": "boolean" } }, "required": [ "id", "name", "visibility", "allows_public_repositories", "default", "runners_url" ] }, "runner-label": { "title": "Self hosted runner label", "description": "A label for a self hosted runner", "type": "object", "properties": { "id": { "type": "integer", "description": "Unique identifier of the label." }, "name": { "type": "string", "description": "Name of the label." }, "type": { "type": "string", "description": "The type of label. Read-only labels are applied automatically when the runner is configured.", "enum": [ "read-only", "custom" ] } }, "required": [ "name" ] }, "runner": { "title": "Self hosted runners", "description": "A self hosted runner", "type": "object", "properties": { "id": { "description": "The id of the runner.", "type": "integer", "examples": [ 5 ] }, "name": { "description": "The name of the runner.", "type": "string", "examples": [ "iMac" ] }, "os": { "description": "The Operating System of the runner.", "type": "string", "examples": [ "macos" ] }, "status": { "description": "The status of the runner.", "type": "string", "examples": [ "online" ] }, "busy": { "type": "boolean" }, "labels": { "type": "array", "items": { "$ref": "#/components/schemas/runner-label" } } }, "required": [ "id", "name", "os", "status", "busy", "labels" ] }, "runner-application": { "title": "Runner Application", "description": "Runner Application", "type": "object", "properties": { "os": { "type": "string" }, "architecture": { "type": "string" }, "download_url": { "type": "string" }, "filename": { "type": "string" }, "temp_download_token": { "description": "A short lived bearer token used to download the runner, if needed.", "type": "string" }, "sha256_checksum": { "type": "string" } }, "required": [ "os", "architecture", "download_url", "filename" ] }, "authentication-token": { "title": "Authentication Token", "description": "Authentication Token", "type": "object", "properties": { "token": { "description": "The token used for authentication", "type": "string", "examples": [ "v1.1f699f1069f60xxx" ] }, "expires_at": { "description": "The time this token expires", "type": "string", "format": "date-time", "examples": [ "2016-07-11T22:14:10Z" ] }, "permissions": { "type": "object", "examples": [ { "issues": "read", "deployments": "write" } ] }, "repositories": { "description": "The repositories this token has access to", "type": "array", "items": { "$ref": "#/components/schemas/repository" } }, "single_file": { "type": [ "string", "null" ], "examples": [ "config.yaml" ] }, "repository_selection": { "description": "Describe whether all repositories have been selected or there's a selection involved", "type": "string", "enum": [ "all", "selected" ] } }, "required": [ "token", "expires_at" ] }, "actor": { "title": "Actor", "description": "Actor", "type": "object", "properties": { "id": { "type": "integer" }, "login": { "type": "string" }, "display_login": { "type": "string" }, "gravatar_id": { "type": [ "string", "null" ] }, "url": { "type": "string", "format": "uri" }, "avatar_url": { "type": "string", "format": "uri" } }, "required": [ "id", "login", "gravatar_id", "url", "avatar_url" ] }, "milestone": { "title": "Milestone", "description": "A collection of related issues and pull requests.", "type": "object", "properties": { "url": { "type": "string", "format": "uri", "examples": [ "https://api.github.com/repos/octocat/Hello-World/milestones/1" ] }, "html_url": { "type": "string", "format": "uri", "examples": [ "https://github.com/octocat/Hello-World/milestones/v1.0" ] }, "labels_url": { "type": "string", "format": "uri", "examples": [ "https://api.github.com/repos/octocat/Hello-World/milestones/1/labels" ] }, "id": { "type": "integer", "examples": [ 1002604 ] }, "node_id": { "type": "string", "examples": [ "MDk6TWlsZXN0b25lMTAwMjYwNA==" ] }, "number": { "description": "The number of the milestone.", "type": "integer", "examples": [ 42 ] }, "state": { "description": "The state of the milestone.", "type": "string", "enum": [ "open", "closed" ], "default": "open", "examples": [ "open" ] }, "title": { "description": "The title of the milestone.", "type": "string", "examples": [ "v1.0" ] }, "description": { "type": [ "string", "null" ], "examples": [ "Tracking milestone for version 1.0" ] }, "creator": { "anyOf": [ { "type": "null" }, { "$ref": "#/components/schemas/simple-user" } ] }, "open_issues": { "type": "integer", "examples": [ 4 ] }, "closed_issues": { "type": "integer", "examples": [ 8 ] }, "created_at": { "type": "string", "format": "date-time", "examples": [ "2011-04-10T20:09:31Z" ] }, "updated_at": { "type": "string", "format": "date-time", "examples": [ "2014-03-03T18:58:10Z" ] }, "closed_at": { "type": [ "string", "null" ], "format": "date-time", "examples": [ "2013-02-12T13:22:01Z" ] }, "due_on": { "type": [ "string", "null" ], "format": "date-time", "examples": [ "2012-10-09T23:39:01Z" ] } }, "required": [ "closed_issues", "creator", "description", "due_on", "closed_at", "id", "node_id", "labels_url", "html_url", "number", "open_issues", "state", "title", "url", "created_at", "updated_at" ] }, "author_association": { "title": "author_association", "type": "string", "description": "How the author is associated with the repository.", "enum": [ "COLLABORATOR", "CONTRIBUTOR", "FIRST_TIMER", "FIRST_TIME_CONTRIBUTOR", "MANNEQUIN", "MEMBER", "NONE", "OWNER" ], "examples": [ "OWNER" ] }, "reaction-rollup": { "title": "Reaction Rollup", "type": "object", "properties": { "url": { "type": "string", "format": "uri" }, "total_count": { "type": "integer" }, "+1": { "type": "integer" }, "-1": { "type": "integer" }, "laugh": { "type": "integer" }, "confused": { "type": "integer" }, "heart": { "type": "integer" }, "hooray": { "type": "integer" }, "eyes": { "type": "integer" }, "rocket": { "type": "integer" } }, "required": [ "url", "total_count", "+1", "-1", "laugh", "confused", "heart", "hooray", "eyes", "rocket" ] }, "issue": { "title": "Issue", "description": "Issues are a great way to keep track of tasks, enhancements, and bugs for your projects.", "type": "object", "properties": { "id": { "type": "integer" }, "node_id": { "type": "string" }, "url": { "description": "URL for the issue", "type": "string", "format": "uri", "examples": [ "https://api.github.com/repositories/42/issues/1" ] }, "repository_url": { "type": "string", "format": "uri" }, "labels_url": { "type": "string" }, "comments_url": { "type": "string", "format": "uri" }, "events_url": { "type": "string", "format": "uri" }, "html_url": { "type": "string", "format": "uri" }, "number": { "description": "Number uniquely identifying the issue within its repository", "type": "integer", "examples": [ 42 ] }, "state": { "description": "State of the issue; either 'open' or 'closed'", "type": "string", "examples": [ "open" ] }, "title": { "description": "Title of the issue", "type": "string", "examples": [ "Widget creation fails in Safari on OS X 10.8" ] }, "body": { "description": "Contents of the issue", "type": [ "string", "null" ], "examples": [ "It looks like the new widget form is broken on Safari. When I try and create the widget, Safari crashes. This is reproducible on 10.8, but not 10.9. Maybe a browser bug?" ] }, "user": { "anyOf": [ { "type": "null" }, { "$ref": "#/components/schemas/simple-user" } ] }, "labels": { "description": "Labels to associate with this issue; pass one or more label names to replace the set of labels on this issue; send an empty array to clear all labels from the issue; note that the labels are silently dropped for users without push access to the repository", "type": "array", "items": { "oneOf": [ { "type": "string" }, { "type": "object", "properties": { "id": { "type": "integer", "format": "int64" }, "node_id": { "type": "string" }, "url": { "type": "string", "format": "uri" }, "name": { "type": "string" }, "description": { "type": [ "string", "null" ] }, "color": { "type": [ "string", "null" ] }, "default": { "type": "boolean" } } } ] }, "examples": [ "bug", "registration" ] }, "assignee": { "anyOf": [ { "type": "null" }, { "$ref": "#/components/schemas/simple-user" } ] }, "assignees": { "type": [ "array", "null" ], "items": { "$ref": "#/components/schemas/simple-user" } }, "milestone": { "anyOf": [ { "type": "null" }, { "$ref": "#/components/schemas/milestone" } ] }, "locked": { "type": "boolean" }, "active_lock_reason": { "type": [ "string", "null" ] }, "comments": { "type": "integer" }, "pull_request": { "type": "object", "properties": { "merged_at": { "type": [ "string", "null" ], "format": "date-time" }, "diff_url": { "type": [ "string", "null" ], "format": "uri" }, "html_url": { "type": [ "string", "null" ], "format": "uri" }, "patch_url": { "type": [ "string", "null" ], "format": "uri" }, "url": { "type": [ "string", "null" ], "format": "uri" } }, "required": [ "diff_url", "html_url", "patch_url", "url" ] }, "closed_at": { "type": [ "string", "null" ], "format": "date-time" }, "created_at": { "type": "string", "format": "date-time" }, "updated_at": { "type": "string", "format": "date-time" }, "draft": { "type": "boolean" }, "closed_by": { "anyOf": [ { "type": "null" }, { "$ref": "#/components/schemas/simple-user" } ] }, "body_html": { "type": "string" }, "body_text": { "type": "string" }, "timeline_url": { "type": "string", "format": "uri" }, "repository": { "$ref": "#/components/schemas/repository" }, "performed_via_github_app": { "anyOf": [ { "type": "null" }, { "$ref": "#/components/schemas/integration" } ] }, "author_association": { "$ref": "#/components/schemas/author_association" }, "reactions": { "$ref": "#/components/schemas/reaction-rollup" } }, "required": [ "assignee", "closed_at", "comments", "comments_url", "events_url", "html_url", "id", "node_id", "labels", "labels_url", "milestone", "number", "repository_url", "state", "locked", "title", "url", "user", "author_association", "created_at", "updated_at" ] }, "issue-comment": { "title": "Issue Comment", "description": "Comments provide a way for people to collaborate on an issue.", "type": "object", "properties": { "id": { "description": "Unique identifier of the issue comment", "type": "integer", "examples": [ 42 ] }, "node_id": { "type": "string" }, "url": { "description": "URL for the issue comment", "type": "string", "format": "uri", "examples": [ "https://api.github.com/repositories/42/issues/comments/1" ] }, "body": { "description": "Contents of the issue comment", "type": "string", "examples": [ "What version of Safari were you using when you observed this bug?" ] }, "body_text": { "type": "string" }, "body_html": { "type": "string" }, "html_url": { "type": "string", "format": "uri" }, "user": { "anyOf": [ { "type": "null" }, { "$ref": "#/components/schemas/simple-user" } ] }, "created_at": { "type": "string", "format": "date-time", "examples": [ "2011-04-14T16:00:49Z" ] }, "updated_at": { "type": "string", "format": "date-time", "examples": [ "2011-04-14T16:00:49Z" ] }, "issue_url": { "type": "string", "format": "uri" }, "author_association": { "$ref": "#/components/schemas/author_association" }, "performed_via_github_app": { "anyOf": [ { "type": "null" }, { "$ref": "#/components/schemas/integration" } ] }, "reactions": { "$ref": "#/components/schemas/reaction-rollup" } }, "required": [ "id", "node_id", "html_url", "issue_url", "author_association", "user", "url", "created_at", "updated_at" ] }, "event": { "title": "Event", "description": "Event", "type": "object", "properties": { "id": { "type": "string" }, "type": { "type": [ "string", "null" ] }, "actor": { "$ref": "#/components/schemas/actor" }, "repo": { "type": "object", "properties": { "id": { "type": "integer" }, "name": { "type": "string" }, "url": { "type": "string", "format": "uri" } }, "required": [ "id", "name", "url" ] }, "org": { "$ref": "#/components/schemas/actor" }, "payload": { "type": "object", "properties": { "action": { "type": "string" }, "issue": { "$ref": "#/components/schemas/issue" }, "comment": { "$ref": "#/components/schemas/issue-comment" }, "pages": { "type": "array", "items": { "type": "object", "properties": { "page_name": { "type": "string" }, "title": { "type": "string" }, "summary": { "type": [ "string", "null" ] }, "action": { "type": "string" }, "sha": { "type": "string" }, "html_url": { "type": "string" } } } } } }, "public": { "type": "boolean" }, "created_at": { "type": [ "string", "null" ], "format": "date-time" } }, "required": [ "id", "type", "actor", "repo", "payload", "public", "created_at" ] }, "link-with-type": { "title": "Link With Type", "description": "Hypermedia Link with Type", "type": "object", "properties": { "href": { "type": "string" }, "type": { "type": "string" } }, "required": [ "href", "type" ] }, "feed": { "title": "Feed", "description": "Feed", "type": "object", "properties": { "timeline_url": { "type": "string", "examples": [ "https://github.com/timeline" ] }, "user_url": { "type": "string", "examples": [ "https://github.com/{user}" ] }, "current_user_public_url": { "type": "string", "examples": [ "https://github.com/octocat" ] }, "current_user_url": { "type": "string", "examples": [ "https://github.com/octocat.private?token=abc123" ] }, "current_user_actor_url": { "type": "string", "examples": [ "https://github.com/octocat.private.actor?token=abc123" ] }, "current_user_organization_url": { "type": "string", "examples": [ "https://github.com/octocat-org" ] }, "current_user_organization_urls": { "type": "array", "items": { "type": "string", "format": "uri" }, "examples": [ "https://github.com/organizations/github/octocat.private.atom?token=abc123" ] }, "_links": { "type": "object", "properties": { "timeline": { "$ref": "#/components/schemas/link-with-type" }, "user": { "$ref": "#/components/schemas/link-with-type" }, "security_advisories": { "$ref": "#/components/schemas/link-with-type" }, "current_user": { "$ref": "#/components/schemas/link-with-type" }, "current_user_public": { "$ref": "#/components/schemas/link-with-type" }, "current_user_actor": { "$ref": "#/components/schemas/link-with-type" }, "current_user_organization": { "$ref": "#/components/schemas/link-with-type" }, "current_user_organizations": { "type": "array", "items": { "$ref": "#/components/schemas/link-with-type" } } }, "required": [ "timeline", "user" ] } }, "required": [ "_links", "timeline_url", "user_url" ] }, "base-gist": { "title": "Base Gist", "description": "Base Gist", "type": "object", "properties": { "url": { "type": "string", "format": "uri" }, "forks_url": { "type": "string", "format": "uri" }, "commits_url": { "type": "string", "format": "uri" }, "id": { "type": "string" }, "node_id": { "type": "string" }, "git_pull_url": { "type": "string", "format": "uri" }, "git_push_url": { "type": "string", "format": "uri" }, "html_url": { "type": "string", "format": "uri" }, "files": { "type": "object", "additionalProperties": { "type": "object", "properties": { "filename": { "type": "string" }, "type": { "type": "string" }, "language": { "type": "string" }, "raw_url": { "type": "string" }, "size": { "type": "integer" } } } }, "public": { "type": "boolean" }, "created_at": { "type": "string", "format": "date-time" }, "updated_at": { "type": "string", "format": "date-time" }, "description": { "type": [ "string", "null" ] }, "comments": { "type": "integer" }, "user": { "anyOf": [ { "type": "null" }, { "$ref": "#/components/schemas/simple-user" } ] }, "comments_url": { "type": "string", "format": "uri" }, "owner": { "$ref": "#/components/schemas/simple-user" }, "truncated": { "type": "boolean" }, "forks": { "type": "array", "items": { } }, "history": { "type": "array", "items": { } } }, "required": [ "id", "node_id", "url", "forks_url", "commits_url", "git_pull_url", "git_push_url", "html_url", "comments_url", "public", "description", "comments", "user", "files", "created_at", "updated_at" ] }, "public-user": { "title": "Public User", "description": "Public User", "type": "object", "properties": { "login": { "type": "string" }, "id": { "type": "integer" }, "node_id": { "type": "string" }, "avatar_url": { "type": "string", "format": "uri" }, "gravatar_id": { "type": [ "string", "null" ] }, "url": { "type": "string", "format": "uri" }, "html_url": { "type": "string", "format": "uri" }, "followers_url": { "type": "string", "format": "uri" }, "following_url": { "type": "string" }, "gists_url": { "type": "string" }, "starred_url": { "type": "string" }, "subscriptions_url": { "type": "string", "format": "uri" }, "organizations_url": { "type": "string", "format": "uri" }, "repos_url": { "type": "string", "format": "uri" }, "events_url": { "type": "string" }, "received_events_url": { "type": "string", "format": "uri" }, "type": { "type": "string" }, "site_admin": { "type": "boolean" }, "name": { "type": [ "string", "null" ] }, "company": { "type": [ "string", "null" ] }, "blog": { "type": [ "string", "null" ] }, "location": { "type": [ "string", "null" ] }, "email": { "type": [ "string", "null" ], "format": "email" }, "hireable": { "type": [ "boolean", "null" ] }, "bio": { "type": [ "string", "null" ] }, "public_repos": { "type": "integer" }, "public_gists": { "type": "integer" }, "followers": { "type": "integer" }, "following": { "type": "integer" }, "created_at": { "type": "string", "format": "date-time" }, "updated_at": { "type": "string", "format": "date-time" }, "plan": { "type": "object", "properties": { "collaborators": { "type": "integer" }, "name": { "type": "string" }, "space": { "type": "integer" }, "private_repos": { "type": "integer" } }, "required": [ "collaborators", "name", "space", "private_repos" ] }, "suspended_at": { "type": [ "string", "null" ], "format": "date-time" }, "private_gists": { "type": "integer", "examples": [ 1 ] }, "total_private_repos": { "type": "integer", "examples": [ 2 ] }, "owned_private_repos": { "type": "integer", "examples": [ 2 ] }, "disk_usage": { "type": "integer", "examples": [ 1 ] }, "collaborators": { "type": "integer", "examples": [ 3 ] } }, "required": [ "avatar_url", "events_url", "followers_url", "following_url", "gists_url", "gravatar_id", "html_url", "id", "node_id", "login", "organizations_url", "received_events_url", "repos_url", "site_admin", "starred_url", "subscriptions_url", "type", "url", "bio", "blog", "company", "email", "followers", "following", "hireable", "location", "name", "public_gists", "public_repos", "created_at", "updated_at" ], "additionalProperties": false }, "gist-history": { "title": "Gist History", "description": "Gist History", "type": "object", "properties": { "user": { "anyOf": [ { "type": "null" }, { "$ref": "#/components/schemas/simple-user" } ] }, "version": { "type": "string" }, "committed_at": { "type": "string", "format": "date-time" }, "change_status": { "type": "object", "properties": { "total": { "type": "integer" }, "additions": { "type": "integer" }, "deletions": { "type": "integer" } } }, "url": { "type": "string", "format": "uri" } } }, "gist-simple": { "title": "Gist Simple", "description": "Gist Simple", "type": "object", "properties": { "forks": { "deprecated": true, "type": [ "array", "null" ], "items": { "type": "object", "properties": { "id": { "type": "string" }, "url": { "type": "string", "format": "uri" }, "user": { "$ref": "#/components/schemas/public-user" }, "created_at": { "type": "string", "format": "date-time" }, "updated_at": { "type": "string", "format": "date-time" } } } }, "history": { "deprecated": true, "type": [ "array", "null" ], "items": { "$ref": "#/components/schemas/gist-history" } }, "fork_of": { "title": "Gist", "description": "Gist", "type": [ "object", "null" ], "properties": { "url": { "type": "string", "format": "uri" }, "forks_url": { "type": "string", "format": "uri" }, "commits_url": { "type": "string", "format": "uri" }, "id": { "type": "string" }, "node_id": { "type": "string" }, "git_pull_url": { "type": "string", "format": "uri" }, "git_push_url": { "type": "string", "format": "uri" }, "html_url": { "type": "string", "format": "uri" }, "files": { "type": "object", "additionalProperties": { "type": "object", "properties": { "filename": { "type": "string" }, "type": { "type": "string" }, "language": { "type": "string" }, "raw_url": { "type": "string" }, "size": { "type": "integer" } } } }, "public": { "type": "boolean" }, "created_at": { "type": "string", "format": "date-time" }, "updated_at": { "type": "string", "format": "date-time" }, "description": { "type": [ "string", "null" ] }, "comments": { "type": "integer" }, "user": { "anyOf": [ { "type": "null" }, { "$ref": "#/components/schemas/simple-user" } ] }, "comments_url": { "type": "string", "format": "uri" }, "owner": { "anyOf": [ { "type": "null" }, { "$ref": "#/components/schemas/simple-user" } ] }, "truncated": { "type": "boolean" }, "forks": { "type": "array", "items": { } }, "history": { "type": "array", "items": { } } }, "required": [ "id", "node_id", "url", "forks_url", "commits_url", "git_pull_url", "git_push_url", "html_url", "comments_url", "public", "description", "comments", "user", "files", "created_at", "updated_at" ] }, "url": { "type": "string" }, "forks_url": { "type": "string" }, "commits_url": { "type": "string" }, "id": { "type": "string" }, "node_id": { "type": "string" }, "git_pull_url": { "type": "string" }, "git_push_url": { "type": "string" }, "html_url": { "type": "string" }, "files": { "type": "object", "additionalProperties": { "type": [ "object", "null" ], "properties": { "filename": { "type": "string" }, "type": { "type": "string" }, "language": { "type": "string" }, "raw_url": { "type": "string" }, "size": { "type": "integer" }, "truncated": { "type": "boolean" }, "content": { "type": "string" } } } }, "public": { "type": "boolean" }, "created_at": { "type": "string" }, "updated_at": { "type": "string" }, "description": { "type": [ "string", "null" ] }, "comments": { "type": "integer" }, "user": { "type": [ "string", "null" ] }, "comments_url": { "type": "string" }, "owner": { "$ref": "#/components/schemas/simple-user" }, "truncated": { "type": "boolean" } } }, "gist-comment": { "title": "Gist Comment", "description": "A comment made to a gist.", "type": "object", "properties": { "id": { "type": "integer", "examples": [ 1 ] }, "node_id": { "type": "string", "examples": [ "MDExOkdpc3RDb21tZW50MQ==" ] }, "url": { "type": "string", "format": "uri", "examples": [ "https://api.github.com/gists/a6db0bec360bb87e9418/comments/1" ] }, "body": { "description": "The comment text.", "type": "string", "maxLength": 65535, "examples": [ "Body of the attachment" ] }, "user": { "anyOf": [ { "type": "null" }, { "$ref": "#/components/schemas/simple-user" } ] }, "created_at": { "type": "string", "format": "date-time", "examples": [ "2011-04-18T23:23:56Z" ] }, "updated_at": { "type": "string", "format": "date-time", "examples": [ "2011-04-18T23:23:56Z" ] }, "author_association": { "$ref": "#/components/schemas/author_association" } }, "required": [ "url", "id", "node_id", "user", "body", "author_association", "created_at", "updated_at" ] }, "gist-commit": { "title": "Gist Commit", "description": "Gist Commit", "type": "object", "properties": { "url": { "type": "string", "format": "uri", "examples": [ "https://api.github.com/gists/aa5a315d61ae9438b18d/57a7f021a713b1c5a6a199b54cc514735d2d462f" ] }, "version": { "type": "string", "examples": [ "57a7f021a713b1c5a6a199b54cc514735d2d462f" ] }, "user": { "anyOf": [ { "type": "null" }, { "$ref": "#/components/schemas/simple-user" } ] }, "change_status": { "type": "object", "properties": { "total": { "type": "integer" }, "additions": { "type": "integer" }, "deletions": { "type": "integer" } } }, "committed_at": { "type": "string", "format": "date-time", "examples": [ "2010-04-14T02:15:15Z" ] } }, "required": [ "url", "user", "version", "committed_at", "change_status" ] }, "gitignore-template": { "title": "Gitignore Template", "description": "Gitignore Template", "type": "object", "properties": { "name": { "type": "string", "examples": [ "C" ] }, "source": { "type": "string", "examples": [ "# Object files\n*.o\n\n# Libraries\n*.lib\n*.a\n\n# Shared objects (inc. Windows DLLs)\n*.dll\n*.so\n*.so.*\n*.dylib\n\n# Executables\n*.exe\n*.out\n*.app\n" ] } }, "required": [ "name", "source" ] }, "license": { "title": "License", "description": "License", "type": "object", "properties": { "key": { "type": "string", "examples": [ "mit" ] }, "name": { "type": "string", "examples": [ "MIT License" ] }, "spdx_id": { "type": [ "string", "null" ], "examples": [ "MIT" ] }, "url": { "type": [ "string", "null" ], "format": "uri", "examples": [ "https://api.github.com/licenses/mit" ] }, "node_id": { "type": "string", "examples": [ "MDc6TGljZW5zZW1pdA==" ] }, "html_url": { "type": "string", "format": "uri", "examples": [ "http://choosealicense.com/licenses/mit/" ] }, "description": { "type": "string", "examples": [ "A permissive license that is short and to the point. It lets people do anything with your code with proper attribution and without warranty." ] }, "implementation": { "type": "string", "examples": [ "Create a text file (typically named LICENSE or LICENSE.txt) in the root of your source code and copy the text of the license into the file. Replace [year] with the current year and [fullname] with the name (or names) of the copyright holders." ] }, "permissions": { "type": "array", "items": { "type": "string" }, "examples": [ "commercial-use", "modifications", "distribution", "sublicense", "private-use" ] }, "conditions": { "type": "array", "items": { "type": "string" }, "examples": [ "include-copyright" ] }, "limitations": { "type": "array", "items": { "type": "string" }, "examples": [ "no-liability" ] }, "body": { "type": "string", "examples": [ "\n\nThe MIT License (MIT)\n\nCopyright (c) [year] [fullname]\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n" ] }, "featured": { "type": "boolean", "examples": [ true ] } }, "required": [ "key", "name", "url", "spdx_id", "node_id", "html_url", "description", "implementation", "permissions", "conditions", "limitations", "body", "featured" ] }, "api-overview": { "title": "Api Overview", "description": "Api Overview", "type": "object", "properties": { "verifiable_password_authentication": { "type": "boolean", "examples": [ true ] }, "packages": { "type": "array", "items": { "type": "string" }, "examples": [ "13.65.0.0/16", "157.55.204.33/32", "2a01:111:f403:f90c::/62" ] }, "dependabot": { "type": "array", "items": { "type": "string" }, "examples": [ "192.168.7.15/32", "192.168.7.16/32" ] }, "installed_version": { "type": "string", "examples": [ "3.0.0" ] } }, "required": [ "verifiable_password_authentication" ] }, "minimal-repository": { "title": "Minimal Repository", "description": "Minimal Repository", "type": "object", "properties": { "id": { "type": "integer", "examples": [ 1296269 ] }, "node_id": { "type": "string", "examples": [ "MDEwOlJlcG9zaXRvcnkxMjk2MjY5" ] }, "name": { "type": "string", "examples": [ "Hello-World" ] }, "full_name": { "type": "string", "examples": [ "octocat/Hello-World" ] }, "owner": { "$ref": "#/components/schemas/simple-user" }, "private": { "type": "boolean" }, "html_url": { "type": "string", "format": "uri", "examples": [ "https://github.com/octocat/Hello-World" ] }, "description": { "type": [ "string", "null" ], "examples": [ "This your first repo!" ] }, "fork": { "type": "boolean" }, "url": { "type": "string", "format": "uri", "examples": [ "https://api.github.com/repos/octocat/Hello-World" ] }, "archive_url": { "type": "string", "examples": [ "http://api.github.com/repos/octocat/Hello-World/{archive_format}{/ref}" ] }, "assignees_url": { "type": "string", "examples": [ "http://api.github.com/repos/octocat/Hello-World/assignees{/user}" ] }, "blobs_url": { "type": "string", "examples": [ "http://api.github.com/repos/octocat/Hello-World/git/blobs{/sha}" ] }, "branches_url": { "type": "string", "examples": [ "http://api.github.com/repos/octocat/Hello-World/branches{/branch}" ] }, "collaborators_url": { "type": "string", "examples": [ "http://api.github.com/repos/octocat/Hello-World/collaborators{/collaborator}" ] }, "comments_url": { "type": "string", "examples": [ "http://api.github.com/repos/octocat/Hello-World/comments{/number}" ] }, "commits_url": { "type": "string", "examples": [ "http://api.github.com/repos/octocat/Hello-World/commits{/sha}" ] }, "compare_url": { "type": "string", "examples": [ "http://api.github.com/repos/octocat/Hello-World/compare/{base}...{head}" ] }, "contents_url": { "type": "string", "examples": [ "http://api.github.com/repos/octocat/Hello-World/contents/{+path}" ] }, "contributors_url": { "type": "string", "format": "uri", "examples": [ "http://api.github.com/repos/octocat/Hello-World/contributors" ] }, "deployments_url": { "type": "string", "format": "uri", "examples": [ "http://api.github.com/repos/octocat/Hello-World/deployments" ] }, "downloads_url": { "type": "string", "format": "uri", "examples": [ "http://api.github.com/repos/octocat/Hello-World/downloads" ] }, "events_url": { "type": "string", "format": "uri", "examples": [ "http://api.github.com/repos/octocat/Hello-World/events" ] }, "forks_url": { "type": "string", "format": "uri", "examples": [ "http://api.github.com/repos/octocat/Hello-World/forks" ] }, "git_commits_url": { "type": "string", "examples": [ "http://api.github.com/repos/octocat/Hello-World/git/commits{/sha}" ] }, "git_refs_url": { "type": "string", "examples": [ "http://api.github.com/repos/octocat/Hello-World/git/refs{/sha}" ] }, "git_tags_url": { "type": "string", "examples": [ "http://api.github.com/repos/octocat/Hello-World/git/tags{/sha}" ] }, "git_url": { "type": "string" }, "issue_comment_url": { "type": "string", "examples": [ "http://api.github.com/repos/octocat/Hello-World/issues/comments{/number}" ] }, "issue_events_url": { "type": "string", "examples": [ "http://api.github.com/repos/octocat/Hello-World/issues/events{/number}" ] }, "issues_url": { "type": "string", "examples": [ "http://api.github.com/repos/octocat/Hello-World/issues{/number}" ] }, "keys_url": { "type": "string", "examples": [ "http://api.github.com/repos/octocat/Hello-World/keys{/key_id}" ] }, "labels_url": { "type": "string", "examples": [ "http://api.github.com/repos/octocat/Hello-World/labels{/name}" ] }, "languages_url": { "type": "string", "format": "uri", "examples": [ "http://api.github.com/repos/octocat/Hello-World/languages" ] }, "merges_url": { "type": "string", "format": "uri", "examples": [ "http://api.github.com/repos/octocat/Hello-World/merges" ] }, "milestones_url": { "type": "string", "examples": [ "http://api.github.com/repos/octocat/Hello-World/milestones{/number}" ] }, "notifications_url": { "type": "string", "examples": [ "http://api.github.com/repos/octocat/Hello-World/notifications{?since,all,participating}" ] }, "pulls_url": { "type": "string", "examples": [ "http://api.github.com/repos/octocat/Hello-World/pulls{/number}" ] }, "releases_url": { "type": "string", "examples": [ "http://api.github.com/repos/octocat/Hello-World/releases{/id}" ] }, "ssh_url": { "type": "string" }, "stargazers_url": { "type": "string", "format": "uri", "examples": [ "http://api.github.com/repos/octocat/Hello-World/stargazers" ] }, "statuses_url": { "type": "string", "examples": [ "http://api.github.com/repos/octocat/Hello-World/statuses/{sha}" ] }, "subscribers_url": { "type": "string", "format": "uri", "examples": [ "http://api.github.com/repos/octocat/Hello-World/subscribers" ] }, "subscription_url": { "type": "string", "format": "uri", "examples": [ "http://api.github.com/repos/octocat/Hello-World/subscription" ] }, "tags_url": { "type": "string", "format": "uri", "examples": [ "http://api.github.com/repos/octocat/Hello-World/tags" ] }, "teams_url": { "type": "string", "format": "uri", "examples": [ "http://api.github.com/repos/octocat/Hello-World/teams" ] }, "trees_url": { "type": "string", "examples": [ "http://api.github.com/repos/octocat/Hello-World/git/trees{/sha}" ] }, "clone_url": { "type": "string" }, "mirror_url": { "type": [ "string", "null" ] }, "hooks_url": { "type": "string", "format": "uri", "examples": [ "http://api.github.com/repos/octocat/Hello-World/hooks" ] }, "svn_url": { "type": "string" }, "homepage": { "type": [ "string", "null" ] }, "language": { "type": [ "string", "null" ] }, "forks_count": { "type": "integer" }, "stargazers_count": { "type": "integer" }, "watchers_count": { "type": "integer" }, "size": { "type": "integer" }, "default_branch": { "type": "string" }, "open_issues_count": { "type": "integer" }, "is_template": { "type": "boolean" }, "topics": { "type": "array", "items": { "type": "string" } }, "has_issues": { "type": "boolean" }, "has_projects": { "type": "boolean" }, "has_wiki": { "type": "boolean" }, "has_pages": { "type": "boolean" }, "has_downloads": { "type": "boolean" }, "archived": { "type": "boolean" }, "disabled": { "type": "boolean" }, "visibility": { "type": "string" }, "pushed_at": { "type": [ "string", "null" ], "format": "date-time", "examples": [ "2011-01-26T19:06:43Z" ] }, "created_at": { "type": [ "string", "null" ], "format": "date-time", "examples": [ "2011-01-26T19:01:12Z" ] }, "updated_at": { "type": [ "string", "null" ], "format": "date-time", "examples": [ "2011-01-26T19:14:43Z" ] }, "permissions": { "type": "object", "properties": { "admin": { "type": "boolean" }, "maintain": { "type": "boolean" }, "push": { "type": "boolean" }, "triage": { "type": "boolean" }, "pull": { "type": "boolean" } } }, "template_repository": { "anyOf": [ { "type": "null" }, { "$ref": "#/components/schemas/repository" } ] }, "temp_clone_token": { "type": "string" }, "delete_branch_on_merge": { "type": "boolean" }, "subscribers_count": { "type": "integer" }, "network_count": { "type": "integer" }, "code_of_conduct": { "$ref": "#/components/schemas/code-of-conduct" }, "license": { "type": [ "object", "null" ], "properties": { "key": { "type": "string" }, "name": { "type": "string" }, "spdx_id": { "type": "string" }, "url": { "type": "string" }, "node_id": { "type": "string" } } }, "forks": { "type": "integer", "examples": [ 0 ] }, "open_issues": { "type": "integer", "examples": [ 0 ] }, "watchers": { "type": "integer", "examples": [ 0 ] }, "allow_forking": { "type": "boolean" } }, "required": [ "archive_url", "assignees_url", "blobs_url", "branches_url", "collaborators_url", "comments_url", "commits_url", "compare_url", "contents_url", "contributors_url", "deployments_url", "description", "downloads_url", "events_url", "fork", "forks_url", "full_name", "git_commits_url", "git_refs_url", "git_tags_url", "hooks_url", "html_url", "id", "node_id", "issue_comment_url", "issue_events_url", "issues_url", "keys_url", "labels_url", "languages_url", "merges_url", "milestones_url", "name", "notifications_url", "owner", "private", "pulls_url", "releases_url", "stargazers_url", "statuses_url", "subscribers_url", "subscription_url", "tags_url", "teams_url", "trees_url", "url" ] }, "thread": { "title": "Thread", "description": "Thread", "type": "object", "properties": { "id": { "type": "string" }, "repository": { "$ref": "#/components/schemas/minimal-repository" }, "subject": { "type": "object", "properties": { "title": { "type": "string" }, "url": { "type": "string" }, "latest_comment_url": { "type": "string" }, "type": { "type": "string" } }, "required": [ "title", "url", "latest_comment_url", "type" ] }, "reason": { "type": "string" }, "unread": { "type": "boolean" }, "updated_at": { "type": "string" }, "last_read_at": { "type": [ "string", "null" ] }, "url": { "type": "string" }, "subscription_url": { "type": "string", "examples": [ "https://api.github.com/notifications/threads/2/subscription" ] } }, "required": [ "id", "unread", "reason", "updated_at", "last_read_at", "subject", "repository", "url", "subscription_url" ] }, "thread-subscription": { "title": "Thread Subscription", "description": "Thread Subscription", "type": "object", "properties": { "subscribed": { "type": "boolean", "examples": [ true ] }, "ignored": { "type": "boolean" }, "reason": { "type": [ "string", "null" ] }, "created_at": { "type": [ "string", "null" ], "format": "date-time", "examples": [ "2012-10-06T21:34:12Z" ] }, "url": { "type": "string", "format": "uri", "examples": [ "https://api.github.com/notifications/threads/1/subscription" ] }, "thread_url": { "type": "string", "format": "uri", "examples": [ "https://api.github.com/notifications/threads/1" ] }, "repository_url": { "type": "string", "format": "uri", "examples": [ "https://api.github.com/repos/1" ] } }, "required": [ "created_at", "ignored", "reason", "url", "subscribed" ] }, "organization-full": { "title": "Organization Full", "description": "Organization Full", "type": "object", "properties": { "login": { "type": "string", "examples": [ "github" ] }, "id": { "type": "integer", "examples": [ 1 ] }, "node_id": { "type": "string", "examples": [ "MDEyOk9yZ2FuaXphdGlvbjE=" ] }, "url": { "type": "string", "format": "uri", "examples": [ "https://api.github.com/orgs/github" ] }, "repos_url": { "type": "string", "format": "uri", "examples": [ "https://api.github.com/orgs/github/repos" ] }, "events_url": { "type": "string", "format": "uri", "examples": [ "https://api.github.com/orgs/github/events" ] }, "hooks_url": { "type": "string", "examples": [ "https://api.github.com/orgs/github/hooks" ] }, "issues_url": { "type": "string", "examples": [ "https://api.github.com/orgs/github/issues" ] }, "members_url": { "type": "string", "examples": [ "https://api.github.com/orgs/github/members{/member}" ] }, "public_members_url": { "type": "string", "examples": [ "https://api.github.com/orgs/github/public_members{/member}" ] }, "avatar_url": { "type": "string", "examples": [ "https://github.com/images/error/octocat_happy.gif" ] }, "description": { "type": [ "string", "null" ], "examples": [ "A great organization" ] }, "name": { "type": "string", "examples": [ "github" ] }, "company": { "type": "string", "examples": [ "GitHub" ] }, "blog": { "type": "string", "format": "uri", "examples": [ "https://github.com/blog" ] }, "location": { "type": "string", "examples": [ "San Francisco" ] }, "email": { "type": "string", "format": "email", "examples": [ "octocat@github.com" ] }, "twitter_username": { "type": [ "string", "null" ], "examples": [ "github" ] }, "is_verified": { "type": "boolean", "examples": [ true ] }, "has_organization_projects": { "type": "boolean", "examples": [ true ] }, "has_repository_projects": { "type": "boolean", "examples": [ true ] }, "public_repos": { "type": "integer", "examples": [ 2 ] }, "public_gists": { "type": "integer", "examples": [ 1 ] }, "followers": { "type": "integer", "examples": [ 20 ] }, "following": { "type": "integer", "examples": [ 0 ] }, "html_url": { "type": "string", "format": "uri", "examples": [ "https://github.com/octocat" ] }, "created_at": { "type": "string", "format": "date-time", "examples": [ "2008-01-14T04:33:35Z" ] }, "type": { "type": "string", "examples": [ "Organization" ] }, "total_private_repos": { "type": "integer", "examples": [ 100 ] }, "owned_private_repos": { "type": "integer", "examples": [ 100 ] }, "private_gists": { "type": [ "integer", "null" ], "examples": [ 81 ] }, "disk_usage": { "type": [ "integer", "null" ], "examples": [ 10000 ] }, "collaborators": { "type": [ "integer", "null" ], "examples": [ 8 ] }, "billing_email": { "type": [ "string", "null" ], "format": "email", "examples": [ "org@example.com" ] }, "plan": { "type": "object", "properties": { "name": { "type": "string" }, "space": { "type": "integer" }, "private_repos": { "type": "integer" }, "filled_seats": { "type": "integer" }, "seats": { "type": "integer" } }, "required": [ "name", "space", "private_repos" ] }, "default_repository_permission": { "type": [ "string", "null" ] }, "members_can_create_repositories": { "type": [ "boolean", "null" ], "examples": [ true ] }, "two_factor_requirement_enabled": { "type": [ "boolean", "null" ], "examples": [ true ] }, "members_allowed_repository_creation_type": { "type": "string", "examples": [ "all" ] }, "members_can_create_public_repositories": { "type": "boolean", "examples": [ true ] }, "members_can_create_private_repositories": { "type": "boolean", "examples": [ true ] }, "members_can_create_internal_repositories": { "type": "boolean", "examples": [ true ] }, "members_can_create_pages": { "type": "boolean", "examples": [ true ] }, "members_can_create_public_pages": { "type": "boolean", "examples": [ true ] }, "members_can_create_private_pages": { "type": "boolean", "examples": [ true ] }, "members_can_fork_private_repositories": { "type": [ "boolean", "null" ], "examples": [ false ] }, "updated_at": { "type": "string", "format": "date-time" } }, "required": [ "login", "url", "id", "node_id", "repos_url", "events_url", "hooks_url", "issues_url", "members_url", "public_members_url", "avatar_url", "description", "html_url", "has_organization_projects", "has_repository_projects", "public_repos", "public_gists", "followers", "following", "type", "created_at", "updated_at" ] }, "enabled-repositories": { "type": "string", "description": "The policy that controls the repositories in the organization that are allowed to run GitHub Actions. Can be one of: `all`, `none`, or `selected`.", "enum": [ "all", "none", "selected" ] }, "actions-organization-permissions": { "type": "object", "properties": { "enabled_repositories": { "$ref": "#/components/schemas/enabled-repositories" }, "selected_repositories_url": { "type": "string", "description": "The API URL to use to get or set the selected repositories that are allowed to run GitHub Actions, when `enabled_repositories` is set to `selected`." }, "allowed_actions": { "$ref": "#/components/schemas/allowed-actions" }, "selected_actions_url": { "$ref": "#/components/schemas/selected-actions-url" } }, "required": [ "enabled_repositories" ] }, "runner-groups-org": { "type": "object", "properties": { "id": { "type": "number" }, "name": { "type": "string" }, "visibility": { "type": "string" }, "default": { "type": "boolean" }, "selected_repositories_url": { "description": "Link to the selected repositories resource for this runner group. Not present unless visibility was set to `selected`", "type": "string" }, "runners_url": { "type": "string" }, "inherited": { "type": "boolean" }, "inherited_allows_public_repositories": { "type": "boolean" }, "allows_public_repositories": { "type": "boolean" } }, "required": [ "id", "name", "visibility", "default", "runners_url", "inherited", "allows_public_repositories" ] }, "organization-actions-secret": { "title": "Actions Secret for an Organization", "description": "Secrets for GitHub Actions for an organization.", "type": "object", "properties": { "name": { "description": "The name of the secret.", "type": "string", "examples": [ "SECRET_TOKEN" ] }, "created_at": { "type": "string", "format": "date-time" }, "updated_at": { "type": "string", "format": "date-time" }, "visibility": { "description": "Visibility of a secret", "enum": [ "all", "private", "selected" ], "type": "string" }, "selected_repositories_url": { "type": "string", "format": "uri", "examples": [ "https://api.github.com/organizations/org/secrets/my_secret/repositories" ] } }, "required": [ "name", "created_at", "updated_at", "visibility" ] }, "actions-public-key": { "title": "ActionsPublicKey", "description": "The public key used for setting Actions Secrets.", "type": "object", "properties": { "key_id": { "description": "The identifier for the key.", "type": "string", "examples": [ "1234567" ] }, "key": { "description": "The Base64 encoded public key.", "type": "string", "examples": [ "hBT5WZEj8ZoOv6TYJsfWq7MxTEQopZO5/IT3ZCVQPzs=" ] }, "id": { "type": "integer", "examples": [ 2 ] }, "url": { "type": "string", "examples": [ "https://api.github.com/user/keys/2" ] }, "title": { "type": "string", "examples": [ "ssh-rsa AAAAB3NzaC1yc2EAAA" ] }, "created_at": { "type": "string", "examples": [ "2011-01-26T19:01:12Z" ] } }, "required": [ "key_id", "key" ] }, "empty-object": { "title": "Empty Object", "description": "An object without any properties.", "type": "object", "properties": { }, "additionalProperties": false }, "org-hook": { "title": "Org Hook", "description": "Org Hook", "type": "object", "properties": { "id": { "type": "integer", "examples": [ 1 ] }, "url": { "type": "string", "format": "uri", "examples": [ "https://api.github.com/orgs/octocat/hooks/1" ] }, "ping_url": { "type": "string", "format": "uri", "examples": [ "https://api.github.com/orgs/octocat/hooks/1/pings" ] }, "name": { "type": "string", "examples": [ "web" ] }, "events": { "type": "array", "items": { "type": "string" }, "examples": [ "push", "pull_request" ] }, "active": { "type": "boolean", "examples": [ true ] }, "config": { "type": "object", "properties": { "url": { "type": "string", "examples": [ "\"http://example.com/2\"" ] }, "insecure_ssl": { "type": "string", "examples": [ "\"0\"" ] }, "content_type": { "type": "string", "examples": [ "\"form\"" ] }, "secret": { "type": "string", "examples": [ "\"********\"" ] } } }, "updated_at": { "type": "string", "format": "date-time", "examples": [ "2011-09-06T20:39:23Z" ] }, "created_at": { "type": "string", "format": "date-time", "examples": [ "2011-09-06T17:26:27Z" ] }, "type": { "type": "string" } }, "required": [ "id", "url", "type", "name", "active", "events", "config", "ping_url", "created_at", "updated_at" ] }, "org-membership": { "title": "Org Membership", "description": "Org Membership", "type": "object", "properties": { "url": { "type": "string", "format": "uri", "examples": [ "https://api.github.com/orgs/octocat/memberships/defunkt" ] }, "state": { "type": "string", "description": "The state of the member in the organization. The `pending` state indicates the user has not yet accepted an invitation.", "enum": [ "active", "pending" ], "examples": [ "active" ] }, "role": { "type": "string", "description": "The user's membership type in the organization.", "enum": [ "admin", "member", "billing_manager" ], "examples": [ "admin" ] }, "organization_url": { "type": "string", "format": "uri", "examples": [ "https://api.github.com/orgs/octocat" ] }, "organization": { "$ref": "#/components/schemas/organization-simple" }, "user": { "anyOf": [ { "type": "null" }, { "$ref": "#/components/schemas/simple-user" } ] }, "permissions": { "type": "object", "properties": { "can_create_repository": { "type": "boolean" } }, "required": [ "can_create_repository" ] } }, "required": [ "state", "role", "organization_url", "url", "organization", "user" ] }, "org-pre-receive-hook": { "type": "object", "properties": { "id": { "type": "integer" }, "name": { "type": "string" }, "enforcement": { "type": "string" }, "configuration_url": { "type": "string" }, "allow_downstream_configuration": { "type": "boolean" } } }, "project": { "title": "Project", "description": "Projects are a way to organize columns and cards of work.", "type": "object", "properties": { "owner_url": { "type": "string", "format": "uri", "examples": [ "https://api.github.com/repos/api-playground/projects-test" ] }, "url": { "type": "string", "format": "uri", "examples": [ "https://api.github.com/projects/1002604" ] }, "html_url": { "type": "string", "format": "uri", "examples": [ "https://github.com/api-playground/projects-test/projects/12" ] }, "columns_url": { "type": "string", "format": "uri", "examples": [ "https://api.github.com/projects/1002604/columns" ] }, "id": { "type": "integer", "examples": [ 1002604 ] }, "node_id": { "type": "string", "examples": [ "MDc6UHJvamVjdDEwMDI2MDQ=" ] }, "name": { "description": "Name of the project", "type": "string", "examples": [ "Week One Sprint" ] }, "body": { "description": "Body of the project", "type": [ "string", "null" ], "examples": [ "This project represents the sprint of the first week in January" ] }, "number": { "type": "integer", "examples": [ 1 ] }, "state": { "description": "State of the project; either 'open' or 'closed'", "type": "string", "examples": [ "open" ] }, "creator": { "anyOf": [ { "type": "null" }, { "$ref": "#/components/schemas/simple-user" } ] }, "created_at": { "type": "string", "format": "date-time", "examples": [ "2011-04-10T20:09:31Z" ] }, "updated_at": { "type": "string", "format": "date-time", "examples": [ "2014-03-03T18:58:10Z" ] }, "organization_permission": { "description": "The baseline permission that all organization members have on this project. Only present if owner is an organization.", "type": "string", "enum": [ "read", "write", "admin", "none" ] }, "private": { "description": "Whether or not this project can be seen by everyone. Only present if owner is an organization.", "type": "boolean" } }, "required": [ "id", "node_id", "number", "name", "body", "state", "url", "html_url", "owner_url", "creator", "columns_url", "created_at", "updated_at" ] }, "team-simple": { "title": "Team Simple", "description": "Groups of organization members that gives permissions on specified repositories.", "type": "object", "properties": { "id": { "description": "Unique identifier of the team", "type": "integer", "examples": [ 1 ] }, "node_id": { "type": "string", "examples": [ "MDQ6VGVhbTE=" ] }, "url": { "description": "URL for the team", "type": "string", "format": "uri", "examples": [ "https://api.github.com/organizations/1/team/1" ] }, "members_url": { "type": "string", "examples": [ "https://api.github.com/organizations/1/team/1/members{/member}" ] }, "name": { "description": "Name of the team", "type": "string", "examples": [ "Justice League" ] }, "description": { "description": "Description of the team", "type": [ "string", "null" ], "examples": [ "A great team." ] }, "permission": { "description": "Permission that the team will have for its repositories", "type": "string", "examples": [ "admin" ] }, "privacy": { "description": "The level of privacy this team should have", "type": "string", "examples": [ "closed" ] }, "html_url": { "type": "string", "format": "uri", "examples": [ "https://github.com/orgs/rails/teams/core" ] }, "repositories_url": { "type": "string", "format": "uri", "examples": [ "https://api.github.com/organizations/1/team/1/repos" ] }, "slug": { "type": "string", "examples": [ "justice-league" ] }, "ldap_dn": { "description": "Distinguished Name (DN) that team maps to within LDAP environment", "type": "string", "examples": [ "uid=example,ou=users,dc=github,dc=com" ] } }, "required": [ "id", "node_id", "url", "members_url", "name", "description", "permission", "html_url", "repositories_url", "slug" ] }, "team": { "title": "Team", "description": "Groups of organization members that gives permissions on specified repositories.", "type": "object", "properties": { "id": { "type": "integer" }, "node_id": { "type": "string" }, "name": { "type": "string" }, "slug": { "type": "string" }, "description": { "type": [ "string", "null" ] }, "privacy": { "type": "string" }, "permission": { "type": "string" }, "permissions": { "type": "object", "properties": { "pull": { "type": "boolean" }, "triage": { "type": "boolean" }, "push": { "type": "boolean" }, "maintain": { "type": "boolean" }, "admin": { "type": "boolean" } }, "required": [ "pull", "triage", "push", "maintain", "admin" ] }, "url": { "type": "string", "format": "uri" }, "html_url": { "type": "string", "format": "uri", "examples": [ "https://github.com/orgs/rails/teams/core" ] }, "members_url": { "type": "string" }, "repositories_url": { "type": "string", "format": "uri" }, "parent": { "anyOf": [ { "type": "null" }, { "$ref": "#/components/schemas/team-simple" } ] } }, "required": [ "id", "node_id", "url", "members_url", "name", "description", "permission", "html_url", "repositories_url", "slug", "parent" ] }, "team-full": { "title": "Full Team", "description": "Groups of organization members that gives permissions on specified repositories.", "type": "object", "properties": { "id": { "description": "Unique identifier of the team", "type": "integer", "examples": [ 42 ] }, "node_id": { "type": "string", "examples": [ "MDQ6VGVhbTE=" ] }, "url": { "description": "URL for the team", "type": "string", "format": "uri", "examples": [ "https://api.github.com/organizations/1/team/1" ] }, "html_url": { "type": "string", "format": "uri", "examples": [ "https://github.com/orgs/rails/teams/core" ] }, "name": { "description": "Name of the team", "type": "string", "examples": [ "Developers" ] }, "slug": { "type": "string", "examples": [ "justice-league" ] }, "description": { "type": [ "string", "null" ], "examples": [ "A great team." ] }, "privacy": { "description": "The level of privacy this team should have", "type": "string", "enum": [ "closed", "secret" ], "examples": [ "closed" ] }, "permission": { "description": "Permission that the team will have for its repositories", "type": "string", "examples": [ "push" ] }, "members_url": { "type": "string", "examples": [ "https://api.github.com/organizations/1/team/1/members{/member}" ] }, "repositories_url": { "type": "string", "format": "uri", "examples": [ "https://api.github.com/organizations/1/team/1/repos" ] }, "parent": { "anyOf": [ { "type": "null" }, { "$ref": "#/components/schemas/team-simple" } ] }, "members_count": { "type": "integer", "examples": [ 3 ] }, "repos_count": { "type": "integer", "examples": [ 10 ] }, "created_at": { "type": "string", "format": "date-time", "examples": [ "2017-07-14T16:53:42Z" ] }, "updated_at": { "type": "string", "format": "date-time", "examples": [ "2017-08-17T12:37:15Z" ] }, "organization": { "$ref": "#/components/schemas/organization-full" }, "ldap_dn": { "description": "Distinguished Name (DN) that team maps to within LDAP environment", "type": "string", "examples": [ "uid=example,ou=users,dc=github,dc=com" ] } }, "required": [ "id", "node_id", "url", "members_url", "name", "description", "permission", "html_url", "repositories_url", "slug", "created_at", "updated_at", "members_count", "repos_count", "organization" ] }, "team-discussion": { "title": "Team Discussion", "description": "A team discussion is a persistent record of a free-form conversation within a team.", "type": "object", "properties": { "author": { "anyOf": [ { "type": "null" }, { "$ref": "#/components/schemas/simple-user" } ] }, "body": { "description": "The main text of the discussion.", "type": "string", "examples": [ "Please suggest improvements to our workflow in comments." ] }, "body_html": { "type": "string", "examples": [ "

      Hi! This is an area for us to collaborate as a team

      " ] }, "body_version": { "description": "The current version of the body content. If provided, this update operation will be rejected if the given version does not match the latest version on the server.", "type": "string", "examples": [ "0307116bbf7ced493b8d8a346c650b71" ] }, "comments_count": { "type": "integer", "examples": [ 0 ] }, "comments_url": { "type": "string", "format": "uri", "examples": [ "https://api.github.com/organizations/1/team/2343027/discussions/1/comments" ] }, "created_at": { "type": "string", "format": "date-time", "examples": [ "2018-01-25T18:56:31Z" ] }, "last_edited_at": { "type": [ "string", "null" ], "format": "date-time" }, "html_url": { "type": "string", "format": "uri", "examples": [ "https://github.com/orgs/github/teams/justice-league/discussions/1" ] }, "node_id": { "type": "string", "examples": [ "MDE0OlRlYW1EaXNjdXNzaW9uMQ==" ] }, "number": { "description": "The unique sequence number of a team discussion.", "type": "integer", "examples": [ 42 ] }, "pinned": { "description": "Whether or not this discussion should be pinned for easy retrieval.", "type": "boolean", "examples": [ true ] }, "private": { "description": "Whether or not this discussion should be restricted to team members and organization administrators.", "type": "boolean", "examples": [ true ] }, "team_url": { "type": "string", "format": "uri", "examples": [ "https://api.github.com/organizations/1/team/2343027" ] }, "title": { "description": "The title of the discussion.", "type": "string", "examples": [ "How can we improve our workflow?" ] }, "updated_at": { "type": "string", "format": "date-time", "examples": [ "2018-01-25T18:56:31Z" ] }, "url": { "type": "string", "format": "uri", "examples": [ "https://api.github.com/organizations/1/team/2343027/discussions/1" ] }, "reactions": { "$ref": "#/components/schemas/reaction-rollup" } }, "required": [ "author", "body", "body_html", "body_version", "comments_count", "comments_url", "created_at", "last_edited_at", "html_url", "pinned", "private", "node_id", "number", "team_url", "title", "updated_at", "url" ] }, "team-discussion-comment": { "title": "Team Discussion Comment", "description": "A reply to a discussion within a team.", "type": "object", "properties": { "author": { "anyOf": [ { "type": "null" }, { "$ref": "#/components/schemas/simple-user" } ] }, "body": { "description": "The main text of the comment.", "type": "string", "examples": [ "I agree with this suggestion." ] }, "body_html": { "type": "string", "examples": [ "

      Do you like apples?

      " ] }, "body_version": { "description": "The current version of the body content. If provided, this update operation will be rejected if the given version does not match the latest version on the server.", "type": "string", "examples": [ "0307116bbf7ced493b8d8a346c650b71" ] }, "created_at": { "type": "string", "format": "date-time", "examples": [ "2018-01-15T23:53:58Z" ] }, "last_edited_at": { "type": [ "string", "null" ], "format": "date-time" }, "discussion_url": { "type": "string", "format": "uri", "examples": [ "https://api.github.com/organizations/1/team/2403582/discussions/1" ] }, "html_url": { "type": "string", "format": "uri", "examples": [ "https://github.com/orgs/github/teams/justice-league/discussions/1/comments/1" ] }, "node_id": { "type": "string", "examples": [ "MDIxOlRlYW1EaXNjdXNzaW9uQ29tbWVudDE=" ] }, "number": { "description": "The unique sequence number of a team discussion comment.", "type": "integer", "examples": [ 42 ] }, "updated_at": { "type": "string", "format": "date-time", "examples": [ "2018-01-15T23:53:58Z" ] }, "url": { "type": "string", "format": "uri", "examples": [ "https://api.github.com/organizations/1/team/2403582/discussions/1/comments/1" ] }, "reactions": { "$ref": "#/components/schemas/reaction-rollup" } }, "required": [ "author", "body", "body_html", "body_version", "created_at", "last_edited_at", "discussion_url", "html_url", "node_id", "number", "updated_at", "url" ] }, "reaction": { "title": "Reaction", "description": "Reactions to conversations provide a way to help people express their feelings more simply and effectively.", "type": "object", "properties": { "id": { "type": "integer", "examples": [ 1 ] }, "node_id": { "type": "string", "examples": [ "MDg6UmVhY3Rpb24x" ] }, "user": { "anyOf": [ { "type": "null" }, { "$ref": "#/components/schemas/simple-user" } ] }, "content": { "description": "The reaction to use", "type": "string", "enum": [ "+1", "-1", "laugh", "confused", "heart", "hooray", "rocket", "eyes" ], "examples": [ "heart" ] }, "created_at": { "type": "string", "format": "date-time", "examples": [ "2016-05-20T20:09:31Z" ] } }, "required": [ "id", "node_id", "user", "content", "created_at" ] }, "team-membership": { "title": "Team Membership", "description": "Team Membership", "type": "object", "properties": { "url": { "type": "string", "format": "uri" }, "role": { "description": "The role of the user in the team.", "enum": [ "member", "maintainer" ], "default": "member", "type": "string", "examples": [ "member" ] }, "state": { "description": "The state of the user's membership in the team.", "type": "string", "enum": [ "active", "pending" ] } }, "required": [ "role", "state", "url" ] }, "team-project": { "title": "Team Project", "description": "A team's access to a project.", "type": "object", "properties": { "owner_url": { "type": "string" }, "url": { "type": "string" }, "html_url": { "type": "string" }, "columns_url": { "type": "string" }, "id": { "type": "integer" }, "node_id": { "type": "string" }, "name": { "type": "string" }, "body": { "type": [ "string", "null" ] }, "number": { "type": "integer" }, "state": { "type": "string" }, "creator": { "$ref": "#/components/schemas/simple-user" }, "created_at": { "type": "string" }, "updated_at": { "type": "string" }, "organization_permission": { "description": "The organization permission for this project. Only present when owner is an organization.", "type": "string" }, "private": { "description": "Whether the project is private or not. Only present when owner is an organization.", "type": "boolean" }, "permissions": { "type": "object", "properties": { "read": { "type": "boolean" }, "write": { "type": "boolean" }, "admin": { "type": "boolean" } }, "required": [ "read", "write", "admin" ] } }, "required": [ "owner_url", "url", "html_url", "columns_url", "id", "node_id", "name", "body", "number", "state", "creator", "created_at", "updated_at", "permissions" ] }, "team-repository": { "title": "Team Repository", "description": "A team's access to a repository.", "type": "object", "properties": { "id": { "description": "Unique identifier of the repository", "type": "integer", "examples": [ 42 ] }, "node_id": { "type": "string", "examples": [ "MDEwOlJlcG9zaXRvcnkxMjk2MjY5" ] }, "name": { "description": "The name of the repository.", "type": "string", "examples": [ "Team Environment" ] }, "full_name": { "type": "string", "examples": [ "octocat/Hello-World" ] }, "license": { "anyOf": [ { "type": "null" }, { "$ref": "#/components/schemas/license-simple" } ] }, "forks": { "type": "integer" }, "permissions": { "type": "object", "properties": { "admin": { "type": "boolean" }, "pull": { "type": "boolean" }, "triage": { "type": "boolean" }, "push": { "type": "boolean" }, "maintain": { "type": "boolean" } }, "required": [ "admin", "pull", "push" ] }, "owner": { "anyOf": [ { "type": "null" }, { "$ref": "#/components/schemas/simple-user" } ] }, "private": { "description": "Whether the repository is private or public.", "default": false, "type": "boolean" }, "html_url": { "type": "string", "format": "uri", "examples": [ "https://github.com/octocat/Hello-World" ] }, "description": { "type": [ "string", "null" ], "examples": [ "This your first repo!" ] }, "fork": { "type": "boolean" }, "url": { "type": "string", "format": "uri", "examples": [ "https://api.github.com/repos/octocat/Hello-World" ] }, "archive_url": { "type": "string", "examples": [ "http://api.github.com/repos/octocat/Hello-World/{archive_format}{/ref}" ] }, "assignees_url": { "type": "string", "examples": [ "http://api.github.com/repos/octocat/Hello-World/assignees{/user}" ] }, "blobs_url": { "type": "string", "examples": [ "http://api.github.com/repos/octocat/Hello-World/git/blobs{/sha}" ] }, "branches_url": { "type": "string", "examples": [ "http://api.github.com/repos/octocat/Hello-World/branches{/branch}" ] }, "collaborators_url": { "type": "string", "examples": [ "http://api.github.com/repos/octocat/Hello-World/collaborators{/collaborator}" ] }, "comments_url": { "type": "string", "examples": [ "http://api.github.com/repos/octocat/Hello-World/comments{/number}" ] }, "commits_url": { "type": "string", "examples": [ "http://api.github.com/repos/octocat/Hello-World/commits{/sha}" ] }, "compare_url": { "type": "string", "examples": [ "http://api.github.com/repos/octocat/Hello-World/compare/{base}...{head}" ] }, "contents_url": { "type": "string", "examples": [ "http://api.github.com/repos/octocat/Hello-World/contents/{+path}" ] }, "contributors_url": { "type": "string", "format": "uri", "examples": [ "http://api.github.com/repos/octocat/Hello-World/contributors" ] }, "deployments_url": { "type": "string", "format": "uri", "examples": [ "http://api.github.com/repos/octocat/Hello-World/deployments" ] }, "downloads_url": { "type": "string", "format": "uri", "examples": [ "http://api.github.com/repos/octocat/Hello-World/downloads" ] }, "events_url": { "type": "string", "format": "uri", "examples": [ "http://api.github.com/repos/octocat/Hello-World/events" ] }, "forks_url": { "type": "string", "format": "uri", "examples": [ "http://api.github.com/repos/octocat/Hello-World/forks" ] }, "git_commits_url": { "type": "string", "examples": [ "http://api.github.com/repos/octocat/Hello-World/git/commits{/sha}" ] }, "git_refs_url": { "type": "string", "examples": [ "http://api.github.com/repos/octocat/Hello-World/git/refs{/sha}" ] }, "git_tags_url": { "type": "string", "examples": [ "http://api.github.com/repos/octocat/Hello-World/git/tags{/sha}" ] }, "git_url": { "type": "string", "examples": [ "git:github.com/octocat/Hello-World.git" ] }, "issue_comment_url": { "type": "string", "examples": [ "http://api.github.com/repos/octocat/Hello-World/issues/comments{/number}" ] }, "issue_events_url": { "type": "string", "examples": [ "http://api.github.com/repos/octocat/Hello-World/issues/events{/number}" ] }, "issues_url": { "type": "string", "examples": [ "http://api.github.com/repos/octocat/Hello-World/issues{/number}" ] }, "keys_url": { "type": "string", "examples": [ "http://api.github.com/repos/octocat/Hello-World/keys{/key_id}" ] }, "labels_url": { "type": "string", "examples": [ "http://api.github.com/repos/octocat/Hello-World/labels{/name}" ] }, "languages_url": { "type": "string", "format": "uri", "examples": [ "http://api.github.com/repos/octocat/Hello-World/languages" ] }, "merges_url": { "type": "string", "format": "uri", "examples": [ "http://api.github.com/repos/octocat/Hello-World/merges" ] }, "milestones_url": { "type": "string", "examples": [ "http://api.github.com/repos/octocat/Hello-World/milestones{/number}" ] }, "notifications_url": { "type": "string", "examples": [ "http://api.github.com/repos/octocat/Hello-World/notifications{?since,all,participating}" ] }, "pulls_url": { "type": "string", "examples": [ "http://api.github.com/repos/octocat/Hello-World/pulls{/number}" ] }, "releases_url": { "type": "string", "examples": [ "http://api.github.com/repos/octocat/Hello-World/releases{/id}" ] }, "ssh_url": { "type": "string", "examples": [ "git@github.com:octocat/Hello-World.git" ] }, "stargazers_url": { "type": "string", "format": "uri", "examples": [ "http://api.github.com/repos/octocat/Hello-World/stargazers" ] }, "statuses_url": { "type": "string", "examples": [ "http://api.github.com/repos/octocat/Hello-World/statuses/{sha}" ] }, "subscribers_url": { "type": "string", "format": "uri", "examples": [ "http://api.github.com/repos/octocat/Hello-World/subscribers" ] }, "subscription_url": { "type": "string", "format": "uri", "examples": [ "http://api.github.com/repos/octocat/Hello-World/subscription" ] }, "tags_url": { "type": "string", "format": "uri", "examples": [ "http://api.github.com/repos/octocat/Hello-World/tags" ] }, "teams_url": { "type": "string", "format": "uri", "examples": [ "http://api.github.com/repos/octocat/Hello-World/teams" ] }, "trees_url": { "type": "string", "examples": [ "http://api.github.com/repos/octocat/Hello-World/git/trees{/sha}" ] }, "clone_url": { "type": "string", "examples": [ "https://github.com/octocat/Hello-World.git" ] }, "mirror_url": { "type": [ "string", "null" ], "format": "uri", "examples": [ "git:git.example.com/octocat/Hello-World" ] }, "hooks_url": { "type": "string", "format": "uri", "examples": [ "http://api.github.com/repos/octocat/Hello-World/hooks" ] }, "svn_url": { "type": "string", "format": "uri", "examples": [ "https://svn.github.com/octocat/Hello-World" ] }, "homepage": { "type": [ "string", "null" ], "format": "uri", "examples": [ "https://github.com" ] }, "language": { "type": [ "string", "null" ] }, "forks_count": { "type": "integer", "examples": [ 9 ] }, "stargazers_count": { "type": "integer", "examples": [ 80 ] }, "watchers_count": { "type": "integer", "examples": [ 80 ] }, "size": { "type": "integer", "examples": [ 108 ] }, "default_branch": { "description": "The default branch of the repository.", "type": "string", "examples": [ "master" ] }, "open_issues_count": { "type": "integer", "examples": [ 0 ] }, "is_template": { "description": "Whether this repository acts as a template that can be used to generate new repositories.", "default": false, "type": "boolean", "examples": [ true ] }, "topics": { "type": "array", "items": { "type": "string" } }, "has_issues": { "description": "Whether issues are enabled.", "default": true, "type": "boolean", "examples": [ true ] }, "has_projects": { "description": "Whether projects are enabled.", "default": true, "type": "boolean", "examples": [ true ] }, "has_wiki": { "description": "Whether the wiki is enabled.", "default": true, "type": "boolean", "examples": [ true ] }, "has_pages": { "type": "boolean" }, "has_downloads": { "description": "Whether downloads are enabled.", "default": true, "type": "boolean", "examples": [ true ] }, "archived": { "description": "Whether the repository is archived.", "default": false, "type": "boolean" }, "disabled": { "type": "boolean", "description": "Returns whether or not this repository disabled." }, "visibility": { "description": "The repository visibility: public, private, or internal.", "default": "public", "type": "string" }, "pushed_at": { "type": [ "string", "null" ], "format": "date-time", "examples": [ "2011-01-26T19:06:43Z" ] }, "created_at": { "type": [ "string", "null" ], "format": "date-time", "examples": [ "2011-01-26T19:01:12Z" ] }, "updated_at": { "type": [ "string", "null" ], "format": "date-time", "examples": [ "2011-01-26T19:14:43Z" ] }, "allow_rebase_merge": { "description": "Whether to allow rebase merges for pull requests.", "default": true, "type": "boolean", "examples": [ true ] }, "template_repository": { "anyOf": [ { "type": "null" }, { "$ref": "#/components/schemas/repository" } ] }, "temp_clone_token": { "type": "string" }, "allow_squash_merge": { "description": "Whether to allow squash merges for pull requests.", "default": true, "type": "boolean", "examples": [ true ] }, "delete_branch_on_merge": { "description": "Whether to delete head branches when pull requests are merged", "default": false, "type": "boolean", "examples": [ false ] }, "allow_merge_commit": { "description": "Whether to allow merge commits for pull requests.", "default": true, "type": "boolean", "examples": [ true ] }, "allow_forking": { "description": "Whether to allow forking this repo", "default": false, "type": "boolean", "examples": [ false ] }, "subscribers_count": { "type": "integer" }, "network_count": { "type": "integer" }, "open_issues": { "type": "integer" }, "watchers": { "type": "integer" }, "master_branch": { "type": "string" } }, "required": [ "archive_url", "assignees_url", "blobs_url", "branches_url", "collaborators_url", "comments_url", "commits_url", "compare_url", "contents_url", "contributors_url", "deployments_url", "description", "downloads_url", "events_url", "fork", "forks_url", "full_name", "git_commits_url", "git_refs_url", "git_tags_url", "hooks_url", "html_url", "id", "node_id", "issue_comment_url", "issue_events_url", "issues_url", "keys_url", "labels_url", "languages_url", "merges_url", "milestones_url", "name", "notifications_url", "owner", "private", "pulls_url", "releases_url", "stargazers_url", "statuses_url", "subscribers_url", "subscription_url", "tags_url", "teams_url", "trees_url", "url", "clone_url", "default_branch", "forks", "forks_count", "git_url", "has_downloads", "has_issues", "has_projects", "has_wiki", "has_pages", "homepage", "language", "archived", "disabled", "mirror_url", "open_issues", "open_issues_count", "license", "pushed_at", "size", "ssh_url", "stargazers_count", "svn_url", "watchers", "watchers_count", "created_at", "updated_at" ] }, "project-card": { "title": "Project Card", "description": "Project cards represent a scope of work.", "type": "object", "properties": { "url": { "type": "string", "format": "uri", "examples": [ "https://api.github.com/projects/columns/cards/1478" ] }, "id": { "description": "The project card's ID", "type": "integer", "examples": [ 42 ] }, "node_id": { "type": "string", "examples": [ "MDExOlByb2plY3RDYXJkMTQ3OA==" ] }, "note": { "type": [ "string", "null" ], "examples": [ "Add payload for delete Project column" ] }, "creator": { "anyOf": [ { "type": "null" }, { "$ref": "#/components/schemas/simple-user" } ] }, "created_at": { "type": "string", "format": "date-time", "examples": [ "2016-09-05T14:21:06Z" ] }, "updated_at": { "type": "string", "format": "date-time", "examples": [ "2016-09-05T14:20:22Z" ] }, "archived": { "description": "Whether or not the card is archived", "type": "boolean", "examples": [ false ] }, "column_name": { "type": "string" }, "project_id": { "type": "string" }, "column_url": { "type": "string", "format": "uri", "examples": [ "https://api.github.com/projects/columns/367" ] }, "content_url": { "type": "string", "format": "uri", "examples": [ "https://api.github.com/repos/api-playground/projects-test/issues/3" ] }, "project_url": { "type": "string", "format": "uri", "examples": [ "https://api.github.com/projects/120" ] } }, "required": [ "id", "node_id", "note", "url", "column_url", "project_url", "creator", "created_at", "updated_at" ] }, "project-column": { "title": "Project Column", "description": "Project columns contain cards of work.", "type": "object", "properties": { "url": { "type": "string", "format": "uri", "examples": [ "https://api.github.com/projects/columns/367" ] }, "project_url": { "type": "string", "format": "uri", "examples": [ "https://api.github.com/projects/120" ] }, "cards_url": { "type": "string", "format": "uri", "examples": [ "https://api.github.com/projects/columns/367/cards" ] }, "id": { "description": "The unique identifier of the project column", "type": "integer", "examples": [ 42 ] }, "node_id": { "type": "string", "examples": [ "MDEzOlByb2plY3RDb2x1bW4zNjc=" ] }, "name": { "description": "Name of the project column", "type": "string", "examples": [ "Remaining tasks" ] }, "created_at": { "type": "string", "format": "date-time", "examples": [ "2016-09-05T14:18:44Z" ] }, "updated_at": { "type": "string", "format": "date-time", "examples": [ "2016-09-05T14:22:28Z" ] } }, "required": [ "id", "node_id", "url", "project_url", "cards_url", "name", "created_at", "updated_at" ] }, "project-collaborator-permission": { "title": "Project Collaborator Permission", "description": "Project Collaborator Permission", "type": "object", "properties": { "permission": { "type": "string" }, "user": { "anyOf": [ { "type": "null" }, { "$ref": "#/components/schemas/simple-user" } ] } }, "required": [ "permission", "user" ] }, "rate-limit": { "title": "Rate Limit", "type": "object", "properties": { "limit": { "type": "integer" }, "remaining": { "type": "integer" }, "reset": { "type": "integer" }, "used": { "type": "integer" } }, "required": [ "limit", "remaining", "reset", "used" ] }, "rate-limit-overview": { "title": "Rate Limit Overview", "description": "Rate Limit Overview", "type": "object", "properties": { "resources": { "type": "object", "properties": { "core": { "$ref": "#/components/schemas/rate-limit" }, "graphql": { "$ref": "#/components/schemas/rate-limit" }, "search": { "$ref": "#/components/schemas/rate-limit" }, "source_import": { "$ref": "#/components/schemas/rate-limit" }, "integration_manifest": { "$ref": "#/components/schemas/rate-limit" }, "code_scanning_upload": { "$ref": "#/components/schemas/rate-limit" }, "actions_runner_registration": { "$ref": "#/components/schemas/rate-limit" }, "scim": { "$ref": "#/components/schemas/rate-limit" } }, "required": [ "core", "search" ] }, "rate": { "$ref": "#/components/schemas/rate-limit" } }, "required": [ "rate", "resources" ] }, "code-of-conduct-simple": { "title": "Code Of Conduct Simple", "description": "Code of Conduct Simple", "type": "object", "properties": { "url": { "type": "string", "format": "uri", "examples": [ "https://api.github.com/repos/github/docs/community/code_of_conduct" ] }, "key": { "type": "string", "examples": [ "citizen_code_of_conduct" ] }, "name": { "type": "string", "examples": [ "Citizen Code of Conduct" ] }, "html_url": { "type": [ "string", "null" ], "format": "uri", "examples": [ "https://github.com/github/docs/blob/main/CODE_OF_CONDUCT.md" ] } }, "required": [ "url", "key", "name", "html_url" ] }, "full-repository": { "title": "Full Repository", "description": "Full Repository", "type": "object", "properties": { "id": { "type": "integer", "examples": [ 1296269 ] }, "node_id": { "type": "string", "examples": [ "MDEwOlJlcG9zaXRvcnkxMjk2MjY5" ] }, "name": { "type": "string", "examples": [ "Hello-World" ] }, "full_name": { "type": "string", "examples": [ "octocat/Hello-World" ] }, "owner": { "$ref": "#/components/schemas/simple-user" }, "private": { "type": "boolean" }, "html_url": { "type": "string", "format": "uri", "examples": [ "https://github.com/octocat/Hello-World" ] }, "description": { "type": [ "string", "null" ], "examples": [ "This your first repo!" ] }, "fork": { "type": "boolean" }, "url": { "type": "string", "format": "uri", "examples": [ "https://api.github.com/repos/octocat/Hello-World" ] }, "archive_url": { "type": "string", "examples": [ "http://api.github.com/repos/octocat/Hello-World/{archive_format}{/ref}" ] }, "assignees_url": { "type": "string", "examples": [ "http://api.github.com/repos/octocat/Hello-World/assignees{/user}" ] }, "blobs_url": { "type": "string", "examples": [ "http://api.github.com/repos/octocat/Hello-World/git/blobs{/sha}" ] }, "branches_url": { "type": "string", "examples": [ "http://api.github.com/repos/octocat/Hello-World/branches{/branch}" ] }, "collaborators_url": { "type": "string", "examples": [ "http://api.github.com/repos/octocat/Hello-World/collaborators{/collaborator}" ] }, "comments_url": { "type": "string", "examples": [ "http://api.github.com/repos/octocat/Hello-World/comments{/number}" ] }, "commits_url": { "type": "string", "examples": [ "http://api.github.com/repos/octocat/Hello-World/commits{/sha}" ] }, "compare_url": { "type": "string", "examples": [ "http://api.github.com/repos/octocat/Hello-World/compare/{base}...{head}" ] }, "contents_url": { "type": "string", "examples": [ "http://api.github.com/repos/octocat/Hello-World/contents/{+path}" ] }, "contributors_url": { "type": "string", "format": "uri", "examples": [ "http://api.github.com/repos/octocat/Hello-World/contributors" ] }, "deployments_url": { "type": "string", "format": "uri", "examples": [ "http://api.github.com/repos/octocat/Hello-World/deployments" ] }, "downloads_url": { "type": "string", "format": "uri", "examples": [ "http://api.github.com/repos/octocat/Hello-World/downloads" ] }, "events_url": { "type": "string", "format": "uri", "examples": [ "http://api.github.com/repos/octocat/Hello-World/events" ] }, "forks_url": { "type": "string", "format": "uri", "examples": [ "http://api.github.com/repos/octocat/Hello-World/forks" ] }, "git_commits_url": { "type": "string", "examples": [ "http://api.github.com/repos/octocat/Hello-World/git/commits{/sha}" ] }, "git_refs_url": { "type": "string", "examples": [ "http://api.github.com/repos/octocat/Hello-World/git/refs{/sha}" ] }, "git_tags_url": { "type": "string", "examples": [ "http://api.github.com/repos/octocat/Hello-World/git/tags{/sha}" ] }, "git_url": { "type": "string", "examples": [ "git:github.com/octocat/Hello-World.git" ] }, "issue_comment_url": { "type": "string", "examples": [ "http://api.github.com/repos/octocat/Hello-World/issues/comments{/number}" ] }, "issue_events_url": { "type": "string", "examples": [ "http://api.github.com/repos/octocat/Hello-World/issues/events{/number}" ] }, "issues_url": { "type": "string", "examples": [ "http://api.github.com/repos/octocat/Hello-World/issues{/number}" ] }, "keys_url": { "type": "string", "examples": [ "http://api.github.com/repos/octocat/Hello-World/keys{/key_id}" ] }, "labels_url": { "type": "string", "examples": [ "http://api.github.com/repos/octocat/Hello-World/labels{/name}" ] }, "languages_url": { "type": "string", "format": "uri", "examples": [ "http://api.github.com/repos/octocat/Hello-World/languages" ] }, "merges_url": { "type": "string", "format": "uri", "examples": [ "http://api.github.com/repos/octocat/Hello-World/merges" ] }, "milestones_url": { "type": "string", "examples": [ "http://api.github.com/repos/octocat/Hello-World/milestones{/number}" ] }, "notifications_url": { "type": "string", "examples": [ "http://api.github.com/repos/octocat/Hello-World/notifications{?since,all,participating}" ] }, "pulls_url": { "type": "string", "examples": [ "http://api.github.com/repos/octocat/Hello-World/pulls{/number}" ] }, "releases_url": { "type": "string", "examples": [ "http://api.github.com/repos/octocat/Hello-World/releases{/id}" ] }, "ssh_url": { "type": "string", "examples": [ "git@github.com:octocat/Hello-World.git" ] }, "stargazers_url": { "type": "string", "format": "uri", "examples": [ "http://api.github.com/repos/octocat/Hello-World/stargazers" ] }, "statuses_url": { "type": "string", "examples": [ "http://api.github.com/repos/octocat/Hello-World/statuses/{sha}" ] }, "subscribers_url": { "type": "string", "format": "uri", "examples": [ "http://api.github.com/repos/octocat/Hello-World/subscribers" ] }, "subscription_url": { "type": "string", "format": "uri", "examples": [ "http://api.github.com/repos/octocat/Hello-World/subscription" ] }, "tags_url": { "type": "string", "format": "uri", "examples": [ "http://api.github.com/repos/octocat/Hello-World/tags" ] }, "teams_url": { "type": "string", "format": "uri", "examples": [ "http://api.github.com/repos/octocat/Hello-World/teams" ] }, "trees_url": { "type": "string", "examples": [ "http://api.github.com/repos/octocat/Hello-World/git/trees{/sha}" ] }, "clone_url": { "type": "string", "examples": [ "https://github.com/octocat/Hello-World.git" ] }, "mirror_url": { "type": [ "string", "null" ], "format": "uri", "examples": [ "git:git.example.com/octocat/Hello-World" ] }, "hooks_url": { "type": "string", "format": "uri", "examples": [ "http://api.github.com/repos/octocat/Hello-World/hooks" ] }, "svn_url": { "type": "string", "format": "uri", "examples": [ "https://svn.github.com/octocat/Hello-World" ] }, "homepage": { "type": [ "string", "null" ], "format": "uri", "examples": [ "https://github.com" ] }, "language": { "type": [ "string", "null" ] }, "forks_count": { "type": "integer", "examples": [ 9 ] }, "stargazers_count": { "type": "integer", "examples": [ 80 ] }, "watchers_count": { "type": "integer", "examples": [ 80 ] }, "size": { "type": "integer", "examples": [ 108 ] }, "default_branch": { "type": "string", "examples": [ "master" ] }, "open_issues_count": { "type": "integer", "examples": [ 0 ] }, "is_template": { "type": "boolean", "examples": [ true ] }, "topics": { "type": "array", "items": { "type": "string" }, "examples": [ "octocat", "atom", "electron", "API" ] }, "has_issues": { "type": "boolean", "examples": [ true ] }, "has_projects": { "type": "boolean", "examples": [ true ] }, "has_wiki": { "type": "boolean", "examples": [ true ] }, "has_pages": { "type": "boolean" }, "has_downloads": { "type": "boolean", "examples": [ true ] }, "archived": { "type": "boolean" }, "disabled": { "type": "boolean", "description": "Returns whether or not this repository disabled." }, "visibility": { "description": "The repository visibility: public, private, or internal.", "type": "string", "examples": [ "public" ] }, "pushed_at": { "type": "string", "format": "date-time", "examples": [ "2011-01-26T19:06:43Z" ] }, "created_at": { "type": "string", "format": "date-time", "examples": [ "2011-01-26T19:01:12Z" ] }, "updated_at": { "type": "string", "format": "date-time", "examples": [ "2011-01-26T19:14:43Z" ] }, "permissions": { "type": "object", "properties": { "admin": { "type": "boolean" }, "maintain": { "type": "boolean" }, "push": { "type": "boolean" }, "triage": { "type": "boolean" }, "pull": { "type": "boolean" } }, "required": [ "admin", "pull", "push" ] }, "allow_rebase_merge": { "type": "boolean", "examples": [ true ] }, "template_repository": { "anyOf": [ { "type": "null" }, { "$ref": "#/components/schemas/repository" } ] }, "temp_clone_token": { "type": [ "string", "null" ] }, "allow_squash_merge": { "type": "boolean", "examples": [ true ] }, "delete_branch_on_merge": { "type": "boolean", "examples": [ false ] }, "allow_merge_commit": { "type": "boolean", "examples": [ true ] }, "allow_forking": { "type": "boolean", "examples": [ true ] }, "subscribers_count": { "type": "integer", "examples": [ 42 ] }, "network_count": { "type": "integer", "examples": [ 0 ] }, "license": { "anyOf": [ { "type": "null" }, { "$ref": "#/components/schemas/license-simple" } ] }, "organization": { "anyOf": [ { "type": "null" }, { "$ref": "#/components/schemas/simple-user" } ] }, "parent": { "$ref": "#/components/schemas/repository" }, "source": { "$ref": "#/components/schemas/repository" }, "forks": { "type": "integer" }, "master_branch": { "type": "string" }, "open_issues": { "type": "integer" }, "watchers": { "type": "integer" }, "anonymous_access_enabled": { "description": "Whether anonymous git access is allowed.", "default": true, "type": "boolean" }, "code_of_conduct": { "$ref": "#/components/schemas/code-of-conduct-simple" } }, "required": [ "archive_url", "assignees_url", "blobs_url", "branches_url", "collaborators_url", "comments_url", "commits_url", "compare_url", "contents_url", "contributors_url", "deployments_url", "description", "downloads_url", "events_url", "fork", "forks_url", "full_name", "git_commits_url", "git_refs_url", "git_tags_url", "hooks_url", "html_url", "id", "node_id", "issue_comment_url", "issue_events_url", "issues_url", "keys_url", "labels_url", "languages_url", "merges_url", "milestones_url", "name", "notifications_url", "owner", "private", "pulls_url", "releases_url", "stargazers_url", "statuses_url", "subscribers_url", "subscription_url", "tags_url", "teams_url", "trees_url", "url", "clone_url", "default_branch", "forks", "forks_count", "git_url", "has_downloads", "has_issues", "has_projects", "has_wiki", "has_pages", "homepage", "language", "archived", "disabled", "mirror_url", "open_issues", "open_issues_count", "license", "pushed_at", "size", "ssh_url", "stargazers_count", "svn_url", "watchers", "watchers_count", "created_at", "updated_at", "network_count", "subscribers_count" ] }, "artifact": { "title": "Artifact", "description": "An artifact", "type": "object", "properties": { "id": { "type": "integer", "examples": [ 5 ] }, "node_id": { "type": "string", "examples": [ "MDEwOkNoZWNrU3VpdGU1" ] }, "name": { "description": "The name of the artifact.", "type": "string", "examples": [ "AdventureWorks.Framework" ] }, "size_in_bytes": { "description": "The size in bytes of the artifact.", "type": "integer", "examples": [ 12345 ] }, "url": { "type": "string", "examples": [ "https://api.github.com/repos/github/hello-world/actions/artifacts/5" ] }, "archive_download_url": { "type": "string", "examples": [ "https://api.github.com/repos/github/hello-world/actions/artifacts/5/zip" ] }, "expired": { "description": "Whether or not the artifact has expired.", "type": "boolean" }, "created_at": { "type": [ "string", "null" ], "format": "date-time" }, "expires_at": { "type": [ "string", "null" ], "format": "date-time" }, "updated_at": { "type": [ "string", "null" ], "format": "date-time" } }, "required": [ "id", "node_id", "name", "size_in_bytes", "url", "archive_download_url", "expired", "created_at", "expires_at", "updated_at" ] }, "job": { "title": "Job", "description": "Information of a job execution in a workflow run", "type": "object", "properties": { "id": { "description": "The id of the job.", "type": "integer", "examples": [ 21 ] }, "run_id": { "description": "The id of the associated workflow run.", "type": "integer", "examples": [ 5 ] }, "run_url": { "type": "string", "examples": [ "https://api.github.com/repos/github/hello-world/actions/runs/5" ] }, "run_attempt": { "type": "integer", "description": "Attempt number of the associated workflow run, 1 for first attempt and higher if the workflow was re-run.", "examples": [ 1 ] }, "node_id": { "type": "string", "examples": [ "MDg6Q2hlY2tSdW40" ] }, "head_sha": { "description": "The SHA of the commit that is being run.", "type": "string", "examples": [ "009b8a3a9ccbb128af87f9b1c0f4c62e8a304f6d" ] }, "url": { "type": "string", "examples": [ "https://api.github.com/repos/github/hello-world/actions/jobs/21" ] }, "html_url": { "type": [ "string", "null" ], "examples": [ "https://github.com/github/hello-world/runs/4" ] }, "status": { "description": "The phase of the lifecycle that the job is currently in.", "type": "string", "enum": [ "queued", "in_progress", "completed" ], "examples": [ "queued" ] }, "conclusion": { "description": "The outcome of the job.", "type": [ "string", "null" ], "examples": [ "success" ] }, "started_at": { "description": "The time that the job started, in ISO 8601 format.", "format": "date-time", "type": "string", "examples": [ "2019-08-08T08:00:00-07:00" ] }, "completed_at": { "description": "The time that the job finished, in ISO 8601 format.", "format": "date-time", "type": [ "string", "null" ], "examples": [ "2019-08-08T08:00:00-07:00" ] }, "name": { "description": "The name of the job.", "type": "string", "examples": [ "test-coverage" ] }, "steps": { "description": "Steps in this job.", "type": "array", "items": { "type": "object", "required": [ "name", "status", "conclusion", "number" ], "properties": { "status": { "description": "The phase of the lifecycle that the job is currently in.", "type": "string", "enum": [ "queued", "in_progress", "completed" ], "examples": [ "queued" ] }, "conclusion": { "description": "The outcome of the job.", "type": [ "string", "null" ], "examples": [ "success" ] }, "name": { "description": "The name of the job.", "type": "string", "examples": [ "test-coverage" ] }, "number": { "type": "integer", "examples": [ 1 ] }, "started_at": { "description": "The time that the step started, in ISO 8601 format.", "format": "date-time", "type": [ "string", "null" ], "examples": [ "2019-08-08T08:00:00-07:00" ] }, "completed_at": { "description": "The time that the job finished, in ISO 8601 format.", "format": "date-time", "type": [ "string", "null" ], "examples": [ "2019-08-08T08:00:00-07:00" ] } } } }, "check_run_url": { "type": "string", "examples": [ "https://api.github.com/repos/github/hello-world/check-runs/4" ] } }, "required": [ "id", "node_id", "run_id", "run_url", "head_sha", "name", "url", "html_url", "status", "conclusion", "started_at", "completed_at", "check_run_url" ] }, "actions-enabled": { "type": "boolean", "description": "Whether GitHub Actions is enabled on the repository." }, "actions-repository-permissions": { "type": "object", "properties": { "enabled": { "$ref": "#/components/schemas/actions-enabled" }, "allowed_actions": { "$ref": "#/components/schemas/allowed-actions" }, "selected_actions_url": { "$ref": "#/components/schemas/selected-actions-url" } }, "required": [ "enabled" ] }, "pull-request-minimal": { "title": "Pull Request Minimal", "type": "object", "properties": { "id": { "type": "integer" }, "number": { "type": "integer" }, "url": { "type": "string" }, "head": { "type": "object", "properties": { "ref": { "type": "string" }, "sha": { "type": "string" }, "repo": { "type": "object", "properties": { "id": { "type": "integer" }, "url": { "type": "string" }, "name": { "type": "string" } }, "required": [ "id", "url", "name" ] } }, "required": [ "ref", "sha", "repo" ] }, "base": { "type": "object", "properties": { "ref": { "type": "string" }, "sha": { "type": "string" }, "repo": { "type": "object", "properties": { "id": { "type": "integer" }, "url": { "type": "string" }, "name": { "type": "string" } }, "required": [ "id", "url", "name" ] } }, "required": [ "ref", "sha", "repo" ] } }, "required": [ "id", "number", "url", "head", "base" ] }, "simple-commit": { "title": "Simple Commit", "description": "Simple Commit", "type": "object", "properties": { "id": { "type": "string" }, "tree_id": { "type": "string" }, "message": { "type": "string" }, "timestamp": { "type": "string", "format": "date-time" }, "author": { "type": [ "object", "null" ], "properties": { "name": { "type": "string" }, "email": { "type": "string" } }, "required": [ "name", "email" ] }, "committer": { "type": [ "object", "null" ], "properties": { "name": { "type": "string" }, "email": { "type": "string" } }, "required": [ "name", "email" ] } }, "required": [ "id", "tree_id", "message", "timestamp", "author", "committer" ] }, "workflow-run": { "title": "Workflow Run", "description": "An invocation of a workflow", "type": "object", "properties": { "id": { "type": "integer", "description": "The ID of the workflow run.", "examples": [ 5 ] }, "name": { "type": [ "string", "null" ], "description": "The name of the workflow run.", "examples": [ "Build" ] }, "node_id": { "type": "string", "examples": [ "MDEwOkNoZWNrU3VpdGU1" ] }, "check_suite_id": { "type": "integer", "description": "The ID of the associated check suite.", "examples": [ 42 ] }, "check_suite_node_id": { "type": "string", "description": "The node ID of the associated check suite.", "examples": [ "MDEwOkNoZWNrU3VpdGU0Mg==" ] }, "head_branch": { "type": [ "string", "null" ], "examples": [ "master" ] }, "head_sha": { "description": "The SHA of the head commit that points to the version of the workflow being run.", "type": "string", "examples": [ "009b8a3a9ccbb128af87f9b1c0f4c62e8a304f6d" ] }, "run_number": { "type": "integer", "description": "The auto incrementing run number for the workflow run.", "examples": [ 106 ] }, "run_attempt": { "type": "integer", "description": "Attempt number of the run, 1 for first attempt and higher if the workflow was re-run.", "examples": [ 1 ] }, "event": { "type": "string", "examples": [ "push" ] }, "status": { "type": [ "string", "null" ], "examples": [ "completed" ] }, "conclusion": { "type": [ "string", "null" ], "examples": [ "neutral" ] }, "workflow_id": { "type": "integer", "description": "The ID of the parent workflow.", "examples": [ 5 ] }, "url": { "type": "string", "description": "The URL to the workflow run.", "examples": [ "https://api.github.com/repos/github/hello-world/actions/runs/5" ] }, "html_url": { "type": "string", "examples": [ "https://github.com/github/hello-world/suites/4" ] }, "pull_requests": { "type": [ "array", "null" ], "items": { "$ref": "#/components/schemas/pull-request-minimal" } }, "created_at": { "type": "string", "format": "date-time" }, "updated_at": { "type": "string", "format": "date-time" }, "run_started_at": { "type": "string", "format": "date-time", "description": "The start time of the latest run. Resets on re-run." }, "jobs_url": { "description": "The URL to the jobs for the workflow run.", "type": "string", "examples": [ "https://api.github.com/repos/github/hello-world/actions/runs/5/jobs" ] }, "logs_url": { "description": "The URL to download the logs for the workflow run.", "type": "string", "examples": [ "https://api.github.com/repos/github/hello-world/actions/runs/5/logs" ] }, "check_suite_url": { "description": "The URL to the associated check suite.", "type": "string", "examples": [ "https://api.github.com/repos/github/hello-world/check-suites/12" ] }, "artifacts_url": { "description": "The URL to the artifacts for the workflow run.", "type": "string", "examples": [ "https://api.github.com/repos/github/hello-world/actions/runs/5/rerun/artifacts" ] }, "cancel_url": { "description": "The URL to cancel the workflow run.", "type": "string", "examples": [ "https://api.github.com/repos/github/hello-world/actions/runs/5/cancel" ] }, "rerun_url": { "description": "The URL to rerun the workflow run.", "type": "string", "examples": [ "https://api.github.com/repos/github/hello-world/actions/runs/5/rerun" ] }, "previous_attempt_url": { "description": "The URL to the previous attempted run of this workflow, if one exists.", "type": [ "string", "null" ], "examples": [ "https://api.github.com/repos/github/hello-world/actions/runs/5/attempts/3" ] }, "workflow_url": { "description": "The URL to the workflow.", "type": "string", "examples": [ "https://api.github.com/repos/github/hello-world/actions/workflows/main.yaml" ] }, "head_commit": { "anyOf": [ { "type": "null" }, { "$ref": "#/components/schemas/simple-commit" } ] }, "repository": { "$ref": "#/components/schemas/minimal-repository" }, "head_repository": { "$ref": "#/components/schemas/minimal-repository" }, "head_repository_id": { "type": "integer", "examples": [ 5 ] } }, "required": [ "id", "node_id", "head_branch", "run_number", "event", "status", "conclusion", "head_sha", "workflow_id", "url", "html_url", "created_at", "updated_at", "head_commit", "head_repository", "repository", "jobs_url", "logs_url", "check_suite_url", "cancel_url", "rerun_url", "artifacts_url", "workflow_url", "pull_requests" ] }, "actions-secret": { "title": "Actions Secret", "description": "Set secrets for GitHub Actions.", "type": "object", "properties": { "name": { "description": "The name of the secret.", "type": "string", "examples": [ "SECRET_TOKEN" ] }, "created_at": { "type": "string", "format": "date-time" }, "updated_at": { "type": "string", "format": "date-time" } }, "required": [ "name", "created_at", "updated_at" ] }, "workflow": { "title": "Workflow", "description": "A GitHub Actions workflow", "type": "object", "properties": { "id": { "type": "integer", "examples": [ 5 ] }, "node_id": { "type": "string", "examples": [ "MDg6V29ya2Zsb3cxMg==" ] }, "name": { "type": "string", "examples": [ "CI" ] }, "path": { "type": "string", "examples": [ "ruby.yaml" ] }, "state": { "type": "string", "enum": [ "active", "deleted", "disabled_fork", "disabled_inactivity", "disabled_manually" ], "examples": [ "active" ] }, "created_at": { "type": "string", "format": "date-time", "examples": [ "2019-12-06T14:20:20.000Z" ] }, "updated_at": { "type": "string", "format": "date-time", "examples": [ "2019-12-06T14:20:20.000Z" ] }, "url": { "type": "string", "examples": [ "https://api.github.com/repos/actions/setup-ruby/workflows/5" ] }, "html_url": { "type": "string", "examples": [ "https://github.com/actions/setup-ruby/blob/master/.github/workflows/ruby.yaml" ] }, "badge_url": { "type": "string", "examples": [ "https://github.com/actions/setup-ruby/workflows/CI/badge.svg" ] }, "deleted_at": { "type": "string", "format": "date-time", "examples": [ "2019-12-06T14:20:20.000Z" ] } }, "required": [ "id", "node_id", "name", "path", "state", "url", "html_url", "badge_url", "created_at", "updated_at" ] }, "protected-branch-required-status-check": { "title": "Protected Branch Required Status Check", "description": "Protected Branch Required Status Check", "type": "object", "properties": { "url": { "type": "string" }, "enforcement_level": { "type": "string" }, "contexts": { "type": "array", "items": { "type": "string" } }, "contexts_url": { "type": "string" }, "strict": { "type": "boolean" } }, "required": [ "contexts" ] }, "protected-branch-admin-enforced": { "title": "Protected Branch Admin Enforced", "description": "Protected Branch Admin Enforced", "type": "object", "properties": { "url": { "type": "string", "format": "uri", "examples": [ "https://api.github.com/repos/octocat/Hello-World/branches/master/protection/enforce_admins" ] }, "enabled": { "type": "boolean", "examples": [ true ] } }, "required": [ "url", "enabled" ] }, "protected-branch-pull-request-review": { "title": "Protected Branch Pull Request Review", "description": "Protected Branch Pull Request Review", "type": "object", "properties": { "url": { "type": "string", "format": "uri", "examples": [ "https://api.github.com/repos/octocat/Hello-World/branches/master/protection/dismissal_restrictions" ] }, "dismissal_restrictions": { "type": "object", "properties": { "users": { "description": "The list of users with review dismissal access.", "type": "array", "items": { "$ref": "#/components/schemas/simple-user" } }, "teams": { "description": "The list of teams with review dismissal access.", "type": "array", "items": { "$ref": "#/components/schemas/team" } }, "url": { "type": "string", "examples": [ "\"https://api.github.com/repos/the-org/an-org-repo/branches/master/protection/dismissal_restrictions\"" ] }, "users_url": { "type": "string", "examples": [ "\"https://api.github.com/repos/the-org/an-org-repo/branches/master/protection/dismissal_restrictions/users\"" ] }, "teams_url": { "type": "string", "examples": [ "\"https://api.github.com/repos/the-org/an-org-repo/branches/master/protection/dismissal_restrictions/teams\"" ] } } }, "dismiss_stale_reviews": { "type": "boolean", "examples": [ true ] }, "require_code_owner_reviews": { "type": "boolean", "examples": [ true ] }, "required_approving_review_count": { "type": "integer", "minimum": 1, "maximum": 6, "examples": [ 2 ] } }, "required": [ "dismiss_stale_reviews", "require_code_owner_reviews" ] }, "branch-restriction-policy": { "title": "Branch Restriction Policy", "description": "Branch Restriction Policy", "type": "object", "properties": { "url": { "type": "string", "format": "uri" }, "users_url": { "type": "string", "format": "uri" }, "teams_url": { "type": "string", "format": "uri" }, "apps_url": { "type": "string", "format": "uri" }, "users": { "type": "array", "items": { "type": "object", "properties": { "login": { "type": "string" }, "id": { "type": "integer" }, "node_id": { "type": "string" }, "avatar_url": { "type": "string" }, "gravatar_id": { "type": "string" }, "url": { "type": "string" }, "html_url": { "type": "string" }, "followers_url": { "type": "string" }, "following_url": { "type": "string" }, "gists_url": { "type": "string" }, "starred_url": { "type": "string" }, "subscriptions_url": { "type": "string" }, "organizations_url": { "type": "string" }, "repos_url": { "type": "string" }, "events_url": { "type": "string" }, "received_events_url": { "type": "string" }, "type": { "type": "string" }, "site_admin": { "type": "boolean" } } } }, "teams": { "type": "array", "items": { "type": "object", "properties": { "id": { "type": "integer" }, "node_id": { "type": "string" }, "url": { "type": "string" }, "html_url": { "type": "string" }, "name": { "type": "string" }, "slug": { "type": "string" }, "description": { "type": [ "string", "null" ] }, "privacy": { "type": "string" }, "permission": { "type": "string" }, "members_url": { "type": "string" }, "repositories_url": { "type": "string" }, "parent": { "type": [ "string", "null" ] } } } }, "apps": { "type": "array", "items": { "type": "object", "properties": { "id": { "type": "integer" }, "slug": { "type": "string" }, "node_id": { "type": "string" }, "owner": { "type": "object", "properties": { "login": { "type": "string" }, "id": { "type": "integer" }, "node_id": { "type": "string" }, "url": { "type": "string" }, "repos_url": { "type": "string" }, "events_url": { "type": "string" }, "hooks_url": { "type": "string" }, "issues_url": { "type": "string" }, "members_url": { "type": "string" }, "public_members_url": { "type": "string" }, "avatar_url": { "type": "string" }, "description": { "type": "string" }, "gravatar_id": { "type": "string", "examples": [ "\"\"" ] }, "html_url": { "type": "string", "examples": [ "\"https://github.com/testorg-ea8ec76d71c3af4b\"" ] }, "followers_url": { "type": "string", "examples": [ "\"https://api.github.com/users/testorg-ea8ec76d71c3af4b/followers\"" ] }, "following_url": { "type": "string", "examples": [ "\"https://api.github.com/users/testorg-ea8ec76d71c3af4b/following{/other_user}\"" ] }, "gists_url": { "type": "string", "examples": [ "\"https://api.github.com/users/testorg-ea8ec76d71c3af4b/gists{/gist_id}\"" ] }, "starred_url": { "type": "string", "examples": [ "\"https://api.github.com/users/testorg-ea8ec76d71c3af4b/starred{/owner}{/repo}\"" ] }, "subscriptions_url": { "type": "string", "examples": [ "\"https://api.github.com/users/testorg-ea8ec76d71c3af4b/subscriptions\"" ] }, "organizations_url": { "type": "string", "examples": [ "\"https://api.github.com/users/testorg-ea8ec76d71c3af4b/orgs\"" ] }, "received_events_url": { "type": "string", "examples": [ "\"https://api.github.com/users/testorg-ea8ec76d71c3af4b/received_events\"" ] }, "type": { "type": "string", "examples": [ "\"Organization\"" ] }, "site_admin": { "type": "boolean", "examples": [ false ] } } }, "name": { "type": "string" }, "description": { "type": "string" }, "external_url": { "type": "string" }, "html_url": { "type": "string" }, "created_at": { "type": "string" }, "updated_at": { "type": "string" }, "permissions": { "type": "object", "properties": { "metadata": { "type": "string" }, "contents": { "type": "string" }, "issues": { "type": "string" }, "single_file": { "type": "string" } } }, "events": { "type": "array", "items": { "type": "string" } } } } } }, "required": [ "url", "users_url", "teams_url", "apps_url", "users", "teams", "apps" ] }, "branch-protection": { "title": "Branch Protection", "description": "Branch Protection", "type": "object", "properties": { "url": { "type": "string" }, "enabled": { "type": "boolean" }, "required_status_checks": { "$ref": "#/components/schemas/protected-branch-required-status-check" }, "enforce_admins": { "$ref": "#/components/schemas/protected-branch-admin-enforced" }, "required_pull_request_reviews": { "$ref": "#/components/schemas/protected-branch-pull-request-review" }, "restrictions": { "$ref": "#/components/schemas/branch-restriction-policy" }, "required_linear_history": { "type": "object", "properties": { "enabled": { "type": "boolean" } } }, "allow_force_pushes": { "type": "object", "properties": { "enabled": { "type": "boolean" } } }, "allow_deletions": { "type": "object", "properties": { "enabled": { "type": "boolean" } } }, "required_conversation_resolution": { "type": "object", "properties": { "enabled": { "type": "boolean" } } }, "name": { "type": "string", "examples": [ "\"branch/with/protection\"" ] }, "protection_url": { "type": "string", "examples": [ "\"https://api.github.com/repos/owner-79e94e2d36b3fd06a32bb213/AAA_Public_Repo/branches/branch/with/protection/protection\"" ] }, "required_signatures": { "type": "object", "properties": { "url": { "type": "string", "format": "uri", "examples": [ "https://api.github.com/repos/octocat/Hello-World/branches/master/protection/required_signatures" ] }, "enabled": { "type": "boolean", "examples": [ true ] } }, "required": [ "url", "enabled" ] } } }, "short-branch": { "title": "Short Branch", "description": "Short Branch", "type": "object", "properties": { "name": { "type": "string" }, "commit": { "type": "object", "properties": { "sha": { "type": "string" }, "url": { "type": "string", "format": "uri" } }, "required": [ "sha", "url" ] }, "protected": { "type": "boolean" }, "protection": { "$ref": "#/components/schemas/branch-protection" }, "protection_url": { "type": "string", "format": "uri" } }, "required": [ "name", "commit", "protected" ] }, "git-user": { "title": "Git User", "description": "Metaproperties for Git author/committer information.", "type": "object", "properties": { "name": { "type": "string", "examples": [ "\"Chris Wanstrath\"" ] }, "email": { "type": "string", "examples": [ "\"chris@ozmm.org\"" ] }, "date": { "type": "string", "examples": [ "\"2007-10-29T02:42:39.000-07:00\"" ] } } }, "verification": { "title": "Verification", "type": "object", "properties": { "verified": { "type": "boolean" }, "reason": { "type": "string" }, "payload": { "type": [ "string", "null" ] }, "signature": { "type": [ "string", "null" ] } }, "required": [ "verified", "reason", "payload", "signature" ] }, "diff-entry": { "title": "Diff Entry", "description": "Diff Entry", "type": "object", "properties": { "sha": { "type": "string", "examples": [ "bbcd538c8e72b8c175046e27cc8f907076331401" ] }, "filename": { "type": "string", "examples": [ "file1.txt" ] }, "status": { "type": "string", "enum": [ "added", "removed", "modified", "renamed", "copied", "changed", "unchanged" ], "examples": [ "added" ] }, "additions": { "type": "integer", "examples": [ 103 ] }, "deletions": { "type": "integer", "examples": [ 21 ] }, "changes": { "type": "integer", "examples": [ 124 ] }, "blob_url": { "type": "string", "format": "uri", "examples": [ "https://github.com/octocat/Hello-World/blob/6dcb09b5b57875f334f61aebed695e2e4193db5e/file1.txt" ] }, "raw_url": { "type": "string", "format": "uri", "examples": [ "https://github.com/octocat/Hello-World/raw/6dcb09b5b57875f334f61aebed695e2e4193db5e/file1.txt" ] }, "contents_url": { "type": "string", "format": "uri", "examples": [ "https://api.github.com/repos/octocat/Hello-World/contents/file1.txt?ref=6dcb09b5b57875f334f61aebed695e2e4193db5e" ] }, "patch": { "type": "string", "examples": [ "@@ -132,7 +132,7 @@ module Test @@ -1000,7 +1000,7 @@ module Test" ] }, "previous_filename": { "type": "string", "examples": [ "file.txt" ] } }, "required": [ "additions", "blob_url", "changes", "contents_url", "deletions", "filename", "raw_url", "sha", "status" ] }, "commit": { "title": "Commit", "description": "Commit", "type": "object", "properties": { "url": { "type": "string", "format": "uri", "examples": [ "https://api.github.com/repos/octocat/Hello-World/commits/6dcb09b5b57875f334f61aebed695e2e4193db5e" ] }, "sha": { "type": "string", "examples": [ "6dcb09b5b57875f334f61aebed695e2e4193db5e" ] }, "node_id": { "type": "string", "examples": [ "MDY6Q29tbWl0NmRjYjA5YjViNTc4NzVmMzM0ZjYxYWViZWQ2OTVlMmU0MTkzZGI1ZQ==" ] }, "html_url": { "type": "string", "format": "uri", "examples": [ "https://github.com/octocat/Hello-World/commit/6dcb09b5b57875f334f61aebed695e2e4193db5e" ] }, "comments_url": { "type": "string", "format": "uri", "examples": [ "https://api.github.com/repos/octocat/Hello-World/commits/6dcb09b5b57875f334f61aebed695e2e4193db5e/comments" ] }, "commit": { "type": "object", "properties": { "url": { "type": "string", "format": "uri", "examples": [ "https://api.github.com/repos/octocat/Hello-World/commits/6dcb09b5b57875f334f61aebed695e2e4193db5e" ] }, "author": { "anyOf": [ { "type": "null" }, { "$ref": "#/components/schemas/git-user" } ] }, "committer": { "anyOf": [ { "type": "null" }, { "$ref": "#/components/schemas/git-user" } ] }, "message": { "type": "string", "examples": [ "Fix all the bugs" ] }, "comment_count": { "type": "integer", "examples": [ 0 ] }, "tree": { "type": "object", "properties": { "sha": { "type": "string", "examples": [ "827efc6d56897b048c772eb4087f854f46256132" ] }, "url": { "type": "string", "format": "uri", "examples": [ "https://api.github.com/repos/octocat/Hello-World/tree/827efc6d56897b048c772eb4087f854f46256132" ] } }, "required": [ "sha", "url" ] }, "verification": { "$ref": "#/components/schemas/verification" } }, "required": [ "author", "committer", "comment_count", "message", "tree", "url" ] }, "author": { "anyOf": [ { "type": "null" }, { "$ref": "#/components/schemas/simple-user" } ] }, "committer": { "anyOf": [ { "type": "null" }, { "$ref": "#/components/schemas/simple-user" } ] }, "parents": { "type": "array", "items": { "type": "object", "properties": { "sha": { "type": "string", "examples": [ "7638417db6d59f3c431d3e1f261cc637155684cd" ] }, "url": { "type": "string", "format": "uri", "examples": [ "https://api.github.com/repos/octocat/Hello-World/commits/7638417db6d59f3c431d3e1f261cc637155684cd" ] }, "html_url": { "type": "string", "format": "uri", "examples": [ "https://github.com/octocat/Hello-World/commit/7638417db6d59f3c431d3e1f261cc637155684cd" ] } }, "required": [ "sha", "url" ] } }, "stats": { "type": "object", "properties": { "additions": { "type": "integer" }, "deletions": { "type": "integer" }, "total": { "type": "integer" } } }, "files": { "type": "array", "items": { "$ref": "#/components/schemas/diff-entry" } } }, "required": [ "url", "sha", "node_id", "html_url", "comments_url", "commit", "author", "committer", "parents" ] }, "branch-with-protection": { "title": "Branch With Protection", "description": "Branch With Protection", "type": "object", "properties": { "name": { "type": "string" }, "commit": { "$ref": "#/components/schemas/commit" }, "_links": { "type": "object", "properties": { "html": { "type": "string" }, "self": { "type": "string", "format": "uri" } }, "required": [ "html", "self" ] }, "protected": { "type": "boolean" }, "protection": { "$ref": "#/components/schemas/branch-protection" }, "protection_url": { "type": "string", "format": "uri" }, "pattern": { "type": "string", "examples": [ "\"mas*\"" ] }, "required_approving_review_count": { "type": "integer", "examples": [ 1 ] } }, "required": [ "name", "commit", "_links", "protection", "protected", "protection_url" ] }, "status-check-policy": { "title": "Status Check Policy", "description": "Status Check Policy", "type": "object", "properties": { "url": { "type": "string", "format": "uri", "examples": [ "https://api.github.com/repos/octocat/Hello-World/branches/master/protection/required_status_checks" ] }, "strict": { "type": "boolean", "examples": [ true ] }, "contexts": { "type": "array", "items": { "type": "string" }, "examples": [ "continuous-integration/travis-ci" ] }, "contexts_url": { "type": "string", "format": "uri", "examples": [ "https://api.github.com/repos/octocat/Hello-World/branches/master/protection/required_status_checks/contexts" ] } }, "required": [ "url", "contexts_url", "strict", "contexts" ] }, "protected-branch": { "title": "Protected Branch", "description": "Branch protections protect branches", "type": "object", "properties": { "url": { "type": "string", "format": "uri" }, "required_status_checks": { "$ref": "#/components/schemas/status-check-policy" }, "required_pull_request_reviews": { "type": "object", "properties": { "url": { "type": "string", "format": "uri" }, "dismiss_stale_reviews": { "type": "boolean" }, "require_code_owner_reviews": { "type": "boolean" }, "required_approving_review_count": { "type": "integer" }, "dismissal_restrictions": { "type": "object", "properties": { "url": { "type": "string", "format": "uri" }, "users_url": { "type": "string", "format": "uri" }, "teams_url": { "type": "string", "format": "uri" }, "users": { "type": "array", "items": { "$ref": "#/components/schemas/simple-user" } }, "teams": { "type": "array", "items": { "$ref": "#/components/schemas/team" } } }, "required": [ "url", "users_url", "teams_url", "users", "teams" ] } }, "required": [ "url" ] }, "required_signatures": { "type": "object", "properties": { "url": { "type": "string", "format": "uri", "examples": [ "https://api.github.com/repos/octocat/Hello-World/branches/master/protection/required_signatures" ] }, "enabled": { "type": "boolean", "examples": [ true ] } }, "required": [ "url", "enabled" ] }, "enforce_admins": { "type": "object", "properties": { "url": { "type": "string", "format": "uri" }, "enabled": { "type": "boolean" } }, "additionalProperties": false, "required": [ "url", "enabled" ] }, "required_linear_history": { "type": "object", "properties": { "enabled": { "type": "boolean" } }, "additionalProperties": false, "required": [ "enabled" ] }, "allow_force_pushes": { "type": "object", "properties": { "enabled": { "type": "boolean" } }, "additionalProperties": false, "required": [ "enabled" ] }, "allow_deletions": { "type": "object", "properties": { "enabled": { "type": "boolean" } }, "additionalProperties": false, "required": [ "enabled" ] }, "restrictions": { "$ref": "#/components/schemas/branch-restriction-policy" }, "required_conversation_resolution": { "type": "object", "properties": { "enabled": { "type": "boolean" } }, "additionalProperties": false } }, "required": [ "url" ] }, "deployment-simple": { "title": "Deployment", "description": "A deployment created as the result of an Actions check run from a workflow that references an environment", "type": "object", "properties": { "url": { "type": "string", "format": "uri", "examples": [ "https://api.github.com/repos/octocat/example/deployments/1" ] }, "id": { "description": "Unique identifier of the deployment", "type": "integer", "examples": [ 42 ] }, "node_id": { "type": "string", "examples": [ "MDEwOkRlcGxveW1lbnQx" ] }, "task": { "description": "Parameter to specify a task to execute", "type": "string", "examples": [ "deploy" ] }, "original_environment": { "type": "string", "examples": [ "staging" ] }, "environment": { "description": "Name for the target deployment environment.", "type": "string", "examples": [ "production" ] }, "description": { "type": [ "string", "null" ], "examples": [ "Deploy request from hubot" ] }, "created_at": { "type": "string", "format": "date-time", "examples": [ "2012-07-20T01:19:13Z" ] }, "updated_at": { "type": "string", "format": "date-time", "examples": [ "2012-07-20T01:19:13Z" ] }, "statuses_url": { "type": "string", "format": "uri", "examples": [ "https://api.github.com/repos/octocat/example/deployments/1/statuses" ] }, "repository_url": { "type": "string", "format": "uri", "examples": [ "https://api.github.com/repos/octocat/example" ] }, "transient_environment": { "description": "Specifies if the given environment is will no longer exist at some point in the future. Default: false.", "type": "boolean", "examples": [ true ] }, "production_environment": { "description": "Specifies if the given environment is one that end-users directly interact with. Default: false.", "type": "boolean", "examples": [ true ] }, "performed_via_github_app": { "anyOf": [ { "type": "null" }, { "$ref": "#/components/schemas/integration" } ] } }, "required": [ "id", "node_id", "task", "environment", "description", "statuses_url", "repository_url", "url", "created_at", "updated_at" ] }, "check-run": { "title": "CheckRun", "description": "A check performed on the code of a given code change", "type": "object", "properties": { "id": { "description": "The id of the check.", "type": "integer", "examples": [ 21 ] }, "head_sha": { "description": "The SHA of the commit that is being checked.", "type": "string", "examples": [ "009b8a3a9ccbb128af87f9b1c0f4c62e8a304f6d" ] }, "node_id": { "type": "string", "examples": [ "MDg6Q2hlY2tSdW40" ] }, "external_id": { "type": [ "string", "null" ], "examples": [ "42" ] }, "url": { "type": "string", "examples": [ "https://api.github.com/repos/github/hello-world/check-runs/4" ] }, "html_url": { "type": [ "string", "null" ], "examples": [ "https://github.com/github/hello-world/runs/4" ] }, "details_url": { "type": [ "string", "null" ], "examples": [ "https://example.com" ] }, "status": { "description": "The phase of the lifecycle that the check is currently in.", "type": "string", "enum": [ "queued", "in_progress", "completed" ], "examples": [ "queued" ] }, "conclusion": { "type": [ "string", "null" ], "enum": [ "success", "failure", "neutral", "cancelled", "skipped", "timed_out", "action_required", null ], "examples": [ "neutral" ] }, "started_at": { "type": [ "string", "null" ], "format": "date-time", "examples": [ "2018-05-04T01:14:52Z" ] }, "completed_at": { "type": [ "string", "null" ], "format": "date-time", "examples": [ "2018-05-04T01:14:52Z" ] }, "output": { "type": "object", "properties": { "title": { "type": [ "string", "null" ] }, "summary": { "type": [ "string", "null" ] }, "text": { "type": [ "string", "null" ] }, "annotations_count": { "type": "integer" }, "annotations_url": { "type": "string", "format": "uri" } }, "required": [ "title", "summary", "text", "annotations_count", "annotations_url" ] }, "name": { "description": "The name of the check.", "type": "string", "examples": [ "test-coverage" ] }, "check_suite": { "type": [ "object", "null" ], "properties": { "id": { "type": "integer" } }, "required": [ "id" ] }, "app": { "anyOf": [ { "type": "null" }, { "$ref": "#/components/schemas/integration" } ] }, "pull_requests": { "type": "array", "items": { "$ref": "#/components/schemas/pull-request-minimal" } }, "deployment": { "$ref": "#/components/schemas/deployment-simple" } }, "required": [ "id", "node_id", "head_sha", "name", "url", "html_url", "details_url", "status", "conclusion", "started_at", "completed_at", "external_id", "check_suite", "output", "app", "pull_requests" ] }, "check-annotation": { "title": "Check Annotation", "description": "Check Annotation", "type": "object", "properties": { "path": { "type": "string", "examples": [ "README.md" ] }, "start_line": { "type": "integer", "examples": [ 2 ] }, "end_line": { "type": "integer", "examples": [ 2 ] }, "start_column": { "type": [ "integer", "null" ], "examples": [ 5 ] }, "end_column": { "type": [ "integer", "null" ], "examples": [ 10 ] }, "annotation_level": { "type": [ "string", "null" ], "examples": [ "warning" ] }, "title": { "type": [ "string", "null" ], "examples": [ "Spell Checker" ] }, "message": { "type": [ "string", "null" ], "examples": [ "Check your spelling for 'banaas'." ] }, "raw_details": { "type": [ "string", "null" ], "examples": [ "Do you mean 'bananas' or 'banana'?" ] }, "blob_href": { "type": "string" } }, "required": [ "path", "blob_href", "start_line", "end_line", "start_column", "end_column", "annotation_level", "title", "message", "raw_details" ] }, "check-suite": { "title": "CheckSuite", "description": "A suite of checks performed on the code of a given code change", "type": "object", "properties": { "id": { "type": "integer", "examples": [ 5 ] }, "node_id": { "type": "string", "examples": [ "MDEwOkNoZWNrU3VpdGU1" ] }, "head_branch": { "type": [ "string", "null" ], "examples": [ "master" ] }, "head_sha": { "description": "The SHA of the head commit that is being checked.", "type": "string", "examples": [ "009b8a3a9ccbb128af87f9b1c0f4c62e8a304f6d" ] }, "status": { "type": [ "string", "null" ], "enum": [ "queued", "in_progress", "completed", null ], "examples": [ "completed" ] }, "conclusion": { "type": [ "string", "null" ], "enum": [ "success", "failure", "neutral", "cancelled", "skipped", "timed_out", "action_required", null ], "examples": [ "neutral" ] }, "url": { "type": [ "string", "null" ], "examples": [ "https://api.github.com/repos/github/hello-world/check-suites/5" ] }, "before": { "type": [ "string", "null" ], "examples": [ "146e867f55c26428e5f9fade55a9bbf5e95a7912" ] }, "after": { "type": [ "string", "null" ], "examples": [ "d6fde92930d4715a2b49857d24b940956b26d2d3" ] }, "pull_requests": { "type": [ "array", "null" ], "items": { "$ref": "#/components/schemas/pull-request-minimal" } }, "app": { "anyOf": [ { "type": "null" }, { "$ref": "#/components/schemas/integration" } ] }, "repository": { "$ref": "#/components/schemas/minimal-repository" }, "created_at": { "type": [ "string", "null" ], "format": "date-time" }, "updated_at": { "type": [ "string", "null" ], "format": "date-time" }, "head_commit": { "$ref": "#/components/schemas/simple-commit" }, "latest_check_runs_count": { "type": "integer" }, "check_runs_url": { "type": "string" }, "rerequestable": { "type": "boolean" }, "runs_rerequestable": { "type": "boolean" } }, "required": [ "id", "node_id", "head_branch", "status", "conclusion", "head_sha", "url", "before", "after", "created_at", "updated_at", "app", "head_commit", "repository", "latest_check_runs_count", "check_runs_url", "pull_requests" ] }, "check-suite-preference": { "title": "Check Suite Preference", "description": "Check suite configuration preferences for a repository.", "type": "object", "required": [ "preferences", "repository" ], "properties": { "preferences": { "type": "object", "properties": { "auto_trigger_checks": { "type": "array", "items": { "type": "object", "properties": { "app_id": { "type": "integer" }, "setting": { "type": "boolean" } }, "required": [ "app_id", "setting" ] } } } }, "repository": { "$ref": "#/components/schemas/minimal-repository" } } }, "code-scanning-analysis-tool-name": { "type": "string", "description": "The name of the tool used to generate the code scanning analysis." }, "code-scanning-analysis-tool-guid": { "type": [ "string", "null" ], "description": "The GUID of the tool used to generate the code scanning analysis, if provided in the uploaded SARIF data." }, "code-scanning-ref": { "type": "string", "description": "The full Git reference, formatted as `refs/heads/`,\n`refs/pull//merge`, or `refs/pull//head`." }, "code-scanning-alert-state": { "type": "string", "description": "State of a code scanning alert.", "enum": [ "open", "closed", "dismissed", "fixed" ] }, "alert-number": { "type": "integer", "description": "The security alert number.", "readOnly": true }, "alert-created-at": { "type": "string", "description": "The time that the alert was created in ISO 8601 format: `YYYY-MM-DDTHH:MM:SSZ`.", "format": "date-time", "readOnly": true }, "alert-url": { "type": "string", "description": "The REST API URL of the alert resource.", "format": "uri", "readOnly": true }, "alert-html-url": { "type": "string", "description": "The GitHub URL of the alert resource.", "format": "uri", "readOnly": true }, "alert-instances-url": { "type": "string", "description": "The REST API URL for fetching the list of instances for an alert.", "format": "uri", "readOnly": true }, "code-scanning-alert-dismissed-at": { "type": [ "string", "null" ], "description": "The time that the alert was dismissed in ISO 8601 format: `YYYY-MM-DDTHH:MM:SSZ`.", "format": "date-time", "readOnly": true }, "code-scanning-alert-dismissed-reason": { "type": [ "string", "null" ], "description": "**Required when the state is dismissed.** The reason for dismissing or closing the alert. Can be one of: `false positive`, `won't fix`, and `used in tests`.", "enum": [ null, "false positive", "won't fix", "used in tests" ] }, "code-scanning-alert-rule-summary": { "type": "object", "properties": { "id": { "type": [ "string", "null" ], "description": "A unique identifier for the rule used to detect the alert." }, "name": { "type": "string", "description": "The name of the rule used to detect the alert." }, "severity": { "type": [ "string", "null" ], "description": "The severity of the alert.", "enum": [ "none", "note", "warning", "error", null ] }, "description": { "type": "string", "description": "A short description of the rule used to detect the alert." } } }, "code-scanning-analysis-tool-version": { "type": [ "string", "null" ], "description": "The version of the tool used to generate the code scanning analysis." }, "code-scanning-analysis-tool": { "type": "object", "properties": { "name": { "$ref": "#/components/schemas/code-scanning-analysis-tool-name" }, "version": { "$ref": "#/components/schemas/code-scanning-analysis-tool-version" }, "guid": { "$ref": "#/components/schemas/code-scanning-analysis-tool-guid" } } }, "code-scanning-analysis-analysis-key": { "type": "string", "description": "Identifies the configuration under which the analysis was executed. For example, in GitHub Actions this includes the workflow filename and job name." }, "code-scanning-alert-environment": { "type": "string", "description": "Identifies the variable values associated with the environment in which the analysis that generated this alert instance was performed, such as the language that was analyzed." }, "code-scanning-analysis-category": { "type": "string", "description": "Identifies the configuration under which the analysis was executed. Used to distinguish between multiple analyses for the same tool and commit, but performed on different languages or different parts of the code." }, "code-scanning-alert-location": { "type": "object", "description": "Describe a region within a file for the alert.", "properties": { "path": { "type": "string" }, "start_line": { "type": "integer" }, "end_line": { "type": "integer" }, "start_column": { "type": "integer" }, "end_column": { "type": "integer" } } }, "code-scanning-alert-classification": { "type": [ "string", "null" ], "description": "A classification of the file. For example to identify it as generated.", "enum": [ "source", "generated", "test", "library", null ] }, "code-scanning-alert-instance": { "type": "object", "properties": { "ref": { "$ref": "#/components/schemas/code-scanning-ref" }, "analysis_key": { "$ref": "#/components/schemas/code-scanning-analysis-analysis-key" }, "environment": { "$ref": "#/components/schemas/code-scanning-alert-environment" }, "category": { "$ref": "#/components/schemas/code-scanning-analysis-category" }, "state": { "$ref": "#/components/schemas/code-scanning-alert-state" }, "commit_sha": { "type": "string" }, "message": { "type": "object", "properties": { "text": { "type": "string" } } }, "location": { "$ref": "#/components/schemas/code-scanning-alert-location" }, "html_url": { "type": "string" }, "classifications": { "type": "array", "description": "Classifications that have been applied to the file that triggered the alert.\nFor example identifying it as documentation, or a generated file.", "items": { "$ref": "#/components/schemas/code-scanning-alert-classification" } } } }, "code-scanning-alert-items": { "type": "object", "properties": { "number": { "$ref": "#/components/schemas/alert-number" }, "created_at": { "$ref": "#/components/schemas/alert-created-at" }, "url": { "$ref": "#/components/schemas/alert-url" }, "html_url": { "$ref": "#/components/schemas/alert-html-url" }, "instances_url": { "$ref": "#/components/schemas/alert-instances-url" }, "state": { "$ref": "#/components/schemas/code-scanning-alert-state" }, "dismissed_by": { "anyOf": [ { "type": "null" }, { "$ref": "#/components/schemas/simple-user" } ] }, "dismissed_at": { "$ref": "#/components/schemas/code-scanning-alert-dismissed-at" }, "dismissed_reason": { "$ref": "#/components/schemas/code-scanning-alert-dismissed-reason" }, "rule": { "$ref": "#/components/schemas/code-scanning-alert-rule-summary" }, "tool": { "$ref": "#/components/schemas/code-scanning-analysis-tool" }, "most_recent_instance": { "$ref": "#/components/schemas/code-scanning-alert-instance" } }, "required": [ "number", "created_at", "url", "html_url", "instances_url", "state", "dismissed_by", "dismissed_at", "dismissed_reason", "rule", "tool", "most_recent_instance" ] }, "code-scanning-alert-rule": { "type": "object", "properties": { "id": { "type": [ "string", "null" ], "description": "A unique identifier for the rule used to detect the alert." }, "name": { "type": "string", "description": "The name of the rule used to detect the alert." }, "severity": { "type": [ "string", "null" ], "description": "The severity of the alert.", "enum": [ "none", "note", "warning", "error", null ] }, "description": { "type": "string", "description": "A short description of the rule used to detect the alert." }, "full_description": { "type": "string", "description": "description of the rule used to detect the alert." }, "tags": { "type": [ "array", "null" ], "description": "A set of tags applicable for the rule.", "items": { "type": "string" } }, "help": { "type": [ "string", "null" ], "description": "Detailed documentation for the rule as GitHub Flavored Markdown." } } }, "code-scanning-alert": { "type": "object", "properties": { "number": { "$ref": "#/components/schemas/alert-number" }, "created_at": { "$ref": "#/components/schemas/alert-created-at" }, "url": { "$ref": "#/components/schemas/alert-url" }, "html_url": { "$ref": "#/components/schemas/alert-html-url" }, "instances_url": { "$ref": "#/components/schemas/alert-instances-url" }, "state": { "$ref": "#/components/schemas/code-scanning-alert-state" }, "dismissed_by": { "anyOf": [ { "type": "null" }, { "$ref": "#/components/schemas/simple-user" } ] }, "dismissed_at": { "$ref": "#/components/schemas/code-scanning-alert-dismissed-at" }, "dismissed_reason": { "$ref": "#/components/schemas/code-scanning-alert-dismissed-reason" }, "rule": { "$ref": "#/components/schemas/code-scanning-alert-rule" }, "tool": { "$ref": "#/components/schemas/code-scanning-analysis-tool" }, "most_recent_instance": { "$ref": "#/components/schemas/code-scanning-alert-instance" }, "instances": { "deprecated": true } }, "required": [ "number", "created_at", "url", "html_url", "instances_url", "state", "dismissed_by", "dismissed_at", "dismissed_reason", "rule", "tool", "most_recent_instance" ] }, "code-scanning-alert-set-state": { "description": "Sets the state of the code scanning alert. Can be one of `open` or `dismissed`. You must provide `dismissed_reason` when you set the state to `dismissed`.", "type": "string", "enum": [ "open", "dismissed" ] }, "code-scanning-analysis-sarif-id": { "type": "string", "description": "An identifier for the upload.", "examples": [ "6c81cd8e-b078-4ac3-a3be-1dad7dbd0b53" ] }, "code-scanning-analysis-commit-sha": { "description": "The SHA of the commit to which the analysis you are uploading relates.", "type": "string", "minLength": 40, "maxLength": 40, "pattern": "^[0-9a-fA-F]+$" }, "code-scanning-analysis-environment": { "type": "string", "description": "Identifies the variable values associated with the environment in which this analysis was performed." }, "code-scanning-analysis-created-at": { "type": "string", "description": "The time that the analysis was created in ISO 8601 format: `YYYY-MM-DDTHH:MM:SSZ`.", "format": "date-time", "readOnly": true }, "code-scanning-analysis-url": { "type": "string", "description": "The REST API URL of the analysis resource.", "format": "uri", "readOnly": true }, "code-scanning-analysis": { "type": "object", "properties": { "ref": { "$ref": "#/components/schemas/code-scanning-ref" }, "commit_sha": { "$ref": "#/components/schemas/code-scanning-analysis-commit-sha" }, "analysis_key": { "$ref": "#/components/schemas/code-scanning-analysis-analysis-key" }, "environment": { "$ref": "#/components/schemas/code-scanning-analysis-environment" }, "category": { "$ref": "#/components/schemas/code-scanning-analysis-category" }, "error": { "type": "string", "examples": [ "error reading field xyz" ] }, "created_at": { "$ref": "#/components/schemas/code-scanning-analysis-created-at" }, "results_count": { "type": "integer", "description": "The total number of results in the analysis." }, "rules_count": { "type": "integer", "description": "The total number of rules used in the analysis." }, "id": { "type": "integer", "description": "Unique identifier for this analysis." }, "url": { "$ref": "#/components/schemas/code-scanning-analysis-url" }, "sarif_id": { "$ref": "#/components/schemas/code-scanning-analysis-sarif-id" }, "tool": { "$ref": "#/components/schemas/code-scanning-analysis-tool" }, "deletable": { "type": "boolean" }, "warning": { "type": "string", "description": "Warning generated when processing the analysis", "examples": [ "123 results were ignored" ] }, "tool_name": { "type": "string" } }, "required": [ "ref", "commit_sha", "analysis_key", "environment", "error", "created_at", "results_count", "rules_count", "id", "url", "sarif_id", "tool", "deletable", "warning" ] }, "code-scanning-analysis-sarif-file": { "description": "A Base64 string representing the SARIF file to upload. You must first compress your SARIF file using [`gzip`](http://www.gnu.org/software/gzip/manual/gzip.html) and then translate the contents of the file into a Base64 encoding string. For more information, see \"[SARIF support for code scanning](https://docs.github.com/enterprise-server@3.0/code-security/secure-coding/sarif-support-for-code-scanning).\"", "type": "string" }, "code-scanning-sarifs-receipt": { "type": "object", "properties": { "id": { "$ref": "#/components/schemas/code-scanning-analysis-sarif-id" }, "url": { "type": "string", "description": "The REST API URL for checking the status of the upload.", "format": "uri", "readOnly": true } } }, "collaborator": { "title": "Collaborator", "description": "Collaborator", "type": "object", "properties": { "login": { "type": "string", "examples": [ "octocat" ] }, "id": { "type": "integer", "examples": [ 1 ] }, "email": { "type": [ "string", "null" ] }, "name": { "type": [ "string", "null" ] }, "node_id": { "type": "string", "examples": [ "MDQ6VXNlcjE=" ] }, "avatar_url": { "type": "string", "format": "uri", "examples": [ "https://github.com/images/error/octocat_happy.gif" ] }, "gravatar_id": { "type": [ "string", "null" ], "examples": [ "41d064eb2195891e12d0413f63227ea7" ] }, "url": { "type": "string", "format": "uri", "examples": [ "https://api.github.com/users/octocat" ] }, "html_url": { "type": "string", "format": "uri", "examples": [ "https://github.com/octocat" ] }, "followers_url": { "type": "string", "format": "uri", "examples": [ "https://api.github.com/users/octocat/followers" ] }, "following_url": { "type": "string", "examples": [ "https://api.github.com/users/octocat/following{/other_user}" ] }, "gists_url": { "type": "string", "examples": [ "https://api.github.com/users/octocat/gists{/gist_id}" ] }, "starred_url": { "type": "string", "examples": [ "https://api.github.com/users/octocat/starred{/owner}{/repo}" ] }, "subscriptions_url": { "type": "string", "format": "uri", "examples": [ "https://api.github.com/users/octocat/subscriptions" ] }, "organizations_url": { "type": "string", "format": "uri", "examples": [ "https://api.github.com/users/octocat/orgs" ] }, "repos_url": { "type": "string", "format": "uri", "examples": [ "https://api.github.com/users/octocat/repos" ] }, "events_url": { "type": "string", "examples": [ "https://api.github.com/users/octocat/events{/privacy}" ] }, "received_events_url": { "type": "string", "format": "uri", "examples": [ "https://api.github.com/users/octocat/received_events" ] }, "type": { "type": "string", "examples": [ "User" ] }, "site_admin": { "type": "boolean" }, "permissions": { "type": "object", "properties": { "pull": { "type": "boolean" }, "triage": { "type": "boolean" }, "push": { "type": "boolean" }, "maintain": { "type": "boolean" }, "admin": { "type": "boolean" } }, "required": [ "pull", "push", "admin" ] } }, "required": [ "avatar_url", "events_url", "followers_url", "following_url", "gists_url", "gravatar_id", "html_url", "id", "node_id", "login", "organizations_url", "received_events_url", "repos_url", "site_admin", "starred_url", "subscriptions_url", "type", "url" ] }, "repository-invitation": { "title": "Repository Invitation", "description": "Repository invitations let you manage who you collaborate with.", "type": "object", "properties": { "id": { "description": "Unique identifier of the repository invitation.", "type": "integer", "examples": [ 42 ] }, "repository": { "$ref": "#/components/schemas/minimal-repository" }, "invitee": { "anyOf": [ { "type": "null" }, { "$ref": "#/components/schemas/simple-user" } ] }, "inviter": { "anyOf": [ { "type": "null" }, { "$ref": "#/components/schemas/simple-user" } ] }, "permissions": { "description": "The permission associated with the invitation.", "type": "string", "enum": [ "read", "write", "admin", "triage", "maintain" ], "examples": [ "read" ] }, "created_at": { "type": "string", "format": "date-time", "examples": [ "2016-06-13T14:52:50-05:00" ] }, "expired": { "description": "Whether or not the invitation has expired", "type": "boolean" }, "url": { "description": "URL for the repository invitation", "type": "string", "examples": [ "https://api.github.com/user/repository-invitations/1" ] }, "html_url": { "type": "string", "examples": [ "https://github.com/octocat/Hello-World/invitations" ] }, "node_id": { "type": "string" } }, "required": [ "id", "node_id", "permissions", "inviter", "invitee", "repository", "url", "html_url", "created_at" ] }, "repository-collaborator-permission": { "title": "Repository Collaborator Permission", "description": "Repository Collaborator Permission", "type": "object", "properties": { "permission": { "type": "string" }, "user": { "anyOf": [ { "type": "null" }, { "$ref": "#/components/schemas/collaborator" } ] } }, "required": [ "permission", "user" ] }, "commit-comment": { "title": "Commit Comment", "description": "Commit Comment", "type": "object", "properties": { "html_url": { "type": "string", "format": "uri" }, "url": { "type": "string", "format": "uri" }, "id": { "type": "integer" }, "node_id": { "type": "string" }, "body": { "type": "string" }, "path": { "type": [ "string", "null" ] }, "position": { "type": [ "integer", "null" ] }, "line": { "type": [ "integer", "null" ] }, "commit_id": { "type": "string" }, "user": { "anyOf": [ { "type": "null" }, { "$ref": "#/components/schemas/simple-user" } ] }, "created_at": { "type": "string", "format": "date-time" }, "updated_at": { "type": "string", "format": "date-time" }, "author_association": { "$ref": "#/components/schemas/author_association" }, "reactions": { "$ref": "#/components/schemas/reaction-rollup" } }, "required": [ "url", "html_url", "id", "node_id", "user", "position", "line", "path", "commit_id", "body", "author_association", "created_at", "updated_at" ] }, "scim-error": { "title": "Scim Error", "description": "Scim Error", "type": "object", "properties": { "message": { "type": [ "string", "null" ] }, "documentation_url": { "type": [ "string", "null" ] }, "detail": { "type": [ "string", "null" ] }, "status": { "type": "integer" }, "scimType": { "type": [ "string", "null" ] }, "schemas": { "type": "array", "items": { "type": "string" } } } }, "branch-short": { "title": "Branch Short", "description": "Branch Short", "type": "object", "properties": { "name": { "type": "string" }, "commit": { "type": "object", "properties": { "sha": { "type": "string" }, "url": { "type": "string" } }, "required": [ "sha", "url" ] }, "protected": { "type": "boolean" } }, "required": [ "name", "commit", "protected" ] }, "link": { "title": "Link", "description": "Hypermedia Link", "type": "object", "properties": { "href": { "type": "string" } }, "required": [ "href" ] }, "pull-request-simple": { "title": "Pull Request Simple", "description": "Pull Request Simple", "type": "object", "properties": { "url": { "type": "string", "format": "uri", "examples": [ "https://api.github.com/repos/octocat/Hello-World/pulls/1347" ] }, "id": { "type": "integer", "examples": [ 1 ] }, "node_id": { "type": "string", "examples": [ "MDExOlB1bGxSZXF1ZXN0MQ==" ] }, "html_url": { "type": "string", "format": "uri", "examples": [ "https://github.com/octocat/Hello-World/pull/1347" ] }, "diff_url": { "type": "string", "format": "uri", "examples": [ "https://github.com/octocat/Hello-World/pull/1347.diff" ] }, "patch_url": { "type": "string", "format": "uri", "examples": [ "https://github.com/octocat/Hello-World/pull/1347.patch" ] }, "issue_url": { "type": "string", "format": "uri", "examples": [ "https://api.github.com/repos/octocat/Hello-World/issues/1347" ] }, "commits_url": { "type": "string", "format": "uri", "examples": [ "https://api.github.com/repos/octocat/Hello-World/pulls/1347/commits" ] }, "review_comments_url": { "type": "string", "format": "uri", "examples": [ "https://api.github.com/repos/octocat/Hello-World/pulls/1347/comments" ] }, "review_comment_url": { "type": "string", "examples": [ "https://api.github.com/repos/octocat/Hello-World/pulls/comments{/number}" ] }, "comments_url": { "type": "string", "format": "uri", "examples": [ "https://api.github.com/repos/octocat/Hello-World/issues/1347/comments" ] }, "statuses_url": { "type": "string", "format": "uri", "examples": [ "https://api.github.com/repos/octocat/Hello-World/statuses/6dcb09b5b57875f334f61aebed695e2e4193db5e" ] }, "number": { "type": "integer", "examples": [ 1347 ] }, "state": { "type": "string", "examples": [ "open" ] }, "locked": { "type": "boolean", "examples": [ true ] }, "title": { "type": "string", "examples": [ "new-feature" ] }, "user": { "anyOf": [ { "type": "null" }, { "$ref": "#/components/schemas/simple-user" } ] }, "body": { "type": [ "string", "null" ], "examples": [ "Please pull these awesome changes" ] }, "labels": { "type": "array", "items": { "type": "object", "properties": { "id": { "type": "integer", "format": "int64" }, "node_id": { "type": "string" }, "url": { "type": "string" }, "name": { "type": "string" }, "description": { "type": "string" }, "color": { "type": "string" }, "default": { "type": "boolean" } }, "required": [ "id", "node_id", "url", "name", "description", "color", "default" ] } }, "milestone": { "anyOf": [ { "type": "null" }, { "$ref": "#/components/schemas/milestone" } ] }, "active_lock_reason": { "type": [ "string", "null" ], "examples": [ "too heated" ] }, "created_at": { "type": "string", "format": "date-time", "examples": [ "2011-01-26T19:01:12Z" ] }, "updated_at": { "type": "string", "format": "date-time", "examples": [ "2011-01-26T19:01:12Z" ] }, "closed_at": { "type": [ "string", "null" ], "format": "date-time", "examples": [ "2011-01-26T19:01:12Z" ] }, "merged_at": { "type": [ "string", "null" ], "format": "date-time", "examples": [ "2011-01-26T19:01:12Z" ] }, "merge_commit_sha": { "type": [ "string", "null" ], "examples": [ "e5bd3914e2e596debea16f433f57875b5b90bcd6" ] }, "assignee": { "anyOf": [ { "type": "null" }, { "$ref": "#/components/schemas/simple-user" } ] }, "assignees": { "type": [ "array", "null" ], "items": { "$ref": "#/components/schemas/simple-user" } }, "requested_reviewers": { "type": [ "array", "null" ], "items": { "$ref": "#/components/schemas/simple-user" } }, "requested_teams": { "type": [ "array", "null" ], "items": { "$ref": "#/components/schemas/team" } }, "head": { "type": "object", "properties": { "label": { "type": "string" }, "ref": { "type": "string" }, "repo": { "$ref": "#/components/schemas/repository" }, "sha": { "type": "string" }, "user": { "anyOf": [ { "type": "null" }, { "$ref": "#/components/schemas/simple-user" } ] } }, "required": [ "label", "ref", "repo", "sha", "user" ] }, "base": { "type": "object", "properties": { "label": { "type": "string" }, "ref": { "type": "string" }, "repo": { "$ref": "#/components/schemas/repository" }, "sha": { "type": "string" }, "user": { "anyOf": [ { "type": "null" }, { "$ref": "#/components/schemas/simple-user" } ] } }, "required": [ "label", "ref", "repo", "sha", "user" ] }, "_links": { "type": "object", "properties": { "comments": { "$ref": "#/components/schemas/link" }, "commits": { "$ref": "#/components/schemas/link" }, "statuses": { "$ref": "#/components/schemas/link" }, "html": { "$ref": "#/components/schemas/link" }, "issue": { "$ref": "#/components/schemas/link" }, "review_comments": { "$ref": "#/components/schemas/link" }, "review_comment": { "$ref": "#/components/schemas/link" }, "self": { "$ref": "#/components/schemas/link" } }, "required": [ "comments", "commits", "statuses", "html", "issue", "review_comments", "review_comment", "self" ] }, "author_association": { "$ref": "#/components/schemas/author_association" }, "draft": { "description": "Indicates whether or not the pull request is a draft.", "type": "boolean", "examples": [ false ] } }, "required": [ "_links", "assignee", "labels", "base", "body", "closed_at", "comments_url", "commits_url", "created_at", "diff_url", "head", "html_url", "id", "node_id", "issue_url", "merge_commit_sha", "merged_at", "milestone", "number", "patch_url", "review_comment_url", "review_comments_url", "statuses_url", "state", "locked", "title", "updated_at", "url", "user", "author_association" ] }, "simple-commit-status": { "title": "Simple Commit Status", "type": "object", "properties": { "description": { "type": [ "string", "null" ] }, "id": { "type": "integer" }, "node_id": { "type": "string" }, "state": { "type": "string" }, "context": { "type": "string" }, "target_url": { "type": "string", "format": "uri" }, "required": { "type": [ "boolean", "null" ] }, "avatar_url": { "type": [ "string", "null" ], "format": "uri" }, "url": { "type": "string", "format": "uri" }, "created_at": { "type": "string", "format": "date-time" }, "updated_at": { "type": "string", "format": "date-time" } }, "required": [ "description", "id", "node_id", "state", "context", "target_url", "avatar_url", "url", "created_at", "updated_at" ] }, "combined-commit-status": { "title": "Combined Commit Status", "description": "Combined Commit Status", "type": "object", "properties": { "state": { "type": "string" }, "statuses": { "type": "array", "items": { "$ref": "#/components/schemas/simple-commit-status" } }, "sha": { "type": "string" }, "total_count": { "type": "integer" }, "repository": { "$ref": "#/components/schemas/minimal-repository" }, "commit_url": { "type": "string", "format": "uri" }, "url": { "type": "string", "format": "uri" } }, "required": [ "state", "sha", "total_count", "statuses", "repository", "commit_url", "url" ] }, "status": { "title": "Status", "description": "The status of a commit.", "type": "object", "properties": { "url": { "type": "string" }, "avatar_url": { "type": [ "string", "null" ] }, "id": { "type": "integer" }, "node_id": { "type": "string" }, "state": { "type": "string" }, "description": { "type": "string" }, "target_url": { "type": "string" }, "context": { "type": "string" }, "created_at": { "type": "string" }, "updated_at": { "type": "string" }, "creator": { "anyOf": [ { "type": "null" }, { "$ref": "#/components/schemas/simple-user" } ] } }, "required": [ "url", "avatar_url", "id", "node_id", "state", "description", "target_url", "context", "created_at", "updated_at", "creator" ] }, "commit-comparison": { "title": "Commit Comparison", "description": "Commit Comparison", "type": "object", "properties": { "url": { "type": "string", "format": "uri", "examples": [ "https://api.github.com/repos/octocat/Hello-World/compare/master...topic" ] }, "html_url": { "type": "string", "format": "uri", "examples": [ "https://github.com/octocat/Hello-World/compare/master...topic" ] }, "permalink_url": { "type": "string", "format": "uri", "examples": [ "https://github.com/octocat/Hello-World/compare/octocat:bbcd538c8e72b8c175046e27cc8f907076331401...octocat:0328041d1152db8ae77652d1618a02e57f745f17" ] }, "diff_url": { "type": "string", "format": "uri", "examples": [ "https://github.com/octocat/Hello-World/compare/master...topic.diff" ] }, "patch_url": { "type": "string", "format": "uri", "examples": [ "https://github.com/octocat/Hello-World/compare/master...topic.patch" ] }, "base_commit": { "$ref": "#/components/schemas/commit" }, "merge_base_commit": { "$ref": "#/components/schemas/commit" }, "status": { "type": "string", "enum": [ "diverged", "ahead", "behind", "identical" ], "examples": [ "ahead" ] }, "ahead_by": { "type": "integer", "examples": [ 4 ] }, "behind_by": { "type": "integer", "examples": [ 5 ] }, "total_commits": { "type": "integer", "examples": [ 6 ] }, "commits": { "type": "array", "items": { "$ref": "#/components/schemas/commit" } }, "files": { "type": "array", "items": { "$ref": "#/components/schemas/diff-entry" } } }, "required": [ "url", "html_url", "permalink_url", "diff_url", "patch_url", "base_commit", "merge_base_commit", "status", "ahead_by", "behind_by", "total_commits", "commits" ] }, "content-reference-attachment": { "title": "ContentReferenceAttachment", "description": "Content Reference attachments allow you to provide context around URLs posted in comments", "type": "object", "properties": { "id": { "description": "The ID of the attachment", "type": "integer", "examples": [ 21 ] }, "title": { "description": "The title of the attachment", "type": "string", "maxLength": 1024, "examples": [ "Title of the attachment" ] }, "body": { "description": "The body of the attachment", "type": "string", "maxLength": 262144, "examples": [ "Body of the attachment" ] }, "node_id": { "description": "The node_id of the content attachment", "type": "string", "examples": [ "MDE3OkNvbnRlbnRBdHRhY2htZW50MjE=" ] } }, "required": [ "id", "title", "body" ] }, "content-tree": { "title": "Content Tree", "description": "Content Tree", "type": "object", "properties": { "type": { "type": "string" }, "size": { "type": "integer" }, "name": { "type": "string" }, "path": { "type": "string" }, "sha": { "type": "string" }, "url": { "type": "string", "format": "uri" }, "git_url": { "type": [ "string", "null" ], "format": "uri" }, "html_url": { "type": [ "string", "null" ], "format": "uri" }, "download_url": { "type": [ "string", "null" ], "format": "uri" }, "entries": { "type": "array", "items": { "type": "object", "properties": { "type": { "type": "string" }, "size": { "type": "integer" }, "name": { "type": "string" }, "path": { "type": "string" }, "content": { "type": "string" }, "sha": { "type": "string" }, "url": { "type": "string", "format": "uri" }, "git_url": { "type": [ "string", "null" ], "format": "uri" }, "html_url": { "type": [ "string", "null" ], "format": "uri" }, "download_url": { "type": [ "string", "null" ], "format": "uri" }, "_links": { "type": "object", "properties": { "git": { "type": [ "string", "null" ], "format": "uri" }, "html": { "type": [ "string", "null" ], "format": "uri" }, "self": { "type": "string", "format": "uri" } }, "required": [ "git", "html", "self" ] } }, "required": [ "_links", "git_url", "html_url", "download_url", "name", "path", "sha", "size", "type", "url" ] } }, "_links": { "type": "object", "properties": { "git": { "type": [ "string", "null" ], "format": "uri" }, "html": { "type": [ "string", "null" ], "format": "uri" }, "self": { "type": "string", "format": "uri" } }, "required": [ "git", "html", "self" ] } }, "required": [ "_links", "git_url", "html_url", "download_url", "name", "path", "sha", "size", "type", "url", "content", "encoding" ] }, "content-directory": { "title": "Content Directory", "description": "A list of directory items", "type": "array", "items": { "type": "object", "properties": { "type": { "type": "string" }, "size": { "type": "integer" }, "name": { "type": "string" }, "path": { "type": "string" }, "content": { "type": "string" }, "sha": { "type": "string" }, "url": { "type": "string", "format": "uri" }, "git_url": { "type": [ "string", "null" ], "format": "uri" }, "html_url": { "type": [ "string", "null" ], "format": "uri" }, "download_url": { "type": [ "string", "null" ], "format": "uri" }, "_links": { "type": "object", "properties": { "git": { "type": [ "string", "null" ], "format": "uri" }, "html": { "type": [ "string", "null" ], "format": "uri" }, "self": { "type": "string", "format": "uri" } }, "required": [ "git", "html", "self" ] } }, "required": [ "_links", "git_url", "html_url", "download_url", "name", "path", "sha", "size", "type", "url" ] } }, "content-file": { "title": "Content File", "description": "Content File", "type": "object", "properties": { "type": { "type": "string" }, "encoding": { "type": "string" }, "size": { "type": "integer" }, "name": { "type": "string" }, "path": { "type": "string" }, "content": { "type": "string" }, "sha": { "type": "string" }, "url": { "type": "string", "format": "uri" }, "git_url": { "type": [ "string", "null" ], "format": "uri" }, "html_url": { "type": [ "string", "null" ], "format": "uri" }, "download_url": { "type": [ "string", "null" ], "format": "uri" }, "_links": { "type": "object", "properties": { "git": { "type": [ "string", "null" ], "format": "uri" }, "html": { "type": [ "string", "null" ], "format": "uri" }, "self": { "type": "string", "format": "uri" } }, "required": [ "git", "html", "self" ] }, "target": { "type": "string", "examples": [ "\"actual/actual.md\"" ] }, "submodule_git_url": { "type": "string", "examples": [ "\"git://example.com/defunkt/dotjs.git\"" ] } }, "required": [ "_links", "git_url", "html_url", "download_url", "name", "path", "sha", "size", "type", "url", "content", "encoding" ] }, "content-symlink": { "title": "Symlink Content", "description": "An object describing a symlink", "type": "object", "properties": { "type": { "type": "string" }, "target": { "type": "string" }, "size": { "type": "integer" }, "name": { "type": "string" }, "path": { "type": "string" }, "sha": { "type": "string" }, "url": { "type": "string", "format": "uri" }, "git_url": { "type": [ "string", "null" ], "format": "uri" }, "html_url": { "type": [ "string", "null" ], "format": "uri" }, "download_url": { "type": [ "string", "null" ], "format": "uri" }, "_links": { "type": "object", "properties": { "git": { "type": [ "string", "null" ], "format": "uri" }, "html": { "type": [ "string", "null" ], "format": "uri" }, "self": { "type": "string", "format": "uri" } }, "required": [ "git", "html", "self" ] } }, "required": [ "_links", "git_url", "html_url", "download_url", "name", "path", "sha", "size", "type", "url", "target" ] }, "content-submodule": { "title": "Symlink Content", "description": "An object describing a symlink", "type": "object", "properties": { "type": { "type": "string" }, "submodule_git_url": { "type": "string", "format": "uri" }, "size": { "type": "integer" }, "name": { "type": "string" }, "path": { "type": "string" }, "sha": { "type": "string" }, "url": { "type": "string", "format": "uri" }, "git_url": { "type": [ "string", "null" ], "format": "uri" }, "html_url": { "type": [ "string", "null" ], "format": "uri" }, "download_url": { "type": [ "string", "null" ], "format": "uri" }, "_links": { "type": "object", "properties": { "git": { "type": [ "string", "null" ], "format": "uri" }, "html": { "type": [ "string", "null" ], "format": "uri" }, "self": { "type": "string", "format": "uri" } }, "required": [ "git", "html", "self" ] } }, "required": [ "_links", "git_url", "html_url", "download_url", "name", "path", "sha", "size", "type", "url", "submodule_git_url" ] }, "file-commit": { "title": "File Commit", "description": "File Commit", "type": "object", "required": [ "content", "commit" ], "properties": { "content": { "type": [ "object", "null" ], "properties": { "name": { "type": "string" }, "path": { "type": "string" }, "sha": { "type": "string" }, "size": { "type": "integer" }, "url": { "type": "string" }, "html_url": { "type": "string" }, "git_url": { "type": "string" }, "download_url": { "type": "string" }, "type": { "type": "string" }, "_links": { "type": "object", "properties": { "self": { "type": "string" }, "git": { "type": "string" }, "html": { "type": "string" } } } } }, "commit": { "type": "object", "properties": { "sha": { "type": "string" }, "node_id": { "type": "string" }, "url": { "type": "string" }, "html_url": { "type": "string" }, "author": { "type": "object", "properties": { "date": { "type": "string" }, "name": { "type": "string" }, "email": { "type": "string" } } }, "committer": { "type": "object", "properties": { "date": { "type": "string" }, "name": { "type": "string" }, "email": { "type": "string" } } }, "message": { "type": "string" }, "tree": { "type": "object", "properties": { "url": { "type": "string" }, "sha": { "type": "string" } } }, "parents": { "type": "array", "items": { "type": "object", "properties": { "url": { "type": "string" }, "html_url": { "type": "string" }, "sha": { "type": "string" } } } }, "verification": { "type": "object", "properties": { "verified": { "type": "boolean" }, "reason": { "type": "string" }, "signature": { "type": [ "string", "null" ] }, "payload": { "type": [ "string", "null" ] } } } } } } }, "contributor": { "title": "Contributor", "description": "Contributor", "type": "object", "properties": { "login": { "type": "string" }, "id": { "type": "integer" }, "node_id": { "type": "string" }, "avatar_url": { "type": "string", "format": "uri" }, "gravatar_id": { "type": [ "string", "null" ] }, "url": { "type": "string", "format": "uri" }, "html_url": { "type": "string", "format": "uri" }, "followers_url": { "type": "string", "format": "uri" }, "following_url": { "type": "string" }, "gists_url": { "type": "string" }, "starred_url": { "type": "string" }, "subscriptions_url": { "type": "string", "format": "uri" }, "organizations_url": { "type": "string", "format": "uri" }, "repos_url": { "type": "string", "format": "uri" }, "events_url": { "type": "string" }, "received_events_url": { "type": "string", "format": "uri" }, "type": { "type": "string" }, "site_admin": { "type": "boolean" }, "contributions": { "type": "integer" }, "email": { "type": "string" }, "name": { "type": "string" } }, "required": [ "contributions", "type" ] }, "deployment": { "title": "Deployment", "description": "A request for a specific ref(branch,sha,tag) to be deployed", "type": "object", "properties": { "url": { "type": "string", "format": "uri", "examples": [ "https://api.github.com/repos/octocat/example/deployments/1" ] }, "id": { "description": "Unique identifier of the deployment", "type": "integer", "examples": [ 42 ] }, "node_id": { "type": "string", "examples": [ "MDEwOkRlcGxveW1lbnQx" ] }, "sha": { "type": "string", "examples": [ "a84d88e7554fc1fa21bcbc4efae3c782a70d2b9d" ] }, "ref": { "description": "The ref to deploy. This can be a branch, tag, or sha.", "type": "string", "examples": [ "topic-branch" ] }, "task": { "description": "Parameter to specify a task to execute", "type": "string", "examples": [ "deploy" ] }, "payload": { "oneOf": [ { "type": "object", "additionalProperties": true }, { "type": "string" } ] }, "original_environment": { "type": "string", "examples": [ "staging" ] }, "environment": { "description": "Name for the target deployment environment.", "type": "string", "examples": [ "production" ] }, "description": { "type": [ "string", "null" ], "examples": [ "Deploy request from hubot" ] }, "creator": { "anyOf": [ { "type": "null" }, { "$ref": "#/components/schemas/simple-user" } ] }, "created_at": { "type": "string", "format": "date-time", "examples": [ "2012-07-20T01:19:13Z" ] }, "updated_at": { "type": "string", "format": "date-time", "examples": [ "2012-07-20T01:19:13Z" ] }, "statuses_url": { "type": "string", "format": "uri", "examples": [ "https://api.github.com/repos/octocat/example/deployments/1/statuses" ] }, "repository_url": { "type": "string", "format": "uri", "examples": [ "https://api.github.com/repos/octocat/example" ] }, "transient_environment": { "description": "Specifies if the given environment is will no longer exist at some point in the future. Default: false.", "type": "boolean", "examples": [ true ] }, "production_environment": { "description": "Specifies if the given environment is one that end-users directly interact with. Default: false.", "type": "boolean", "examples": [ true ] }, "performed_via_github_app": { "anyOf": [ { "type": "null" }, { "$ref": "#/components/schemas/integration" } ] } }, "required": [ "id", "node_id", "sha", "ref", "task", "environment", "creator", "payload", "description", "statuses_url", "repository_url", "url", "created_at", "updated_at" ] }, "deployment-status": { "title": "Deployment Status", "description": "The status of a deployment.", "type": "object", "properties": { "url": { "type": "string", "format": "uri", "examples": [ "https://api.github.com/repos/octocat/example/deployments/42/statuses/1" ] }, "id": { "type": "integer", "examples": [ 1 ] }, "node_id": { "type": "string", "examples": [ "MDE2OkRlcGxveW1lbnRTdGF0dXMx" ] }, "state": { "description": "The state of the status.", "enum": [ "error", "failure", "inactive", "pending", "success", "queued", "in_progress" ], "type": "string", "examples": [ "success" ] }, "creator": { "anyOf": [ { "type": "null" }, { "$ref": "#/components/schemas/simple-user" } ] }, "description": { "description": "A short description of the status.", "default": "", "type": "string", "maxLength": 140, "examples": [ "Deployment finished successfully." ] }, "environment": { "description": "The environment of the deployment that the status is for.", "default": "", "type": "string", "examples": [ "production" ] }, "target_url": { "description": "Deprecated: the URL to associate with this status.", "default": "", "type": "string", "format": "uri", "examples": [ "https://example.com/deployment/42/output" ] }, "created_at": { "type": "string", "format": "date-time", "examples": [ "2012-07-20T01:19:13Z" ] }, "updated_at": { "type": "string", "format": "date-time", "examples": [ "2012-07-20T01:19:13Z" ] }, "deployment_url": { "type": "string", "format": "uri", "examples": [ "https://api.github.com/repos/octocat/example/deployments/42" ] }, "repository_url": { "type": "string", "format": "uri", "examples": [ "https://api.github.com/repos/octocat/example" ] }, "environment_url": { "description": "The URL for accessing your environment.", "default": "", "type": "string", "format": "uri", "examples": [ "https://staging.example.com/" ] }, "log_url": { "description": "The URL to associate with this status.", "default": "", "type": "string", "format": "uri", "examples": [ "https://example.com/deployment/42/output" ] }, "performed_via_github_app": { "anyOf": [ { "type": "null" }, { "$ref": "#/components/schemas/integration" } ] } }, "required": [ "id", "node_id", "state", "creator", "description", "deployment_url", "target_url", "repository_url", "url", "created_at", "updated_at" ] }, "short-blob": { "title": "Short Blob", "description": "Short Blob", "type": "object", "properties": { "url": { "type": "string" }, "sha": { "type": "string" } }, "required": [ "url", "sha" ] }, "blob": { "title": "Blob", "description": "Blob", "type": "object", "properties": { "content": { "type": "string" }, "encoding": { "type": "string" }, "url": { "type": "string", "format": "uri" }, "sha": { "type": "string" }, "size": { "type": [ "integer", "null" ] }, "node_id": { "type": "string" }, "highlighted_content": { "type": "string" } }, "required": [ "sha", "url", "node_id", "size", "content", "encoding" ] }, "git-commit": { "title": "Git Commit", "description": "Low-level Git commit operations within a repository", "type": "object", "properties": { "sha": { "description": "SHA for the commit", "type": "string", "examples": [ "7638417db6d59f3c431d3e1f261cc637155684cd" ] }, "node_id": { "type": "string" }, "url": { "type": "string", "format": "uri" }, "author": { "description": "Identifying information for the git-user", "type": "object", "properties": { "date": { "description": "Timestamp of the commit", "format": "date-time", "type": "string", "examples": [ "2014-08-09T08:02:04+12:00" ] }, "email": { "type": "string", "description": "Git email address of the user", "examples": [ "monalisa.octocat@example.com" ] }, "name": { "description": "Name of the git user", "type": "string", "examples": [ "Monalisa Octocat" ] } }, "required": [ "email", "name", "date" ] }, "committer": { "description": "Identifying information for the git-user", "type": "object", "properties": { "date": { "description": "Timestamp of the commit", "format": "date-time", "type": "string", "examples": [ "2014-08-09T08:02:04+12:00" ] }, "email": { "type": "string", "description": "Git email address of the user", "examples": [ "monalisa.octocat@example.com" ] }, "name": { "description": "Name of the git user", "type": "string", "examples": [ "Monalisa Octocat" ] } }, "required": [ "email", "name", "date" ] }, "message": { "description": "Message describing the purpose of the commit", "type": "string", "examples": [ "Fix #42" ] }, "tree": { "type": "object", "properties": { "sha": { "description": "SHA for the commit", "type": "string", "examples": [ "7638417db6d59f3c431d3e1f261cc637155684cd" ] }, "url": { "type": "string", "format": "uri" } }, "required": [ "sha", "url" ] }, "parents": { "type": "array", "items": { "type": "object", "properties": { "sha": { "description": "SHA for the commit", "type": "string", "examples": [ "7638417db6d59f3c431d3e1f261cc637155684cd" ] }, "url": { "type": "string", "format": "uri" }, "html_url": { "type": "string", "format": "uri" } }, "required": [ "sha", "url", "html_url" ] } }, "verification": { "type": "object", "properties": { "verified": { "type": "boolean" }, "reason": { "type": "string" }, "signature": { "type": [ "string", "null" ] }, "payload": { "type": [ "string", "null" ] } }, "required": [ "verified", "reason", "signature", "payload" ] }, "html_url": { "type": "string", "format": "uri" } }, "required": [ "sha", "node_id", "url", "html_url", "author", "committer", "tree", "message", "parents", "verification" ] }, "git-ref": { "title": "Git Reference", "description": "Git references within a repository", "type": "object", "properties": { "ref": { "type": "string" }, "node_id": { "type": "string" }, "url": { "type": "string", "format": "uri" }, "object": { "type": "object", "properties": { "type": { "type": "string" }, "sha": { "description": "SHA for the reference", "type": "string", "minLength": 40, "maxLength": 40, "examples": [ "7638417db6d59f3c431d3e1f261cc637155684cd" ] }, "url": { "type": "string", "format": "uri" } }, "required": [ "type", "sha", "url" ] } }, "required": [ "ref", "node_id", "url", "object" ] }, "git-tag": { "title": "Git Tag", "description": "Metadata for a Git tag", "type": "object", "properties": { "node_id": { "type": "string", "examples": [ "MDM6VGFnOTQwYmQzMzYyNDhlZmFlMGY5ZWU1YmM3YjJkNWM5ODU4ODdiMTZhYw==" ] }, "tag": { "description": "Name of the tag", "type": "string", "examples": [ "v0.0.1" ] }, "sha": { "type": "string", "examples": [ "940bd336248efae0f9ee5bc7b2d5c985887b16ac" ] }, "url": { "description": "URL for the tag", "type": "string", "format": "uri", "examples": [ "https://api.github.com/repositories/42/git/tags/940bd336248efae0f9ee5bc7b2d5c985887b16ac" ] }, "message": { "description": "Message describing the purpose of the tag", "type": "string", "examples": [ "Initial public release" ] }, "tagger": { "type": "object", "properties": { "date": { "type": "string" }, "email": { "type": "string" }, "name": { "type": "string" } }, "required": [ "date", "email", "name" ] }, "object": { "type": "object", "properties": { "sha": { "type": "string" }, "type": { "type": "string" }, "url": { "type": "string", "format": "uri" } }, "required": [ "sha", "type", "url" ] }, "verification": { "$ref": "#/components/schemas/verification" } }, "required": [ "sha", "url", "node_id", "tagger", "object", "tag", "message" ] }, "git-tree": { "title": "Git Tree", "description": "The hierarchy between files in a Git repository.", "type": "object", "properties": { "sha": { "type": "string" }, "url": { "type": "string", "format": "uri" }, "truncated": { "type": "boolean" }, "tree": { "description": "Objects specifying a tree structure", "type": "array", "items": { "type": "object", "properties": { "path": { "type": "string", "examples": [ "test/file.rb" ] }, "mode": { "type": "string", "examples": [ "040000" ] }, "type": { "type": "string", "examples": [ "tree" ] }, "sha": { "type": "string", "examples": [ "23f6827669e43831def8a7ad935069c8bd418261" ] }, "size": { "type": "integer", "examples": [ 12 ] }, "url": { "type": "string", "examples": [ "https://api.github.com/repos/owner-482f3203ecf01f67e9deb18e/BBB_Private_Repo/git/blobs/23f6827669e43831def8a7ad935069c8bd418261" ] } } }, "examples": [ { "path": "file.rb", "mode": "100644", "type": "blob", "size": 30, "sha": "44b4fc6d56897b048c772eb4087f854f46256132", "url": "https://api.github.com/repos/octocat/Hello-World/git/blobs/44b4fc6d56897b048c772eb4087f854f46256132", "properties": { "path": { "type": "string" }, "mode": { "type": "string" }, "type": { "type": "string" }, "size": { "type": "integer" }, "sha": { "type": "string" }, "url": { "type": "string" } }, "required": [ "path", "mode", "type", "sha", "url", "size" ] } ] } }, "required": [ "sha", "url", "tree", "truncated" ] }, "hook-response": { "title": "Hook Response", "type": "object", "properties": { "code": { "type": [ "integer", "null" ] }, "status": { "type": [ "string", "null" ] }, "message": { "type": [ "string", "null" ] } }, "required": [ "code", "status", "message" ] }, "hook": { "title": "Webhook", "description": "Webhooks for repositories.", "type": "object", "properties": { "type": { "type": "string" }, "id": { "description": "Unique identifier of the webhook.", "type": "integer", "examples": [ 42 ] }, "name": { "description": "The name of a valid service, use 'web' for a webhook.", "type": "string", "examples": [ "web" ] }, "active": { "description": "Determines whether the hook is actually triggered on pushes.", "type": "boolean", "examples": [ true ] }, "events": { "description": "Determines what events the hook is triggered for. Default: ['push'].", "type": "array", "items": { "type": "string" }, "examples": [ "push", "pull_request" ] }, "config": { "type": "object", "properties": { "email": { "type": "string", "examples": [ "\"foo@bar.com\"" ] }, "password": { "type": "string", "examples": [ "\"foo\"" ] }, "room": { "type": "string", "examples": [ "\"roomer\"" ] }, "subdomain": { "type": "string", "examples": [ "\"foo\"" ] }, "url": { "$ref": "#/components/schemas/webhook-config-url" }, "insecure_ssl": { "$ref": "#/components/schemas/webhook-config-insecure-ssl" }, "content_type": { "$ref": "#/components/schemas/webhook-config-content-type" }, "digest": { "type": "string", "examples": [ "\"sha256\"" ] }, "secret": { "$ref": "#/components/schemas/webhook-config-secret" }, "token": { "type": "string", "examples": [ "\"abc\"" ] } } }, "updated_at": { "type": "string", "format": "date-time", "examples": [ "2011-09-06T20:39:23Z" ] }, "created_at": { "type": "string", "format": "date-time", "examples": [ "2011-09-06T17:26:27Z" ] }, "url": { "type": "string", "format": "uri", "examples": [ "https://api.github.com/repos/octocat/Hello-World/hooks/1" ] }, "test_url": { "type": "string", "format": "uri", "examples": [ "https://api.github.com/repos/octocat/Hello-World/hooks/1/test" ] }, "ping_url": { "type": "string", "format": "uri", "examples": [ "https://api.github.com/repos/octocat/Hello-World/hooks/1/pings" ] }, "last_response": { "$ref": "#/components/schemas/hook-response" } }, "required": [ "id", "url", "type", "name", "active", "events", "config", "ping_url", "created_at", "updated_at", "last_response", "test_url" ] }, "issue-event-label": { "title": "Issue Event Label", "description": "Issue Event Label", "type": "object", "properties": { "name": { "type": [ "string", "null" ] }, "color": { "type": [ "string", "null" ] } }, "required": [ "name", "color" ] }, "issue-event-dismissed-review": { "title": "Issue Event Dismissed Review", "type": "object", "properties": { "state": { "type": "string" }, "review_id": { "type": "integer" }, "dismissal_message": { "type": [ "string", "null" ] }, "dismissal_commit_id": { "type": [ "string", "null" ] } }, "required": [ "state", "review_id", "dismissal_message" ] }, "issue-event-milestone": { "title": "Issue Event Milestone", "description": "Issue Event Milestone", "type": "object", "properties": { "title": { "type": "string" } }, "required": [ "title" ] }, "issue-event-project-card": { "title": "Issue Event Project Card", "description": "Issue Event Project Card", "type": "object", "properties": { "url": { "type": "string", "format": "uri" }, "id": { "type": "integer" }, "project_url": { "type": "string", "format": "uri" }, "project_id": { "type": "integer" }, "column_name": { "type": "string" }, "previous_column_name": { "type": "string" } }, "required": [ "url", "id", "project_url", "project_id", "column_name" ] }, "issue-event-rename": { "title": "Issue Event Rename", "description": "Issue Event Rename", "type": "object", "properties": { "from": { "type": "string" }, "to": { "type": "string" } }, "required": [ "from", "to" ] }, "issue-event": { "title": "Issue Event", "description": "Issue Event", "type": "object", "properties": { "id": { "type": "integer", "examples": [ 1 ] }, "node_id": { "type": "string", "examples": [ "MDEwOklzc3VlRXZlbnQx" ] }, "url": { "type": "string", "format": "uri", "examples": [ "https://api.github.com/repos/octocat/Hello-World/issues/events/1" ] }, "actor": { "anyOf": [ { "type": "null" }, { "$ref": "#/components/schemas/simple-user" } ] }, "event": { "type": "string", "examples": [ "closed" ] }, "commit_id": { "type": [ "string", "null" ], "examples": [ "6dcb09b5b57875f334f61aebed695e2e4193db5e" ] }, "commit_url": { "type": [ "string", "null" ], "examples": [ "https://api.github.com/repos/octocat/Hello-World/commits/6dcb09b5b57875f334f61aebed695e2e4193db5e" ] }, "created_at": { "type": "string", "format": "date-time", "examples": [ "2011-04-14T16:00:49Z" ] }, "issue": { "anyOf": [ { "type": "null" }, { "$ref": "#/components/schemas/issue" } ] }, "label": { "$ref": "#/components/schemas/issue-event-label" }, "assignee": { "anyOf": [ { "type": "null" }, { "$ref": "#/components/schemas/simple-user" } ] }, "assigner": { "anyOf": [ { "type": "null" }, { "$ref": "#/components/schemas/simple-user" } ] }, "review_requester": { "anyOf": [ { "type": "null" }, { "$ref": "#/components/schemas/simple-user" } ] }, "requested_reviewer": { "anyOf": [ { "type": "null" }, { "$ref": "#/components/schemas/simple-user" } ] }, "requested_team": { "$ref": "#/components/schemas/team" }, "dismissed_review": { "$ref": "#/components/schemas/issue-event-dismissed-review" }, "milestone": { "$ref": "#/components/schemas/issue-event-milestone" }, "project_card": { "$ref": "#/components/schemas/issue-event-project-card" }, "rename": { "$ref": "#/components/schemas/issue-event-rename" }, "author_association": { "$ref": "#/components/schemas/author_association" }, "lock_reason": { "type": [ "string", "null" ] }, "performed_via_github_app": { "anyOf": [ { "type": "null" }, { "$ref": "#/components/schemas/integration" } ] } }, "required": [ "id", "node_id", "url", "actor", "event", "commit_id", "commit_url", "created_at" ] }, "labeled-issue-event": { "title": "Labeled Issue Event", "description": "Labeled Issue Event", "type": "object", "properties": { "id": { "type": "integer" }, "node_id": { "type": "string" }, "url": { "type": "string" }, "actor": { "$ref": "#/components/schemas/simple-user" }, "event": { "type": "string" }, "commit_id": { "type": [ "string", "null" ] }, "commit_url": { "type": [ "string", "null" ] }, "created_at": { "type": "string" }, "performed_via_github_app": { "anyOf": [ { "type": "null" }, { "$ref": "#/components/schemas/integration" } ] }, "label": { "type": "object", "properties": { "name": { "type": "string" }, "color": { "type": "string" } }, "required": [ "name", "color" ] } }, "required": [ "label", "id", "node_id", "url", "actor", "event", "commit_id", "commit_url", "created_at", "performed_via_github_app" ] }, "unlabeled-issue-event": { "title": "Unlabeled Issue Event", "description": "Unlabeled Issue Event", "type": "object", "properties": { "id": { "type": "integer" }, "node_id": { "type": "string" }, "url": { "type": "string" }, "actor": { "$ref": "#/components/schemas/simple-user" }, "event": { "type": "string" }, "commit_id": { "type": [ "string", "null" ] }, "commit_url": { "type": [ "string", "null" ] }, "created_at": { "type": "string" }, "performed_via_github_app": { "anyOf": [ { "type": "null" }, { "$ref": "#/components/schemas/integration" } ] }, "label": { "type": "object", "properties": { "name": { "type": "string" }, "color": { "type": "string" } }, "required": [ "name", "color" ] } }, "required": [ "label", "id", "node_id", "url", "actor", "event", "commit_id", "commit_url", "created_at", "performed_via_github_app" ] }, "assigned-issue-event": { "title": "Assigned Issue Event", "description": "Assigned Issue Event", "type": "object", "properties": { "id": { "type": "integer" }, "node_id": { "type": "string" }, "url": { "type": "string" }, "actor": { "$ref": "#/components/schemas/simple-user" }, "event": { "type": "string" }, "commit_id": { "type": [ "string", "null" ] }, "commit_url": { "type": [ "string", "null" ] }, "created_at": { "type": "string" }, "performed_via_github_app": { "$ref": "#/components/schemas/integration" }, "assignee": { "$ref": "#/components/schemas/simple-user" }, "assigner": { "$ref": "#/components/schemas/simple-user" } }, "required": [ "id", "node_id", "url", "actor", "event", "commit_id", "commit_url", "created_at", "performed_via_github_app", "assignee", "assigner" ] }, "unassigned-issue-event": { "title": "Unassigned Issue Event", "description": "Unassigned Issue Event", "type": "object", "properties": { "id": { "type": "integer" }, "node_id": { "type": "string" }, "url": { "type": "string" }, "actor": { "$ref": "#/components/schemas/simple-user" }, "event": { "type": "string" }, "commit_id": { "type": [ "string", "null" ] }, "commit_url": { "type": [ "string", "null" ] }, "created_at": { "type": "string" }, "performed_via_github_app": { "anyOf": [ { "type": "null" }, { "$ref": "#/components/schemas/integration" } ] }, "assignee": { "$ref": "#/components/schemas/simple-user" }, "assigner": { "$ref": "#/components/schemas/simple-user" } }, "required": [ "id", "node_id", "url", "actor", "event", "commit_id", "commit_url", "created_at", "performed_via_github_app", "assignee", "assigner" ] }, "milestoned-issue-event": { "title": "Milestoned Issue Event", "description": "Milestoned Issue Event", "type": "object", "properties": { "id": { "type": "integer" }, "node_id": { "type": "string" }, "url": { "type": "string" }, "actor": { "$ref": "#/components/schemas/simple-user" }, "event": { "type": "string" }, "commit_id": { "type": [ "string", "null" ] }, "commit_url": { "type": [ "string", "null" ] }, "created_at": { "type": "string" }, "performed_via_github_app": { "anyOf": [ { "type": "null" }, { "$ref": "#/components/schemas/integration" } ] }, "milestone": { "type": "object", "properties": { "title": { "type": "string" } }, "required": [ "title" ] } }, "required": [ "milestone", "id", "node_id", "url", "actor", "event", "commit_id", "commit_url", "created_at", "performed_via_github_app" ] }, "demilestoned-issue-event": { "title": "Demilestoned Issue Event", "description": "Demilestoned Issue Event", "type": "object", "properties": { "id": { "type": "integer" }, "node_id": { "type": "string" }, "url": { "type": "string" }, "actor": { "$ref": "#/components/schemas/simple-user" }, "event": { "type": "string" }, "commit_id": { "type": [ "string", "null" ] }, "commit_url": { "type": [ "string", "null" ] }, "created_at": { "type": "string" }, "performed_via_github_app": { "anyOf": [ { "type": "null" }, { "$ref": "#/components/schemas/integration" } ] }, "milestone": { "type": "object", "properties": { "title": { "type": "string" } }, "required": [ "title" ] } }, "required": [ "milestone", "id", "node_id", "url", "actor", "event", "commit_id", "commit_url", "created_at", "performed_via_github_app" ] }, "renamed-issue-event": { "title": "Renamed Issue Event", "description": "Renamed Issue Event", "type": "object", "properties": { "id": { "type": "integer" }, "node_id": { "type": "string" }, "url": { "type": "string" }, "actor": { "$ref": "#/components/schemas/simple-user" }, "event": { "type": "string" }, "commit_id": { "type": [ "string", "null" ] }, "commit_url": { "type": [ "string", "null" ] }, "created_at": { "type": "string" }, "performed_via_github_app": { "anyOf": [ { "type": "null" }, { "$ref": "#/components/schemas/integration" } ] }, "rename": { "type": "object", "properties": { "from": { "type": "string" }, "to": { "type": "string" } }, "required": [ "from", "to" ] } }, "required": [ "rename", "id", "node_id", "url", "actor", "event", "commit_id", "commit_url", "created_at", "performed_via_github_app" ] }, "review-requested-issue-event": { "title": "Review Requested Issue Event", "description": "Review Requested Issue Event", "type": "object", "properties": { "id": { "type": "integer" }, "node_id": { "type": "string" }, "url": { "type": "string" }, "actor": { "$ref": "#/components/schemas/simple-user" }, "event": { "type": "string" }, "commit_id": { "type": [ "string", "null" ] }, "commit_url": { "type": [ "string", "null" ] }, "created_at": { "type": "string" }, "performed_via_github_app": { "anyOf": [ { "type": "null" }, { "$ref": "#/components/schemas/integration" } ] }, "review_requester": { "$ref": "#/components/schemas/simple-user" }, "requested_team": { "$ref": "#/components/schemas/team" }, "requested_reviewer": { "$ref": "#/components/schemas/simple-user" } }, "required": [ "review_requester", "id", "node_id", "url", "actor", "event", "commit_id", "commit_url", "created_at", "performed_via_github_app" ] }, "review-request-removed-issue-event": { "title": "Review Request Removed Issue Event", "description": "Review Request Removed Issue Event", "type": "object", "properties": { "id": { "type": "integer" }, "node_id": { "type": "string" }, "url": { "type": "string" }, "actor": { "$ref": "#/components/schemas/simple-user" }, "event": { "type": "string" }, "commit_id": { "type": [ "string", "null" ] }, "commit_url": { "type": [ "string", "null" ] }, "created_at": { "type": "string" }, "performed_via_github_app": { "anyOf": [ { "type": "null" }, { "$ref": "#/components/schemas/integration" } ] }, "review_requester": { "$ref": "#/components/schemas/simple-user" }, "requested_team": { "$ref": "#/components/schemas/team" }, "requested_reviewer": { "$ref": "#/components/schemas/simple-user" } }, "required": [ "review_requester", "id", "node_id", "url", "actor", "event", "commit_id", "commit_url", "created_at", "performed_via_github_app" ] }, "review-dismissed-issue-event": { "title": "Review Dismissed Issue Event", "description": "Review Dismissed Issue Event", "type": "object", "properties": { "id": { "type": "integer" }, "node_id": { "type": "string" }, "url": { "type": "string" }, "actor": { "$ref": "#/components/schemas/simple-user" }, "event": { "type": "string" }, "commit_id": { "type": [ "string", "null" ] }, "commit_url": { "type": [ "string", "null" ] }, "created_at": { "type": "string" }, "performed_via_github_app": { "anyOf": [ { "type": "null" }, { "$ref": "#/components/schemas/integration" } ] }, "dismissed_review": { "type": "object", "properties": { "state": { "type": "string" }, "review_id": { "type": "integer" }, "dismissal_message": { "type": [ "string", "null" ] }, "dismissal_commit_id": { "type": "string" } }, "required": [ "state", "review_id", "dismissal_message" ] } }, "required": [ "dismissed_review", "id", "node_id", "url", "actor", "event", "commit_id", "commit_url", "created_at", "performed_via_github_app" ] }, "locked-issue-event": { "title": "Locked Issue Event", "description": "Locked Issue Event", "type": "object", "properties": { "id": { "type": "integer" }, "node_id": { "type": "string" }, "url": { "type": "string" }, "actor": { "$ref": "#/components/schemas/simple-user" }, "event": { "type": "string" }, "commit_id": { "type": [ "string", "null" ] }, "commit_url": { "type": [ "string", "null" ] }, "created_at": { "type": "string" }, "performed_via_github_app": { "anyOf": [ { "type": "null" }, { "$ref": "#/components/schemas/integration" } ] }, "lock_reason": { "type": [ "string", "null" ], "examples": [ "\"off-topic\"" ] } }, "required": [ "lock_reason", "id", "node_id", "url", "actor", "event", "commit_id", "commit_url", "created_at", "performed_via_github_app" ] }, "added-to-project-issue-event": { "title": "Added to Project Issue Event", "description": "Added to Project Issue Event", "type": "object", "properties": { "id": { "type": "integer" }, "node_id": { "type": "string" }, "url": { "type": "string" }, "actor": { "$ref": "#/components/schemas/simple-user" }, "event": { "type": "string" }, "commit_id": { "type": [ "string", "null" ] }, "commit_url": { "type": [ "string", "null" ] }, "created_at": { "type": "string" }, "performed_via_github_app": { "anyOf": [ { "type": "null" }, { "$ref": "#/components/schemas/integration" } ] }, "project_card": { "type": "object", "properties": { "id": { "type": "integer" }, "url": { "type": "string", "format": "uri" }, "project_id": { "type": "integer" }, "project_url": { "type": "string", "format": "uri" }, "column_name": { "type": "string" }, "previous_column_name": { "type": "string" } }, "required": [ "id", "url", "project_id", "project_url", "column_name" ] } }, "required": [ "id", "node_id", "url", "actor", "event", "commit_id", "commit_url", "created_at", "performed_via_github_app" ] }, "moved-column-in-project-issue-event": { "title": "Moved Column in Project Issue Event", "description": "Moved Column in Project Issue Event", "type": "object", "properties": { "id": { "type": "integer" }, "node_id": { "type": "string" }, "url": { "type": "string" }, "actor": { "$ref": "#/components/schemas/simple-user" }, "event": { "type": "string" }, "commit_id": { "type": [ "string", "null" ] }, "commit_url": { "type": [ "string", "null" ] }, "created_at": { "type": "string" }, "performed_via_github_app": { "anyOf": [ { "type": "null" }, { "$ref": "#/components/schemas/integration" } ] }, "project_card": { "type": "object", "properties": { "id": { "type": "integer" }, "url": { "type": "string", "format": "uri" }, "project_id": { "type": "integer" }, "project_url": { "type": "string", "format": "uri" }, "column_name": { "type": "string" }, "previous_column_name": { "type": "string" } }, "required": [ "id", "url", "project_id", "project_url", "column_name" ] } }, "required": [ "id", "node_id", "url", "actor", "event", "commit_id", "commit_url", "created_at", "performed_via_github_app" ] }, "removed-from-project-issue-event": { "title": "Removed from Project Issue Event", "description": "Removed from Project Issue Event", "type": "object", "properties": { "id": { "type": "integer" }, "node_id": { "type": "string" }, "url": { "type": "string" }, "actor": { "$ref": "#/components/schemas/simple-user" }, "event": { "type": "string" }, "commit_id": { "type": [ "string", "null" ] }, "commit_url": { "type": [ "string", "null" ] }, "created_at": { "type": "string" }, "performed_via_github_app": { "anyOf": [ { "type": "null" }, { "$ref": "#/components/schemas/integration" } ] }, "project_card": { "type": "object", "properties": { "id": { "type": "integer" }, "url": { "type": "string", "format": "uri" }, "project_id": { "type": "integer" }, "project_url": { "type": "string", "format": "uri" }, "column_name": { "type": "string" }, "previous_column_name": { "type": "string" } }, "required": [ "id", "url", "project_id", "project_url", "column_name" ] } }, "required": [ "id", "node_id", "url", "actor", "event", "commit_id", "commit_url", "created_at", "performed_via_github_app" ] }, "converted-note-to-issue-issue-event": { "title": "Converted Note to Issue Issue Event", "description": "Converted Note to Issue Issue Event", "type": "object", "properties": { "id": { "type": "integer" }, "node_id": { "type": "string" }, "url": { "type": "string" }, "actor": { "$ref": "#/components/schemas/simple-user" }, "event": { "type": "string" }, "commit_id": { "type": [ "string", "null" ] }, "commit_url": { "type": [ "string", "null" ] }, "created_at": { "type": "string" }, "performed_via_github_app": { "$ref": "#/components/schemas/integration" }, "project_card": { "type": "object", "properties": { "id": { "type": "integer" }, "url": { "type": "string", "format": "uri" }, "project_id": { "type": "integer" }, "project_url": { "type": "string", "format": "uri" }, "column_name": { "type": "string" }, "previous_column_name": { "type": "string" } }, "required": [ "id", "url", "project_id", "project_url", "column_name" ] } }, "required": [ "id", "node_id", "url", "actor", "event", "commit_id", "commit_url", "created_at", "performed_via_github_app" ] }, "issue-event-for-issue": { "title": "Issue Event for Issue", "description": "Issue Event for Issue", "anyOf": [ { "$ref": "#/components/schemas/labeled-issue-event" }, { "$ref": "#/components/schemas/unlabeled-issue-event" }, { "$ref": "#/components/schemas/assigned-issue-event" }, { "$ref": "#/components/schemas/unassigned-issue-event" }, { "$ref": "#/components/schemas/milestoned-issue-event" }, { "$ref": "#/components/schemas/demilestoned-issue-event" }, { "$ref": "#/components/schemas/renamed-issue-event" }, { "$ref": "#/components/schemas/review-requested-issue-event" }, { "$ref": "#/components/schemas/review-request-removed-issue-event" }, { "$ref": "#/components/schemas/review-dismissed-issue-event" }, { "$ref": "#/components/schemas/locked-issue-event" }, { "$ref": "#/components/schemas/added-to-project-issue-event" }, { "$ref": "#/components/schemas/moved-column-in-project-issue-event" }, { "$ref": "#/components/schemas/removed-from-project-issue-event" }, { "$ref": "#/components/schemas/converted-note-to-issue-issue-event" } ] }, "label": { "title": "Label", "description": "Color-coded labels help you categorize and filter your issues (just like labels in Gmail).", "type": "object", "properties": { "id": { "type": "integer", "format": "int64", "examples": [ 208045946 ] }, "node_id": { "type": "string", "examples": [ "MDU6TGFiZWwyMDgwNDU5NDY=" ] }, "url": { "description": "URL for the label", "type": "string", "format": "uri", "examples": [ "https://api.github.com/repositories/42/labels/bug" ] }, "name": { "description": "The name of the label.", "type": "string", "examples": [ "bug" ] }, "description": { "type": [ "string", "null" ], "examples": [ "Something isn't working" ] }, "color": { "description": "6-character hex code, without the leading #, identifying the color", "type": "string", "examples": [ "FFFFFF" ] }, "default": { "type": "boolean", "examples": [ true ] } }, "required": [ "id", "node_id", "url", "name", "description", "color", "default" ] }, "timeline-comment-event": { "title": "Timeline Comment Event", "description": "Timeline Comment Event", "type": "object", "properties": { "event": { "type": "string" }, "actor": { "$ref": "#/components/schemas/simple-user" }, "id": { "description": "Unique identifier of the issue comment", "type": "integer", "examples": [ 42 ] }, "node_id": { "type": "string" }, "url": { "description": "URL for the issue comment", "type": "string", "format": "uri", "examples": [ "https://api.github.com/repositories/42/issues/comments/1" ] }, "body": { "description": "Contents of the issue comment", "type": "string", "examples": [ "What version of Safari were you using when you observed this bug?" ] }, "body_text": { "type": "string" }, "body_html": { "type": "string" }, "html_url": { "type": "string", "format": "uri" }, "user": { "$ref": "#/components/schemas/simple-user" }, "created_at": { "type": "string", "format": "date-time", "examples": [ "2011-04-14T16:00:49Z" ] }, "updated_at": { "type": "string", "format": "date-time", "examples": [ "2011-04-14T16:00:49Z" ] }, "issue_url": { "type": "string", "format": "uri" }, "author_association": { "$ref": "#/components/schemas/author_association" }, "performed_via_github_app": { "anyOf": [ { "type": "null" }, { "$ref": "#/components/schemas/integration" } ] }, "reactions": { "$ref": "#/components/schemas/reaction-rollup" } }, "required": [ "event", "actor", "id", "node_id", "html_url", "issue_url", "author_association", "user", "url", "created_at", "updated_at" ] }, "timeline-cross-referenced-event": { "title": "Timeline Cross Referenced Event", "description": "Timeline Cross Referenced Event", "type": "object", "properties": { "event": { "type": "string" }, "actor": { "$ref": "#/components/schemas/simple-user" }, "created_at": { "type": "string", "format": "date-time" }, "updated_at": { "type": "string", "format": "date-time" }, "source": { "type": "object", "properties": { "type": { "type": "string" }, "issue": { "$ref": "#/components/schemas/issue" } } } }, "required": [ "event", "created_at", "updated_at", "source" ] }, "timeline-committed-event": { "title": "Timeline Committed Event", "description": "Timeline Committed Event", "type": "object", "properties": { "event": { "type": "string" }, "sha": { "description": "SHA for the commit", "type": "string", "examples": [ "7638417db6d59f3c431d3e1f261cc637155684cd" ] }, "node_id": { "type": "string" }, "url": { "type": "string", "format": "uri" }, "author": { "description": "Identifying information for the git-user", "type": "object", "properties": { "date": { "description": "Timestamp of the commit", "format": "date-time", "type": "string", "examples": [ "2014-08-09T08:02:04+12:00" ] }, "email": { "type": "string", "description": "Git email address of the user", "examples": [ "monalisa.octocat@example.com" ] }, "name": { "description": "Name of the git user", "type": "string", "examples": [ "Monalisa Octocat" ] } }, "required": [ "email", "name", "date" ] }, "committer": { "description": "Identifying information for the git-user", "type": "object", "properties": { "date": { "description": "Timestamp of the commit", "format": "date-time", "type": "string", "examples": [ "2014-08-09T08:02:04+12:00" ] }, "email": { "type": "string", "description": "Git email address of the user", "examples": [ "monalisa.octocat@example.com" ] }, "name": { "description": "Name of the git user", "type": "string", "examples": [ "Monalisa Octocat" ] } }, "required": [ "email", "name", "date" ] }, "message": { "description": "Message describing the purpose of the commit", "type": "string", "examples": [ "Fix #42" ] }, "tree": { "type": "object", "properties": { "sha": { "description": "SHA for the commit", "type": "string", "examples": [ "7638417db6d59f3c431d3e1f261cc637155684cd" ] }, "url": { "type": "string", "format": "uri" } }, "required": [ "sha", "url" ] }, "parents": { "type": "array", "items": { "type": "object", "properties": { "sha": { "description": "SHA for the commit", "type": "string", "examples": [ "7638417db6d59f3c431d3e1f261cc637155684cd" ] }, "url": { "type": "string", "format": "uri" }, "html_url": { "type": "string", "format": "uri" } }, "required": [ "sha", "url", "html_url" ] } }, "verification": { "type": "object", "properties": { "verified": { "type": "boolean" }, "reason": { "type": "string" }, "signature": { "type": [ "string", "null" ] }, "payload": { "type": [ "string", "null" ] } }, "required": [ "verified", "reason", "signature", "payload" ] }, "html_url": { "type": "string", "format": "uri" } }, "required": [ "sha", "node_id", "url", "html_url", "author", "committer", "tree", "message", "parents", "verification" ] }, "timeline-reviewed-event": { "title": "Timeline Reviewed Event", "description": "Timeline Reviewed Event", "type": "object", "properties": { "event": { "type": "string" }, "id": { "description": "Unique identifier of the review", "type": "integer", "examples": [ 42 ] }, "node_id": { "type": "string", "examples": [ "MDE3OlB1bGxSZXF1ZXN0UmV2aWV3ODA=" ] }, "user": { "$ref": "#/components/schemas/simple-user" }, "body": { "description": "The text of the review.", "type": [ "string", "null" ], "examples": [ "This looks great." ] }, "state": { "type": "string", "examples": [ "CHANGES_REQUESTED" ] }, "html_url": { "type": "string", "format": "uri", "examples": [ "https://github.com/octocat/Hello-World/pull/12#pullrequestreview-80" ] }, "pull_request_url": { "type": "string", "format": "uri", "examples": [ "https://api.github.com/repos/octocat/Hello-World/pulls/12" ] }, "_links": { "type": "object", "properties": { "html": { "type": "object", "properties": { "href": { "type": "string" } }, "required": [ "href" ] }, "pull_request": { "type": "object", "properties": { "href": { "type": "string" } }, "required": [ "href" ] } }, "required": [ "html", "pull_request" ] }, "submitted_at": { "type": "string", "format": "date-time" }, "commit_id": { "description": "A commit SHA for the review.", "type": "string", "examples": [ "54bb654c9e6025347f57900a4a5c2313a96b8035" ] }, "body_html": { "type": "string" }, "body_text": { "type": "string" }, "author_association": { "$ref": "#/components/schemas/author_association" } }, "required": [ "event", "id", "node_id", "user", "body", "state", "commit_id", "html_url", "pull_request_url", "_links", "author_association" ] }, "pull-request-review-comment": { "title": "Pull Request Review Comment", "description": "Pull Request Review Comments are comments on a portion of the Pull Request's diff.", "type": "object", "properties": { "url": { "description": "URL for the pull request review comment", "type": "string", "examples": [ "https://api.github.com/repos/octocat/Hello-World/pulls/comments/1" ] }, "pull_request_review_id": { "description": "The ID of the pull request review to which the comment belongs.", "type": [ "integer", "null" ], "examples": [ 42 ] }, "id": { "description": "The ID of the pull request review comment.", "type": "integer", "examples": [ 1 ] }, "node_id": { "description": "The node ID of the pull request review comment.", "type": "string", "examples": [ "MDI0OlB1bGxSZXF1ZXN0UmV2aWV3Q29tbWVudDEw" ] }, "diff_hunk": { "description": "The diff of the line that the comment refers to.", "type": "string", "examples": [ "@@ -16,33 +16,40 @@ public class Connection : IConnection..." ] }, "path": { "description": "The relative path of the file to which the comment applies.", "type": "string", "examples": [ "config/database.yaml" ] }, "position": { "description": "The line index in the diff to which the comment applies.", "type": "integer", "examples": [ 1 ] }, "original_position": { "description": "The index of the original line in the diff to which the comment applies.", "type": "integer", "examples": [ 4 ] }, "commit_id": { "description": "The SHA of the commit to which the comment applies.", "type": "string", "examples": [ "6dcb09b5b57875f334f61aebed695e2e4193db5e" ] }, "original_commit_id": { "description": "The SHA of the original commit to which the comment applies.", "type": "string", "examples": [ "9c48853fa3dc5c1c3d6f1f1cd1f2743e72652840" ] }, "in_reply_to_id": { "description": "The comment ID to reply to.", "type": "integer", "examples": [ 8 ] }, "user": { "$ref": "#/components/schemas/simple-user" }, "body": { "description": "The text of the comment.", "type": "string", "examples": [ "We should probably include a check for null values here." ] }, "created_at": { "type": "string", "format": "date-time", "examples": [ "2011-04-14T16:00:49Z" ] }, "updated_at": { "type": "string", "format": "date-time", "examples": [ "2011-04-14T16:00:49Z" ] }, "html_url": { "description": "HTML URL for the pull request review comment.", "type": "string", "format": "uri", "examples": [ "https://github.com/octocat/Hello-World/pull/1#discussion-diff-1" ] }, "pull_request_url": { "description": "URL for the pull request that the review comment belongs to.", "type": "string", "format": "uri", "examples": [ "https://api.github.com/repos/octocat/Hello-World/pulls/1" ] }, "author_association": { "$ref": "#/components/schemas/author_association" }, "_links": { "type": "object", "properties": { "self": { "type": "object", "properties": { "href": { "type": "string", "format": "uri", "examples": [ "https://api.github.com/repos/octocat/Hello-World/pulls/comments/1" ] } }, "required": [ "href" ] }, "html": { "type": "object", "properties": { "href": { "type": "string", "format": "uri", "examples": [ "https://github.com/octocat/Hello-World/pull/1#discussion-diff-1" ] } }, "required": [ "href" ] }, "pull_request": { "type": "object", "properties": { "href": { "type": "string", "format": "uri", "examples": [ "https://api.github.com/repos/octocat/Hello-World/pulls/1" ] } }, "required": [ "href" ] } }, "required": [ "self", "html", "pull_request" ] }, "start_line": { "type": [ "integer", "null" ], "description": "The first line of the range for a multi-line comment.", "examples": [ 2 ] }, "original_start_line": { "type": [ "integer", "null" ], "description": "The first line of the range for a multi-line comment.", "examples": [ 2 ] }, "start_side": { "type": [ "string", "null" ], "description": "The side of the first line of the range for a multi-line comment.", "enum": [ "LEFT", "RIGHT", null ], "default": "RIGHT" }, "line": { "description": "The line of the blob to which the comment applies. The last line of the range for a multi-line comment", "type": "integer", "examples": [ 2 ] }, "original_line": { "description": "The line of the blob to which the comment applies. The last line of the range for a multi-line comment", "type": "integer", "examples": [ 2 ] }, "side": { "description": "The side of the diff to which the comment applies. The side of the last line of the range for a multi-line comment", "enum": [ "LEFT", "RIGHT" ], "default": "RIGHT", "type": "string" }, "reactions": { "$ref": "#/components/schemas/reaction-rollup" }, "body_html": { "type": "string", "examples": [ "\"

      comment body

      \"" ] }, "body_text": { "type": "string", "examples": [ "\"comment body\"" ] } }, "required": [ "url", "id", "node_id", "pull_request_review_id", "diff_hunk", "path", "position", "original_position", "commit_id", "original_commit_id", "user", "body", "created_at", "updated_at", "html_url", "pull_request_url", "author_association", "_links" ] }, "timeline-line-commented-event": { "title": "Timeline Line Commented Event", "description": "Timeline Line Commented Event", "type": "object", "properties": { "event": { "type": "string" }, "node_id": { "type": "string" }, "comments": { "type": "array", "items": { "$ref": "#/components/schemas/pull-request-review-comment" } } } }, "timeline-commit-commented-event": { "title": "Timeline Commit Commented Event", "description": "Timeline Commit Commented Event", "type": "object", "properties": { "event": { "type": "string" }, "node_id": { "type": "string" }, "commit_id": { "type": "string" }, "comments": { "type": "array", "items": { "$ref": "#/components/schemas/commit-comment" } } } }, "timeline-assigned-issue-event": { "title": "Timeline Assigned Issue Event", "description": "Timeline Assigned Issue Event", "type": "object", "properties": { "id": { "type": "integer" }, "node_id": { "type": "string" }, "url": { "type": "string" }, "actor": { "$ref": "#/components/schemas/simple-user" }, "event": { "type": "string" }, "commit_id": { "type": [ "string", "null" ] }, "commit_url": { "type": [ "string", "null" ] }, "created_at": { "type": "string" }, "performed_via_github_app": { "anyOf": [ { "type": "null" }, { "$ref": "#/components/schemas/integration" } ] }, "assignee": { "$ref": "#/components/schemas/simple-user" } }, "required": [ "id", "node_id", "url", "actor", "event", "commit_id", "commit_url", "created_at", "performed_via_github_app", "assignee" ] }, "timeline-unassigned-issue-event": { "title": "Timeline Unassigned Issue Event", "description": "Timeline Unassigned Issue Event", "type": "object", "properties": { "id": { "type": "integer" }, "node_id": { "type": "string" }, "url": { "type": "string" }, "actor": { "$ref": "#/components/schemas/simple-user" }, "event": { "type": "string" }, "commit_id": { "type": [ "string", "null" ] }, "commit_url": { "type": [ "string", "null" ] }, "created_at": { "type": "string" }, "performed_via_github_app": { "anyOf": [ { "type": "null" }, { "$ref": "#/components/schemas/integration" } ] }, "assignee": { "$ref": "#/components/schemas/simple-user" } }, "required": [ "id", "node_id", "url", "actor", "event", "commit_id", "commit_url", "created_at", "performed_via_github_app", "assignee" ] }, "state-change-issue-event": { "title": "State Change Issue Event", "description": "State Change Issue Event", "type": "object", "properties": { "id": { "type": "integer" }, "node_id": { "type": "string" }, "url": { "type": "string" }, "actor": { "$ref": "#/components/schemas/simple-user" }, "event": { "type": "string" }, "commit_id": { "type": [ "string", "null" ] }, "commit_url": { "type": [ "string", "null" ] }, "created_at": { "type": "string" }, "performed_via_github_app": { "anyOf": [ { "type": "null" }, { "$ref": "#/components/schemas/integration" } ] } }, "required": [ "id", "node_id", "url", "actor", "event", "commit_id", "commit_url", "created_at", "performed_via_github_app" ] }, "timeline-issue-events": { "title": "Timeline Event", "description": "Timeline Event", "type": "object", "anyOf": [ { "$ref": "#/components/schemas/labeled-issue-event" }, { "$ref": "#/components/schemas/unlabeled-issue-event" }, { "$ref": "#/components/schemas/milestoned-issue-event" }, { "$ref": "#/components/schemas/demilestoned-issue-event" }, { "$ref": "#/components/schemas/renamed-issue-event" }, { "$ref": "#/components/schemas/review-requested-issue-event" }, { "$ref": "#/components/schemas/review-request-removed-issue-event" }, { "$ref": "#/components/schemas/review-dismissed-issue-event" }, { "$ref": "#/components/schemas/locked-issue-event" }, { "$ref": "#/components/schemas/added-to-project-issue-event" }, { "$ref": "#/components/schemas/moved-column-in-project-issue-event" }, { "$ref": "#/components/schemas/removed-from-project-issue-event" }, { "$ref": "#/components/schemas/converted-note-to-issue-issue-event" }, { "$ref": "#/components/schemas/timeline-comment-event" }, { "$ref": "#/components/schemas/timeline-cross-referenced-event" }, { "$ref": "#/components/schemas/timeline-committed-event" }, { "$ref": "#/components/schemas/timeline-reviewed-event" }, { "$ref": "#/components/schemas/timeline-line-commented-event" }, { "$ref": "#/components/schemas/timeline-commit-commented-event" }, { "$ref": "#/components/schemas/timeline-assigned-issue-event" }, { "$ref": "#/components/schemas/timeline-unassigned-issue-event" }, { "$ref": "#/components/schemas/state-change-issue-event" } ] }, "deploy-key": { "title": "Deploy Key", "description": "An SSH key granting access to a single repository.", "type": "object", "properties": { "id": { "type": "integer" }, "key": { "type": "string" }, "url": { "type": "string" }, "title": { "type": "string" }, "verified": { "type": "boolean" }, "created_at": { "type": "string" }, "read_only": { "type": "boolean" } }, "required": [ "id", "key", "url", "title", "verified", "created_at", "read_only" ] }, "language": { "title": "Language", "description": "Language", "type": "object", "additionalProperties": { "type": "integer" } }, "license-content": { "title": "License Content", "description": "License Content", "type": "object", "properties": { "name": { "type": "string" }, "path": { "type": "string" }, "sha": { "type": "string" }, "size": { "type": "integer" }, "url": { "type": "string", "format": "uri" }, "html_url": { "type": [ "string", "null" ], "format": "uri" }, "git_url": { "type": [ "string", "null" ], "format": "uri" }, "download_url": { "type": [ "string", "null" ], "format": "uri" }, "type": { "type": "string" }, "content": { "type": "string" }, "encoding": { "type": "string" }, "_links": { "type": "object", "properties": { "git": { "type": [ "string", "null" ], "format": "uri" }, "html": { "type": [ "string", "null" ], "format": "uri" }, "self": { "type": "string", "format": "uri" } }, "required": [ "git", "html", "self" ] }, "license": { "anyOf": [ { "type": "null" }, { "$ref": "#/components/schemas/license-simple" } ] } }, "required": [ "_links", "git_url", "html_url", "download_url", "name", "path", "sha", "size", "type", "url", "content", "encoding", "license" ] }, "pages-source-hash": { "title": "Pages Source Hash", "type": "object", "properties": { "branch": { "type": "string" }, "path": { "type": "string" } }, "required": [ "branch", "path" ] }, "pages-https-certificate": { "title": "Pages Https Certificate", "type": "object", "properties": { "state": { "type": "string", "enum": [ "new", "authorization_created", "authorization_pending", "authorized", "authorization_revoked", "issued", "uploaded", "approved", "errored", "bad_authz", "destroy_pending", "dns_changed" ], "examples": [ "approved" ] }, "description": { "type": "string", "examples": [ "Certificate is approved" ] }, "domains": { "type": "array", "items": { "type": "string" }, "description": "Array of the domain set and its alternate name (if it is configured)", "examples": [ "example.com", "www.example.com" ] }, "expires_at": { "type": "string", "format": "date" } }, "required": [ "state", "description", "domains" ] }, "page": { "title": "GitHub Pages", "description": "The configuration for GitHub Pages for a repository.", "type": "object", "properties": { "url": { "type": "string", "description": "The API address for accessing this Page resource.", "format": "uri", "examples": [ "https://api.github.com/repos/github/hello-world/pages" ] }, "status": { "type": [ "string", "null" ], "description": "The status of the most recent build of the Page.", "enum": [ "built", "building", "errored", null ], "examples": [ "built" ] }, "cname": { "description": "The Pages site's custom domain", "type": [ "string", "null" ], "examples": [ "example.com" ] }, "protected_domain_state": { "type": [ "string", "null" ], "description": "The state if the domain is verified", "enum": [ "pending", "verified", "unverified", null ], "examples": [ "pending" ] }, "pending_domain_unverified_at": { "type": [ "string", "null" ], "description": "The timestamp when a pending domain becomes unverified.", "format": "date-time" }, "custom_404": { "type": "boolean", "description": "Whether the Page has a custom 404 page.", "default": false, "examples": [ false ] }, "html_url": { "type": "string", "description": "The web address the Page can be accessed from.", "format": "uri", "examples": [ "https://example.com" ] }, "source": { "$ref": "#/components/schemas/pages-source-hash" }, "public": { "type": "boolean", "description": "Whether the GitHub Pages site is publicly visible. If set to `true`, the site is accessible to anyone on the internet. If set to `false`, the site will only be accessible to users who have at least `read` access to the repository that published the site.", "examples": [ true ] }, "https_certificate": { "$ref": "#/components/schemas/pages-https-certificate" }, "https_enforced": { "type": "boolean", "description": "Whether https is enabled on the domain", "examples": [ true ] } }, "required": [ "url", "status", "cname", "custom_404", "public" ] }, "page-build": { "title": "Page Build", "description": "Page Build", "type": "object", "properties": { "url": { "type": "string", "format": "uri" }, "status": { "type": "string" }, "error": { "type": "object", "properties": { "message": { "type": [ "string", "null" ] } }, "required": [ "message" ] }, "pusher": { "anyOf": [ { "type": "null" }, { "$ref": "#/components/schemas/simple-user" } ] }, "commit": { "type": "string" }, "duration": { "type": "integer" }, "created_at": { "type": "string", "format": "date-time" }, "updated_at": { "type": "string", "format": "date-time" } }, "required": [ "url", "status", "error", "pusher", "commit", "duration", "created_at", "updated_at" ] }, "page-build-status": { "title": "Page Build Status", "description": "Page Build Status", "type": "object", "properties": { "url": { "type": "string", "format": "uri", "examples": [ "https://api.github.com/repos/github/hello-world/pages/builds/latest" ] }, "status": { "type": "string", "examples": [ "queued" ] } }, "required": [ "url", "status" ] }, "repository-pre-receive-hook": { "type": "object", "properties": { "id": { "type": "integer" }, "name": { "type": "string" }, "enforcement": { "type": "string" }, "configuration_url": { "type": "string" } } }, "pull-request": { "type": "object", "title": "Pull Request", "description": "Pull requests let you tell others about changes you've pushed to a repository on GitHub. Once a pull request is sent, interested parties can review the set of changes, discuss potential modifications, and even push follow-up commits if necessary.", "properties": { "url": { "type": "string", "format": "uri", "examples": [ "https://api.github.com/repos/octocat/Hello-World/pulls/1347" ] }, "id": { "type": "integer", "examples": [ 1 ] }, "node_id": { "type": "string", "examples": [ "MDExOlB1bGxSZXF1ZXN0MQ==" ] }, "html_url": { "type": "string", "format": "uri", "examples": [ "https://github.com/octocat/Hello-World/pull/1347" ] }, "diff_url": { "type": "string", "format": "uri", "examples": [ "https://github.com/octocat/Hello-World/pull/1347.diff" ] }, "patch_url": { "type": "string", "format": "uri", "examples": [ "https://github.com/octocat/Hello-World/pull/1347.patch" ] }, "issue_url": { "type": "string", "format": "uri", "examples": [ "https://api.github.com/repos/octocat/Hello-World/issues/1347" ] }, "commits_url": { "type": "string", "format": "uri", "examples": [ "https://api.github.com/repos/octocat/Hello-World/pulls/1347/commits" ] }, "review_comments_url": { "type": "string", "format": "uri", "examples": [ "https://api.github.com/repos/octocat/Hello-World/pulls/1347/comments" ] }, "review_comment_url": { "type": "string", "examples": [ "https://api.github.com/repos/octocat/Hello-World/pulls/comments{/number}" ] }, "comments_url": { "type": "string", "format": "uri", "examples": [ "https://api.github.com/repos/octocat/Hello-World/issues/1347/comments" ] }, "statuses_url": { "type": "string", "format": "uri", "examples": [ "https://api.github.com/repos/octocat/Hello-World/statuses/6dcb09b5b57875f334f61aebed695e2e4193db5e" ] }, "number": { "description": "Number uniquely identifying the pull request within its repository.", "type": "integer", "examples": [ 42 ] }, "state": { "description": "State of this Pull Request. Either `open` or `closed`.", "enum": [ "open", "closed" ], "type": "string", "examples": [ "open" ] }, "locked": { "type": "boolean", "examples": [ true ] }, "title": { "description": "The title of the pull request.", "type": "string", "examples": [ "Amazing new feature" ] }, "user": { "anyOf": [ { "type": "null" }, { "$ref": "#/components/schemas/simple-user" } ] }, "body": { "type": [ "string", "null" ], "examples": [ "Please pull these awesome changes" ] }, "labels": { "type": "array", "items": { "type": "object", "properties": { "id": { "type": "integer", "format": "int64" }, "node_id": { "type": "string" }, "url": { "type": "string" }, "name": { "type": "string" }, "description": { "type": [ "string", "null" ] }, "color": { "type": "string" }, "default": { "type": "boolean" } }, "required": [ "id", "node_id", "url", "name", "description", "color", "default" ] } }, "milestone": { "anyOf": [ { "type": "null" }, { "$ref": "#/components/schemas/milestone" } ] }, "active_lock_reason": { "type": [ "string", "null" ], "examples": [ "too heated" ] }, "created_at": { "type": "string", "format": "date-time", "examples": [ "2011-01-26T19:01:12Z" ] }, "updated_at": { "type": "string", "format": "date-time", "examples": [ "2011-01-26T19:01:12Z" ] }, "closed_at": { "type": [ "string", "null" ], "format": "date-time", "examples": [ "2011-01-26T19:01:12Z" ] }, "merged_at": { "type": [ "string", "null" ], "format": "date-time", "examples": [ "2011-01-26T19:01:12Z" ] }, "merge_commit_sha": { "type": [ "string", "null" ], "examples": [ "e5bd3914e2e596debea16f433f57875b5b90bcd6" ] }, "assignee": { "anyOf": [ { "type": "null" }, { "$ref": "#/components/schemas/simple-user" } ] }, "assignees": { "type": [ "array", "null" ], "items": { "$ref": "#/components/schemas/simple-user" } }, "requested_reviewers": { "type": [ "array", "null" ], "items": { "$ref": "#/components/schemas/simple-user" } }, "requested_teams": { "type": [ "array", "null" ], "items": { "$ref": "#/components/schemas/team-simple" } }, "head": { "type": "object", "properties": { "label": { "type": "string" }, "ref": { "type": "string" }, "repo": { "type": [ "object", "null" ], "properties": { "archive_url": { "type": "string" }, "assignees_url": { "type": "string" }, "blobs_url": { "type": "string" }, "branches_url": { "type": "string" }, "collaborators_url": { "type": "string" }, "comments_url": { "type": "string" }, "commits_url": { "type": "string" }, "compare_url": { "type": "string" }, "contents_url": { "type": "string" }, "contributors_url": { "type": "string", "format": "uri" }, "deployments_url": { "type": "string", "format": "uri" }, "description": { "type": [ "string", "null" ] }, "downloads_url": { "type": "string", "format": "uri" }, "events_url": { "type": "string", "format": "uri" }, "fork": { "type": "boolean" }, "forks_url": { "type": "string", "format": "uri" }, "full_name": { "type": "string" }, "git_commits_url": { "type": "string" }, "git_refs_url": { "type": "string" }, "git_tags_url": { "type": "string" }, "hooks_url": { "type": "string", "format": "uri" }, "html_url": { "type": "string", "format": "uri" }, "id": { "type": "integer" }, "node_id": { "type": "string" }, "issue_comment_url": { "type": "string" }, "issue_events_url": { "type": "string" }, "issues_url": { "type": "string" }, "keys_url": { "type": "string" }, "labels_url": { "type": "string" }, "languages_url": { "type": "string", "format": "uri" }, "merges_url": { "type": "string", "format": "uri" }, "milestones_url": { "type": "string" }, "name": { "type": "string" }, "notifications_url": { "type": "string" }, "owner": { "type": "object", "properties": { "avatar_url": { "type": "string", "format": "uri" }, "events_url": { "type": "string" }, "followers_url": { "type": "string", "format": "uri" }, "following_url": { "type": "string" }, "gists_url": { "type": "string" }, "gravatar_id": { "type": [ "string", "null" ] }, "html_url": { "type": "string", "format": "uri" }, "id": { "type": "integer" }, "node_id": { "type": "string" }, "login": { "type": "string" }, "organizations_url": { "type": "string", "format": "uri" }, "received_events_url": { "type": "string", "format": "uri" }, "repos_url": { "type": "string", "format": "uri" }, "site_admin": { "type": "boolean" }, "starred_url": { "type": "string" }, "subscriptions_url": { "type": "string", "format": "uri" }, "type": { "type": "string" }, "url": { "type": "string", "format": "uri" } }, "required": [ "avatar_url", "events_url", "followers_url", "following_url", "gists_url", "gravatar_id", "html_url", "id", "node_id", "login", "organizations_url", "received_events_url", "repos_url", "site_admin", "starred_url", "subscriptions_url", "type", "url" ] }, "private": { "type": "boolean" }, "pulls_url": { "type": "string" }, "releases_url": { "type": "string" }, "stargazers_url": { "type": "string", "format": "uri" }, "statuses_url": { "type": "string" }, "subscribers_url": { "type": "string", "format": "uri" }, "subscription_url": { "type": "string", "format": "uri" }, "tags_url": { "type": "string", "format": "uri" }, "teams_url": { "type": "string", "format": "uri" }, "trees_url": { "type": "string" }, "url": { "type": "string", "format": "uri" }, "clone_url": { "type": "string" }, "default_branch": { "type": "string" }, "forks": { "type": "integer" }, "forks_count": { "type": "integer" }, "git_url": { "type": "string" }, "has_downloads": { "type": "boolean" }, "has_issues": { "type": "boolean" }, "has_projects": { "type": "boolean" }, "has_wiki": { "type": "boolean" }, "has_pages": { "type": "boolean" }, "homepage": { "type": [ "string", "null" ], "format": "uri" }, "language": { "type": [ "string", "null" ] }, "master_branch": { "type": "string" }, "archived": { "type": "boolean" }, "disabled": { "type": "boolean" }, "visibility": { "description": "The repository visibility: public, private, or internal.", "type": "string" }, "mirror_url": { "type": [ "string", "null" ], "format": "uri" }, "open_issues": { "type": "integer" }, "open_issues_count": { "type": "integer" }, "permissions": { "type": "object", "properties": { "admin": { "type": "boolean" }, "maintain": { "type": "boolean" }, "push": { "type": "boolean" }, "triage": { "type": "boolean" }, "pull": { "type": "boolean" } }, "required": [ "admin", "pull", "push" ] }, "temp_clone_token": { "type": "string" }, "allow_merge_commit": { "type": "boolean" }, "allow_squash_merge": { "type": "boolean" }, "allow_rebase_merge": { "type": "boolean" }, "license": { "type": [ "object", "null" ], "properties": { "key": { "type": "string" }, "name": { "type": "string" }, "url": { "type": [ "string", "null" ], "format": "uri" }, "spdx_id": { "type": [ "string", "null" ] }, "node_id": { "type": "string" } }, "required": [ "key", "name", "url", "spdx_id", "node_id" ] }, "pushed_at": { "type": "string", "format": "date-time" }, "size": { "type": "integer" }, "ssh_url": { "type": "string" }, "stargazers_count": { "type": "integer" }, "svn_url": { "type": "string", "format": "uri" }, "topics": { "type": "array", "items": { "type": "string" } }, "watchers": { "type": "integer" }, "watchers_count": { "type": "integer" }, "created_at": { "type": "string", "format": "date-time" }, "updated_at": { "type": "string", "format": "date-time" }, "allow_forking": { "type": "boolean" }, "is_template": { "type": "boolean" } }, "required": [ "archive_url", "assignees_url", "blobs_url", "branches_url", "collaborators_url", "comments_url", "commits_url", "compare_url", "contents_url", "contributors_url", "deployments_url", "description", "downloads_url", "events_url", "fork", "forks_url", "full_name", "git_commits_url", "git_refs_url", "git_tags_url", "hooks_url", "html_url", "id", "node_id", "issue_comment_url", "issue_events_url", "issues_url", "keys_url", "labels_url", "languages_url", "merges_url", "milestones_url", "name", "notifications_url", "owner", "private", "pulls_url", "releases_url", "stargazers_url", "statuses_url", "subscribers_url", "subscription_url", "tags_url", "teams_url", "trees_url", "url", "clone_url", "default_branch", "forks", "forks_count", "git_url", "has_downloads", "has_issues", "has_projects", "has_wiki", "has_pages", "homepage", "language", "archived", "disabled", "mirror_url", "open_issues", "open_issues_count", "license", "pushed_at", "size", "ssh_url", "stargazers_count", "svn_url", "watchers", "watchers_count", "created_at", "updated_at" ] }, "sha": { "type": "string" }, "user": { "type": "object", "properties": { "avatar_url": { "type": "string", "format": "uri" }, "events_url": { "type": "string" }, "followers_url": { "type": "string", "format": "uri" }, "following_url": { "type": "string" }, "gists_url": { "type": "string" }, "gravatar_id": { "type": [ "string", "null" ] }, "html_url": { "type": "string", "format": "uri" }, "id": { "type": "integer" }, "node_id": { "type": "string" }, "login": { "type": "string" }, "organizations_url": { "type": "string", "format": "uri" }, "received_events_url": { "type": "string", "format": "uri" }, "repos_url": { "type": "string", "format": "uri" }, "site_admin": { "type": "boolean" }, "starred_url": { "type": "string" }, "subscriptions_url": { "type": "string", "format": "uri" }, "type": { "type": "string" }, "url": { "type": "string", "format": "uri" } }, "required": [ "avatar_url", "events_url", "followers_url", "following_url", "gists_url", "gravatar_id", "html_url", "id", "node_id", "login", "organizations_url", "received_events_url", "repos_url", "site_admin", "starred_url", "subscriptions_url", "type", "url" ] } }, "required": [ "label", "ref", "repo", "sha", "user" ] }, "base": { "type": "object", "properties": { "label": { "type": "string" }, "ref": { "type": "string" }, "repo": { "type": "object", "properties": { "archive_url": { "type": "string" }, "assignees_url": { "type": "string" }, "blobs_url": { "type": "string" }, "branches_url": { "type": "string" }, "collaborators_url": { "type": "string" }, "comments_url": { "type": "string" }, "commits_url": { "type": "string" }, "compare_url": { "type": "string" }, "contents_url": { "type": "string" }, "contributors_url": { "type": "string", "format": "uri" }, "deployments_url": { "type": "string", "format": "uri" }, "description": { "type": [ "string", "null" ] }, "downloads_url": { "type": "string", "format": "uri" }, "events_url": { "type": "string", "format": "uri" }, "fork": { "type": "boolean" }, "forks_url": { "type": "string", "format": "uri" }, "full_name": { "type": "string" }, "git_commits_url": { "type": "string" }, "git_refs_url": { "type": "string" }, "git_tags_url": { "type": "string" }, "hooks_url": { "type": "string", "format": "uri" }, "html_url": { "type": "string", "format": "uri" }, "id": { "type": "integer" }, "is_template": { "type": "boolean" }, "node_id": { "type": "string" }, "issue_comment_url": { "type": "string" }, "issue_events_url": { "type": "string" }, "issues_url": { "type": "string" }, "keys_url": { "type": "string" }, "labels_url": { "type": "string" }, "languages_url": { "type": "string", "format": "uri" }, "merges_url": { "type": "string", "format": "uri" }, "milestones_url": { "type": "string" }, "name": { "type": "string" }, "notifications_url": { "type": "string" }, "owner": { "type": "object", "properties": { "avatar_url": { "type": "string", "format": "uri" }, "events_url": { "type": "string" }, "followers_url": { "type": "string", "format": "uri" }, "following_url": { "type": "string" }, "gists_url": { "type": "string" }, "gravatar_id": { "type": [ "string", "null" ] }, "html_url": { "type": "string", "format": "uri" }, "id": { "type": "integer" }, "node_id": { "type": "string" }, "login": { "type": "string" }, "organizations_url": { "type": "string", "format": "uri" }, "received_events_url": { "type": "string", "format": "uri" }, "repos_url": { "type": "string", "format": "uri" }, "site_admin": { "type": "boolean" }, "starred_url": { "type": "string" }, "subscriptions_url": { "type": "string", "format": "uri" }, "type": { "type": "string" }, "url": { "type": "string", "format": "uri" } }, "required": [ "avatar_url", "events_url", "followers_url", "following_url", "gists_url", "gravatar_id", "html_url", "id", "node_id", "login", "organizations_url", "received_events_url", "repos_url", "site_admin", "starred_url", "subscriptions_url", "type", "url" ] }, "private": { "type": "boolean" }, "pulls_url": { "type": "string" }, "releases_url": { "type": "string" }, "stargazers_url": { "type": "string", "format": "uri" }, "statuses_url": { "type": "string" }, "subscribers_url": { "type": "string", "format": "uri" }, "subscription_url": { "type": "string", "format": "uri" }, "tags_url": { "type": "string", "format": "uri" }, "teams_url": { "type": "string", "format": "uri" }, "trees_url": { "type": "string" }, "url": { "type": "string", "format": "uri" }, "clone_url": { "type": "string" }, "default_branch": { "type": "string" }, "forks": { "type": "integer" }, "forks_count": { "type": "integer" }, "git_url": { "type": "string" }, "has_downloads": { "type": "boolean" }, "has_issues": { "type": "boolean" }, "has_projects": { "type": "boolean" }, "has_wiki": { "type": "boolean" }, "has_pages": { "type": "boolean" }, "homepage": { "type": [ "string", "null" ], "format": "uri" }, "language": { "type": [ "string", "null" ] }, "master_branch": { "type": "string" }, "archived": { "type": "boolean" }, "disabled": { "type": "boolean" }, "visibility": { "description": "The repository visibility: public, private, or internal.", "type": "string" }, "mirror_url": { "type": [ "string", "null" ], "format": "uri" }, "open_issues": { "type": "integer" }, "open_issues_count": { "type": "integer" }, "permissions": { "type": "object", "properties": { "admin": { "type": "boolean" }, "maintain": { "type": "boolean" }, "push": { "type": "boolean" }, "triage": { "type": "boolean" }, "pull": { "type": "boolean" } }, "required": [ "admin", "pull", "push" ] }, "temp_clone_token": { "type": "string" }, "allow_merge_commit": { "type": "boolean" }, "allow_squash_merge": { "type": "boolean" }, "allow_rebase_merge": { "type": "boolean" }, "license": { "anyOf": [ { "type": "null" }, { "$ref": "#/components/schemas/license-simple" } ] }, "pushed_at": { "type": "string", "format": "date-time" }, "size": { "type": "integer" }, "ssh_url": { "type": "string" }, "stargazers_count": { "type": "integer" }, "svn_url": { "type": "string", "format": "uri" }, "topics": { "type": "array", "items": { "type": "string" } }, "watchers": { "type": "integer" }, "watchers_count": { "type": "integer" }, "created_at": { "type": "string", "format": "date-time" }, "updated_at": { "type": "string", "format": "date-time" }, "allow_forking": { "type": "boolean" } }, "required": [ "archive_url", "assignees_url", "blobs_url", "branches_url", "collaborators_url", "comments_url", "commits_url", "compare_url", "contents_url", "contributors_url", "deployments_url", "description", "downloads_url", "events_url", "fork", "forks_url", "full_name", "git_commits_url", "git_refs_url", "git_tags_url", "hooks_url", "html_url", "id", "node_id", "issue_comment_url", "issue_events_url", "issues_url", "keys_url", "labels_url", "languages_url", "merges_url", "milestones_url", "name", "notifications_url", "owner", "private", "pulls_url", "releases_url", "stargazers_url", "statuses_url", "subscribers_url", "subscription_url", "tags_url", "teams_url", "trees_url", "url", "clone_url", "default_branch", "forks", "forks_count", "git_url", "has_downloads", "has_issues", "has_projects", "has_wiki", "has_pages", "homepage", "language", "archived", "disabled", "mirror_url", "open_issues", "open_issues_count", "license", "pushed_at", "size", "ssh_url", "stargazers_count", "svn_url", "watchers", "watchers_count", "created_at", "updated_at" ] }, "sha": { "type": "string" }, "user": { "type": "object", "properties": { "avatar_url": { "type": "string", "format": "uri" }, "events_url": { "type": "string" }, "followers_url": { "type": "string", "format": "uri" }, "following_url": { "type": "string" }, "gists_url": { "type": "string" }, "gravatar_id": { "type": [ "string", "null" ] }, "html_url": { "type": "string", "format": "uri" }, "id": { "type": "integer" }, "node_id": { "type": "string" }, "login": { "type": "string" }, "organizations_url": { "type": "string", "format": "uri" }, "received_events_url": { "type": "string", "format": "uri" }, "repos_url": { "type": "string", "format": "uri" }, "site_admin": { "type": "boolean" }, "starred_url": { "type": "string" }, "subscriptions_url": { "type": "string", "format": "uri" }, "type": { "type": "string" }, "url": { "type": "string", "format": "uri" } }, "required": [ "avatar_url", "events_url", "followers_url", "following_url", "gists_url", "gravatar_id", "html_url", "id", "node_id", "login", "organizations_url", "received_events_url", "repos_url", "site_admin", "starred_url", "subscriptions_url", "type", "url" ] } }, "required": [ "label", "ref", "repo", "sha", "user" ] }, "_links": { "type": "object", "properties": { "comments": { "$ref": "#/components/schemas/link" }, "commits": { "$ref": "#/components/schemas/link" }, "statuses": { "$ref": "#/components/schemas/link" }, "html": { "$ref": "#/components/schemas/link" }, "issue": { "$ref": "#/components/schemas/link" }, "review_comments": { "$ref": "#/components/schemas/link" }, "review_comment": { "$ref": "#/components/schemas/link" }, "self": { "$ref": "#/components/schemas/link" } }, "required": [ "comments", "commits", "statuses", "html", "issue", "review_comments", "review_comment", "self" ] }, "author_association": { "$ref": "#/components/schemas/author_association" }, "draft": { "description": "Indicates whether or not the pull request is a draft.", "type": "boolean", "examples": [ false ] }, "merged": { "type": "boolean" }, "mergeable": { "type": [ "boolean", "null" ], "examples": [ true ] }, "rebaseable": { "type": [ "boolean", "null" ], "examples": [ true ] }, "mergeable_state": { "type": "string", "examples": [ "clean" ] }, "merged_by": { "anyOf": [ { "type": "null" }, { "$ref": "#/components/schemas/simple-user" } ] }, "comments": { "type": "integer", "examples": [ 10 ] }, "review_comments": { "type": "integer", "examples": [ 0 ] }, "maintainer_can_modify": { "description": "Indicates whether maintainers can modify the pull request.", "type": "boolean", "examples": [ true ] }, "commits": { "type": "integer", "examples": [ 3 ] }, "additions": { "type": "integer", "examples": [ 100 ] }, "deletions": { "type": "integer", "examples": [ 3 ] }, "changed_files": { "type": "integer", "examples": [ 5 ] } }, "required": [ "_links", "assignee", "labels", "base", "body", "closed_at", "comments_url", "commits_url", "created_at", "diff_url", "head", "html_url", "id", "node_id", "issue_url", "merge_commit_sha", "merged_at", "milestone", "number", "patch_url", "review_comment_url", "review_comments_url", "statuses_url", "state", "locked", "title", "updated_at", "url", "user", "author_association", "additions", "changed_files", "comments", "commits", "deletions", "mergeable", "mergeable_state", "merged", "maintainer_can_modify", "merged_by", "review_comments" ] }, "pull-request-merge-result": { "title": "Pull Request Merge Result", "description": "Pull Request Merge Result", "type": "object", "properties": { "sha": { "type": "string" }, "merged": { "type": "boolean" }, "message": { "type": "string" } }, "required": [ "merged", "message", "sha" ] }, "pull-request-review-request": { "title": "Pull Request Review Request", "description": "Pull Request Review Request", "type": "object", "properties": { "users": { "type": "array", "items": { "$ref": "#/components/schemas/simple-user" } }, "teams": { "type": "array", "items": { "$ref": "#/components/schemas/team" } } }, "required": [ "users", "teams" ] }, "pull-request-review": { "title": "Pull Request Review", "description": "Pull Request Reviews are reviews on pull requests.", "type": "object", "properties": { "id": { "description": "Unique identifier of the review", "type": "integer", "examples": [ 42 ] }, "node_id": { "type": "string", "examples": [ "MDE3OlB1bGxSZXF1ZXN0UmV2aWV3ODA=" ] }, "user": { "anyOf": [ { "type": "null" }, { "$ref": "#/components/schemas/simple-user" } ] }, "body": { "description": "The text of the review.", "type": "string", "examples": [ "This looks great." ] }, "state": { "type": "string", "examples": [ "CHANGES_REQUESTED" ] }, "html_url": { "type": "string", "format": "uri", "examples": [ "https://github.com/octocat/Hello-World/pull/12#pullrequestreview-80" ] }, "pull_request_url": { "type": "string", "format": "uri", "examples": [ "https://api.github.com/repos/octocat/Hello-World/pulls/12" ] }, "_links": { "type": "object", "properties": { "html": { "type": "object", "properties": { "href": { "type": "string" } }, "required": [ "href" ] }, "pull_request": { "type": "object", "properties": { "href": { "type": "string" } }, "required": [ "href" ] } }, "required": [ "html", "pull_request" ] }, "submitted_at": { "type": "string", "format": "date-time" }, "commit_id": { "description": "A commit SHA for the review.", "type": "string", "examples": [ "54bb654c9e6025347f57900a4a5c2313a96b8035" ] }, "body_html": { "type": "string" }, "body_text": { "type": "string" }, "author_association": { "$ref": "#/components/schemas/author_association" } }, "required": [ "id", "node_id", "user", "body", "state", "commit_id", "html_url", "pull_request_url", "_links", "author_association" ] }, "review-comment": { "title": "Legacy Review Comment", "description": "Legacy Review Comment", "type": "object", "properties": { "url": { "type": "string", "format": "uri", "examples": [ "https://api.github.com/repos/octocat/Hello-World/pulls/comments/1" ] }, "pull_request_review_id": { "type": [ "integer", "null" ], "examples": [ 42 ] }, "id": { "type": "integer", "examples": [ 10 ] }, "node_id": { "type": "string", "examples": [ "MDI0OlB1bGxSZXF1ZXN0UmV2aWV3Q29tbWVudDEw" ] }, "diff_hunk": { "type": "string", "examples": [ "@@ -16,33 +16,40 @@ public class Connection : IConnection..." ] }, "path": { "type": "string", "examples": [ "file1.txt" ] }, "position": { "type": [ "integer", "null" ], "examples": [ 1 ] }, "original_position": { "type": "integer", "examples": [ 4 ] }, "commit_id": { "type": "string", "examples": [ "6dcb09b5b57875f334f61aebed695e2e4193db5e" ] }, "original_commit_id": { "type": "string", "examples": [ "9c48853fa3dc5c1c3d6f1f1cd1f2743e72652840" ] }, "in_reply_to_id": { "type": "integer", "examples": [ 8 ] }, "user": { "anyOf": [ { "type": "null" }, { "$ref": "#/components/schemas/simple-user" } ] }, "body": { "type": "string", "examples": [ "Great stuff" ] }, "created_at": { "type": "string", "format": "date-time", "examples": [ "2011-04-14T16:00:49Z" ] }, "updated_at": { "type": "string", "format": "date-time", "examples": [ "2011-04-14T16:00:49Z" ] }, "html_url": { "type": "string", "format": "uri", "examples": [ "https://github.com/octocat/Hello-World/pull/1#discussion-diff-1" ] }, "pull_request_url": { "type": "string", "format": "uri", "examples": [ "https://api.github.com/repos/octocat/Hello-World/pulls/1" ] }, "author_association": { "$ref": "#/components/schemas/author_association" }, "_links": { "type": "object", "properties": { "self": { "$ref": "#/components/schemas/link" }, "html": { "$ref": "#/components/schemas/link" }, "pull_request": { "$ref": "#/components/schemas/link" } }, "required": [ "self", "html", "pull_request" ] }, "body_text": { "type": "string" }, "body_html": { "type": "string" }, "reactions": { "$ref": "#/components/schemas/reaction-rollup" }, "side": { "description": "The side of the first line of the range for a multi-line comment.", "enum": [ "LEFT", "RIGHT" ], "default": "RIGHT", "type": "string" }, "start_side": { "type": [ "string", "null" ], "description": "The side of the first line of the range for a multi-line comment.", "enum": [ "LEFT", "RIGHT", null ], "default": "RIGHT" }, "line": { "description": "The line of the blob to which the comment applies. The last line of the range for a multi-line comment", "type": "integer", "examples": [ 2 ] }, "original_line": { "description": "The original line of the blob to which the comment applies. The last line of the range for a multi-line comment", "type": "integer", "examples": [ 2 ] }, "start_line": { "description": "The first line of the range for a multi-line comment.", "type": [ "integer", "null" ], "examples": [ 2 ] }, "original_start_line": { "description": "The original first line of the range for a multi-line comment.", "type": [ "integer", "null" ], "examples": [ 2 ] } }, "required": [ "id", "node_id", "url", "body", "diff_hunk", "path", "position", "original_position", "commit_id", "original_commit_id", "user", "pull_request_review_id", "html_url", "pull_request_url", "_links", "author_association", "created_at", "updated_at" ] }, "release-asset": { "title": "Release Asset", "description": "Data related to a release.", "type": "object", "properties": { "url": { "type": "string", "format": "uri" }, "browser_download_url": { "type": "string", "format": "uri" }, "id": { "type": "integer" }, "node_id": { "type": "string" }, "name": { "description": "The file name of the asset.", "type": "string", "examples": [ "Team Environment" ] }, "label": { "type": [ "string", "null" ] }, "state": { "description": "State of the release asset.", "type": "string", "enum": [ "uploaded", "open" ] }, "content_type": { "type": "string" }, "size": { "type": "integer" }, "download_count": { "type": "integer" }, "created_at": { "type": "string", "format": "date-time" }, "updated_at": { "type": "string", "format": "date-time" }, "uploader": { "anyOf": [ { "type": "null" }, { "$ref": "#/components/schemas/simple-user" } ] } }, "required": [ "id", "name", "content_type", "size", "state", "url", "node_id", "download_count", "label", "uploader", "browser_download_url", "created_at", "updated_at" ] }, "release": { "title": "Release", "description": "A release.", "type": "object", "properties": { "url": { "type": "string", "format": "uri" }, "html_url": { "type": "string", "format": "uri" }, "assets_url": { "type": "string", "format": "uri" }, "upload_url": { "type": "string" }, "tarball_url": { "type": [ "string", "null" ], "format": "uri" }, "zipball_url": { "type": [ "string", "null" ], "format": "uri" }, "id": { "type": "integer" }, "node_id": { "type": "string" }, "tag_name": { "description": "The name of the tag.", "type": "string", "examples": [ "v1.0.0" ] }, "target_commitish": { "description": "Specifies the commitish value that determines where the Git tag is created from.", "type": "string", "examples": [ "master" ] }, "name": { "type": [ "string", "null" ] }, "body": { "type": [ "string", "null" ] }, "draft": { "description": "true to create a draft (unpublished) release, false to create a published one.", "type": "boolean", "examples": [ false ] }, "prerelease": { "description": "Whether to identify the release as a prerelease or a full release.", "type": "boolean", "examples": [ false ] }, "created_at": { "type": "string", "format": "date-time" }, "published_at": { "type": [ "string", "null" ], "format": "date-time" }, "author": { "$ref": "#/components/schemas/simple-user" }, "assets": { "type": "array", "items": { "$ref": "#/components/schemas/release-asset" } }, "body_html": { "type": "string" }, "body_text": { "type": "string" }, "reactions": { "$ref": "#/components/schemas/reaction-rollup" } }, "required": [ "assets_url", "upload_url", "tarball_url", "zipball_url", "created_at", "published_at", "draft", "id", "node_id", "author", "html_url", "name", "prerelease", "tag_name", "target_commitish", "assets", "url" ] }, "stargazer": { "title": "Stargazer", "description": "Stargazer", "type": "object", "properties": { "starred_at": { "type": "string", "format": "date-time" }, "user": { "anyOf": [ { "type": "null" }, { "$ref": "#/components/schemas/simple-user" } ] } }, "required": [ "starred_at", "user" ] }, "code-frequency-stat": { "title": "Code Frequency Stat", "description": "Code Frequency Stat", "type": "array", "items": { "type": "integer" } }, "commit-activity": { "title": "Commit Activity", "description": "Commit Activity", "type": "object", "properties": { "days": { "type": "array", "items": { "type": "integer" }, "examples": [ 0, 3, 26, 20, 39, 1, 0 ] }, "total": { "type": "integer", "examples": [ 89 ] }, "week": { "type": "integer", "examples": [ 1336280400 ] } }, "required": [ "days", "total", "week" ] }, "contributor-activity": { "title": "Contributor Activity", "description": "Contributor Activity", "type": "object", "properties": { "author": { "anyOf": [ { "type": "null" }, { "$ref": "#/components/schemas/simple-user" } ] }, "total": { "type": "integer", "examples": [ 135 ] }, "weeks": { "type": "array", "items": { "type": "object", "properties": { "w": { "type": "integer" }, "a": { "type": "integer" }, "d": { "type": "integer" }, "c": { "type": "integer" } } }, "examples": [ { "w": "1367712000", "a": 6898, "d": 77, "c": 10 } ] } }, "required": [ "author", "total", "weeks" ] }, "participation-stats": { "title": "Participation Stats", "type": "object", "properties": { "all": { "type": "array", "items": { "type": "integer" } }, "owner": { "type": "array", "items": { "type": "integer" } } }, "required": [ "all", "owner" ] }, "repository-subscription": { "title": "Repository Invitation", "description": "Repository invitations let you manage who you collaborate with.", "type": "object", "properties": { "subscribed": { "description": "Determines if notifications should be received from this repository.", "type": "boolean", "examples": [ true ] }, "ignored": { "description": "Determines if all notifications should be blocked from this repository.", "type": "boolean" }, "reason": { "type": [ "string", "null" ] }, "created_at": { "type": "string", "format": "date-time", "examples": [ "2012-10-06T21:34:12Z" ] }, "url": { "type": "string", "format": "uri", "examples": [ "https://api.github.com/repos/octocat/example/subscription" ] }, "repository_url": { "type": "string", "format": "uri", "examples": [ "https://api.github.com/repos/octocat/example" ] } }, "required": [ "created_at", "ignored", "reason", "subscribed", "url", "repository_url" ] }, "tag": { "title": "Tag", "description": "Tag", "type": "object", "properties": { "name": { "type": "string", "examples": [ "v0.1" ] }, "commit": { "type": "object", "properties": { "sha": { "type": "string" }, "url": { "type": "string", "format": "uri" } }, "required": [ "sha", "url" ] }, "zipball_url": { "type": "string", "format": "uri", "examples": [ "https://github.com/octocat/Hello-World/zipball/v0.1" ] }, "tarball_url": { "type": "string", "format": "uri", "examples": [ "https://github.com/octocat/Hello-World/tarball/v0.1" ] }, "node_id": { "type": "string" } }, "required": [ "name", "node_id", "commit", "zipball_url", "tarball_url" ] }, "topic": { "title": "Topic", "description": "A topic aggregates entities that are related to a subject.", "type": "object", "properties": { "names": { "type": "array", "items": { "type": "string" } } }, "required": [ "names" ] }, "search-result-text-matches": { "title": "Search Result Text Matches", "type": "array", "items": { "type": "object", "properties": { "object_url": { "type": "string" }, "object_type": { "type": [ "string", "null" ] }, "property": { "type": "string" }, "fragment": { "type": "string" }, "matches": { "type": "array", "items": { "type": "object", "properties": { "text": { "type": "string" }, "indices": { "type": "array", "items": { "type": "integer" } } } } } } } }, "code-search-result-item": { "title": "Code Search Result Item", "description": "Code Search Result Item", "type": "object", "properties": { "name": { "type": "string" }, "path": { "type": "string" }, "sha": { "type": "string" }, "url": { "type": "string", "format": "uri" }, "git_url": { "type": "string", "format": "uri" }, "html_url": { "type": "string", "format": "uri" }, "repository": { "$ref": "#/components/schemas/minimal-repository" }, "score": { "type": "number" }, "file_size": { "type": "integer" }, "language": { "type": [ "string", "null" ] }, "last_modified_at": { "type": "string", "format": "date-time" }, "line_numbers": { "type": "array", "items": { "type": "string" }, "examples": [ "73..77", "77..78" ] }, "text_matches": { "$ref": "#/components/schemas/search-result-text-matches" } }, "required": [ "score", "name", "path", "sha", "git_url", "html_url", "url", "repository" ] }, "commit-search-result-item": { "title": "Commit Search Result Item", "description": "Commit Search Result Item", "type": "object", "properties": { "url": { "type": "string", "format": "uri" }, "sha": { "type": "string" }, "html_url": { "type": "string", "format": "uri" }, "comments_url": { "type": "string", "format": "uri" }, "commit": { "type": "object", "properties": { "author": { "type": "object", "properties": { "name": { "type": "string" }, "email": { "type": "string" }, "date": { "type": "string", "format": "date-time" } }, "required": [ "name", "email", "date" ] }, "committer": { "anyOf": [ { "type": "null" }, { "$ref": "#/components/schemas/git-user" } ] }, "comment_count": { "type": "integer" }, "message": { "type": "string" }, "tree": { "type": "object", "properties": { "sha": { "type": "string" }, "url": { "type": "string", "format": "uri" } }, "required": [ "sha", "url" ] }, "url": { "type": "string", "format": "uri" }, "verification": { "$ref": "#/components/schemas/verification" } }, "required": [ "author", "committer", "comment_count", "message", "tree", "url" ] }, "author": { "anyOf": [ { "type": "null" }, { "$ref": "#/components/schemas/simple-user" } ] }, "committer": { "anyOf": [ { "type": "null" }, { "$ref": "#/components/schemas/git-user" } ] }, "parents": { "type": "array", "items": { "type": "object", "properties": { "url": { "type": "string" }, "html_url": { "type": "string" }, "sha": { "type": "string" } } } }, "repository": { "$ref": "#/components/schemas/minimal-repository" }, "score": { "type": "number" }, "node_id": { "type": "string" }, "text_matches": { "$ref": "#/components/schemas/search-result-text-matches" } }, "required": [ "sha", "node_id", "url", "html_url", "author", "committer", "parents", "comments_url", "commit", "repository", "score" ] }, "issue-search-result-item": { "title": "Issue Search Result Item", "description": "Issue Search Result Item", "type": "object", "properties": { "url": { "type": "string", "format": "uri" }, "repository_url": { "type": "string", "format": "uri" }, "labels_url": { "type": "string" }, "comments_url": { "type": "string", "format": "uri" }, "events_url": { "type": "string", "format": "uri" }, "html_url": { "type": "string", "format": "uri" }, "id": { "type": "integer" }, "node_id": { "type": "string" }, "number": { "type": "integer" }, "title": { "type": "string" }, "locked": { "type": "boolean" }, "active_lock_reason": { "type": [ "string", "null" ] }, "assignees": { "type": [ "array", "null" ], "items": { "$ref": "#/components/schemas/simple-user" } }, "user": { "anyOf": [ { "type": "null" }, { "$ref": "#/components/schemas/simple-user" } ] }, "labels": { "type": "array", "items": { "type": "object", "properties": { "id": { "type": "integer", "format": "int64" }, "node_id": { "type": "string" }, "url": { "type": "string" }, "name": { "type": "string" }, "color": { "type": "string" }, "default": { "type": "boolean" }, "description": { "type": [ "string", "null" ] } } } }, "state": { "type": "string" }, "assignee": { "anyOf": [ { "type": "null" }, { "$ref": "#/components/schemas/simple-user" } ] }, "milestone": { "anyOf": [ { "type": "null" }, { "$ref": "#/components/schemas/milestone" } ] }, "comments": { "type": "integer" }, "created_at": { "type": "string", "format": "date-time" }, "updated_at": { "type": "string", "format": "date-time" }, "closed_at": { "type": [ "string", "null" ], "format": "date-time" }, "text_matches": { "$ref": "#/components/schemas/search-result-text-matches" }, "pull_request": { "type": "object", "properties": { "merged_at": { "type": [ "string", "null" ], "format": "date-time" }, "diff_url": { "type": [ "string", "null" ], "format": "uri" }, "html_url": { "type": [ "string", "null" ], "format": "uri" }, "patch_url": { "type": [ "string", "null" ], "format": "uri" }, "url": { "type": [ "string", "null" ], "format": "uri" } }, "required": [ "diff_url", "html_url", "patch_url", "url" ] }, "body": { "type": "string" }, "score": { "type": "number" }, "author_association": { "$ref": "#/components/schemas/author_association" }, "draft": { "type": "boolean" }, "repository": { "$ref": "#/components/schemas/repository" }, "body_html": { "type": "string" }, "body_text": { "type": "string" }, "timeline_url": { "type": "string", "format": "uri" }, "performed_via_github_app": { "anyOf": [ { "type": "null" }, { "$ref": "#/components/schemas/integration" } ] }, "reactions": { "$ref": "#/components/schemas/reaction-rollup" } }, "required": [ "assignee", "closed_at", "comments", "comments_url", "events_url", "html_url", "id", "node_id", "labels", "labels_url", "milestone", "number", "repository_url", "state", "locked", "title", "url", "user", "author_association", "created_at", "updated_at", "score" ] }, "label-search-result-item": { "title": "Label Search Result Item", "description": "Label Search Result Item", "type": "object", "properties": { "id": { "type": "integer" }, "node_id": { "type": "string" }, "url": { "type": "string", "format": "uri" }, "name": { "type": "string" }, "color": { "type": "string" }, "default": { "type": "boolean" }, "description": { "type": [ "string", "null" ] }, "score": { "type": "number" }, "text_matches": { "$ref": "#/components/schemas/search-result-text-matches" } }, "required": [ "id", "node_id", "url", "name", "color", "default", "description", "score" ] }, "repo-search-result-item": { "title": "Repo Search Result Item", "description": "Repo Search Result Item", "type": "object", "properties": { "id": { "type": "integer" }, "node_id": { "type": "string" }, "name": { "type": "string" }, "full_name": { "type": "string" }, "owner": { "anyOf": [ { "type": "null" }, { "$ref": "#/components/schemas/simple-user" } ] }, "private": { "type": "boolean" }, "html_url": { "type": "string", "format": "uri" }, "description": { "type": [ "string", "null" ] }, "fork": { "type": "boolean" }, "url": { "type": "string", "format": "uri" }, "created_at": { "type": "string", "format": "date-time" }, "updated_at": { "type": "string", "format": "date-time" }, "pushed_at": { "type": "string", "format": "date-time" }, "homepage": { "type": [ "string", "null" ], "format": "uri" }, "size": { "type": "integer" }, "stargazers_count": { "type": "integer" }, "watchers_count": { "type": "integer" }, "language": { "type": [ "string", "null" ] }, "forks_count": { "type": "integer" }, "open_issues_count": { "type": "integer" }, "master_branch": { "type": "string" }, "default_branch": { "type": "string" }, "score": { "type": "number" }, "forks_url": { "type": "string", "format": "uri" }, "keys_url": { "type": "string" }, "collaborators_url": { "type": "string" }, "teams_url": { "type": "string", "format": "uri" }, "hooks_url": { "type": "string", "format": "uri" }, "issue_events_url": { "type": "string" }, "events_url": { "type": "string", "format": "uri" }, "assignees_url": { "type": "string" }, "branches_url": { "type": "string" }, "tags_url": { "type": "string", "format": "uri" }, "blobs_url": { "type": "string" }, "git_tags_url": { "type": "string" }, "git_refs_url": { "type": "string" }, "trees_url": { "type": "string" }, "statuses_url": { "type": "string" }, "languages_url": { "type": "string", "format": "uri" }, "stargazers_url": { "type": "string", "format": "uri" }, "contributors_url": { "type": "string", "format": "uri" }, "subscribers_url": { "type": "string", "format": "uri" }, "subscription_url": { "type": "string", "format": "uri" }, "commits_url": { "type": "string" }, "git_commits_url": { "type": "string" }, "comments_url": { "type": "string" }, "issue_comment_url": { "type": "string" }, "contents_url": { "type": "string" }, "compare_url": { "type": "string" }, "merges_url": { "type": "string", "format": "uri" }, "archive_url": { "type": "string" }, "downloads_url": { "type": "string", "format": "uri" }, "issues_url": { "type": "string" }, "pulls_url": { "type": "string" }, "milestones_url": { "type": "string" }, "notifications_url": { "type": "string" }, "labels_url": { "type": "string" }, "releases_url": { "type": "string" }, "deployments_url": { "type": "string", "format": "uri" }, "git_url": { "type": "string" }, "ssh_url": { "type": "string" }, "clone_url": { "type": "string" }, "svn_url": { "type": "string", "format": "uri" }, "forks": { "type": "integer" }, "open_issues": { "type": "integer" }, "watchers": { "type": "integer" }, "topics": { "type": "array", "items": { "type": "string" } }, "mirror_url": { "type": [ "string", "null" ], "format": "uri" }, "has_issues": { "type": "boolean" }, "has_projects": { "type": "boolean" }, "has_pages": { "type": "boolean" }, "has_wiki": { "type": "boolean" }, "has_downloads": { "type": "boolean" }, "archived": { "type": "boolean" }, "disabled": { "type": "boolean", "description": "Returns whether or not this repository disabled." }, "visibility": { "description": "The repository visibility: public, private, or internal.", "type": "string" }, "license": { "anyOf": [ { "type": "null" }, { "$ref": "#/components/schemas/license-simple" } ] }, "permissions": { "type": "object", "properties": { "admin": { "type": "boolean" }, "maintain": { "type": "boolean" }, "push": { "type": "boolean" }, "triage": { "type": "boolean" }, "pull": { "type": "boolean" } }, "required": [ "admin", "pull", "push" ] }, "text_matches": { "$ref": "#/components/schemas/search-result-text-matches" }, "temp_clone_token": { "type": "string" }, "allow_merge_commit": { "type": "boolean" }, "allow_squash_merge": { "type": "boolean" }, "allow_rebase_merge": { "type": "boolean" }, "delete_branch_on_merge": { "type": "boolean" }, "allow_forking": { "type": "boolean" }, "is_template": { "type": "boolean" } }, "required": [ "archive_url", "assignees_url", "blobs_url", "branches_url", "collaborators_url", "comments_url", "commits_url", "compare_url", "contents_url", "contributors_url", "deployments_url", "description", "downloads_url", "events_url", "fork", "forks_url", "full_name", "git_commits_url", "git_refs_url", "git_tags_url", "hooks_url", "html_url", "id", "node_id", "issue_comment_url", "issue_events_url", "issues_url", "keys_url", "labels_url", "languages_url", "merges_url", "milestones_url", "name", "notifications_url", "owner", "private", "pulls_url", "releases_url", "stargazers_url", "statuses_url", "subscribers_url", "subscription_url", "tags_url", "teams_url", "trees_url", "url", "clone_url", "default_branch", "forks", "forks_count", "git_url", "has_downloads", "has_issues", "has_projects", "has_wiki", "has_pages", "homepage", "language", "archived", "disabled", "mirror_url", "open_issues", "open_issues_count", "license", "pushed_at", "size", "ssh_url", "stargazers_count", "svn_url", "watchers", "watchers_count", "created_at", "updated_at", "score" ] }, "topic-search-result-item": { "title": "Topic Search Result Item", "description": "Topic Search Result Item", "type": "object", "properties": { "name": { "type": "string" }, "display_name": { "type": [ "string", "null" ] }, "short_description": { "type": [ "string", "null" ] }, "description": { "type": [ "string", "null" ] }, "created_by": { "type": [ "string", "null" ] }, "released": { "type": [ "string", "null" ] }, "created_at": { "type": "string", "format": "date-time" }, "updated_at": { "type": "string", "format": "date-time" }, "featured": { "type": "boolean" }, "curated": { "type": "boolean" }, "score": { "type": "number" }, "repository_count": { "type": [ "integer", "null" ] }, "logo_url": { "type": [ "string", "null" ], "format": "uri" }, "text_matches": { "$ref": "#/components/schemas/search-result-text-matches" }, "related": { "type": [ "array", "null" ], "items": { "type": "object", "properties": { "topic_relation": { "type": "object", "properties": { "id": { "type": "integer" }, "name": { "type": "string" }, "topic_id": { "type": "integer" }, "relation_type": { "type": "string" } } } } } }, "aliases": { "type": [ "array", "null" ], "items": { "type": "object", "properties": { "topic_relation": { "type": "object", "properties": { "id": { "type": "integer" }, "name": { "type": "string" }, "topic_id": { "type": "integer" }, "relation_type": { "type": "string" } } } } } } }, "required": [ "name", "display_name", "short_description", "description", "created_by", "released", "created_at", "updated_at", "featured", "curated", "score" ] }, "user-search-result-item": { "title": "User Search Result Item", "description": "User Search Result Item", "type": "object", "properties": { "login": { "type": "string" }, "id": { "type": "integer" }, "node_id": { "type": "string" }, "avatar_url": { "type": "string", "format": "uri" }, "gravatar_id": { "type": [ "string", "null" ] }, "url": { "type": "string", "format": "uri" }, "html_url": { "type": "string", "format": "uri" }, "followers_url": { "type": "string", "format": "uri" }, "subscriptions_url": { "type": "string", "format": "uri" }, "organizations_url": { "type": "string", "format": "uri" }, "repos_url": { "type": "string", "format": "uri" }, "received_events_url": { "type": "string", "format": "uri" }, "type": { "type": "string" }, "score": { "type": "number" }, "following_url": { "type": "string" }, "gists_url": { "type": "string" }, "starred_url": { "type": "string" }, "events_url": { "type": "string" }, "public_repos": { "type": "integer" }, "public_gists": { "type": "integer" }, "followers": { "type": "integer" }, "following": { "type": "integer" }, "created_at": { "type": "string", "format": "date-time" }, "updated_at": { "type": "string", "format": "date-time" }, "name": { "type": [ "string", "null" ] }, "bio": { "type": [ "string", "null" ] }, "email": { "type": [ "string", "null" ], "format": "email" }, "location": { "type": [ "string", "null" ] }, "site_admin": { "type": "boolean" }, "hireable": { "type": [ "boolean", "null" ] }, "text_matches": { "$ref": "#/components/schemas/search-result-text-matches" }, "blog": { "type": [ "string", "null" ] }, "company": { "type": [ "string", "null" ] }, "suspended_at": { "type": [ "string", "null" ], "format": "date-time" } }, "required": [ "avatar_url", "events_url", "followers_url", "following_url", "gists_url", "gravatar_id", "html_url", "id", "node_id", "login", "organizations_url", "received_events_url", "repos_url", "site_admin", "starred_url", "subscriptions_url", "type", "url", "score" ] }, "configuration-status": { "type": "object", "properties": { "status": { "type": "string" }, "progress": { "type": "array", "items": { "type": "object", "properties": { "status": { "type": "string" }, "key": { "type": "string" } }, "required": [ "status", "key" ] } } } }, "maintenance-status": { "type": "object", "properties": { "status": { "type": "string" }, "scheduled_time": { "type": "string" }, "connection_services": { "type": "array", "items": { "type": "object", "properties": { "name": { "type": "string" }, "number": { "type": "integer" } }, "required": [ "name", "number" ] } } } }, "enterprise-settings": { "type": "object", "properties": { "enterprise": { "type": "object", "properties": { "private_mode": { "type": "boolean" }, "public_pages": { "type": "boolean" }, "subdomain_isolation": { "type": "boolean" }, "signup_enabled": { "type": "boolean" }, "github_hostname": { "type": "string" }, "identicons_host": { "type": "string" }, "http_proxy": { "type": [ "string", "null" ] }, "auth_mode": { "type": "string" }, "expire_sessions": { "type": "boolean" }, "admin_password": { "type": [ "string", "null" ] }, "configuration_id": { "type": "integer" }, "configuration_run_count": { "type": "integer" }, "avatar": { "type": "object", "properties": { "enabled": { "type": "boolean" }, "uri": { "type": "string" } } }, "customer": { "type": "object", "properties": { "name": { "type": "string" }, "email": { "type": "string" }, "uuid": { "type": "string" }, "secret_key_data": { "type": "string" }, "public_key_data": { "type": "string" } } }, "license": { "type": "object", "properties": { "seats": { "type": "integer" }, "evaluation": { "type": "boolean" }, "perpetual": { "type": "boolean" }, "unlimited_seating": { "type": "boolean" }, "support_key": { "type": "string" }, "ssh_allowed": { "type": "boolean" }, "cluster_support": { "type": "boolean" }, "expire_at": { "type": "string" } } }, "github_ssl": { "type": "object", "properties": { "enabled": { "type": "boolean" }, "cert": { "type": [ "string", "null" ] }, "key": { "type": [ "string", "null" ] } } }, "ldap": { "type": "object", "properties": { "host": { "type": [ "string", "null" ] }, "port": { "type": "integer" }, "base": { "type": "array", "items": { } }, "uid": { "type": [ "string", "null" ] }, "bind_dn": { "type": [ "string", "null" ] }, "password": { "type": [ "string", "null" ] }, "method": { "type": "string" }, "search_strategy": { "type": "string" }, "user_groups": { "type": "array", "items": { } }, "admin_group": { "type": [ "string", "null" ] }, "virtual_attribute_enabled": { "type": "boolean" }, "recursive_group_search": { "type": "boolean" }, "posix_support": { "type": "boolean" }, "user_sync_emails": { "type": "boolean" }, "user_sync_keys": { "type": "boolean" }, "user_sync_interval": { "type": "integer" }, "team_sync_interval": { "type": "integer" }, "sync_enabled": { "type": "boolean" }, "reconciliation": { "type": "object", "properties": { "user": { "type": [ "string", "null" ] }, "org": { "type": [ "string", "null" ] } } }, "profile": { "type": "object", "properties": { "uid": { "type": "string" }, "name": { "type": [ "string", "null" ] }, "mail": { "type": [ "string", "null" ] }, "key": { "type": [ "string", "null" ] } } } } }, "cas": { "type": "object", "properties": { "url": { "type": [ "string", "null" ] } } }, "saml": { "type": "object", "properties": { "sso_url": { "type": [ "string", "null" ] }, "certificate": { "type": [ "string", "null" ] }, "certificate_path": { "type": [ "string", "null" ] }, "issuer": { "type": [ "string", "null" ] }, "idp_initiated_sso": { "type": "boolean" }, "disable_admin_demote": { "type": "boolean" } } }, "github_oauth": { "type": "object", "properties": { "client_id": { "type": "string" }, "client_secret": { "type": "string" }, "organization_name": { "type": "string" }, "organization_team": { "type": "string" } } }, "smtp": { "type": "object", "properties": { "enabled": { "type": "boolean" }, "address": { "type": "string" }, "authentication": { "type": "string" }, "port": { "type": "string" }, "domain": { "type": "string" }, "username": { "type": "string" }, "user_name": { "type": "string" }, "enable_starttls_auto": { "type": "boolean" }, "password": { "type": "string" }, "discard-to-noreply-address": { "type": "boolean" }, "support_address": { "type": "string" }, "support_address_type": { "type": "string" }, "noreply_address": { "type": "string" } } }, "ntp": { "type": "object", "properties": { "primary_server": { "type": "string" }, "secondary_server": { "type": "string" } } }, "timezone": { "type": [ "string", "null" ] }, "snmp": { "type": "object", "properties": { "enabled": { "type": "boolean" }, "community": { "type": "string" } } }, "syslog": { "type": "object", "properties": { "enabled": { "type": "boolean" }, "server": { "type": [ "string", "null" ] }, "protocol_name": { "type": "string" } } }, "assets": { "type": [ "string", "null" ] }, "pages": { "type": "object", "properties": { "enabled": { "type": "boolean" } } }, "collectd": { "type": "object", "properties": { "enabled": { "type": "boolean" }, "server": { "type": [ "string", "null" ] }, "port": { "type": "integer" }, "encryption": { "type": [ "string", "null" ] }, "username": { "type": [ "string", "null" ] }, "password": { "type": [ "string", "null" ] } } }, "mapping": { "type": "object", "properties": { "enabled": { "type": "boolean" }, "tileserver": { "type": [ "string", "null" ] }, "basemap": { "type": "string" }, "token": { "type": [ "string", "null" ] } } }, "load_balancer": { "type": [ "string", "null" ] } } }, "run_list": { "type": "array", "items": { "type": "string" } } } }, "ssh-key": { "type": "object", "properties": { "key": { "type": "string" }, "pretty-print": { "type": "string" } } }, "private-user": { "title": "Private User", "description": "Private User", "type": "object", "properties": { "login": { "type": "string", "examples": [ "octocat" ] }, "id": { "type": "integer", "examples": [ 1 ] }, "node_id": { "type": "string", "examples": [ "MDQ6VXNlcjE=" ] }, "avatar_url": { "type": "string", "format": "uri", "examples": [ "https://github.com/images/error/octocat_happy.gif" ] }, "gravatar_id": { "type": [ "string", "null" ], "examples": [ "41d064eb2195891e12d0413f63227ea7" ] }, "url": { "type": "string", "format": "uri", "examples": [ "https://api.github.com/users/octocat" ] }, "html_url": { "type": "string", "format": "uri", "examples": [ "https://github.com/octocat" ] }, "followers_url": { "type": "string", "format": "uri", "examples": [ "https://api.github.com/users/octocat/followers" ] }, "following_url": { "type": "string", "examples": [ "https://api.github.com/users/octocat/following{/other_user}" ] }, "gists_url": { "type": "string", "examples": [ "https://api.github.com/users/octocat/gists{/gist_id}" ] }, "starred_url": { "type": "string", "examples": [ "https://api.github.com/users/octocat/starred{/owner}{/repo}" ] }, "subscriptions_url": { "type": "string", "format": "uri", "examples": [ "https://api.github.com/users/octocat/subscriptions" ] }, "organizations_url": { "type": "string", "format": "uri", "examples": [ "https://api.github.com/users/octocat/orgs" ] }, "repos_url": { "type": "string", "format": "uri", "examples": [ "https://api.github.com/users/octocat/repos" ] }, "events_url": { "type": "string", "examples": [ "https://api.github.com/users/octocat/events{/privacy}" ] }, "received_events_url": { "type": "string", "format": "uri", "examples": [ "https://api.github.com/users/octocat/received_events" ] }, "type": { "type": "string", "examples": [ "User" ] }, "site_admin": { "type": "boolean" }, "name": { "type": [ "string", "null" ], "examples": [ "monalisa octocat" ] }, "company": { "type": [ "string", "null" ], "examples": [ "GitHub" ] }, "blog": { "type": [ "string", "null" ], "examples": [ "https://github.com/blog" ] }, "location": { "type": [ "string", "null" ], "examples": [ "San Francisco" ] }, "email": { "type": [ "string", "null" ], "format": "email", "examples": [ "octocat@github.com" ] }, "hireable": { "type": [ "boolean", "null" ] }, "bio": { "type": [ "string", "null" ], "examples": [ "There once was..." ] }, "public_repos": { "type": "integer", "examples": [ 2 ] }, "public_gists": { "type": "integer", "examples": [ 1 ] }, "followers": { "type": "integer", "examples": [ 20 ] }, "following": { "type": "integer", "examples": [ 0 ] }, "created_at": { "type": "string", "format": "date-time", "examples": [ "2008-01-14T04:33:35Z" ] }, "updated_at": { "type": "string", "format": "date-time", "examples": [ "2008-01-14T04:33:35Z" ] }, "private_gists": { "type": "integer", "examples": [ 81 ] }, "total_private_repos": { "type": "integer", "examples": [ 100 ] }, "owned_private_repos": { "type": "integer", "examples": [ 100 ] }, "disk_usage": { "type": "integer", "examples": [ 10000 ] }, "collaborators": { "type": "integer", "examples": [ 8 ] }, "two_factor_authentication": { "type": "boolean", "examples": [ true ] }, "plan": { "type": "object", "properties": { "collaborators": { "type": "integer" }, "name": { "type": "string" }, "space": { "type": "integer" }, "private_repos": { "type": "integer" } }, "required": [ "collaborators", "name", "space", "private_repos" ] }, "suspended_at": { "type": "string", "format": "date-time" }, "business_plus": { "type": "boolean" }, "ldap_dn": { "type": "string" } }, "required": [ "avatar_url", "events_url", "followers_url", "following_url", "gists_url", "gravatar_id", "html_url", "id", "node_id", "login", "organizations_url", "received_events_url", "repos_url", "site_admin", "starred_url", "subscriptions_url", "type", "url", "bio", "blog", "company", "email", "followers", "following", "hireable", "location", "name", "public_gists", "public_repos", "created_at", "updated_at", "collaborators", "disk_usage", "owned_private_repos", "private_gists", "total_private_repos", "two_factor_authentication" ] }, "email": { "title": "Email", "description": "Email", "type": "object", "properties": { "email": { "type": "string", "format": "email", "examples": [ "octocat@github.com" ] }, "primary": { "type": "boolean", "examples": [ true ] }, "verified": { "type": "boolean", "examples": [ true ] }, "visibility": { "type": [ "string", "null" ], "examples": [ "public" ] } }, "required": [ "email", "primary", "verified", "visibility" ] }, "gpg-key": { "title": "GPG Key", "description": "A unique encryption key", "type": "object", "properties": { "id": { "type": "integer", "examples": [ 3 ] }, "primary_key_id": { "type": [ "integer", "null" ] }, "key_id": { "type": "string", "examples": [ "3262EFF25BA0D270" ] }, "public_key": { "type": "string", "examples": [ "xsBNBFayYZ..." ] }, "emails": { "type": "array", "items": { "type": "object", "properties": { "email": { "type": "string" }, "verified": { "type": "boolean" } } }, "examples": [ { "email": "mastahyeti@users.noreply.github.com", "verified": true } ] }, "subkeys": { "type": "array", "items": { "type": "object", "properties": { "id": { "type": "integer" }, "primary_key_id": { "type": "integer" }, "key_id": { "type": "string" }, "public_key": { "type": "string" }, "emails": { "type": "array", "items": { } }, "subkeys": { "type": "array", "items": { } }, "can_sign": { "type": "boolean" }, "can_encrypt_comms": { "type": "boolean" }, "can_encrypt_storage": { "type": "boolean" }, "can_certify": { "type": "boolean" }, "created_at": { "type": "string" }, "expires_at": { "type": [ "string", "null" ] }, "raw_key": { "type": [ "string", "null" ] } } }, "examples": [ { "id": 4, "primary_key_id": 3, "key_id": "4A595D4C72EE49C7", "public_key": "zsBNBFayYZ...", "emails": [ ], "subkeys": [ ], "can_sign": false, "can_encrypt_comms": true, "can_encrypt_storage": true, "can_certify": false, "created_at": "2016-03-24T11:31:04-06:00", "expires_at": null } ] }, "can_sign": { "type": "boolean", "examples": [ true ] }, "can_encrypt_comms": { "type": "boolean" }, "can_encrypt_storage": { "type": "boolean" }, "can_certify": { "type": "boolean", "examples": [ true ] }, "created_at": { "type": "string", "format": "date-time", "examples": [ "2016-03-24T11:31:04-06:00" ] }, "expires_at": { "type": [ "string", "null" ], "format": "date-time" }, "raw_key": { "type": [ "string", "null" ] } }, "required": [ "id", "primary_key_id", "key_id", "raw_key", "public_key", "created_at", "expires_at", "can_sign", "can_encrypt_comms", "can_encrypt_storage", "can_certify", "emails", "subkeys" ] }, "key": { "title": "Key", "description": "Key", "type": "object", "properties": { "key": { "type": "string" }, "id": { "type": "integer" }, "url": { "type": "string" }, "title": { "type": "string" }, "created_at": { "type": "string", "format": "date-time" }, "verified": { "type": "boolean" }, "read_only": { "type": "boolean" } }, "required": [ "key", "id", "url", "title", "created_at", "verified", "read_only" ] }, "starred-repository": { "title": "Starred Repository", "description": "Starred Repository", "type": "object", "properties": { "starred_at": { "type": "string", "format": "date-time" }, "repo": { "$ref": "#/components/schemas/repository" } }, "required": [ "starred_at", "repo" ] }, "hovercard": { "title": "Hovercard", "description": "Hovercard", "type": "object", "properties": { "contexts": { "type": "array", "items": { "type": "object", "properties": { "message": { "type": "string" }, "octicon": { "type": "string" } }, "required": [ "message", "octicon" ] } } }, "required": [ "contexts" ] }, "key-simple": { "title": "Key Simple", "description": "Key Simple", "type": "object", "properties": { "id": { "type": "integer" }, "key": { "type": "string" } }, "required": [ "key", "id" ] } }, "examples": { "global-hook-items": { "value": [ { "type": "Global", "id": 1, "name": "web", "active": true, "events": [ "organization", "user" ], "config": { "url": "https://example.com", "content_type": "json", "insecure_ssl": "0", "secret": "********" }, "updated_at": "2017-12-07T00:14:59Z", "created_at": "2017-12-07T00:14:59Z", "url": "https://api.github.com/admin/hooks/1", "ping_url": "https://api.github.com/admin/hooks/1/pings" } ] }, "global-hook": { "value": { "type": "Global", "id": 1, "name": "web", "active": true, "events": [ "organization", "user" ], "config": { "url": "https://example.com", "content_type": "json", "insecure_ssl": "0", "secret": "********" }, "updated_at": "2017-12-07T00:14:59Z", "created_at": "2017-12-07T00:14:59Z", "url": "https://api.github.com/admin/hooks/1", "ping_url": "https://api.github.com/admin/hooks/1/pings" } }, "global-hook-2": { "value": { "type": "Global", "id": 1, "name": "web", "active": true, "events": [ "organization" ], "config": { "url": "https://example.com", "content_type": "form", "insecure_ssl": "0" }, "updated_at": "2017-12-07T00:14:59Z", "created_at": "2017-12-07T00:14:59Z", "url": "https://api.github.com/admin/hooks/1", "ping_url": "https://api.github.com/admin/hooks/1/pings" } }, "enterprise-public-key-items": { "value": [ { "key": "2Sg8iYjAxxmI2LvUXpJjkYrMxURPc8r+dB7TJyvv1234", "id": 2, "url": "https://api.github.com/user/keys/2", "title": "ssh-rsa AAAAB3NzaC1yc2EAAA", "created_at": "2020-06-11T21:31:57Z", "verified": false, "read_only": false, "last_used": "2020-06-11T22:31:57Z", "user_id": 1, "repository_id": 2 }, { "key": "9Og8iYjAyymI9LvABpJerYrMxURPc8r+dB7TJyvv1234", "id": 3, "url": "https://api.github.com/user/keys/2", "title": "ssh-rsa AAAAB3NzaC1yc2EAAA", "created_at": "2020-06-11T21:31:57Z", "verified": false, "read_only": false, "last_used": "2020-06-11T22:31:57Z", "user_id": 1, "repository_id": 2 } ] }, "ldap-mapping-team": { "value": { "ldap_dn": "cn=Enterprise Ops,ou=teams,dc=github,dc=com", "id": 1, "node_id": "MDQ6VGVhbTE=", "url": "https://api.github.com/teams/1", "html_url": "https://github.com/orgs/github/teams/justice-league", "name": "Justice League", "slug": "justice-league", "description": "A great team.", "privacy": "closed", "permission": "admin", "members_url": "https://api.github.com/teams/1/members{/member}", "repositories_url": "https://api.github.com/teams/1/repos", "parent": null } }, "ldap-mapping-user": { "value": { "ldap_dn": "uid=asdf,ou=users,dc=github,dc=com", "login": "octocat", "id": 1, "node_id": "MDQ6VXNlcjE=", "avatar_url": "https://github.com/images/error/octocat_happy.gif", "gravatar_id": "", "url": "https://api.github.com/users/octocat", "html_url": "https://github.com/octocat", "followers_url": "https://api.github.com/users/octocat/followers", "following_url": "https://api.github.com/users/octocat/following{/other_user}", "gists_url": "https://api.github.com/users/octocat/gists{/gist_id}", "starred_url": "https://api.github.com/users/octocat/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/octocat/subscriptions", "organizations_url": "https://api.github.com/users/octocat/orgs", "repos_url": "https://api.github.com/users/octocat/repos", "events_url": "https://api.github.com/users/octocat/events{/privacy}", "received_events_url": "https://api.github.com/users/octocat/received_events", "type": "User", "site_admin": false, "name": "monalisa octocat", "company": "GitHub", "blog": "https://github.com/blog", "location": "San Francisco", "email": "octocat@github.com", "hireable": false, "bio": "There once was...", "twitter_username": "monatheoctocat", "public_repos": 2, "public_gists": 1, "followers": 20, "following": 0, "created_at": "2008-01-14T04:33:35Z", "updated_at": "2008-01-14T04:33:35Z", "private_gists": 81, "total_private_repos": 100, "owned_private_repos": 100, "disk_usage": 10000, "collaborators": 8, "two_factor_authentication": true, "plan": { "name": "Medium", "space": 400, "private_repos": 20, "collaborators": 0 } } }, "organization-simple": { "value": { "login": "github", "id": 1, "node_id": "MDEyOk9yZ2FuaXphdGlvbjE=", "url": "https://api.github.com/orgs/github", "repos_url": "https://api.github.com/orgs/github/repos", "events_url": "https://api.github.com/orgs/github/events", "hooks_url": "https://api.github.com/orgs/github/hooks", "issues_url": "https://api.github.com/orgs/github/issues", "members_url": "https://api.github.com/orgs/github/members{/member}", "public_members_url": "https://api.github.com/orgs/github/public_members{/member}", "avatar_url": "https://github.com/images/error/octocat_happy.gif", "description": "A great organization" } }, "pre-receive-environment-items": { "value": [ { "id": 1, "name": "Default", "image_url": "githubenterprise://internal", "url": "https://github.example.com/api/v3/admin/pre-receive-environments/1", "html_url": "https://github.example.com/admin/pre-receive-environments/1", "default_environment": true, "created_at": "2016-05-20T11:35:45-05:00", "hooks_count": 14, "download": { "url": "https://github.example.com/api/v3/admin/pre-receive-environments/1/downloads/latest", "state": "not_started", "downloaded_at": "2016-05-26T07:42:53-05:00", "message": null } }, { "id": 2, "name": "DevTools Hook Env", "image_url": "https://my_file_server/path/to/devtools_env.tar.gz", "url": "https://github.example.com/api/v3/admin/pre-receive-environments/2", "html_url": "https://github.example.com/admin/pre-receive-environments/2", "default_environment": false, "created_at": "2016-05-20T11:35:45-05:00", "hooks_count": 1, "download": { "url": "https://github.example.com/api/v3/admin/pre-receive-environments/2/downloads/latest", "state": "success", "downloaded_at": "2016-05-26T07:42:53-05:00", "message": null } } ] }, "pre-receive-environment": { "value": { "id": 2, "name": "DevTools Hook Env", "image_url": "https://my_file_server/path/to/devtools_env.tar.gz", "url": "https://github.example.com/api/v3/admin/pre-receive-environments/2", "html_url": "https://github.example.com/admin/pre-receive-environments/2", "default_environment": false, "created_at": "2016-05-20T11:35:45-05:00", "hooks_count": 1, "download": { "url": "https://github.example.com/api/v3/admin/pre-receive-environments/2/downloads/latest", "state": "not_started", "downloaded_at": null, "message": null } } }, "pre-receive-environment-default-response": { "value": { "id": 2, "name": "DevTools Hook Env", "image_url": "https://my_file_server/path/to/devtools_env.tar.gz", "url": "https://github.example.com/api/v3/admin/pre-receive-environments/2", "html_url": "https://github.example.com/admin/pre-receive-environments/2", "default_environment": false, "created_at": "2016-05-20T11:35:45-05:00", "hooks_count": 1, "download": { "url": "https://github.example.com/api/v3/admin/pre-receive-environments/2/downloads/latest", "state": "success", "downloaded_at": "2016-05-26T07:42:53-05:00", "message": null } } }, "pre-receive-environment-download-status-default-response": { "value": { "url": "https://github.example.com/api/v3/admin/pre-receive-environments/3/downloads/latest", "state": "not_started", "downloaded_at": null, "message": null } }, "pre-receive-environment-download-status": { "value": { "url": "https://github.example.com/api/v3/admin/pre-receive-environments/3/downloads/latest", "state": "success", "downloaded_at": "2016-05-26T07:42:53-05:00", "message": null } }, "pre-receive-hook-items": { "value": [ { "id": 1, "name": "Check Commits", "enforcement": "disabled", "script": "scripts/commmit_check.sh", "script_repository": { "id": 595, "full_name": "DevIT/hooks", "url": "https://github.example.com/api/v3/repos/DevIT/hooks", "html_url": "https://github.example.com/DevIT/hooks" }, "environment": { "id": 2, "name": "DevTools Hook Env", "image_url": "https://my_file_server/path/to/devtools_env.tar.gz", "url": "https://github.example.com/api/v3/admin/pre-receive-environments/2", "html_url": "https://github.example.com/admin/pre-receive-environments/2", "default_environment": false, "created_at": "2016-05-20T11:35:45-05:00", "hooks_count": 1, "download": { "url": "https://github.example.com/api/v3/admin/pre-receive-environments/2/downloads/latest", "state": "success", "downloaded_at": "2016-05-26T07:42:53-05:00", "message": null } }, "allow_downstream_configuration": false } ] }, "pre-receive-hook": { "value": { "id": 1, "name": "Check Commits", "enforcement": "disabled", "script": "scripts/commmit_check.sh", "script_repository": { "id": 595, "full_name": "DevIT/hooks", "url": "https://github.example.com/api/v3/repos/DevIT/hooks", "html_url": "https://github.example.com/DevIT/hooks" }, "environment": { "id": 2, "name": "DevTools Hook Env", "image_url": "https://my_file_server/path/to/devtools_env.tar.gz", "url": "https://github.example.com/api/v3/admin/pre-receive-environments/2", "html_url": "https://github.example.com/admin/pre-receive-environments/2", "default_environment": false, "created_at": "2016-05-20T11:35:45-05:00", "hooks_count": 1, "download": { "url": "https://github.example.com/api/v3/admin/pre-receive-environments/2/downloads/latest", "state": "success", "downloaded_at": "2016-05-26T07:42:53-05:00", "message": null } }, "allow_downstream_configuration": false } }, "pre-receive-hook-2": { "value": { "id": 1, "name": "Check Commits", "enforcement": "disabled", "script": "scripts/commmit_check.sh", "script_repository": { "id": 595, "full_name": "DevIT/hooks", "url": "https://github.example.com/api/v3/repos/DevIT/hooks", "html_url": "https://github.example.com/DevIT/hooks" }, "environment": { "id": 1, "name": "Default", "image_url": "githubenterprise://internal", "url": "https://github.example.com/api/v3/admin/pre-receive-environments/1", "html_url": "https://github.example.com/admin/pre-receive-environments/1", "default_environment": true, "created_at": "2016-05-20T11:35:45-05:00", "hooks_count": 1, "download": { "url": "https://github.example.com/api/v3/admin/pre-receive-environments/1/downloads/latest", "state": "success", "downloaded_at": "2016-05-26T07:42:53-05:00", "message": null } }, "allow_downstream_configuration": true } }, "authorization-items": { "value": [ { "id": 2, "url": "https://enterprise.octocat.com/api/v3/authorizations/2", "app": { "name": "My personal access token", "url": "https://docs.github.com/enterprise/rest/reference/enterprise-admin#list-personal-access-tokens", "client_id": "00000000000000000000" }, "token": "ghp_16C7e42F292c6912E7710c838347Ae178B4a", "hashed_token": "23cffb2fab1b0a62747863eba88cb9327e561f2f7a0c8661c0d9b83146cb8d45", "token_last_eight": "Ae178B4a", "note": "My personal access token", "note_url": null, "created_at": "2019-04-24T21:49:02Z", "updated_at": "2019-04-24T21:49:02Z", "scopes": [ "admin:business", "admin:gpg_key", "admin:org", "admin:org_hook", "admin:pre_receive_hook", "admin:public_key", "admin:repo_hook", "delete_repo", "gist", "notifications", "repo", "user", "write:discussion" ], "fingerprint": null } ] }, "simple-user": { "value": { "login": "octocat", "id": 1, "node_id": "MDQ6VXNlcjE=", "avatar_url": "https://github.com/images/error/octocat_happy.gif", "gravatar_id": "", "url": "https://api.github.com/users/octocat", "html_url": "https://github.com/octocat", "followers_url": "https://api.github.com/users/octocat/followers", "following_url": "https://api.github.com/users/octocat/following{/other_user}", "gists_url": "https://api.github.com/users/octocat/gists{/gist_id}", "starred_url": "https://api.github.com/users/octocat/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/octocat/subscriptions", "organizations_url": "https://api.github.com/users/octocat/orgs", "repos_url": "https://api.github.com/users/octocat/repos", "events_url": "https://api.github.com/users/octocat/events{/privacy}", "received_events_url": "https://api.github.com/users/octocat/received_events", "type": "User", "site_admin": false } }, "authorization": { "value": { "id": 1, "url": "https://api.github.com/authorizations/1", "scopes": [ "public_repo" ], "token": "ghu_16C7e42F292c6912E7710c838347Ae178B4a", "token_last_eight": "Ae178B4a", "hashed_token": "25f94a2a5c7fbaf499c665bc73d67c1c87e496da8985131633ee0a95819db2e8", "app": { "url": "http://my-github-app.com", "name": "my github app", "client_id": "abcde12345fghij67890" }, "note": "optional note", "note_url": "http://optional/note/url", "updated_at": "2011-09-06T20:39:23Z", "created_at": "2011-09-06T17:26:27Z", "fingerprint": "jklmnop12345678" } }, "integration": { "value": { "id": 1, "slug": "octoapp", "node_id": "MDExOkludGVncmF0aW9uMQ==", "owner": { "login": "github", "id": 1, "node_id": "MDEyOk9yZ2FuaXphdGlvbjE=", "url": "https://api.github.com/orgs/github", "repos_url": "https://api.github.com/orgs/github/repos", "events_url": "https://api.github.com/orgs/github/events", "avatar_url": "https://github.com/images/error/octocat_happy.gif", "gravatar_id": "", "html_url": "https://github.com/octocat", "followers_url": "https://api.github.com/users/octocat/followers", "following_url": "https://api.github.com/users/octocat/following{/other_user}", "gists_url": "https://api.github.com/users/octocat/gists{/gist_id}", "starred_url": "https://api.github.com/users/octocat/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/octocat/subscriptions", "organizations_url": "https://api.github.com/users/octocat/orgs", "received_events_url": "https://api.github.com/users/octocat/received_events", "type": "User", "site_admin": true }, "name": "Octocat App", "description": "", "external_url": "https://example.com", "html_url": "https://github.com/apps/octoapp", "created_at": "2017-07-08T16:18:44-04:00", "updated_at": "2017-07-08T16:18:44-04:00", "permissions": { "metadata": "read", "contents": "read", "issues": "write", "single_file": "write" }, "events": [ "push", "pull_request" ] } }, "integration-from-manifest": { "value": { "id": 1, "slug": "octoapp", "node_id": "MDxOkludGVncmF0aW9uMQ==", "owner": { "login": "github", "id": 1, "node_id": "MDEyOk9yZ2FuaXphdGlvbjE=", "url": "https://api.github.com/orgs/github", "repos_url": "https://api.github.com/orgs/github/repos", "events_url": "https://api.github.com/orgs/github/events", "avatar_url": "https://github.com/images/error/octocat_happy.gif", "gravatar_id": "", "html_url": "https://github.com/octocat", "followers_url": "https://api.github.com/users/octocat/followers", "following_url": "https://api.github.com/users/octocat/following{/other_user}", "gists_url": "https://api.github.com/users/octocat/gists{/gist_id}", "starred_url": "https://api.github.com/users/octocat/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/octocat/subscriptions", "organizations_url": "https://api.github.com/users/octocat/orgs", "received_events_url": "https://api.github.com/users/octocat/received_events", "type": "User", "site_admin": true }, "name": "Octocat App", "description": "", "external_url": "https://example.com", "html_url": "https://github.com/apps/octoapp", "created_at": "2017-07-08T16:18:44-04:00", "updated_at": "2017-07-08T16:18:44-04:00", "permissions": { "metadata": "read", "contents": "read", "issues": "write", "single_file": "write" }, "events": [ "push", "pull_request" ], "client_id": "Iv1.8a61f9b3a7aba766", "client_secret": "1726be1638095a19edd134c77bde3aa2ece1e5d8", "webhook_secret": "e340154128314309424b7c8e90325147d99fdafa", "pem": "-----BEGIN RSA PRIVATE KEY-----\nMIIEowIBAAKCAQEAuEPzOUE+kiEH1WLiMeBytTEF856j0hOVcSUSUkZxKvqczkWM\n9vo1gDyC7ZXhdH9fKh32aapba3RSsp4ke+giSmYTk2mGR538ShSDxh0OgpJmjiKP\nX0Bj4j5sFqfXuCtl9SkH4iueivv4R53ktqM+n6hk98l6hRwC39GVIblAh2lEM4L/\n6WvYwuQXPMM5OG2Ryh2tDZ1WS5RKfgq+9ksNJ5Q9UtqtqHkO+E63N5OK9sbzpUUm\noNaOl3udTlZD3A8iqwMPVxH4SxgATBPAc+bmjk6BMJ0qIzDcVGTrqrzUiywCTLma\nszdk8GjzXtPDmuBgNn+o6s02qVGpyydgEuqmTQIDAQABAoIBACL6AvkjQVVLn8kJ\ndBYznJJ4M8ECo+YEgaFwgAHODT0zRQCCgzd+Vxl4YwHmKV2Lr+y2s0drZt8GvYva\nKOK8NYYZyi15IlwFyRXmvvykF1UBpSXluYFDH7KaVroWMgRreHcIys5LqVSIb6Bo\ngDmK0yBLPp8qR29s2b7ScZRtLaqGJiX+j55rNzrZwxHkxFHyG9OG+u9IsBElcKCP\nkYCVE8ZdYexfnKOZbgn2kZB9qu0T/Mdvki8yk3I2bI6xYO24oQmhnT36qnqWoCBX\nNuCNsBQgpYZeZET8mEAUmo9d+ABmIHIvSs005agK8xRaP4+6jYgy6WwoejJRF5yd\nNBuF7aECgYEA50nZ4FiZYV0vcJDxFYeY3kYOvVuKn8OyW+2rg7JIQTremIjv8FkE\nZnwuF9ZRxgqLxUIfKKfzp/5l5LrycNoj2YKfHKnRejxRWXqG+ZETfxxlmlRns0QG\nJ4+BYL0CoanDSeA4fuyn4Bv7cy/03TDhfg/Uq0Aeg+hhcPE/vx3ebPsCgYEAy/Pv\neDLssOSdeyIxf0Brtocg6aPXIVaLdus+bXmLg77rJIFytAZmTTW8SkkSczWtucI3\nFI1I6sei/8FdPzAl62/JDdlf7Wd9K7JIotY4TzT7Tm7QU7xpfLLYIP1bOFjN81rk\n77oOD4LsXcosB/U6s1blPJMZ6AlO2EKs10UuR1cCgYBipzuJ2ADEaOz9RLWwi0AH\nPza2Sj+c2epQD9ZivD7Zo/Sid3ZwvGeGF13JyR7kLEdmAkgsHUdu1rI7mAolXMaB\n1pdrsHureeLxGbRM6za3tzMXWv1Il7FQWoPC8ZwXvMOR1VQDv4nzq7vbbA8z8c+c\n57+8tALQHOTDOgQIzwK61QKBgERGVc0EJy4Uag+VY8J4m1ZQKBluqo7TfP6DQ7O8\nM5MX73maB/7yAX8pVO39RjrhJlYACRZNMbK+v/ckEQYdJSSKmGCVe0JrGYDuPtic\nI9+IGfSorf7KHPoMmMN6bPYQ7Gjh7a++tgRFTMEc8956Hnt4xGahy9NcglNtBpVN\n6G8jAoGBAMCh028pdzJa/xeBHLLaVB2sc0Fe7993WlsPmnVE779dAz7qMscOtXJK\nfgtriltLSSD6rTA9hUAsL/X62rY0wdXuNdijjBb/qvrx7CAV6i37NK1CjABNjsfG\nZM372Ac6zc1EqSrid2IjET1YqyIW2KGLI1R2xbQc98UGlt48OdWu\n-----END RSA PRIVATE KEY-----\n" } }, "webhook-config": { "value": { "content_type": "json", "insecure_ssl": "0", "secret": "********", "url": "https://example.com/webhook" } }, "base-installation-items": { "value": [ { "id": 1, "account": { "login": "octocat", "id": 1, "node_id": "MDQ6VXNlcjE=", "avatar_url": "https://github.com/images/error/octocat_happy.gif", "gravatar_id": "", "url": "https://api.github.com/users/octocat", "html_url": "https://github.com/octocat", "followers_url": "https://api.github.com/users/octocat/followers", "following_url": "https://api.github.com/users/octocat/following{/other_user}", "gists_url": "https://api.github.com/users/octocat/gists{/gist_id}", "starred_url": "https://api.github.com/users/octocat/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/octocat/subscriptions", "organizations_url": "https://api.github.com/users/octocat/orgs", "repos_url": "https://api.github.com/users/octocat/repos", "events_url": "https://api.github.com/users/octocat/events{/privacy}", "received_events_url": "https://api.github.com/users/octocat/received_events", "type": "User", "site_admin": false }, "access_tokens_url": "https://api.github.com/installations/1/access_tokens", "repositories_url": "https://api.github.com/installation/repositories", "html_url": "https://github.com/organizations/github/settings/installations/1", "app_id": 1, "target_id": 1, "target_type": "Organization", "permissions": { "checks": "write", "metadata": "read", "contents": "read" }, "events": [ "push", "pull_request" ], "single_file_name": "config.yaml", "has_multiple_single_files": true, "single_file_paths": [ "config.yml", ".github/issue_TEMPLATE.md" ], "repository_selection": "selected", "created_at": "2017-07-08T16:18:44-04:00", "updated_at": "2017-07-08T16:18:44-04:00", "app_slug": "github-actions", "suspended_at": null, "suspended_by": null } ] }, "base-installation": { "value": { "id": 1, "account": { "login": "octocat", "id": 1, "node_id": "MDQ6VXNlcjE=", "avatar_url": "https://github.com/images/error/octocat_happy.gif", "gravatar_id": "", "url": "https://api.github.com/users/octocat", "html_url": "https://github.com/octocat", "followers_url": "https://api.github.com/users/octocat/followers", "following_url": "https://api.github.com/users/octocat/following{/other_user}", "gists_url": "https://api.github.com/users/octocat/gists{/gist_id}", "starred_url": "https://api.github.com/users/octocat/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/octocat/subscriptions", "organizations_url": "https://api.github.com/users/octocat/orgs", "repos_url": "https://api.github.com/users/octocat/repos", "events_url": "https://api.github.com/users/octocat/events{/privacy}", "received_events_url": "https://api.github.com/users/octocat/received_events", "type": "User", "site_admin": false }, "access_tokens_url": "https://api.github.com/installations/1/access_tokens", "repositories_url": "https://api.github.com/installation/repositories", "html_url": "https://github.com/organizations/github/settings/installations/1", "app_id": 1, "target_id": 1, "target_type": "Organization", "permissions": { "checks": "write", "metadata": "read", "contents": "read" }, "events": [ "push", "pull_request" ], "single_file_name": "config.yaml", "has_multiple_single_files": true, "single_file_paths": [ "config.yml", ".github/issue_TEMPLATE.md" ], "repository_selection": "selected", "created_at": "2017-07-08T16:18:44-04:00", "updated_at": "2017-07-08T16:18:44-04:00", "app_slug": "github-actions", "suspended_at": null, "suspended_by": null } }, "installation-token": { "value": { "token": "ghs_16C7e42F292c6912E7710c838347Ae178B4a", "expires_at": "2016-07-11T22:14:10Z", "permissions": { "issues": "write", "contents": "read" }, "repository_selection": "selected", "repositories": [ { "id": 1296269, "node_id": "MDEwOlJlcG9zaXRvcnkxMjk2MjY5", "name": "Hello-World", "full_name": "octocat/Hello-World", "owner": { "login": "octocat", "id": 1, "node_id": "MDQ6VXNlcjE=", "avatar_url": "https://github.com/images/error/octocat_happy.gif", "gravatar_id": "", "url": "https://api.github.com/users/octocat", "html_url": "https://github.com/octocat", "followers_url": "https://api.github.com/users/octocat/followers", "following_url": "https://api.github.com/users/octocat/following{/other_user}", "gists_url": "https://api.github.com/users/octocat/gists{/gist_id}", "starred_url": "https://api.github.com/users/octocat/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/octocat/subscriptions", "organizations_url": "https://api.github.com/users/octocat/orgs", "repos_url": "https://api.github.com/users/octocat/repos", "events_url": "https://api.github.com/users/octocat/events{/privacy}", "received_events_url": "https://api.github.com/users/octocat/received_events", "type": "User", "site_admin": false }, "private": false, "html_url": "https://github.com/octocat/Hello-World", "description": "This your first repo!", "fork": false, "url": "https://api.github.com/repos/octocat/Hello-World", "archive_url": "https://api.github.com/repos/octocat/Hello-World/{archive_format}{/ref}", "assignees_url": "https://api.github.com/repos/octocat/Hello-World/assignees{/user}", "blobs_url": "https://api.github.com/repos/octocat/Hello-World/git/blobs{/sha}", "branches_url": "https://api.github.com/repos/octocat/Hello-World/branches{/branch}", "collaborators_url": "https://api.github.com/repos/octocat/Hello-World/collaborators{/collaborator}", "comments_url": "https://api.github.com/repos/octocat/Hello-World/comments{/number}", "commits_url": "https://api.github.com/repos/octocat/Hello-World/commits{/sha}", "compare_url": "https://api.github.com/repos/octocat/Hello-World/compare/{base}...{head}", "contents_url": "https://api.github.com/repos/octocat/Hello-World/contents/{+path}", "contributors_url": "https://api.github.com/repos/octocat/Hello-World/contributors", "deployments_url": "https://api.github.com/repos/octocat/Hello-World/deployments", "downloads_url": "https://api.github.com/repos/octocat/Hello-World/downloads", "events_url": "https://api.github.com/repos/octocat/Hello-World/events", "forks_url": "https://api.github.com/repos/octocat/Hello-World/forks", "git_commits_url": "https://api.github.com/repos/octocat/Hello-World/git/commits{/sha}", "git_refs_url": "https://api.github.com/repos/octocat/Hello-World/git/refs{/sha}", "git_tags_url": "https://api.github.com/repos/octocat/Hello-World/git/tags{/sha}", "git_url": "git:github.com/octocat/Hello-World.git", "issue_comment_url": "https://api.github.com/repos/octocat/Hello-World/issues/comments{/number}", "issue_events_url": "https://api.github.com/repos/octocat/Hello-World/issues/events{/number}", "issues_url": "https://api.github.com/repos/octocat/Hello-World/issues{/number}", "keys_url": "https://api.github.com/repos/octocat/Hello-World/keys{/key_id}", "labels_url": "https://api.github.com/repos/octocat/Hello-World/labels{/name}", "languages_url": "https://api.github.com/repos/octocat/Hello-World/languages", "merges_url": "https://api.github.com/repos/octocat/Hello-World/merges", "milestones_url": "https://api.github.com/repos/octocat/Hello-World/milestones{/number}", "notifications_url": "https://api.github.com/repos/octocat/Hello-World/notifications{?since,all,participating}", "pulls_url": "https://api.github.com/repos/octocat/Hello-World/pulls{/number}", "releases_url": "https://api.github.com/repos/octocat/Hello-World/releases{/id}", "ssh_url": "git@github.com:octocat/Hello-World.git", "stargazers_url": "https://api.github.com/repos/octocat/Hello-World/stargazers", "statuses_url": "https://api.github.com/repos/octocat/Hello-World/statuses/{sha}", "subscribers_url": "https://api.github.com/repos/octocat/Hello-World/subscribers", "subscription_url": "https://api.github.com/repos/octocat/Hello-World/subscription", "tags_url": "https://api.github.com/repos/octocat/Hello-World/tags", "teams_url": "https://api.github.com/repos/octocat/Hello-World/teams", "trees_url": "https://api.github.com/repos/octocat/Hello-World/git/trees{/sha}", "clone_url": "https://github.com/octocat/Hello-World.git", "mirror_url": "git:git.example.com/octocat/Hello-World", "hooks_url": "https://api.github.com/repos/octocat/Hello-World/hooks", "svn_url": "https://svn.github.com/octocat/Hello-World", "homepage": "https://github.com", "language": null, "forks_count": 9, "stargazers_count": 80, "watchers_count": 80, "size": 108, "default_branch": "master", "open_issues_count": 0, "is_template": true, "topics": [ "octocat", "atom", "electron", "api" ], "has_issues": true, "has_projects": true, "has_wiki": true, "has_pages": false, "has_downloads": true, "archived": false, "disabled": false, "visibility": "public", "pushed_at": "2011-01-26T19:06:43Z", "created_at": "2011-01-26T19:01:12Z", "updated_at": "2011-01-26T19:14:43Z", "permissions": { "admin": false, "push": false, "pull": true }, "allow_rebase_merge": true, "template_repository": null, "temp_clone_token": "ABTLWHOULUVAXGTRYU7OC2876QJ2O", "allow_squash_merge": true, "delete_branch_on_merge": true, "allow_merge_commit": true, "subscribers_count": 42, "network_count": 0, "license": { "key": "mit", "name": "MIT License", "url": "https://api.github.com/licenses/mit", "spdx_id": "MIT", "node_id": "MDc6TGljZW5zZW1pdA==", "html_url": "https://github.com/licenses/mit" }, "forks": 1, "open_issues": 1, "watchers": 1 } ] } }, "application-grant-items": { "value": [ { "id": 1, "url": "https://api.github.com/applications/grants/1", "app": { "url": "http://my-github-app.com", "name": "my github app", "client_id": "abcde12345fghij67890" }, "created_at": "2011-09-06T17:26:27Z", "updated_at": "2011-09-06T20:39:23Z", "scopes": [ "public_repo" ] } ] }, "application-grant": { "value": { "id": 1, "url": "https://api.github.com/applications/grants/1", "app": { "url": "http://my-github-app.com", "name": "my github app", "client_id": "abcde12345fghij67890" }, "created_at": "2011-09-06T17:26:27Z", "updated_at": "2011-09-06T20:39:23Z", "scopes": [ "public_repo" ] } }, "authorization-with-user": { "value": { "id": 1, "url": "https://api.github.com/authorizations/1", "scopes": [ "public_repo", "user" ], "token": "ghu_16C7e42F292c6912E7710c838347Ae178B4a", "token_last_eight": "Ae178B4a", "hashed_token": "25f94a2a5c7fbaf499c665bc73d67c1c87e496da8985131633ee0a95819db2e8", "app": { "url": "http://my-github-app.com", "name": "my github app", "client_id": "abcde12345fghij67890" }, "note": "optional note", "note_url": "http://optional/note/url", "updated_at": "2011-09-06T20:39:23Z", "created_at": "2011-09-06T17:26:27Z", "fingerprint": "jklmnop12345678", "expires_at": "2011-09-08T17:26:27Z", "user": { "login": "octocat", "id": 1, "node_id": "MDQ6VXNlcjE=", "avatar_url": "https://github.com/images/error/octocat_happy.gif", "gravatar_id": "", "url": "https://api.github.com/users/octocat", "html_url": "https://github.com/octocat", "followers_url": "https://api.github.com/users/octocat/followers", "following_url": "https://api.github.com/users/octocat/following{/other_user}", "gists_url": "https://api.github.com/users/octocat/gists{/gist_id}", "starred_url": "https://api.github.com/users/octocat/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/octocat/subscriptions", "organizations_url": "https://api.github.com/users/octocat/orgs", "repos_url": "https://api.github.com/users/octocat/repos", "events_url": "https://api.github.com/users/octocat/events{/privacy}", "received_events_url": "https://api.github.com/users/octocat/received_events", "type": "User", "site_admin": false } } }, "scope-token": { "value": { "id": 1, "url": "https://api.github.com/authorizations/1", "scopes": [ ], "token": "ghu_16C7e42F292c6912E7710c838347Ae178B4a", "token_last_eight": "Ae178B4a", "hashed_token": "25f94a2a5c7fbaf499c665bc73d67c1c87e496da8985131633ee0a95819db2e8", "app": { "url": "http://my-github-app.com", "name": "my github app", "client_id": "abcde12345fghij67890" }, "note": "optional note", "note_url": "http://optional/note/url", "updated_at": "2011-09-06T20:39:23Z", "created_at": "2011-09-06T17:26:27Z", "fingerprint": "jklmnop12345678", "expires_at": "2011-09-08T17:26:27Z", "user": { "login": "octocat", "id": 1, "node_id": "MDQ6VXNlcjE=", "avatar_url": "https://github.com/images/error/octocat_happy.gif", "gravatar_id": "", "url": "https://api.github.com/users/octocat", "html_url": "https://github.com/octocat", "followers_url": "https://api.github.com/users/octocat/followers", "following_url": "https://api.github.com/users/octocat/following{/other_user}", "gists_url": "https://api.github.com/users/octocat/gists{/gist_id}", "starred_url": "https://api.github.com/users/octocat/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/octocat/subscriptions", "organizations_url": "https://api.github.com/users/octocat/orgs", "repos_url": "https://api.github.com/users/octocat/repos", "events_url": "https://api.github.com/users/octocat/events{/privacy}", "received_events_url": "https://api.github.com/users/octocat/received_events", "type": "User", "site_admin": false }, "installation": { "permissions": { "metadata": "read", "issues": "write", "contents": "read" }, "repository_selection": "selected", "single_file_name": ".github/workflow.yml", "repositories_url": "https://api.github.com/user/repos", "account": { "login": "octocat", "id": 1, "node_id": "MDQ6VXNlcjE=", "avatar_url": "https://github.com/images/error/octocat_happy.gif", "gravatar_id": "", "url": "https://api.github.com/users/octocat", "html_url": "https://github.com/octocat", "followers_url": "https://api.github.com/users/octocat/followers", "following_url": "https://api.github.com/users/octocat/following{/other_user}", "gists_url": "https://api.github.com/users/octocat/gists{/gist_id}", "starred_url": "https://api.github.com/users/octocat/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/octocat/subscriptions", "organizations_url": "https://api.github.com/users/octocat/orgs", "repos_url": "https://api.github.com/users/octocat/repos", "events_url": "https://api.github.com/users/octocat/events{/privacy}", "received_events_url": "https://api.github.com/users/octocat/received_events", "type": "User", "site_admin": false }, "has_multiple_single_files": false, "single_file_paths": [ ] } } }, "authorization-response-if-returning-an-existing-token-2": { "value": { "id": 1, "url": "https://api.github.com/authorizations/1", "scopes": [ "public_repo" ], "token": "ghu_16C7e42F292c6912E7710c838347Ae178B4a", "token_last_eight": "Ae178B4a", "hashed_token": "25f94a2a5c7fbaf499c665bc73d67c1c87e496da8985131633ee0a95819db2e8", "app": { "url": "http://my-github-app.com", "name": "my github app", "client_id": "abcde12345fghij67890" }, "note": "optional note", "note_url": "http://optional/note/url", "updated_at": "2011-09-06T20:39:23Z", "created_at": "2011-09-06T17:26:27Z", "fingerprint": "" } }, "authorization-response-if-returning-an-existing-token": { "value": { "id": 1, "url": "https://api.github.com/authorizations/1", "scopes": [ "public_repo" ], "token": "ghu_16C7e42F292c6912E7710c838347Ae178B4a", "token_last_eight": "Ae178B4a", "hashed_token": "25f94a2a5c7fbaf499c665bc73d67c1c87e496da8985131633ee0a95819db2e8", "app": { "url": "http://my-github-app.com", "name": "my github app", "client_id": "abcde12345fghij67890" }, "note": "optional note", "note_url": "http://optional/note/url", "updated_at": "2011-09-06T20:39:23Z", "created_at": "2011-09-06T17:26:27Z", "fingerprint": "jklmnop12345678" } }, "authorization-3": { "value": { "id": 1, "url": "https://api.github.com/authorizations/1", "scopes": [ "public_repo" ], "token": "ghu_16C7e42F292c6912E7710c838347Ae178B4a", "token_last_eight": "Ae178B4a", "hashed_token": "25f94a2a5c7fbaf499c665bc73d67c1c87e496da8985131633ee0a95819db2e8", "app": { "url": "http://my-github-app.com", "name": "my github app", "client_id": "abcde12345fghij67890" }, "note": "optional note", "note_url": "http://optional/note/url", "updated_at": "2011-09-06T20:39:23Z", "created_at": "2011-09-06T17:26:27Z", "fingerprint": "jklmnop12345678" } }, "authorization-2": { "value": { "id": 1, "url": "https://api.github.com/authorizations/1", "scopes": [ "public_repo" ], "token": "ghu_16C7e42F292c6912E7710c838347Ae178B4a", "token_last_eight": "Ae178B4a", "hashed_token": "25f94a2a5c7fbaf499c665bc73d67c1c87e496da8985131633ee0a95819db2e8", "app": { "url": "http://my-github-app.com", "name": "my github app", "client_id": "abcde12345fghij67890" }, "note": "optional note", "note_url": "http://optional/note/url", "updated_at": "2011-09-06T20:39:23Z", "created_at": "2011-09-06T17:26:27Z", "fingerprint": "jklmnop12345678" } }, "code-of-conduct-simple-items": { "value": [ { "key": "citizen_code_of_conduct", "name": "Citizen Code of Conduct", "url": "https://api.github.com/codes_of_conduct/citizen_code_of_conduct", "html_url": "http://citizencodeofconduct.org/" }, { "key": "contributor_covenant", "name": "Contributor Covenant", "url": "https://api.github.com/codes_of_conduct/contributor_covenant", "html_url": "https://www.contributor-covenant.org/version/2/0/code_of_conduct/" } ] }, "code-of-conduct": { "value": { "key": "contributor_covenant", "name": "Contributor Covenant", "url": "https://api.github.com/codes_of_conduct/contributor_covenant", "body": "# Contributor Covenant Code of Conduct\n\n## Our Pledge\n\nIn the interest of fostering an open and welcoming environment, we as contributors and maintainers pledge to making participation in our project and our community a harassment-free experience for everyone, regardless of age, body size, disability, ethnicity, gender identity and expression, level of experience, nationality, personal appearance, race, religion, or sexual identity and orientation.\n\n## Our Standards\n\nExamples of behavior that contributes to creating a positive environment include:\n\n* Using welcoming and inclusive language\n* Being respectful of differing viewpoints and experiences\n* Gracefully accepting constructive criticism\n* Focusing on what is best for the community\n* Showing empathy towards other community members\n\nExamples of unacceptable behavior by participants include:\n\n* The use of sexualized language or imagery and unwelcome sexual attention or advances\n* Trolling, insulting/derogatory comments, and personal or political attacks\n* Public or private harassment\n* Publishing others' private information, such as a physical or electronic address, without explicit permission\n* Other conduct which could reasonably be considered inappropriate in a professional setting\n\n## Our Responsibilities\n\nProject maintainers are responsible for clarifying the standards of acceptable behavior and are expected to take appropriate and fair corrective action in response\n to any instances of unacceptable behavior.\n\nProject maintainers have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, or to ban temporarily or permanently any contributor for other behaviors that they deem inappropriate, threatening, offensive, or harmful.\n\n## Scope\n\nThis Code of Conduct applies both within project spaces and in public spaces when an individual is representing the project or its community. Examples of representing a project or community include using an official project e-mail address,\n posting via an official social media account, or acting as an appointed representative at an online or offline event. Representation of a project may be further defined and clarified by project maintainers.\n\n## Enforcement\n\nInstances of abusive, harassing, or otherwise unacceptable behavior may be reported by contacting the project team at [EMAIL]. The project team will review and investigate all complaints, and will respond in a way that it deems appropriate to the circumstances. The project team is obligated to maintain confidentiality with regard to the reporter of an incident. Further details of specific enforcement policies may be posted separately.\n\nProject maintainers who do not follow or enforce the Code of Conduct in good faith may face temporary or permanent repercussions as determined by other members of the project's leadership.\n\n## Attribution\n\nThis Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, available at [http://contributor-covenant.org/version/1/4][version]\n\n[homepage]: http://contributor-covenant.org\n[version]: http://contributor-covenant.org/version/1/4/\n", "html_url": "http://contributor-covenant.org/version/1/4/" } }, "announcement": { "summary": "Default response", "value": { "announcement": "Very **important** announcement about _nothing_.", "expires_at": "2021-01-01T00:00:00.000+00:00" } }, "license-info": { "value": { "seats": 1400, "seats_used": 1316, "seats_available": 84, "kind": "standard", "days_until_expiration": 365, "expire_at": "2016/02/06 12:41:52 -0600" } }, "enterprise-overview": { "value": { "repos": { "total_repos": 212, "root_repos": 194, "fork_repos": 18, "org_repos": 51, "total_pushes": 3082, "total_wikis": 15 }, "hooks": { "total_hooks": 27, "active_hooks": 23, "inactive_hooks": 4 }, "pages": { "total_pages": 36 }, "orgs": { "total_orgs": 33, "disabled_orgs": 0, "total_teams": 60, "total_team_members": 314 }, "users": { "total_users": 254, "admin_users": 45, "suspended_users": 21 }, "pulls": { "total_pulls": 86, "merged_pulls": 60, "mergeable_pulls": 21, "unmergeable_pulls": 3 }, "issues": { "total_issues": 179, "open_issues": 83, "closed_issues": 96 }, "milestones": { "total_milestones": 7, "open_milestones": 6, "closed_milestones": 1 }, "gists": { "total_gists": 178, "private_gists": 151, "public_gists": 25 }, "comments": { "total_commit_comments": 6, "total_gist_comments": 28, "total_issue_comments": 366, "total_pull_request_comments": 30 } } }, "actions-enterprise-permissions": { "value": { "enabled_organizations": "all", "allowed_actions": "selected", "selected_actions_url": "https://api.github.com/enterprises/2/actions/permissions/selected-actions" } }, "organization-targets": { "value": { "total_count": 1, "organizations": [ { "login": "octocat", "id": 161335, "node_id": "MDEwOlJlcG9zaXRvcnkxMjk2MjY5", "url": "https://api.github.com/orgs/octo-org", "repos_url": "https://api.github.com/orgs/octo-org/repos", "events_url": "https://api.github.com/orgs/octo-org/events", "hooks_url": "https://api.github.com/orgs/octo-org/hooks", "issues_url": "https://api.github.com/orgs/octo-org/issues", "members_url": "https://api.github.com/orgs/octo-org/members{/member}", "public_members_url": "https://api.github.com/orgs/octo-org/public_members{/member}", "avatar_url": "https://github.com/images/error/octocat_happy.gif", "description": "A great organization" } ] } }, "selected-actions": { "value": { "github_owned_allowed": true, "verified_allowed": false, "patterns_allowed": [ "monalisa/octocat@*", "docker/*" ] } }, "runner-groups-enterprise": { "value": { "total_count": 3, "runner_groups": [ { "id": 1, "name": "Default", "visibility": "all", "default": true, "runners_url": "https://api.github.com/enterprises/octo-corp/actions/runner_groups/1/runners", "allows_public_repositories": false }, { "id": 2, "name": "octo-runner-group", "visibility": "selected", "default": false, "selected_organizations_url": "https://api.github.com/enterprises/octo-corp/actions/runner_groups/2/organizations", "runners_url": "https://api.github.com/enterprises/octo-corp/actions/runner_groups/2/runners", "allows_public_repositories": true }, { "id": 3, "name": "expensive-hardware", "visibility": "private", "default": false, "runners_url": "https://api.github.com/enterprises/octo-corp/actions/runner_groups/3/runners", "allows_public_repositories": true } ] } }, "runner-group-enterprise": { "value": { "id": 2, "name": "octo-runner-group", "visibility": "selected", "default": false, "selected_organizations_url": "https://api.github.com/enterprises/octo-corp/actions/runner-groups/2/organizations", "runners_url": "https://api.github.com/enterprises/octo-corp/actions/runner-groups/2/runners", "allows_public_repositories": false } }, "runner-group-update-enterprise": { "value": { "id": 2, "name": "Expensive hardware runners", "visibility": "selected", "default": false, "selected_organizations_url": "https://api.github.com/enterprises/octo-corp/actions/runner-groups/2/organizations", "runners_url": "https://api.github.com/enterprises/octo-corp/actions/runner-groups/2/runners", "allows_public_repositories": true } }, "runner-paginated": { "value": { "total_count": 2, "runners": [ { "id": 23, "name": "linux_runner", "os": "linux", "status": "online", "busy": true, "labels": [ { "id": 5, "name": "self-hosted", "type": "read-only" }, { "id": 7, "name": "X64", "type": "read-only" }, { "id": 11, "name": "Linux", "type": "read-only" } ] }, { "id": 24, "name": "mac_runner", "os": "macos", "status": "offline", "busy": false, "labels": [ { "id": 5, "name": "self-hosted", "type": "read-only" }, { "id": 7, "name": "X64", "type": "read-only" }, { "id": 20, "name": "macOS", "type": "read-only" }, { "id": 21, "name": "no-gpu", "type": "custom" } ] } ] } }, "runner-application-items": { "value": [ { "os": "osx", "architecture": "x64", "download_url": "https://github.com/actions/runner/releases/download/v2.164.0/actions-runner-osx-x64-2.164.0.tar.gz", "filename": "actions-runner-osx-x64-2.164.0.tar.gz" }, { "os": "linux", "architecture": "x64", "download_url": "https://github.com/actions/runner/releases/download/v2.164.0/actions-runner-linux-x64-2.164.0.tar.gz", "filename": "actions-runner-linux-x64-2.164.0.tar.gz" }, { "os": "linux", "architecture": "arm", "download_url": "https://github.com/actions/runner/releases/download/v2.164.0/actions-runner-linux-arm-2.164.0.tar.gz", "filename": "actions-runner-linux-arm-2.164.0.tar.gz" }, { "os": "win", "architecture": "x64", "download_url": "https://github.com/actions/runner/releases/download/v2.164.0/actions-runner-win-x64-2.164.0.zip", "filename": "actions-runner-win-x64-2.164.0.zip" }, { "os": "linux", "architecture": "arm64", "download_url": "https://github.com/actions/runner/releases/download/v2.164.0/actions-runner-linux-arm64-2.164.0.tar.gz", "filename": "actions-runner-linux-arm64-2.164.0.tar.gz" } ] }, "authentication-token": { "value": { "token": "LLBF3JGZDX3P5PMEXLND6TS6FCWO6", "expires_at": "2020-01-22T12:13:35.123-08:00" } }, "authentication-token-2": { "value": { "token": "AABF3JGZDX3P5PMEXLND6TS6FCWO6", "expires_at": "2020-01-29T12:13:35.123-08:00" } }, "runner": { "value": { "id": 23, "name": "MBP", "os": "macos", "status": "online", "busy": true, "labels": [ { "id": 5, "name": "self-hosted", "type": "read-only" }, { "id": 7, "name": "X64", "type": "read-only" }, { "id": 20, "name": "macOS", "type": "read-only" }, { "id": 21, "name": "no-gpu", "type": "custom" } ] } }, "feed": { "value": { "timeline_url": "https://github.com/timeline", "user_url": "https://github.com/{user}", "current_user_public_url": "https://github.com/octocat", "current_user_url": "https://github.com/octocat.private?token=abc123", "current_user_actor_url": "https://github.com/octocat.private.actor?token=abc123", "current_user_organization_url": "", "current_user_organization_urls": [ "https://github.com/organizations/github/octocat.private.atom?token=abc123" ], "_links": { "timeline": { "href": "https://github.com/timeline", "type": "application/atom+xml" }, "user": { "href": "https://github.com/{user}", "type": "application/atom+xml" }, "current_user_public": { "href": "https://github.com/octocat", "type": "application/atom+xml" }, "current_user": { "href": "https://github.com/octocat.private?token=abc123", "type": "application/atom+xml" }, "current_user_actor": { "href": "https://github.com/octocat.private.actor?token=abc123", "type": "application/atom+xml" }, "current_user_organization": { "href": "", "type": "" }, "current_user_organizations": [ { "href": "https://github.com/organizations/github/octocat.private.atom?token=abc123", "type": "application/atom+xml" } ] } } }, "base-gist-items": { "value": [ { "url": "https://api.github.com/gists/aa5a315d61ae9438b18d", "forks_url": "https://api.github.com/gists/aa5a315d61ae9438b18d/forks", "commits_url": "https://api.github.com/gists/aa5a315d61ae9438b18d/commits", "id": "aa5a315d61ae9438b18d", "node_id": "MDQ6R2lzdGFhNWEzMTVkNjFhZTk0MzhiMThk", "git_pull_url": "https://gist.github.com/aa5a315d61ae9438b18d.git", "git_push_url": "https://gist.github.com/aa5a315d61ae9438b18d.git", "html_url": "https://gist.github.com/aa5a315d61ae9438b18d", "files": { "hello_world.rb": { "filename": "hello_world.rb", "type": "application/x-ruby", "language": "Ruby", "raw_url": "https://gist.githubusercontent.com/octocat/6cad326836d38bd3a7ae/raw/db9c55113504e46fa076e7df3a04ce592e2e86d8/hello_world.rb", "size": 167 } }, "public": true, "created_at": "2010-04-14T02:15:15Z", "updated_at": "2011-06-20T11:34:15Z", "description": "Hello World Examples", "comments": 0, "user": null, "comments_url": "https://api.github.com/gists/aa5a315d61ae9438b18d/comments/", "owner": { "login": "octocat", "id": 1, "node_id": "MDQ6VXNlcjE=", "avatar_url": "https://github.com/images/error/octocat_happy.gif", "gravatar_id": "", "url": "https://api.github.com/users/octocat", "html_url": "https://github.com/octocat", "followers_url": "https://api.github.com/users/octocat/followers", "following_url": "https://api.github.com/users/octocat/following{/other_user}", "gists_url": "https://api.github.com/users/octocat/gists{/gist_id}", "starred_url": "https://api.github.com/users/octocat/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/octocat/subscriptions", "organizations_url": "https://api.github.com/users/octocat/orgs", "repos_url": "https://api.github.com/users/octocat/repos", "events_url": "https://api.github.com/users/octocat/events{/privacy}", "received_events_url": "https://api.github.com/users/octocat/received_events", "type": "User", "site_admin": false }, "truncated": false } ] }, "gist": { "value": { "url": "https://api.github.com/gists/aa5a315d61ae9438b18d", "forks_url": "https://api.github.com/gists/aa5a315d61ae9438b18d/forks", "commits_url": "https://api.github.com/gists/aa5a315d61ae9438b18d/commits", "id": "aa5a315d61ae9438b18d", "node_id": "MDQ6R2lzdGFhNWEzMTVkNjFhZTk0MzhiMThk", "git_pull_url": "https://gist.github.com/aa5a315d61ae9438b18d.git", "git_push_url": "https://gist.github.com/aa5a315d61ae9438b18d.git", "html_url": "https://gist.github.com/aa5a315d61ae9438b18d", "created_at": "2010-04-14T02:15:15Z", "updated_at": "2011-06-20T11:34:15Z", "description": "Hello World Examples", "comments": 0, "comments_url": "https://api.github.com/gists/aa5a315d61ae9438b18d/comments/" } }, "gist-comment-items": { "value": [ { "id": 1, "node_id": "MDExOkdpc3RDb21tZW50MQ==", "url": "https://api.github.com/gists/a6db0bec360bb87e9418/comments/1", "body": "Just commenting for the sake of commenting", "user": { "login": "octocat", "id": 1, "node_id": "MDQ6VXNlcjE=", "avatar_url": "https://github.com/images/error/octocat_happy.gif", "gravatar_id": "", "url": "https://api.github.com/users/octocat", "html_url": "https://github.com/octocat", "followers_url": "https://api.github.com/users/octocat/followers", "following_url": "https://api.github.com/users/octocat/following{/other_user}", "gists_url": "https://api.github.com/users/octocat/gists{/gist_id}", "starred_url": "https://api.github.com/users/octocat/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/octocat/subscriptions", "organizations_url": "https://api.github.com/users/octocat/orgs", "repos_url": "https://api.github.com/users/octocat/repos", "events_url": "https://api.github.com/users/octocat/events{/privacy}", "received_events_url": "https://api.github.com/users/octocat/received_events", "type": "User", "site_admin": false }, "created_at": "2011-04-18T23:23:56Z", "updated_at": "2011-04-18T23:23:56Z", "author_association": "COLLABORATOR" } ] }, "gist-comment": { "value": { "id": 1, "node_id": "MDExOkdpc3RDb21tZW50MQ==", "url": "https://api.github.com/gists/a6db0bec360bb87e9418/comments/1", "body": "Just commenting for the sake of commenting", "user": { "login": "octocat", "id": 1, "node_id": "MDQ6VXNlcjE=", "avatar_url": "https://github.com/images/error/octocat_happy.gif", "gravatar_id": "", "url": "https://api.github.com/users/octocat", "html_url": "https://github.com/octocat", "followers_url": "https://api.github.com/users/octocat/followers", "following_url": "https://api.github.com/users/octocat/following{/other_user}", "gists_url": "https://api.github.com/users/octocat/gists{/gist_id}", "starred_url": "https://api.github.com/users/octocat/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/octocat/subscriptions", "organizations_url": "https://api.github.com/users/octocat/orgs", "repos_url": "https://api.github.com/users/octocat/repos", "events_url": "https://api.github.com/users/octocat/events{/privacy}", "received_events_url": "https://api.github.com/users/octocat/received_events", "type": "User", "site_admin": false }, "created_at": "2011-04-18T23:23:56Z", "updated_at": "2011-04-18T23:23:56Z", "author_association": "COLLABORATOR" } }, "gist-commit-items": { "value": [ { "url": "https://api.github.com/gists/aa5a315d61ae9438b18d/57a7f021a713b1c5a6a199b54cc514735d2d462f", "version": "57a7f021a713b1c5a6a199b54cc514735d2d462f", "user": { "login": "octocat", "id": 1, "node_id": "MDQ6VXNlcjE=", "avatar_url": "https://github.com/images/error/octocat_happy.gif", "gravatar_id": "", "url": "https://api.github.com/users/octocat", "html_url": "https://github.com/octocat", "followers_url": "https://api.github.com/users/octocat/followers", "following_url": "https://api.github.com/users/octocat/following{/other_user}", "gists_url": "https://api.github.com/users/octocat/gists{/gist_id}", "starred_url": "https://api.github.com/users/octocat/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/octocat/subscriptions", "organizations_url": "https://api.github.com/users/octocat/orgs", "repos_url": "https://api.github.com/users/octocat/repos", "events_url": "https://api.github.com/users/octocat/events{/privacy}", "received_events_url": "https://api.github.com/users/octocat/received_events", "type": "User", "site_admin": false }, "change_status": { "deletions": 0, "additions": 180, "total": 180 }, "committed_at": "2010-04-14T02:15:15Z" } ] }, "gist-fork-items": { "value": [ { "url": "https://api.github.com/gists/aa5a315d61ae9438b18d", "forks_url": "https://api.github.com/gists/aa5a315d61ae9438b18d/forks", "commits_url": "https://api.github.com/gists/aa5a315d61ae9438b18d/commits", "id": "aa5a315d61ae9438b18d", "node_id": "MDQ6R2lzdGFhNWEzMTVkNjFhZTk0MzhiMThk", "git_pull_url": "https://gist.github.com/aa5a315d61ae9438b18d.git", "git_push_url": "https://gist.github.com/aa5a315d61ae9438b18d.git", "html_url": "https://gist.github.com/aa5a315d61ae9438b18d", "files": { "hello_world.rb": { "filename": "hello_world.rb", "type": "application/x-ruby", "language": "Ruby", "raw_url": "https://gist.githubusercontent.com/octocat/6cad326836d38bd3a7ae/raw/db9c55113504e46fa076e7df3a04ce592e2e86d8/hello_world.rb", "size": 167 } }, "public": true, "created_at": "2010-04-14T02:15:15Z", "updated_at": "2011-06-20T11:34:15Z", "description": "Hello World Examples", "comments": 1, "user": null, "comments_url": "https://api.github.com/gists/aa5a315d61ae9438b18d/comments/", "owner": { "login": "octocat", "id": 1, "node_id": "MDQ6VXNlcjE=", "avatar_url": "https://github.com/images/error/octocat_happy.gif", "gravatar_id": "", "url": "https://api.github.com/users/octocat", "html_url": "https://github.com/octocat", "followers_url": "https://api.github.com/users/octocat/followers", "following_url": "https://api.github.com/users/octocat/following{/other_user}", "gists_url": "https://api.github.com/users/octocat/gists{/gist_id}", "starred_url": "https://api.github.com/users/octocat/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/octocat/subscriptions", "organizations_url": "https://api.github.com/users/octocat/orgs", "repos_url": "https://api.github.com/users/octocat/repos", "events_url": "https://api.github.com/users/octocat/events{/privacy}", "received_events_url": "https://api.github.com/users/octocat/received_events", "type": "User", "site_admin": false } } ] }, "base-gist": { "value": { "url": "https://api.github.com/gists/aa5a315d61ae9438b18d", "forks_url": "https://api.github.com/gists/aa5a315d61ae9438b18d/forks", "commits_url": "https://api.github.com/gists/aa5a315d61ae9438b18d/commits", "id": "aa5a315d61ae9438b18d", "node_id": "MDQ6R2lzdGFhNWEzMTVkNjFhZTk0MzhiMThk", "git_pull_url": "https://gist.github.com/aa5a315d61ae9438b18d.git", "git_push_url": "https://gist.github.com/aa5a315d61ae9438b18d.git", "html_url": "https://gist.github.com/aa5a315d61ae9438b18d", "files": { "hello_world.rb": { "filename": "hello_world.rb", "type": "application/x-ruby", "language": "Ruby", "raw_url": "https://gist.githubusercontent.com/octocat/6cad326836d38bd3a7ae/raw/db9c55113504e46fa076e7df3a04ce592e2e86d8/hello_world.rb", "size": 167 } }, "public": true, "created_at": "2010-04-14T02:15:15Z", "updated_at": "2011-06-20T11:34:15Z", "description": "Hello World Examples", "comments": 0, "user": null, "comments_url": "https://api.github.com/gists/aa5a315d61ae9438b18d/comments/", "owner": { "login": "octocat", "id": 1, "node_id": "MDQ6VXNlcjE=", "avatar_url": "https://github.com/images/error/octocat_happy.gif", "gravatar_id": "", "url": "https://api.github.com/users/octocat", "html_url": "https://github.com/octocat", "followers_url": "https://api.github.com/users/octocat/followers", "following_url": "https://api.github.com/users/octocat/following{/other_user}", "gists_url": "https://api.github.com/users/octocat/gists{/gist_id}", "starred_url": "https://api.github.com/users/octocat/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/octocat/subscriptions", "organizations_url": "https://api.github.com/users/octocat/orgs", "repos_url": "https://api.github.com/users/octocat/repos", "events_url": "https://api.github.com/users/octocat/events{/privacy}", "received_events_url": "https://api.github.com/users/octocat/received_events", "type": "User", "site_admin": false }, "truncated": false } }, "gitignore-template": { "value": { "name": "C", "source": "# Object files\n*.o\n\n# Libraries\n*.lib\n*.a\n\n# Shared objects (inc. Windows DLLs)\n*.dll\n*.so\n*.so.*\n*.dylib\n\n# Executables\n*.exe\n*.out\n*.app\n" } }, "repository-paginated-2": { "value": { "total_count": 1, "repositories": [ { "id": 1296269, "node_id": "MDEwOlJlcG9zaXRvcnkxMjk2MjY5", "name": "Hello-World", "full_name": "octocat/Hello-World", "owner": { "login": "octocat", "id": 1, "node_id": "MDQ6VXNlcjE=", "avatar_url": "https://github.com/images/error/octocat_happy.gif", "gravatar_id": "", "url": "https://api.github.com/users/octocat", "html_url": "https://github.com/octocat", "followers_url": "https://api.github.com/users/octocat/followers", "following_url": "https://api.github.com/users/octocat/following{/other_user}", "gists_url": "https://api.github.com/users/octocat/gists{/gist_id}", "starred_url": "https://api.github.com/users/octocat/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/octocat/subscriptions", "organizations_url": "https://api.github.com/users/octocat/orgs", "repos_url": "https://api.github.com/users/octocat/repos", "events_url": "https://api.github.com/users/octocat/events{/privacy}", "received_events_url": "https://api.github.com/users/octocat/received_events", "type": "User", "site_admin": false }, "private": false, "html_url": "https://github.com/octocat/Hello-World", "description": "This your first repo!", "fork": false, "url": "https://api.github.com/repos/octocat/Hello-World", "archive_url": "https://api.github.com/repos/octocat/Hello-World/{archive_format}{/ref}", "assignees_url": "https://api.github.com/repos/octocat/Hello-World/assignees{/user}", "blobs_url": "https://api.github.com/repos/octocat/Hello-World/git/blobs{/sha}", "branches_url": "https://api.github.com/repos/octocat/Hello-World/branches{/branch}", "collaborators_url": "https://api.github.com/repos/octocat/Hello-World/collaborators{/collaborator}", "comments_url": "https://api.github.com/repos/octocat/Hello-World/comments{/number}", "commits_url": "https://api.github.com/repos/octocat/Hello-World/commits{/sha}", "compare_url": "https://api.github.com/repos/octocat/Hello-World/compare/{base}...{head}", "contents_url": "https://api.github.com/repos/octocat/Hello-World/contents/{+path}", "contributors_url": "https://api.github.com/repos/octocat/Hello-World/contributors", "deployments_url": "https://api.github.com/repos/octocat/Hello-World/deployments", "downloads_url": "https://api.github.com/repos/octocat/Hello-World/downloads", "events_url": "https://api.github.com/repos/octocat/Hello-World/events", "forks_url": "https://api.github.com/repos/octocat/Hello-World/forks", "git_commits_url": "https://api.github.com/repos/octocat/Hello-World/git/commits{/sha}", "git_refs_url": "https://api.github.com/repos/octocat/Hello-World/git/refs{/sha}", "git_tags_url": "https://api.github.com/repos/octocat/Hello-World/git/tags{/sha}", "git_url": "git:github.com/octocat/Hello-World.git", "issue_comment_url": "https://api.github.com/repos/octocat/Hello-World/issues/comments{/number}", "issue_events_url": "https://api.github.com/repos/octocat/Hello-World/issues/events{/number}", "issues_url": "https://api.github.com/repos/octocat/Hello-World/issues{/number}", "keys_url": "https://api.github.com/repos/octocat/Hello-World/keys{/key_id}", "labels_url": "https://api.github.com/repos/octocat/Hello-World/labels{/name}", "languages_url": "https://api.github.com/repos/octocat/Hello-World/languages", "merges_url": "https://api.github.com/repos/octocat/Hello-World/merges", "milestones_url": "https://api.github.com/repos/octocat/Hello-World/milestones{/number}", "notifications_url": "https://api.github.com/repos/octocat/Hello-World/notifications{?since,all,participating}", "pulls_url": "https://api.github.com/repos/octocat/Hello-World/pulls{/number}", "releases_url": "https://api.github.com/repos/octocat/Hello-World/releases{/id}", "ssh_url": "git@github.com:octocat/Hello-World.git", "stargazers_url": "https://api.github.com/repos/octocat/Hello-World/stargazers", "statuses_url": "https://api.github.com/repos/octocat/Hello-World/statuses/{sha}", "subscribers_url": "https://api.github.com/repos/octocat/Hello-World/subscribers", "subscription_url": "https://api.github.com/repos/octocat/Hello-World/subscription", "tags_url": "https://api.github.com/repos/octocat/Hello-World/tags", "teams_url": "https://api.github.com/repos/octocat/Hello-World/teams", "trees_url": "https://api.github.com/repos/octocat/Hello-World/git/trees{/sha}", "clone_url": "https://github.com/octocat/Hello-World.git", "mirror_url": "git:git.example.com/octocat/Hello-World", "hooks_url": "https://api.github.com/repos/octocat/Hello-World/hooks", "svn_url": "https://svn.github.com/octocat/Hello-World", "homepage": "https://github.com", "language": null, "forks_count": 9, "stargazers_count": 80, "watchers_count": 80, "size": 108, "default_branch": "master", "open_issues_count": 0, "is_template": true, "topics": [ "octocat", "atom", "electron", "api" ], "has_issues": true, "has_projects": true, "has_wiki": true, "has_pages": false, "has_downloads": true, "archived": false, "disabled": false, "visibility": "public", "pushed_at": "2011-01-26T19:06:43Z", "created_at": "2011-01-26T19:01:12Z", "updated_at": "2011-01-26T19:14:43Z", "allow_rebase_merge": true, "template_repository": null, "temp_clone_token": "ABTLWHOULUVAXGTRYU7OC2876QJ2O", "allow_squash_merge": true, "delete_branch_on_merge": true, "allow_merge_commit": true, "subscribers_count": 42, "network_count": 0, "license": { "key": "mit", "name": "MIT License", "url": "https://api.github.com/licenses/mit", "spdx_id": "MIT", "node_id": "MDc6TGljZW5zZW1pdA==", "html_url": "https://github.com/licenses/mit" }, "forks": 1, "open_issues": 1, "watchers": 1 } ] } }, "issue-with-repo-items": { "value": [ { "id": 1, "node_id": "MDU6SXNzdWUx", "url": "https://api.github.com/repos/octocat/Hello-World/issues/1347", "repository_url": "https://api.github.com/repos/octocat/Hello-World", "labels_url": "https://api.github.com/repos/octocat/Hello-World/issues/1347/labels{/name}", "comments_url": "https://api.github.com/repos/octocat/Hello-World/issues/1347/comments", "events_url": "https://api.github.com/repos/octocat/Hello-World/issues/1347/events", "html_url": "https://github.com/octocat/Hello-World/issues/1347", "number": 1347, "state": "open", "title": "Found a bug", "body": "I'm having a problem with this.", "user": { "login": "octocat", "id": 1, "node_id": "MDQ6VXNlcjE=", "avatar_url": "https://github.com/images/error/octocat_happy.gif", "gravatar_id": "", "url": "https://api.github.com/users/octocat", "html_url": "https://github.com/octocat", "followers_url": "https://api.github.com/users/octocat/followers", "following_url": "https://api.github.com/users/octocat/following{/other_user}", "gists_url": "https://api.github.com/users/octocat/gists{/gist_id}", "starred_url": "https://api.github.com/users/octocat/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/octocat/subscriptions", "organizations_url": "https://api.github.com/users/octocat/orgs", "repos_url": "https://api.github.com/users/octocat/repos", "events_url": "https://api.github.com/users/octocat/events{/privacy}", "received_events_url": "https://api.github.com/users/octocat/received_events", "type": "User", "site_admin": false }, "labels": [ { "id": 208045946, "node_id": "MDU6TGFiZWwyMDgwNDU5NDY=", "url": "https://api.github.com/repos/octocat/Hello-World/labels/bug", "name": "bug", "description": "Something isn't working", "color": "f29513", "default": true } ], "assignee": { "login": "octocat", "id": 1, "node_id": "MDQ6VXNlcjE=", "avatar_url": "https://github.com/images/error/octocat_happy.gif", "gravatar_id": "", "url": "https://api.github.com/users/octocat", "html_url": "https://github.com/octocat", "followers_url": "https://api.github.com/users/octocat/followers", "following_url": "https://api.github.com/users/octocat/following{/other_user}", "gists_url": "https://api.github.com/users/octocat/gists{/gist_id}", "starred_url": "https://api.github.com/users/octocat/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/octocat/subscriptions", "organizations_url": "https://api.github.com/users/octocat/orgs", "repos_url": "https://api.github.com/users/octocat/repos", "events_url": "https://api.github.com/users/octocat/events{/privacy}", "received_events_url": "https://api.github.com/users/octocat/received_events", "type": "User", "site_admin": false }, "assignees": [ { "login": "octocat", "id": 1, "node_id": "MDQ6VXNlcjE=", "avatar_url": "https://github.com/images/error/octocat_happy.gif", "gravatar_id": "", "url": "https://api.github.com/users/octocat", "html_url": "https://github.com/octocat", "followers_url": "https://api.github.com/users/octocat/followers", "following_url": "https://api.github.com/users/octocat/following{/other_user}", "gists_url": "https://api.github.com/users/octocat/gists{/gist_id}", "starred_url": "https://api.github.com/users/octocat/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/octocat/subscriptions", "organizations_url": "https://api.github.com/users/octocat/orgs", "repos_url": "https://api.github.com/users/octocat/repos", "events_url": "https://api.github.com/users/octocat/events{/privacy}", "received_events_url": "https://api.github.com/users/octocat/received_events", "type": "User", "site_admin": false } ], "milestone": { "url": "https://api.github.com/repos/octocat/Hello-World/milestones/1", "html_url": "https://github.com/octocat/Hello-World/milestones/v1.0", "labels_url": "https://api.github.com/repos/octocat/Hello-World/milestones/1/labels", "id": 1002604, "node_id": "MDk6TWlsZXN0b25lMTAwMjYwNA==", "number": 1, "state": "open", "title": "v1.0", "description": "Tracking milestone for version 1.0", "creator": { "login": "octocat", "id": 1, "node_id": "MDQ6VXNlcjE=", "avatar_url": "https://github.com/images/error/octocat_happy.gif", "gravatar_id": "", "url": "https://api.github.com/users/octocat", "html_url": "https://github.com/octocat", "followers_url": "https://api.github.com/users/octocat/followers", "following_url": "https://api.github.com/users/octocat/following{/other_user}", "gists_url": "https://api.github.com/users/octocat/gists{/gist_id}", "starred_url": "https://api.github.com/users/octocat/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/octocat/subscriptions", "organizations_url": "https://api.github.com/users/octocat/orgs", "repos_url": "https://api.github.com/users/octocat/repos", "events_url": "https://api.github.com/users/octocat/events{/privacy}", "received_events_url": "https://api.github.com/users/octocat/received_events", "type": "User", "site_admin": false }, "open_issues": 4, "closed_issues": 8, "created_at": "2011-04-10T20:09:31Z", "updated_at": "2014-03-03T18:58:10Z", "closed_at": "2013-02-12T13:22:01Z", "due_on": "2012-10-09T23:39:01Z" }, "locked": true, "active_lock_reason": "too heated", "comments": 0, "pull_request": { "url": "https://api.github.com/repos/octocat/Hello-World/pulls/1347", "html_url": "https://github.com/octocat/Hello-World/pull/1347", "diff_url": "https://github.com/octocat/Hello-World/pull/1347.diff", "patch_url": "https://github.com/octocat/Hello-World/pull/1347.patch" }, "closed_at": null, "created_at": "2011-04-22T13:33:48Z", "updated_at": "2011-04-22T13:33:48Z", "repository": { "id": 1296269, "node_id": "MDEwOlJlcG9zaXRvcnkxMjk2MjY5", "name": "Hello-World", "full_name": "octocat/Hello-World", "owner": { "login": "octocat", "id": 1, "node_id": "MDQ6VXNlcjE=", "avatar_url": "https://github.com/images/error/octocat_happy.gif", "gravatar_id": "", "url": "https://api.github.com/users/octocat", "html_url": "https://github.com/octocat", "followers_url": "https://api.github.com/users/octocat/followers", "following_url": "https://api.github.com/users/octocat/following{/other_user}", "gists_url": "https://api.github.com/users/octocat/gists{/gist_id}", "starred_url": "https://api.github.com/users/octocat/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/octocat/subscriptions", "organizations_url": "https://api.github.com/users/octocat/orgs", "repos_url": "https://api.github.com/users/octocat/repos", "events_url": "https://api.github.com/users/octocat/events{/privacy}", "received_events_url": "https://api.github.com/users/octocat/received_events", "type": "User", "site_admin": false }, "private": false, "html_url": "https://github.com/octocat/Hello-World", "description": "This your first repo!", "fork": false, "url": "https://api.github.com/repos/octocat/Hello-World", "archive_url": "https://api.github.com/repos/octocat/Hello-World/{archive_format}{/ref}", "assignees_url": "https://api.github.com/repos/octocat/Hello-World/assignees{/user}", "blobs_url": "https://api.github.com/repos/octocat/Hello-World/git/blobs{/sha}", "branches_url": "https://api.github.com/repos/octocat/Hello-World/branches{/branch}", "collaborators_url": "https://api.github.com/repos/octocat/Hello-World/collaborators{/collaborator}", "comments_url": "https://api.github.com/repos/octocat/Hello-World/comments{/number}", "commits_url": "https://api.github.com/repos/octocat/Hello-World/commits{/sha}", "compare_url": "https://api.github.com/repos/octocat/Hello-World/compare/{base}...{head}", "contents_url": "https://api.github.com/repos/octocat/Hello-World/contents/{+path}", "contributors_url": "https://api.github.com/repos/octocat/Hello-World/contributors", "deployments_url": "https://api.github.com/repos/octocat/Hello-World/deployments", "downloads_url": "https://api.github.com/repos/octocat/Hello-World/downloads", "events_url": "https://api.github.com/repos/octocat/Hello-World/events", "forks_url": "https://api.github.com/repos/octocat/Hello-World/forks", "git_commits_url": "https://api.github.com/repos/octocat/Hello-World/git/commits{/sha}", "git_refs_url": "https://api.github.com/repos/octocat/Hello-World/git/refs{/sha}", "git_tags_url": "https://api.github.com/repos/octocat/Hello-World/git/tags{/sha}", "git_url": "git:github.com/octocat/Hello-World.git", "issue_comment_url": "https://api.github.com/repos/octocat/Hello-World/issues/comments{/number}", "issue_events_url": "https://api.github.com/repos/octocat/Hello-World/issues/events{/number}", "issues_url": "https://api.github.com/repos/octocat/Hello-World/issues{/number}", "keys_url": "https://api.github.com/repos/octocat/Hello-World/keys{/key_id}", "labels_url": "https://api.github.com/repos/octocat/Hello-World/labels{/name}", "languages_url": "https://api.github.com/repos/octocat/Hello-World/languages", "merges_url": "https://api.github.com/repos/octocat/Hello-World/merges", "milestones_url": "https://api.github.com/repos/octocat/Hello-World/milestones{/number}", "notifications_url": "https://api.github.com/repos/octocat/Hello-World/notifications{?since,all,participating}", "pulls_url": "https://api.github.com/repos/octocat/Hello-World/pulls{/number}", "releases_url": "https://api.github.com/repos/octocat/Hello-World/releases{/id}", "ssh_url": "git@github.com:octocat/Hello-World.git", "stargazers_url": "https://api.github.com/repos/octocat/Hello-World/stargazers", "statuses_url": "https://api.github.com/repos/octocat/Hello-World/statuses/{sha}", "subscribers_url": "https://api.github.com/repos/octocat/Hello-World/subscribers", "subscription_url": "https://api.github.com/repos/octocat/Hello-World/subscription", "tags_url": "https://api.github.com/repos/octocat/Hello-World/tags", "teams_url": "https://api.github.com/repos/octocat/Hello-World/teams", "trees_url": "https://api.github.com/repos/octocat/Hello-World/git/trees{/sha}", "clone_url": "https://github.com/octocat/Hello-World.git", "mirror_url": "git:git.example.com/octocat/Hello-World", "hooks_url": "https://api.github.com/repos/octocat/Hello-World/hooks", "svn_url": "https://svn.github.com/octocat/Hello-World", "homepage": "https://github.com", "language": null, "forks_count": 9, "stargazers_count": 80, "watchers_count": 80, "size": 108, "default_branch": "master", "open_issues_count": 0, "is_template": true, "topics": [ "octocat", "atom", "electron", "api" ], "has_issues": true, "has_projects": true, "has_wiki": true, "has_pages": false, "has_downloads": true, "archived": false, "disabled": false, "visibility": "public", "pushed_at": "2011-01-26T19:06:43Z", "created_at": "2011-01-26T19:01:12Z", "updated_at": "2011-01-26T19:14:43Z", "permissions": { "admin": false, "push": false, "pull": true }, "allow_rebase_merge": true, "template_repository": null, "temp_clone_token": "ABTLWHOULUVAXGTRYU7OC2876QJ2O", "allow_squash_merge": true, "delete_branch_on_merge": true, "allow_merge_commit": true, "subscribers_count": 42, "network_count": 0, "license": { "key": "mit", "name": "MIT License", "url": "https://api.github.com/licenses/mit", "spdx_id": "MIT", "node_id": "MDc6TGljZW5zZW1pdA==", "html_url": "https://github.com/licenses/mit" }, "forks": 1, "open_issues": 1, "watchers": 1 }, "author_association": "COLLABORATOR" } ] }, "license-simple-items": { "value": [ { "key": "mit", "name": "MIT License", "spdx_id": "MIT", "url": "https://api.github.com/licenses/mit", "node_id": "MDc6TGljZW5zZW1pdA==" }, { "key": "lgpl-3.0", "name": "GNU Lesser General Public License v3.0", "spdx_id": "LGPL-3.0", "url": "https://api.github.com/licenses/lgpl-3.0", "node_id": "MDc6TGljZW5zZW1pdA==" }, { "key": "mpl-2.0", "name": "Mozilla Public License 2.0", "spdx_id": "MPL-2.0", "url": "https://api.github.com/licenses/mpl-2.0", "node_id": "MDc6TGljZW5zZW1pdA==" }, { "key": "agpl-3.0", "name": "GNU Affero General Public License v3.0", "spdx_id": "AGPL-3.0", "url": "https://api.github.com/licenses/agpl-3.0", "node_id": "MDc6TGljZW5zZW1pdA==" }, { "key": "unlicense", "name": "The Unlicense", "spdx_id": "Unlicense", "url": "https://api.github.com/licenses/unlicense", "node_id": "MDc6TGljZW5zZW1pdA==" }, { "key": "apache-2.0", "name": "Apache License 2.0", "spdx_id": "Apache-2.0", "url": "https://api.github.com/licenses/apache-2.0", "node_id": "MDc6TGljZW5zZW1pdA==" }, { "key": "gpl-3.0", "name": "GNU General Public License v3.0", "spdx_id": "GPL-3.0", "url": "https://api.github.com/licenses/gpl-3.0", "node_id": "MDc6TGljZW5zZW1pdA==" } ] }, "license": { "value": { "key": "mit", "name": "MIT License", "spdx_id": "MIT", "url": "https://api.github.com/licenses/mit", "node_id": "MDc6TGljZW5zZW1pdA==", "html_url": "http://choosealicense.com/licenses/mit/", "description": "A permissive license that is short and to the point. It lets people do anything with your code with proper attribution and without warranty.", "implementation": "Create a text file (typically named LICENSE or LICENSE.txt) in the root of your source code and copy the text of the license into the file. Replace [year] with the current year and [fullname] with the name (or names) of the copyright holders.", "permissions": [ "commercial-use", "modifications", "distribution", "sublicense", "private-use" ], "conditions": [ "include-copyright" ], "limitations": [ "no-liability" ], "body": "\n\nThe MIT License (MIT)\n\nCopyright (c) [year] [fullname]\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n", "featured": true } }, "api-overview": { "value": { "verifiable_password_authentication": true, "packages": [ "192.30.252.0/22" ], "dependabot": [ "54.158.161.132" ], "installed_version": "3.0.0" } }, "thread-items": { "value": [ { "id": "1", "repository": { "id": 1296269, "node_id": "MDEwOlJlcG9zaXRvcnkxMjk2MjY5", "name": "Hello-World", "full_name": "octocat/Hello-World", "owner": { "login": "octocat", "id": 1, "node_id": "MDQ6VXNlcjE=", "avatar_url": "https://github.com/images/error/octocat_happy.gif", "gravatar_id": "", "url": "https://api.github.com/users/octocat", "html_url": "https://github.com/octocat", "followers_url": "https://api.github.com/users/octocat/followers", "following_url": "https://api.github.com/users/octocat/following{/other_user}", "gists_url": "https://api.github.com/users/octocat/gists{/gist_id}", "starred_url": "https://api.github.com/users/octocat/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/octocat/subscriptions", "organizations_url": "https://api.github.com/users/octocat/orgs", "repos_url": "https://api.github.com/users/octocat/repos", "events_url": "https://api.github.com/users/octocat/events{/privacy}", "received_events_url": "https://api.github.com/users/octocat/received_events", "type": "User", "site_admin": false }, "private": false, "html_url": "https://github.com/octocat/Hello-World", "description": "This your first repo!", "fork": false, "url": "https://api.github.com/repos/octocat/Hello-World", "archive_url": "https://api.github.com/repos/octocat/Hello-World/{archive_format}{/ref}", "assignees_url": "https://api.github.com/repos/octocat/Hello-World/assignees{/user}", "blobs_url": "https://api.github.com/repos/octocat/Hello-World/git/blobs{/sha}", "branches_url": "https://api.github.com/repos/octocat/Hello-World/branches{/branch}", "collaborators_url": "https://api.github.com/repos/octocat/Hello-World/collaborators{/collaborator}", "comments_url": "https://api.github.com/repos/octocat/Hello-World/comments{/number}", "commits_url": "https://api.github.com/repos/octocat/Hello-World/commits{/sha}", "compare_url": "https://api.github.com/repos/octocat/Hello-World/compare/{base}...{head}", "contents_url": "https://api.github.com/repos/octocat/Hello-World/contents/{+path}", "contributors_url": "https://api.github.com/repos/octocat/Hello-World/contributors", "deployments_url": "https://api.github.com/repos/octocat/Hello-World/deployments", "downloads_url": "https://api.github.com/repos/octocat/Hello-World/downloads", "events_url": "https://api.github.com/repos/octocat/Hello-World/events", "forks_url": "https://api.github.com/repos/octocat/Hello-World/forks", "git_commits_url": "https://api.github.com/repos/octocat/Hello-World/git/commits{/sha}", "git_refs_url": "https://api.github.com/repos/octocat/Hello-World/git/refs{/sha}", "git_tags_url": "https://api.github.com/repos/octocat/Hello-World/git/tags{/sha}", "git_url": "git:github.com/octocat/Hello-World.git", "issue_comment_url": "https://api.github.com/repos/octocat/Hello-World/issues/comments{/number}", "issue_events_url": "https://api.github.com/repos/octocat/Hello-World/issues/events{/number}", "issues_url": "https://api.github.com/repos/octocat/Hello-World/issues{/number}", "keys_url": "https://api.github.com/repos/octocat/Hello-World/keys{/key_id}", "labels_url": "https://api.github.com/repos/octocat/Hello-World/labels{/name}", "languages_url": "https://api.github.com/repos/octocat/Hello-World/languages", "merges_url": "https://api.github.com/repos/octocat/Hello-World/merges", "milestones_url": "https://api.github.com/repos/octocat/Hello-World/milestones{/number}", "notifications_url": "https://api.github.com/repos/octocat/Hello-World/notifications{?since,all,participating}", "pulls_url": "https://api.github.com/repos/octocat/Hello-World/pulls{/number}", "releases_url": "https://api.github.com/repos/octocat/Hello-World/releases{/id}", "ssh_url": "git@github.com:octocat/Hello-World.git", "stargazers_url": "https://api.github.com/repos/octocat/Hello-World/stargazers", "statuses_url": "https://api.github.com/repos/octocat/Hello-World/statuses/{sha}", "subscribers_url": "https://api.github.com/repos/octocat/Hello-World/subscribers", "subscription_url": "https://api.github.com/repos/octocat/Hello-World/subscription", "tags_url": "https://api.github.com/repos/octocat/Hello-World/tags", "teams_url": "https://api.github.com/repos/octocat/Hello-World/teams", "trees_url": "https://api.github.com/repos/octocat/Hello-World/git/trees{/sha}", "hooks_url": "http://api.github.com/repos/octocat/Hello-World/hooks" }, "subject": { "title": "Greetings", "url": "https://api.github.com/repos/octokit/octokit.rb/issues/123", "latest_comment_url": "https://api.github.com/repos/octokit/octokit.rb/issues/comments/123", "type": "Issue" }, "reason": "subscribed", "unread": true, "updated_at": "2014-11-07T22:01:45Z", "last_read_at": "2014-11-07T22:01:45Z", "url": "https://api.github.com/notifications/threads/1", "subscription_url": "https://api.github.com/notifications/threads/1/subscription" } ] }, "thread": { "value": { "id": "1", "repository": { "id": 1296269, "node_id": "MDEwOlJlcG9zaXRvcnkxMjk2MjY5", "name": "Hello-World", "full_name": "octocat/Hello-World", "owner": { "login": "octocat", "id": 1, "node_id": "MDQ6VXNlcjE=", "avatar_url": "https://github.com/images/error/octocat_happy.gif", "gravatar_id": "", "url": "https://api.github.com/users/octocat", "html_url": "https://github.com/octocat", "followers_url": "https://api.github.com/users/octocat/followers", "following_url": "https://api.github.com/users/octocat/following{/other_user}", "gists_url": "https://api.github.com/users/octocat/gists{/gist_id}", "starred_url": "https://api.github.com/users/octocat/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/octocat/subscriptions", "organizations_url": "https://api.github.com/users/octocat/orgs", "repos_url": "https://api.github.com/users/octocat/repos", "events_url": "https://api.github.com/users/octocat/events{/privacy}", "received_events_url": "https://api.github.com/users/octocat/received_events", "type": "User", "site_admin": false }, "private": false, "html_url": "https://github.com/octocat/Hello-World", "description": "This your first repo!", "fork": false, "url": "https://api.github.com/repos/octocat/Hello-World", "archive_url": "https://api.github.com/repos/octocat/Hello-World/{archive_format}{/ref}", "assignees_url": "https://api.github.com/repos/octocat/Hello-World/assignees{/user}", "blobs_url": "https://api.github.com/repos/octocat/Hello-World/git/blobs{/sha}", "branches_url": "https://api.github.com/repos/octocat/Hello-World/branches{/branch}", "collaborators_url": "https://api.github.com/repos/octocat/Hello-World/collaborators{/collaborator}", "comments_url": "https://api.github.com/repos/octocat/Hello-World/comments{/number}", "commits_url": "https://api.github.com/repos/octocat/Hello-World/commits{/sha}", "compare_url": "https://api.github.com/repos/octocat/Hello-World/compare/{base}...{head}", "contents_url": "https://api.github.com/repos/octocat/Hello-World/contents/{+path}", "contributors_url": "https://api.github.com/repos/octocat/Hello-World/contributors", "deployments_url": "https://api.github.com/repos/octocat/Hello-World/deployments", "downloads_url": "https://api.github.com/repos/octocat/Hello-World/downloads", "events_url": "https://api.github.com/repos/octocat/Hello-World/events", "forks_url": "https://api.github.com/repos/octocat/Hello-World/forks", "git_commits_url": "https://api.github.com/repos/octocat/Hello-World/git/commits{/sha}", "git_refs_url": "https://api.github.com/repos/octocat/Hello-World/git/refs{/sha}", "git_tags_url": "https://api.github.com/repos/octocat/Hello-World/git/tags{/sha}", "git_url": "git:github.com/octocat/Hello-World.git", "issue_comment_url": "https://api.github.com/repos/octocat/Hello-World/issues/comments{/number}", "issue_events_url": "https://api.github.com/repos/octocat/Hello-World/issues/events{/number}", "issues_url": "https://api.github.com/repos/octocat/Hello-World/issues{/number}", "keys_url": "https://api.github.com/repos/octocat/Hello-World/keys{/key_id}", "labels_url": "https://api.github.com/repos/octocat/Hello-World/labels{/name}", "languages_url": "https://api.github.com/repos/octocat/Hello-World/languages", "merges_url": "https://api.github.com/repos/octocat/Hello-World/merges", "milestones_url": "https://api.github.com/repos/octocat/Hello-World/milestones{/number}", "notifications_url": "https://api.github.com/repos/octocat/Hello-World/notifications{?since,all,participating}", "pulls_url": "https://api.github.com/repos/octocat/Hello-World/pulls{/number}", "releases_url": "https://api.github.com/repos/octocat/Hello-World/releases{/id}", "ssh_url": "git@github.com:octocat/Hello-World.git", "stargazers_url": "https://api.github.com/repos/octocat/Hello-World/stargazers", "statuses_url": "https://api.github.com/repos/octocat/Hello-World/statuses/{sha}", "subscribers_url": "https://api.github.com/repos/octocat/Hello-World/subscribers", "subscription_url": "https://api.github.com/repos/octocat/Hello-World/subscription", "tags_url": "https://api.github.com/repos/octocat/Hello-World/tags", "teams_url": "https://api.github.com/repos/octocat/Hello-World/teams", "trees_url": "https://api.github.com/repos/octocat/Hello-World/git/trees{/sha}", "hooks_url": "http://api.github.com/repos/octocat/Hello-World/hooks" }, "subject": { "title": "Greetings", "url": "https://api.github.com/repos/octokit/octokit.rb/issues/123", "latest_comment_url": "https://api.github.com/repos/octokit/octokit.rb/issues/comments/123", "type": "Issue" }, "reason": "subscribed", "unread": true, "updated_at": "2014-11-07T22:01:45Z", "last_read_at": "2014-11-07T22:01:45Z", "url": "https://api.github.com/notifications/threads/1", "subscription_url": "https://api.github.com/notifications/threads/1/subscription" } }, "thread-subscription": { "value": { "subscribed": true, "ignored": false, "reason": null, "created_at": "2012-10-06T21:34:12Z", "url": "https://api.github.com/notifications/threads/1/subscription", "thread_url": "https://api.github.com/notifications/threads/1" } }, "organization-simple-items": { "value": [ { "login": "github", "id": 1, "node_id": "MDEyOk9yZ2FuaXphdGlvbjE=", "url": "https://api.github.com/orgs/github", "repos_url": "https://api.github.com/orgs/github/repos", "events_url": "https://api.github.com/orgs/github/events", "hooks_url": "https://api.github.com/orgs/github/hooks", "issues_url": "https://api.github.com/orgs/github/issues", "members_url": "https://api.github.com/orgs/github/members{/member}", "public_members_url": "https://api.github.com/orgs/github/public_members{/member}", "avatar_url": "https://github.com/images/error/octocat_happy.gif", "description": "A great organization" } ] }, "organization-full-default-response": { "summary": "Default response", "value": { "login": "github", "id": 1, "node_id": "MDEyOk9yZ2FuaXphdGlvbjE=", "url": "https://api.github.com/orgs/github", "repos_url": "https://api.github.com/orgs/github/repos", "events_url": "https://api.github.com/orgs/github/events", "hooks_url": "https://api.github.com/orgs/github/hooks", "issues_url": "https://api.github.com/orgs/github/issues", "members_url": "https://api.github.com/orgs/github/members{/member}", "public_members_url": "https://api.github.com/orgs/github/public_members{/member}", "avatar_url": "https://github.com/images/error/octocat_happy.gif", "description": "A great organization", "name": "github", "company": "GitHub", "blog": "https://github.com/blog", "location": "San Francisco", "email": "octocat@github.com", "twitter_username": "github", "is_verified": true, "has_organization_projects": true, "has_repository_projects": true, "public_repos": 2, "public_gists": 1, "followers": 20, "following": 0, "html_url": "https://github.com/octocat", "created_at": "2008-01-14T04:33:35Z", "updated_at": "2014-03-03T18:58:10Z", "type": "Organization", "total_private_repos": 100, "owned_private_repos": 100, "private_gists": 81, "disk_usage": 10000, "collaborators": 8, "billing_email": "mona@github.com", "plan": { "name": "Medium", "space": 400, "private_repos": 20, "filled_seats": 4, "seats": 5 }, "default_repository_permission": "read", "members_can_create_repositories": true, "two_factor_requirement_enabled": true, "members_allowed_repository_creation_type": "all", "members_can_create_public_repositories": false, "members_can_create_private_repositories": false, "members_can_create_internal_repositories": false, "members_can_create_pages": true, "members_can_fork_private_repositories": false } }, "organization-full": { "value": { "login": "github", "id": 1, "node_id": "MDEyOk9yZ2FuaXphdGlvbjE=", "url": "https://api.github.com/orgs/github", "repos_url": "https://api.github.com/orgs/github/repos", "events_url": "https://api.github.com/orgs/github/events", "hooks_url": "https://api.github.com/orgs/github/hooks", "issues_url": "https://api.github.com/orgs/github/issues", "members_url": "https://api.github.com/orgs/github/members{/member}", "public_members_url": "https://api.github.com/orgs/github/public_members{/member}", "avatar_url": "https://github.com/images/error/octocat_happy.gif", "description": "A great organization", "name": "github", "company": "GitHub", "blog": "https://github.com/blog", "location": "San Francisco", "email": "octocat@github.com", "twitter_username": "github", "is_verified": true, "has_organization_projects": true, "has_repository_projects": true, "public_repos": 2, "public_gists": 1, "followers": 20, "following": 0, "html_url": "https://github.com/octocat", "created_at": "2008-01-14T04:33:35Z", "type": "Organization", "total_private_repos": 100, "owned_private_repos": 100, "private_gists": 81, "disk_usage": 10000, "collaborators": 8, "billing_email": "mona@github.com", "plan": { "name": "Medium", "space": 400, "private_repos": 20 }, "default_repository_permission": "read", "members_can_create_repositories": true, "two_factor_requirement_enabled": true, "members_allowed_repository_creation_type": "all", "members_can_create_public_repositories": false, "members_can_create_private_repositories": false, "members_can_create_internal_repositories": false, "members_can_create_pages": true, "members_can_create_public_pages": true, "members_can_create_private_pages": true, "members_can_fork_private_repositories": false, "updated_at": "2014-03-03T18:58:10Z" } }, "actions-organization-permissions": { "value": { "enabled_repositories": "all", "allowed_actions": "selected", "selected_actions_url": "https://api.github.com/organizations/42/actions/permissions/selected-actions" } }, "repository-paginated": { "value": { "total_count": 1, "repositories": [ { "id": 1296269, "node_id": "MDEwOlJlcG9zaXRvcnkxMjk2MjY5", "name": "Hello-World", "full_name": "octocat/Hello-World", "owner": { "login": "octocat", "id": 1, "node_id": "MDQ6VXNlcjE=", "avatar_url": "https://github.com/images/error/octocat_happy.gif", "gravatar_id": "", "url": "https://api.github.com/users/octocat", "html_url": "https://github.com/octocat", "followers_url": "https://api.github.com/users/octocat/followers", "following_url": "https://api.github.com/users/octocat/following{/other_user}", "gists_url": "https://api.github.com/users/octocat/gists{/gist_id}", "starred_url": "https://api.github.com/users/octocat/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/octocat/subscriptions", "organizations_url": "https://api.github.com/users/octocat/orgs", "repos_url": "https://api.github.com/users/octocat/repos", "events_url": "https://api.github.com/users/octocat/events{/privacy}", "received_events_url": "https://api.github.com/users/octocat/received_events", "type": "User", "site_admin": false }, "private": false, "html_url": "https://github.com/octocat/Hello-World", "description": "This your first repo!", "fork": false, "url": "https://api.github.com/repos/octocat/Hello-World", "archive_url": "https://api.github.com/repos/octocat/Hello-World/{archive_format}{/ref}", "assignees_url": "https://api.github.com/repos/octocat/Hello-World/assignees{/user}", "blobs_url": "https://api.github.com/repos/octocat/Hello-World/git/blobs{/sha}", "branches_url": "https://api.github.com/repos/octocat/Hello-World/branches{/branch}", "collaborators_url": "https://api.github.com/repos/octocat/Hello-World/collaborators{/collaborator}", "comments_url": "https://api.github.com/repos/octocat/Hello-World/comments{/number}", "commits_url": "https://api.github.com/repos/octocat/Hello-World/commits{/sha}", "compare_url": "https://api.github.com/repos/octocat/Hello-World/compare/{base}...{head}", "contents_url": "https://api.github.com/repos/octocat/Hello-World/contents/{+path}", "contributors_url": "https://api.github.com/repos/octocat/Hello-World/contributors", "deployments_url": "https://api.github.com/repos/octocat/Hello-World/deployments", "downloads_url": "https://api.github.com/repos/octocat/Hello-World/downloads", "events_url": "https://api.github.com/repos/octocat/Hello-World/events", "forks_url": "https://api.github.com/repos/octocat/Hello-World/forks", "git_commits_url": "https://api.github.com/repos/octocat/Hello-World/git/commits{/sha}", "git_refs_url": "https://api.github.com/repos/octocat/Hello-World/git/refs{/sha}", "git_tags_url": "https://api.github.com/repos/octocat/Hello-World/git/tags{/sha}", "git_url": "git:github.com/octocat/Hello-World.git", "issue_comment_url": "https://api.github.com/repos/octocat/Hello-World/issues/comments{/number}", "issue_events_url": "https://api.github.com/repos/octocat/Hello-World/issues/events{/number}", "issues_url": "https://api.github.com/repos/octocat/Hello-World/issues{/number}", "keys_url": "https://api.github.com/repos/octocat/Hello-World/keys{/key_id}", "labels_url": "https://api.github.com/repos/octocat/Hello-World/labels{/name}", "languages_url": "https://api.github.com/repos/octocat/Hello-World/languages", "merges_url": "https://api.github.com/repos/octocat/Hello-World/merges", "milestones_url": "https://api.github.com/repos/octocat/Hello-World/milestones{/number}", "notifications_url": "https://api.github.com/repos/octocat/Hello-World/notifications{?since,all,participating}", "pulls_url": "https://api.github.com/repos/octocat/Hello-World/pulls{/number}", "releases_url": "https://api.github.com/repos/octocat/Hello-World/releases{/id}", "ssh_url": "git@github.com:octocat/Hello-World.git", "stargazers_url": "https://api.github.com/repos/octocat/Hello-World/stargazers", "statuses_url": "https://api.github.com/repos/octocat/Hello-World/statuses/{sha}", "subscribers_url": "https://api.github.com/repos/octocat/Hello-World/subscribers", "subscription_url": "https://api.github.com/repos/octocat/Hello-World/subscription", "tags_url": "https://api.github.com/repos/octocat/Hello-World/tags", "teams_url": "https://api.github.com/repos/octocat/Hello-World/teams", "trees_url": "https://api.github.com/repos/octocat/Hello-World/git/trees{/sha}", "clone_url": "https://github.com/octocat/Hello-World.git", "mirror_url": "git:git.example.com/octocat/Hello-World", "hooks_url": "https://api.github.com/repos/octocat/Hello-World/hooks", "svn_url": "https://svn.github.com/octocat/Hello-World", "homepage": "https://github.com", "language": null, "forks_count": 9, "stargazers_count": 80, "watchers_count": 80, "size": 108, "default_branch": "master", "open_issues_count": 0, "is_template": true, "topics": [ "octocat", "atom", "electron", "api" ], "has_issues": true, "has_projects": true, "has_wiki": true, "has_pages": false, "has_downloads": true, "archived": false, "disabled": false, "visibility": "public", "pushed_at": "2011-01-26T19:06:43Z", "created_at": "2011-01-26T19:01:12Z", "updated_at": "2011-01-26T19:14:43Z", "permissions": { "admin": false, "push": false, "pull": true }, "allow_rebase_merge": true, "template_repository": null, "temp_clone_token": "ABTLWHOULUVAXGTRYU7OC2876QJ2O", "allow_squash_merge": true, "delete_branch_on_merge": true, "allow_merge_commit": true, "subscribers_count": 42, "network_count": 0, "license": { "key": "mit", "name": "MIT License", "url": "https://api.github.com/licenses/mit", "spdx_id": "MIT", "node_id": "MDc6TGljZW5zZW1pdA==", "html_url": "https://github.com/licenses/mit" }, "forks": 1, "open_issues": 1, "watchers": 1 } ] } }, "runner-groups-org": { "value": { "total_count": 3, "runner_groups": [ { "id": 1, "name": "Default", "visibility": "all", "default": true, "runners_url": "https://api.github.com/orgs/octo-org/actions/runner_groups/1/runners", "inherited": false, "allows_public_repositories": true }, { "id": 2, "name": "octo-runner-group", "visibility": "selected", "default": false, "selected_repositories_url": "https://api.github.com/orgs/octo-org/actions/runner_groups/2/repositories", "runners_url": "https://api.github.com/orgs/octo-org/actions/runner_groups/2/runners", "inherited": true, "allows_public_repositories": true }, { "id": 3, "name": "expensive-hardware", "visibility": "private", "default": false, "runners_url": "https://api.github.com/orgs/octo-org/actions/runner_groups/3/runners", "inherited": false, "allows_public_repositories": true } ] } }, "runner-group": { "value": { "id": 2, "name": "octo-runner-group", "visibility": "selected", "default": false, "selected_repositories_url": "https://api.github.com/orgs/octo-org/actions/runner-groups/2/repositories", "runners_url": "https://api.github.com/orgs/octo-org/actions/runner_groups/2/runners", "inherited": false, "allows_public_repositories": true } }, "runner-group-item": { "value": { "id": 2, "name": "octo-runner-group", "visibility": "selected", "default": false, "selected_repositories_url": "https://api.github.com/orgs/octo-org/actions/runner_groups/2/repositories", "runners_url": "https://api.github.com/orgs/octo-org/actions/runner_groups/2/runners", "inherited": false, "allows_public_repositories": true } }, "minimal-repository-paginated": { "value": { "total_count": 1, "repositories": [ { "id": 1296269, "node_id": "MDEwOlJlcG9zaXRvcnkxMjk2MjY5", "name": "Hello-World", "full_name": "octocat/Hello-World", "owner": { "login": "octocat", "id": 1, "node_id": "MDQ6VXNlcjE=", "avatar_url": "https://github.com/images/error/octocat_happy.gif", "gravatar_id": "", "url": "https://api.github.com/users/octocat", "html_url": "https://github.com/octocat", "followers_url": "https://api.github.com/users/octocat/followers", "following_url": "https://api.github.com/users/octocat/following{/other_user}", "gists_url": "https://api.github.com/users/octocat/gists{/gist_id}", "starred_url": "https://api.github.com/users/octocat/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/octocat/subscriptions", "organizations_url": "https://api.github.com/users/octocat/orgs", "repos_url": "https://api.github.com/users/octocat/repos", "events_url": "https://api.github.com/users/octocat/events{/privacy}", "received_events_url": "https://api.github.com/users/octocat/received_events", "type": "User", "site_admin": false }, "private": false, "html_url": "https://github.com/octocat/Hello-World", "description": "This your first repo!", "fork": false, "url": "https://api.github.com/repos/octocat/Hello-World", "archive_url": "https://api.github.com/repos/octocat/Hello-World/{archive_format}{/ref}", "assignees_url": "https://api.github.com/repos/octocat/Hello-World/assignees{/user}", "blobs_url": "https://api.github.com/repos/octocat/Hello-World/git/blobs{/sha}", "branches_url": "https://api.github.com/repos/octocat/Hello-World/branches{/branch}", "collaborators_url": "https://api.github.com/repos/octocat/Hello-World/collaborators{/collaborator}", "comments_url": "https://api.github.com/repos/octocat/Hello-World/comments{/number}", "commits_url": "https://api.github.com/repos/octocat/Hello-World/commits{/sha}", "compare_url": "https://api.github.com/repos/octocat/Hello-World/compare/{base}...{head}", "contents_url": "https://api.github.com/repos/octocat/Hello-World/contents/{+path}", "contributors_url": "https://api.github.com/repos/octocat/Hello-World/contributors", "deployments_url": "https://api.github.com/repos/octocat/Hello-World/deployments", "downloads_url": "https://api.github.com/repos/octocat/Hello-World/downloads", "events_url": "https://api.github.com/repos/octocat/Hello-World/events", "forks_url": "https://api.github.com/repos/octocat/Hello-World/forks", "git_commits_url": "https://api.github.com/repos/octocat/Hello-World/git/commits{/sha}", "git_refs_url": "https://api.github.com/repos/octocat/Hello-World/git/refs{/sha}", "git_tags_url": "https://api.github.com/repos/octocat/Hello-World/git/tags{/sha}", "git_url": "git:github.com/octocat/Hello-World.git", "issue_comment_url": "https://api.github.com/repos/octocat/Hello-World/issues/comments{/number}", "issue_events_url": "https://api.github.com/repos/octocat/Hello-World/issues/events{/number}", "issues_url": "https://api.github.com/repos/octocat/Hello-World/issues{/number}", "keys_url": "https://api.github.com/repos/octocat/Hello-World/keys{/key_id}", "labels_url": "https://api.github.com/repos/octocat/Hello-World/labels{/name}", "languages_url": "https://api.github.com/repos/octocat/Hello-World/languages", "merges_url": "https://api.github.com/repos/octocat/Hello-World/merges", "milestones_url": "https://api.github.com/repos/octocat/Hello-World/milestones{/number}", "notifications_url": "https://api.github.com/repos/octocat/Hello-World/notifications{?since,all,participating}", "pulls_url": "https://api.github.com/repos/octocat/Hello-World/pulls{/number}", "releases_url": "https://api.github.com/repos/octocat/Hello-World/releases{/id}", "ssh_url": "git@github.com:octocat/Hello-World.git", "stargazers_url": "https://api.github.com/repos/octocat/Hello-World/stargazers", "statuses_url": "https://api.github.com/repos/octocat/Hello-World/statuses/{sha}", "subscribers_url": "https://api.github.com/repos/octocat/Hello-World/subscribers", "subscription_url": "https://api.github.com/repos/octocat/Hello-World/subscription", "tags_url": "https://api.github.com/repos/octocat/Hello-World/tags", "teams_url": "https://api.github.com/repos/octocat/Hello-World/teams", "trees_url": "https://api.github.com/repos/octocat/Hello-World/git/trees{/sha}", "clone_url": "https://github.com/octocat/Hello-World.git", "mirror_url": "git:git.example.com/octocat/Hello-World", "hooks_url": "https://api.github.com/repos/octocat/Hello-World/hooks", "svn_url": "https://svn.github.com/octocat/Hello-World", "homepage": "https://github.com", "language": null, "forks_count": 9, "stargazers_count": 80, "watchers_count": 80, "size": 108, "default_branch": "master", "open_issues_count": 0, "is_template": true, "topics": [ "octocat", "atom", "electron", "api" ], "has_issues": true, "has_projects": true, "has_wiki": true, "has_pages": false, "has_downloads": true, "archived": false, "disabled": false, "visibility": "public", "pushed_at": "2011-01-26T19:06:43Z", "created_at": "2011-01-26T19:01:12Z", "updated_at": "2011-01-26T19:14:43Z", "permissions": { "admin": false, "push": false, "pull": true }, "template_repository": { "id": 1296269, "node_id": "MDEwOlJlcG9zaXRvcnkxMjk2MjY5", "name": "Hello-World", "full_name": "octocat/Hello-World", "owner": { "login": "octocat", "id": 1, "node_id": "MDQ6VXNlcjE=", "avatar_url": "https://github.com/images/error/octocat_happy.gif", "gravatar_id": "", "url": "https://api.github.com/users/octocat", "html_url": "https://github.com/octocat", "followers_url": "https://api.github.com/users/octocat/followers", "following_url": "https://api.github.com/users/octocat/following{/other_user}", "gists_url": "https://api.github.com/users/octocat/gists{/gist_id}", "starred_url": "https://api.github.com/users/octocat/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/octocat/subscriptions", "organizations_url": "https://api.github.com/users/octocat/orgs", "repos_url": "https://api.github.com/users/octocat/repos", "events_url": "https://api.github.com/users/octocat/events{/privacy}", "received_events_url": "https://api.github.com/users/octocat/received_events", "type": "User", "site_admin": false }, "private": false, "html_url": "https://github.com/octocat/Hello-World", "description": "This your first repo!", "fork": false, "url": "https://api.github.com/repos/octocat/Hello-World", "archive_url": "https://api.github.com/repos/octocat/Hello-World/{archive_format}{/ref}", "assignees_url": "https://api.github.com/repos/octocat/Hello-World/assignees{/user}", "blobs_url": "https://api.github.com/repos/octocat/Hello-World/git/blobs{/sha}", "branches_url": "https://api.github.com/repos/octocat/Hello-World/branches{/branch}", "collaborators_url": "https://api.github.com/repos/octocat/Hello-World/collaborators{/collaborator}", "comments_url": "https://api.github.com/repos/octocat/Hello-World/comments{/number}", "commits_url": "https://api.github.com/repos/octocat/Hello-World/commits{/sha}", "compare_url": "https://api.github.com/repos/octocat/Hello-World/compare/{base}...{head}", "contents_url": "https://api.github.com/repos/octocat/Hello-World/contents/{+path}", "contributors_url": "https://api.github.com/repos/octocat/Hello-World/contributors", "deployments_url": "https://api.github.com/repos/octocat/Hello-World/deployments", "downloads_url": "https://api.github.com/repos/octocat/Hello-World/downloads", "events_url": "https://api.github.com/repos/octocat/Hello-World/events", "forks_url": "https://api.github.com/repos/octocat/Hello-World/forks", "git_commits_url": "https://api.github.com/repos/octocat/Hello-World/git/commits{/sha}", "git_refs_url": "https://api.github.com/repos/octocat/Hello-World/git/refs{/sha}", "git_tags_url": "https://api.github.com/repos/octocat/Hello-World/git/tags{/sha}", "git_url": "git:github.com/octocat/Hello-World.git", "issue_comment_url": "https://api.github.com/repos/octocat/Hello-World/issues/comments{/number}", "issue_events_url": "https://api.github.com/repos/octocat/Hello-World/issues/events{/number}", "issues_url": "https://api.github.com/repos/octocat/Hello-World/issues{/number}", "keys_url": "https://api.github.com/repos/octocat/Hello-World/keys{/key_id}", "labels_url": "https://api.github.com/repos/octocat/Hello-World/labels{/name}", "languages_url": "https://api.github.com/repos/octocat/Hello-World/languages", "merges_url": "https://api.github.com/repos/octocat/Hello-World/merges", "milestones_url": "https://api.github.com/repos/octocat/Hello-World/milestones{/number}", "notifications_url": "https://api.github.com/repos/octocat/Hello-World/notifications{?since,all,participating}", "pulls_url": "https://api.github.com/repos/octocat/Hello-World/pulls{/number}", "releases_url": "https://api.github.com/repos/octocat/Hello-World/releases{/id}", "ssh_url": "git@github.com:octocat/Hello-World.git", "stargazers_url": "https://api.github.com/repos/octocat/Hello-World/stargazers", "statuses_url": "https://api.github.com/repos/octocat/Hello-World/statuses/{sha}", "subscribers_url": "https://api.github.com/repos/octocat/Hello-World/subscribers", "subscription_url": "https://api.github.com/repos/octocat/Hello-World/subscription", "tags_url": "https://api.github.com/repos/octocat/Hello-World/tags", "teams_url": "https://api.github.com/repos/octocat/Hello-World/teams", "trees_url": "https://api.github.com/repos/octocat/Hello-World/git/trees{/sha}", "clone_url": "https://github.com/octocat/Hello-World.git", "mirror_url": "git:git.example.com/octocat/Hello-World", "hooks_url": "https://api.github.com/repos/octocat/Hello-World/hooks", "svn_url": "https://svn.github.com/octocat/Hello-World", "homepage": "https://github.com", "organization": null, "language": null, "forks": 9, "forks_count": 9, "stargazers_count": 80, "watchers_count": 80, "watchers": 80, "size": 108, "default_branch": "master", "open_issues": 0, "open_issues_count": 0, "is_template": true, "license": { "key": "mit", "name": "MIT License", "url": "https://api.github.com/licenses/mit", "spdx_id": "MIT", "node_id": "MDc6TGljZW5zZW1pdA==", "html_url": "https://api.github.com/licenses/mit" }, "topics": [ "octocat", "atom", "electron", "api" ], "has_issues": true, "has_projects": true, "has_wiki": true, "has_pages": false, "has_downloads": true, "archived": false, "disabled": false, "visibility": "public", "pushed_at": "2011-01-26T19:06:43Z", "created_at": "2011-01-26T19:01:12Z", "updated_at": "2011-01-26T19:14:43Z", "permissions": { "admin": false, "push": false, "pull": true }, "allow_rebase_merge": true, "template_repository": null, "temp_clone_token": "ABTLWHOULUVAXGTRYU7OC2876QJ2O", "allow_squash_merge": true, "delete_branch_on_merge": true, "allow_merge_commit": true, "subscribers_count": 42, "network_count": 0 }, "temp_clone_token": "ABTLWHOULUVAXGTRYU7OC2876QJ2O", "delete_branch_on_merge": true, "subscribers_count": 42, "network_count": 0, "license": { "key": "mit", "name": "MIT License", "url": "https://api.github.com/licenses/mit", "spdx_id": "MIT", "node_id": "MDc6TGljZW5zZW1pdA==" }, "forks": 1, "open_issues": 1, "watchers": 1 } ] } }, "organization-actions-secret-paginated": { "value": { "total_count": 3, "secrets": [ { "name": "GIST_ID", "created_at": "2019-08-10T14:59:22Z", "updated_at": "2020-01-10T14:59:22Z", "visibility": "private" }, { "name": "DEPLOY_TOKEN", "created_at": "2019-08-10T14:59:22Z", "updated_at": "2020-01-10T14:59:22Z", "visibility": "all" }, { "name": "GH_TOKEN", "created_at": "2019-08-10T14:59:22Z", "updated_at": "2020-01-10T14:59:22Z", "visibility": "selected", "selected_repositories_url": "https://api.github.com/orgs/octo-org/actions/secrets/SUPER_SECRET/repositories" } ] } }, "actions-public-key": { "value": { "key_id": "012345678912345678", "key": "2Sg8iYjAxxmI2LvUXpJjkYrMxURPc8r+dB7TJyvv1234" } }, "organization-actions-secret": { "value": { "name": "GH_TOKEN", "created_at": "2019-08-10T14:59:22Z", "updated_at": "2020-01-10T14:59:22Z", "visibility": "selected", "selected_repositories_url": "https://api.github.com/orgs/octo-org/actions/secrets/SUPER_SECRET/repositories" } }, "public-repository-paginated": { "value": { "total_count": 1, "repositories": [ { "id": 1296269, "node_id": "MDEwOlJlcG9zaXRvcnkxMjk2MjY5", "name": "Hello-World", "full_name": "octocat/Hello-World", "owner": { "login": "octocat", "id": 1, "node_id": "MDQ6VXNlcjE=", "avatar_url": "https://github.com/images/error/octocat_happy.gif", "gravatar_id": "", "url": "https://api.github.com/users/octocat", "html_url": "https://github.com/octocat", "followers_url": "https://api.github.com/users/octocat/followers", "following_url": "https://api.github.com/users/octocat/following{/other_user}", "gists_url": "https://api.github.com/users/octocat/gists{/gist_id}", "starred_url": "https://api.github.com/users/octocat/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/octocat/subscriptions", "organizations_url": "https://api.github.com/users/octocat/orgs", "repos_url": "https://api.github.com/users/octocat/repos", "events_url": "https://api.github.com/users/octocat/events{/privacy}", "received_events_url": "https://api.github.com/users/octocat/received_events", "type": "User", "site_admin": false }, "private": false, "html_url": "https://github.com/octocat/Hello-World", "description": "This your first repo!", "fork": false, "url": "https://api.github.com/repos/octocat/Hello-World", "archive_url": "https://api.github.com/repos/octocat/Hello-World/{archive_format}{/ref}", "assignees_url": "https://api.github.com/repos/octocat/Hello-World/assignees{/user}", "blobs_url": "https://api.github.com/repos/octocat/Hello-World/git/blobs{/sha}", "branches_url": "https://api.github.com/repos/octocat/Hello-World/branches{/branch}", "collaborators_url": "https://api.github.com/repos/octocat/Hello-World/collaborators{/collaborator}", "comments_url": "https://api.github.com/repos/octocat/Hello-World/comments{/number}", "commits_url": "https://api.github.com/repos/octocat/Hello-World/commits{/sha}", "compare_url": "https://api.github.com/repos/octocat/Hello-World/compare/{base}...{head}", "contents_url": "https://api.github.com/repos/octocat/Hello-World/contents/{+path}", "contributors_url": "https://api.github.com/repos/octocat/Hello-World/contributors", "deployments_url": "https://api.github.com/repos/octocat/Hello-World/deployments", "downloads_url": "https://api.github.com/repos/octocat/Hello-World/downloads", "events_url": "https://api.github.com/repos/octocat/Hello-World/events", "forks_url": "https://api.github.com/repos/octocat/Hello-World/forks", "git_commits_url": "https://api.github.com/repos/octocat/Hello-World/git/commits{/sha}", "git_refs_url": "https://api.github.com/repos/octocat/Hello-World/git/refs{/sha}", "git_tags_url": "https://api.github.com/repos/octocat/Hello-World/git/tags{/sha}", "git_url": "git:github.com/octocat/Hello-World.git", "issue_comment_url": "https://api.github.com/repos/octocat/Hello-World/issues/comments{/number}", "issue_events_url": "https://api.github.com/repos/octocat/Hello-World/issues/events{/number}", "issues_url": "https://api.github.com/repos/octocat/Hello-World/issues{/number}", "keys_url": "https://api.github.com/repos/octocat/Hello-World/keys{/key_id}", "labels_url": "https://api.github.com/repos/octocat/Hello-World/labels{/name}", "languages_url": "https://api.github.com/repos/octocat/Hello-World/languages", "merges_url": "https://api.github.com/repos/octocat/Hello-World/merges", "milestones_url": "https://api.github.com/repos/octocat/Hello-World/milestones{/number}", "notifications_url": "https://api.github.com/repos/octocat/Hello-World/notifications{?since,all,participating}", "pulls_url": "https://api.github.com/repos/octocat/Hello-World/pulls{/number}", "releases_url": "https://api.github.com/repos/octocat/Hello-World/releases{/id}", "ssh_url": "git@github.com:octocat/Hello-World.git", "stargazers_url": "https://api.github.com/repos/octocat/Hello-World/stargazers", "statuses_url": "https://api.github.com/repos/octocat/Hello-World/statuses/{sha}", "subscribers_url": "https://api.github.com/repos/octocat/Hello-World/subscribers", "subscription_url": "https://api.github.com/repos/octocat/Hello-World/subscription", "tags_url": "https://api.github.com/repos/octocat/Hello-World/tags", "teams_url": "https://api.github.com/repos/octocat/Hello-World/teams", "trees_url": "https://api.github.com/repos/octocat/Hello-World/git/trees{/sha}", "hooks_url": "http://api.github.com/repos/octocat/Hello-World/hooks" } ] } }, "org-hook-items": { "value": [ { "id": 1, "url": "https://api.github.com/orgs/octocat/hooks/1", "ping_url": "https://api.github.com/orgs/octocat/hooks/1/pings", "name": "web", "events": [ "push", "pull_request" ], "active": true, "config": { "url": "http://example.com", "content_type": "json" }, "updated_at": "2011-09-06T20:39:23Z", "created_at": "2011-09-06T17:26:27Z", "type": "Organization" } ] }, "org-hook": { "value": { "id": 1, "url": "https://api.github.com/orgs/octocat/hooks/1", "ping_url": "https://api.github.com/orgs/octocat/hooks/1/pings", "name": "web", "events": [ "push", "pull_request" ], "active": true, "config": { "url": "http://example.com", "content_type": "json" }, "updated_at": "2011-09-06T20:39:23Z", "created_at": "2011-09-06T17:26:27Z", "type": "Organization" } }, "org-hook-2": { "value": { "id": 1, "url": "https://api.github.com/orgs/octocat/hooks/1", "ping_url": "https://api.github.com/orgs/octocat/hooks/1/pings", "name": "web", "events": [ "pull_request" ], "active": true, "config": { "url": "http://example.com", "content_type": "json" }, "updated_at": "2011-09-06T20:39:23Z", "created_at": "2011-09-06T17:26:27Z", "type": "Organization" } }, "installation": { "value": { "id": 1, "account": { "login": "github", "id": 1, "node_id": "MDEyOk9yZ2FuaXphdGlvbjE=", "avatar_url": "https://github.com/images/error/hubot_happy.gif", "gravatar_id": "", "url": "https://api.github.com/orgs/github", "html_url": "https://github.com/github", "followers_url": "https://api.github.com/users/github/followers", "following_url": "https://api.github.com/users/github/following{/other_user}", "gists_url": "https://api.github.com/users/github/gists{/gist_id}", "starred_url": "https://api.github.com/users/github/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/github/subscriptions", "organizations_url": "https://api.github.com/users/github/orgs", "repos_url": "https://api.github.com/orgs/github/repos", "events_url": "https://api.github.com/orgs/github/events", "received_events_url": "https://api.github.com/users/github/received_events", "type": "Organization", "site_admin": false }, "repository_selection": "all", "access_tokens_url": "https://api.github.com/installations/1/access_tokens", "repositories_url": "https://api.github.com/installation/repositories", "html_url": "https://github.com/organizations/github/settings/installations/1", "app_id": 1, "target_id": 1, "target_type": "Organization", "permissions": { "checks": "write", "metadata": "read", "contents": "read" }, "events": [ "push", "pull_request" ], "created_at": "2018-02-09T20:51:14Z", "updated_at": "2018-02-09T20:51:14Z", "single_file_name": "config.yml", "has_multiple_single_files": true, "single_file_paths": [ "config.yml", ".github/issue_TEMPLATE.md" ], "app_slug": "github-actions", "suspended_at": null, "suspended_by": null } }, "installation-paginated": { "value": { "total_count": 1, "installations": [ { "id": 25381, "account": { "login": "octo-org", "id": 6811672, "node_id": "MDEyOk9yZ2FuaXphdGlvbjY4MTE2NzI=", "avatar_url": "https://avatars3.githubusercontent.com/u/6811672?v=4", "gravatar_id": "", "url": "https://api.github.com/users/octo-org", "html_url": "https://github.com/octo-org", "followers_url": "https://api.github.com/users/octo-org/followers", "following_url": "https://api.github.com/users/octo-org/following{/other_user}", "gists_url": "https://api.github.com/users/octo-org/gists{/gist_id}", "starred_url": "https://api.github.com/users/octo-org/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/octo-org/subscriptions", "organizations_url": "https://api.github.com/users/octo-org/orgs", "repos_url": "https://api.github.com/users/octo-org/repos", "events_url": "https://api.github.com/users/octo-org/events{/privacy}", "received_events_url": "https://api.github.com/users/octo-org/received_events", "type": "Organization", "site_admin": false }, "repository_selection": "selected", "access_tokens_url": "https://api.github.com/app/installations/25381/access_tokens", "repositories_url": "https://api.github.com/installation/repositories", "html_url": "https://github.com/organizations/octo-org/settings/installations/25381", "app_id": 2218, "target_id": 6811672, "target_type": "Organization", "permissions": { "deployments": "write", "metadata": "read", "pull_requests": "read", "statuses": "read" }, "events": [ "deployment", "deployment_status" ], "created_at": "2017-05-16T08:47:09.000-07:00", "updated_at": "2017-06-06T11:23:23.000-07:00", "single_file_name": "config.yml", "has_multiple_single_files": true, "single_file_paths": [ "config.yml", ".github/issue_TEMPLATE.md" ], "app_slug": "github-actions", "suspended_at": null, "suspended_by": null } ] } }, "simple-user-items": { "value": [ { "login": "octocat", "id": 1, "node_id": "MDQ6VXNlcjE=", "avatar_url": "https://github.com/images/error/octocat_happy.gif", "gravatar_id": "", "url": "https://api.github.com/users/octocat", "html_url": "https://github.com/octocat", "followers_url": "https://api.github.com/users/octocat/followers", "following_url": "https://api.github.com/users/octocat/following{/other_user}", "gists_url": "https://api.github.com/users/octocat/gists{/gist_id}", "starred_url": "https://api.github.com/users/octocat/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/octocat/subscriptions", "organizations_url": "https://api.github.com/users/octocat/orgs", "repos_url": "https://api.github.com/users/octocat/repos", "events_url": "https://api.github.com/users/octocat/events{/privacy}", "received_events_url": "https://api.github.com/users/octocat/received_events", "type": "User", "site_admin": false } ] }, "org-membership-response-if-user-has-an-active-admin-membership-with-organization": { "summary": "Response if user has an active admin membership with organization", "value": { "url": "https://api.github.com/orgs/octocat/memberships/defunkt", "state": "active", "role": "admin", "organization_url": "https://api.github.com/orgs/octocat", "organization": { "login": "github", "id": 1, "node_id": "MDEyOk9yZ2FuaXphdGlvbjE=", "url": "https://api.github.com/orgs/github", "repos_url": "https://api.github.com/orgs/github/repos", "events_url": "https://api.github.com/orgs/github/events", "hooks_url": "https://api.github.com/orgs/github/hooks", "issues_url": "https://api.github.com/orgs/github/issues", "members_url": "https://api.github.com/orgs/github/members{/member}", "public_members_url": "https://api.github.com/orgs/github/public_members{/member}", "avatar_url": "https://github.com/images/error/octocat_happy.gif", "description": "A great organization" }, "user": { "login": "octocat", "id": 1, "node_id": "MDQ6VXNlcjE=", "avatar_url": "https://github.com/images/error/octocat_happy.gif", "gravatar_id": "", "url": "https://api.github.com/users/octocat", "html_url": "https://github.com/octocat", "followers_url": "https://api.github.com/users/octocat/followers", "following_url": "https://api.github.com/users/octocat/following{/other_user}", "gists_url": "https://api.github.com/users/octocat/gists{/gist_id}", "starred_url": "https://api.github.com/users/octocat/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/octocat/subscriptions", "organizations_url": "https://api.github.com/users/octocat/orgs", "repos_url": "https://api.github.com/users/octocat/repos", "events_url": "https://api.github.com/users/octocat/events{/privacy}", "received_events_url": "https://api.github.com/users/octocat/received_events", "type": "User", "site_admin": false } } }, "org-pre-receive-hook-items": { "value": [ { "id": 42, "name": "Check Commits", "enforcement": "disabled", "configuration_url": "https://github.example.com/api/v3/admin/pre-receive-hooks/42", "allow_downstream_configuration": true } ] }, "org-pre-receive-hook": { "value": { "id": 42, "name": "Check Commits", "enforcement": "disabled", "configuration_url": "https://github.example.com/api/v3/admin/pre-receive-hooks/42", "allow_downstream_configuration": true } }, "org-pre-receive-hook-2": { "value": { "id": 42, "name": "Check Commits", "enforcement": "enabled", "configuration_url": "https://github.example.com/api/v3/orgs/octocat/pre-receive-hooks/42", "allow_downstream_configuration": false } }, "project-items": { "value": [ { "owner_url": "https://api.github.com/orgs/octocat", "url": "https://api.github.com/projects/1002605", "html_url": "https://github.com/orgs/api-playground/projects/1", "columns_url": "https://api.github.com/projects/1002605/columns", "id": 1002605, "node_id": "MDc6UHJvamVjdDEwMDI2MDU=", "name": "Organization Roadmap", "body": "High-level roadmap for the upcoming year.", "number": 1, "state": "open", "creator": { "login": "octocat", "id": 1, "node_id": "MDQ6VXNlcjE=", "avatar_url": "https://github.com/images/error/octocat_happy.gif", "gravatar_id": "", "url": "https://api.github.com/users/octocat", "html_url": "https://github.com/octocat", "followers_url": "https://api.github.com/users/octocat/followers", "following_url": "https://api.github.com/users/octocat/following{/other_user}", "gists_url": "https://api.github.com/users/octocat/gists{/gist_id}", "starred_url": "https://api.github.com/users/octocat/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/octocat/subscriptions", "organizations_url": "https://api.github.com/users/octocat/orgs", "repos_url": "https://api.github.com/users/octocat/repos", "events_url": "https://api.github.com/users/octocat/events{/privacy}", "received_events_url": "https://api.github.com/users/octocat/received_events", "type": "User", "site_admin": false }, "created_at": "2011-04-11T20:09:31Z", "updated_at": "2014-03-04T18:58:10Z" } ] }, "project-2": { "value": { "owner_url": "https://api.github.com/orgs/octocat", "url": "https://api.github.com/projects/1002605", "html_url": "https://github.com/orgs/api-playground/projects/1", "columns_url": "https://api.github.com/projects/1002605/columns", "id": 1002605, "node_id": "MDc6UHJvamVjdDEwMDI2MDU=", "name": "Organization Roadmap", "body": "High-level roadmap for the upcoming year.", "number": 1, "state": "open", "creator": { "login": "octocat", "id": 1, "node_id": "MDQ6VXNlcjE=", "avatar_url": "https://github.com/images/error/octocat_happy.gif", "gravatar_id": "", "url": "https://api.github.com/users/octocat", "html_url": "https://github.com/octocat", "followers_url": "https://api.github.com/users/octocat/followers", "following_url": "https://api.github.com/users/octocat/following{/other_user}", "gists_url": "https://api.github.com/users/octocat/gists{/gist_id}", "starred_url": "https://api.github.com/users/octocat/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/octocat/subscriptions", "organizations_url": "https://api.github.com/users/octocat/orgs", "repos_url": "https://api.github.com/users/octocat/repos", "events_url": "https://api.github.com/users/octocat/events{/privacy}", "received_events_url": "https://api.github.com/users/octocat/received_events", "type": "User", "site_admin": false }, "created_at": "2011-04-11T20:09:31Z", "updated_at": "2014-03-04T18:58:10Z" } }, "minimal-repository-items": { "value": [ { "id": 1296269, "node_id": "MDEwOlJlcG9zaXRvcnkxMjk2MjY5", "name": "Hello-World", "full_name": "octocat/Hello-World", "owner": { "login": "octocat", "id": 1, "node_id": "MDQ6VXNlcjE=", "avatar_url": "https://github.com/images/error/octocat_happy.gif", "gravatar_id": "", "url": "https://api.github.com/users/octocat", "html_url": "https://github.com/octocat", "followers_url": "https://api.github.com/users/octocat/followers", "following_url": "https://api.github.com/users/octocat/following{/other_user}", "gists_url": "https://api.github.com/users/octocat/gists{/gist_id}", "starred_url": "https://api.github.com/users/octocat/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/octocat/subscriptions", "organizations_url": "https://api.github.com/users/octocat/orgs", "repos_url": "https://api.github.com/users/octocat/repos", "events_url": "https://api.github.com/users/octocat/events{/privacy}", "received_events_url": "https://api.github.com/users/octocat/received_events", "type": "User", "site_admin": false }, "private": false, "html_url": "https://github.com/octocat/Hello-World", "description": "This your first repo!", "fork": false, "url": "https://api.github.com/repos/octocat/Hello-World", "archive_url": "https://api.github.com/repos/octocat/Hello-World/{archive_format}{/ref}", "assignees_url": "https://api.github.com/repos/octocat/Hello-World/assignees{/user}", "blobs_url": "https://api.github.com/repos/octocat/Hello-World/git/blobs{/sha}", "branches_url": "https://api.github.com/repos/octocat/Hello-World/branches{/branch}", "collaborators_url": "https://api.github.com/repos/octocat/Hello-World/collaborators{/collaborator}", "comments_url": "https://api.github.com/repos/octocat/Hello-World/comments{/number}", "commits_url": "https://api.github.com/repos/octocat/Hello-World/commits{/sha}", "compare_url": "https://api.github.com/repos/octocat/Hello-World/compare/{base}...{head}", "contents_url": "https://api.github.com/repos/octocat/Hello-World/contents/{+path}", "contributors_url": "https://api.github.com/repos/octocat/Hello-World/contributors", "deployments_url": "https://api.github.com/repos/octocat/Hello-World/deployments", "downloads_url": "https://api.github.com/repos/octocat/Hello-World/downloads", "events_url": "https://api.github.com/repos/octocat/Hello-World/events", "forks_url": "https://api.github.com/repos/octocat/Hello-World/forks", "git_commits_url": "https://api.github.com/repos/octocat/Hello-World/git/commits{/sha}", "git_refs_url": "https://api.github.com/repos/octocat/Hello-World/git/refs{/sha}", "git_tags_url": "https://api.github.com/repos/octocat/Hello-World/git/tags{/sha}", "git_url": "git:github.com/octocat/Hello-World.git", "issue_comment_url": "https://api.github.com/repos/octocat/Hello-World/issues/comments{/number}", "issue_events_url": "https://api.github.com/repos/octocat/Hello-World/issues/events{/number}", "issues_url": "https://api.github.com/repos/octocat/Hello-World/issues{/number}", "keys_url": "https://api.github.com/repos/octocat/Hello-World/keys{/key_id}", "labels_url": "https://api.github.com/repos/octocat/Hello-World/labels{/name}", "languages_url": "https://api.github.com/repos/octocat/Hello-World/languages", "merges_url": "https://api.github.com/repos/octocat/Hello-World/merges", "milestones_url": "https://api.github.com/repos/octocat/Hello-World/milestones{/number}", "notifications_url": "https://api.github.com/repos/octocat/Hello-World/notifications{?since,all,participating}", "pulls_url": "https://api.github.com/repos/octocat/Hello-World/pulls{/number}", "releases_url": "https://api.github.com/repos/octocat/Hello-World/releases{/id}", "ssh_url": "git@github.com:octocat/Hello-World.git", "stargazers_url": "https://api.github.com/repos/octocat/Hello-World/stargazers", "statuses_url": "https://api.github.com/repos/octocat/Hello-World/statuses/{sha}", "subscribers_url": "https://api.github.com/repos/octocat/Hello-World/subscribers", "subscription_url": "https://api.github.com/repos/octocat/Hello-World/subscription", "tags_url": "https://api.github.com/repos/octocat/Hello-World/tags", "teams_url": "https://api.github.com/repos/octocat/Hello-World/teams", "trees_url": "https://api.github.com/repos/octocat/Hello-World/git/trees{/sha}", "clone_url": "https://github.com/octocat/Hello-World.git", "mirror_url": "git:git.example.com/octocat/Hello-World", "hooks_url": "https://api.github.com/repos/octocat/Hello-World/hooks", "svn_url": "https://svn.github.com/octocat/Hello-World", "homepage": "https://github.com", "language": null, "forks_count": 9, "stargazers_count": 80, "watchers_count": 80, "size": 108, "default_branch": "master", "open_issues_count": 0, "is_template": false, "topics": [ "octocat", "atom", "electron", "api" ], "has_issues": true, "has_projects": true, "has_wiki": true, "has_pages": false, "has_downloads": true, "archived": false, "disabled": false, "visibility": "public", "pushed_at": "2011-01-26T19:06:43Z", "created_at": "2011-01-26T19:01:12Z", "updated_at": "2011-01-26T19:14:43Z", "permissions": { "admin": false, "push": false, "pull": true }, "template_repository": null } ] }, "repository": { "value": { "id": 1296269, "node_id": "MDEwOlJlcG9zaXRvcnkxMjk2MjY5", "name": "Hello-World", "full_name": "octocat/Hello-World", "owner": { "login": "octocat", "id": 1, "node_id": "MDQ6VXNlcjE=", "avatar_url": "https://github.com/images/error/octocat_happy.gif", "gravatar_id": "", "url": "https://api.github.com/users/octocat", "html_url": "https://github.com/octocat", "followers_url": "https://api.github.com/users/octocat/followers", "following_url": "https://api.github.com/users/octocat/following{/other_user}", "gists_url": "https://api.github.com/users/octocat/gists{/gist_id}", "starred_url": "https://api.github.com/users/octocat/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/octocat/subscriptions", "organizations_url": "https://api.github.com/users/octocat/orgs", "repos_url": "https://api.github.com/users/octocat/repos", "events_url": "https://api.github.com/users/octocat/events{/privacy}", "received_events_url": "https://api.github.com/users/octocat/received_events", "type": "User", "site_admin": false }, "private": false, "html_url": "https://github.com/octocat/Hello-World", "description": "This your first repo!", "fork": false, "url": "https://api.github.com/repos/octocat/Hello-World", "archive_url": "https://api.github.com/repos/octocat/Hello-World/{archive_format}{/ref}", "assignees_url": "https://api.github.com/repos/octocat/Hello-World/assignees{/user}", "blobs_url": "https://api.github.com/repos/octocat/Hello-World/git/blobs{/sha}", "branches_url": "https://api.github.com/repos/octocat/Hello-World/branches{/branch}", "collaborators_url": "https://api.github.com/repos/octocat/Hello-World/collaborators{/collaborator}", "comments_url": "https://api.github.com/repos/octocat/Hello-World/comments{/number}", "commits_url": "https://api.github.com/repos/octocat/Hello-World/commits{/sha}", "compare_url": "https://api.github.com/repos/octocat/Hello-World/compare/{base}...{head}", "contents_url": "https://api.github.com/repos/octocat/Hello-World/contents/{+path}", "contributors_url": "https://api.github.com/repos/octocat/Hello-World/contributors", "deployments_url": "https://api.github.com/repos/octocat/Hello-World/deployments", "downloads_url": "https://api.github.com/repos/octocat/Hello-World/downloads", "events_url": "https://api.github.com/repos/octocat/Hello-World/events", "forks_url": "https://api.github.com/repos/octocat/Hello-World/forks", "git_commits_url": "https://api.github.com/repos/octocat/Hello-World/git/commits{/sha}", "git_refs_url": "https://api.github.com/repos/octocat/Hello-World/git/refs{/sha}", "git_tags_url": "https://api.github.com/repos/octocat/Hello-World/git/tags{/sha}", "git_url": "git:github.com/octocat/Hello-World.git", "issue_comment_url": "https://api.github.com/repos/octocat/Hello-World/issues/comments{/number}", "issue_events_url": "https://api.github.com/repos/octocat/Hello-World/issues/events{/number}", "issues_url": "https://api.github.com/repos/octocat/Hello-World/issues{/number}", "keys_url": "https://api.github.com/repos/octocat/Hello-World/keys{/key_id}", "labels_url": "https://api.github.com/repos/octocat/Hello-World/labels{/name}", "languages_url": "https://api.github.com/repos/octocat/Hello-World/languages", "merges_url": "https://api.github.com/repos/octocat/Hello-World/merges", "milestones_url": "https://api.github.com/repos/octocat/Hello-World/milestones{/number}", "notifications_url": "https://api.github.com/repos/octocat/Hello-World/notifications{?since,all,participating}", "pulls_url": "https://api.github.com/repos/octocat/Hello-World/pulls{/number}", "releases_url": "https://api.github.com/repos/octocat/Hello-World/releases{/id}", "ssh_url": "git@github.com:octocat/Hello-World.git", "stargazers_url": "https://api.github.com/repos/octocat/Hello-World/stargazers", "statuses_url": "https://api.github.com/repos/octocat/Hello-World/statuses/{sha}", "subscribers_url": "https://api.github.com/repos/octocat/Hello-World/subscribers", "subscription_url": "https://api.github.com/repos/octocat/Hello-World/subscription", "tags_url": "https://api.github.com/repos/octocat/Hello-World/tags", "teams_url": "https://api.github.com/repos/octocat/Hello-World/teams", "trees_url": "https://api.github.com/repos/octocat/Hello-World/git/trees{/sha}", "clone_url": "https://github.com/octocat/Hello-World.git", "mirror_url": "git:git.example.com/octocat/Hello-World", "hooks_url": "https://api.github.com/repos/octocat/Hello-World/hooks", "svn_url": "https://svn.github.com/octocat/Hello-World", "homepage": "https://github.com", "forks": 9, "forks_count": 9, "stargazers_count": 80, "watchers_count": 80, "watchers": 80, "size": 108, "default_branch": "master", "open_issues": 0, "open_issues_count": 0, "is_template": true, "license": { "key": "mit", "name": "MIT License", "url": "https://api.github.com/licenses/mit", "spdx_id": "MIT", "node_id": "MDc6TGljZW5zZW1pdA==", "html_url": "https://api.github.com/licenses/mit" }, "topics": [ "octocat", "atom", "electron", "api" ], "has_issues": true, "has_projects": true, "has_wiki": true, "has_pages": false, "has_downloads": true, "archived": false, "disabled": false, "visibility": "public", "pushed_at": "2011-01-26T19:06:43Z", "created_at": "2011-01-26T19:01:12Z", "updated_at": "2011-01-26T19:14:43Z", "permissions": { "admin": false, "push": false, "pull": true }, "allow_rebase_merge": true, "temp_clone_token": "ABTLWHOULUVAXGTRYU7OC2876QJ2O", "allow_squash_merge": true, "delete_branch_on_merge": true, "allow_merge_commit": true, "subscribers_count": 42, "network_count": 0 } }, "team-items": { "value": [ { "id": 1, "node_id": "MDQ6VGVhbTE=", "url": "https://api.github.com/teams/1", "html_url": "https://github.com/orgs/github/teams/justice-league", "name": "Justice League", "slug": "justice-league", "description": "A great team.", "privacy": "closed", "permission": "admin", "members_url": "https://api.github.com/teams/1/members{/member}", "repositories_url": "https://api.github.com/teams/1/repos", "parent": null } ] }, "team-full": { "value": { "id": 1, "node_id": "MDQ6VGVhbTE=", "url": "https://api.github.com/teams/1", "html_url": "https://github.com/orgs/github/teams/justice-league", "name": "Justice League", "slug": "justice-league", "description": "A great team.", "privacy": "closed", "permission": "admin", "members_url": "https://api.github.com/teams/1/members{/member}", "repositories_url": "https://api.github.com/teams/1/repos", "members_count": 3, "repos_count": 10, "created_at": "2017-07-14T16:53:42Z", "updated_at": "2017-08-17T12:37:15Z", "organization": { "login": "github", "id": 1, "node_id": "MDEyOk9yZ2FuaXphdGlvbjE=", "url": "https://api.github.com/orgs/github", "repos_url": "https://api.github.com/orgs/github/repos", "events_url": "https://api.github.com/orgs/github/events", "hooks_url": "https://api.github.com/orgs/github/hooks", "issues_url": "https://api.github.com/orgs/github/issues", "members_url": "https://api.github.com/orgs/github/members{/member}", "public_members_url": "https://api.github.com/orgs/github/public_members{/member}", "avatar_url": "https://github.com/images/error/octocat_happy.gif", "description": "A great organization", "name": "github", "company": "GitHub", "blog": "https://github.com/blog", "location": "San Francisco", "email": "octocat@github.com", "has_organization_projects": true, "has_repository_projects": true, "public_repos": 2, "public_gists": 1, "followers": 20, "following": 0, "html_url": "https://github.com/octocat", "created_at": "2008-01-14T04:33:35Z", "updated_at": "2017-08-17T12:37:15Z", "type": "Organization" }, "ldap_dn": "uid=asdf,ou=users,dc=github,dc=com" } }, "team-discussion-items": { "value": [ { "author": { "login": "octocat", "id": 1, "node_id": "MDQ6VXNlcjE=", "avatar_url": "https://github.com/images/error/octocat_happy.gif", "gravatar_id": "", "url": "https://api.github.com/users/octocat", "html_url": "https://github.com/octocat", "followers_url": "https://api.github.com/users/octocat/followers", "following_url": "https://api.github.com/users/octocat/following{/other_user}", "gists_url": "https://api.github.com/users/octocat/gists{/gist_id}", "starred_url": "https://api.github.com/users/octocat/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/octocat/subscriptions", "organizations_url": "https://api.github.com/users/octocat/orgs", "repos_url": "https://api.github.com/users/octocat/repos", "events_url": "https://api.github.com/users/octocat/events{/privacy}", "received_events_url": "https://api.github.com/users/octocat/received_events", "type": "User", "site_admin": false }, "body": "Hi! This is an area for us to collaborate as a team.", "body_html": "

      Hi! This is an area for us to collaborate as a team

      ", "body_version": "0d495416a700fb06133c612575d92bfb", "comments_count": 0, "comments_url": "https://api.github.com/teams/2343027/discussions/1/comments", "created_at": "2018-01-25T18:56:31Z", "last_edited_at": null, "html_url": "https://github.com/orgs/github/teams/justice-league/discussions/1", "node_id": "MDE0OlRlYW1EaXNjdXNzaW9uMQ==", "number": 1, "pinned": false, "private": false, "team_url": "https://api.github.com/teams/2343027", "title": "Our first team post", "updated_at": "2018-01-25T18:56:31Z", "url": "https://api.github.com/teams/2343027/discussions/1", "reactions": { "url": "https://api.github.com/teams/2343027/discussions/1/reactions", "total_count": 5, "+1": 3, "-1": 1, "laugh": 0, "confused": 0, "heart": 1, "hooray": 0, "eyes": 1, "rocket": 1 } } ] }, "team-discussion": { "value": { "author": { "login": "octocat", "id": 1, "node_id": "MDQ6VXNlcjE=", "avatar_url": "https://github.com/images/error/octocat_happy.gif", "gravatar_id": "", "url": "https://api.github.com/users/octocat", "html_url": "https://github.com/octocat", "followers_url": "https://api.github.com/users/octocat/followers", "following_url": "https://api.github.com/users/octocat/following{/other_user}", "gists_url": "https://api.github.com/users/octocat/gists{/gist_id}", "starred_url": "https://api.github.com/users/octocat/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/octocat/subscriptions", "organizations_url": "https://api.github.com/users/octocat/orgs", "repos_url": "https://api.github.com/users/octocat/repos", "events_url": "https://api.github.com/users/octocat/events{/privacy}", "received_events_url": "https://api.github.com/users/octocat/received_events", "type": "User", "site_admin": false }, "body": "Hi! This is an area for us to collaborate as a team.", "body_html": "

      Hi! This is an area for us to collaborate as a team

      ", "body_version": "0d495416a700fb06133c612575d92bfb", "comments_count": 0, "comments_url": "https://api.github.com/teams/2343027/discussions/1/comments", "created_at": "2018-01-25T18:56:31Z", "last_edited_at": null, "html_url": "https://github.com/orgs/github/teams/justice-league/discussions/1", "node_id": "MDE0OlRlYW1EaXNjdXNzaW9uMQ==", "number": 1, "pinned": false, "private": false, "team_url": "https://api.github.com/teams/2343027", "title": "Our first team post", "updated_at": "2018-01-25T18:56:31Z", "url": "https://api.github.com/teams/2343027/discussions/1", "reactions": { "url": "https://api.github.com/teams/2343027/discussions/1/reactions", "total_count": 5, "+1": 3, "-1": 1, "laugh": 0, "confused": 0, "heart": 1, "hooray": 0, "eyes": 1, "rocket": 1 } } }, "team-discussion-2": { "value": { "author": { "login": "octocat", "id": 1, "node_id": "MDQ6VXNlcjE=", "avatar_url": "https://github.com/images/error/octocat_happy.gif", "gravatar_id": "", "url": "https://api.github.com/users/octocat", "html_url": "https://github.com/octocat", "followers_url": "https://api.github.com/users/octocat/followers", "following_url": "https://api.github.com/users/octocat/following{/other_user}", "gists_url": "https://api.github.com/users/octocat/gists{/gist_id}", "starred_url": "https://api.github.com/users/octocat/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/octocat/subscriptions", "organizations_url": "https://api.github.com/users/octocat/orgs", "repos_url": "https://api.github.com/users/octocat/repos", "events_url": "https://api.github.com/users/octocat/events{/privacy}", "received_events_url": "https://api.github.com/users/octocat/received_events", "type": "User", "site_admin": false }, "body": "Hi! This is an area for us to collaborate as a team.", "body_html": "

      Hi! This is an area for us to collaborate as a team

      ", "body_version": "0d495416a700fb06133c612575d92bfb", "comments_count": 1, "comments_url": "https://api.github.com/teams/2343027/discussions/1/comments", "created_at": "2018-01-25T18:56:31Z", "last_edited_at": "2018-01-26T18:22:20Z", "html_url": "https://github.com/orgs/github/teams/justice-league/discussions/1", "node_id": "MDE0OlRlYW1EaXNjdXNzaW9uMQ==", "number": 1, "pinned": false, "private": false, "team_url": "https://api.github.com/teams/2343027", "title": "Welcome to our first team post", "updated_at": "2018-01-26T18:22:20Z", "url": "https://api.github.com/teams/2343027/discussions/1", "reactions": { "url": "https://api.github.com/teams/2343027/discussions/1/reactions", "total_count": 5, "+1": 3, "-1": 1, "laugh": 0, "confused": 0, "heart": 1, "hooray": 0, "eyes": 1, "rocket": 1 } } }, "team-discussion-comment-items": { "value": [ { "author": { "login": "octocat", "id": 1, "node_id": "MDQ6VXNlcjE=", "avatar_url": "https://github.com/images/error/octocat_happy.gif", "gravatar_id": "", "url": "https://api.github.com/users/octocat", "html_url": "https://github.com/octocat", "followers_url": "https://api.github.com/users/octocat/followers", "following_url": "https://api.github.com/users/octocat/following{/other_user}", "gists_url": "https://api.github.com/users/octocat/gists{/gist_id}", "starred_url": "https://api.github.com/users/octocat/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/octocat/subscriptions", "organizations_url": "https://api.github.com/users/octocat/orgs", "repos_url": "https://api.github.com/users/octocat/repos", "events_url": "https://api.github.com/users/octocat/events{/privacy}", "received_events_url": "https://api.github.com/users/octocat/received_events", "type": "User", "site_admin": false }, "body": "Do you like apples?", "body_html": "

      Do you like apples?

      ", "body_version": "5eb32b219cdc6a5a9b29ba5d6caa9c51", "created_at": "2018-01-15T23:53:58Z", "last_edited_at": null, "discussion_url": "https://api.github.com/teams/2403582/discussions/1", "html_url": "https://github.com/orgs/github/teams/justice-league/discussions/1/comments/1", "node_id": "MDIxOlRlYW1EaXNjdXNzaW9uQ29tbWVudDE=", "number": 1, "updated_at": "2018-01-15T23:53:58Z", "url": "https://api.github.com/teams/2403582/discussions/1/comments/1", "reactions": { "url": "https://api.github.com/teams/2403582/discussions/1/reactions", "total_count": 5, "+1": 3, "-1": 1, "laugh": 0, "confused": 0, "heart": 1, "hooray": 0, "eyes": 1, "rocket": 1 } } ] }, "team-discussion-comment": { "value": { "author": { "login": "octocat", "id": 1, "node_id": "MDQ6VXNlcjE=", "avatar_url": "https://github.com/images/error/octocat_happy.gif", "gravatar_id": "", "url": "https://api.github.com/users/octocat", "html_url": "https://github.com/octocat", "followers_url": "https://api.github.com/users/octocat/followers", "following_url": "https://api.github.com/users/octocat/following{/other_user}", "gists_url": "https://api.github.com/users/octocat/gists{/gist_id}", "starred_url": "https://api.github.com/users/octocat/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/octocat/subscriptions", "organizations_url": "https://api.github.com/users/octocat/orgs", "repos_url": "https://api.github.com/users/octocat/repos", "events_url": "https://api.github.com/users/octocat/events{/privacy}", "received_events_url": "https://api.github.com/users/octocat/received_events", "type": "User", "site_admin": false }, "body": "Do you like apples?", "body_html": "

      Do you like apples?

      ", "body_version": "5eb32b219cdc6a5a9b29ba5d6caa9c51", "created_at": "2018-01-15T23:53:58Z", "last_edited_at": null, "discussion_url": "https://api.github.com/teams/2403582/discussions/1", "html_url": "https://github.com/orgs/github/teams/justice-league/discussions/1/comments/1", "node_id": "MDIxOlRlYW1EaXNjdXNzaW9uQ29tbWVudDE=", "number": 1, "updated_at": "2018-01-15T23:53:58Z", "url": "https://api.github.com/teams/2403582/discussions/1/comments/1", "reactions": { "url": "https://api.github.com/teams/2403582/discussions/1/reactions", "total_count": 5, "+1": 3, "-1": 1, "laugh": 0, "confused": 0, "heart": 1, "hooray": 0, "eyes": 1, "rocket": 1 } } }, "team-discussion-comment-2": { "value": { "author": { "login": "octocat", "id": 1, "node_id": "MDQ6VXNlcjE=", "avatar_url": "https://github.com/images/error/octocat_happy.gif", "gravatar_id": "", "url": "https://api.github.com/users/octocat", "html_url": "https://github.com/octocat", "followers_url": "https://api.github.com/users/octocat/followers", "following_url": "https://api.github.com/users/octocat/following{/other_user}", "gists_url": "https://api.github.com/users/octocat/gists{/gist_id}", "starred_url": "https://api.github.com/users/octocat/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/octocat/subscriptions", "organizations_url": "https://api.github.com/users/octocat/orgs", "repos_url": "https://api.github.com/users/octocat/repos", "events_url": "https://api.github.com/users/octocat/events{/privacy}", "received_events_url": "https://api.github.com/users/octocat/received_events", "type": "User", "site_admin": false }, "body": "Do you like pineapples?", "body_html": "

      Do you like pineapples?

      ", "body_version": "e6907b24d9c93cc0c5024a7af5888116", "created_at": "2018-01-15T23:53:58Z", "last_edited_at": "2018-01-26T18:22:20Z", "discussion_url": "https://api.github.com/teams/2403582/discussions/1", "html_url": "https://github.com/orgs/github/teams/justice-league/discussions/1/comments/1", "node_id": "MDIxOlRlYW1EaXNjdXNzaW9uQ29tbWVudDE=", "number": 1, "updated_at": "2018-01-26T18:22:20Z", "url": "https://api.github.com/teams/2403582/discussions/1/comments/1", "reactions": { "url": "https://api.github.com/teams/2403582/discussions/1/reactions", "total_count": 5, "+1": 3, "-1": 1, "laugh": 0, "confused": 0, "heart": 1, "hooray": 0, "eyes": 1, "rocket": 1 } } }, "reaction-items": { "value": [ { "id": 1, "node_id": "MDg6UmVhY3Rpb24x", "user": { "login": "octocat", "id": 1, "node_id": "MDQ6VXNlcjE=", "avatar_url": "https://github.com/images/error/octocat_happy.gif", "gravatar_id": "", "url": "https://api.github.com/users/octocat", "html_url": "https://github.com/octocat", "followers_url": "https://api.github.com/users/octocat/followers", "following_url": "https://api.github.com/users/octocat/following{/other_user}", "gists_url": "https://api.github.com/users/octocat/gists{/gist_id}", "starred_url": "https://api.github.com/users/octocat/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/octocat/subscriptions", "organizations_url": "https://api.github.com/users/octocat/orgs", "repos_url": "https://api.github.com/users/octocat/repos", "events_url": "https://api.github.com/users/octocat/events{/privacy}", "received_events_url": "https://api.github.com/users/octocat/received_events", "type": "User", "site_admin": false }, "content": "heart", "created_at": "2016-05-20T20:09:31Z" } ] }, "reaction": { "value": { "id": 1, "node_id": "MDg6UmVhY3Rpb24x", "user": { "login": "octocat", "id": 1, "node_id": "MDQ6VXNlcjE=", "avatar_url": "https://github.com/images/error/octocat_happy.gif", "gravatar_id": "", "url": "https://api.github.com/users/octocat", "html_url": "https://github.com/octocat", "followers_url": "https://api.github.com/users/octocat/followers", "following_url": "https://api.github.com/users/octocat/following{/other_user}", "gists_url": "https://api.github.com/users/octocat/gists{/gist_id}", "starred_url": "https://api.github.com/users/octocat/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/octocat/subscriptions", "organizations_url": "https://api.github.com/users/octocat/orgs", "repos_url": "https://api.github.com/users/octocat/repos", "events_url": "https://api.github.com/users/octocat/events{/privacy}", "received_events_url": "https://api.github.com/users/octocat/received_events", "type": "User", "site_admin": false }, "content": "heart", "created_at": "2016-05-20T20:09:31Z" } }, "team-membership-response-if-user-is-a-team-maintainer": { "summary": "Response if user is a team maintainer", "value": { "url": "https://api.github.com/teams/1/memberships/octocat", "role": "maintainer", "state": "active" } }, "team-membership-response-if-users-membership-with-team-is-now-pending": { "summary": "Response if user's membership with team is now pending", "value": { "url": "https://api.github.com/teams/1/memberships/octocat", "role": "member", "state": "pending" } }, "team-project-items": { "value": [ { "owner_url": "https://api.github.com/orgs/octocat", "url": "https://api.github.com/projects/1002605", "html_url": "https://github.com/orgs/api-playground/projects/1", "columns_url": "https://api.github.com/projects/1002605/columns", "id": 1002605, "node_id": "MDc6UHJvamVjdDEwMDI2MDU=", "name": "Organization Roadmap", "body": "High-level roadmap for the upcoming year.", "number": 1, "state": "open", "creator": { "login": "octocat", "id": 1, "node_id": "MDQ6VXNlcjE=", "avatar_url": "https://github.com/images/error/octocat_happy.gif", "gravatar_id": "", "url": "https://api.github.com/users/octocat", "html_url": "https://github.com/octocat", "followers_url": "https://api.github.com/users/octocat/followers", "following_url": "https://api.github.com/users/octocat/following{/other_user}", "gists_url": "https://api.github.com/users/octocat/gists{/gist_id}", "starred_url": "https://api.github.com/users/octocat/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/octocat/subscriptions", "organizations_url": "https://api.github.com/users/octocat/orgs", "repos_url": "https://api.github.com/users/octocat/repos", "events_url": "https://api.github.com/users/octocat/events{/privacy}", "received_events_url": "https://api.github.com/users/octocat/received_events", "type": "User", "site_admin": false }, "created_at": "2011-04-11T20:09:31Z", "updated_at": "2014-03-04T18:58:10Z", "organization_permission": "write", "private": false, "permissions": { "read": true, "write": true, "admin": false } } ] }, "team-project": { "value": { "owner_url": "https://api.github.com/orgs/octocat", "url": "https://api.github.com/projects/1002605", "html_url": "https://github.com/orgs/api-playground/projects/1", "columns_url": "https://api.github.com/projects/1002605/columns", "id": 1002605, "node_id": "MDc6UHJvamVjdDEwMDI2MDU=", "name": "Organization Roadmap", "body": "High-level roadmap for the upcoming year.", "number": 1, "state": "open", "creator": { "login": "octocat", "id": 1, "node_id": "MDQ6VXNlcjE=", "avatar_url": "https://github.com/images/error/octocat_happy.gif", "gravatar_id": "", "url": "https://api.github.com/users/octocat", "html_url": "https://github.com/octocat", "followers_url": "https://api.github.com/users/octocat/followers", "following_url": "https://api.github.com/users/octocat/following{/other_user}", "gists_url": "https://api.github.com/users/octocat/gists{/gist_id}", "starred_url": "https://api.github.com/users/octocat/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/octocat/subscriptions", "organizations_url": "https://api.github.com/users/octocat/orgs", "repos_url": "https://api.github.com/users/octocat/repos", "events_url": "https://api.github.com/users/octocat/events{/privacy}", "received_events_url": "https://api.github.com/users/octocat/received_events", "type": "User", "site_admin": false }, "created_at": "2011-04-11T20:09:31Z", "updated_at": "2014-03-04T18:58:10Z", "organization_permission": "write", "private": false, "permissions": { "read": true, "write": true, "admin": false } } }, "team-repository-alternative-response-with-repository-permissions": { "value": { "id": 1296269, "node_id": "MDEwOlJlcG9zaXRvcnkxMjk2MjY5", "name": "Hello-World", "full_name": "octocat/Hello-World", "owner": { "login": "octocat", "id": 1, "node_id": "MDQ6VXNlcjE=", "avatar_url": "https://github.com/images/error/octocat_happy.gif", "gravatar_id": "", "url": "https://api.github.com/users/octocat", "html_url": "https://github.com/octocat", "followers_url": "https://api.github.com/users/octocat/followers", "following_url": "https://api.github.com/users/octocat/following{/other_user}", "gists_url": "https://api.github.com/users/octocat/gists{/gist_id}", "starred_url": "https://api.github.com/users/octocat/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/octocat/subscriptions", "organizations_url": "https://api.github.com/users/octocat/orgs", "repos_url": "https://api.github.com/users/octocat/repos", "events_url": "https://api.github.com/users/octocat/events{/privacy}", "received_events_url": "https://api.github.com/users/octocat/received_events", "type": "User", "site_admin": false }, "private": false, "html_url": "https://github.com/octocat/Hello-World", "description": "This your first repo!", "fork": false, "url": "https://api.github.com/repos/octocat/Hello-World", "archive_url": "https://api.github.com/repos/octocat/Hello-World/{archive_format}{/ref}", "assignees_url": "https://api.github.com/repos/octocat/Hello-World/assignees{/user}", "blobs_url": "https://api.github.com/repos/octocat/Hello-World/git/blobs{/sha}", "branches_url": "https://api.github.com/repos/octocat/Hello-World/branches{/branch}", "collaborators_url": "https://api.github.com/repos/octocat/Hello-World/collaborators{/collaborator}", "comments_url": "https://api.github.com/repos/octocat/Hello-World/comments{/number}", "commits_url": "https://api.github.com/repos/octocat/Hello-World/commits{/sha}", "compare_url": "https://api.github.com/repos/octocat/Hello-World/compare/{base}...{head}", "contents_url": "https://api.github.com/repos/octocat/Hello-World/contents/{+path}", "contributors_url": "https://api.github.com/repos/octocat/Hello-World/contributors", "deployments_url": "https://api.github.com/repos/octocat/Hello-World/deployments", "downloads_url": "https://api.github.com/repos/octocat/Hello-World/downloads", "events_url": "https://api.github.com/repos/octocat/Hello-World/events", "forks_url": "https://api.github.com/repos/octocat/Hello-World/forks", "git_commits_url": "https://api.github.com/repos/octocat/Hello-World/git/commits{/sha}", "git_refs_url": "https://api.github.com/repos/octocat/Hello-World/git/refs{/sha}", "git_tags_url": "https://api.github.com/repos/octocat/Hello-World/git/tags{/sha}", "git_url": "git:github.com/octocat/Hello-World.git", "issue_comment_url": "https://api.github.com/repos/octocat/Hello-World/issues/comments{/number}", "issue_events_url": "https://api.github.com/repos/octocat/Hello-World/issues/events{/number}", "issues_url": "https://api.github.com/repos/octocat/Hello-World/issues{/number}", "keys_url": "https://api.github.com/repos/octocat/Hello-World/keys{/key_id}", "labels_url": "https://api.github.com/repos/octocat/Hello-World/labels{/name}", "languages_url": "https://api.github.com/repos/octocat/Hello-World/languages", "merges_url": "https://api.github.com/repos/octocat/Hello-World/merges", "milestones_url": "https://api.github.com/repos/octocat/Hello-World/milestones{/number}", "notifications_url": "https://api.github.com/repos/octocat/Hello-World/notifications{?since,all,participating}", "pulls_url": "https://api.github.com/repos/octocat/Hello-World/pulls{/number}", "releases_url": "https://api.github.com/repos/octocat/Hello-World/releases{/id}", "ssh_url": "git@github.com:octocat/Hello-World.git", "stargazers_url": "https://api.github.com/repos/octocat/Hello-World/stargazers", "statuses_url": "https://api.github.com/repos/octocat/Hello-World/statuses/{sha}", "subscribers_url": "https://api.github.com/repos/octocat/Hello-World/subscribers", "subscription_url": "https://api.github.com/repos/octocat/Hello-World/subscription", "tags_url": "https://api.github.com/repos/octocat/Hello-World/tags", "teams_url": "https://api.github.com/repos/octocat/Hello-World/teams", "trees_url": "https://api.github.com/repos/octocat/Hello-World/git/trees{/sha}", "clone_url": "https://github.com/octocat/Hello-World.git", "mirror_url": "git:git.example.com/octocat/Hello-World", "hooks_url": "https://api.github.com/repos/octocat/Hello-World/hooks", "svn_url": "https://svn.github.com/octocat/Hello-World", "homepage": "https://github.com", "forks_count": 9, "stargazers_count": 80, "watchers_count": 80, "size": 108, "default_branch": "master", "open_issues_count": 0, "is_template": false, "topics": [ "octocat", "atom", "electron", "api" ], "has_issues": true, "has_projects": true, "has_wiki": true, "has_pages": false, "has_downloads": true, "archived": false, "disabled": false, "visibility": "public", "pushed_at": "2011-01-26T19:06:43Z", "created_at": "2011-01-26T19:01:12Z", "updated_at": "2011-01-26T19:14:43Z", "permissions": { "admin": false, "maintain": false, "push": false, "triage": false, "pull": true }, "allow_rebase_merge": true, "template_repository": { "id": 1296269, "node_id": "MDEwOlJlcG9zaXRvcnkxMjk2MjY5", "name": "Hello-World-Template", "full_name": "octocat/Hello-World-Template", "owner": { "login": "octocat", "id": 1, "node_id": "MDQ6VXNlcjE=", "avatar_url": "https://github.com/images/error/octocat_happy.gif", "gravatar_id": "", "url": "https://api.github.com/users/octocat", "html_url": "https://github.com/octocat", "followers_url": "https://api.github.com/users/octocat/followers", "following_url": "https://api.github.com/users/octocat/following{/other_user}", "gists_url": "https://api.github.com/users/octocat/gists{/gist_id}", "starred_url": "https://api.github.com/users/octocat/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/octocat/subscriptions", "organizations_url": "https://api.github.com/users/octocat/orgs", "repos_url": "https://api.github.com/users/octocat/repos", "events_url": "https://api.github.com/users/octocat/events{/privacy}", "received_events_url": "https://api.github.com/users/octocat/received_events", "type": "User", "site_admin": false }, "private": false, "html_url": "https://github.com/octocat/Hello-World-Template", "description": "This your first repo!", "fork": false, "url": "https://api.github.com/repos/octocat/Hello-World-Template", "archive_url": "https://api.github.com/repos/octocat/Hello-World-Template/{archive_format}{/ref}", "assignees_url": "https://api.github.com/repos/octocat/Hello-World-Template/assignees{/user}", "blobs_url": "https://api.github.com/repos/octocat/Hello-World-Template/git/blobs{/sha}", "branches_url": "https://api.github.com/repos/octocat/Hello-World-Template/branches{/branch}", "collaborators_url": "https://api.github.com/repos/octocat/Hello-World-Template/collaborators{/collaborator}", "comments_url": "https://api.github.com/repos/octocat/Hello-World-Template/comments{/number}", "commits_url": "https://api.github.com/repos/octocat/Hello-World-Template/commits{/sha}", "compare_url": "https://api.github.com/repos/octocat/Hello-World-Template/compare/{base}...{head}", "contents_url": "https://api.github.com/repos/octocat/Hello-World-Template/contents/{+path}", "contributors_url": "https://api.github.com/repos/octocat/Hello-World-Template/contributors", "deployments_url": "https://api.github.com/repos/octocat/Hello-World-Template/deployments", "downloads_url": "https://api.github.com/repos/octocat/Hello-World-Template/downloads", "events_url": "https://api.github.com/repos/octocat/Hello-World-Template/events", "forks_url": "https://api.github.com/repos/octocat/Hello-World-Template/forks", "git_commits_url": "https://api.github.com/repos/octocat/Hello-World-Template/git/commits{/sha}", "git_refs_url": "https://api.github.com/repos/octocat/Hello-World-Template/git/refs{/sha}", "git_tags_url": "https://api.github.com/repos/octocat/Hello-World-Template/git/tags{/sha}", "git_url": "git:github.com/octocat/Hello-World-Template.git", "issue_comment_url": "https://api.github.com/repos/octocat/Hello-World-Template/issues/comments{/number}", "issue_events_url": "https://api.github.com/repos/octocat/Hello-World-Template/issues/events{/number}", "issues_url": "https://api.github.com/repos/octocat/Hello-World-Template/issues{/number}", "keys_url": "https://api.github.com/repos/octocat/Hello-World-Template/keys{/key_id}", "labels_url": "https://api.github.com/repos/octocat/Hello-World-Template/labels{/name}", "languages_url": "https://api.github.com/repos/octocat/Hello-World-Template/languages", "merges_url": "https://api.github.com/repos/octocat/Hello-World-Template/merges", "milestones_url": "https://api.github.com/repos/octocat/Hello-World-Template/milestones{/number}", "notifications_url": "https://api.github.com/repos/octocat/Hello-World-Template/notifications{?since,all,participating}", "pulls_url": "https://api.github.com/repos/octocat/Hello-World-Template/pulls{/number}", "releases_url": "https://api.github.com/repos/octocat/Hello-World-Template/releases{/id}", "ssh_url": "git@github.com:octocat/Hello-World-Template.git", "stargazers_url": "https://api.github.com/repos/octocat/Hello-World-Template/stargazers", "statuses_url": "https://api.github.com/repos/octocat/Hello-World-Template/statuses/{sha}", "subscribers_url": "https://api.github.com/repos/octocat/Hello-World-Template/subscribers", "subscription_url": "https://api.github.com/repos/octocat/Hello-World-Template/subscription", "tags_url": "https://api.github.com/repos/octocat/Hello-World-Template/tags", "teams_url": "https://api.github.com/repos/octocat/Hello-World-Template/teams", "trees_url": "https://api.github.com/repos/octocat/Hello-World-Template/git/trees{/sha}", "clone_url": "https://github.com/octocat/Hello-World-Template.git", "mirror_url": "git:git.example.com/octocat/Hello-World-Template", "hooks_url": "https://api.github.com/repos/octocat/Hello-World-Template/hooks", "svn_url": "https://svn.github.com/octocat/Hello-World-Template", "homepage": "https://github.com", "forks": 9, "forks_count": 9, "stargazers_count": 80, "watchers_count": 80, "watchers": 80, "size": 108, "default_branch": "master", "open_issues": 0, "open_issues_count": 0, "is_template": true, "license": { "key": "mit", "name": "MIT License", "url": "https://api.github.com/licenses/mit", "spdx_id": "MIT", "node_id": "MDc6TGljZW5zZW1pdA==", "html_url": "https://api.github.com/licenses/mit" }, "topics": [ "octocat", "atom", "electron", "api" ], "has_issues": true, "has_projects": true, "has_wiki": true, "has_pages": false, "has_downloads": true, "archived": false, "disabled": false, "visibility": "public", "pushed_at": "2011-01-26T19:06:43Z", "created_at": "2011-01-26T19:01:12Z", "updated_at": "2011-01-26T19:14:43Z", "permissions": { "pull": true, "triage": false, "push": false, "maintain": false, "admin": false }, "allow_rebase_merge": true, "temp_clone_token": "ABTLWHOULUVAXGTRYU7OC2876QJ2O", "allow_squash_merge": true, "delete_branch_on_merge": true, "allow_merge_commit": true, "subscribers_count": 42, "network_count": 0 }, "temp_clone_token": "ABTLWHOULUVAXGTRYU7OC2876QJ2O", "allow_squash_merge": true, "delete_branch_on_merge": true, "allow_merge_commit": true, "subscribers_count": 42, "network_count": 0, "license": { "key": "mit", "name": "MIT License", "url": "https://api.github.com/licenses/mit", "spdx_id": "MIT", "node_id": "MDc6TGljZW5zZW1pdA==", "html_url": "https://api.github.com/licenses/mit" }, "forks": 1, "open_issues": 1, "watchers": 1 } }, "team-items-response-if-child-teams-exist": { "value": [ { "id": 2, "node_id": "MDQ6VGVhbTI=", "url": "https://api.github.com/teams/2", "name": "Original Roster", "slug": "original-roster", "description": "Started it all.", "privacy": "closed", "permission": "admin", "members_url": "https://api.github.com/teams/2/members{/member}", "repositories_url": "https://api.github.com/teams/2/repos", "parent": { "id": 1, "node_id": "MDQ6VGVhbTE=", "url": "https://api.github.com/teams/1", "html_url": "https://github.com/orgs/github/teams/justice-league", "name": "Justice League", "slug": "justice-league", "description": "A great team.", "privacy": "closed", "permission": "admin", "members_url": "https://api.github.com/teams/1/members{/member}", "repositories_url": "https://api.github.com/teams/1/repos" }, "html_url": "https://github.com/orgs/rails/teams/core" } ] }, "project-card": { "value": { "url": "https://api.github.com/projects/columns/cards/1478", "id": 1478, "node_id": "MDExOlByb2plY3RDYXJkMTQ3OA==", "note": "Add payload for delete Project column", "creator": { "login": "octocat", "id": 1, "node_id": "MDQ6VXNlcjE=", "avatar_url": "https://github.com/images/error/octocat_happy.gif", "gravatar_id": "", "url": "https://api.github.com/users/octocat", "html_url": "https://github.com/octocat", "followers_url": "https://api.github.com/users/octocat/followers", "following_url": "https://api.github.com/users/octocat/following{/other_user}", "gists_url": "https://api.github.com/users/octocat/gists{/gist_id}", "starred_url": "https://api.github.com/users/octocat/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/octocat/subscriptions", "organizations_url": "https://api.github.com/users/octocat/orgs", "repos_url": "https://api.github.com/users/octocat/repos", "events_url": "https://api.github.com/users/octocat/events{/privacy}", "received_events_url": "https://api.github.com/users/octocat/received_events", "type": "User", "site_admin": false }, "created_at": "2016-09-05T14:21:06Z", "updated_at": "2016-09-05T14:20:22Z", "archived": false, "column_url": "https://api.github.com/projects/columns/367", "content_url": "https://api.github.com/repos/api-playground/projects-test/issues/3", "project_url": "https://api.github.com/projects/120" } }, "project-column": { "value": { "url": "https://api.github.com/projects/columns/367", "project_url": "https://api.github.com/projects/120", "cards_url": "https://api.github.com/projects/columns/367/cards", "id": 367, "node_id": "MDEzOlByb2plY3RDb2x1bW4zNjc=", "name": "To Do", "created_at": "2016-09-05T14:18:44Z", "updated_at": "2016-09-05T14:22:28Z" } }, "project-card-items": { "value": [ { "url": "https://api.github.com/projects/columns/cards/1478", "id": 1478, "node_id": "MDExOlByb2plY3RDYXJkMTQ3OA==", "note": "Add payload for delete Project column", "creator": { "login": "octocat", "id": 1, "node_id": "MDQ6VXNlcjE=", "avatar_url": "https://github.com/images/error/octocat_happy.gif", "gravatar_id": "", "url": "https://api.github.com/users/octocat", "html_url": "https://github.com/octocat", "followers_url": "https://api.github.com/users/octocat/followers", "following_url": "https://api.github.com/users/octocat/following{/other_user}", "gists_url": "https://api.github.com/users/octocat/gists{/gist_id}", "starred_url": "https://api.github.com/users/octocat/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/octocat/subscriptions", "organizations_url": "https://api.github.com/users/octocat/orgs", "repos_url": "https://api.github.com/users/octocat/repos", "events_url": "https://api.github.com/users/octocat/events{/privacy}", "received_events_url": "https://api.github.com/users/octocat/received_events", "type": "User", "site_admin": false }, "created_at": "2016-09-05T14:21:06Z", "updated_at": "2016-09-05T14:20:22Z", "archived": false, "column_url": "https://api.github.com/projects/columns/367", "content_url": "https://api.github.com/repos/api-playground/projects-test/issues/3", "project_url": "https://api.github.com/projects/120" } ] }, "project-3": { "value": { "owner_url": "https://api.github.com/repos/api-playground/projects-test", "url": "https://api.github.com/projects/1002604", "html_url": "https://github.com/api-playground/projects-test/projects/1", "columns_url": "https://api.github.com/projects/1002604/columns", "id": 1002604, "node_id": "MDc6UHJvamVjdDEwMDI2MDQ=", "name": "Projects Documentation", "body": "Developer documentation project for the developer site.", "number": 1, "state": "open", "creator": { "login": "octocat", "id": 1, "node_id": "MDQ6VXNlcjE=", "avatar_url": "https://github.com/images/error/octocat_happy.gif", "gravatar_id": "", "url": "https://api.github.com/users/octocat", "html_url": "https://github.com/octocat", "followers_url": "https://api.github.com/users/octocat/followers", "following_url": "https://api.github.com/users/octocat/following{/other_user}", "gists_url": "https://api.github.com/users/octocat/gists{/gist_id}", "starred_url": "https://api.github.com/users/octocat/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/octocat/subscriptions", "organizations_url": "https://api.github.com/users/octocat/orgs", "repos_url": "https://api.github.com/users/octocat/repos", "events_url": "https://api.github.com/users/octocat/events{/privacy}", "received_events_url": "https://api.github.com/users/octocat/received_events", "type": "User", "site_admin": false }, "created_at": "2011-04-10T20:09:31Z", "updated_at": "2014-03-03T18:58:10Z" } }, "project-collaborator-permission": { "value": { "permission": "admin", "user": { "login": "octocat", "id": 1, "node_id": "MDQ6VXNlcjE=", "avatar_url": "https://github.com/images/error/octocat_happy.gif", "gravatar_id": "", "url": "https://api.github.com/users/octocat", "html_url": "https://github.com/octocat", "followers_url": "https://api.github.com/users/octocat/followers", "following_url": "https://api.github.com/users/octocat/following{/other_user}", "gists_url": "https://api.github.com/users/octocat/gists{/gist_id}", "starred_url": "https://api.github.com/users/octocat/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/octocat/subscriptions", "organizations_url": "https://api.github.com/users/octocat/orgs", "repos_url": "https://api.github.com/users/octocat/repos", "events_url": "https://api.github.com/users/octocat/events{/privacy}", "received_events_url": "https://api.github.com/users/octocat/received_events", "type": "User", "site_admin": false } } }, "project-column-items": { "value": [ { "url": "https://api.github.com/projects/columns/367", "project_url": "https://api.github.com/projects/120", "cards_url": "https://api.github.com/projects/columns/367/cards", "id": 367, "node_id": "MDEzOlByb2plY3RDb2x1bW4zNjc=", "name": "To Do", "created_at": "2016-09-05T14:18:44Z", "updated_at": "2016-09-05T14:22:28Z" } ] }, "rate-limit-overview": { "value": { "resources": { "core": { "limit": 5000, "remaining": 4999, "reset": 1372700873, "used": 1 }, "search": { "limit": 30, "remaining": 18, "reset": 1372697452, "used": 12 }, "graphql": { "limit": 5000, "remaining": 4993, "reset": 1372700389, "used": 7 }, "integration_manifest": { "limit": 5000, "remaining": 4999, "reset": 1551806725, "used": 1 }, "code_scanning_upload": { "limit": 500, "remaining": 499, "reset": 1551806725, "used": 1 } }, "rate": { "limit": 5000, "remaining": 4999, "reset": 1372700873, "used": 1 } } }, "full-repository-default-response": { "summary": "Default response", "value": { "id": 1296269, "node_id": "MDEwOlJlcG9zaXRvcnkxMjk2MjY5", "name": "Hello-World", "full_name": "octocat/Hello-World", "owner": { "login": "octocat", "id": 1, "node_id": "MDQ6VXNlcjE=", "avatar_url": "https://github.com/images/error/octocat_happy.gif", "gravatar_id": "", "url": "https://api.github.com/users/octocat", "html_url": "https://github.com/octocat", "followers_url": "https://api.github.com/users/octocat/followers", "following_url": "https://api.github.com/users/octocat/following{/other_user}", "gists_url": "https://api.github.com/users/octocat/gists{/gist_id}", "starred_url": "https://api.github.com/users/octocat/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/octocat/subscriptions", "organizations_url": "https://api.github.com/users/octocat/orgs", "repos_url": "https://api.github.com/users/octocat/repos", "events_url": "https://api.github.com/users/octocat/events{/privacy}", "received_events_url": "https://api.github.com/users/octocat/received_events", "type": "User", "site_admin": false }, "private": false, "html_url": "https://github.com/octocat/Hello-World", "description": "This your first repo!", "fork": false, "url": "https://api.github.com/repos/octocat/Hello-World", "archive_url": "https://api.github.com/repos/octocat/Hello-World/{archive_format}{/ref}", "assignees_url": "https://api.github.com/repos/octocat/Hello-World/assignees{/user}", "blobs_url": "https://api.github.com/repos/octocat/Hello-World/git/blobs{/sha}", "branches_url": "https://api.github.com/repos/octocat/Hello-World/branches{/branch}", "collaborators_url": "https://api.github.com/repos/octocat/Hello-World/collaborators{/collaborator}", "comments_url": "https://api.github.com/repos/octocat/Hello-World/comments{/number}", "commits_url": "https://api.github.com/repos/octocat/Hello-World/commits{/sha}", "compare_url": "https://api.github.com/repos/octocat/Hello-World/compare/{base}...{head}", "contents_url": "https://api.github.com/repos/octocat/Hello-World/contents/{+path}", "contributors_url": "https://api.github.com/repos/octocat/Hello-World/contributors", "deployments_url": "https://api.github.com/repos/octocat/Hello-World/deployments", "downloads_url": "https://api.github.com/repos/octocat/Hello-World/downloads", "events_url": "https://api.github.com/repos/octocat/Hello-World/events", "forks_url": "https://api.github.com/repos/octocat/Hello-World/forks", "git_commits_url": "https://api.github.com/repos/octocat/Hello-World/git/commits{/sha}", "git_refs_url": "https://api.github.com/repos/octocat/Hello-World/git/refs{/sha}", "git_tags_url": "https://api.github.com/repos/octocat/Hello-World/git/tags{/sha}", "git_url": "git:github.com/octocat/Hello-World.git", "issue_comment_url": "https://api.github.com/repos/octocat/Hello-World/issues/comments{/number}", "issue_events_url": "https://api.github.com/repos/octocat/Hello-World/issues/events{/number}", "issues_url": "https://api.github.com/repos/octocat/Hello-World/issues{/number}", "keys_url": "https://api.github.com/repos/octocat/Hello-World/keys{/key_id}", "labels_url": "https://api.github.com/repos/octocat/Hello-World/labels{/name}", "languages_url": "https://api.github.com/repos/octocat/Hello-World/languages", "merges_url": "https://api.github.com/repos/octocat/Hello-World/merges", "milestones_url": "https://api.github.com/repos/octocat/Hello-World/milestones{/number}", "notifications_url": "https://api.github.com/repos/octocat/Hello-World/notifications{?since,all,participating}", "pulls_url": "https://api.github.com/repos/octocat/Hello-World/pulls{/number}", "releases_url": "https://api.github.com/repos/octocat/Hello-World/releases{/id}", "ssh_url": "git@github.com:octocat/Hello-World.git", "stargazers_url": "https://api.github.com/repos/octocat/Hello-World/stargazers", "statuses_url": "https://api.github.com/repos/octocat/Hello-World/statuses/{sha}", "subscribers_url": "https://api.github.com/repos/octocat/Hello-World/subscribers", "subscription_url": "https://api.github.com/repos/octocat/Hello-World/subscription", "tags_url": "https://api.github.com/repos/octocat/Hello-World/tags", "teams_url": "https://api.github.com/repos/octocat/Hello-World/teams", "trees_url": "https://api.github.com/repos/octocat/Hello-World/git/trees{/sha}", "clone_url": "https://github.com/octocat/Hello-World.git", "mirror_url": "git:git.example.com/octocat/Hello-World", "hooks_url": "https://api.github.com/repos/octocat/Hello-World/hooks", "svn_url": "https://svn.github.com/octocat/Hello-World", "homepage": "https://github.com", "forks_count": 9, "forks": 9, "stargazers_count": 80, "watchers_count": 80, "watchers": 80, "size": 108, "default_branch": "master", "open_issues_count": 0, "open_issues": 0, "is_template": false, "topics": [ "octocat", "atom", "electron", "api" ], "has_issues": true, "has_projects": true, "has_wiki": true, "has_pages": false, "has_downloads": true, "archived": false, "disabled": false, "visibility": "public", "pushed_at": "2011-01-26T19:06:43Z", "created_at": "2011-01-26T19:01:12Z", "updated_at": "2011-01-26T19:14:43Z", "permissions": { "pull": true, "push": false, "admin": false }, "allow_rebase_merge": true, "template_repository": { "id": 1296269, "node_id": "MDEwOlJlcG9zaXRvcnkxMjk2MjY5", "name": "Hello-World-Template", "full_name": "octocat/Hello-World-Template", "owner": { "login": "octocat", "id": 1, "node_id": "MDQ6VXNlcjE=", "avatar_url": "https://github.com/images/error/octocat_happy.gif", "gravatar_id": "", "url": "https://api.github.com/users/octocat", "html_url": "https://github.com/octocat", "followers_url": "https://api.github.com/users/octocat/followers", "following_url": "https://api.github.com/users/octocat/following{/other_user}", "gists_url": "https://api.github.com/users/octocat/gists{/gist_id}", "starred_url": "https://api.github.com/users/octocat/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/octocat/subscriptions", "organizations_url": "https://api.github.com/users/octocat/orgs", "repos_url": "https://api.github.com/users/octocat/repos", "events_url": "https://api.github.com/users/octocat/events{/privacy}", "received_events_url": "https://api.github.com/users/octocat/received_events", "type": "User", "site_admin": false }, "private": false, "html_url": "https://github.com/octocat/Hello-World-Template", "description": "This your first repo!", "fork": false, "url": "https://api.github.com/repos/octocat/Hello-World-Template", "archive_url": "https://api.github.com/repos/octocat/Hello-World-Template/{archive_format}{/ref}", "assignees_url": "https://api.github.com/repos/octocat/Hello-World-Template/assignees{/user}", "blobs_url": "https://api.github.com/repos/octocat/Hello-World-Template/git/blobs{/sha}", "branches_url": "https://api.github.com/repos/octocat/Hello-World-Template/branches{/branch}", "collaborators_url": "https://api.github.com/repos/octocat/Hello-World-Template/collaborators{/collaborator}", "comments_url": "https://api.github.com/repos/octocat/Hello-World-Template/comments{/number}", "commits_url": "https://api.github.com/repos/octocat/Hello-World-Template/commits{/sha}", "compare_url": "https://api.github.com/repos/octocat/Hello-World-Template/compare/{base}...{head}", "contents_url": "https://api.github.com/repos/octocat/Hello-World-Template/contents/{+path}", "contributors_url": "https://api.github.com/repos/octocat/Hello-World-Template/contributors", "deployments_url": "https://api.github.com/repos/octocat/Hello-World-Template/deployments", "downloads_url": "https://api.github.com/repos/octocat/Hello-World-Template/downloads", "events_url": "https://api.github.com/repos/octocat/Hello-World-Template/events", "forks_url": "https://api.github.com/repos/octocat/Hello-World-Template/forks", "git_commits_url": "https://api.github.com/repos/octocat/Hello-World-Template/git/commits{/sha}", "git_refs_url": "https://api.github.com/repos/octocat/Hello-World-Template/git/refs{/sha}", "git_tags_url": "https://api.github.com/repos/octocat/Hello-World-Template/git/tags{/sha}", "git_url": "git:github.com/octocat/Hello-World-Template.git", "issue_comment_url": "https://api.github.com/repos/octocat/Hello-World-Template/issues/comments{/number}", "issue_events_url": "https://api.github.com/repos/octocat/Hello-World-Template/issues/events{/number}", "issues_url": "https://api.github.com/repos/octocat/Hello-World-Template/issues{/number}", "keys_url": "https://api.github.com/repos/octocat/Hello-World-Template/keys{/key_id}", "labels_url": "https://api.github.com/repos/octocat/Hello-World-Template/labels{/name}", "languages_url": "https://api.github.com/repos/octocat/Hello-World-Template/languages", "merges_url": "https://api.github.com/repos/octocat/Hello-World-Template/merges", "milestones_url": "https://api.github.com/repos/octocat/Hello-World-Template/milestones{/number}", "notifications_url": "https://api.github.com/repos/octocat/Hello-World-Template/notifications{?since,all,participating}", "pulls_url": "https://api.github.com/repos/octocat/Hello-World-Template/pulls{/number}", "releases_url": "https://api.github.com/repos/octocat/Hello-World-Template/releases{/id}", "ssh_url": "git@github.com:octocat/Hello-World-Template.git", "stargazers_url": "https://api.github.com/repos/octocat/Hello-World-Template/stargazers", "statuses_url": "https://api.github.com/repos/octocat/Hello-World-Template/statuses/{sha}", "subscribers_url": "https://api.github.com/repos/octocat/Hello-World-Template/subscribers", "subscription_url": "https://api.github.com/repos/octocat/Hello-World-Template/subscription", "tags_url": "https://api.github.com/repos/octocat/Hello-World-Template/tags", "teams_url": "https://api.github.com/repos/octocat/Hello-World-Template/teams", "trees_url": "https://api.github.com/repos/octocat/Hello-World-Template/git/trees{/sha}", "clone_url": "https://github.com/octocat/Hello-World-Template.git", "mirror_url": "git:git.example.com/octocat/Hello-World-Template", "hooks_url": "https://api.github.com/repos/octocat/Hello-World-Template/hooks", "svn_url": "https://svn.github.com/octocat/Hello-World-Template", "homepage": "https://github.com", "forks": 9, "forks_count": 9, "stargazers_count": 80, "watchers_count": 80, "watchers": 80, "size": 108, "default_branch": "master", "open_issues": 0, "open_issues_count": 0, "is_template": true, "license": { "key": "mit", "name": "MIT License", "url": "https://api.github.com/licenses/mit", "spdx_id": "MIT", "node_id": "MDc6TGljZW5zZW1pdA==", "html_url": "https://api.github.com/licenses/mit" }, "topics": [ "octocat", "atom", "electron", "api" ], "has_issues": true, "has_projects": true, "has_wiki": true, "has_pages": false, "has_downloads": true, "archived": false, "disabled": false, "visibility": "public", "pushed_at": "2011-01-26T19:06:43Z", "created_at": "2011-01-26T19:01:12Z", "updated_at": "2011-01-26T19:14:43Z", "permissions": { "admin": false, "push": false, "pull": true }, "allow_rebase_merge": true, "temp_clone_token": "ABTLWHOULUVAXGTRYU7OC2876QJ2O", "allow_squash_merge": true, "delete_branch_on_merge": true, "allow_merge_commit": true, "subscribers_count": 42, "network_count": 0 }, "temp_clone_token": "ABTLWHOULUVAXGTRYU7OC2876QJ2O", "allow_squash_merge": true, "delete_branch_on_merge": true, "allow_merge_commit": true, "subscribers_count": 42, "network_count": 0, "license": { "key": "mit", "name": "MIT License", "spdx_id": "MIT", "url": "https://api.github.com/licenses/mit", "node_id": "MDc6TGljZW5zZW1pdA==" }, "organization": { "login": "octocat", "id": 1, "node_id": "MDQ6VXNlcjE=", "avatar_url": "https://github.com/images/error/octocat_happy.gif", "gravatar_id": "", "url": "https://api.github.com/users/octocat", "html_url": "https://github.com/octocat", "followers_url": "https://api.github.com/users/octocat/followers", "following_url": "https://api.github.com/users/octocat/following{/other_user}", "gists_url": "https://api.github.com/users/octocat/gists{/gist_id}", "starred_url": "https://api.github.com/users/octocat/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/octocat/subscriptions", "organizations_url": "https://api.github.com/users/octocat/orgs", "repos_url": "https://api.github.com/users/octocat/repos", "events_url": "https://api.github.com/users/octocat/events{/privacy}", "received_events_url": "https://api.github.com/users/octocat/received_events", "type": "Organization", "site_admin": false }, "parent": { "id": 1296269, "node_id": "MDEwOlJlcG9zaXRvcnkxMjk2MjY5", "name": "Hello-World", "full_name": "octocat/Hello-World", "owner": { "login": "octocat", "id": 1, "node_id": "MDQ6VXNlcjE=", "avatar_url": "https://github.com/images/error/octocat_happy.gif", "gravatar_id": "", "url": "https://api.github.com/users/octocat", "html_url": "https://github.com/octocat", "followers_url": "https://api.github.com/users/octocat/followers", "following_url": "https://api.github.com/users/octocat/following{/other_user}", "gists_url": "https://api.github.com/users/octocat/gists{/gist_id}", "starred_url": "https://api.github.com/users/octocat/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/octocat/subscriptions", "organizations_url": "https://api.github.com/users/octocat/orgs", "repos_url": "https://api.github.com/users/octocat/repos", "events_url": "https://api.github.com/users/octocat/events{/privacy}", "received_events_url": "https://api.github.com/users/octocat/received_events", "type": "User", "site_admin": false }, "private": false, "html_url": "https://github.com/octocat/Hello-World", "description": "This your first repo!", "fork": false, "url": "https://api.github.com/repos/octocat/Hello-World", "archive_url": "https://api.github.com/repos/octocat/Hello-World/{archive_format}{/ref}", "assignees_url": "https://api.github.com/repos/octocat/Hello-World/assignees{/user}", "blobs_url": "https://api.github.com/repos/octocat/Hello-World/git/blobs{/sha}", "branches_url": "https://api.github.com/repos/octocat/Hello-World/branches{/branch}", "collaborators_url": "https://api.github.com/repos/octocat/Hello-World/collaborators{/collaborator}", "comments_url": "https://api.github.com/repos/octocat/Hello-World/comments{/number}", "commits_url": "https://api.github.com/repos/octocat/Hello-World/commits{/sha}", "compare_url": "https://api.github.com/repos/octocat/Hello-World/compare/{base}...{head}", "contents_url": "https://api.github.com/repos/octocat/Hello-World/contents/{+path}", "contributors_url": "https://api.github.com/repos/octocat/Hello-World/contributors", "deployments_url": "https://api.github.com/repos/octocat/Hello-World/deployments", "downloads_url": "https://api.github.com/repos/octocat/Hello-World/downloads", "events_url": "https://api.github.com/repos/octocat/Hello-World/events", "forks_url": "https://api.github.com/repos/octocat/Hello-World/forks", "git_commits_url": "https://api.github.com/repos/octocat/Hello-World/git/commits{/sha}", "git_refs_url": "https://api.github.com/repos/octocat/Hello-World/git/refs{/sha}", "git_tags_url": "https://api.github.com/repos/octocat/Hello-World/git/tags{/sha}", "git_url": "git:github.com/octocat/Hello-World.git", "issue_comment_url": "https://api.github.com/repos/octocat/Hello-World/issues/comments{/number}", "issue_events_url": "https://api.github.com/repos/octocat/Hello-World/issues/events{/number}", "issues_url": "https://api.github.com/repos/octocat/Hello-World/issues{/number}", "keys_url": "https://api.github.com/repos/octocat/Hello-World/keys{/key_id}", "labels_url": "https://api.github.com/repos/octocat/Hello-World/labels{/name}", "languages_url": "https://api.github.com/repos/octocat/Hello-World/languages", "merges_url": "https://api.github.com/repos/octocat/Hello-World/merges", "milestones_url": "https://api.github.com/repos/octocat/Hello-World/milestones{/number}", "notifications_url": "https://api.github.com/repos/octocat/Hello-World/notifications{?since,all,participating}", "pulls_url": "https://api.github.com/repos/octocat/Hello-World/pulls{/number}", "releases_url": "https://api.github.com/repos/octocat/Hello-World/releases{/id}", "ssh_url": "git@github.com:octocat/Hello-World.git", "stargazers_url": "https://api.github.com/repos/octocat/Hello-World/stargazers", "statuses_url": "https://api.github.com/repos/octocat/Hello-World/statuses/{sha}", "subscribers_url": "https://api.github.com/repos/octocat/Hello-World/subscribers", "subscription_url": "https://api.github.com/repos/octocat/Hello-World/subscription", "tags_url": "https://api.github.com/repos/octocat/Hello-World/tags", "teams_url": "https://api.github.com/repos/octocat/Hello-World/teams", "trees_url": "https://api.github.com/repos/octocat/Hello-World/git/trees{/sha}", "clone_url": "https://github.com/octocat/Hello-World.git", "mirror_url": "git:git.example.com/octocat/Hello-World", "hooks_url": "https://api.github.com/repos/octocat/Hello-World/hooks", "svn_url": "https://svn.github.com/octocat/Hello-World", "homepage": "https://github.com", "forks_count": 9, "stargazers_count": 80, "watchers_count": 80, "size": 108, "default_branch": "master", "open_issues_count": 0, "is_template": true, "topics": [ "octocat", "atom", "electron", "api" ], "has_issues": true, "has_projects": true, "has_wiki": true, "has_pages": false, "has_downloads": true, "archived": false, "disabled": false, "visibility": "public", "pushed_at": "2011-01-26T19:06:43Z", "created_at": "2011-01-26T19:01:12Z", "updated_at": "2011-01-26T19:14:43Z", "permissions": { "admin": false, "push": false, "pull": true }, "allow_rebase_merge": true, "temp_clone_token": "ABTLWHOULUVAXGTRYU7OC2876QJ2O", "allow_squash_merge": true, "delete_branch_on_merge": true, "allow_merge_commit": true, "subscribers_count": 42, "network_count": 0, "license": { "key": "mit", "name": "MIT License", "url": "https://api.github.com/licenses/mit", "spdx_id": "MIT", "node_id": "MDc6TGljZW5zZW1pdA==", "html_url": "https://api.github.com/licenses/mit" }, "forks": 1, "open_issues": 1, "watchers": 1 }, "source": { "id": 1296269, "node_id": "MDEwOlJlcG9zaXRvcnkxMjk2MjY5", "name": "Hello-World", "full_name": "octocat/Hello-World", "owner": { "login": "octocat", "id": 1, "node_id": "MDQ6VXNlcjE=", "avatar_url": "https://github.com/images/error/octocat_happy.gif", "gravatar_id": "", "url": "https://api.github.com/users/octocat", "html_url": "https://github.com/octocat", "followers_url": "https://api.github.com/users/octocat/followers", "following_url": "https://api.github.com/users/octocat/following{/other_user}", "gists_url": "https://api.github.com/users/octocat/gists{/gist_id}", "starred_url": "https://api.github.com/users/octocat/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/octocat/subscriptions", "organizations_url": "https://api.github.com/users/octocat/orgs", "repos_url": "https://api.github.com/users/octocat/repos", "events_url": "https://api.github.com/users/octocat/events{/privacy}", "received_events_url": "https://api.github.com/users/octocat/received_events", "type": "User", "site_admin": false }, "private": false, "html_url": "https://github.com/octocat/Hello-World", "description": "This your first repo!", "fork": false, "url": "https://api.github.com/repos/octocat/Hello-World", "archive_url": "https://api.github.com/repos/octocat/Hello-World/{archive_format}{/ref}", "assignees_url": "https://api.github.com/repos/octocat/Hello-World/assignees{/user}", "blobs_url": "https://api.github.com/repos/octocat/Hello-World/git/blobs{/sha}", "branches_url": "https://api.github.com/repos/octocat/Hello-World/branches{/branch}", "collaborators_url": "https://api.github.com/repos/octocat/Hello-World/collaborators{/collaborator}", "comments_url": "https://api.github.com/repos/octocat/Hello-World/comments{/number}", "commits_url": "https://api.github.com/repos/octocat/Hello-World/commits{/sha}", "compare_url": "https://api.github.com/repos/octocat/Hello-World/compare/{base}...{head}", "contents_url": "https://api.github.com/repos/octocat/Hello-World/contents/{+path}", "contributors_url": "https://api.github.com/repos/octocat/Hello-World/contributors", "deployments_url": "https://api.github.com/repos/octocat/Hello-World/deployments", "downloads_url": "https://api.github.com/repos/octocat/Hello-World/downloads", "events_url": "https://api.github.com/repos/octocat/Hello-World/events", "forks_url": "https://api.github.com/repos/octocat/Hello-World/forks", "git_commits_url": "https://api.github.com/repos/octocat/Hello-World/git/commits{/sha}", "git_refs_url": "https://api.github.com/repos/octocat/Hello-World/git/refs{/sha}", "git_tags_url": "https://api.github.com/repos/octocat/Hello-World/git/tags{/sha}", "git_url": "git:github.com/octocat/Hello-World.git", "issue_comment_url": "https://api.github.com/repos/octocat/Hello-World/issues/comments{/number}", "issue_events_url": "https://api.github.com/repos/octocat/Hello-World/issues/events{/number}", "issues_url": "https://api.github.com/repos/octocat/Hello-World/issues{/number}", "keys_url": "https://api.github.com/repos/octocat/Hello-World/keys{/key_id}", "labels_url": "https://api.github.com/repos/octocat/Hello-World/labels{/name}", "languages_url": "https://api.github.com/repos/octocat/Hello-World/languages", "merges_url": "https://api.github.com/repos/octocat/Hello-World/merges", "milestones_url": "https://api.github.com/repos/octocat/Hello-World/milestones{/number}", "notifications_url": "https://api.github.com/repos/octocat/Hello-World/notifications{?since,all,participating}", "pulls_url": "https://api.github.com/repos/octocat/Hello-World/pulls{/number}", "releases_url": "https://api.github.com/repos/octocat/Hello-World/releases{/id}", "ssh_url": "git@github.com:octocat/Hello-World.git", "stargazers_url": "https://api.github.com/repos/octocat/Hello-World/stargazers", "statuses_url": "https://api.github.com/repos/octocat/Hello-World/statuses/{sha}", "subscribers_url": "https://api.github.com/repos/octocat/Hello-World/subscribers", "subscription_url": "https://api.github.com/repos/octocat/Hello-World/subscription", "tags_url": "https://api.github.com/repos/octocat/Hello-World/tags", "teams_url": "https://api.github.com/repos/octocat/Hello-World/teams", "trees_url": "https://api.github.com/repos/octocat/Hello-World/git/trees{/sha}", "clone_url": "https://github.com/octocat/Hello-World.git", "mirror_url": "git:git.example.com/octocat/Hello-World", "hooks_url": "https://api.github.com/repos/octocat/Hello-World/hooks", "svn_url": "https://svn.github.com/octocat/Hello-World", "homepage": "https://github.com", "forks_count": 9, "stargazers_count": 80, "watchers_count": 80, "size": 108, "default_branch": "master", "open_issues_count": 0, "is_template": true, "topics": [ "octocat", "atom", "electron", "api" ], "has_issues": true, "has_projects": true, "has_wiki": true, "has_pages": false, "has_downloads": true, "archived": false, "disabled": false, "visibility": "public", "pushed_at": "2011-01-26T19:06:43Z", "created_at": "2011-01-26T19:01:12Z", "updated_at": "2011-01-26T19:14:43Z", "permissions": { "admin": false, "push": false, "pull": true }, "allow_rebase_merge": true, "temp_clone_token": "ABTLWHOULUVAXGTRYU7OC2876QJ2O", "allow_squash_merge": true, "delete_branch_on_merge": true, "allow_merge_commit": true, "subscribers_count": 42, "network_count": 0, "license": { "key": "mit", "name": "MIT License", "url": "https://api.github.com/licenses/mit", "spdx_id": "MIT", "node_id": "MDc6TGljZW5zZW1pdA==", "html_url": "https://api.github.com/licenses/mit" }, "forks": 1, "open_issues": 1, "watchers": 1 } } }, "full-repository-response-with-scarlet-witch-preview-media-type": { "summary": "Response with scarlet-witch-preview media type", "value": { "id": 1296269, "node_id": "MDEwOlJlcG9zaXRvcnkxMjk2MjY5", "name": "Hello-World", "full_name": "octocat/Hello-World", "owner": { "login": "octocat", "id": 1, "node_id": "MDQ6VXNlcjE=", "avatar_url": "https://github.com/images/error/octocat_happy.gif", "gravatar_id": "", "url": "https://api.github.com/users/octocat", "html_url": "https://github.com/octocat", "followers_url": "https://api.github.com/users/octocat/followers", "following_url": "https://api.github.com/users/octocat/following{/other_user}", "gists_url": "https://api.github.com/users/octocat/gists{/gist_id}", "starred_url": "https://api.github.com/users/octocat/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/octocat/subscriptions", "organizations_url": "https://api.github.com/users/octocat/orgs", "repos_url": "https://api.github.com/users/octocat/repos", "events_url": "https://api.github.com/users/octocat/events{/privacy}", "received_events_url": "https://api.github.com/users/octocat/received_events", "type": "User", "site_admin": false }, "private": false, "html_url": "https://github.com/octocat/Hello-World", "description": "This your first repo!", "fork": false, "url": "https://api.github.com/repos/octocat/Hello-World", "archive_url": "https://api.github.com/repos/octocat/Hello-World/{archive_format}{/ref}", "assignees_url": "https://api.github.com/repos/octocat/Hello-World/assignees{/user}", "blobs_url": "https://api.github.com/repos/octocat/Hello-World/git/blobs{/sha}", "branches_url": "https://api.github.com/repos/octocat/Hello-World/branches{/branch}", "collaborators_url": "https://api.github.com/repos/octocat/Hello-World/collaborators{/collaborator}", "comments_url": "https://api.github.com/repos/octocat/Hello-World/comments{/number}", "commits_url": "https://api.github.com/repos/octocat/Hello-World/commits{/sha}", "compare_url": "https://api.github.com/repos/octocat/Hello-World/compare/{base}...{head}", "contents_url": "https://api.github.com/repos/octocat/Hello-World/contents/{+path}", "contributors_url": "https://api.github.com/repos/octocat/Hello-World/contributors", "deployments_url": "https://api.github.com/repos/octocat/Hello-World/deployments", "downloads_url": "https://api.github.com/repos/octocat/Hello-World/downloads", "events_url": "https://api.github.com/repos/octocat/Hello-World/events", "forks_url": "https://api.github.com/repos/octocat/Hello-World/forks", "git_commits_url": "https://api.github.com/repos/octocat/Hello-World/git/commits{/sha}", "git_refs_url": "https://api.github.com/repos/octocat/Hello-World/git/refs{/sha}", "git_tags_url": "https://api.github.com/repos/octocat/Hello-World/git/tags{/sha}", "git_url": "git:github.com/octocat/Hello-World.git", "issue_comment_url": "https://api.github.com/repos/octocat/Hello-World/issues/comments{/number}", "issue_events_url": "https://api.github.com/repos/octocat/Hello-World/issues/events{/number}", "issues_url": "https://api.github.com/repos/octocat/Hello-World/issues{/number}", "keys_url": "https://api.github.com/repos/octocat/Hello-World/keys{/key_id}", "labels_url": "https://api.github.com/repos/octocat/Hello-World/labels{/name}", "languages_url": "https://api.github.com/repos/octocat/Hello-World/languages", "merges_url": "https://api.github.com/repos/octocat/Hello-World/merges", "milestones_url": "https://api.github.com/repos/octocat/Hello-World/milestones{/number}", "notifications_url": "https://api.github.com/repos/octocat/Hello-World/notifications{?since,all,participating}", "pulls_url": "https://api.github.com/repos/octocat/Hello-World/pulls{/number}", "releases_url": "https://api.github.com/repos/octocat/Hello-World/releases{/id}", "ssh_url": "git@github.com:octocat/Hello-World.git", "stargazers_url": "https://api.github.com/repos/octocat/Hello-World/stargazers", "statuses_url": "https://api.github.com/repos/octocat/Hello-World/statuses/{sha}", "subscribers_url": "https://api.github.com/repos/octocat/Hello-World/subscribers", "subscription_url": "https://api.github.com/repos/octocat/Hello-World/subscription", "tags_url": "https://api.github.com/repos/octocat/Hello-World/tags", "teams_url": "https://api.github.com/repos/octocat/Hello-World/teams", "trees_url": "https://api.github.com/repos/octocat/Hello-World/git/trees{/sha}", "clone_url": "https://github.com/octocat/Hello-World.git", "mirror_url": "git:git.example.com/octocat/Hello-World", "hooks_url": "https://api.github.com/repos/octocat/Hello-World/hooks", "svn_url": "https://svn.github.com/octocat/Hello-World", "homepage": "https://github.com", "forks_count": 9, "forks": 9, "stargazers_count": 80, "watchers_count": 80, "watchers": 80, "size": 108, "default_branch": "master", "open_issues_count": 0, "open_issues": 0, "is_template": false, "topics": [ "octocat", "atom", "electron", "api" ], "has_issues": true, "has_projects": true, "has_wiki": true, "has_pages": false, "has_downloads": true, "archived": false, "disabled": false, "visibility": "public", "pushed_at": "2011-01-26T19:06:43Z", "created_at": "2011-01-26T19:01:12Z", "updated_at": "2011-01-26T19:14:43Z", "permissions": { "pull": true, "push": false, "admin": false }, "allow_rebase_merge": true, "template_repository": { "id": 1296269, "node_id": "MDEwOlJlcG9zaXRvcnkxMjk2MjY5", "name": "Hello-World-Template", "full_name": "octocat/Hello-World-Template", "owner": { "login": "octocat", "id": 1, "node_id": "MDQ6VXNlcjE=", "avatar_url": "https://github.com/images/error/octocat_happy.gif", "gravatar_id": "", "url": "https://api.github.com/users/octocat", "html_url": "https://github.com/octocat", "followers_url": "https://api.github.com/users/octocat/followers", "following_url": "https://api.github.com/users/octocat/following{/other_user}", "gists_url": "https://api.github.com/users/octocat/gists{/gist_id}", "starred_url": "https://api.github.com/users/octocat/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/octocat/subscriptions", "organizations_url": "https://api.github.com/users/octocat/orgs", "repos_url": "https://api.github.com/users/octocat/repos", "events_url": "https://api.github.com/users/octocat/events{/privacy}", "received_events_url": "https://api.github.com/users/octocat/received_events", "type": "User", "site_admin": false }, "private": false, "html_url": "https://github.com/octocat/Hello-World-Template", "description": "This your first repo!", "fork": false, "url": "https://api.github.com/repos/octocat/Hello-World-Template", "archive_url": "https://api.github.com/repos/octocat/Hello-World-Template/{archive_format}{/ref}", "assignees_url": "https://api.github.com/repos/octocat/Hello-World-Template/assignees{/user}", "blobs_url": "https://api.github.com/repos/octocat/Hello-World-Template/git/blobs{/sha}", "branches_url": "https://api.github.com/repos/octocat/Hello-World-Template/branches{/branch}", "collaborators_url": "https://api.github.com/repos/octocat/Hello-World-Template/collaborators{/collaborator}", "comments_url": "https://api.github.com/repos/octocat/Hello-World-Template/comments{/number}", "commits_url": "https://api.github.com/repos/octocat/Hello-World-Template/commits{/sha}", "compare_url": "https://api.github.com/repos/octocat/Hello-World-Template/compare/{base}...{head}", "contents_url": "https://api.github.com/repos/octocat/Hello-World-Template/contents/{+path}", "contributors_url": "https://api.github.com/repos/octocat/Hello-World-Template/contributors", "deployments_url": "https://api.github.com/repos/octocat/Hello-World-Template/deployments", "downloads_url": "https://api.github.com/repos/octocat/Hello-World-Template/downloads", "events_url": "https://api.github.com/repos/octocat/Hello-World-Template/events", "forks_url": "https://api.github.com/repos/octocat/Hello-World-Template/forks", "git_commits_url": "https://api.github.com/repos/octocat/Hello-World-Template/git/commits{/sha}", "git_refs_url": "https://api.github.com/repos/octocat/Hello-World-Template/git/refs{/sha}", "git_tags_url": "https://api.github.com/repos/octocat/Hello-World-Template/git/tags{/sha}", "git_url": "git:github.com/octocat/Hello-World-Template.git", "issue_comment_url": "https://api.github.com/repos/octocat/Hello-World-Template/issues/comments{/number}", "issue_events_url": "https://api.github.com/repos/octocat/Hello-World-Template/issues/events{/number}", "issues_url": "https://api.github.com/repos/octocat/Hello-World-Template/issues{/number}", "keys_url": "https://api.github.com/repos/octocat/Hello-World-Template/keys{/key_id}", "labels_url": "https://api.github.com/repos/octocat/Hello-World-Template/labels{/name}", "languages_url": "https://api.github.com/repos/octocat/Hello-World-Template/languages", "merges_url": "https://api.github.com/repos/octocat/Hello-World-Template/merges", "milestones_url": "https://api.github.com/repos/octocat/Hello-World-Template/milestones{/number}", "notifications_url": "https://api.github.com/repos/octocat/Hello-World-Template/notifications{?since,all,participating}", "pulls_url": "https://api.github.com/repos/octocat/Hello-World-Template/pulls{/number}", "releases_url": "https://api.github.com/repos/octocat/Hello-World-Template/releases{/id}", "ssh_url": "git@github.com:octocat/Hello-World-Template.git", "stargazers_url": "https://api.github.com/repos/octocat/Hello-World-Template/stargazers", "statuses_url": "https://api.github.com/repos/octocat/Hello-World-Template/statuses/{sha}", "subscribers_url": "https://api.github.com/repos/octocat/Hello-World-Template/subscribers", "subscription_url": "https://api.github.com/repos/octocat/Hello-World-Template/subscription", "tags_url": "https://api.github.com/repos/octocat/Hello-World-Template/tags", "teams_url": "https://api.github.com/repos/octocat/Hello-World-Template/teams", "trees_url": "https://api.github.com/repos/octocat/Hello-World-Template/git/trees{/sha}", "clone_url": "https://github.com/octocat/Hello-World-Template.git", "mirror_url": "git:git.example.com/octocat/Hello-World-Template", "hooks_url": "https://api.github.com/repos/octocat/Hello-World-Template/hooks", "svn_url": "https://svn.github.com/octocat/Hello-World-Template", "homepage": "https://github.com", "forks": 9, "forks_count": 9, "stargazers_count": 80, "watchers_count": 80, "watchers": 80, "size": 108, "default_branch": "master", "open_issues": 0, "open_issues_count": 0, "is_template": true, "license": { "key": "mit", "name": "MIT License", "url": "https://api.github.com/licenses/mit", "spdx_id": "MIT", "node_id": "MDc6TGljZW5zZW1pdA==", "html_url": "https://api.github.com/licenses/mit" }, "topics": [ "octocat", "atom", "electron", "api" ], "has_issues": true, "has_projects": true, "has_wiki": true, "has_pages": false, "has_downloads": true, "archived": false, "disabled": false, "visibility": "public", "pushed_at": "2011-01-26T19:06:43Z", "created_at": "2011-01-26T19:01:12Z", "updated_at": "2011-01-26T19:14:43Z", "permissions": { "admin": false, "push": false, "pull": true }, "allow_rebase_merge": true, "temp_clone_token": "ABTLWHOULUVAXGTRYU7OC2876QJ2O", "allow_squash_merge": true, "delete_branch_on_merge": true, "allow_merge_commit": true, "subscribers_count": 42, "network_count": 0 }, "temp_clone_token": "ABTLWHOULUVAXGTRYU7OC2876QJ2O", "allow_squash_merge": true, "delete_branch_on_merge": true, "allow_merge_commit": true, "subscribers_count": 42, "network_count": 0, "license": { "key": "mit", "name": "MIT License", "spdx_id": "MIT", "url": "https://api.github.com/licenses/mit", "node_id": "MDc6TGljZW5zZW1pdA==" }, "organization": { "login": "octocat", "id": 1, "node_id": "MDQ6VXNlcjE=", "avatar_url": "https://github.com/images/error/octocat_happy.gif", "gravatar_id": "", "url": "https://api.github.com/users/octocat", "html_url": "https://github.com/octocat", "followers_url": "https://api.github.com/users/octocat/followers", "following_url": "https://api.github.com/users/octocat/following{/other_user}", "gists_url": "https://api.github.com/users/octocat/gists{/gist_id}", "starred_url": "https://api.github.com/users/octocat/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/octocat/subscriptions", "organizations_url": "https://api.github.com/users/octocat/orgs", "repos_url": "https://api.github.com/users/octocat/repos", "events_url": "https://api.github.com/users/octocat/events{/privacy}", "received_events_url": "https://api.github.com/users/octocat/received_events", "type": "Organization", "site_admin": false }, "parent": { "id": 1296269, "node_id": "MDEwOlJlcG9zaXRvcnkxMjk2MjY5", "name": "Hello-World", "full_name": "octocat/Hello-World", "owner": { "login": "octocat", "id": 1, "node_id": "MDQ6VXNlcjE=", "avatar_url": "https://github.com/images/error/octocat_happy.gif", "gravatar_id": "", "url": "https://api.github.com/users/octocat", "html_url": "https://github.com/octocat", "followers_url": "https://api.github.com/users/octocat/followers", "following_url": "https://api.github.com/users/octocat/following{/other_user}", "gists_url": "https://api.github.com/users/octocat/gists{/gist_id}", "starred_url": "https://api.github.com/users/octocat/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/octocat/subscriptions", "organizations_url": "https://api.github.com/users/octocat/orgs", "repos_url": "https://api.github.com/users/octocat/repos", "events_url": "https://api.github.com/users/octocat/events{/privacy}", "received_events_url": "https://api.github.com/users/octocat/received_events", "type": "User", "site_admin": false }, "private": false, "html_url": "https://github.com/octocat/Hello-World", "description": "This your first repo!", "fork": false, "url": "https://api.github.com/repos/octocat/Hello-World", "archive_url": "https://api.github.com/repos/octocat/Hello-World/{archive_format}{/ref}", "assignees_url": "https://api.github.com/repos/octocat/Hello-World/assignees{/user}", "blobs_url": "https://api.github.com/repos/octocat/Hello-World/git/blobs{/sha}", "branches_url": "https://api.github.com/repos/octocat/Hello-World/branches{/branch}", "collaborators_url": "https://api.github.com/repos/octocat/Hello-World/collaborators{/collaborator}", "comments_url": "https://api.github.com/repos/octocat/Hello-World/comments{/number}", "commits_url": "https://api.github.com/repos/octocat/Hello-World/commits{/sha}", "compare_url": "https://api.github.com/repos/octocat/Hello-World/compare/{base}...{head}", "contents_url": "https://api.github.com/repos/octocat/Hello-World/contents/{+path}", "contributors_url": "https://api.github.com/repos/octocat/Hello-World/contributors", "deployments_url": "https://api.github.com/repos/octocat/Hello-World/deployments", "downloads_url": "https://api.github.com/repos/octocat/Hello-World/downloads", "events_url": "https://api.github.com/repos/octocat/Hello-World/events", "forks_url": "https://api.github.com/repos/octocat/Hello-World/forks", "git_commits_url": "https://api.github.com/repos/octocat/Hello-World/git/commits{/sha}", "git_refs_url": "https://api.github.com/repos/octocat/Hello-World/git/refs{/sha}", "git_tags_url": "https://api.github.com/repos/octocat/Hello-World/git/tags{/sha}", "git_url": "git:github.com/octocat/Hello-World.git", "issue_comment_url": "https://api.github.com/repos/octocat/Hello-World/issues/comments{/number}", "issue_events_url": "https://api.github.com/repos/octocat/Hello-World/issues/events{/number}", "issues_url": "https://api.github.com/repos/octocat/Hello-World/issues{/number}", "keys_url": "https://api.github.com/repos/octocat/Hello-World/keys{/key_id}", "labels_url": "https://api.github.com/repos/octocat/Hello-World/labels{/name}", "languages_url": "https://api.github.com/repos/octocat/Hello-World/languages", "merges_url": "https://api.github.com/repos/octocat/Hello-World/merges", "milestones_url": "https://api.github.com/repos/octocat/Hello-World/milestones{/number}", "notifications_url": "https://api.github.com/repos/octocat/Hello-World/notifications{?since,all,participating}", "pulls_url": "https://api.github.com/repos/octocat/Hello-World/pulls{/number}", "releases_url": "https://api.github.com/repos/octocat/Hello-World/releases{/id}", "ssh_url": "git@github.com:octocat/Hello-World.git", "stargazers_url": "https://api.github.com/repos/octocat/Hello-World/stargazers", "statuses_url": "https://api.github.com/repos/octocat/Hello-World/statuses/{sha}", "subscribers_url": "https://api.github.com/repos/octocat/Hello-World/subscribers", "subscription_url": "https://api.github.com/repos/octocat/Hello-World/subscription", "tags_url": "https://api.github.com/repos/octocat/Hello-World/tags", "teams_url": "https://api.github.com/repos/octocat/Hello-World/teams", "trees_url": "https://api.github.com/repos/octocat/Hello-World/git/trees{/sha}", "clone_url": "https://github.com/octocat/Hello-World.git", "mirror_url": "git:git.example.com/octocat/Hello-World", "hooks_url": "https://api.github.com/repos/octocat/Hello-World/hooks", "svn_url": "https://svn.github.com/octocat/Hello-World", "homepage": "https://github.com", "forks_count": 9, "stargazers_count": 80, "watchers_count": 80, "size": 108, "default_branch": "master", "open_issues_count": 0, "is_template": true, "topics": [ "octocat", "atom", "electron", "api" ], "has_issues": true, "has_projects": true, "has_wiki": true, "has_pages": false, "has_downloads": true, "archived": false, "disabled": false, "visibility": "public", "pushed_at": "2011-01-26T19:06:43Z", "created_at": "2011-01-26T19:01:12Z", "updated_at": "2011-01-26T19:14:43Z", "permissions": { "admin": false, "push": false, "pull": true }, "allow_rebase_merge": true, "temp_clone_token": "ABTLWHOULUVAXGTRYU7OC2876QJ2O", "allow_squash_merge": true, "delete_branch_on_merge": true, "allow_merge_commit": true, "subscribers_count": 42, "network_count": 0, "license": { "key": "mit", "name": "MIT License", "url": "https://api.github.com/licenses/mit", "spdx_id": "MIT", "node_id": "MDc6TGljZW5zZW1pdA==", "html_url": "https://api.github.com/licenses/mit" }, "forks": 1, "open_issues": 1, "watchers": 1 }, "source": { "id": 1296269, "node_id": "MDEwOlJlcG9zaXRvcnkxMjk2MjY5", "name": "Hello-World", "full_name": "octocat/Hello-World", "owner": { "login": "octocat", "id": 1, "node_id": "MDQ6VXNlcjE=", "avatar_url": "https://github.com/images/error/octocat_happy.gif", "gravatar_id": "", "url": "https://api.github.com/users/octocat", "html_url": "https://github.com/octocat", "followers_url": "https://api.github.com/users/octocat/followers", "following_url": "https://api.github.com/users/octocat/following{/other_user}", "gists_url": "https://api.github.com/users/octocat/gists{/gist_id}", "starred_url": "https://api.github.com/users/octocat/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/octocat/subscriptions", "organizations_url": "https://api.github.com/users/octocat/orgs", "repos_url": "https://api.github.com/users/octocat/repos", "events_url": "https://api.github.com/users/octocat/events{/privacy}", "received_events_url": "https://api.github.com/users/octocat/received_events", "type": "User", "site_admin": false }, "private": false, "html_url": "https://github.com/octocat/Hello-World", "description": "This your first repo!", "fork": false, "url": "https://api.github.com/repos/octocat/Hello-World", "archive_url": "https://api.github.com/repos/octocat/Hello-World/{archive_format}{/ref}", "assignees_url": "https://api.github.com/repos/octocat/Hello-World/assignees{/user}", "blobs_url": "https://api.github.com/repos/octocat/Hello-World/git/blobs{/sha}", "branches_url": "https://api.github.com/repos/octocat/Hello-World/branches{/branch}", "collaborators_url": "https://api.github.com/repos/octocat/Hello-World/collaborators{/collaborator}", "comments_url": "https://api.github.com/repos/octocat/Hello-World/comments{/number}", "commits_url": "https://api.github.com/repos/octocat/Hello-World/commits{/sha}", "compare_url": "https://api.github.com/repos/octocat/Hello-World/compare/{base}...{head}", "contents_url": "https://api.github.com/repos/octocat/Hello-World/contents/{+path}", "contributors_url": "https://api.github.com/repos/octocat/Hello-World/contributors", "deployments_url": "https://api.github.com/repos/octocat/Hello-World/deployments", "downloads_url": "https://api.github.com/repos/octocat/Hello-World/downloads", "events_url": "https://api.github.com/repos/octocat/Hello-World/events", "forks_url": "https://api.github.com/repos/octocat/Hello-World/forks", "git_commits_url": "https://api.github.com/repos/octocat/Hello-World/git/commits{/sha}", "git_refs_url": "https://api.github.com/repos/octocat/Hello-World/git/refs{/sha}", "git_tags_url": "https://api.github.com/repos/octocat/Hello-World/git/tags{/sha}", "git_url": "git:github.com/octocat/Hello-World.git", "issue_comment_url": "https://api.github.com/repos/octocat/Hello-World/issues/comments{/number}", "issue_events_url": "https://api.github.com/repos/octocat/Hello-World/issues/events{/number}", "issues_url": "https://api.github.com/repos/octocat/Hello-World/issues{/number}", "keys_url": "https://api.github.com/repos/octocat/Hello-World/keys{/key_id}", "labels_url": "https://api.github.com/repos/octocat/Hello-World/labels{/name}", "languages_url": "https://api.github.com/repos/octocat/Hello-World/languages", "merges_url": "https://api.github.com/repos/octocat/Hello-World/merges", "milestones_url": "https://api.github.com/repos/octocat/Hello-World/milestones{/number}", "notifications_url": "https://api.github.com/repos/octocat/Hello-World/notifications{?since,all,participating}", "pulls_url": "https://api.github.com/repos/octocat/Hello-World/pulls{/number}", "releases_url": "https://api.github.com/repos/octocat/Hello-World/releases{/id}", "ssh_url": "git@github.com:octocat/Hello-World.git", "stargazers_url": "https://api.github.com/repos/octocat/Hello-World/stargazers", "statuses_url": "https://api.github.com/repos/octocat/Hello-World/statuses/{sha}", "subscribers_url": "https://api.github.com/repos/octocat/Hello-World/subscribers", "subscription_url": "https://api.github.com/repos/octocat/Hello-World/subscription", "tags_url": "https://api.github.com/repos/octocat/Hello-World/tags", "teams_url": "https://api.github.com/repos/octocat/Hello-World/teams", "trees_url": "https://api.github.com/repos/octocat/Hello-World/git/trees{/sha}", "clone_url": "https://github.com/octocat/Hello-World.git", "mirror_url": "git:git.example.com/octocat/Hello-World", "hooks_url": "https://api.github.com/repos/octocat/Hello-World/hooks", "svn_url": "https://svn.github.com/octocat/Hello-World", "homepage": "https://github.com", "forks_count": 9, "stargazers_count": 80, "watchers_count": 80, "size": 108, "default_branch": "master", "open_issues_count": 0, "is_template": true, "topics": [ "octocat", "atom", "electron", "api" ], "has_issues": true, "has_projects": true, "has_wiki": true, "has_pages": false, "has_downloads": true, "archived": false, "disabled": false, "visibility": "public", "pushed_at": "2011-01-26T19:06:43Z", "created_at": "2011-01-26T19:01:12Z", "updated_at": "2011-01-26T19:14:43Z", "permissions": { "admin": false, "push": false, "pull": true }, "allow_rebase_merge": true, "temp_clone_token": "ABTLWHOULUVAXGTRYU7OC2876QJ2O", "allow_squash_merge": true, "delete_branch_on_merge": true, "allow_merge_commit": true, "subscribers_count": 42, "network_count": 0, "license": { "key": "mit", "name": "MIT License", "url": "https://api.github.com/licenses/mit", "spdx_id": "MIT", "node_id": "MDc6TGljZW5zZW1pdA==", "html_url": "https://api.github.com/licenses/mit" }, "forks": 1, "open_issues": 1, "watchers": 1 }, "code_of_conduct": { "key": "other", "name": "Other", "html_url": "https://github.com/github/docs/blob/main/CODE_OF_CONDUCT.md", "url": "https://api.github.com/repos/github/docs/community/code_of_conduct" } } }, "full-repository": { "value": { "id": 1296269, "node_id": "MDEwOlJlcG9zaXRvcnkxMjk2MjY5", "name": "Hello-World", "full_name": "octocat/Hello-World", "owner": { "login": "octocat", "id": 1, "node_id": "MDQ6VXNlcjE=", "avatar_url": "https://github.com/images/error/octocat_happy.gif", "gravatar_id": "", "url": "https://api.github.com/users/octocat", "html_url": "https://github.com/octocat", "followers_url": "https://api.github.com/users/octocat/followers", "following_url": "https://api.github.com/users/octocat/following{/other_user}", "gists_url": "https://api.github.com/users/octocat/gists{/gist_id}", "starred_url": "https://api.github.com/users/octocat/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/octocat/subscriptions", "organizations_url": "https://api.github.com/users/octocat/orgs", "repos_url": "https://api.github.com/users/octocat/repos", "events_url": "https://api.github.com/users/octocat/events{/privacy}", "received_events_url": "https://api.github.com/users/octocat/received_events", "type": "User", "site_admin": false }, "private": false, "html_url": "https://github.com/octocat/Hello-World", "description": "This your first repo!", "fork": false, "url": "https://api.github.com/repos/octocat/Hello-World", "archive_url": "https://api.github.com/repos/octocat/Hello-World/{archive_format}{/ref}", "assignees_url": "https://api.github.com/repos/octocat/Hello-World/assignees{/user}", "blobs_url": "https://api.github.com/repos/octocat/Hello-World/git/blobs{/sha}", "branches_url": "https://api.github.com/repos/octocat/Hello-World/branches{/branch}", "collaborators_url": "https://api.github.com/repos/octocat/Hello-World/collaborators{/collaborator}", "comments_url": "https://api.github.com/repos/octocat/Hello-World/comments{/number}", "commits_url": "https://api.github.com/repos/octocat/Hello-World/commits{/sha}", "compare_url": "https://api.github.com/repos/octocat/Hello-World/compare/{base}...{head}", "contents_url": "https://api.github.com/repos/octocat/Hello-World/contents/{+path}", "contributors_url": "https://api.github.com/repos/octocat/Hello-World/contributors", "deployments_url": "https://api.github.com/repos/octocat/Hello-World/deployments", "downloads_url": "https://api.github.com/repos/octocat/Hello-World/downloads", "events_url": "https://api.github.com/repos/octocat/Hello-World/events", "forks_url": "https://api.github.com/repos/octocat/Hello-World/forks", "git_commits_url": "https://api.github.com/repos/octocat/Hello-World/git/commits{/sha}", "git_refs_url": "https://api.github.com/repos/octocat/Hello-World/git/refs{/sha}", "git_tags_url": "https://api.github.com/repos/octocat/Hello-World/git/tags{/sha}", "git_url": "git:github.com/octocat/Hello-World.git", "issue_comment_url": "https://api.github.com/repos/octocat/Hello-World/issues/comments{/number}", "issue_events_url": "https://api.github.com/repos/octocat/Hello-World/issues/events{/number}", "issues_url": "https://api.github.com/repos/octocat/Hello-World/issues{/number}", "keys_url": "https://api.github.com/repos/octocat/Hello-World/keys{/key_id}", "labels_url": "https://api.github.com/repos/octocat/Hello-World/labels{/name}", "languages_url": "https://api.github.com/repos/octocat/Hello-World/languages", "merges_url": "https://api.github.com/repos/octocat/Hello-World/merges", "milestones_url": "https://api.github.com/repos/octocat/Hello-World/milestones{/number}", "notifications_url": "https://api.github.com/repos/octocat/Hello-World/notifications{?since,all,participating}", "pulls_url": "https://api.github.com/repos/octocat/Hello-World/pulls{/number}", "releases_url": "https://api.github.com/repos/octocat/Hello-World/releases{/id}", "ssh_url": "git@github.com:octocat/Hello-World.git", "stargazers_url": "https://api.github.com/repos/octocat/Hello-World/stargazers", "statuses_url": "https://api.github.com/repos/octocat/Hello-World/statuses/{sha}", "subscribers_url": "https://api.github.com/repos/octocat/Hello-World/subscribers", "subscription_url": "https://api.github.com/repos/octocat/Hello-World/subscription", "tags_url": "https://api.github.com/repos/octocat/Hello-World/tags", "teams_url": "https://api.github.com/repos/octocat/Hello-World/teams", "trees_url": "https://api.github.com/repos/octocat/Hello-World/git/trees{/sha}", "clone_url": "https://github.com/octocat/Hello-World.git", "mirror_url": "git:git.example.com/octocat/Hello-World", "hooks_url": "https://api.github.com/repos/octocat/Hello-World/hooks", "svn_url": "https://svn.github.com/octocat/Hello-World", "homepage": "https://github.com", "license": { "key": "mit", "name": "MIT License", "url": "https://api.github.com/licenses/mit", "spdx_id": "MIT", "node_id": "MDc6TGljZW5zZW1pdA==", "html_url": "https://github.com/licenses/mit" }, "forks_count": 9, "forks": 9, "stargazers_count": 80, "watchers_count": 80, "watchers": 80, "size": 108, "default_branch": "master", "open_issues_count": 0, "open_issues": 0, "is_template": false, "topics": [ "octocat", "atom", "electron", "api" ], "has_issues": true, "has_projects": true, "has_wiki": true, "has_pages": false, "has_downloads": true, "archived": false, "disabled": false, "visibility": "public", "pushed_at": "2011-01-26T19:06:43Z", "created_at": "2011-01-26T19:01:12Z", "updated_at": "2011-01-26T19:14:43Z", "permissions": { "pull": true, "push": false, "admin": false }, "allow_rebase_merge": true, "template_repository": { "id": 1296269, "node_id": "MDEwOlJlcG9zaXRvcnkxMjk2MjY5", "name": "Hello-World-Template", "full_name": "octocat/Hello-World-Template", "owner": { "login": "octocat", "id": 1, "node_id": "MDQ6VXNlcjE=", "avatar_url": "https://github.com/images/error/octocat_happy.gif", "gravatar_id": "", "url": "https://api.github.com/users/octocat", "html_url": "https://github.com/octocat", "followers_url": "https://api.github.com/users/octocat/followers", "following_url": "https://api.github.com/users/octocat/following{/other_user}", "gists_url": "https://api.github.com/users/octocat/gists{/gist_id}", "starred_url": "https://api.github.com/users/octocat/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/octocat/subscriptions", "organizations_url": "https://api.github.com/users/octocat/orgs", "repos_url": "https://api.github.com/users/octocat/repos", "events_url": "https://api.github.com/users/octocat/events{/privacy}", "received_events_url": "https://api.github.com/users/octocat/received_events", "type": "User", "site_admin": false }, "private": false, "html_url": "https://github.com/octocat/Hello-World-Template", "description": "This your first repo!", "fork": false, "url": "https://api.github.com/repos/octocat/Hello-World-Template", "archive_url": "https://api.github.com/repos/octocat/Hello-World-Template/{archive_format}{/ref}", "assignees_url": "https://api.github.com/repos/octocat/Hello-World-Template/assignees{/user}", "blobs_url": "https://api.github.com/repos/octocat/Hello-World-Template/git/blobs{/sha}", "branches_url": "https://api.github.com/repos/octocat/Hello-World-Template/branches{/branch}", "collaborators_url": "https://api.github.com/repos/octocat/Hello-World-Template/collaborators{/collaborator}", "comments_url": "https://api.github.com/repos/octocat/Hello-World-Template/comments{/number}", "commits_url": "https://api.github.com/repos/octocat/Hello-World-Template/commits{/sha}", "compare_url": "https://api.github.com/repos/octocat/Hello-World-Template/compare/{base}...{head}", "contents_url": "https://api.github.com/repos/octocat/Hello-World-Template/contents/{+path}", "contributors_url": "https://api.github.com/repos/octocat/Hello-World-Template/contributors", "deployments_url": "https://api.github.com/repos/octocat/Hello-World-Template/deployments", "downloads_url": "https://api.github.com/repos/octocat/Hello-World-Template/downloads", "events_url": "https://api.github.com/repos/octocat/Hello-World-Template/events", "forks_url": "https://api.github.com/repos/octocat/Hello-World-Template/forks", "git_commits_url": "https://api.github.com/repos/octocat/Hello-World-Template/git/commits{/sha}", "git_refs_url": "https://api.github.com/repos/octocat/Hello-World-Template/git/refs{/sha}", "git_tags_url": "https://api.github.com/repos/octocat/Hello-World-Template/git/tags{/sha}", "git_url": "git:github.com/octocat/Hello-World-Template.git", "issue_comment_url": "https://api.github.com/repos/octocat/Hello-World-Template/issues/comments{/number}", "issue_events_url": "https://api.github.com/repos/octocat/Hello-World-Template/issues/events{/number}", "issues_url": "https://api.github.com/repos/octocat/Hello-World-Template/issues{/number}", "keys_url": "https://api.github.com/repos/octocat/Hello-World-Template/keys{/key_id}", "labels_url": "https://api.github.com/repos/octocat/Hello-World-Template/labels{/name}", "languages_url": "https://api.github.com/repos/octocat/Hello-World-Template/languages", "merges_url": "https://api.github.com/repos/octocat/Hello-World-Template/merges", "milestones_url": "https://api.github.com/repos/octocat/Hello-World-Template/milestones{/number}", "notifications_url": "https://api.github.com/repos/octocat/Hello-World-Template/notifications{?since,all,participating}", "pulls_url": "https://api.github.com/repos/octocat/Hello-World-Template/pulls{/number}", "releases_url": "https://api.github.com/repos/octocat/Hello-World-Template/releases{/id}", "ssh_url": "git@github.com:octocat/Hello-World-Template.git", "stargazers_url": "https://api.github.com/repos/octocat/Hello-World-Template/stargazers", "statuses_url": "https://api.github.com/repos/octocat/Hello-World-Template/statuses/{sha}", "subscribers_url": "https://api.github.com/repos/octocat/Hello-World-Template/subscribers", "subscription_url": "https://api.github.com/repos/octocat/Hello-World-Template/subscription", "tags_url": "https://api.github.com/repos/octocat/Hello-World-Template/tags", "teams_url": "https://api.github.com/repos/octocat/Hello-World-Template/teams", "trees_url": "https://api.github.com/repos/octocat/Hello-World-Template/git/trees{/sha}", "clone_url": "https://github.com/octocat/Hello-World-Template.git", "mirror_url": "git:git.example.com/octocat/Hello-World-Template", "hooks_url": "https://api.github.com/repos/octocat/Hello-World-Template/hooks", "svn_url": "https://svn.github.com/octocat/Hello-World-Template", "homepage": "https://github.com", "forks": 9, "forks_count": 9, "stargazers_count": 80, "watchers_count": 80, "watchers": 80, "size": 108, "default_branch": "master", "open_issues": 0, "open_issues_count": 0, "is_template": true, "license": { "key": "mit", "name": "MIT License", "url": "https://api.github.com/licenses/mit", "spdx_id": "MIT", "node_id": "MDc6TGljZW5zZW1pdA==", "html_url": "https://api.github.com/licenses/mit" }, "topics": [ "octocat", "atom", "electron", "api" ], "has_issues": true, "has_projects": true, "has_wiki": true, "has_pages": false, "has_downloads": true, "archived": false, "disabled": false, "visibility": "public", "pushed_at": "2011-01-26T19:06:43Z", "created_at": "2011-01-26T19:01:12Z", "updated_at": "2011-01-26T19:14:43Z", "permissions": { "admin": false, "push": false, "pull": true }, "allow_rebase_merge": true, "temp_clone_token": "ABTLWHOULUVAXGTRYU7OC2876QJ2O", "allow_squash_merge": true, "delete_branch_on_merge": true, "allow_merge_commit": true, "subscribers_count": 42, "network_count": 0 }, "temp_clone_token": "ABTLWHOULUVAXGTRYU7OC2876QJ2O", "allow_squash_merge": true, "delete_branch_on_merge": true, "allow_merge_commit": true, "allow_forking": true, "subscribers_count": 42, "network_count": 0, "organization": { "login": "octocat", "id": 1, "node_id": "MDQ6VXNlcjE=", "avatar_url": "https://github.com/images/error/octocat_happy.gif", "gravatar_id": "", "url": "https://api.github.com/users/octocat", "html_url": "https://github.com/octocat", "followers_url": "https://api.github.com/users/octocat/followers", "following_url": "https://api.github.com/users/octocat/following{/other_user}", "gists_url": "https://api.github.com/users/octocat/gists{/gist_id}", "starred_url": "https://api.github.com/users/octocat/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/octocat/subscriptions", "organizations_url": "https://api.github.com/users/octocat/orgs", "repos_url": "https://api.github.com/users/octocat/repos", "events_url": "https://api.github.com/users/octocat/events{/privacy}", "received_events_url": "https://api.github.com/users/octocat/received_events", "type": "Organization", "site_admin": false }, "parent": { "id": 1296269, "node_id": "MDEwOlJlcG9zaXRvcnkxMjk2MjY5", "name": "Hello-World", "full_name": "octocat/Hello-World", "owner": { "login": "octocat", "id": 1, "node_id": "MDQ6VXNlcjE=", "avatar_url": "https://github.com/images/error/octocat_happy.gif", "gravatar_id": "", "url": "https://api.github.com/users/octocat", "html_url": "https://github.com/octocat", "followers_url": "https://api.github.com/users/octocat/followers", "following_url": "https://api.github.com/users/octocat/following{/other_user}", "gists_url": "https://api.github.com/users/octocat/gists{/gist_id}", "starred_url": "https://api.github.com/users/octocat/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/octocat/subscriptions", "organizations_url": "https://api.github.com/users/octocat/orgs", "repos_url": "https://api.github.com/users/octocat/repos", "events_url": "https://api.github.com/users/octocat/events{/privacy}", "received_events_url": "https://api.github.com/users/octocat/received_events", "type": "User", "site_admin": false }, "private": false, "html_url": "https://github.com/octocat/Hello-World", "description": "This your first repo!", "fork": false, "url": "https://api.github.com/repos/octocat/Hello-World", "archive_url": "https://api.github.com/repos/octocat/Hello-World/{archive_format}{/ref}", "assignees_url": "https://api.github.com/repos/octocat/Hello-World/assignees{/user}", "blobs_url": "https://api.github.com/repos/octocat/Hello-World/git/blobs{/sha}", "branches_url": "https://api.github.com/repos/octocat/Hello-World/branches{/branch}", "collaborators_url": "https://api.github.com/repos/octocat/Hello-World/collaborators{/collaborator}", "comments_url": "https://api.github.com/repos/octocat/Hello-World/comments{/number}", "commits_url": "https://api.github.com/repos/octocat/Hello-World/commits{/sha}", "compare_url": "https://api.github.com/repos/octocat/Hello-World/compare/{base}...{head}", "contents_url": "https://api.github.com/repos/octocat/Hello-World/contents/{+path}", "contributors_url": "https://api.github.com/repos/octocat/Hello-World/contributors", "deployments_url": "https://api.github.com/repos/octocat/Hello-World/deployments", "downloads_url": "https://api.github.com/repos/octocat/Hello-World/downloads", "events_url": "https://api.github.com/repos/octocat/Hello-World/events", "forks_url": "https://api.github.com/repos/octocat/Hello-World/forks", "git_commits_url": "https://api.github.com/repos/octocat/Hello-World/git/commits{/sha}", "git_refs_url": "https://api.github.com/repos/octocat/Hello-World/git/refs{/sha}", "git_tags_url": "https://api.github.com/repos/octocat/Hello-World/git/tags{/sha}", "git_url": "git:github.com/octocat/Hello-World.git", "issue_comment_url": "https://api.github.com/repos/octocat/Hello-World/issues/comments{/number}", "issue_events_url": "https://api.github.com/repos/octocat/Hello-World/issues/events{/number}", "issues_url": "https://api.github.com/repos/octocat/Hello-World/issues{/number}", "keys_url": "https://api.github.com/repos/octocat/Hello-World/keys{/key_id}", "labels_url": "https://api.github.com/repos/octocat/Hello-World/labels{/name}", "languages_url": "https://api.github.com/repos/octocat/Hello-World/languages", "merges_url": "https://api.github.com/repos/octocat/Hello-World/merges", "milestones_url": "https://api.github.com/repos/octocat/Hello-World/milestones{/number}", "notifications_url": "https://api.github.com/repos/octocat/Hello-World/notifications{?since,all,participating}", "pulls_url": "https://api.github.com/repos/octocat/Hello-World/pulls{/number}", "releases_url": "https://api.github.com/repos/octocat/Hello-World/releases{/id}", "ssh_url": "git@github.com:octocat/Hello-World.git", "stargazers_url": "https://api.github.com/repos/octocat/Hello-World/stargazers", "statuses_url": "https://api.github.com/repos/octocat/Hello-World/statuses/{sha}", "subscribers_url": "https://api.github.com/repos/octocat/Hello-World/subscribers", "subscription_url": "https://api.github.com/repos/octocat/Hello-World/subscription", "tags_url": "https://api.github.com/repos/octocat/Hello-World/tags", "teams_url": "https://api.github.com/repos/octocat/Hello-World/teams", "trees_url": "https://api.github.com/repos/octocat/Hello-World/git/trees{/sha}", "clone_url": "https://github.com/octocat/Hello-World.git", "mirror_url": "git:git.example.com/octocat/Hello-World", "hooks_url": "https://api.github.com/repos/octocat/Hello-World/hooks", "svn_url": "https://svn.github.com/octocat/Hello-World", "homepage": "https://github.com", "forks_count": 9, "stargazers_count": 80, "watchers_count": 80, "size": 108, "default_branch": "master", "open_issues_count": 0, "is_template": true, "topics": [ "octocat", "atom", "electron", "api" ], "has_issues": true, "has_projects": true, "has_wiki": true, "has_pages": false, "has_downloads": true, "archived": false, "disabled": false, "visibility": "public", "pushed_at": "2011-01-26T19:06:43Z", "created_at": "2011-01-26T19:01:12Z", "updated_at": "2011-01-26T19:14:43Z", "permissions": { "admin": false, "push": false, "pull": true }, "allow_rebase_merge": true, "temp_clone_token": "ABTLWHOULUVAXGTRYU7OC2876QJ2O", "allow_squash_merge": true, "delete_branch_on_merge": true, "allow_merge_commit": true, "subscribers_count": 42, "network_count": 0, "license": { "key": "mit", "name": "MIT License", "url": "https://api.github.com/licenses/mit", "spdx_id": "MIT", "node_id": "MDc6TGljZW5zZW1pdA==", "html_url": "https://api.github.com/licenses/mit" }, "forks": 1, "open_issues": 1, "watchers": 1 }, "source": { "id": 1296269, "node_id": "MDEwOlJlcG9zaXRvcnkxMjk2MjY5", "name": "Hello-World", "full_name": "octocat/Hello-World", "owner": { "login": "octocat", "id": 1, "node_id": "MDQ6VXNlcjE=", "avatar_url": "https://github.com/images/error/octocat_happy.gif", "gravatar_id": "", "url": "https://api.github.com/users/octocat", "html_url": "https://github.com/octocat", "followers_url": "https://api.github.com/users/octocat/followers", "following_url": "https://api.github.com/users/octocat/following{/other_user}", "gists_url": "https://api.github.com/users/octocat/gists{/gist_id}", "starred_url": "https://api.github.com/users/octocat/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/octocat/subscriptions", "organizations_url": "https://api.github.com/users/octocat/orgs", "repos_url": "https://api.github.com/users/octocat/repos", "events_url": "https://api.github.com/users/octocat/events{/privacy}", "received_events_url": "https://api.github.com/users/octocat/received_events", "type": "User", "site_admin": false }, "private": false, "html_url": "https://github.com/octocat/Hello-World", "description": "This your first repo!", "fork": false, "url": "https://api.github.com/repos/octocat/Hello-World", "archive_url": "https://api.github.com/repos/octocat/Hello-World/{archive_format}{/ref}", "assignees_url": "https://api.github.com/repos/octocat/Hello-World/assignees{/user}", "blobs_url": "https://api.github.com/repos/octocat/Hello-World/git/blobs{/sha}", "branches_url": "https://api.github.com/repos/octocat/Hello-World/branches{/branch}", "collaborators_url": "https://api.github.com/repos/octocat/Hello-World/collaborators{/collaborator}", "comments_url": "https://api.github.com/repos/octocat/Hello-World/comments{/number}", "commits_url": "https://api.github.com/repos/octocat/Hello-World/commits{/sha}", "compare_url": "https://api.github.com/repos/octocat/Hello-World/compare/{base}...{head}", "contents_url": "https://api.github.com/repos/octocat/Hello-World/contents/{+path}", "contributors_url": "https://api.github.com/repos/octocat/Hello-World/contributors", "deployments_url": "https://api.github.com/repos/octocat/Hello-World/deployments", "downloads_url": "https://api.github.com/repos/octocat/Hello-World/downloads", "events_url": "https://api.github.com/repos/octocat/Hello-World/events", "forks_url": "https://api.github.com/repos/octocat/Hello-World/forks", "git_commits_url": "https://api.github.com/repos/octocat/Hello-World/git/commits{/sha}", "git_refs_url": "https://api.github.com/repos/octocat/Hello-World/git/refs{/sha}", "git_tags_url": "https://api.github.com/repos/octocat/Hello-World/git/tags{/sha}", "git_url": "git:github.com/octocat/Hello-World.git", "issue_comment_url": "https://api.github.com/repos/octocat/Hello-World/issues/comments{/number}", "issue_events_url": "https://api.github.com/repos/octocat/Hello-World/issues/events{/number}", "issues_url": "https://api.github.com/repos/octocat/Hello-World/issues{/number}", "keys_url": "https://api.github.com/repos/octocat/Hello-World/keys{/key_id}", "labels_url": "https://api.github.com/repos/octocat/Hello-World/labels{/name}", "languages_url": "https://api.github.com/repos/octocat/Hello-World/languages", "merges_url": "https://api.github.com/repos/octocat/Hello-World/merges", "milestones_url": "https://api.github.com/repos/octocat/Hello-World/milestones{/number}", "notifications_url": "https://api.github.com/repos/octocat/Hello-World/notifications{?since,all,participating}", "pulls_url": "https://api.github.com/repos/octocat/Hello-World/pulls{/number}", "releases_url": "https://api.github.com/repos/octocat/Hello-World/releases{/id}", "ssh_url": "git@github.com:octocat/Hello-World.git", "stargazers_url": "https://api.github.com/repos/octocat/Hello-World/stargazers", "statuses_url": "https://api.github.com/repos/octocat/Hello-World/statuses/{sha}", "subscribers_url": "https://api.github.com/repos/octocat/Hello-World/subscribers", "subscription_url": "https://api.github.com/repos/octocat/Hello-World/subscription", "tags_url": "https://api.github.com/repos/octocat/Hello-World/tags", "teams_url": "https://api.github.com/repos/octocat/Hello-World/teams", "trees_url": "https://api.github.com/repos/octocat/Hello-World/git/trees{/sha}", "clone_url": "https://github.com/octocat/Hello-World.git", "mirror_url": "git:git.example.com/octocat/Hello-World", "hooks_url": "https://api.github.com/repos/octocat/Hello-World/hooks", "svn_url": "https://svn.github.com/octocat/Hello-World", "homepage": "https://github.com", "forks_count": 9, "stargazers_count": 80, "watchers_count": 80, "size": 108, "default_branch": "master", "open_issues_count": 0, "is_template": true, "topics": [ "octocat", "atom", "electron", "api" ], "has_issues": true, "has_projects": true, "has_wiki": true, "has_pages": false, "has_downloads": true, "archived": false, "disabled": false, "visibility": "public", "pushed_at": "2011-01-26T19:06:43Z", "created_at": "2011-01-26T19:01:12Z", "updated_at": "2011-01-26T19:14:43Z", "permissions": { "admin": false, "push": false, "pull": true }, "allow_rebase_merge": true, "temp_clone_token": "ABTLWHOULUVAXGTRYU7OC2876QJ2O", "allow_squash_merge": true, "delete_branch_on_merge": true, "allow_merge_commit": true, "subscribers_count": 42, "network_count": 0, "license": { "key": "mit", "name": "MIT License", "url": "https://api.github.com/licenses/mit", "spdx_id": "MIT", "node_id": "MDc6TGljZW5zZW1pdA==", "html_url": "https://api.github.com/licenses/mit" }, "forks": 1, "open_issues": 1, "watchers": 1 } } }, "artifact-paginated": { "value": { "total_count": 2, "artifacts": [ { "id": 11, "node_id": "MDg6QXJ0aWZhY3QxMQ==", "name": "Rails", "size_in_bytes": 556, "url": "https://api.github.com/repos/octo-org/octo-docs/actions/artifacts/11", "archive_download_url": "https://api.github.com/repos/octo-org/octo-docs/actions/artifacts/11/zip", "expired": false, "created_at": "2020-01-10T14:59:22Z", "expires_at": "2020-03-21T14:59:22Z", "updated_at": "2020-02-21T14:59:22Z" }, { "id": 13, "node_id": "MDg6QXJ0aWZhY3QxMw==", "name": "", "size_in_bytes": 453, "url": "https://api.github.com/repos/octo-org/octo-docs/actions/artifacts/13", "archive_download_url": "https://api.github.com/repos/octo-org/octo-docs/actions/artifacts/13/zip", "expired": false, "created_at": "2020-01-10T14:59:22Z", "expires_at": "2020-03-21T14:59:22Z", "updated_at": "2020-02-21T14:59:22Z" } ] } }, "artifact": { "value": { "id": 11, "node_id": "MDg6QXJ0aWZhY3QxMQ==", "name": "Rails", "size_in_bytes": 556, "url": "https://api.github.com/repos/octo-org/octo-docs/actions/artifacts/11", "archive_download_url": "https://api.github.com/repos/octo-org/octo-docs/actions/artifacts/11/zip", "expired": false, "created_at": "2020-01-10T14:59:22Z", "expires_at": "2020-01-21T14:59:22Z", "updated_at": "2020-01-21T14:59:22Z" } }, "job": { "value": { "id": 399444496, "run_id": 29679449, "run_url": "https://api.github.com/repos/octo-org/octo-repo/actions/runs/29679449", "node_id": "MDEyOldvcmtmbG93IEpvYjM5OTQ0NDQ5Ng==", "head_sha": "f83a356604ae3c5d03e1b46ef4d1ca77d64a90b0", "url": "https://api.github.com/repos/octo-org/octo-repo/actions/jobs/399444496", "html_url": "https://github.com/octo-org/octo-repo/runs/399444496", "status": "completed", "conclusion": "success", "started_at": "2020-01-20T17:42:40Z", "completed_at": "2020-01-20T17:44:39Z", "name": "build", "steps": [ { "name": "Set up job", "status": "completed", "conclusion": "success", "number": 1, "started_at": "2020-01-20T09:42:40.000-08:00", "completed_at": "2020-01-20T09:42:41.000-08:00" }, { "name": "Run actions/checkout@v2", "status": "completed", "conclusion": "success", "number": 2, "started_at": "2020-01-20T09:42:41.000-08:00", "completed_at": "2020-01-20T09:42:45.000-08:00" }, { "name": "Set up Ruby", "status": "completed", "conclusion": "success", "number": 3, "started_at": "2020-01-20T09:42:45.000-08:00", "completed_at": "2020-01-20T09:42:45.000-08:00" }, { "name": "Run actions/cache@v2", "status": "completed", "conclusion": "success", "number": 4, "started_at": "2020-01-20T09:42:45.000-08:00", "completed_at": "2020-01-20T09:42:48.000-08:00" }, { "name": "Install Bundler", "status": "completed", "conclusion": "success", "number": 5, "started_at": "2020-01-20T09:42:48.000-08:00", "completed_at": "2020-01-20T09:42:52.000-08:00" }, { "name": "Install Gems", "status": "completed", "conclusion": "success", "number": 6, "started_at": "2020-01-20T09:42:52.000-08:00", "completed_at": "2020-01-20T09:42:53.000-08:00" }, { "name": "Run Tests", "status": "completed", "conclusion": "success", "number": 7, "started_at": "2020-01-20T09:42:53.000-08:00", "completed_at": "2020-01-20T09:42:59.000-08:00" }, { "name": "Deploy to Heroku", "status": "completed", "conclusion": "success", "number": 8, "started_at": "2020-01-20T09:42:59.000-08:00", "completed_at": "2020-01-20T09:44:39.000-08:00" }, { "name": "Post actions/cache@v2", "status": "completed", "conclusion": "success", "number": 16, "started_at": "2020-01-20T09:44:39.000-08:00", "completed_at": "2020-01-20T09:44:39.000-08:00" }, { "name": "Complete job", "status": "completed", "conclusion": "success", "number": 17, "started_at": "2020-01-20T09:44:39.000-08:00", "completed_at": "2020-01-20T09:44:39.000-08:00" } ], "check_run_url": "https://api.github.com/repos/octo-org/octo-repo/check-runs/399444496" } }, "actions-repository-permissions": { "value": { "enabled": true, "allowed_actions": "selected", "selected_actions_url": "https://api.github.com/repositories/42/actions/permissions/selected-actions" } }, "workflow-run-paginated": { "value": { "total_count": 1, "workflow_runs": [ { "id": 30433642, "name": "Build", "node_id": "MDEyOldvcmtmbG93IFJ1bjI2OTI4OQ==", "head_branch": "master", "head_sha": "acb5820ced9479c074f688cc328bf03f341a511d", "run_number": 562, "event": "push", "status": "queued", "conclusion": null, "workflow_id": 159038, "url": "https://api.github.com/repos/octo-org/octo-repo/actions/runs/30433642", "html_url": "https://github.com/octo-org/octo-repo/actions/runs/30433642", "pull_requests": [ ], "created_at": "2020-01-22T19:33:08Z", "updated_at": "2020-01-22T19:33:08Z", "jobs_url": "https://api.github.com/repos/octo-org/octo-repo/actions/runs/30433642/jobs", "logs_url": "https://api.github.com/repos/octo-org/octo-repo/actions/runs/30433642/logs", "check_suite_url": "https://api.github.com/repos/octo-org/octo-repo/check-suites/414944374", "artifacts_url": "https://api.github.com/repos/octo-org/octo-repo/actions/runs/30433642/artifacts", "cancel_url": "https://api.github.com/repos/octo-org/octo-repo/actions/runs/30433642/cancel", "rerun_url": "https://api.github.com/repos/octo-org/octo-repo/actions/runs/30433642/rerun", "workflow_url": "https://api.github.com/repos/octo-org/octo-repo/actions/workflows/159038", "head_commit": { "id": "acb5820ced9479c074f688cc328bf03f341a511d", "tree_id": "d23f6eedb1e1b9610bbc754ddb5197bfe7271223", "message": "Create linter.yaml", "timestamp": "2020-01-22T19:33:05Z", "author": { "name": "Octo Cat", "email": "octocat@github.com" }, "committer": { "name": "GitHub", "email": "noreply@github.com" } }, "repository": { "id": 1296269, "node_id": "MDEwOlJlcG9zaXRvcnkxMjk2MjY5", "name": "Hello-World", "full_name": "octocat/Hello-World", "owner": { "login": "octocat", "id": 1, "node_id": "MDQ6VXNlcjE=", "avatar_url": "https://github.com/images/error/octocat_happy.gif", "gravatar_id": "", "url": "https://api.github.com/users/octocat", "html_url": "https://github.com/octocat", "followers_url": "https://api.github.com/users/octocat/followers", "following_url": "https://api.github.com/users/octocat/following{/other_user}", "gists_url": "https://api.github.com/users/octocat/gists{/gist_id}", "starred_url": "https://api.github.com/users/octocat/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/octocat/subscriptions", "organizations_url": "https://api.github.com/users/octocat/orgs", "repos_url": "https://api.github.com/users/octocat/repos", "events_url": "https://api.github.com/users/octocat/events{/privacy}", "received_events_url": "https://api.github.com/users/octocat/received_events", "type": "User", "site_admin": false }, "private": false, "html_url": "https://github.com/octocat/Hello-World", "description": "This your first repo!", "fork": false, "url": "https://api.github.com/repos/octocat/Hello-World", "archive_url": "https://api.github.com/repos/octocat/Hello-World/{archive_format}{/ref}", "assignees_url": "https://api.github.com/repos/octocat/Hello-World/assignees{/user}", "blobs_url": "https://api.github.com/repos/octocat/Hello-World/git/blobs{/sha}", "branches_url": "https://api.github.com/repos/octocat/Hello-World/branches{/branch}", "collaborators_url": "https://api.github.com/repos/octocat/Hello-World/collaborators{/collaborator}", "comments_url": "https://api.github.com/repos/octocat/Hello-World/comments{/number}", "commits_url": "https://api.github.com/repos/octocat/Hello-World/commits{/sha}", "compare_url": "https://api.github.com/repos/octocat/Hello-World/compare/{base}...{head}", "contents_url": "https://api.github.com/repos/octocat/Hello-World/contents/{+path}", "contributors_url": "https://api.github.com/repos/octocat/Hello-World/contributors", "deployments_url": "https://api.github.com/repos/octocat/Hello-World/deployments", "downloads_url": "https://api.github.com/repos/octocat/Hello-World/downloads", "events_url": "https://api.github.com/repos/octocat/Hello-World/events", "forks_url": "https://api.github.com/repos/octocat/Hello-World/forks", "git_commits_url": "https://api.github.com/repos/octocat/Hello-World/git/commits{/sha}", "git_refs_url": "https://api.github.com/repos/octocat/Hello-World/git/refs{/sha}", "git_tags_url": "https://api.github.com/repos/octocat/Hello-World/git/tags{/sha}", "git_url": "git:github.com/octocat/Hello-World.git", "issue_comment_url": "https://api.github.com/repos/octocat/Hello-World/issues/comments{/number}", "issue_events_url": "https://api.github.com/repos/octocat/Hello-World/issues/events{/number}", "issues_url": "https://api.github.com/repos/octocat/Hello-World/issues{/number}", "keys_url": "https://api.github.com/repos/octocat/Hello-World/keys{/key_id}", "labels_url": "https://api.github.com/repos/octocat/Hello-World/labels{/name}", "languages_url": "https://api.github.com/repos/octocat/Hello-World/languages", "merges_url": "https://api.github.com/repos/octocat/Hello-World/merges", "milestones_url": "https://api.github.com/repos/octocat/Hello-World/milestones{/number}", "notifications_url": "https://api.github.com/repos/octocat/Hello-World/notifications{?since,all,participating}", "pulls_url": "https://api.github.com/repos/octocat/Hello-World/pulls{/number}", "releases_url": "https://api.github.com/repos/octocat/Hello-World/releases{/id}", "ssh_url": "git@github.com:octocat/Hello-World.git", "stargazers_url": "https://api.github.com/repos/octocat/Hello-World/stargazers", "statuses_url": "https://api.github.com/repos/octocat/Hello-World/statuses/{sha}", "subscribers_url": "https://api.github.com/repos/octocat/Hello-World/subscribers", "subscription_url": "https://api.github.com/repos/octocat/Hello-World/subscription", "tags_url": "https://api.github.com/repos/octocat/Hello-World/tags", "teams_url": "https://api.github.com/repos/octocat/Hello-World/teams", "trees_url": "https://api.github.com/repos/octocat/Hello-World/git/trees{/sha}", "hooks_url": "http://api.github.com/repos/octocat/Hello-World/hooks" }, "head_repository": { "id": 217723378, "node_id": "MDEwOlJlcG9zaXRvcnkyMTc3MjMzNzg=", "name": "octo-repo", "full_name": "octo-org/octo-repo", "private": true, "owner": { "login": "octocat", "id": 1, "node_id": "MDQ6VXNlcjE=", "avatar_url": "https://github.com/images/error/octocat_happy.gif", "gravatar_id": "", "url": "https://api.github.com/users/octocat", "html_url": "https://github.com/octocat", "followers_url": "https://api.github.com/users/octocat/followers", "following_url": "https://api.github.com/users/octocat/following{/other_user}", "gists_url": "https://api.github.com/users/octocat/gists{/gist_id}", "starred_url": "https://api.github.com/users/octocat/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/octocat/subscriptions", "organizations_url": "https://api.github.com/users/octocat/orgs", "repos_url": "https://api.github.com/users/octocat/repos", "events_url": "https://api.github.com/users/octocat/events{/privacy}", "received_events_url": "https://api.github.com/users/octocat/received_events", "type": "User", "site_admin": false }, "html_url": "https://github.com/octo-org/octo-repo", "description": null, "fork": false, "url": "https://api.github.com/repos/octo-org/octo-repo", "forks_url": "https://api.github.com/repos/octo-org/octo-repo/forks", "keys_url": "https://api.github.com/repos/octo-org/octo-repo/keys{/key_id}", "collaborators_url": "https://api.github.com/repos/octo-org/octo-repo/collaborators{/collaborator}", "teams_url": "https://api.github.com/repos/octo-org/octo-repo/teams", "hooks_url": "https://api.github.com/repos/octo-org/octo-repo/hooks", "issue_events_url": "https://api.github.com/repos/octo-org/octo-repo/issues/events{/number}", "events_url": "https://api.github.com/repos/octo-org/octo-repo/events", "assignees_url": "https://api.github.com/repos/octo-org/octo-repo/assignees{/user}", "branches_url": "https://api.github.com/repos/octo-org/octo-repo/branches{/branch}", "tags_url": "https://api.github.com/repos/octo-org/octo-repo/tags", "blobs_url": "https://api.github.com/repos/octo-org/octo-repo/git/blobs{/sha}", "git_tags_url": "https://api.github.com/repos/octo-org/octo-repo/git/tags{/sha}", "git_refs_url": "https://api.github.com/repos/octo-org/octo-repo/git/refs{/sha}", "trees_url": "https://api.github.com/repos/octo-org/octo-repo/git/trees{/sha}", "statuses_url": "https://api.github.com/repos/octo-org/octo-repo/statuses/{sha}", "languages_url": "https://api.github.com/repos/octo-org/octo-repo/languages", "stargazers_url": "https://api.github.com/repos/octo-org/octo-repo/stargazers", "contributors_url": "https://api.github.com/repos/octo-org/octo-repo/contributors", "subscribers_url": "https://api.github.com/repos/octo-org/octo-repo/subscribers", "subscription_url": "https://api.github.com/repos/octo-org/octo-repo/subscription", "commits_url": "https://api.github.com/repos/octo-org/octo-repo/commits{/sha}", "git_commits_url": "https://api.github.com/repos/octo-org/octo-repo/git/commits{/sha}", "comments_url": "https://api.github.com/repos/octo-org/octo-repo/comments{/number}", "issue_comment_url": "https://api.github.com/repos/octo-org/octo-repo/issues/comments{/number}", "contents_url": "https://api.github.com/repos/octo-org/octo-repo/contents/{+path}", "compare_url": "https://api.github.com/repos/octo-org/octo-repo/compare/{base}...{head}", "merges_url": "https://api.github.com/repos/octo-org/octo-repo/merges", "archive_url": "https://api.github.com/repos/octo-org/octo-repo/{archive_format}{/ref}", "downloads_url": "https://api.github.com/repos/octo-org/octo-repo/downloads", "issues_url": "https://api.github.com/repos/octo-org/octo-repo/issues{/number}", "pulls_url": "https://api.github.com/repos/octo-org/octo-repo/pulls{/number}", "milestones_url": "https://api.github.com/repos/octo-org/octo-repo/milestones{/number}", "notifications_url": "https://api.github.com/repos/octo-org/octo-repo/notifications{?since,all,participating}", "labels_url": "https://api.github.com/repos/octo-org/octo-repo/labels{/name}", "releases_url": "https://api.github.com/repos/octo-org/octo-repo/releases{/id}", "deployments_url": "https://api.github.com/repos/octo-org/octo-repo/deployments" } } ] } }, "workflow-run": { "value": { "id": 30433642, "name": "Build", "node_id": "MDEyOldvcmtmbG93IFJ1bjI2OTI4OQ==", "check_suite_id": 42, "check_suite_node_id": "MDEwOkNoZWNrU3VpdGU0Mg==", "head_branch": "master", "head_sha": "acb5820ced9479c074f688cc328bf03f341a511d", "run_number": 562, "event": "push", "status": "queued", "workflow_id": 159038, "url": "https://api.github.com/repos/octo-org/octo-repo/actions/runs/30433642", "html_url": "https://github.com/octo-org/octo-repo/actions/runs/30433642", "pull_requests": [ ], "created_at": "2020-01-22T19:33:08Z", "updated_at": "2020-01-22T19:33:08Z", "jobs_url": "https://api.github.com/repos/octo-org/octo-repo/actions/runs/30433642/jobs", "logs_url": "https://api.github.com/repos/octo-org/octo-repo/actions/runs/30433642/logs", "check_suite_url": "https://api.github.com/repos/octo-org/octo-repo/check-suites/414944374", "artifacts_url": "https://api.github.com/repos/octo-org/octo-repo/actions/runs/30433642/artifacts", "cancel_url": "https://api.github.com/repos/octo-org/octo-repo/actions/runs/30433642/cancel", "rerun_url": "https://api.github.com/repos/octo-org/octo-repo/actions/runs/30433642/rerun", "workflow_url": "https://api.github.com/repos/octo-org/octo-repo/actions/workflows/159038", "head_commit": { "id": "acb5820ced9479c074f688cc328bf03f341a511d", "tree_id": "d23f6eedb1e1b9610bbc754ddb5197bfe7271223", "message": "Create linter.yaml", "timestamp": "2020-01-22T19:33:05Z", "author": { "name": "Octo Cat", "email": "octocat@github.com" }, "committer": { "name": "GitHub", "email": "noreply@github.com" } }, "repository": { "id": 1296269, "node_id": "MDEwOlJlcG9zaXRvcnkxMjk2MjY5", "name": "Hello-World", "full_name": "octocat/Hello-World", "owner": { "login": "octocat", "id": 1, "node_id": "MDQ6VXNlcjE=", "avatar_url": "https://github.com/images/error/octocat_happy.gif", "gravatar_id": "", "url": "https://api.github.com/users/octocat", "html_url": "https://github.com/octocat", "followers_url": "https://api.github.com/users/octocat/followers", "following_url": "https://api.github.com/users/octocat/following{/other_user}", "gists_url": "https://api.github.com/users/octocat/gists{/gist_id}", "starred_url": "https://api.github.com/users/octocat/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/octocat/subscriptions", "organizations_url": "https://api.github.com/users/octocat/orgs", "repos_url": "https://api.github.com/users/octocat/repos", "events_url": "https://api.github.com/users/octocat/events{/privacy}", "received_events_url": "https://api.github.com/users/octocat/received_events", "type": "User", "site_admin": false }, "private": false, "html_url": "https://github.com/octocat/Hello-World", "description": "This your first repo!", "fork": false, "url": "https://api.github.com/repos/octocat/Hello-World", "archive_url": "https://api.github.com/repos/octocat/Hello-World/{archive_format}{/ref}", "assignees_url": "https://api.github.com/repos/octocat/Hello-World/assignees{/user}", "blobs_url": "https://api.github.com/repos/octocat/Hello-World/git/blobs{/sha}", "branches_url": "https://api.github.com/repos/octocat/Hello-World/branches{/branch}", "collaborators_url": "https://api.github.com/repos/octocat/Hello-World/collaborators{/collaborator}", "comments_url": "https://api.github.com/repos/octocat/Hello-World/comments{/number}", "commits_url": "https://api.github.com/repos/octocat/Hello-World/commits{/sha}", "compare_url": "https://api.github.com/repos/octocat/Hello-World/compare/{base}...{head}", "contents_url": "https://api.github.com/repos/octocat/Hello-World/contents/{+path}", "contributors_url": "https://api.github.com/repos/octocat/Hello-World/contributors", "deployments_url": "https://api.github.com/repos/octocat/Hello-World/deployments", "downloads_url": "https://api.github.com/repos/octocat/Hello-World/downloads", "events_url": "https://api.github.com/repos/octocat/Hello-World/events", "forks_url": "https://api.github.com/repos/octocat/Hello-World/forks", "git_commits_url": "https://api.github.com/repos/octocat/Hello-World/git/commits{/sha}", "git_refs_url": "https://api.github.com/repos/octocat/Hello-World/git/refs{/sha}", "git_tags_url": "https://api.github.com/repos/octocat/Hello-World/git/tags{/sha}", "git_url": "git:github.com/octocat/Hello-World.git", "issue_comment_url": "https://api.github.com/repos/octocat/Hello-World/issues/comments{/number}", "issue_events_url": "https://api.github.com/repos/octocat/Hello-World/issues/events{/number}", "issues_url": "https://api.github.com/repos/octocat/Hello-World/issues{/number}", "keys_url": "https://api.github.com/repos/octocat/Hello-World/keys{/key_id}", "labels_url": "https://api.github.com/repos/octocat/Hello-World/labels{/name}", "languages_url": "https://api.github.com/repos/octocat/Hello-World/languages", "merges_url": "https://api.github.com/repos/octocat/Hello-World/merges", "milestones_url": "https://api.github.com/repos/octocat/Hello-World/milestones{/number}", "notifications_url": "https://api.github.com/repos/octocat/Hello-World/notifications{?since,all,participating}", "pulls_url": "https://api.github.com/repos/octocat/Hello-World/pulls{/number}", "releases_url": "https://api.github.com/repos/octocat/Hello-World/releases{/id}", "ssh_url": "git@github.com:octocat/Hello-World.git", "stargazers_url": "https://api.github.com/repos/octocat/Hello-World/stargazers", "statuses_url": "https://api.github.com/repos/octocat/Hello-World/statuses/{sha}", "subscribers_url": "https://api.github.com/repos/octocat/Hello-World/subscribers", "subscription_url": "https://api.github.com/repos/octocat/Hello-World/subscription", "tags_url": "https://api.github.com/repos/octocat/Hello-World/tags", "teams_url": "https://api.github.com/repos/octocat/Hello-World/teams", "trees_url": "https://api.github.com/repos/octocat/Hello-World/git/trees{/sha}", "hooks_url": "http://api.github.com/repos/octocat/Hello-World/hooks" }, "head_repository": { "id": 217723378, "node_id": "MDEwOlJlcG9zaXRvcnkyMTc3MjMzNzg=", "name": "octo-repo", "full_name": "octo-org/octo-repo", "private": true, "owner": { "login": "octocat", "id": 1, "node_id": "MDQ6VXNlcjE=", "avatar_url": "https://github.com/images/error/octocat_happy.gif", "gravatar_id": "", "url": "https://api.github.com/users/octocat", "html_url": "https://github.com/octocat", "followers_url": "https://api.github.com/users/octocat/followers", "following_url": "https://api.github.com/users/octocat/following{/other_user}", "gists_url": "https://api.github.com/users/octocat/gists{/gist_id}", "starred_url": "https://api.github.com/users/octocat/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/octocat/subscriptions", "organizations_url": "https://api.github.com/users/octocat/orgs", "repos_url": "https://api.github.com/users/octocat/repos", "events_url": "https://api.github.com/users/octocat/events{/privacy}", "received_events_url": "https://api.github.com/users/octocat/received_events", "type": "User", "site_admin": false }, "html_url": "https://github.com/octo-org/octo-repo", "description": null, "fork": false, "url": "https://api.github.com/repos/octo-org/octo-repo", "forks_url": "https://api.github.com/repos/octo-org/octo-repo/forks", "keys_url": "https://api.github.com/repos/octo-org/octo-repo/keys{/key_id}", "collaborators_url": "https://api.github.com/repos/octo-org/octo-repo/collaborators{/collaborator}", "teams_url": "https://api.github.com/repos/octo-org/octo-repo/teams", "hooks_url": "https://api.github.com/repos/octo-org/octo-repo/hooks", "issue_events_url": "https://api.github.com/repos/octo-org/octo-repo/issues/events{/number}", "events_url": "https://api.github.com/repos/octo-org/octo-repo/events", "assignees_url": "https://api.github.com/repos/octo-org/octo-repo/assignees{/user}", "branches_url": "https://api.github.com/repos/octo-org/octo-repo/branches{/branch}", "tags_url": "https://api.github.com/repos/octo-org/octo-repo/tags", "blobs_url": "https://api.github.com/repos/octo-org/octo-repo/git/blobs{/sha}", "git_tags_url": "https://api.github.com/repos/octo-org/octo-repo/git/tags{/sha}", "git_refs_url": "https://api.github.com/repos/octo-org/octo-repo/git/refs{/sha}", "trees_url": "https://api.github.com/repos/octo-org/octo-repo/git/trees{/sha}", "statuses_url": "https://api.github.com/repos/octo-org/octo-repo/statuses/{sha}", "languages_url": "https://api.github.com/repos/octo-org/octo-repo/languages", "stargazers_url": "https://api.github.com/repos/octo-org/octo-repo/stargazers", "contributors_url": "https://api.github.com/repos/octo-org/octo-repo/contributors", "subscribers_url": "https://api.github.com/repos/octo-org/octo-repo/subscribers", "subscription_url": "https://api.github.com/repos/octo-org/octo-repo/subscription", "commits_url": "https://api.github.com/repos/octo-org/octo-repo/commits{/sha}", "git_commits_url": "https://api.github.com/repos/octo-org/octo-repo/git/commits{/sha}", "comments_url": "https://api.github.com/repos/octo-org/octo-repo/comments{/number}", "issue_comment_url": "https://api.github.com/repos/octo-org/octo-repo/issues/comments{/number}", "contents_url": "https://api.github.com/repos/octo-org/octo-repo/contents/{+path}", "compare_url": "https://api.github.com/repos/octo-org/octo-repo/compare/{base}...{head}", "merges_url": "https://api.github.com/repos/octo-org/octo-repo/merges", "archive_url": "https://api.github.com/repos/octo-org/octo-repo/{archive_format}{/ref}", "downloads_url": "https://api.github.com/repos/octo-org/octo-repo/downloads", "issues_url": "https://api.github.com/repos/octo-org/octo-repo/issues{/number}", "pulls_url": "https://api.github.com/repos/octo-org/octo-repo/pulls{/number}", "milestones_url": "https://api.github.com/repos/octo-org/octo-repo/milestones{/number}", "notifications_url": "https://api.github.com/repos/octo-org/octo-repo/notifications{?since,all,participating}", "labels_url": "https://api.github.com/repos/octo-org/octo-repo/labels{/name}", "releases_url": "https://api.github.com/repos/octo-org/octo-repo/releases{/id}", "deployments_url": "https://api.github.com/repos/octo-org/octo-repo/deployments" } } }, "job-paginated": { "value": { "total_count": 1, "jobs": [ { "id": 399444496, "run_id": 29679449, "run_url": "https://api.github.com/repos/octo-org/octo-repo/actions/runs/29679449", "node_id": "MDEyOldvcmtmbG93IEpvYjM5OTQ0NDQ5Ng==", "head_sha": "f83a356604ae3c5d03e1b46ef4d1ca77d64a90b0", "url": "https://api.github.com/repos/octo-org/octo-repo/actions/jobs/399444496", "html_url": "https://github.com/octo-org/octo-repo/runs/399444496", "status": "completed", "conclusion": "success", "started_at": "2020-01-20T17:42:40Z", "completed_at": "2020-01-20T17:44:39Z", "name": "build", "steps": [ { "name": "Set up job", "status": "completed", "conclusion": "success", "number": 1, "started_at": "2020-01-20T09:42:40.000-08:00", "completed_at": "2020-01-20T09:42:41.000-08:00" }, { "name": "Run actions/checkout@v2", "status": "completed", "conclusion": "success", "number": 2, "started_at": "2020-01-20T09:42:41.000-08:00", "completed_at": "2020-01-20T09:42:45.000-08:00" }, { "name": "Set up Ruby", "status": "completed", "conclusion": "success", "number": 3, "started_at": "2020-01-20T09:42:45.000-08:00", "completed_at": "2020-01-20T09:42:45.000-08:00" }, { "name": "Run actions/cache@v2", "status": "completed", "conclusion": "success", "number": 4, "started_at": "2020-01-20T09:42:45.000-08:00", "completed_at": "2020-01-20T09:42:48.000-08:00" }, { "name": "Install Bundler", "status": "completed", "conclusion": "success", "number": 5, "started_at": "2020-01-20T09:42:48.000-08:00", "completed_at": "2020-01-20T09:42:52.000-08:00" }, { "name": "Install Gems", "status": "completed", "conclusion": "success", "number": 6, "started_at": "2020-01-20T09:42:52.000-08:00", "completed_at": "2020-01-20T09:42:53.000-08:00" }, { "name": "Run Tests", "status": "completed", "conclusion": "success", "number": 7, "started_at": "2020-01-20T09:42:53.000-08:00", "completed_at": "2020-01-20T09:42:59.000-08:00" }, { "name": "Deploy to Heroku", "status": "completed", "conclusion": "success", "number": 8, "started_at": "2020-01-20T09:42:59.000-08:00", "completed_at": "2020-01-20T09:44:39.000-08:00" }, { "name": "Post actions/cache@v2", "status": "completed", "conclusion": "success", "number": 16, "started_at": "2020-01-20T09:44:39.000-08:00", "completed_at": "2020-01-20T09:44:39.000-08:00" }, { "name": "Complete job", "status": "completed", "conclusion": "success", "number": 17, "started_at": "2020-01-20T09:44:39.000-08:00", "completed_at": "2020-01-20T09:44:39.000-08:00" } ], "check_run_url": "https://api.github.com/repos/octo-org/octo-repo/check-runs/399444496" } ] } }, "actions-secret-paginated": { "value": { "total_count": 2, "secrets": [ { "name": "GH_TOKEN", "created_at": "2019-08-10T14:59:22Z", "updated_at": "2020-01-10T14:59:22Z" }, { "name": "GIST_ID", "created_at": "2020-01-10T10:59:22Z", "updated_at": "2020-01-11T11:59:22Z" } ] } }, "actions-secret": { "value": { "name": "GH_TOKEN", "created_at": "2019-08-10T14:59:22Z", "updated_at": "2020-01-10T14:59:22Z" } }, "workflow-paginated": { "value": { "total_count": 2, "workflows": [ { "id": 161335, "node_id": "MDg6V29ya2Zsb3cxNjEzMzU=", "name": "CI", "path": ".github/workflows/blank.yaml", "state": "active", "created_at": "2020-01-08T23:48:37.000-08:00", "updated_at": "2020-01-08T23:50:21.000-08:00", "url": "https://api.github.com/repos/octo-org/octo-repo/actions/workflows/161335", "html_url": "https://github.com/octo-org/octo-repo/blob/master/.github/workflows/161335", "badge_url": "https://github.com/octo-org/octo-repo/workflows/CI/badge.svg" }, { "id": 269289, "node_id": "MDE4OldvcmtmbG93IFNlY29uZGFyeTI2OTI4OQ==", "name": "Linter", "path": ".github/workflows/linter.yaml", "state": "active", "created_at": "2020-01-08T23:48:37.000-08:00", "updated_at": "2020-01-08T23:50:21.000-08:00", "url": "https://api.github.com/repos/octo-org/octo-repo/actions/workflows/269289", "html_url": "https://github.com/octo-org/octo-repo/blob/master/.github/workflows/269289", "badge_url": "https://github.com/octo-org/octo-repo/workflows/Linter/badge.svg" } ] } }, "workflow": { "value": { "id": 161335, "node_id": "MDg6V29ya2Zsb3cxNjEzMzU=", "name": "CI", "path": ".github/workflows/blank.yaml", "state": "active", "created_at": "2020-01-08T23:48:37.000-08:00", "updated_at": "2020-01-08T23:50:21.000-08:00", "url": "https://api.github.com/repos/octo-org/octo-repo/actions/workflows/161335", "html_url": "https://github.com/octo-org/octo-repo/blob/master/.github/workflows/161335", "badge_url": "https://github.com/octo-org/octo-repo/workflows/CI/badge.svg" } }, "short-branch-with-protection-items": { "value": [ { "name": "master", "commit": { "sha": "c5b97d5ae6c19d5c5df71a34c7fbeeda2479ccbc", "url": "https://api.github.com/repos/octocat/Hello-World/commits/c5b97d5ae6c19d5c5df71a34c7fbeeda2479ccbc" }, "protected": true, "protection": { "required_status_checks": { "enforcement_level": "non_admins", "contexts": [ "ci-test", "linter" ] } }, "protection_url": "https://api.github.com/repos/octocat/hello-world/branches/master/protection" } ] }, "branch-protection": { "value": { "url": "https://api.github.com/repos/octocat/Hello-World/branches/master/protection", "required_status_checks": { "url": "https://api.github.com/repos/octocat/Hello-World/branches/master/protection/required_status_checks", "contexts": [ "continuous-integration/travis-ci" ], "contexts_url": "https://api.github.com/repos/octocat/Hello-World/branches/master/protection/required_status_checks/contexts", "enforcement_level": "non_admins" }, "enforce_admins": { "url": "https://api.github.com/repos/octocat/Hello-World/branches/master/protection/enforce_admins", "enabled": true }, "required_pull_request_reviews": { "url": "https://api.github.com/repos/octocat/Hello-World/branches/master/protection/required_pull_request_reviews", "dismissal_restrictions": { "url": "https://api.github.com/repos/octocat/Hello-World/branches/master/protection/dismissal_restrictions", "users_url": "https://api.github.com/repos/octocat/Hello-World/branches/master/protection/dismissal_restrictions/users", "teams_url": "https://api.github.com/repos/octocat/Hello-World/branches/master/protection/dismissal_restrictions/teams", "users": [ { "login": "octocat", "id": 1, "node_id": "MDQ6VXNlcjE=", "avatar_url": "https://github.com/images/error/octocat_happy.gif", "gravatar_id": "", "url": "https://api.github.com/users/octocat", "html_url": "https://github.com/octocat", "followers_url": "https://api.github.com/users/octocat/followers", "following_url": "https://api.github.com/users/octocat/following{/other_user}", "gists_url": "https://api.github.com/users/octocat/gists{/gist_id}", "starred_url": "https://api.github.com/users/octocat/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/octocat/subscriptions", "organizations_url": "https://api.github.com/users/octocat/orgs", "repos_url": "https://api.github.com/users/octocat/repos", "events_url": "https://api.github.com/users/octocat/events{/privacy}", "received_events_url": "https://api.github.com/users/octocat/received_events", "type": "User", "site_admin": false } ], "teams": [ { "id": 1, "node_id": "MDQ6VGVhbTE=", "url": "https://api.github.com/teams/1", "html_url": "https://github.com/orgs/github/teams/justice-league", "name": "Justice League", "slug": "justice-league", "description": "A great team.", "privacy": "closed", "permission": "admin", "members_url": "https://api.github.com/teams/1/members{/member}", "repositories_url": "https://api.github.com/teams/1/repos", "parent": null } ] }, "dismiss_stale_reviews": true, "require_code_owner_reviews": true, "required_approving_review_count": 2 }, "restrictions": { "url": "https://api.github.com/repos/octocat/Hello-World/branches/master/protection/restrictions", "users_url": "https://api.github.com/repos/octocat/Hello-World/branches/master/protection/restrictions/users", "teams_url": "https://api.github.com/repos/octocat/Hello-World/branches/master/protection/restrictions/teams", "apps_url": "https://api.github.com/repos/octocat/Hello-World/branches/master/protection/restrictions/teams", "users": [ { "login": "octocat", "id": 1, "node_id": "MDQ6VXNlcjE=", "avatar_url": "https://github.com/images/error/octocat_happy.gif", "gravatar_id": "", "url": "https://api.github.com/users/octocat", "html_url": "https://github.com/octocat", "followers_url": "https://api.github.com/users/octocat/followers", "following_url": "https://api.github.com/users/octocat/following{/other_user}", "gists_url": "https://api.github.com/users/octocat/gists{/gist_id}", "starred_url": "https://api.github.com/users/octocat/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/octocat/subscriptions", "organizations_url": "https://api.github.com/users/octocat/orgs", "repos_url": "https://api.github.com/users/octocat/repos", "events_url": "https://api.github.com/users/octocat/events{/privacy}", "received_events_url": "https://api.github.com/users/octocat/received_events", "type": "User", "site_admin": false } ], "teams": [ { "id": 1, "node_id": "MDQ6VGVhbTE=", "url": "https://api.github.com/teams/1", "html_url": "https://github.com/orgs/github/teams/justice-league", "name": "Justice League", "slug": "justice-league", "description": "A great team.", "privacy": "closed", "permission": "admin", "members_url": "https://api.github.com/teams/1/members{/member}", "repositories_url": "https://api.github.com/teams/1/repos", "parent": null } ], "apps": [ { "id": 1, "slug": "octoapp", "node_id": "MDExOkludGVncmF0aW9uMQ==", "owner": { "login": "github", "id": 1, "node_id": "MDEyOk9yZ2FuaXphdGlvbjE=", "url": "https://api.github.com/orgs/github", "repos_url": "https://api.github.com/orgs/github/repos", "events_url": "https://api.github.com/orgs/github/events", "hooks_url": "https://api.github.com/orgs/github/hooks", "issues_url": "https://api.github.com/orgs/github/issues", "members_url": "https://api.github.com/orgs/github/members{/member}", "public_members_url": "https://api.github.com/orgs/github/public_members{/member}", "avatar_url": "https://github.com/images/error/octocat_happy.gif", "description": "A great organization" }, "name": "Octocat App", "description": "", "external_url": "https://example.com", "html_url": "https://github.com/apps/octoapp", "created_at": "2017-07-08T16:18:44-04:00", "updated_at": "2017-07-08T16:18:44-04:00", "permissions": { "metadata": "read", "contents": "read", "issues": "write", "single_file": "write" }, "events": [ "push", "pull_request" ] } ] }, "required_linear_history": { "enabled": true }, "allow_force_pushes": { "enabled": true }, "allow_deletions": { "enabled": true }, "required_conversation_resolution": { "enabled": true } } }, "protected-branch-admin-enforced-2": { "value": { "url": "https://api.github.com/repos/octocat/Hello-World/branches/master/protection/enforce_admins", "enabled": true } }, "protected-branch-pull-request-review": { "value": { "url": "https://api.github.com/repos/octocat/Hello-World/branches/master/protection/required_pull_request_reviews", "dismissal_restrictions": { "url": "https://api.github.com/repos/octocat/Hello-World/branches/master/protection/dismissal_restrictions", "users_url": "https://api.github.com/repos/octocat/Hello-World/branches/master/protection/dismissal_restrictions/users", "teams_url": "https://api.github.com/repos/octocat/Hello-World/branches/master/protection/dismissal_restrictions/teams", "users": [ { "login": "octocat", "id": 1, "node_id": "MDQ6VXNlcjE=", "avatar_url": "https://github.com/images/error/octocat_happy.gif", "gravatar_id": "", "url": "https://api.github.com/users/octocat", "html_url": "https://github.com/octocat", "followers_url": "https://api.github.com/users/octocat/followers", "following_url": "https://api.github.com/users/octocat/following{/other_user}", "gists_url": "https://api.github.com/users/octocat/gists{/gist_id}", "starred_url": "https://api.github.com/users/octocat/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/octocat/subscriptions", "organizations_url": "https://api.github.com/users/octocat/orgs", "repos_url": "https://api.github.com/users/octocat/repos", "events_url": "https://api.github.com/users/octocat/events{/privacy}", "received_events_url": "https://api.github.com/users/octocat/received_events", "type": "User", "site_admin": false } ], "teams": [ { "id": 1, "node_id": "MDQ6VGVhbTE=", "url": "https://api.github.com/teams/1", "html_url": "https://github.com/orgs/github/teams/justice-league", "name": "Justice League", "slug": "justice-league", "description": "A great team.", "privacy": "closed", "permission": "admin", "members_url": "https://api.github.com/teams/1/members{/member}", "repositories_url": "https://api.github.com/teams/1/repos", "parent": null } ] }, "dismiss_stale_reviews": true, "require_code_owner_reviews": true, "required_approving_review_count": 2 } }, "protected-branch-admin-enforced": { "value": { "url": "https://api.github.com/repos/octocat/Hello-World/branches/master/protection/required_signatures", "enabled": true } }, "status-check-policy": { "value": { "url": "https://api.github.com/repos/octocat/Hello-World/branches/master/protection/required_status_checks", "strict": true, "contexts": [ "continuous-integration/travis-ci" ], "contexts_url": "https://api.github.com/repos/octocat/Hello-World/branches/master/protection/required_status_checks/contexts" } }, "branch-restriction-policy": { "value": { "url": "https://api.github.com/repos/octocat/Hello-World/branches/master/protection/restrictions", "users_url": "https://api.github.com/repos/octocat/Hello-World/branches/master/protection/restrictions/users", "teams_url": "https://api.github.com/repos/octocat/Hello-World/branches/master/protection/restrictions/teams", "apps_url": "https://api.github.com/repos/octocat/Hello-World/branches/master/protection/restrictions/teams", "users": [ { "login": "octocat", "id": 1, "node_id": "MDQ6VXNlcjE=", "avatar_url": "https://github.com/images/error/octocat_happy.gif", "gravatar_id": "", "url": "https://api.github.com/users/octocat", "html_url": "https://github.com/octocat", "followers_url": "https://api.github.com/users/octocat/followers", "following_url": "https://api.github.com/users/octocat/following{/other_user}", "gists_url": "https://api.github.com/users/octocat/gists{/gist_id}", "starred_url": "https://api.github.com/users/octocat/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/octocat/subscriptions", "organizations_url": "https://api.github.com/users/octocat/orgs", "repos_url": "https://api.github.com/users/octocat/repos", "events_url": "https://api.github.com/users/octocat/events{/privacy}", "received_events_url": "https://api.github.com/users/octocat/received_events", "type": "User", "site_admin": false } ], "teams": [ { "id": 1, "node_id": "MDQ6VGVhbTE=", "url": "https://api.github.com/teams/1", "html_url": "https://github.com/orgs/github/teams/justice-league", "name": "Justice League", "slug": "justice-league", "description": "A great team.", "privacy": "closed", "permission": "admin", "members_url": "https://api.github.com/teams/1/members{/member}", "repositories_url": "https://api.github.com/teams/1/repos", "parent": null } ], "apps": [ { "id": 1, "slug": "octoapp", "node_id": "MDExOkludGVncmF0aW9uMQ==", "owner": { "login": "github", "id": 1, "node_id": "MDEyOk9yZ2FuaXphdGlvbjE=", "url": "https://api.github.com/orgs/github", "repos_url": "https://api.github.com/orgs/github/repos", "events_url": "https://api.github.com/orgs/github/events", "hooks_url": "https://api.github.com/orgs/github/hooks", "issues_url": "https://api.github.com/orgs/github/issues", "members_url": "https://api.github.com/orgs/github/members{/member}", "public_members_url": "https://api.github.com/orgs/github/public_members{/member}", "avatar_url": "https://github.com/images/error/octocat_happy.gif", "description": "A great organization" }, "name": "Octocat App", "description": "", "external_url": "https://example.com", "html_url": "https://github.com/apps/octoapp", "created_at": "2017-07-08T16:18:44-04:00", "updated_at": "2017-07-08T16:18:44-04:00", "permissions": { "metadata": "read", "contents": "read", "issues": "write", "single_file": "write" }, "events": [ "push", "pull_request" ] } ] } }, "integration-items": { "value": [ { "id": 1, "slug": "octoapp", "node_id": "MDExOkludGVncmF0aW9uMQ==", "owner": { "login": "github", "id": 1, "node_id": "MDEyOk9yZ2FuaXphdGlvbjE=", "url": "https://api.github.com/orgs/github", "repos_url": "https://api.github.com/orgs/github/repos", "events_url": "https://api.github.com/orgs/github/events", "avatar_url": "https://github.com/images/error/octocat_happy.gif", "gravatar_id": "", "html_url": "https://github.com/octocat", "followers_url": "https://api.github.com/users/octocat/followers", "following_url": "https://api.github.com/users/octocat/following{/other_user}", "gists_url": "https://api.github.com/users/octocat/gists{/gist_id}", "starred_url": "https://api.github.com/users/octocat/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/octocat/subscriptions", "organizations_url": "https://api.github.com/users/octocat/orgs", "received_events_url": "https://api.github.com/users/octocat/received_events", "type": "User", "site_admin": true }, "name": "Octocat App", "description": "", "external_url": "https://example.com", "html_url": "https://github.com/apps/octoapp", "created_at": "2017-07-08T16:18:44-04:00", "updated_at": "2017-07-08T16:18:44-04:00", "permissions": { "metadata": "read", "contents": "read", "issues": "write", "single_file": "write" }, "events": [ "push", "pull_request" ] } ] }, "check-run-example-of-completed-conclusion": { "summary": "Response for completed conclusion", "value": { "id": 4, "head_sha": "ce587453ced02b1526dfb4cb910479d431683101", "node_id": "MDg6Q2hlY2tSdW40", "external_id": "", "url": "https://api.github.com/repos/github/hello-world/check-runs/4", "html_url": "https://github.com/github/hello-world/runs/4", "details_url": "https://example.com", "status": "completed", "conclusion": "neutral", "started_at": "2018-05-04T01:14:52Z", "completed_at": "2018-05-04T01:14:52Z", "output": { "title": "Mighty Readme report", "summary": "There are 0 failures, 2 warnings, and 1 notice.", "text": "You may have some misspelled words on lines 2 and 4. You also may want to add a section in your README about how to install your app.", "annotations_count": 2, "annotations_url": "https://api.github.com/repos/github/hello-world/check-runs/4/annotations" }, "name": "mighty_readme", "check_suite": { "id": 5 }, "app": { "id": 1, "slug": "octoapp", "node_id": "MDExOkludGVncmF0aW9uMQ==", "owner": { "login": "github", "id": 1, "node_id": "MDEyOk9yZ2FuaXphdGlvbjE=", "url": "https://api.github.com/orgs/github", "repos_url": "https://api.github.com/orgs/github/repos", "events_url": "https://api.github.com/orgs/github/events", "avatar_url": "https://github.com/images/error/octocat_happy.gif", "gravatar_id": "", "html_url": "https://github.com/octocat", "followers_url": "https://api.github.com/users/octocat/followers", "following_url": "https://api.github.com/users/octocat/following{/other_user}", "gists_url": "https://api.github.com/users/octocat/gists{/gist_id}", "starred_url": "https://api.github.com/users/octocat/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/octocat/subscriptions", "organizations_url": "https://api.github.com/users/octocat/orgs", "received_events_url": "https://api.github.com/users/octocat/received_events", "type": "User", "site_admin": true }, "name": "Octocat App", "description": "", "external_url": "https://example.com", "html_url": "https://github.com/apps/octoapp", "created_at": "2017-07-08T16:18:44-04:00", "updated_at": "2017-07-08T16:18:44-04:00", "permissions": { "metadata": "read", "contents": "read", "issues": "write", "single_file": "write" }, "events": [ "push", "pull_request" ] }, "pull_requests": [ { "url": "https://api.github.com/repos/github/hello-world/pulls/1", "id": 1934, "number": 3956, "head": { "ref": "say-hello", "sha": "3dca65fa3e8d4b3da3f3d056c59aee1c50f41390", "repo": { "id": 526, "url": "https://api.github.com/repos/github/hello-world", "name": "hello-world" } }, "base": { "ref": "master", "sha": "e7fdf7640066d71ad16a86fbcbb9c6a10a18af4f", "repo": { "id": 526, "url": "https://api.github.com/repos/github/hello-world", "name": "hello-world" } } } ] } }, "check-run": { "value": { "id": 4, "head_sha": "ce587453ced02b1526dfb4cb910479d431683101", "node_id": "MDg6Q2hlY2tSdW40", "external_id": "", "url": "https://api.github.com/repos/github/hello-world/check-runs/4", "html_url": "https://github.com/github/hello-world/runs/4", "details_url": "https://example.com", "status": "completed", "conclusion": "neutral", "started_at": "2018-05-04T01:14:52Z", "completed_at": "2018-05-04T01:14:52Z", "output": { "title": "Mighty Readme report", "summary": "There are 0 failures, 2 warnings, and 1 notice.", "text": "You may have some misspelled words on lines 2 and 4. You also may want to add a section in your README about how to install your app.", "annotations_count": 2, "annotations_url": "https://api.github.com/repos/github/hello-world/check-runs/4/annotations" }, "name": "mighty_readme", "check_suite": { "id": 5 }, "app": { "id": 1, "slug": "octoapp", "node_id": "MDExOkludGVncmF0aW9uMQ==", "owner": { "login": "github", "id": 1, "node_id": "MDEyOk9yZ2FuaXphdGlvbjE=", "url": "https://api.github.com/orgs/github", "repos_url": "https://api.github.com/orgs/github/repos", "events_url": "https://api.github.com/orgs/github/events", "avatar_url": "https://github.com/images/error/octocat_happy.gif", "gravatar_id": "", "html_url": "https://github.com/octocat", "followers_url": "https://api.github.com/users/octocat/followers", "following_url": "https://api.github.com/users/octocat/following{/other_user}", "gists_url": "https://api.github.com/users/octocat/gists{/gist_id}", "starred_url": "https://api.github.com/users/octocat/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/octocat/subscriptions", "organizations_url": "https://api.github.com/users/octocat/orgs", "received_events_url": "https://api.github.com/users/octocat/received_events", "type": "User", "site_admin": true }, "name": "Octocat App", "description": "", "external_url": "https://example.com", "html_url": "https://github.com/apps/octoapp", "created_at": "2017-07-08T16:18:44-04:00", "updated_at": "2017-07-08T16:18:44-04:00", "permissions": { "metadata": "read", "contents": "read", "issues": "write", "single_file": "write" }, "events": [ "push", "pull_request" ] }, "pull_requests": [ { "url": "https://api.github.com/repos/github/hello-world/pulls/1", "id": 1934, "number": 3956, "head": { "ref": "say-hello", "sha": "3dca65fa3e8d4b3da3f3d056c59aee1c50f41390", "repo": { "id": 526, "url": "https://api.github.com/repos/github/hello-world", "name": "hello-world" } }, "base": { "ref": "master", "sha": "e7fdf7640066d71ad16a86fbcbb9c6a10a18af4f", "repo": { "id": 526, "url": "https://api.github.com/repos/github/hello-world", "name": "hello-world" } } } ] } }, "check-annotation-items": { "value": [ { "path": "README.md", "start_line": 2, "end_line": 2, "start_column": 5, "end_column": 10, "annotation_level": "warning", "title": "Spell Checker", "message": "Check your spelling for 'banaas'.", "raw_details": "Do you mean 'bananas' or 'banana'?", "blob_href": "https://api.github.com/repos/github/rest-api-description/git/blobs/abc" } ] }, "check-suite": { "value": { "id": 5, "node_id": "MDEwOkNoZWNrU3VpdGU1", "head_branch": "master", "head_sha": "d6fde92930d4715a2b49857d24b940956b26d2d3", "status": "completed", "conclusion": "neutral", "url": "https://api.github.com/repos/github/hello-world/check-suites/5", "before": "146e867f55c26428e5f9fade55a9bbf5e95a7912", "after": "d6fde92930d4715a2b49857d24b940956b26d2d3", "pull_requests": [ ], "created_at": "2017-07-08T16:18:44-04:00", "updated_at": "2017-07-08T16:18:44-04:00", "app": { "id": 1, "slug": "octoapp", "node_id": "MDExOkludGVncmF0aW9uMQ==", "owner": { "login": "github", "id": 1, "node_id": "MDEyOk9yZ2FuaXphdGlvbjE=", "url": "https://api.github.com/orgs/github", "repos_url": "https://api.github.com/orgs/github/repos", "events_url": "https://api.github.com/orgs/github/events", "avatar_url": "https://github.com/images/error/octocat_happy.gif", "gravatar_id": "", "html_url": "https://github.com/octocat", "followers_url": "https://api.github.com/users/octocat/followers", "following_url": "https://api.github.com/users/octocat/following{/other_user}", "gists_url": "https://api.github.com/users/octocat/gists{/gist_id}", "starred_url": "https://api.github.com/users/octocat/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/octocat/subscriptions", "organizations_url": "https://api.github.com/users/octocat/orgs", "received_events_url": "https://api.github.com/users/octocat/received_events", "type": "User", "site_admin": true }, "name": "Octocat App", "description": "", "external_url": "https://example.com", "html_url": "https://github.com/apps/octoapp", "created_at": "2017-07-08T16:18:44-04:00", "updated_at": "2017-07-08T16:18:44-04:00", "permissions": { "metadata": "read", "contents": "read", "issues": "write", "single_file": "write" }, "events": [ "push", "pull_request" ] }, "repository": { "id": 1296269, "node_id": "MDEwOlJlcG9zaXRvcnkxMjk2MjY5", "name": "Hello-World", "full_name": "octocat/Hello-World", "template_repository": { "id": 1296269, "node_id": "MDEwOlJlcG9zaXRvcnkxMjk2MjY5", "name": "Hello-World-Template", "full_name": "octocat/Hello-World-Template", "owner": { "login": "octocat", "id": 1, "node_id": "MDQ6VXNlcjE=", "avatar_url": "https://github.com/images/error/octocat_happy.gif", "gravatar_id": "", "url": "https://api.github.com/users/octocat", "html_url": "https://github.com/octocat", "followers_url": "https://api.github.com/users/octocat/followers", "following_url": "https://api.github.com/users/octocat/following{/other_user}", "gists_url": "https://api.github.com/users/octocat/gists{/gist_id}", "starred_url": "https://api.github.com/users/octocat/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/octocat/subscriptions", "organizations_url": "https://api.github.com/users/octocat/orgs", "repos_url": "https://api.github.com/users/octocat/repos", "events_url": "https://api.github.com/users/octocat/events{/privacy}", "received_events_url": "https://api.github.com/users/octocat/received_events", "type": "User", "site_admin": false }, "private": false, "html_url": "https://github.com/octocat/Hello-World-Template", "description": "This your first repo!", "fork": false, "url": "https://api.github.com/repos/octocat/Hello-World-Template", "archive_url": "https://api.github.com/repos/octocat/Hello-World-Template/{archive_format}{/ref}", "assignees_url": "https://api.github.com/repos/octocat/Hello-World-Template/assignees{/user}", "blobs_url": "https://api.github.com/repos/octocat/Hello-World-Template/git/blobs{/sha}", "branches_url": "https://api.github.com/repos/octocat/Hello-World-Template/branches{/branch}", "collaborators_url": "https://api.github.com/repos/octocat/Hello-World-Template/collaborators{/collaborator}", "comments_url": "https://api.github.com/repos/octocat/Hello-World-Template/comments{/number}", "commits_url": "https://api.github.com/repos/octocat/Hello-World-Template/commits{/sha}", "compare_url": "https://api.github.com/repos/octocat/Hello-World-Template/compare/{base}...{head}", "contents_url": "https://api.github.com/repos/octocat/Hello-World-Template/contents/{+path}", "contributors_url": "https://api.github.com/repos/octocat/Hello-World-Template/contributors", "deployments_url": "https://api.github.com/repos/octocat/Hello-World-Template/deployments", "downloads_url": "https://api.github.com/repos/octocat/Hello-World-Template/downloads", "events_url": "https://api.github.com/repos/octocat/Hello-World-Template/events", "forks_url": "https://api.github.com/repos/octocat/Hello-World-Template/forks", "git_commits_url": "https://api.github.com/repos/octocat/Hello-World-Template/git/commits{/sha}", "git_refs_url": "https://api.github.com/repos/octocat/Hello-World-Template/git/refs{/sha}", "git_tags_url": "https://api.github.com/repos/octocat/Hello-World-Template/git/tags{/sha}", "git_url": "git:github.com/octocat/Hello-World-Template.git", "issue_comment_url": "https://api.github.com/repos/octocat/Hello-World-Template/issues/comments{/number}", "issue_events_url": "https://api.github.com/repos/octocat/Hello-World-Template/issues/events{/number}", "issues_url": "https://api.github.com/repos/octocat/Hello-World-Template/issues{/number}", "keys_url": "https://api.github.com/repos/octocat/Hello-World-Template/keys{/key_id}", "labels_url": "https://api.github.com/repos/octocat/Hello-World-Template/labels{/name}", "languages_url": "https://api.github.com/repos/octocat/Hello-World-Template/languages", "merges_url": "https://api.github.com/repos/octocat/Hello-World-Template/merges", "milestones_url": "https://api.github.com/repos/octocat/Hello-World-Template/milestones{/number}", "notifications_url": "https://api.github.com/repos/octocat/Hello-World-Template/notifications{?since,all,participating}", "pulls_url": "https://api.github.com/repos/octocat/Hello-World-Template/pulls{/number}", "releases_url": "https://api.github.com/repos/octocat/Hello-World-Template/releases{/id}", "ssh_url": "git@github.com:octocat/Hello-World-Template.git", "stargazers_url": "https://api.github.com/repos/octocat/Hello-World-Template/stargazers", "statuses_url": "https://api.github.com/repos/octocat/Hello-World-Template/statuses/{sha}", "subscribers_url": "https://api.github.com/repos/octocat/Hello-World-Template/subscribers", "subscription_url": "https://api.github.com/repos/octocat/Hello-World-Template/subscription", "tags_url": "https://api.github.com/repos/octocat/Hello-World-Template/tags", "teams_url": "https://api.github.com/repos/octocat/Hello-World-Template/teams", "trees_url": "https://api.github.com/repos/octocat/Hello-World-Template/git/trees{/sha}", "clone_url": "https://github.com/octocat/Hello-World-Template.git", "mirror_url": "git:git.example.com/octocat/Hello-World-Template", "hooks_url": "https://api.github.com/repos/octocat/Hello-World-Template/hooks", "svn_url": "https://svn.github.com/octocat/Hello-World-Template", "homepage": "https://github.com", "forks": 9, "forks_count": 9, "stargazers_count": 80, "watchers_count": 80, "watchers": 80, "size": 108, "default_branch": "master", "open_issues": 0, "open_issues_count": 0, "is_template": true, "license": { "key": "mit", "name": "MIT License", "url": "https://api.github.com/licenses/mit", "spdx_id": "MIT", "node_id": "MDc6TGljZW5zZW1pdA==", "html_url": "https://api.github.com/licenses/mit" }, "topics": [ "octocat", "atom", "electron", "api" ], "has_issues": true, "has_projects": true, "has_wiki": true, "has_pages": false, "has_downloads": true, "archived": false, "disabled": false, "visibility": "public", "pushed_at": "2011-01-26T19:06:43Z", "created_at": "2011-01-26T19:01:12Z", "updated_at": "2011-01-26T19:14:43Z", "permissions": { "admin": false, "push": false, "pull": true }, "allow_rebase_merge": true, "temp_clone_token": "ABTLWHOULUVAXGTRYU7OC2876QJ2O", "allow_squash_merge": true, "delete_branch_on_merge": true, "allow_merge_commit": true, "subscribers_count": 42, "network_count": 0 }, "owner": { "login": "octocat", "id": 1, "node_id": "MDQ6VXNlcjE=", "avatar_url": "https://github.com/images/error/octocat_happy.gif", "gravatar_id": "", "url": "https://api.github.com/users/octocat", "html_url": "https://github.com/octocat", "followers_url": "https://api.github.com/users/octocat/followers", "following_url": "https://api.github.com/users/octocat/following{/other_user}", "gists_url": "https://api.github.com/users/octocat/gists{/gist_id}", "starred_url": "https://api.github.com/users/octocat/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/octocat/subscriptions", "organizations_url": "https://api.github.com/users/octocat/orgs", "repos_url": "https://api.github.com/users/octocat/repos", "events_url": "https://api.github.com/users/octocat/events{/privacy}", "received_events_url": "https://api.github.com/users/octocat/received_events", "type": "User", "site_admin": false }, "private": false, "html_url": "https://github.com/octocat/Hello-World", "description": "This your first repo!", "fork": false, "url": "https://api.github.com/repos/octocat/Hello-World", "archive_url": "https://api.github.com/repos/octocat/Hello-World/{archive_format}{/ref}", "assignees_url": "https://api.github.com/repos/octocat/Hello-World/assignees{/user}", "blobs_url": "https://api.github.com/repos/octocat/Hello-World/git/blobs{/sha}", "branches_url": "https://api.github.com/repos/octocat/Hello-World/branches{/branch}", "collaborators_url": "https://api.github.com/repos/octocat/Hello-World/collaborators{/collaborator}", "comments_url": "https://api.github.com/repos/octocat/Hello-World/comments{/number}", "commits_url": "https://api.github.com/repos/octocat/Hello-World/commits{/sha}", "compare_url": "https://api.github.com/repos/octocat/Hello-World/compare/{base}...{head}", "contents_url": "https://api.github.com/repos/octocat/Hello-World/contents/{+path}", "contributors_url": "https://api.github.com/repos/octocat/Hello-World/contributors", "deployments_url": "https://api.github.com/repos/octocat/Hello-World/deployments", "downloads_url": "https://api.github.com/repos/octocat/Hello-World/downloads", "events_url": "https://api.github.com/repos/octocat/Hello-World/events", "forks_url": "https://api.github.com/repos/octocat/Hello-World/forks", "git_commits_url": "https://api.github.com/repos/octocat/Hello-World/git/commits{/sha}", "git_refs_url": "https://api.github.com/repos/octocat/Hello-World/git/refs{/sha}", "git_tags_url": "https://api.github.com/repos/octocat/Hello-World/git/tags{/sha}", "git_url": "git:github.com/octocat/Hello-World.git", "issue_comment_url": "https://api.github.com/repos/octocat/Hello-World/issues/comments{/number}", "issue_events_url": "https://api.github.com/repos/octocat/Hello-World/issues/events{/number}", "issues_url": "https://api.github.com/repos/octocat/Hello-World/issues{/number}", "keys_url": "https://api.github.com/repos/octocat/Hello-World/keys{/key_id}", "labels_url": "https://api.github.com/repos/octocat/Hello-World/labels{/name}", "languages_url": "https://api.github.com/repos/octocat/Hello-World/languages", "merges_url": "https://api.github.com/repos/octocat/Hello-World/merges", "milestones_url": "https://api.github.com/repos/octocat/Hello-World/milestones{/number}", "notifications_url": "https://api.github.com/repos/octocat/Hello-World/notifications{?since,all,participating}", "pulls_url": "https://api.github.com/repos/octocat/Hello-World/pulls{/number}", "releases_url": "https://api.github.com/repos/octocat/Hello-World/releases{/id}", "ssh_url": "git@github.com:octocat/Hello-World.git", "stargazers_url": "https://api.github.com/repos/octocat/Hello-World/stargazers", "statuses_url": "https://api.github.com/repos/octocat/Hello-World/statuses/{sha}", "subscribers_url": "https://api.github.com/repos/octocat/Hello-World/subscribers", "subscription_url": "https://api.github.com/repos/octocat/Hello-World/subscription", "tags_url": "https://api.github.com/repos/octocat/Hello-World/tags", "teams_url": "https://api.github.com/repos/octocat/Hello-World/teams", "trees_url": "https://api.github.com/repos/octocat/Hello-World/git/trees{/sha}", "clone_url": "https://github.com/octocat/Hello-World.git", "mirror_url": "git:git.example.com/octocat/Hello-World", "hooks_url": "https://api.github.com/repos/octocat/Hello-World/hooks", "svn_url": "https://svn.github.com/octocat/Hello-World", "homepage": "https://github.com", "forks_count": 9, "stargazers_count": 80, "watchers_count": 80, "size": 108, "default_branch": "master", "open_issues_count": 0, "is_template": false, "topics": [ "octocat", "atom", "electron", "api" ], "has_issues": true, "has_projects": true, "has_wiki": true, "has_pages": false, "has_downloads": true, "archived": false, "disabled": false, "visibility": "public", "pushed_at": "2011-01-26T19:06:43Z", "created_at": "2011-01-26T19:01:12Z", "updated_at": "2011-01-26T19:14:43Z", "permissions": { "admin": false, "push": false, "pull": true }, "temp_clone_token": "ABTLWHOULUVAXGTRYU7OC2876QJ2O", "delete_branch_on_merge": true, "subscribers_count": 42, "network_count": 0 }, "head_commit": { "id": "7fd1a60b01f91b314f59955a4e4d4e80d8edf11d", "tree_id": "7fd1a60b01f91b314f59955a4e4d4e80d8edf11d", "message": "Merge pull request #6 from Spaceghost/patch-1\n\nNew line at end of file.", "timestamp": "2016-10-10T00:00:00Z", "author": { "name": "The Octocat", "email": "octocat@nowhere.com" }, "committer": { "name": "The Octocat", "email": "octocat@nowhere.com" } }, "latest_check_runs_count": 1, "check_runs_url": "https://api.github.com/repos/octocat/Hello-World/check-suites/5/check-runs" } }, "check-suite-preference": { "value": { "preferences": { "auto_trigger_checks": [ { "app_id": 2, "setting": true }, { "app_id": 4, "setting": false } ] }, "repository": { "id": 1296269, "node_id": "MDEwOlJlcG9zaXRvcnkxMjk2MjY5", "name": "Hello-World", "full_name": "octocat/Hello-World", "owner": { "login": "octocat", "id": 1, "node_id": "MDQ6VXNlcjE=", "avatar_url": "https://github.com/images/error/octocat_happy.gif", "gravatar_id": "", "url": "https://api.github.com/users/octocat", "html_url": "https://github.com/octocat", "followers_url": "https://api.github.com/users/octocat/followers", "following_url": "https://api.github.com/users/octocat/following{/other_user}", "gists_url": "https://api.github.com/users/octocat/gists{/gist_id}", "starred_url": "https://api.github.com/users/octocat/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/octocat/subscriptions", "organizations_url": "https://api.github.com/users/octocat/orgs", "repos_url": "https://api.github.com/users/octocat/repos", "events_url": "https://api.github.com/users/octocat/events{/privacy}", "received_events_url": "https://api.github.com/users/octocat/received_events", "type": "User", "site_admin": false }, "private": false, "html_url": "https://github.com/octocat/Hello-World", "description": "This your first repo!", "fork": false, "url": "https://api.github.com/repos/octocat/Hello-World", "archive_url": "https://api.github.com/repos/octocat/Hello-World/{archive_format}{/ref}", "assignees_url": "https://api.github.com/repos/octocat/Hello-World/assignees{/user}", "blobs_url": "https://api.github.com/repos/octocat/Hello-World/git/blobs{/sha}", "branches_url": "https://api.github.com/repos/octocat/Hello-World/branches{/branch}", "collaborators_url": "https://api.github.com/repos/octocat/Hello-World/collaborators{/collaborator}", "comments_url": "https://api.github.com/repos/octocat/Hello-World/comments{/number}", "commits_url": "https://api.github.com/repos/octocat/Hello-World/commits{/sha}", "compare_url": "https://api.github.com/repos/octocat/Hello-World/compare/{base}...{head}", "contents_url": "https://api.github.com/repos/octocat/Hello-World/contents/{+path}", "contributors_url": "https://api.github.com/repos/octocat/Hello-World/contributors", "deployments_url": "https://api.github.com/repos/octocat/Hello-World/deployments", "downloads_url": "https://api.github.com/repos/octocat/Hello-World/downloads", "events_url": "https://api.github.com/repos/octocat/Hello-World/events", "forks_url": "https://api.github.com/repos/octocat/Hello-World/forks", "git_commits_url": "https://api.github.com/repos/octocat/Hello-World/git/commits{/sha}", "git_refs_url": "https://api.github.com/repos/octocat/Hello-World/git/refs{/sha}", "git_tags_url": "https://api.github.com/repos/octocat/Hello-World/git/tags{/sha}", "git_url": "git:github.com/octocat/Hello-World.git", "issue_comment_url": "https://api.github.com/repos/octocat/Hello-World/issues/comments{/number}", "issue_events_url": "https://api.github.com/repos/octocat/Hello-World/issues/events{/number}", "issues_url": "https://api.github.com/repos/octocat/Hello-World/issues{/number}", "keys_url": "https://api.github.com/repos/octocat/Hello-World/keys{/key_id}", "labels_url": "https://api.github.com/repos/octocat/Hello-World/labels{/name}", "languages_url": "https://api.github.com/repos/octocat/Hello-World/languages", "merges_url": "https://api.github.com/repos/octocat/Hello-World/merges", "milestones_url": "https://api.github.com/repos/octocat/Hello-World/milestones{/number}", "notifications_url": "https://api.github.com/repos/octocat/Hello-World/notifications{?since,all,participating}", "pulls_url": "https://api.github.com/repos/octocat/Hello-World/pulls{/number}", "releases_url": "https://api.github.com/repos/octocat/Hello-World/releases{/id}", "ssh_url": "git@github.com:octocat/Hello-World.git", "stargazers_url": "https://api.github.com/repos/octocat/Hello-World/stargazers", "statuses_url": "https://api.github.com/repos/octocat/Hello-World/statuses/{sha}", "subscribers_url": "https://api.github.com/repos/octocat/Hello-World/subscribers", "subscription_url": "https://api.github.com/repos/octocat/Hello-World/subscription", "tags_url": "https://api.github.com/repos/octocat/Hello-World/tags", "teams_url": "https://api.github.com/repos/octocat/Hello-World/teams", "trees_url": "https://api.github.com/repos/octocat/Hello-World/git/trees{/sha}", "clone_url": "https://github.com/octocat/Hello-World.git", "mirror_url": "git:git.example.com/octocat/Hello-World", "hooks_url": "https://api.github.com/repos/octocat/Hello-World/hooks", "svn_url": "https://svn.github.com/octocat/Hello-World", "homepage": "https://github.com", "forks_count": 9, "stargazers_count": 80, "watchers_count": 80, "size": 108, "default_branch": "master", "open_issues_count": 0, "is_template": false, "topics": [ "octocat", "atom", "electron", "api" ], "has_issues": true, "has_projects": true, "has_wiki": true, "has_pages": false, "has_downloads": true, "archived": false, "disabled": false, "visibility": "public", "pushed_at": "2011-01-26T19:06:43Z", "created_at": "2011-01-26T19:01:12Z", "updated_at": "2011-01-26T19:14:43Z", "permissions": { "admin": false, "push": false, "pull": true }, "template_repository": { "id": 1296269, "node_id": "MDEwOlJlcG9zaXRvcnkxMjk2MjY5", "name": "Hello-World-Template", "full_name": "octocat/Hello-World-Template", "owner": { "login": "octocat", "id": 1, "node_id": "MDQ6VXNlcjE=", "avatar_url": "https://github.com/images/error/octocat_happy.gif", "gravatar_id": "", "url": "https://api.github.com/users/octocat", "html_url": "https://github.com/octocat", "followers_url": "https://api.github.com/users/octocat/followers", "following_url": "https://api.github.com/users/octocat/following{/other_user}", "gists_url": "https://api.github.com/users/octocat/gists{/gist_id}", "starred_url": "https://api.github.com/users/octocat/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/octocat/subscriptions", "organizations_url": "https://api.github.com/users/octocat/orgs", "repos_url": "https://api.github.com/users/octocat/repos", "events_url": "https://api.github.com/users/octocat/events{/privacy}", "received_events_url": "https://api.github.com/users/octocat/received_events", "type": "User", "site_admin": false }, "private": false, "html_url": "https://github.com/octocat/Hello-World-Template", "description": "This your first repo!", "fork": false, "url": "https://api.github.com/repos/octocat/Hello-World-Template", "archive_url": "https://api.github.com/repos/octocat/Hello-World-Template/{archive_format}{/ref}", "assignees_url": "https://api.github.com/repos/octocat/Hello-World-Template/assignees{/user}", "blobs_url": "https://api.github.com/repos/octocat/Hello-World-Template/git/blobs{/sha}", "branches_url": "https://api.github.com/repos/octocat/Hello-World-Template/branches{/branch}", "collaborators_url": "https://api.github.com/repos/octocat/Hello-World-Template/collaborators{/collaborator}", "comments_url": "https://api.github.com/repos/octocat/Hello-World-Template/comments{/number}", "commits_url": "https://api.github.com/repos/octocat/Hello-World-Template/commits{/sha}", "compare_url": "https://api.github.com/repos/octocat/Hello-World-Template/compare/{base}...{head}", "contents_url": "https://api.github.com/repos/octocat/Hello-World-Template/contents/{+path}", "contributors_url": "https://api.github.com/repos/octocat/Hello-World-Template/contributors", "deployments_url": "https://api.github.com/repos/octocat/Hello-World-Template/deployments", "downloads_url": "https://api.github.com/repos/octocat/Hello-World-Template/downloads", "events_url": "https://api.github.com/repos/octocat/Hello-World-Template/events", "forks_url": "https://api.github.com/repos/octocat/Hello-World-Template/forks", "git_commits_url": "https://api.github.com/repos/octocat/Hello-World-Template/git/commits{/sha}", "git_refs_url": "https://api.github.com/repos/octocat/Hello-World-Template/git/refs{/sha}", "git_tags_url": "https://api.github.com/repos/octocat/Hello-World-Template/git/tags{/sha}", "git_url": "git:github.com/octocat/Hello-World-Template.git", "issue_comment_url": "https://api.github.com/repos/octocat/Hello-World-Template/issues/comments{/number}", "issue_events_url": "https://api.github.com/repos/octocat/Hello-World-Template/issues/events{/number}", "issues_url": "https://api.github.com/repos/octocat/Hello-World-Template/issues{/number}", "keys_url": "https://api.github.com/repos/octocat/Hello-World-Template/keys{/key_id}", "labels_url": "https://api.github.com/repos/octocat/Hello-World-Template/labels{/name}", "languages_url": "https://api.github.com/repos/octocat/Hello-World-Template/languages", "merges_url": "https://api.github.com/repos/octocat/Hello-World-Template/merges", "milestones_url": "https://api.github.com/repos/octocat/Hello-World-Template/milestones{/number}", "notifications_url": "https://api.github.com/repos/octocat/Hello-World-Template/notifications{?since,all,participating}", "pulls_url": "https://api.github.com/repos/octocat/Hello-World-Template/pulls{/number}", "releases_url": "https://api.github.com/repos/octocat/Hello-World-Template/releases{/id}", "ssh_url": "git@github.com:octocat/Hello-World-Template.git", "stargazers_url": "https://api.github.com/repos/octocat/Hello-World-Template/stargazers", "statuses_url": "https://api.github.com/repos/octocat/Hello-World-Template/statuses/{sha}", "subscribers_url": "https://api.github.com/repos/octocat/Hello-World-Template/subscribers", "subscription_url": "https://api.github.com/repos/octocat/Hello-World-Template/subscription", "tags_url": "https://api.github.com/repos/octocat/Hello-World-Template/tags", "teams_url": "https://api.github.com/repos/octocat/Hello-World-Template/teams", "trees_url": "https://api.github.com/repos/octocat/Hello-World-Template/git/trees{/sha}", "clone_url": "https://github.com/octocat/Hello-World-Template.git", "mirror_url": "git:git.example.com/octocat/Hello-World-Template", "hooks_url": "https://api.github.com/repos/octocat/Hello-World-Template/hooks", "svn_url": "https://svn.github.com/octocat/Hello-World-Template", "homepage": "https://github.com", "forks": 9, "forks_count": 9, "stargazers_count": 80, "watchers_count": 80, "watchers": 80, "size": 108, "default_branch": "master", "open_issues": 0, "open_issues_count": 0, "is_template": true, "license": { "key": "mit", "name": "MIT License", "url": "https://api.github.com/licenses/mit", "spdx_id": "MIT", "node_id": "MDc6TGljZW5zZW1pdA==", "html_url": "https://api.github.com/licenses/mit" }, "topics": [ "octocat", "atom", "electron", "api" ], "has_issues": true, "has_projects": true, "has_wiki": true, "has_pages": false, "has_downloads": true, "archived": false, "disabled": false, "visibility": "public", "pushed_at": "2011-01-26T19:06:43Z", "created_at": "2011-01-26T19:01:12Z", "updated_at": "2011-01-26T19:14:43Z", "permissions": { "admin": false, "push": false, "pull": true }, "allow_rebase_merge": true, "temp_clone_token": "ABTLWHOULUVAXGTRYU7OC2876QJ2O", "allow_squash_merge": true, "delete_branch_on_merge": true, "allow_merge_commit": true, "subscribers_count": 42, "network_count": 0 } } } }, "check-run-paginated": { "value": { "total_count": 1, "check_runs": [ { "id": 4, "head_sha": "ce587453ced02b1526dfb4cb910479d431683101", "node_id": "MDg6Q2hlY2tSdW40", "external_id": "", "url": "https://api.github.com/repos/github/hello-world/check-runs/4", "html_url": "https://github.com/github/hello-world/runs/4", "details_url": "https://example.com", "status": "completed", "conclusion": "neutral", "started_at": "2018-05-04T01:14:52Z", "completed_at": "2018-05-04T01:14:52Z", "output": { "title": "Mighty Readme report", "summary": "There are 0 failures, 2 warnings, and 1 notice.", "text": "You may have some misspelled words on lines 2 and 4. You also may want to add a section in your README about how to install your app.", "annotations_count": 2, "annotations_url": "https://api.github.com/repos/github/hello-world/check-runs/4/annotations" }, "name": "mighty_readme", "check_suite": { "id": 5 }, "app": { "id": 1, "slug": "octoapp", "node_id": "MDExOkludGVncmF0aW9uMQ==", "owner": { "login": "github", "id": 1, "node_id": "MDEyOk9yZ2FuaXphdGlvbjE=", "url": "https://api.github.com/orgs/github", "repos_url": "https://api.github.com/orgs/github/repos", "events_url": "https://api.github.com/orgs/github/events", "avatar_url": "https://github.com/images/error/octocat_happy.gif", "gravatar_id": "", "html_url": "https://github.com/octocat", "followers_url": "https://api.github.com/users/octocat/followers", "following_url": "https://api.github.com/users/octocat/following{/other_user}", "gists_url": "https://api.github.com/users/octocat/gists{/gist_id}", "starred_url": "https://api.github.com/users/octocat/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/octocat/subscriptions", "organizations_url": "https://api.github.com/users/octocat/orgs", "received_events_url": "https://api.github.com/users/octocat/received_events", "type": "User", "site_admin": true }, "name": "Octocat App", "description": "", "external_url": "https://example.com", "html_url": "https://github.com/apps/octoapp", "created_at": "2017-07-08T16:18:44-04:00", "updated_at": "2017-07-08T16:18:44-04:00", "permissions": { "metadata": "read", "contents": "read", "issues": "write", "single_file": "write" }, "events": [ "push", "pull_request" ] }, "pull_requests": [ { "url": "https://api.github.com/repos/github/hello-world/pulls/1", "id": 1934, "number": 3956, "head": { "ref": "say-hello", "sha": "3dca65fa3e8d4b3da3f3d056c59aee1c50f41390", "repo": { "id": 526, "url": "https://api.github.com/repos/github/hello-world", "name": "hello-world" } }, "base": { "ref": "master", "sha": "e7fdf7640066d71ad16a86fbcbb9c6a10a18af4f", "repo": { "id": 526, "url": "https://api.github.com/repos/github/hello-world", "name": "hello-world" } } } ] } ] } }, "code-scanning-alert-items": { "value": [ { "number": 4, "created_at": "2020-02-13T12:29:18Z", "url": "https://api.github.com/repos/octocat/hello-world/code-scanning/alerts/4", "html_url": "https://github.com/octocat/hello-world/code-scanning/4", "state": "open", "dismissed_by": null, "dismissed_at": null, "dismissed_reason": null, "rule": { "id": "js/zipslip", "severity": "error", "description": "Arbitrary file write during zip extraction", "name": "js/zipslip" }, "tool": { "name": "CodeQL", "guid": null, "version": "2.4.0" }, "most_recent_instance": { "ref": "refs/heads/main", "analysis_key": ".github/workflows/codeql-analysis.yml:CodeQL-Build", "environment": "{}", "state": "open", "commit_sha": "39406e42cb832f683daa691dd652a8dc36ee8930", "message": { "text": "This path depends on a user-provided value." }, "location": { "path": "spec-main/api-session-spec.ts", "start_line": 917, "end_line": 917, "start_column": 7, "end_column": 18 }, "classifications": [ "test" ] }, "instances_url": "https://api.github.com/repos/octocat/hello-world/code-scanning/alerts/4/instances" }, { "number": 3, "created_at": "2020-02-13T12:29:18Z", "url": "https://api.github.com/repos/octocat/hello-world/code-scanning/alerts/3", "html_url": "https://github.com/octocat/hello-world/code-scanning/3", "state": "dismissed", "dismissed_by": { "login": "octocat", "id": 1, "node_id": "MDQ6VXNlcjE=", "avatar_url": "https://github.com/images/error/octocat_happy.gif", "gravatar_id": "", "url": "https://api.github.com/users/octocat", "html_url": "https://github.com/octocat", "followers_url": "https://api.github.com/users/octocat/followers", "following_url": "https://api.github.com/users/octocat/following{/other_user}", "gists_url": "https://api.github.com/users/octocat/gists{/gist_id}", "starred_url": "https://api.github.com/users/octocat/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/octocat/subscriptions", "organizations_url": "https://api.github.com/users/octocat/orgs", "repos_url": "https://api.github.com/users/octocat/repos", "events_url": "https://api.github.com/users/octocat/events{/privacy}", "received_events_url": "https://api.github.com/users/octocat/received_events", "type": "User", "site_admin": false }, "dismissed_at": "2020-02-14T12:29:18Z", "dismissed_reason": "false positive", "rule": { "id": "js/zipslip", "severity": "error", "description": "Arbitrary file write during zip extraction", "name": "js/zipslip" }, "tool": { "name": "CodeQL", "guid": null, "version": "2.4.0" }, "most_recent_instance": { "ref": "refs/heads/main", "analysis_key": ".github/workflows/codeql-analysis.yml:CodeQL-Build", "environment": "{}", "state": "open", "commit_sha": "39406e42cb832f683daa691dd652a8dc36ee8930", "message": { "text": "This path depends on a user-provided value." }, "location": { "path": "lib/ab12-gen.js", "start_line": 917, "end_line": 917, "start_column": 7, "end_column": 18 }, "classifications": [ ] }, "instances_url": "https://api.github.com/repos/octocat/hello-world/code-scanning/alerts/3/instances" } ] }, "code-scanning-alert": { "value": { "number": 42, "created_at": "2020-06-19T11:21:34Z", "url": "https://api.github.com/repos/octocat/hello-world/code-scanning/alerts/42", "html_url": "https://github.com/octocat/hello-world/code-scanning/42", "state": "dismissed", "dismissed_by": { "login": "octocat", "id": 54933897, "node_id": "MDQ6VXNlcjE=", "avatar_url": "https://github.com/images/error/octocat_happy.gif", "gravatar_id": "", "url": "https://api.github.com/users/octocat", "html_url": "https://github.com/octocat", "followers_url": "https://api.github.com/users/octocat/followers", "following_url": "https://api.github.com/users/octocat/following{/other_user}", "gists_url": "https://api.github.com/users/octocat/gists{/gist_id}", "starred_url": "https://api.github.com/users/octocat/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/octocat/subscriptions", "organizations_url": "https://api.github.com/users/octocat/orgs", "repos_url": "https://api.github.com/users/octocat/repos", "events_url": "https://api.github.com/users/octocat/events{/privacy}", "received_events_url": "https://api.github.com/users/octocat/received_events", "type": "User", "site_admin": false }, "dismissed_at": "2020-02-14T12:29:18Z", "dismissed_reason": "false positive", "rule": { "id": "js/zipslip", "severity": "error", "description": "Arbitrary file write during zip extraction (\"Zip Slip\")", "name": "js/zipslip", "full_description": "Extracting files from a malicious zip archive without validating that the destination file path is within the destination directory can cause files outside the destination directory to be overwritten.", "tags": [ "security", "external/cwe/cwe-022" ], "help": "# Arbitrary file write during zip extraction (\"Zip Slip\")\\nExtracting files from a malicious zip archive without validating that the destination file path is within the destination directory can cause files outside the destination directory to be overwritten ..." }, "tool": { "name": "CodeQL", "guid": null, "version": "2.4.0" }, "most_recent_instance": { "ref": "refs/heads/main", "analysis_key": ".github/workflows/codeql-analysis.yml:CodeQL-Build", "environment": "{}", "state": "dismissed", "commit_sha": "39406e42cb832f683daa691dd652a8dc36ee8930", "message": { "text": "This path depends on a user-provided value." }, "location": { "path": "spec-main/api-session-spec.ts", "start_line": 917, "end_line": 917, "start_column": 7, "end_column": 18 }, "classifications": [ "test" ] }, "instances_url": "https://api.github.com/repos/octocat/hello-world/code-scanning/alerts/42/instances" } }, "code-scanning-alert-dismissed": { "value": { "number": 42, "created_at": "2020-08-25T21:28:36Z", "url": "https://api.github.com/repos/octocat/hello-world/code-scanning/alerts/42", "html_url": "https://github.com/octocat/hello-world/code-scanning/42", "state": "dismissed", "dismissed_by": { "login": "octocat", "id": 1, "node_id": "MDQ6VXNlcjE=", "avatar_url": "https://github.com/images/error/octocat_happy.gif", "gravatar_id": "", "url": "https://api.github.com/users/octocat", "html_url": "https://github.com/octocat", "followers_url": "https://api.github.com/users/octocat/followers", "following_url": "https://api.github.com/users/octocat/following{/other_user}", "gists_url": "https://api.github.com/users/octocat/gists{/gist_id}", "starred_url": "https://api.github.com/users/octocat/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/octocat/subscriptions", "organizations_url": "https://api.github.com/users/octocat/orgs", "repos_url": "https://api.github.com/users/octocat/repos", "events_url": "https://api.github.com/users/octocat/events{/privacy}", "received_events_url": "https://api.github.com/users/octocat/received_events", "type": "User", "site_admin": false }, "dismissed_at": "2020-09-02T22:34:56Z", "dismissed_reason": "false positive", "rule": { "id": "js/zipslip", "severity": "error", "description": "Arbitrary file write during zip extraction (\"Zip Slip\")", "name": "js/zipslip", "full_description": "Extracting files from a malicious zip archive without validating that the destination file path is within the destination directory can cause files outside the destination directory to be overwritten.", "tags": [ "security", "external/cwe/cwe-022" ], "help": "# Arbitrary file write during zip extraction (\"Zip Slip\")\\nExtracting files from a malicious zip archive without validating that the destination file path is within the destination directory can cause files outside the destination directory to be overwritten ..." }, "tool": { "name": "CodeQL", "guid": null, "version": "2.4.0" }, "most_recent_instance": { "ref": "refs/heads/main", "analysis_key": ".github/workflows/codeql-analysis.yml:CodeQL-Build", "environment": "{}", "state": "dismissed", "commit_sha": "39406e42cb832f683daa691dd652a8dc36ee8930", "message": { "text": "This path depends on a user-provided value." }, "location": { "path": "spec-main/api-session-spec.ts", "start_line": 917, "end_line": 917, "start_column": 7, "end_column": 18 }, "classifications": [ "test" ] }, "instances_url": "https://api.github.com/repos/octocat/hello-world/code-scanning/alerts/42/instances" } }, "code-scanning-analysis-items": { "value": [ { "ref": "refs/heads/main", "commit_sha": "d99612c3e1f2970085cfbaeadf8f010ef69bad83", "analysis_key": ".github/workflows/codeql-analysis.yml:analyze", "environment": "{\"language\":\"python\"}", "error": "", "category": ".github/workflows/codeql-analysis.yml:analyze/language:python", "created_at": "2020-08-27T15:05:21Z", "results_count": 17, "rules_count": 49, "id": 201, "url": "https://api.github.com/repos/octocat/hello-world/code-scanning/analyses/201", "sarif_id": "6c81cd8e-b078-4ac3-a3be-1dad7dbd0b53", "tool": { "name": "CodeQL", "guid": null, "version": "2.4.0" }, "deletable": true, "warning": "" }, { "ref": "refs/heads/my-branch", "commit_sha": "c8cff6510d4d084fb1b4aa13b64b97ca12b07321", "analysis_key": ".github/workflows/shiftleft.yml:build", "environment": "{}", "error": "", "category": ".github/workflows/shiftleft.yml:build/", "created_at": "2020-08-31T22:46:44Z", "results_count": 17, "rules_count": 32, "id": 200, "url": "https://api.github.com/repos/octocat/hello-world/code-scanning/analyses/200", "sarif_id": "8981cd8e-b078-4ac3-a3be-1dad7dbd0b582", "tool": { "name": "Python Security Analysis", "guid": null, "version": "1.2.0" }, "deletable": true, "warning": "" } ] }, "code-scanning-sarif-upload": { "summary": "Default response", "value": { "id": "47177e22-5596-11eb-80a1-c1e54ef945c6", "url": "https://api.github.com/repos/octocat/hello-world/code-scanning/sarifs/47177e22-5596-11eb-80a1-c1e54ef945c6" } }, "collaborator-items": { "value": [ { "login": "octocat", "id": 1, "node_id": "MDQ6VXNlcjE=", "avatar_url": "https://github.com/images/error/octocat_happy.gif", "gravatar_id": "", "url": "https://api.github.com/users/octocat", "html_url": "https://github.com/octocat", "followers_url": "https://api.github.com/users/octocat/followers", "following_url": "https://api.github.com/users/octocat/following{/other_user}", "gists_url": "https://api.github.com/users/octocat/gists{/gist_id}", "starred_url": "https://api.github.com/users/octocat/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/octocat/subscriptions", "organizations_url": "https://api.github.com/users/octocat/orgs", "repos_url": "https://api.github.com/users/octocat/repos", "events_url": "https://api.github.com/users/octocat/events{/privacy}", "received_events_url": "https://api.github.com/users/octocat/received_events", "type": "User", "site_admin": false, "permissions": { "pull": true, "push": true, "admin": false } } ] }, "repository-invitation-response-when-a-new-invitation-is-created": { "value": { "id": 1, "node_id": "MDEwOlJlcG9zaXRvcnkxMjk2MjY5", "repository": { "id": 1296269, "node_id": "MDEwOlJlcG9zaXRvcnkxMjk2MjY5", "name": "Hello-World", "full_name": "octocat/Hello-World", "owner": { "login": "octocat", "id": 1, "node_id": "MDQ6VXNlcjE=", "avatar_url": "https://github.com/images/error/octocat_happy.gif", "gravatar_id": "", "url": "https://api.github.com/users/octocat", "html_url": "https://github.com/octocat", "followers_url": "https://api.github.com/users/octocat/followers", "following_url": "https://api.github.com/users/octocat/following{/other_user}", "gists_url": "https://api.github.com/users/octocat/gists{/gist_id}", "starred_url": "https://api.github.com/users/octocat/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/octocat/subscriptions", "organizations_url": "https://api.github.com/users/octocat/orgs", "repos_url": "https://api.github.com/users/octocat/repos", "events_url": "https://api.github.com/users/octocat/events{/privacy}", "received_events_url": "https://api.github.com/users/octocat/received_events", "type": "User", "site_admin": false }, "private": false, "html_url": "https://github.com/octocat/Hello-World", "description": "This your first repo!", "fork": false, "url": "https://api.github.com/repos/octocat/Hello-World", "archive_url": "https://api.github.com/repos/octocat/Hello-World/{archive_format}{/ref}", "assignees_url": "https://api.github.com/repos/octocat/Hello-World/assignees{/user}", "blobs_url": "https://api.github.com/repos/octocat/Hello-World/git/blobs{/sha}", "branches_url": "https://api.github.com/repos/octocat/Hello-World/branches{/branch}", "collaborators_url": "https://api.github.com/repos/octocat/Hello-World/collaborators{/collaborator}", "comments_url": "https://api.github.com/repos/octocat/Hello-World/comments{/number}", "commits_url": "https://api.github.com/repos/octocat/Hello-World/commits{/sha}", "compare_url": "https://api.github.com/repos/octocat/Hello-World/compare/{base}...{head}", "contents_url": "https://api.github.com/repos/octocat/Hello-World/contents/{+path}", "contributors_url": "https://api.github.com/repos/octocat/Hello-World/contributors", "deployments_url": "https://api.github.com/repos/octocat/Hello-World/deployments", "downloads_url": "https://api.github.com/repos/octocat/Hello-World/downloads", "events_url": "https://api.github.com/repos/octocat/Hello-World/events", "forks_url": "https://api.github.com/repos/octocat/Hello-World/forks", "git_commits_url": "https://api.github.com/repos/octocat/Hello-World/git/commits{/sha}", "git_refs_url": "https://api.github.com/repos/octocat/Hello-World/git/refs{/sha}", "git_tags_url": "https://api.github.com/repos/octocat/Hello-World/git/tags{/sha}", "git_url": "git:github.com/octocat/Hello-World.git", "issue_comment_url": "https://api.github.com/repos/octocat/Hello-World/issues/comments{/number}", "issue_events_url": "https://api.github.com/repos/octocat/Hello-World/issues/events{/number}", "issues_url": "https://api.github.com/repos/octocat/Hello-World/issues{/number}", "keys_url": "https://api.github.com/repos/octocat/Hello-World/keys{/key_id}", "labels_url": "https://api.github.com/repos/octocat/Hello-World/labels{/name}", "languages_url": "https://api.github.com/repos/octocat/Hello-World/languages", "merges_url": "https://api.github.com/repos/octocat/Hello-World/merges", "milestones_url": "https://api.github.com/repos/octocat/Hello-World/milestones{/number}", "notifications_url": "https://api.github.com/repos/octocat/Hello-World/notifications{?since,all,participating}", "pulls_url": "https://api.github.com/repos/octocat/Hello-World/pulls{/number}", "releases_url": "https://api.github.com/repos/octocat/Hello-World/releases{/id}", "ssh_url": "git@github.com:octocat/Hello-World.git", "stargazers_url": "https://api.github.com/repos/octocat/Hello-World/stargazers", "statuses_url": "https://api.github.com/repos/octocat/Hello-World/statuses/{sha}", "subscribers_url": "https://api.github.com/repos/octocat/Hello-World/subscribers", "subscription_url": "https://api.github.com/repos/octocat/Hello-World/subscription", "tags_url": "https://api.github.com/repos/octocat/Hello-World/tags", "teams_url": "https://api.github.com/repos/octocat/Hello-World/teams", "trees_url": "https://api.github.com/repos/octocat/Hello-World/git/trees{/sha}", "hooks_url": "http://api.github.com/repos/octocat/Hello-World/hooks" }, "invitee": { "login": "octocat", "id": 1, "node_id": "MDQ6VXNlcjE=", "avatar_url": "https://github.com/images/error/octocat_happy.gif", "gravatar_id": "", "url": "https://api.github.com/users/octocat", "html_url": "https://github.com/octocat", "followers_url": "https://api.github.com/users/octocat/followers", "following_url": "https://api.github.com/users/octocat/following{/other_user}", "gists_url": "https://api.github.com/users/octocat/gists{/gist_id}", "starred_url": "https://api.github.com/users/octocat/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/octocat/subscriptions", "organizations_url": "https://api.github.com/users/octocat/orgs", "repos_url": "https://api.github.com/users/octocat/repos", "events_url": "https://api.github.com/users/octocat/events{/privacy}", "received_events_url": "https://api.github.com/users/octocat/received_events", "type": "User", "site_admin": false }, "inviter": { "login": "octocat", "id": 1, "node_id": "MDQ6VXNlcjE=", "avatar_url": "https://github.com/images/error/octocat_happy.gif", "gravatar_id": "", "url": "https://api.github.com/users/octocat", "html_url": "https://github.com/octocat", "followers_url": "https://api.github.com/users/octocat/followers", "following_url": "https://api.github.com/users/octocat/following{/other_user}", "gists_url": "https://api.github.com/users/octocat/gists{/gist_id}", "starred_url": "https://api.github.com/users/octocat/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/octocat/subscriptions", "organizations_url": "https://api.github.com/users/octocat/orgs", "repos_url": "https://api.github.com/users/octocat/repos", "events_url": "https://api.github.com/users/octocat/events{/privacy}", "received_events_url": "https://api.github.com/users/octocat/received_events", "type": "User", "site_admin": false }, "permissions": "write", "created_at": "2016-06-13T14:52:50-05:00", "url": "https://api.github.com/user/repository_invitations/1296269", "html_url": "https://github.com/octocat/Hello-World/invitations" } }, "repository-collaborator-permission-response-if-user-has-admin-permissions": { "value": { "permission": "admin", "user": { "login": "octocat", "id": 1, "node_id": "MDQ6VXNlcjE=", "avatar_url": "https://github.com/images/error/octocat_happy.gif", "gravatar_id": "", "url": "https://api.github.com/users/octocat", "html_url": "https://github.com/octocat", "followers_url": "https://api.github.com/users/octocat/followers", "following_url": "https://api.github.com/users/octocat/following{/other_user}", "gists_url": "https://api.github.com/users/octocat/gists{/gist_id}", "starred_url": "https://api.github.com/users/octocat/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/octocat/subscriptions", "organizations_url": "https://api.github.com/users/octocat/orgs", "repos_url": "https://api.github.com/users/octocat/repos", "events_url": "https://api.github.com/users/octocat/events{/privacy}", "received_events_url": "https://api.github.com/users/octocat/received_events", "type": "User", "site_admin": false } } }, "commit-comment-items": { "value": [ { "html_url": "https://github.com/octocat/Hello-World/commit/6dcb09b5b57875f334f61aebed695e2e4193db5e#commitcomment-1", "url": "https://api.github.com/repos/octocat/Hello-World/comments/1", "id": 1, "node_id": "MDEzOkNvbW1pdENvbW1lbnQx", "body": "Great stuff", "path": "file1.txt", "position": 4, "line": 14, "commit_id": "6dcb09b5b57875f334f61aebed695e2e4193db5e", "user": { "login": "octocat", "id": 1, "node_id": "MDQ6VXNlcjE=", "avatar_url": "https://github.com/images/error/octocat_happy.gif", "gravatar_id": "", "url": "https://api.github.com/users/octocat", "html_url": "https://github.com/octocat", "followers_url": "https://api.github.com/users/octocat/followers", "following_url": "https://api.github.com/users/octocat/following{/other_user}", "gists_url": "https://api.github.com/users/octocat/gists{/gist_id}", "starred_url": "https://api.github.com/users/octocat/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/octocat/subscriptions", "organizations_url": "https://api.github.com/users/octocat/orgs", "repos_url": "https://api.github.com/users/octocat/repos", "events_url": "https://api.github.com/users/octocat/events{/privacy}", "received_events_url": "https://api.github.com/users/octocat/received_events", "type": "User", "site_admin": false }, "created_at": "2011-04-14T16:00:49Z", "updated_at": "2011-04-14T16:00:49Z", "author_association": "COLLABORATOR" } ] }, "commit-comment": { "value": { "html_url": "https://github.com/octocat/Hello-World/commit/6dcb09b5b57875f334f61aebed695e2e4193db5e#commitcomment-1", "url": "https://api.github.com/repos/octocat/Hello-World/comments/1", "id": 1, "node_id": "MDEzOkNvbW1pdENvbW1lbnQx", "body": "Great stuff", "path": "file1.txt", "position": 4, "line": 14, "commit_id": "6dcb09b5b57875f334f61aebed695e2e4193db5e", "author_association": "COLLABORATOR", "user": { "login": "octocat", "id": 1, "node_id": "MDQ6VXNlcjE=", "avatar_url": "https://github.com/images/error/octocat_happy.gif", "gravatar_id": "", "url": "https://api.github.com/users/octocat", "html_url": "https://github.com/octocat", "followers_url": "https://api.github.com/users/octocat/followers", "following_url": "https://api.github.com/users/octocat/following{/other_user}", "gists_url": "https://api.github.com/users/octocat/gists{/gist_id}", "starred_url": "https://api.github.com/users/octocat/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/octocat/subscriptions", "organizations_url": "https://api.github.com/users/octocat/orgs", "repos_url": "https://api.github.com/users/octocat/repos", "events_url": "https://api.github.com/users/octocat/events{/privacy}", "received_events_url": "https://api.github.com/users/octocat/received_events", "type": "User", "site_admin": false }, "created_at": "2011-04-14T16:00:49Z", "updated_at": "2011-04-14T16:00:49Z" } }, "commit-comment-2": { "value": { "html_url": "https://github.com/octocat/Hello-World/commit/6dcb09b5b57875f334f61aebed695e2e4193db5e#commitcomment-1", "url": "https://api.github.com/repos/octocat/Hello-World/comments/1", "id": 1, "node_id": "MDEzOkNvbW1pdENvbW1lbnQx", "body": "Nice change", "path": "file1.txt", "position": 4, "line": 14, "commit_id": "6dcb09b5b57875f334f61aebed695e2e4193db5e", "author_association": "COLLABORATOR", "user": { "login": "octocat", "id": 1, "node_id": "MDQ6VXNlcjE=", "avatar_url": "https://github.com/images/error/octocat_happy.gif", "gravatar_id": "", "url": "https://api.github.com/users/octocat", "html_url": "https://github.com/octocat", "followers_url": "https://api.github.com/users/octocat/followers", "following_url": "https://api.github.com/users/octocat/following{/other_user}", "gists_url": "https://api.github.com/users/octocat/gists{/gist_id}", "starred_url": "https://api.github.com/users/octocat/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/octocat/subscriptions", "organizations_url": "https://api.github.com/users/octocat/orgs", "repos_url": "https://api.github.com/users/octocat/repos", "events_url": "https://api.github.com/users/octocat/events{/privacy}", "received_events_url": "https://api.github.com/users/octocat/received_events", "type": "User", "site_admin": false }, "created_at": "2011-04-14T16:00:49Z", "updated_at": "2011-04-14T16:00:49Z" } }, "commit-items": { "value": [ { "url": "https://api.github.com/repos/octocat/Hello-World/commits/6dcb09b5b57875f334f61aebed695e2e4193db5e", "sha": "6dcb09b5b57875f334f61aebed695e2e4193db5e", "node_id": "MDY6Q29tbWl0NmRjYjA5YjViNTc4NzVmMzM0ZjYxYWViZWQ2OTVlMmU0MTkzZGI1ZQ==", "html_url": "https://github.com/octocat/Hello-World/commit/6dcb09b5b57875f334f61aebed695e2e4193db5e", "comments_url": "https://api.github.com/repos/octocat/Hello-World/commits/6dcb09b5b57875f334f61aebed695e2e4193db5e/comments", "commit": { "url": "https://api.github.com/repos/octocat/Hello-World/git/commits/6dcb09b5b57875f334f61aebed695e2e4193db5e", "author": { "name": "Monalisa Octocat", "email": "support@github.com", "date": "2011-04-14T16:00:49Z" }, "committer": { "name": "Monalisa Octocat", "email": "support@github.com", "date": "2011-04-14T16:00:49Z" }, "message": "Fix all the bugs", "tree": { "url": "https://api.github.com/repos/octocat/Hello-World/tree/6dcb09b5b57875f334f61aebed695e2e4193db5e", "sha": "6dcb09b5b57875f334f61aebed695e2e4193db5e" }, "comment_count": 0, "verification": { "verified": false, "reason": "unsigned", "signature": null, "payload": null } }, "author": { "login": "octocat", "id": 1, "node_id": "MDQ6VXNlcjE=", "avatar_url": "https://github.com/images/error/octocat_happy.gif", "gravatar_id": "", "url": "https://api.github.com/users/octocat", "html_url": "https://github.com/octocat", "followers_url": "https://api.github.com/users/octocat/followers", "following_url": "https://api.github.com/users/octocat/following{/other_user}", "gists_url": "https://api.github.com/users/octocat/gists{/gist_id}", "starred_url": "https://api.github.com/users/octocat/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/octocat/subscriptions", "organizations_url": "https://api.github.com/users/octocat/orgs", "repos_url": "https://api.github.com/users/octocat/repos", "events_url": "https://api.github.com/users/octocat/events{/privacy}", "received_events_url": "https://api.github.com/users/octocat/received_events", "type": "User", "site_admin": false }, "committer": { "login": "octocat", "id": 1, "node_id": "MDQ6VXNlcjE=", "avatar_url": "https://github.com/images/error/octocat_happy.gif", "gravatar_id": "", "url": "https://api.github.com/users/octocat", "html_url": "https://github.com/octocat", "followers_url": "https://api.github.com/users/octocat/followers", "following_url": "https://api.github.com/users/octocat/following{/other_user}", "gists_url": "https://api.github.com/users/octocat/gists{/gist_id}", "starred_url": "https://api.github.com/users/octocat/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/octocat/subscriptions", "organizations_url": "https://api.github.com/users/octocat/orgs", "repos_url": "https://api.github.com/users/octocat/repos", "events_url": "https://api.github.com/users/octocat/events{/privacy}", "received_events_url": "https://api.github.com/users/octocat/received_events", "type": "User", "site_admin": false }, "parents": [ { "url": "https://api.github.com/repos/octocat/Hello-World/commits/6dcb09b5b57875f334f61aebed695e2e4193db5e", "sha": "6dcb09b5b57875f334f61aebed695e2e4193db5e" } ] } ] }, "branch-short-items": { "value": [ { "name": "branch_5", "commit": { "sha": "c5b97d5ae6c19d5c5df71a34c7fbeeda2479ccbc", "url": "https://api.github.com/repos/octocat/Hello-World/commits/c5b97d5ae6c19d5c5df71a34c7fbeeda2479ccbc" }, "protected": false } ] }, "pull-request-simple-items": { "value": [ { "url": "https://api.github.com/repos/octocat/Hello-World/pulls/1347", "id": 1, "node_id": "MDExOlB1bGxSZXF1ZXN0MQ==", "html_url": "https://github.com/octocat/Hello-World/pull/1347", "diff_url": "https://github.com/octocat/Hello-World/pull/1347.diff", "patch_url": "https://github.com/octocat/Hello-World/pull/1347.patch", "issue_url": "https://api.github.com/repos/octocat/Hello-World/issues/1347", "commits_url": "https://api.github.com/repos/octocat/Hello-World/pulls/1347/commits", "review_comments_url": "https://api.github.com/repos/octocat/Hello-World/pulls/1347/comments", "review_comment_url": "https://api.github.com/repos/octocat/Hello-World/pulls/comments{/number}", "comments_url": "https://api.github.com/repos/octocat/Hello-World/issues/1347/comments", "statuses_url": "https://api.github.com/repos/octocat/Hello-World/statuses/6dcb09b5b57875f334f61aebed695e2e4193db5e", "number": 1347, "state": "open", "locked": true, "title": "Amazing new feature", "user": { "login": "octocat", "id": 1, "node_id": "MDQ6VXNlcjE=", "avatar_url": "https://github.com/images/error/octocat_happy.gif", "gravatar_id": "", "url": "https://api.github.com/users/octocat", "html_url": "https://github.com/octocat", "followers_url": "https://api.github.com/users/octocat/followers", "following_url": "https://api.github.com/users/octocat/following{/other_user}", "gists_url": "https://api.github.com/users/octocat/gists{/gist_id}", "starred_url": "https://api.github.com/users/octocat/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/octocat/subscriptions", "organizations_url": "https://api.github.com/users/octocat/orgs", "repos_url": "https://api.github.com/users/octocat/repos", "events_url": "https://api.github.com/users/octocat/events{/privacy}", "received_events_url": "https://api.github.com/users/octocat/received_events", "type": "User", "site_admin": false }, "body": "Please pull these awesome changes in!", "labels": [ { "id": 208045946, "node_id": "MDU6TGFiZWwyMDgwNDU5NDY=", "url": "https://api.github.com/repos/octocat/Hello-World/labels/bug", "name": "bug", "description": "Something isn't working", "color": "f29513", "default": true } ], "milestone": { "url": "https://api.github.com/repos/octocat/Hello-World/milestones/1", "html_url": "https://github.com/octocat/Hello-World/milestones/v1.0", "labels_url": "https://api.github.com/repos/octocat/Hello-World/milestones/1/labels", "id": 1002604, "node_id": "MDk6TWlsZXN0b25lMTAwMjYwNA==", "number": 1, "state": "open", "title": "v1.0", "description": "Tracking milestone for version 1.0", "creator": { "login": "octocat", "id": 1, "node_id": "MDQ6VXNlcjE=", "avatar_url": "https://github.com/images/error/octocat_happy.gif", "gravatar_id": "", "url": "https://api.github.com/users/octocat", "html_url": "https://github.com/octocat", "followers_url": "https://api.github.com/users/octocat/followers", "following_url": "https://api.github.com/users/octocat/following{/other_user}", "gists_url": "https://api.github.com/users/octocat/gists{/gist_id}", "starred_url": "https://api.github.com/users/octocat/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/octocat/subscriptions", "organizations_url": "https://api.github.com/users/octocat/orgs", "repos_url": "https://api.github.com/users/octocat/repos", "events_url": "https://api.github.com/users/octocat/events{/privacy}", "received_events_url": "https://api.github.com/users/octocat/received_events", "type": "User", "site_admin": false }, "open_issues": 4, "closed_issues": 8, "created_at": "2011-04-10T20:09:31Z", "updated_at": "2014-03-03T18:58:10Z", "closed_at": "2013-02-12T13:22:01Z", "due_on": "2012-10-09T23:39:01Z" }, "active_lock_reason": "too heated", "created_at": "2011-01-26T19:01:12Z", "updated_at": "2011-01-26T19:01:12Z", "closed_at": "2011-01-26T19:01:12Z", "merged_at": "2011-01-26T19:01:12Z", "merge_commit_sha": "e5bd3914e2e596debea16f433f57875b5b90bcd6", "assignee": { "login": "octocat", "id": 1, "node_id": "MDQ6VXNlcjE=", "avatar_url": "https://github.com/images/error/octocat_happy.gif", "gravatar_id": "", "url": "https://api.github.com/users/octocat", "html_url": "https://github.com/octocat", "followers_url": "https://api.github.com/users/octocat/followers", "following_url": "https://api.github.com/users/octocat/following{/other_user}", "gists_url": "https://api.github.com/users/octocat/gists{/gist_id}", "starred_url": "https://api.github.com/users/octocat/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/octocat/subscriptions", "organizations_url": "https://api.github.com/users/octocat/orgs", "repos_url": "https://api.github.com/users/octocat/repos", "events_url": "https://api.github.com/users/octocat/events{/privacy}", "received_events_url": "https://api.github.com/users/octocat/received_events", "type": "User", "site_admin": false }, "assignees": [ { "login": "octocat", "id": 1, "node_id": "MDQ6VXNlcjE=", "avatar_url": "https://github.com/images/error/octocat_happy.gif", "gravatar_id": "", "url": "https://api.github.com/users/octocat", "html_url": "https://github.com/octocat", "followers_url": "https://api.github.com/users/octocat/followers", "following_url": "https://api.github.com/users/octocat/following{/other_user}", "gists_url": "https://api.github.com/users/octocat/gists{/gist_id}", "starred_url": "https://api.github.com/users/octocat/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/octocat/subscriptions", "organizations_url": "https://api.github.com/users/octocat/orgs", "repos_url": "https://api.github.com/users/octocat/repos", "events_url": "https://api.github.com/users/octocat/events{/privacy}", "received_events_url": "https://api.github.com/users/octocat/received_events", "type": "User", "site_admin": false }, { "login": "hubot", "id": 1, "node_id": "MDQ6VXNlcjE=", "avatar_url": "https://github.com/images/error/hubot_happy.gif", "gravatar_id": "", "url": "https://api.github.com/users/hubot", "html_url": "https://github.com/hubot", "followers_url": "https://api.github.com/users/hubot/followers", "following_url": "https://api.github.com/users/hubot/following{/other_user}", "gists_url": "https://api.github.com/users/hubot/gists{/gist_id}", "starred_url": "https://api.github.com/users/hubot/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/hubot/subscriptions", "organizations_url": "https://api.github.com/users/hubot/orgs", "repos_url": "https://api.github.com/users/hubot/repos", "events_url": "https://api.github.com/users/hubot/events{/privacy}", "received_events_url": "https://api.github.com/users/hubot/received_events", "type": "User", "site_admin": true } ], "requested_reviewers": [ { "login": "other_user", "id": 1, "node_id": "MDQ6VXNlcjE=", "avatar_url": "https://github.com/images/error/other_user_happy.gif", "gravatar_id": "", "url": "https://api.github.com/users/other_user", "html_url": "https://github.com/other_user", "followers_url": "https://api.github.com/users/other_user/followers", "following_url": "https://api.github.com/users/other_user/following{/other_user}", "gists_url": "https://api.github.com/users/other_user/gists{/gist_id}", "starred_url": "https://api.github.com/users/other_user/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/other_user/subscriptions", "organizations_url": "https://api.github.com/users/other_user/orgs", "repos_url": "https://api.github.com/users/other_user/repos", "events_url": "https://api.github.com/users/other_user/events{/privacy}", "received_events_url": "https://api.github.com/users/other_user/received_events", "type": "User", "site_admin": false } ], "requested_teams": [ { "id": 1, "node_id": "MDQ6VGVhbTE=", "url": "https://api.github.com/teams/1", "html_url": "https://github.com/orgs/github/teams/justice-league", "name": "Justice League", "slug": "justice-league", "description": "A great team.", "privacy": "closed", "permission": "admin", "members_url": "https://api.github.com/teams/1/members{/member}", "repositories_url": "https://api.github.com/teams/1/repos" } ], "head": { "label": "octocat:new-topic", "ref": "new-topic", "sha": "6dcb09b5b57875f334f61aebed695e2e4193db5e", "user": { "login": "octocat", "id": 1, "node_id": "MDQ6VXNlcjE=", "avatar_url": "https://github.com/images/error/octocat_happy.gif", "gravatar_id": "", "url": "https://api.github.com/users/octocat", "html_url": "https://github.com/octocat", "followers_url": "https://api.github.com/users/octocat/followers", "following_url": "https://api.github.com/users/octocat/following{/other_user}", "gists_url": "https://api.github.com/users/octocat/gists{/gist_id}", "starred_url": "https://api.github.com/users/octocat/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/octocat/subscriptions", "organizations_url": "https://api.github.com/users/octocat/orgs", "repos_url": "https://api.github.com/users/octocat/repos", "events_url": "https://api.github.com/users/octocat/events{/privacy}", "received_events_url": "https://api.github.com/users/octocat/received_events", "type": "User", "site_admin": false }, "repo": { "id": 1296269, "node_id": "MDEwOlJlcG9zaXRvcnkxMjk2MjY5", "name": "Hello-World", "full_name": "octocat/Hello-World", "owner": { "login": "octocat", "id": 1, "node_id": "MDQ6VXNlcjE=", "avatar_url": "https://github.com/images/error/octocat_happy.gif", "gravatar_id": "", "url": "https://api.github.com/users/octocat", "html_url": "https://github.com/octocat", "followers_url": "https://api.github.com/users/octocat/followers", "following_url": "https://api.github.com/users/octocat/following{/other_user}", "gists_url": "https://api.github.com/users/octocat/gists{/gist_id}", "starred_url": "https://api.github.com/users/octocat/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/octocat/subscriptions", "organizations_url": "https://api.github.com/users/octocat/orgs", "repos_url": "https://api.github.com/users/octocat/repos", "events_url": "https://api.github.com/users/octocat/events{/privacy}", "received_events_url": "https://api.github.com/users/octocat/received_events", "type": "User", "site_admin": false }, "private": false, "html_url": "https://github.com/octocat/Hello-World", "description": "This your first repo!", "fork": false, "url": "https://api.github.com/repos/octocat/Hello-World", "archive_url": "https://api.github.com/repos/octocat/Hello-World/{archive_format}{/ref}", "assignees_url": "https://api.github.com/repos/octocat/Hello-World/assignees{/user}", "blobs_url": "https://api.github.com/repos/octocat/Hello-World/git/blobs{/sha}", "branches_url": "https://api.github.com/repos/octocat/Hello-World/branches{/branch}", "collaborators_url": "https://api.github.com/repos/octocat/Hello-World/collaborators{/collaborator}", "comments_url": "https://api.github.com/repos/octocat/Hello-World/comments{/number}", "commits_url": "https://api.github.com/repos/octocat/Hello-World/commits{/sha}", "compare_url": "https://api.github.com/repos/octocat/Hello-World/compare/{base}...{head}", "contents_url": "https://api.github.com/repos/octocat/Hello-World/contents/{+path}", "contributors_url": "https://api.github.com/repos/octocat/Hello-World/contributors", "deployments_url": "https://api.github.com/repos/octocat/Hello-World/deployments", "downloads_url": "https://api.github.com/repos/octocat/Hello-World/downloads", "events_url": "https://api.github.com/repos/octocat/Hello-World/events", "forks_url": "https://api.github.com/repos/octocat/Hello-World/forks", "git_commits_url": "https://api.github.com/repos/octocat/Hello-World/git/commits{/sha}", "git_refs_url": "https://api.github.com/repos/octocat/Hello-World/git/refs{/sha}", "git_tags_url": "https://api.github.com/repos/octocat/Hello-World/git/tags{/sha}", "git_url": "git:github.com/octocat/Hello-World.git", "issue_comment_url": "https://api.github.com/repos/octocat/Hello-World/issues/comments{/number}", "issue_events_url": "https://api.github.com/repos/octocat/Hello-World/issues/events{/number}", "issues_url": "https://api.github.com/repos/octocat/Hello-World/issues{/number}", "keys_url": "https://api.github.com/repos/octocat/Hello-World/keys{/key_id}", "labels_url": "https://api.github.com/repos/octocat/Hello-World/labels{/name}", "languages_url": "https://api.github.com/repos/octocat/Hello-World/languages", "merges_url": "https://api.github.com/repos/octocat/Hello-World/merges", "milestones_url": "https://api.github.com/repos/octocat/Hello-World/milestones{/number}", "notifications_url": "https://api.github.com/repos/octocat/Hello-World/notifications{?since,all,participating}", "pulls_url": "https://api.github.com/repos/octocat/Hello-World/pulls{/number}", "releases_url": "https://api.github.com/repos/octocat/Hello-World/releases{/id}", "ssh_url": "git@github.com:octocat/Hello-World.git", "stargazers_url": "https://api.github.com/repos/octocat/Hello-World/stargazers", "statuses_url": "https://api.github.com/repos/octocat/Hello-World/statuses/{sha}", "subscribers_url": "https://api.github.com/repos/octocat/Hello-World/subscribers", "subscription_url": "https://api.github.com/repos/octocat/Hello-World/subscription", "tags_url": "https://api.github.com/repos/octocat/Hello-World/tags", "teams_url": "https://api.github.com/repos/octocat/Hello-World/teams", "trees_url": "https://api.github.com/repos/octocat/Hello-World/git/trees{/sha}", "clone_url": "https://github.com/octocat/Hello-World.git", "mirror_url": "git:git.example.com/octocat/Hello-World", "hooks_url": "https://api.github.com/repos/octocat/Hello-World/hooks", "svn_url": "https://svn.github.com/octocat/Hello-World", "homepage": "https://github.com", "language": null, "forks_count": 9, "stargazers_count": 80, "watchers_count": 80, "size": 108, "default_branch": "master", "open_issues_count": 0, "is_template": true, "topics": [ "octocat", "atom", "electron", "api" ], "has_issues": true, "has_projects": true, "has_wiki": true, "has_pages": false, "has_downloads": true, "archived": false, "disabled": false, "visibility": "public", "pushed_at": "2011-01-26T19:06:43Z", "created_at": "2011-01-26T19:01:12Z", "updated_at": "2011-01-26T19:14:43Z", "permissions": { "admin": false, "push": false, "pull": true }, "allow_rebase_merge": true, "template_repository": null, "temp_clone_token": "ABTLWHOULUVAXGTRYU7OC2876QJ2O", "allow_squash_merge": true, "delete_branch_on_merge": true, "allow_merge_commit": true, "subscribers_count": 42, "network_count": 0, "license": { "key": "mit", "name": "MIT License", "url": "https://api.github.com/licenses/mit", "spdx_id": "MIT", "node_id": "MDc6TGljZW5zZW1pdA==", "html_url": "https://github.com/licenses/mit" }, "forks": 1, "open_issues": 1, "watchers": 1 } }, "base": { "label": "octocat:master", "ref": "master", "sha": "6dcb09b5b57875f334f61aebed695e2e4193db5e", "user": { "login": "octocat", "id": 1, "node_id": "MDQ6VXNlcjE=", "avatar_url": "https://github.com/images/error/octocat_happy.gif", "gravatar_id": "", "url": "https://api.github.com/users/octocat", "html_url": "https://github.com/octocat", "followers_url": "https://api.github.com/users/octocat/followers", "following_url": "https://api.github.com/users/octocat/following{/other_user}", "gists_url": "https://api.github.com/users/octocat/gists{/gist_id}", "starred_url": "https://api.github.com/users/octocat/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/octocat/subscriptions", "organizations_url": "https://api.github.com/users/octocat/orgs", "repos_url": "https://api.github.com/users/octocat/repos", "events_url": "https://api.github.com/users/octocat/events{/privacy}", "received_events_url": "https://api.github.com/users/octocat/received_events", "type": "User", "site_admin": false }, "repo": { "id": 1296269, "node_id": "MDEwOlJlcG9zaXRvcnkxMjk2MjY5", "name": "Hello-World", "full_name": "octocat/Hello-World", "owner": { "login": "octocat", "id": 1, "node_id": "MDQ6VXNlcjE=", "avatar_url": "https://github.com/images/error/octocat_happy.gif", "gravatar_id": "", "url": "https://api.github.com/users/octocat", "html_url": "https://github.com/octocat", "followers_url": "https://api.github.com/users/octocat/followers", "following_url": "https://api.github.com/users/octocat/following{/other_user}", "gists_url": "https://api.github.com/users/octocat/gists{/gist_id}", "starred_url": "https://api.github.com/users/octocat/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/octocat/subscriptions", "organizations_url": "https://api.github.com/users/octocat/orgs", "repos_url": "https://api.github.com/users/octocat/repos", "events_url": "https://api.github.com/users/octocat/events{/privacy}", "received_events_url": "https://api.github.com/users/octocat/received_events", "type": "User", "site_admin": false }, "private": false, "html_url": "https://github.com/octocat/Hello-World", "description": "This your first repo!", "fork": false, "url": "https://api.github.com/repos/octocat/Hello-World", "archive_url": "https://api.github.com/repos/octocat/Hello-World/{archive_format}{/ref}", "assignees_url": "https://api.github.com/repos/octocat/Hello-World/assignees{/user}", "blobs_url": "https://api.github.com/repos/octocat/Hello-World/git/blobs{/sha}", "branches_url": "https://api.github.com/repos/octocat/Hello-World/branches{/branch}", "collaborators_url": "https://api.github.com/repos/octocat/Hello-World/collaborators{/collaborator}", "comments_url": "https://api.github.com/repos/octocat/Hello-World/comments{/number}", "commits_url": "https://api.github.com/repos/octocat/Hello-World/commits{/sha}", "compare_url": "https://api.github.com/repos/octocat/Hello-World/compare/{base}...{head}", "contents_url": "https://api.github.com/repos/octocat/Hello-World/contents/{+path}", "contributors_url": "https://api.github.com/repos/octocat/Hello-World/contributors", "deployments_url": "https://api.github.com/repos/octocat/Hello-World/deployments", "downloads_url": "https://api.github.com/repos/octocat/Hello-World/downloads", "events_url": "https://api.github.com/repos/octocat/Hello-World/events", "forks_url": "https://api.github.com/repos/octocat/Hello-World/forks", "git_commits_url": "https://api.github.com/repos/octocat/Hello-World/git/commits{/sha}", "git_refs_url": "https://api.github.com/repos/octocat/Hello-World/git/refs{/sha}", "git_tags_url": "https://api.github.com/repos/octocat/Hello-World/git/tags{/sha}", "git_url": "git:github.com/octocat/Hello-World.git", "issue_comment_url": "https://api.github.com/repos/octocat/Hello-World/issues/comments{/number}", "issue_events_url": "https://api.github.com/repos/octocat/Hello-World/issues/events{/number}", "issues_url": "https://api.github.com/repos/octocat/Hello-World/issues{/number}", "keys_url": "https://api.github.com/repos/octocat/Hello-World/keys{/key_id}", "labels_url": "https://api.github.com/repos/octocat/Hello-World/labels{/name}", "languages_url": "https://api.github.com/repos/octocat/Hello-World/languages", "merges_url": "https://api.github.com/repos/octocat/Hello-World/merges", "milestones_url": "https://api.github.com/repos/octocat/Hello-World/milestones{/number}", "notifications_url": "https://api.github.com/repos/octocat/Hello-World/notifications{?since,all,participating}", "pulls_url": "https://api.github.com/repos/octocat/Hello-World/pulls{/number}", "releases_url": "https://api.github.com/repos/octocat/Hello-World/releases{/id}", "ssh_url": "git@github.com:octocat/Hello-World.git", "stargazers_url": "https://api.github.com/repos/octocat/Hello-World/stargazers", "statuses_url": "https://api.github.com/repos/octocat/Hello-World/statuses/{sha}", "subscribers_url": "https://api.github.com/repos/octocat/Hello-World/subscribers", "subscription_url": "https://api.github.com/repos/octocat/Hello-World/subscription", "tags_url": "https://api.github.com/repos/octocat/Hello-World/tags", "teams_url": "https://api.github.com/repos/octocat/Hello-World/teams", "trees_url": "https://api.github.com/repos/octocat/Hello-World/git/trees{/sha}", "clone_url": "https://github.com/octocat/Hello-World.git", "mirror_url": "git:git.example.com/octocat/Hello-World", "hooks_url": "https://api.github.com/repos/octocat/Hello-World/hooks", "svn_url": "https://svn.github.com/octocat/Hello-World", "homepage": "https://github.com", "language": null, "forks_count": 9, "stargazers_count": 80, "watchers_count": 80, "size": 108, "default_branch": "master", "open_issues_count": 0, "is_template": true, "topics": [ "octocat", "atom", "electron", "api" ], "has_issues": true, "has_projects": true, "has_wiki": true, "has_pages": false, "has_downloads": true, "archived": false, "disabled": false, "visibility": "public", "pushed_at": "2011-01-26T19:06:43Z", "created_at": "2011-01-26T19:01:12Z", "updated_at": "2011-01-26T19:14:43Z", "permissions": { "admin": false, "push": false, "pull": true }, "allow_rebase_merge": true, "template_repository": null, "temp_clone_token": "ABTLWHOULUVAXGTRYU7OC2876QJ2O", "allow_squash_merge": true, "delete_branch_on_merge": true, "allow_merge_commit": true, "subscribers_count": 42, "network_count": 0, "license": { "key": "mit", "name": "MIT License", "url": "https://api.github.com/licenses/mit", "spdx_id": "MIT", "node_id": "MDc6TGljZW5zZW1pdA==", "html_url": "https://github.com/licenses/mit" }, "forks": 1, "open_issues": 1, "watchers": 1 } }, "_links": { "self": { "href": "https://api.github.com/repos/octocat/Hello-World/pulls/1347" }, "html": { "href": "https://github.com/octocat/Hello-World/pull/1347" }, "issue": { "href": "https://api.github.com/repos/octocat/Hello-World/issues/1347" }, "comments": { "href": "https://api.github.com/repos/octocat/Hello-World/issues/1347/comments" }, "review_comments": { "href": "https://api.github.com/repos/octocat/Hello-World/pulls/1347/comments" }, "review_comment": { "href": "https://api.github.com/repos/octocat/Hello-World/pulls/comments{/number}" }, "commits": { "href": "https://api.github.com/repos/octocat/Hello-World/pulls/1347/commits" }, "statuses": { "href": "https://api.github.com/repos/octocat/Hello-World/statuses/6dcb09b5b57875f334f61aebed695e2e4193db5e" } }, "author_association": "OWNER", "draft": false } ] }, "commit": { "value": { "url": "https://api.github.com/repos/octocat/Hello-World/commits/6dcb09b5b57875f334f61aebed695e2e4193db5e", "sha": "6dcb09b5b57875f334f61aebed695e2e4193db5e", "node_id": "MDY6Q29tbWl0NmRjYjA5YjViNTc4NzVmMzM0ZjYxYWViZWQ2OTVlMmU0MTkzZGI1ZQ==", "html_url": "https://github.com/octocat/Hello-World/commit/6dcb09b5b57875f334f61aebed695e2e4193db5e", "comments_url": "https://api.github.com/repos/octocat/Hello-World/commits/6dcb09b5b57875f334f61aebed695e2e4193db5e/comments", "commit": { "url": "https://api.github.com/repos/octocat/Hello-World/git/commits/6dcb09b5b57875f334f61aebed695e2e4193db5e", "author": { "name": "Monalisa Octocat", "email": "mona@github.com", "date": "2011-04-14T16:00:49Z" }, "committer": { "name": "Monalisa Octocat", "email": "mona@github.com", "date": "2011-04-14T16:00:49Z" }, "message": "Fix all the bugs", "tree": { "url": "https://api.github.com/repos/octocat/Hello-World/tree/6dcb09b5b57875f334f61aebed695e2e4193db5e", "sha": "6dcb09b5b57875f334f61aebed695e2e4193db5e" }, "comment_count": 0, "verification": { "verified": false, "reason": "unsigned", "signature": null, "payload": null } }, "author": { "login": "octocat", "id": 1, "node_id": "MDQ6VXNlcjE=", "avatar_url": "https://github.com/images/error/octocat_happy.gif", "gravatar_id": "", "url": "https://api.github.com/users/octocat", "html_url": "https://github.com/octocat", "followers_url": "https://api.github.com/users/octocat/followers", "following_url": "https://api.github.com/users/octocat/following{/other_user}", "gists_url": "https://api.github.com/users/octocat/gists{/gist_id}", "starred_url": "https://api.github.com/users/octocat/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/octocat/subscriptions", "organizations_url": "https://api.github.com/users/octocat/orgs", "repos_url": "https://api.github.com/users/octocat/repos", "events_url": "https://api.github.com/users/octocat/events{/privacy}", "received_events_url": "https://api.github.com/users/octocat/received_events", "type": "User", "site_admin": false }, "committer": { "login": "octocat", "id": 1, "node_id": "MDQ6VXNlcjE=", "avatar_url": "https://github.com/images/error/octocat_happy.gif", "gravatar_id": "", "url": "https://api.github.com/users/octocat", "html_url": "https://github.com/octocat", "followers_url": "https://api.github.com/users/octocat/followers", "following_url": "https://api.github.com/users/octocat/following{/other_user}", "gists_url": "https://api.github.com/users/octocat/gists{/gist_id}", "starred_url": "https://api.github.com/users/octocat/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/octocat/subscriptions", "organizations_url": "https://api.github.com/users/octocat/orgs", "repos_url": "https://api.github.com/users/octocat/repos", "events_url": "https://api.github.com/users/octocat/events{/privacy}", "received_events_url": "https://api.github.com/users/octocat/received_events", "type": "User", "site_admin": false }, "parents": [ { "url": "https://api.github.com/repos/octocat/Hello-World/commits/6dcb09b5b57875f334f61aebed695e2e4193db5e", "sha": "6dcb09b5b57875f334f61aebed695e2e4193db5e" } ], "stats": { "additions": 104, "deletions": 4, "total": 108 }, "files": [ { "filename": "file1.txt", "additions": 10, "deletions": 2, "changes": 12, "status": "modified", "raw_url": "https://github.com/octocat/Hello-World/raw/7ca483543807a51b6079e54ac4cc392bc29ae284/file1.txt", "blob_url": "https://github.com/octocat/Hello-World/blob/7ca483543807a51b6079e54ac4cc392bc29ae284/file1.txt", "patch": "@@ -29,7 +29,7 @@\n....." } ] } }, "check-suite-paginated": { "value": { "total_count": 1, "check_suites": [ { "id": 5, "node_id": "MDEwOkNoZWNrU3VpdGU1", "head_branch": "master", "head_sha": "d6fde92930d4715a2b49857d24b940956b26d2d3", "status": "completed", "conclusion": "neutral", "url": "https://api.github.com/repos/github/hello-world/check-suites/5", "before": "146e867f55c26428e5f9fade55a9bbf5e95a7912", "after": "d6fde92930d4715a2b49857d24b940956b26d2d3", "pull_requests": [ ], "app": { "id": 1, "slug": "octoapp", "node_id": "MDExOkludGVncmF0aW9uMQ==", "owner": { "login": "github", "id": 1, "node_id": "MDEyOk9yZ2FuaXphdGlvbjE=", "url": "https://api.github.com/orgs/github", "repos_url": "https://api.github.com/orgs/github/repos", "events_url": "https://api.github.com/orgs/github/events", "avatar_url": "https://github.com/images/error/octocat_happy.gif", "gravatar_id": "", "html_url": "https://github.com/octocat", "followers_url": "https://api.github.com/users/octocat/followers", "following_url": "https://api.github.com/users/octocat/following{/other_user}", "gists_url": "https://api.github.com/users/octocat/gists{/gist_id}", "starred_url": "https://api.github.com/users/octocat/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/octocat/subscriptions", "organizations_url": "https://api.github.com/users/octocat/orgs", "received_events_url": "https://api.github.com/users/octocat/received_events", "type": "User", "site_admin": true }, "name": "Octocat App", "description": "", "external_url": "https://example.com", "html_url": "https://github.com/apps/octoapp", "created_at": "2017-07-08T16:18:44-04:00", "updated_at": "2017-07-08T16:18:44-04:00", "permissions": { "metadata": "read", "contents": "read", "issues": "write", "single_file": "write" }, "events": [ "push", "pull_request" ] }, "repository": { "id": 1296269, "node_id": "MDEwOlJlcG9zaXRvcnkxMjk2MjY5", "name": "Hello-World", "full_name": "octocat/Hello-World", "owner": { "login": "octocat", "id": 1, "node_id": "MDQ6VXNlcjE=", "avatar_url": "https://github.com/images/error/octocat_happy.gif", "gravatar_id": "", "url": "https://api.github.com/users/octocat", "html_url": "https://github.com/octocat", "followers_url": "https://api.github.com/users/octocat/followers", "following_url": "https://api.github.com/users/octocat/following{/other_user}", "gists_url": "https://api.github.com/users/octocat/gists{/gist_id}", "starred_url": "https://api.github.com/users/octocat/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/octocat/subscriptions", "organizations_url": "https://api.github.com/users/octocat/orgs", "repos_url": "https://api.github.com/users/octocat/repos", "events_url": "https://api.github.com/users/octocat/events{/privacy}", "received_events_url": "https://api.github.com/users/octocat/received_events", "type": "User", "site_admin": false }, "private": false, "html_url": "https://github.com/octocat/Hello-World", "description": "This your first repo!", "fork": false, "url": "https://api.github.com/repos/octocat/Hello-World", "archive_url": "https://api.github.com/repos/octocat/Hello-World/{archive_format}{/ref}", "assignees_url": "https://api.github.com/repos/octocat/Hello-World/assignees{/user}", "blobs_url": "https://api.github.com/repos/octocat/Hello-World/git/blobs{/sha}", "branches_url": "https://api.github.com/repos/octocat/Hello-World/branches{/branch}", "collaborators_url": "https://api.github.com/repos/octocat/Hello-World/collaborators{/collaborator}", "comments_url": "https://api.github.com/repos/octocat/Hello-World/comments{/number}", "commits_url": "https://api.github.com/repos/octocat/Hello-World/commits{/sha}", "compare_url": "https://api.github.com/repos/octocat/Hello-World/compare/{base}...{head}", "contents_url": "https://api.github.com/repos/octocat/Hello-World/contents/{+path}", "contributors_url": "https://api.github.com/repos/octocat/Hello-World/contributors", "deployments_url": "https://api.github.com/repos/octocat/Hello-World/deployments", "downloads_url": "https://api.github.com/repos/octocat/Hello-World/downloads", "events_url": "https://api.github.com/repos/octocat/Hello-World/events", "forks_url": "https://api.github.com/repos/octocat/Hello-World/forks", "git_commits_url": "https://api.github.com/repos/octocat/Hello-World/git/commits{/sha}", "git_refs_url": "https://api.github.com/repos/octocat/Hello-World/git/refs{/sha}", "git_tags_url": "https://api.github.com/repos/octocat/Hello-World/git/tags{/sha}", "git_url": "git:github.com/octocat/Hello-World.git", "issue_comment_url": "https://api.github.com/repos/octocat/Hello-World/issues/comments{/number}", "issue_events_url": "https://api.github.com/repos/octocat/Hello-World/issues/events{/number}", "issues_url": "https://api.github.com/repos/octocat/Hello-World/issues{/number}", "keys_url": "https://api.github.com/repos/octocat/Hello-World/keys{/key_id}", "labels_url": "https://api.github.com/repos/octocat/Hello-World/labels{/name}", "languages_url": "https://api.github.com/repos/octocat/Hello-World/languages", "merges_url": "https://api.github.com/repos/octocat/Hello-World/merges", "milestones_url": "https://api.github.com/repos/octocat/Hello-World/milestones{/number}", "notifications_url": "https://api.github.com/repos/octocat/Hello-World/notifications{?since,all,participating}", "pulls_url": "https://api.github.com/repos/octocat/Hello-World/pulls{/number}", "releases_url": "https://api.github.com/repos/octocat/Hello-World/releases{/id}", "ssh_url": "git@github.com:octocat/Hello-World.git", "stargazers_url": "https://api.github.com/repos/octocat/Hello-World/stargazers", "statuses_url": "https://api.github.com/repos/octocat/Hello-World/statuses/{sha}", "subscribers_url": "https://api.github.com/repos/octocat/Hello-World/subscribers", "subscription_url": "https://api.github.com/repos/octocat/Hello-World/subscription", "tags_url": "https://api.github.com/repos/octocat/Hello-World/tags", "teams_url": "https://api.github.com/repos/octocat/Hello-World/teams", "trees_url": "https://api.github.com/repos/octocat/Hello-World/git/trees{/sha}", "clone_url": "https://github.com/octocat/Hello-World.git", "mirror_url": "git:git.example.com/octocat/Hello-World", "hooks_url": "https://api.github.com/repos/octocat/Hello-World/hooks", "svn_url": "https://svn.github.com/octocat/Hello-World", "homepage": "https://github.com", "language": null, "forks_count": 9, "stargazers_count": 80, "watchers_count": 80, "size": 108, "default_branch": "master", "open_issues_count": 0, "is_template": true, "topics": [ "octocat", "atom", "electron", "api" ], "has_issues": true, "has_projects": true, "has_wiki": true, "has_pages": false, "has_downloads": true, "archived": false, "disabled": false, "visibility": "public", "pushed_at": "2011-01-26T19:06:43Z", "created_at": "2011-01-26T19:01:12Z", "updated_at": "2011-01-26T19:14:43Z", "permissions": { "admin": false, "push": false, "pull": true }, "temp_clone_token": "ABTLWHOULUVAXGTRYU7OC2876QJ2O", "delete_branch_on_merge": true, "subscribers_count": 42, "network_count": 0 }, "created_at": "2011-01-26T19:01:12Z", "updated_at": "2011-01-26T19:14:43Z", "head_commit": { "id": "7fd1a60b01f91b314f59955a4e4d4e80d8edf11d", "tree_id": "7fd1a60b01f91b314f59955a4e4d4e80d8edf11d", "message": "Merge pull request #6 from Spaceghost/patch-1\n\nNew line at end of file.", "timestamp": "2016-10-10T00:00:00Z", "author": { "name": "The Octocat", "email": "octocat@nowhere.com" }, "committer": { "name": "The Octocat", "email": "octocat@nowhere.com" } }, "latest_check_runs_count": 1, "check_runs_url": "https://api.github.com/repos/octocat/Hello-World/check-suites/5/check-runs" } ] } }, "combined-commit-status": { "value": { "state": "success", "statuses": [ { "url": "https://api.github.com/repos/octocat/Hello-World/statuses/6dcb09b5b57875f334f61aebed695e2e4193db5e", "avatar_url": "https://github.com/images/error/hubot_happy.gif", "id": 1, "node_id": "MDY6U3RhdHVzMQ==", "state": "success", "description": "Build has completed successfully", "target_url": "https://ci.example.com/1000/output", "context": "continuous-integration/jenkins", "created_at": "2012-07-20T01:19:13Z", "updated_at": "2012-07-20T01:19:13Z" }, { "url": "https://api.github.com/repos/octocat/Hello-World/statuses/6dcb09b5b57875f334f61aebed695e2e4193db5e", "avatar_url": "https://github.com/images/error/other_user_happy.gif", "id": 2, "node_id": "MDY6U3RhdHVzMg==", "state": "success", "description": "Testing has completed successfully", "target_url": "https://ci.example.com/2000/output", "context": "security/brakeman", "created_at": "2012-08-20T01:19:13Z", "updated_at": "2012-08-20T01:19:13Z" } ], "sha": "6dcb09b5b57875f334f61aebed695e2e4193db5e", "total_count": 2, "repository": { "id": 1296269, "node_id": "MDEwOlJlcG9zaXRvcnkxMjk2MjY5", "name": "Hello-World", "full_name": "octocat/Hello-World", "owner": { "login": "octocat", "id": 1, "node_id": "MDQ6VXNlcjE=", "avatar_url": "https://github.com/images/error/octocat_happy.gif", "gravatar_id": "", "url": "https://api.github.com/users/octocat", "html_url": "https://github.com/octocat", "followers_url": "https://api.github.com/users/octocat/followers", "following_url": "https://api.github.com/users/octocat/following{/other_user}", "gists_url": "https://api.github.com/users/octocat/gists{/gist_id}", "starred_url": "https://api.github.com/users/octocat/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/octocat/subscriptions", "organizations_url": "https://api.github.com/users/octocat/orgs", "repos_url": "https://api.github.com/users/octocat/repos", "events_url": "https://api.github.com/users/octocat/events{/privacy}", "received_events_url": "https://api.github.com/users/octocat/received_events", "type": "User", "site_admin": false }, "private": false, "html_url": "https://github.com/octocat/Hello-World", "description": "This your first repo!", "fork": false, "url": "https://api.github.com/repos/octocat/Hello-World", "archive_url": "https://api.github.com/repos/octocat/Hello-World/{archive_format}{/ref}", "assignees_url": "https://api.github.com/repos/octocat/Hello-World/assignees{/user}", "blobs_url": "https://api.github.com/repos/octocat/Hello-World/git/blobs{/sha}", "branches_url": "https://api.github.com/repos/octocat/Hello-World/branches{/branch}", "collaborators_url": "https://api.github.com/repos/octocat/Hello-World/collaborators{/collaborator}", "comments_url": "https://api.github.com/repos/octocat/Hello-World/comments{/number}", "commits_url": "https://api.github.com/repos/octocat/Hello-World/commits{/sha}", "compare_url": "https://api.github.com/repos/octocat/Hello-World/compare/{base}...{head}", "contents_url": "https://api.github.com/repos/octocat/Hello-World/contents/{+path}", "contributors_url": "https://api.github.com/repos/octocat/Hello-World/contributors", "deployments_url": "https://api.github.com/repos/octocat/Hello-World/deployments", "downloads_url": "https://api.github.com/repos/octocat/Hello-World/downloads", "events_url": "https://api.github.com/repos/octocat/Hello-World/events", "forks_url": "https://api.github.com/repos/octocat/Hello-World/forks", "git_commits_url": "https://api.github.com/repos/octocat/Hello-World/git/commits{/sha}", "git_refs_url": "https://api.github.com/repos/octocat/Hello-World/git/refs{/sha}", "git_tags_url": "https://api.github.com/repos/octocat/Hello-World/git/tags{/sha}", "git_url": "git:github.com/octocat/Hello-World.git", "issue_comment_url": "https://api.github.com/repos/octocat/Hello-World/issues/comments{/number}", "issue_events_url": "https://api.github.com/repos/octocat/Hello-World/issues/events{/number}", "issues_url": "https://api.github.com/repos/octocat/Hello-World/issues{/number}", "keys_url": "https://api.github.com/repos/octocat/Hello-World/keys{/key_id}", "labels_url": "https://api.github.com/repos/octocat/Hello-World/labels{/name}", "languages_url": "https://api.github.com/repos/octocat/Hello-World/languages", "merges_url": "https://api.github.com/repos/octocat/Hello-World/merges", "milestones_url": "https://api.github.com/repos/octocat/Hello-World/milestones{/number}", "notifications_url": "https://api.github.com/repos/octocat/Hello-World/notifications{?since,all,participating}", "pulls_url": "https://api.github.com/repos/octocat/Hello-World/pulls{/number}", "releases_url": "https://api.github.com/repos/octocat/Hello-World/releases{/id}", "ssh_url": "git@github.com:octocat/Hello-World.git", "stargazers_url": "https://api.github.com/repos/octocat/Hello-World/stargazers", "statuses_url": "https://api.github.com/repos/octocat/Hello-World/statuses/{sha}", "subscribers_url": "https://api.github.com/repos/octocat/Hello-World/subscribers", "subscription_url": "https://api.github.com/repos/octocat/Hello-World/subscription", "tags_url": "https://api.github.com/repos/octocat/Hello-World/tags", "teams_url": "https://api.github.com/repos/octocat/Hello-World/teams", "trees_url": "https://api.github.com/repos/octocat/Hello-World/git/trees{/sha}", "hooks_url": "http://api.github.com/repos/octocat/Hello-World/hooks" }, "commit_url": "https://api.github.com/repos/octocat/Hello-World/6dcb09b5b57875f334f61aebed695e2e4193db5e", "url": "https://api.github.com/repos/octocat/Hello-World/6dcb09b5b57875f334f61aebed695e2e4193db5e/status" } }, "status-items": { "value": [ { "url": "https://api.github.com/repos/octocat/Hello-World/statuses/6dcb09b5b57875f334f61aebed695e2e4193db5e", "avatar_url": "https://github.com/images/error/hubot_happy.gif", "id": 1, "node_id": "MDY6U3RhdHVzMQ==", "state": "success", "description": "Build has completed successfully", "target_url": "https://ci.example.com/1000/output", "context": "continuous-integration/jenkins", "created_at": "2012-07-20T01:19:13Z", "updated_at": "2012-07-20T01:19:13Z", "creator": { "login": "octocat", "id": 1, "node_id": "MDQ6VXNlcjE=", "avatar_url": "https://github.com/images/error/octocat_happy.gif", "gravatar_id": "", "url": "https://api.github.com/users/octocat", "html_url": "https://github.com/octocat", "followers_url": "https://api.github.com/users/octocat/followers", "following_url": "https://api.github.com/users/octocat/following{/other_user}", "gists_url": "https://api.github.com/users/octocat/gists{/gist_id}", "starred_url": "https://api.github.com/users/octocat/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/octocat/subscriptions", "organizations_url": "https://api.github.com/users/octocat/orgs", "repos_url": "https://api.github.com/users/octocat/repos", "events_url": "https://api.github.com/users/octocat/events{/privacy}", "received_events_url": "https://api.github.com/users/octocat/received_events", "type": "User", "site_admin": false } } ] }, "commit-comparison": { "value": { "url": "https://api.github.com/repos/octocat/Hello-World/compare/master...topic", "html_url": "https://github.com/octocat/Hello-World/compare/master...topic", "permalink_url": "https://github.com/octocat/Hello-World/compare/octocat:bbcd538c8e72b8c175046e27cc8f907076331401...octocat:0328041d1152db8ae77652d1618a02e57f745f17", "diff_url": "https://github.com/octocat/Hello-World/compare/master...topic.diff", "patch_url": "https://github.com/octocat/Hello-World/compare/master...topic.patch", "base_commit": { "url": "https://api.github.com/repos/octocat/Hello-World/commits/6dcb09b5b57875f334f61aebed695e2e4193db5e", "sha": "6dcb09b5b57875f334f61aebed695e2e4193db5e", "node_id": "MDY6Q29tbWl0NmRjYjA5YjViNTc4NzVmMzM0ZjYxYWViZWQ2OTVlMmU0MTkzZGI1ZQ==", "html_url": "https://github.com/octocat/Hello-World/commit/6dcb09b5b57875f334f61aebed695e2e4193db5e", "comments_url": "https://api.github.com/repos/octocat/Hello-World/commits/6dcb09b5b57875f334f61aebed695e2e4193db5e/comments", "commit": { "url": "https://api.github.com/repos/octocat/Hello-World/git/commits/6dcb09b5b57875f334f61aebed695e2e4193db5e", "author": { "name": "Monalisa Octocat", "email": "mona@github.com", "date": "2011-04-14T16:00:49Z" }, "committer": { "name": "Monalisa Octocat", "email": "mona@github.com", "date": "2011-04-14T16:00:49Z" }, "message": "Fix all the bugs", "tree": { "url": "https://api.github.com/repos/octocat/Hello-World/tree/6dcb09b5b57875f334f61aebed695e2e4193db5e", "sha": "6dcb09b5b57875f334f61aebed695e2e4193db5e" }, "comment_count": 0, "verification": { "verified": false, "reason": "unsigned", "signature": null, "payload": null } }, "author": { "login": "octocat", "id": 1, "node_id": "MDQ6VXNlcjE=", "avatar_url": "https://github.com/images/error/octocat_happy.gif", "gravatar_id": "", "url": "https://api.github.com/users/octocat", "html_url": "https://github.com/octocat", "followers_url": "https://api.github.com/users/octocat/followers", "following_url": "https://api.github.com/users/octocat/following{/other_user}", "gists_url": "https://api.github.com/users/octocat/gists{/gist_id}", "starred_url": "https://api.github.com/users/octocat/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/octocat/subscriptions", "organizations_url": "https://api.github.com/users/octocat/orgs", "repos_url": "https://api.github.com/users/octocat/repos", "events_url": "https://api.github.com/users/octocat/events{/privacy}", "received_events_url": "https://api.github.com/users/octocat/received_events", "type": "User", "site_admin": false }, "committer": { "login": "octocat", "id": 1, "node_id": "MDQ6VXNlcjE=", "avatar_url": "https://github.com/images/error/octocat_happy.gif", "gravatar_id": "", "url": "https://api.github.com/users/octocat", "html_url": "https://github.com/octocat", "followers_url": "https://api.github.com/users/octocat/followers", "following_url": "https://api.github.com/users/octocat/following{/other_user}", "gists_url": "https://api.github.com/users/octocat/gists{/gist_id}", "starred_url": "https://api.github.com/users/octocat/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/octocat/subscriptions", "organizations_url": "https://api.github.com/users/octocat/orgs", "repos_url": "https://api.github.com/users/octocat/repos", "events_url": "https://api.github.com/users/octocat/events{/privacy}", "received_events_url": "https://api.github.com/users/octocat/received_events", "type": "User", "site_admin": false }, "parents": [ { "url": "https://api.github.com/repos/octocat/Hello-World/commits/6dcb09b5b57875f334f61aebed695e2e4193db5e", "sha": "6dcb09b5b57875f334f61aebed695e2e4193db5e" } ] }, "merge_base_commit": { "url": "https://api.github.com/repos/octocat/Hello-World/commits/6dcb09b5b57875f334f61aebed695e2e4193db5e", "sha": "6dcb09b5b57875f334f61aebed695e2e4193db5e", "node_id": "MDY6Q29tbWl0NmRjYjA5YjViNTc4NzVmMzM0ZjYxYWViZWQ2OTVlMmU0MTkzZGI1ZQ==", "html_url": "https://github.com/octocat/Hello-World/commit/6dcb09b5b57875f334f61aebed695e2e4193db5e", "comments_url": "https://api.github.com/repos/octocat/Hello-World/commits/6dcb09b5b57875f334f61aebed695e2e4193db5e/comments", "commit": { "url": "https://api.github.com/repos/octocat/Hello-World/git/commits/6dcb09b5b57875f334f61aebed695e2e4193db5e", "author": { "name": "Monalisa Octocat", "email": "mona@github.com", "date": "2011-04-14T16:00:49Z" }, "committer": { "name": "Monalisa Octocat", "email": "mona@github.com", "date": "2011-04-14T16:00:49Z" }, "message": "Fix all the bugs", "tree": { "url": "https://api.github.com/repos/octocat/Hello-World/tree/6dcb09b5b57875f334f61aebed695e2e4193db5e", "sha": "6dcb09b5b57875f334f61aebed695e2e4193db5e" }, "comment_count": 0, "verification": { "verified": false, "reason": "unsigned", "signature": null, "payload": null } }, "author": { "login": "octocat", "id": 1, "node_id": "MDQ6VXNlcjE=", "avatar_url": "https://github.com/images/error/octocat_happy.gif", "gravatar_id": "", "url": "https://api.github.com/users/octocat", "html_url": "https://github.com/octocat", "followers_url": "https://api.github.com/users/octocat/followers", "following_url": "https://api.github.com/users/octocat/following{/other_user}", "gists_url": "https://api.github.com/users/octocat/gists{/gist_id}", "starred_url": "https://api.github.com/users/octocat/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/octocat/subscriptions", "organizations_url": "https://api.github.com/users/octocat/orgs", "repos_url": "https://api.github.com/users/octocat/repos", "events_url": "https://api.github.com/users/octocat/events{/privacy}", "received_events_url": "https://api.github.com/users/octocat/received_events", "type": "User", "site_admin": false }, "committer": { "login": "octocat", "id": 1, "node_id": "MDQ6VXNlcjE=", "avatar_url": "https://github.com/images/error/octocat_happy.gif", "gravatar_id": "", "url": "https://api.github.com/users/octocat", "html_url": "https://github.com/octocat", "followers_url": "https://api.github.com/users/octocat/followers", "following_url": "https://api.github.com/users/octocat/following{/other_user}", "gists_url": "https://api.github.com/users/octocat/gists{/gist_id}", "starred_url": "https://api.github.com/users/octocat/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/octocat/subscriptions", "organizations_url": "https://api.github.com/users/octocat/orgs", "repos_url": "https://api.github.com/users/octocat/repos", "events_url": "https://api.github.com/users/octocat/events{/privacy}", "received_events_url": "https://api.github.com/users/octocat/received_events", "type": "User", "site_admin": false }, "parents": [ { "url": "https://api.github.com/repos/octocat/Hello-World/commits/6dcb09b5b57875f334f61aebed695e2e4193db5e", "sha": "6dcb09b5b57875f334f61aebed695e2e4193db5e" } ] }, "status": "behind", "ahead_by": 1, "behind_by": 2, "total_commits": 1, "commits": [ { "url": "https://api.github.com/repos/octocat/Hello-World/commits/6dcb09b5b57875f334f61aebed695e2e4193db5e", "sha": "6dcb09b5b57875f334f61aebed695e2e4193db5e", "node_id": "MDY6Q29tbWl0NmRjYjA5YjViNTc4NzVmMzM0ZjYxYWViZWQ2OTVlMmU0MTkzZGI1ZQ==", "html_url": "https://github.com/octocat/Hello-World/commit/6dcb09b5b57875f334f61aebed695e2e4193db5e", "comments_url": "https://api.github.com/repos/octocat/Hello-World/commits/6dcb09b5b57875f334f61aebed695e2e4193db5e/comments", "commit": { "url": "https://api.github.com/repos/octocat/Hello-World/git/commits/6dcb09b5b57875f334f61aebed695e2e4193db5e", "author": { "name": "Monalisa Octocat", "email": "mona@github.com", "date": "2011-04-14T16:00:49Z" }, "committer": { "name": "Monalisa Octocat", "email": "mona@github.com", "date": "2011-04-14T16:00:49Z" }, "message": "Fix all the bugs", "tree": { "url": "https://api.github.com/repos/octocat/Hello-World/tree/6dcb09b5b57875f334f61aebed695e2e4193db5e", "sha": "6dcb09b5b57875f334f61aebed695e2e4193db5e" }, "comment_count": 0, "verification": { "verified": false, "reason": "unsigned", "signature": null, "payload": null } }, "author": { "login": "octocat", "id": 1, "node_id": "MDQ6VXNlcjE=", "avatar_url": "https://github.com/images/error/octocat_happy.gif", "gravatar_id": "", "url": "https://api.github.com/users/octocat", "html_url": "https://github.com/octocat", "followers_url": "https://api.github.com/users/octocat/followers", "following_url": "https://api.github.com/users/octocat/following{/other_user}", "gists_url": "https://api.github.com/users/octocat/gists{/gist_id}", "starred_url": "https://api.github.com/users/octocat/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/octocat/subscriptions", "organizations_url": "https://api.github.com/users/octocat/orgs", "repos_url": "https://api.github.com/users/octocat/repos", "events_url": "https://api.github.com/users/octocat/events{/privacy}", "received_events_url": "https://api.github.com/users/octocat/received_events", "type": "User", "site_admin": false }, "committer": { "login": "octocat", "id": 1, "node_id": "MDQ6VXNlcjE=", "avatar_url": "https://github.com/images/error/octocat_happy.gif", "gravatar_id": "", "url": "https://api.github.com/users/octocat", "html_url": "https://github.com/octocat", "followers_url": "https://api.github.com/users/octocat/followers", "following_url": "https://api.github.com/users/octocat/following{/other_user}", "gists_url": "https://api.github.com/users/octocat/gists{/gist_id}", "starred_url": "https://api.github.com/users/octocat/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/octocat/subscriptions", "organizations_url": "https://api.github.com/users/octocat/orgs", "repos_url": "https://api.github.com/users/octocat/repos", "events_url": "https://api.github.com/users/octocat/events{/privacy}", "received_events_url": "https://api.github.com/users/octocat/received_events", "type": "User", "site_admin": false }, "parents": [ { "url": "https://api.github.com/repos/octocat/Hello-World/commits/6dcb09b5b57875f334f61aebed695e2e4193db5e", "sha": "6dcb09b5b57875f334f61aebed695e2e4193db5e" } ] } ], "files": [ { "sha": "bbcd538c8e72b8c175046e27cc8f907076331401", "filename": "file1.txt", "status": "added", "additions": 103, "deletions": 21, "changes": 124, "blob_url": "https://github.com/octocat/Hello-World/blob/6dcb09b5b57875f334f61aebed695e2e4193db5e/file1.txt", "raw_url": "https://github.com/octocat/Hello-World/raw/6dcb09b5b57875f334f61aebed695e2e4193db5e/file1.txt", "contents_url": "https://api.github.com/repos/octocat/Hello-World/contents/file1.txt?ref=6dcb09b5b57875f334f61aebed695e2e4193db5e", "patch": "@@ -132,7 +132,7 @@ module Test @@ -1000,7 +1000,7 @@ module Test" } ] } }, "content-reference-attachment": { "value": { "id": 101, "title": "[A-1234] Error found in core/models.py file'", "body": "You have used an email that already exists for the user_email_uniq field.\n ## DETAILS:\n\nThe (email)=(Octocat@github.com) already exists.\n\n The error was found in core/models.py in get_or_create_user at line 62.\n\n self.save()" } }, "content-file-response-if-content-is-a-file": { "summary": "Response if content is a file", "value": { "type": "file", "encoding": "base64", "size": 5362, "name": "README.md", "path": "README.md", "content": "encoded content ...", "sha": "3d21ec53a331a6f037a91c368710b99387d012c1", "url": "https://api.github.com/repos/octokit/octokit.rb/contents/README.md", "git_url": "https://api.github.com/repos/octokit/octokit.rb/git/blobs/3d21ec53a331a6f037a91c368710b99387d012c1", "html_url": "https://github.com/octokit/octokit.rb/blob/master/README.md", "download_url": "https://raw.githubusercontent.com/octokit/octokit.rb/master/README.md", "_links": { "git": "https://api.github.com/repos/octokit/octokit.rb/git/blobs/3d21ec53a331a6f037a91c368710b99387d012c1", "self": "https://api.github.com/repos/octokit/octokit.rb/contents/README.md", "html": "https://github.com/octokit/octokit.rb/blob/master/README.md" } } }, "content-file-response-if-content-is-a-directory": { "summary": "Response if content is a directory", "value": [ { "type": "file", "size": 625, "name": "octokit.rb", "path": "lib/octokit.rb", "sha": "fff6fe3a23bf1c8ea0692b4a883af99bee26fd3b", "url": "https://api.github.com/repos/octokit/octokit.rb/contents/lib/octokit.rb", "git_url": "https://api.github.com/repos/octokit/octokit.rb/git/blobs/fff6fe3a23bf1c8ea0692b4a883af99bee26fd3b", "html_url": "https://github.com/octokit/octokit.rb/blob/master/lib/octokit.rb", "download_url": "https://raw.githubusercontent.com/octokit/octokit.rb/master/lib/octokit.rb", "_links": { "self": "https://api.github.com/repos/octokit/octokit.rb/contents/lib/octokit.rb", "git": "https://api.github.com/repos/octokit/octokit.rb/git/blobs/fff6fe3a23bf1c8ea0692b4a883af99bee26fd3b", "html": "https://github.com/octokit/octokit.rb/blob/master/lib/octokit.rb" } }, { "type": "dir", "size": 0, "name": "octokit", "path": "lib/octokit", "sha": "a84d88e7554fc1fa21bcbc4efae3c782a70d2b9d", "url": "https://api.github.com/repos/octokit/octokit.rb/contents/lib/octokit", "git_url": "https://api.github.com/repos/octokit/octokit.rb/git/trees/a84d88e7554fc1fa21bcbc4efae3c782a70d2b9d", "html_url": "https://github.com/octokit/octokit.rb/tree/master/lib/octokit", "download_url": null, "_links": { "self": "https://api.github.com/repos/octokit/octokit.rb/contents/lib/octokit", "git": "https://api.github.com/repos/octokit/octokit.rb/git/trees/a84d88e7554fc1fa21bcbc4efae3c782a70d2b9d", "html": "https://github.com/octokit/octokit.rb/tree/master/lib/octokit" } } ] }, "content-file-response-if-content-is-a-symlink": { "summary": "Response if content is a symlink", "value": { "type": "symlink", "target": "/path/to/symlink/target", "size": 23, "name": "some-symlink", "path": "bin/some-symlink", "sha": "452a98979c88e093d682cab404a3ec82babebb48", "url": "https://api.github.com/repos/octokit/octokit.rb/contents/bin/some-symlink", "git_url": "https://api.github.com/repos/octokit/octokit.rb/git/blobs/452a98979c88e093d682cab404a3ec82babebb48", "html_url": "https://github.com/octokit/octokit.rb/blob/master/bin/some-symlink", "download_url": "https://raw.githubusercontent.com/octokit/octokit.rb/master/bin/some-symlink", "_links": { "git": "https://api.github.com/repos/octokit/octokit.rb/git/blobs/452a98979c88e093d682cab404a3ec82babebb48", "self": "https://api.github.com/repos/octokit/octokit.rb/contents/bin/some-symlink", "html": "https://github.com/octokit/octokit.rb/blob/master/bin/some-symlink" } } }, "content-file-response-if-content-is-a-submodule": { "summary": "Response if content is a submodule", "value": { "type": "submodule", "submodule_git_url": "git://github.com/jquery/qunit.git", "size": 0, "name": "qunit", "path": "test/qunit", "sha": "6ca3721222109997540bd6d9ccd396902e0ad2f9", "url": "https://api.github.com/repos/jquery/jquery/contents/test/qunit?ref=master", "git_url": "https://api.github.com/repos/jquery/qunit/git/trees/6ca3721222109997540bd6d9ccd396902e0ad2f9", "html_url": "https://github.com/jquery/qunit/tree/6ca3721222109997540bd6d9ccd396902e0ad2f9", "download_url": null, "_links": { "git": "https://api.github.com/repos/jquery/qunit/git/trees/6ca3721222109997540bd6d9ccd396902e0ad2f9", "self": "https://api.github.com/repos/jquery/jquery/contents/test/qunit?ref=master", "html": "https://github.com/jquery/qunit/tree/6ca3721222109997540bd6d9ccd396902e0ad2f9" } } }, "file-commit-example-for-updating-a-file": { "value": { "content": { "name": "hello.txt", "path": "notes/hello.txt", "sha": "a56507ed892d05a37c6d6128c260937ea4d287bd", "size": 9, "url": "https://api.github.com/repos/octocat/Hello-World/contents/notes/hello.txt", "html_url": "https://github.com/octocat/Hello-World/blob/master/notes/hello.txt", "git_url": "https://api.github.com/repos/octocat/Hello-World/git/blobs/a56507ed892d05a37c6d6128c260937ea4d287bd", "download_url": "https://raw.githubusercontent.com/octocat/HelloWorld/master/notes/hello.txt", "type": "file", "_links": { "self": "https://api.github.com/repos/octocat/Hello-World/contents/notes/hello.txt", "git": "https://api.github.com/repos/octocat/Hello-World/git/blobs/a56507ed892d05a37c6d6128c260937ea4d287bd", "html": "https://github.com/octocat/Hello-World/blob/master/notes/hello.txt" } }, "commit": { "sha": "18a43cd8e1e3a79c786e3d808a73d23b6d212b16", "node_id": "MDY6Q29tbWl0MThhNDNjZDhlMWUzYTc5Yzc4NmUzZDgwOGE3M2QyM2I2ZDIxMmIxNg==", "url": "https://api.github.com/repos/octocat/Hello-World/git/commits/18a43cd8e1e3a79c786e3d808a73d23b6d212b16", "html_url": "https://github.com/octocat/Hello-World/git/commit/18a43cd8e1e3a79c786e3d808a73d23b6d212b16", "author": { "date": "2014-11-07T22:01:45Z", "name": "Monalisa Octocat", "email": "octocat@github.com" }, "committer": { "date": "2014-11-07T22:01:45Z", "name": "Monalisa Octocat", "email": "octocat@github.com" }, "message": "my commit message", "tree": { "url": "https://api.github.com/repos/octocat/Hello-World/git/trees/9a21f8e2018f42ffcf369b24d2cd20bc25c9e66f", "sha": "9a21f8e2018f42ffcf369b24d2cd20bc25c9e66f" }, "parents": [ { "url": "https://api.github.com/repos/octocat/Hello-World/git/commits/da5a433788da5c255edad7979b328b67d79f53f6", "html_url": "https://github.com/octocat/Hello-World/git/commit/da5a433788da5c255edad7979b328b67d79f53f6", "sha": "da5a433788da5c255edad7979b328b67d79f53f6" } ], "verification": { "verified": false, "reason": "unsigned", "signature": null, "payload": null } } } }, "file-commit-example-for-creating-a-file": { "value": { "content": { "name": "hello.txt", "path": "notes/hello.txt", "sha": "95b966ae1c166bd92f8ae7d1c313e738c731dfc3", "size": 9, "url": "https://api.github.com/repos/octocat/Hello-World/contents/notes/hello.txt", "html_url": "https://github.com/octocat/Hello-World/blob/master/notes/hello.txt", "git_url": "https://api.github.com/repos/octocat/Hello-World/git/blobs/95b966ae1c166bd92f8ae7d1c313e738c731dfc3", "download_url": "https://raw.githubusercontent.com/octocat/HelloWorld/master/notes/hello.txt", "type": "file", "_links": { "self": "https://api.github.com/repos/octocat/Hello-World/contents/notes/hello.txt", "git": "https://api.github.com/repos/octocat/Hello-World/git/blobs/95b966ae1c166bd92f8ae7d1c313e738c731dfc3", "html": "https://github.com/octocat/Hello-World/blob/master/notes/hello.txt" } }, "commit": { "sha": "7638417db6d59f3c431d3e1f261cc637155684cd", "node_id": "MDY6Q29tbWl0NzYzODQxN2RiNmQ1OWYzYzQzMWQzZTFmMjYxY2M2MzcxNTU2ODRjZA==", "url": "https://api.github.com/repos/octocat/Hello-World/git/commits/7638417db6d59f3c431d3e1f261cc637155684cd", "html_url": "https://github.com/octocat/Hello-World/git/commit/7638417db6d59f3c431d3e1f261cc637155684cd", "author": { "date": "2014-11-07T22:01:45Z", "name": "Monalisa Octocat", "email": "octocat@github.com" }, "committer": { "date": "2014-11-07T22:01:45Z", "name": "Monalisa Octocat", "email": "octocat@github.com" }, "message": "my commit message", "tree": { "url": "https://api.github.com/repos/octocat/Hello-World/git/trees/691272480426f78a0138979dd3ce63b77f706feb", "sha": "691272480426f78a0138979dd3ce63b77f706feb" }, "parents": [ { "url": "https://api.github.com/repos/octocat/Hello-World/git/commits/1acc419d4d6a9ce985db7be48c6349a0475975b5", "html_url": "https://github.com/octocat/Hello-World/git/commit/1acc419d4d6a9ce985db7be48c6349a0475975b5", "sha": "1acc419d4d6a9ce985db7be48c6349a0475975b5" } ], "verification": { "verified": false, "reason": "unsigned", "signature": null, "payload": null } } } }, "file-commit": { "value": { "content": null, "commit": { "sha": "7638417db6d59f3c431d3e1f261cc637155684cd", "node_id": "MDY6Q29tbWl0NzYzODQxN2RiNmQ1OWYzYzQzMWQzZTFmMjYxY2M2MzcxNTU2ODRjZA==", "url": "https://api.github.com/repos/octocat/Hello-World/git/commits/7638417db6d59f3c431d3e1f261cc637155684cd", "html_url": "https://github.com/octocat/Hello-World/git/commit/7638417db6d59f3c431d3e1f261cc637155684cd", "author": { "date": "2014-11-07T22:01:45Z", "name": "Monalisa Octocat", "email": "octocat@github.com" }, "committer": { "date": "2014-11-07T22:01:45Z", "name": "Monalisa Octocat", "email": "octocat@github.com" }, "message": "my commit message", "tree": { "url": "https://api.github.com/repos/octocat/Hello-World/git/trees/691272480426f78a0138979dd3ce63b77f706feb", "sha": "691272480426f78a0138979dd3ce63b77f706feb" }, "parents": [ { "url": "https://api.github.com/repos/octocat/Hello-World/git/commits/1acc419d4d6a9ce985db7be48c6349a0475975b5", "html_url": "https://github.com/octocat/Hello-World/git/commit/1acc419d4d6a9ce985db7be48c6349a0475975b5", "sha": "1acc419d4d6a9ce985db7be48c6349a0475975b5" } ], "verification": { "verified": false, "reason": "unsigned", "signature": null, "payload": null } } } }, "contributor-items-response-if-repository-contains-content": { "value": [ { "login": "octocat", "id": 1, "node_id": "MDQ6VXNlcjE=", "avatar_url": "https://github.com/images/error/octocat_happy.gif", "gravatar_id": "", "url": "https://api.github.com/users/octocat", "html_url": "https://github.com/octocat", "followers_url": "https://api.github.com/users/octocat/followers", "following_url": "https://api.github.com/users/octocat/following{/other_user}", "gists_url": "https://api.github.com/users/octocat/gists{/gist_id}", "starred_url": "https://api.github.com/users/octocat/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/octocat/subscriptions", "organizations_url": "https://api.github.com/users/octocat/orgs", "repos_url": "https://api.github.com/users/octocat/repos", "events_url": "https://api.github.com/users/octocat/events{/privacy}", "received_events_url": "https://api.github.com/users/octocat/received_events", "type": "User", "site_admin": false, "contributions": 32 } ] }, "deployment-items": { "value": [ { "url": "https://api.github.com/repos/octocat/example/deployments/1", "id": 1, "node_id": "MDEwOkRlcGxveW1lbnQx", "sha": "a84d88e7554fc1fa21bcbc4efae3c782a70d2b9d", "ref": "topic-branch", "task": "deploy", "payload": { }, "original_environment": "staging", "environment": "production", "description": "Deploy request from hubot", "creator": { "login": "octocat", "id": 1, "node_id": "MDQ6VXNlcjE=", "avatar_url": "https://github.com/images/error/octocat_happy.gif", "gravatar_id": "", "url": "https://api.github.com/users/octocat", "html_url": "https://github.com/octocat", "followers_url": "https://api.github.com/users/octocat/followers", "following_url": "https://api.github.com/users/octocat/following{/other_user}", "gists_url": "https://api.github.com/users/octocat/gists{/gist_id}", "starred_url": "https://api.github.com/users/octocat/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/octocat/subscriptions", "organizations_url": "https://api.github.com/users/octocat/orgs", "repos_url": "https://api.github.com/users/octocat/repos", "events_url": "https://api.github.com/users/octocat/events{/privacy}", "received_events_url": "https://api.github.com/users/octocat/received_events", "type": "User", "site_admin": false }, "created_at": "2012-07-20T01:19:13Z", "updated_at": "2012-07-20T01:19:13Z", "statuses_url": "https://api.github.com/repos/octocat/example/deployments/1/statuses", "repository_url": "https://api.github.com/repos/octocat/example", "transient_environment": false, "production_environment": true } ] }, "deployment-simple-example": { "summary": "Simple example", "value": { "url": "https://api.github.com/repos/octocat/example/deployments/1", "id": 1, "node_id": "MDEwOkRlcGxveW1lbnQx", "sha": "a84d88e7554fc1fa21bcbc4efae3c782a70d2b9d", "ref": "topic-branch", "task": "deploy", "payload": { }, "original_environment": "staging", "environment": "production", "description": "Deploy request from hubot", "creator": { "login": "octocat", "id": 1, "node_id": "MDQ6VXNlcjE=", "avatar_url": "https://github.com/images/error/octocat_happy.gif", "gravatar_id": "", "url": "https://api.github.com/users/octocat", "html_url": "https://github.com/octocat", "followers_url": "https://api.github.com/users/octocat/followers", "following_url": "https://api.github.com/users/octocat/following{/other_user}", "gists_url": "https://api.github.com/users/octocat/gists{/gist_id}", "starred_url": "https://api.github.com/users/octocat/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/octocat/subscriptions", "organizations_url": "https://api.github.com/users/octocat/orgs", "repos_url": "https://api.github.com/users/octocat/repos", "events_url": "https://api.github.com/users/octocat/events{/privacy}", "received_events_url": "https://api.github.com/users/octocat/received_events", "type": "User", "site_admin": false }, "created_at": "2012-07-20T01:19:13Z", "updated_at": "2012-07-20T01:19:13Z", "statuses_url": "https://api.github.com/repos/octocat/example/deployments/1/statuses", "repository_url": "https://api.github.com/repos/octocat/example", "transient_environment": false, "production_environment": true } }, "deployment": { "value": { "url": "https://api.github.com/repos/octocat/example/deployments/1", "id": 1, "node_id": "MDEwOkRlcGxveW1lbnQx", "sha": "a84d88e7554fc1fa21bcbc4efae3c782a70d2b9d", "ref": "topic-branch", "task": "deploy", "payload": { }, "original_environment": "staging", "environment": "production", "description": "Deploy request from hubot", "creator": { "login": "octocat", "id": 1, "node_id": "MDQ6VXNlcjE=", "avatar_url": "https://github.com/images/error/octocat_happy.gif", "gravatar_id": "", "url": "https://api.github.com/users/octocat", "html_url": "https://github.com/octocat", "followers_url": "https://api.github.com/users/octocat/followers", "following_url": "https://api.github.com/users/octocat/following{/other_user}", "gists_url": "https://api.github.com/users/octocat/gists{/gist_id}", "starred_url": "https://api.github.com/users/octocat/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/octocat/subscriptions", "organizations_url": "https://api.github.com/users/octocat/orgs", "repos_url": "https://api.github.com/users/octocat/repos", "events_url": "https://api.github.com/users/octocat/events{/privacy}", "received_events_url": "https://api.github.com/users/octocat/received_events", "type": "User", "site_admin": false }, "created_at": "2012-07-20T01:19:13Z", "updated_at": "2012-07-20T01:19:13Z", "statuses_url": "https://api.github.com/repos/octocat/example/deployments/1/statuses", "repository_url": "https://api.github.com/repos/octocat/example", "transient_environment": false, "production_environment": true } }, "deployment-status-items": { "value": [ { "url": "https://api.github.com/repos/octocat/example/deployments/42/statuses/1", "id": 1, "node_id": "MDE2OkRlcGxveW1lbnRTdGF0dXMx", "state": "success", "creator": { "login": "octocat", "id": 1, "node_id": "MDQ6VXNlcjE=", "avatar_url": "https://github.com/images/error/octocat_happy.gif", "gravatar_id": "", "url": "https://api.github.com/users/octocat", "html_url": "https://github.com/octocat", "followers_url": "https://api.github.com/users/octocat/followers", "following_url": "https://api.github.com/users/octocat/following{/other_user}", "gists_url": "https://api.github.com/users/octocat/gists{/gist_id}", "starred_url": "https://api.github.com/users/octocat/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/octocat/subscriptions", "organizations_url": "https://api.github.com/users/octocat/orgs", "repos_url": "https://api.github.com/users/octocat/repos", "events_url": "https://api.github.com/users/octocat/events{/privacy}", "received_events_url": "https://api.github.com/users/octocat/received_events", "type": "User", "site_admin": false }, "description": "Deployment finished successfully.", "environment": "production", "target_url": "https://example.com/deployment/42/output", "created_at": "2012-07-20T01:19:13Z", "updated_at": "2012-07-20T01:19:13Z", "deployment_url": "https://api.github.com/repos/octocat/example/deployments/42", "repository_url": "https://api.github.com/repos/octocat/example", "environment_url": "https://test-branch.lab.acme.com", "log_url": "https://example.com/deployment/42/output" } ] }, "deployment-status": { "value": { "url": "https://api.github.com/repos/octocat/example/deployments/42/statuses/1", "id": 1, "node_id": "MDE2OkRlcGxveW1lbnRTdGF0dXMx", "state": "success", "creator": { "login": "octocat", "id": 1, "node_id": "MDQ6VXNlcjE=", "avatar_url": "https://github.com/images/error/octocat_happy.gif", "gravatar_id": "", "url": "https://api.github.com/users/octocat", "html_url": "https://github.com/octocat", "followers_url": "https://api.github.com/users/octocat/followers", "following_url": "https://api.github.com/users/octocat/following{/other_user}", "gists_url": "https://api.github.com/users/octocat/gists{/gist_id}", "starred_url": "https://api.github.com/users/octocat/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/octocat/subscriptions", "organizations_url": "https://api.github.com/users/octocat/orgs", "repos_url": "https://api.github.com/users/octocat/repos", "events_url": "https://api.github.com/users/octocat/events{/privacy}", "received_events_url": "https://api.github.com/users/octocat/received_events", "type": "User", "site_admin": false }, "description": "Deployment finished successfully.", "environment": "production", "target_url": "https://example.com/deployment/42/output", "created_at": "2012-07-20T01:19:13Z", "updated_at": "2012-07-20T01:19:13Z", "deployment_url": "https://api.github.com/repos/octocat/example/deployments/42", "repository_url": "https://api.github.com/repos/octocat/example", "environment_url": "https://test-branch.lab.acme.com", "log_url": "https://example.com/deployment/42/output" } }, "minimal-repository-items-2": { "value": [ { "id": 1296269, "node_id": "MDEwOlJlcG9zaXRvcnkxMjk2MjY5", "name": "Hello-World", "full_name": "octocat/Hello-World", "owner": { "login": "octocat", "id": 1, "node_id": "MDQ6VXNlcjE=", "avatar_url": "https://github.com/images/error/octocat_happy.gif", "gravatar_id": "", "url": "https://api.github.com/users/octocat", "html_url": "https://github.com/octocat", "followers_url": "https://api.github.com/users/octocat/followers", "following_url": "https://api.github.com/users/octocat/following{/other_user}", "gists_url": "https://api.github.com/users/octocat/gists{/gist_id}", "starred_url": "https://api.github.com/users/octocat/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/octocat/subscriptions", "organizations_url": "https://api.github.com/users/octocat/orgs", "repos_url": "https://api.github.com/users/octocat/repos", "events_url": "https://api.github.com/users/octocat/events{/privacy}", "received_events_url": "https://api.github.com/users/octocat/received_events", "type": "User", "site_admin": false }, "private": false, "html_url": "https://github.com/octocat/Hello-World", "description": "This your first repo!", "fork": true, "url": "https://api.github.com/repos/octocat/Hello-World", "archive_url": "https://api.github.com/repos/octocat/Hello-World/{archive_format}{/ref}", "assignees_url": "https://api.github.com/repos/octocat/Hello-World/assignees{/user}", "blobs_url": "https://api.github.com/repos/octocat/Hello-World/git/blobs{/sha}", "branches_url": "https://api.github.com/repos/octocat/Hello-World/branches{/branch}", "collaborators_url": "https://api.github.com/repos/octocat/Hello-World/collaborators{/collaborator}", "comments_url": "https://api.github.com/repos/octocat/Hello-World/comments{/number}", "commits_url": "https://api.github.com/repos/octocat/Hello-World/commits{/sha}", "compare_url": "https://api.github.com/repos/octocat/Hello-World/compare/{base}...{head}", "contents_url": "https://api.github.com/repos/octocat/Hello-World/contents/{+path}", "contributors_url": "https://api.github.com/repos/octocat/Hello-World/contributors", "deployments_url": "https://api.github.com/repos/octocat/Hello-World/deployments", "downloads_url": "https://api.github.com/repos/octocat/Hello-World/downloads", "events_url": "https://api.github.com/repos/octocat/Hello-World/events", "forks_url": "https://api.github.com/repos/octocat/Hello-World/forks", "git_commits_url": "https://api.github.com/repos/octocat/Hello-World/git/commits{/sha}", "git_refs_url": "https://api.github.com/repos/octocat/Hello-World/git/refs{/sha}", "git_tags_url": "https://api.github.com/repos/octocat/Hello-World/git/tags{/sha}", "git_url": "git:github.com/octocat/Hello-World.git", "issue_comment_url": "https://api.github.com/repos/octocat/Hello-World/issues/comments{/number}", "issue_events_url": "https://api.github.com/repos/octocat/Hello-World/issues/events{/number}", "issues_url": "https://api.github.com/repos/octocat/Hello-World/issues{/number}", "keys_url": "https://api.github.com/repos/octocat/Hello-World/keys{/key_id}", "labels_url": "https://api.github.com/repos/octocat/Hello-World/labels{/name}", "languages_url": "https://api.github.com/repos/octocat/Hello-World/languages", "merges_url": "https://api.github.com/repos/octocat/Hello-World/merges", "milestones_url": "https://api.github.com/repos/octocat/Hello-World/milestones{/number}", "notifications_url": "https://api.github.com/repos/octocat/Hello-World/notifications{?since,all,participating}", "pulls_url": "https://api.github.com/repos/octocat/Hello-World/pulls{/number}", "releases_url": "https://api.github.com/repos/octocat/Hello-World/releases{/id}", "ssh_url": "git@github.com:octocat/Hello-World.git", "stargazers_url": "https://api.github.com/repos/octocat/Hello-World/stargazers", "statuses_url": "https://api.github.com/repos/octocat/Hello-World/statuses/{sha}", "subscribers_url": "https://api.github.com/repos/octocat/Hello-World/subscribers", "subscription_url": "https://api.github.com/repos/octocat/Hello-World/subscription", "tags_url": "https://api.github.com/repos/octocat/Hello-World/tags", "teams_url": "https://api.github.com/repos/octocat/Hello-World/teams", "trees_url": "https://api.github.com/repos/octocat/Hello-World/git/trees{/sha}", "clone_url": "https://github.com/octocat/Hello-World.git", "mirror_url": "git:git.example.com/octocat/Hello-World", "hooks_url": "https://api.github.com/repos/octocat/Hello-World/hooks", "svn_url": "https://svn.github.com/octocat/Hello-World", "homepage": "https://github.com", "language": null, "forks_count": 9, "stargazers_count": 80, "watchers_count": 80, "size": 108, "default_branch": "master", "open_issues_count": 0, "is_template": true, "topics": [ "octocat", "atom", "electron", "api" ], "has_issues": true, "has_projects": true, "has_wiki": true, "has_pages": false, "has_downloads": true, "archived": false, "disabled": false, "visibility": "public", "pushed_at": "2011-01-26T19:06:43Z", "created_at": "2011-01-26T19:01:12Z", "updated_at": "2011-01-26T19:14:43Z", "permissions": { "admin": false, "push": false, "pull": true }, "temp_clone_token": "ABTLWHOULUVAXGTRYU7OC2876QJ2O", "delete_branch_on_merge": true, "subscribers_count": 42, "network_count": 0, "license": { "key": "mit", "name": "MIT License", "spdx_id": "MIT", "url": "https://api.github.com/licenses/mit", "node_id": "MDc6TGljZW5zZW1pdA==" } } ] }, "short-blob": { "value": { "url": "https://api.github.com/repos/octocat/example/git/blobs/3a0f86fb8db8eea7ccbb9a95f325ddbedfb25e15", "sha": "3a0f86fb8db8eea7ccbb9a95f325ddbedfb25e15" } }, "blob": { "value": { "content": "Q29udGVudCBvZiB0aGUgYmxvYg==", "encoding": "base64", "url": "https://api.github.com/repos/octocat/example/git/blobs/3a0f86fb8db8eea7ccbb9a95f325ddbedfb25e15", "sha": "3a0f86fb8db8eea7ccbb9a95f325ddbedfb25e15", "size": 19, "node_id": "Q29udGVudCBvZiB0aGUgYmxvYg==" } }, "git-commit": { "value": { "sha": "7638417db6d59f3c431d3e1f261cc637155684cd", "node_id": "MDY6Q29tbWl0NzYzODQxN2RiNmQ1OWYzYzQzMWQzZTFmMjYxY2M2MzcxNTU2ODRjZA==", "url": "https://api.github.com/repos/octocat/Hello-World/git/commits/7638417db6d59f3c431d3e1f261cc637155684cd", "author": { "date": "2014-11-07T22:01:45Z", "name": "Monalisa Octocat", "email": "octocat@github.com" }, "committer": { "date": "2014-11-07T22:01:45Z", "name": "Monalisa Octocat", "email": "octocat@github.com" }, "message": "my commit message", "tree": { "url": "https://api.github.com/repos/octocat/Hello-World/git/trees/827efc6d56897b048c772eb4087f854f46256132", "sha": "827efc6d56897b048c772eb4087f854f46256132" }, "parents": [ { "url": "https://api.github.com/repos/octocat/Hello-World/git/commits/7d1b31e74ee336d15cbd21741bc88a537ed063a0", "sha": "7d1b31e74ee336d15cbd21741bc88a537ed063a0", "html_url": "https://github.com/octocat/Hello-World/commit/7d1b31e74ee336d15cbd21741bc88a537ed063a0" } ], "verification": { "verified": false, "reason": "unsigned", "signature": null, "payload": null }, "html_url": "https://github.com/octocat/Hello-World/commit/7638417db6d59f3c431d3e1f261cc637155684cd" } }, "git-commit-2": { "value": { "sha": "7638417db6d59f3c431d3e1f261cc637155684cd", "node_id": "MDY6Q29tbWl0NmRjYjA5YjViNTc4NzVmMzM0ZjYxYWViZWQ2OTVlMmU0MTkzZGI1ZQ==", "url": "https://api.github.com/repos/octocat/Hello-World/git/commits/7638417db6d59f3c431d3e1f261cc637155684cd", "html_url": "https://github.com/octocat/Hello-World/commit/7638417db6d59f3c431d3e1f261cc637155684cd", "author": { "date": "2014-11-07T22:01:45Z", "name": "Monalisa Octocat", "email": "octocat@github.com" }, "committer": { "date": "2014-11-07T22:01:45Z", "name": "Monalisa Octocat", "email": "octocat@github.com" }, "message": "added readme, because im a good github citizen", "tree": { "url": "https://api.github.com/repos/octocat/Hello-World/git/trees/691272480426f78a0138979dd3ce63b77f706feb", "sha": "691272480426f78a0138979dd3ce63b77f706feb" }, "parents": [ { "url": "https://api.github.com/repos/octocat/Hello-World/git/commits/1acc419d4d6a9ce985db7be48c6349a0475975b5", "sha": "1acc419d4d6a9ce985db7be48c6349a0475975b5", "html_url": "https://github.com/octocat/Hello-World/commit/7638417db6d59f3c431d3e1f261cc637155684cd" } ], "verification": { "verified": false, "reason": "unsigned", "signature": null, "payload": null } } }, "git-ref-items": { "value": [ { "ref": "refs/heads/feature-a", "node_id": "MDM6UmVmcmVmcy9oZWFkcy9mZWF0dXJlLWE=", "url": "https://api.github.com/repos/octocat/Hello-World/git/refs/heads/feature-a", "object": { "type": "commit", "sha": "aa218f56b14c9653891f9e74264a383fa43fefbd", "url": "https://api.github.com/repos/octocat/Hello-World/git/commits/aa218f56b14c9653891f9e74264a383fa43fefbd" } }, { "ref": "refs/heads/feature-b", "node_id": "MDM6UmVmcmVmcy9oZWFkcy9mZWF0dXJlLWI=", "url": "https://api.github.com/repos/octocat/Hello-World/git/refs/heads/feature-b", "object": { "type": "commit", "sha": "612077ae6dffb4d2fbd8ce0cccaa58893b07b5ac", "url": "https://api.github.com/repos/octocat/Hello-World/git/commits/612077ae6dffb4d2fbd8ce0cccaa58893b07b5ac" } } ] }, "git-ref": { "value": { "ref": "refs/heads/featureA", "node_id": "MDM6UmVmcmVmcy9oZWFkcy9mZWF0dXJlQQ==", "url": "https://api.github.com/repos/octocat/Hello-World/git/refs/heads/featureA", "object": { "type": "commit", "sha": "aa218f56b14c9653891f9e74264a383fa43fefbd", "url": "https://api.github.com/repos/octocat/Hello-World/git/commits/aa218f56b14c9653891f9e74264a383fa43fefbd" } } }, "git-tag": { "value": { "node_id": "MDM6VGFnOTQwYmQzMzYyNDhlZmFlMGY5ZWU1YmM3YjJkNWM5ODU4ODdiMTZhYw==", "tag": "v0.0.1", "sha": "940bd336248efae0f9ee5bc7b2d5c985887b16ac", "url": "https://api.github.com/repos/octocat/Hello-World/git/tags/940bd336248efae0f9ee5bc7b2d5c985887b16ac", "message": "initial version", "tagger": { "name": "Monalisa Octocat", "email": "octocat@github.com", "date": "2014-11-07T22:01:45Z" }, "object": { "type": "commit", "sha": "c3d0be41ecbe669545ee3e94d31ed9a4bc91ee3c", "url": "https://api.github.com/repos/octocat/Hello-World/git/commits/c3d0be41ecbe669545ee3e94d31ed9a4bc91ee3c" }, "verification": { "verified": false, "reason": "unsigned", "signature": null, "payload": null } } }, "git-tree": { "value": { "sha": "cd8274d15fa3ae2ab983129fb037999f264ba9a7", "url": "https://api.github.com/repos/octocat/Hello-World/trees/cd8274d15fa3ae2ab983129fb037999f264ba9a7", "tree": [ { "path": "file.rb", "mode": "100644", "type": "blob", "size": 132, "sha": "7c258a9869f33c1e1e1f74fbb32f07c86cb5a75b", "url": "https://api.github.com/repos/octocat/Hello-World/git/blobs/7c258a9869f33c1e1e1f74fbb32f07c86cb5a75b" } ], "truncated": true } }, "git-tree-default-response": { "summary": "Default response", "value": { "sha": "9fb037999f264ba9a7fc6274d15fa3ae2ab98312", "url": "https://api.github.com/repos/octocat/Hello-World/trees/9fb037999f264ba9a7fc6274d15fa3ae2ab98312", "tree": [ { "path": "file.rb", "mode": "100644", "type": "blob", "size": 30, "sha": "44b4fc6d56897b048c772eb4087f854f46256132", "url": "https://api.github.com/repos/octocat/Hello-World/git/blobs/44b4fc6d56897b048c772eb4087f854f46256132" }, { "path": "subdir", "mode": "040000", "type": "tree", "sha": "f484d249c660418515fb01c2b9662073663c242e", "url": "https://api.github.com/repos/octocat/Hello-World/git/blobs/f484d249c660418515fb01c2b9662073663c242e" }, { "path": "exec_file", "mode": "100755", "type": "blob", "size": 75, "sha": "45b983be36b73c0788dc9cbcb76cbb80fc7bb057", "url": "https://api.github.com/repos/octocat/Hello-World/git/blobs/45b983be36b73c0788dc9cbcb76cbb80fc7bb057" } ], "truncated": false } }, "git-tree-response-recursively-retrieving-a-tree": { "summary": "Response recursively retrieving a tree", "value": { "sha": "fc6274d15fa3ae2ab983129fb037999f264ba9a7", "url": "https://api.github.com/repos/octocat/Hello-World/trees/fc6274d15fa3ae2ab983129fb037999f264ba9a7", "tree": [ { "path": "subdir/file.txt", "mode": "100644", "type": "blob", "size": 132, "sha": "7c258a9869f33c1e1e1f74fbb32f07c86cb5a75b", "url": "https://api.github.com/repos/octocat/Hello-World/git/7c258a9869f33c1e1e1f74fbb32f07c86cb5a75b" } ], "truncated": false } }, "hook-items": { "value": [ { "type": "Repository", "id": 12345678, "name": "web", "active": true, "events": [ "push", "pull_request" ], "config": { "content_type": "json", "insecure_ssl": "0", "url": "https://example.com/webhook" }, "updated_at": "2019-06-03T00:57:16Z", "created_at": "2019-06-03T00:57:16Z", "url": "https://api.github.com/repos/octocat/Hello-World/hooks/12345678", "test_url": "https://api.github.com/repos/octocat/Hello-World/hooks/12345678/test", "ping_url": "https://api.github.com/repos/octocat/Hello-World/hooks/12345678/pings", "last_response": { "code": null, "status": "unused", "message": null } } ] }, "hook": { "value": { "type": "Repository", "id": 12345678, "name": "web", "active": true, "events": [ "push", "pull_request" ], "config": { "content_type": "json", "insecure_ssl": "0", "url": "https://example.com/webhook" }, "updated_at": "2019-06-03T00:57:16Z", "created_at": "2019-06-03T00:57:16Z", "url": "https://api.github.com/repos/octocat/Hello-World/hooks/12345678", "test_url": "https://api.github.com/repos/octocat/Hello-World/hooks/12345678/test", "ping_url": "https://api.github.com/repos/octocat/Hello-World/hooks/12345678/pings", "last_response": { "code": null, "status": "unused", "message": null } } }, "repository-invitation-items": { "value": [ { "id": 1, "repository": { "id": 1296269, "node_id": "MDEwOlJlcG9zaXRvcnkxMjk2MjY5", "name": "Hello-World", "full_name": "octocat/Hello-World", "owner": { "login": "octocat", "id": 1, "node_id": "MDQ6VXNlcjE=", "avatar_url": "https://github.com/images/error/octocat_happy.gif", "gravatar_id": "", "url": "https://api.github.com/users/octocat", "html_url": "https://github.com/octocat", "followers_url": "https://api.github.com/users/octocat/followers", "following_url": "https://api.github.com/users/octocat/following{/other_user}", "gists_url": "https://api.github.com/users/octocat/gists{/gist_id}", "starred_url": "https://api.github.com/users/octocat/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/octocat/subscriptions", "organizations_url": "https://api.github.com/users/octocat/orgs", "repos_url": "https://api.github.com/users/octocat/repos", "events_url": "https://api.github.com/users/octocat/events{/privacy}", "received_events_url": "https://api.github.com/users/octocat/received_events", "type": "User", "site_admin": false }, "private": false, "html_url": "https://github.com/octocat/Hello-World", "description": "This your first repo!", "fork": false, "url": "https://api.github.com/repos/octocat/Hello-World", "archive_url": "https://api.github.com/repos/octocat/Hello-World/{archive_format}{/ref}", "assignees_url": "https://api.github.com/repos/octocat/Hello-World/assignees{/user}", "blobs_url": "https://api.github.com/repos/octocat/Hello-World/git/blobs{/sha}", "branches_url": "https://api.github.com/repos/octocat/Hello-World/branches{/branch}", "collaborators_url": "https://api.github.com/repos/octocat/Hello-World/collaborators{/collaborator}", "comments_url": "https://api.github.com/repos/octocat/Hello-World/comments{/number}", "commits_url": "https://api.github.com/repos/octocat/Hello-World/commits{/sha}", "compare_url": "https://api.github.com/repos/octocat/Hello-World/compare/{base}...{head}", "contents_url": "https://api.github.com/repos/octocat/Hello-World/contents/{+path}", "contributors_url": "https://api.github.com/repos/octocat/Hello-World/contributors", "deployments_url": "https://api.github.com/repos/octocat/Hello-World/deployments", "downloads_url": "https://api.github.com/repos/octocat/Hello-World/downloads", "events_url": "https://api.github.com/repos/octocat/Hello-World/events", "forks_url": "https://api.github.com/repos/octocat/Hello-World/forks", "git_commits_url": "https://api.github.com/repos/octocat/Hello-World/git/commits{/sha}", "git_refs_url": "https://api.github.com/repos/octocat/Hello-World/git/refs{/sha}", "git_tags_url": "https://api.github.com/repos/octocat/Hello-World/git/tags{/sha}", "git_url": "git:github.com/octocat/Hello-World.git", "issue_comment_url": "https://api.github.com/repos/octocat/Hello-World/issues/comments{/number}", "issue_events_url": "https://api.github.com/repos/octocat/Hello-World/issues/events{/number}", "issues_url": "https://api.github.com/repos/octocat/Hello-World/issues{/number}", "keys_url": "https://api.github.com/repos/octocat/Hello-World/keys{/key_id}", "labels_url": "https://api.github.com/repos/octocat/Hello-World/labels{/name}", "languages_url": "https://api.github.com/repos/octocat/Hello-World/languages", "merges_url": "https://api.github.com/repos/octocat/Hello-World/merges", "milestones_url": "https://api.github.com/repos/octocat/Hello-World/milestones{/number}", "notifications_url": "https://api.github.com/repos/octocat/Hello-World/notifications{?since,all,participating}", "pulls_url": "https://api.github.com/repos/octocat/Hello-World/pulls{/number}", "releases_url": "https://api.github.com/repos/octocat/Hello-World/releases{/id}", "ssh_url": "git@github.com:octocat/Hello-World.git", "stargazers_url": "https://api.github.com/repos/octocat/Hello-World/stargazers", "statuses_url": "https://api.github.com/repos/octocat/Hello-World/statuses/{sha}", "subscribers_url": "https://api.github.com/repos/octocat/Hello-World/subscribers", "subscription_url": "https://api.github.com/repos/octocat/Hello-World/subscription", "tags_url": "https://api.github.com/repos/octocat/Hello-World/tags", "teams_url": "https://api.github.com/repos/octocat/Hello-World/teams", "trees_url": "https://api.github.com/repos/octocat/Hello-World/git/trees{/sha}", "hooks_url": "http://api.github.com/repos/octocat/Hello-World/hooks" }, "invitee": { "login": "octocat", "id": 1, "node_id": "MDQ6VXNlcjE=", "avatar_url": "https://github.com/images/error/octocat_happy.gif", "gravatar_id": "", "url": "https://api.github.com/users/octocat", "html_url": "https://github.com/octocat", "followers_url": "https://api.github.com/users/octocat/followers", "following_url": "https://api.github.com/users/octocat/following{/other_user}", "gists_url": "https://api.github.com/users/octocat/gists{/gist_id}", "starred_url": "https://api.github.com/users/octocat/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/octocat/subscriptions", "organizations_url": "https://api.github.com/users/octocat/orgs", "repos_url": "https://api.github.com/users/octocat/repos", "events_url": "https://api.github.com/users/octocat/events{/privacy}", "received_events_url": "https://api.github.com/users/octocat/received_events", "type": "User", "site_admin": false }, "inviter": { "login": "octocat", "id": 1, "node_id": "MDQ6VXNlcjE=", "avatar_url": "https://github.com/images/error/octocat_happy.gif", "gravatar_id": "", "url": "https://api.github.com/users/octocat", "html_url": "https://github.com/octocat", "followers_url": "https://api.github.com/users/octocat/followers", "following_url": "https://api.github.com/users/octocat/following{/other_user}", "gists_url": "https://api.github.com/users/octocat/gists{/gist_id}", "starred_url": "https://api.github.com/users/octocat/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/octocat/subscriptions", "organizations_url": "https://api.github.com/users/octocat/orgs", "repos_url": "https://api.github.com/users/octocat/repos", "events_url": "https://api.github.com/users/octocat/events{/privacy}", "received_events_url": "https://api.github.com/users/octocat/received_events", "type": "User", "site_admin": false }, "permissions": "write", "created_at": "2016-06-13T14:52:50-05:00", "url": "https://api.github.com/user/repository_invitations/1296269", "html_url": "https://github.com/octocat/Hello-World/invitations", "node_id": "MDQ6VXNlcjE=" } ] }, "repository-invitation": { "value": { "id": 1, "node_id": "MDEwOlJlcG9zaXRvcnkxMjk2MjY5", "repository": { "id": 1296269, "node_id": "MDEwOlJlcG9zaXRvcnkxMjk2MjY5", "name": "Hello-World", "full_name": "octocat/Hello-World", "owner": { "login": "octocat", "id": 1, "node_id": "MDQ6VXNlcjE=", "avatar_url": "https://github.com/images/error/octocat_happy.gif", "gravatar_id": "", "url": "https://api.github.com/users/octocat", "html_url": "https://github.com/octocat", "followers_url": "https://api.github.com/users/octocat/followers", "following_url": "https://api.github.com/users/octocat/following{/other_user}", "gists_url": "https://api.github.com/users/octocat/gists{/gist_id}", "starred_url": "https://api.github.com/users/octocat/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/octocat/subscriptions", "organizations_url": "https://api.github.com/users/octocat/orgs", "repos_url": "https://api.github.com/users/octocat/repos", "events_url": "https://api.github.com/users/octocat/events{/privacy}", "received_events_url": "https://api.github.com/users/octocat/received_events", "type": "User", "site_admin": false }, "private": false, "html_url": "https://github.com/octocat/Hello-World", "description": "This your first repo!", "fork": false, "url": "https://api.github.com/repos/octocat/Hello-World", "archive_url": "https://api.github.com/repos/octocat/Hello-World/{archive_format}{/ref}", "assignees_url": "https://api.github.com/repos/octocat/Hello-World/assignees{/user}", "blobs_url": "https://api.github.com/repos/octocat/Hello-World/git/blobs{/sha}", "branches_url": "https://api.github.com/repos/octocat/Hello-World/branches{/branch}", "collaborators_url": "https://api.github.com/repos/octocat/Hello-World/collaborators{/collaborator}", "comments_url": "https://api.github.com/repos/octocat/Hello-World/comments{/number}", "commits_url": "https://api.github.com/repos/octocat/Hello-World/commits{/sha}", "compare_url": "https://api.github.com/repos/octocat/Hello-World/compare/{base}...{head}", "contents_url": "https://api.github.com/repos/octocat/Hello-World/contents/{+path}", "contributors_url": "https://api.github.com/repos/octocat/Hello-World/contributors", "deployments_url": "https://api.github.com/repos/octocat/Hello-World/deployments", "downloads_url": "https://api.github.com/repos/octocat/Hello-World/downloads", "events_url": "https://api.github.com/repos/octocat/Hello-World/events", "forks_url": "https://api.github.com/repos/octocat/Hello-World/forks", "git_commits_url": "https://api.github.com/repos/octocat/Hello-World/git/commits{/sha}", "git_refs_url": "https://api.github.com/repos/octocat/Hello-World/git/refs{/sha}", "git_tags_url": "https://api.github.com/repos/octocat/Hello-World/git/tags{/sha}", "git_url": "git:github.com/octocat/Hello-World.git", "issue_comment_url": "https://api.github.com/repos/octocat/Hello-World/issues/comments{/number}", "issue_events_url": "https://api.github.com/repos/octocat/Hello-World/issues/events{/number}", "issues_url": "https://api.github.com/repos/octocat/Hello-World/issues{/number}", "keys_url": "https://api.github.com/repos/octocat/Hello-World/keys{/key_id}", "labels_url": "https://api.github.com/repos/octocat/Hello-World/labels{/name}", "languages_url": "https://api.github.com/repos/octocat/Hello-World/languages", "merges_url": "https://api.github.com/repos/octocat/Hello-World/merges", "milestones_url": "https://api.github.com/repos/octocat/Hello-World/milestones{/number}", "notifications_url": "https://api.github.com/repos/octocat/Hello-World/notifications{?since,all,participating}", "pulls_url": "https://api.github.com/repos/octocat/Hello-World/pulls{/number}", "releases_url": "https://api.github.com/repos/octocat/Hello-World/releases{/id}", "ssh_url": "git@github.com:octocat/Hello-World.git", "stargazers_url": "https://api.github.com/repos/octocat/Hello-World/stargazers", "statuses_url": "https://api.github.com/repos/octocat/Hello-World/statuses/{sha}", "subscribers_url": "https://api.github.com/repos/octocat/Hello-World/subscribers", "subscription_url": "https://api.github.com/repos/octocat/Hello-World/subscription", "tags_url": "https://api.github.com/repos/octocat/Hello-World/tags", "teams_url": "https://api.github.com/repos/octocat/Hello-World/teams", "trees_url": "https://api.github.com/repos/octocat/Hello-World/git/trees{/sha}", "hooks_url": "http://api.github.com/repos/octocat/Hello-World/hooks" }, "invitee": { "login": "octocat", "id": 1, "node_id": "MDQ6VXNlcjE=", "avatar_url": "https://github.com/images/error/octocat_happy.gif", "gravatar_id": "", "url": "https://api.github.com/users/octocat", "html_url": "https://github.com/octocat", "followers_url": "https://api.github.com/users/octocat/followers", "following_url": "https://api.github.com/users/octocat/following{/other_user}", "gists_url": "https://api.github.com/users/octocat/gists{/gist_id}", "starred_url": "https://api.github.com/users/octocat/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/octocat/subscriptions", "organizations_url": "https://api.github.com/users/octocat/orgs", "repos_url": "https://api.github.com/users/octocat/repos", "events_url": "https://api.github.com/users/octocat/events{/privacy}", "received_events_url": "https://api.github.com/users/octocat/received_events", "type": "User", "site_admin": false }, "inviter": { "login": "octocat", "id": 1, "node_id": "MDQ6VXNlcjE=", "avatar_url": "https://github.com/images/error/octocat_happy.gif", "gravatar_id": "", "url": "https://api.github.com/users/octocat", "html_url": "https://github.com/octocat", "followers_url": "https://api.github.com/users/octocat/followers", "following_url": "https://api.github.com/users/octocat/following{/other_user}", "gists_url": "https://api.github.com/users/octocat/gists{/gist_id}", "starred_url": "https://api.github.com/users/octocat/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/octocat/subscriptions", "organizations_url": "https://api.github.com/users/octocat/orgs", "repos_url": "https://api.github.com/users/octocat/repos", "events_url": "https://api.github.com/users/octocat/events{/privacy}", "received_events_url": "https://api.github.com/users/octocat/received_events", "type": "User", "site_admin": false }, "permissions": "write", "created_at": "2016-06-13T14:52:50-05:00", "expired": false, "url": "https://api.github.com/user/repository_invitations/1296269", "html_url": "https://github.com/octocat/Hello-World/invitations" } }, "issue-items": { "value": [ { "id": 1, "node_id": "MDU6SXNzdWUx", "url": "https://api.github.com/repos/octocat/Hello-World/issues/1347", "repository_url": "https://api.github.com/repos/octocat/Hello-World", "labels_url": "https://api.github.com/repos/octocat/Hello-World/issues/1347/labels{/name}", "comments_url": "https://api.github.com/repos/octocat/Hello-World/issues/1347/comments", "events_url": "https://api.github.com/repos/octocat/Hello-World/issues/1347/events", "html_url": "https://github.com/octocat/Hello-World/issues/1347", "number": 1347, "state": "open", "title": "Found a bug", "body": "I'm having a problem with this.", "user": { "login": "octocat", "id": 1, "node_id": "MDQ6VXNlcjE=", "avatar_url": "https://github.com/images/error/octocat_happy.gif", "gravatar_id": "", "url": "https://api.github.com/users/octocat", "html_url": "https://github.com/octocat", "followers_url": "https://api.github.com/users/octocat/followers", "following_url": "https://api.github.com/users/octocat/following{/other_user}", "gists_url": "https://api.github.com/users/octocat/gists{/gist_id}", "starred_url": "https://api.github.com/users/octocat/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/octocat/subscriptions", "organizations_url": "https://api.github.com/users/octocat/orgs", "repos_url": "https://api.github.com/users/octocat/repos", "events_url": "https://api.github.com/users/octocat/events{/privacy}", "received_events_url": "https://api.github.com/users/octocat/received_events", "type": "User", "site_admin": false }, "labels": [ { "id": 208045946, "node_id": "MDU6TGFiZWwyMDgwNDU5NDY=", "url": "https://api.github.com/repos/octocat/Hello-World/labels/bug", "name": "bug", "description": "Something isn't working", "color": "f29513", "default": true } ], "assignee": { "login": "octocat", "id": 1, "node_id": "MDQ6VXNlcjE=", "avatar_url": "https://github.com/images/error/octocat_happy.gif", "gravatar_id": "", "url": "https://api.github.com/users/octocat", "html_url": "https://github.com/octocat", "followers_url": "https://api.github.com/users/octocat/followers", "following_url": "https://api.github.com/users/octocat/following{/other_user}", "gists_url": "https://api.github.com/users/octocat/gists{/gist_id}", "starred_url": "https://api.github.com/users/octocat/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/octocat/subscriptions", "organizations_url": "https://api.github.com/users/octocat/orgs", "repos_url": "https://api.github.com/users/octocat/repos", "events_url": "https://api.github.com/users/octocat/events{/privacy}", "received_events_url": "https://api.github.com/users/octocat/received_events", "type": "User", "site_admin": false }, "assignees": [ { "login": "octocat", "id": 1, "node_id": "MDQ6VXNlcjE=", "avatar_url": "https://github.com/images/error/octocat_happy.gif", "gravatar_id": "", "url": "https://api.github.com/users/octocat", "html_url": "https://github.com/octocat", "followers_url": "https://api.github.com/users/octocat/followers", "following_url": "https://api.github.com/users/octocat/following{/other_user}", "gists_url": "https://api.github.com/users/octocat/gists{/gist_id}", "starred_url": "https://api.github.com/users/octocat/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/octocat/subscriptions", "organizations_url": "https://api.github.com/users/octocat/orgs", "repos_url": "https://api.github.com/users/octocat/repos", "events_url": "https://api.github.com/users/octocat/events{/privacy}", "received_events_url": "https://api.github.com/users/octocat/received_events", "type": "User", "site_admin": false } ], "milestone": { "url": "https://api.github.com/repos/octocat/Hello-World/milestones/1", "html_url": "https://github.com/octocat/Hello-World/milestones/v1.0", "labels_url": "https://api.github.com/repos/octocat/Hello-World/milestones/1/labels", "id": 1002604, "node_id": "MDk6TWlsZXN0b25lMTAwMjYwNA==", "number": 1, "state": "open", "title": "v1.0", "description": "Tracking milestone for version 1.0", "creator": { "login": "octocat", "id": 1, "node_id": "MDQ6VXNlcjE=", "avatar_url": "https://github.com/images/error/octocat_happy.gif", "gravatar_id": "", "url": "https://api.github.com/users/octocat", "html_url": "https://github.com/octocat", "followers_url": "https://api.github.com/users/octocat/followers", "following_url": "https://api.github.com/users/octocat/following{/other_user}", "gists_url": "https://api.github.com/users/octocat/gists{/gist_id}", "starred_url": "https://api.github.com/users/octocat/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/octocat/subscriptions", "organizations_url": "https://api.github.com/users/octocat/orgs", "repos_url": "https://api.github.com/users/octocat/repos", "events_url": "https://api.github.com/users/octocat/events{/privacy}", "received_events_url": "https://api.github.com/users/octocat/received_events", "type": "User", "site_admin": false }, "open_issues": 4, "closed_issues": 8, "created_at": "2011-04-10T20:09:31Z", "updated_at": "2014-03-03T18:58:10Z", "closed_at": "2013-02-12T13:22:01Z", "due_on": "2012-10-09T23:39:01Z" }, "locked": true, "active_lock_reason": "too heated", "comments": 0, "pull_request": { "url": "https://api.github.com/repos/octocat/Hello-World/pulls/1347", "html_url": "https://github.com/octocat/Hello-World/pull/1347", "diff_url": "https://github.com/octocat/Hello-World/pull/1347.diff", "patch_url": "https://github.com/octocat/Hello-World/pull/1347.patch" }, "closed_at": null, "created_at": "2011-04-22T13:33:48Z", "updated_at": "2011-04-22T13:33:48Z", "closed_by": { "login": "octocat", "id": 1, "node_id": "MDQ6VXNlcjE=", "avatar_url": "https://github.com/images/error/octocat_happy.gif", "gravatar_id": "", "url": "https://api.github.com/users/octocat", "html_url": "https://github.com/octocat", "followers_url": "https://api.github.com/users/octocat/followers", "following_url": "https://api.github.com/users/octocat/following{/other_user}", "gists_url": "https://api.github.com/users/octocat/gists{/gist_id}", "starred_url": "https://api.github.com/users/octocat/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/octocat/subscriptions", "organizations_url": "https://api.github.com/users/octocat/orgs", "repos_url": "https://api.github.com/users/octocat/repos", "events_url": "https://api.github.com/users/octocat/events{/privacy}", "received_events_url": "https://api.github.com/users/octocat/received_events", "type": "User", "site_admin": false }, "author_association": "COLLABORATOR" } ] }, "issue": { "value": { "id": 1, "node_id": "MDU6SXNzdWUx", "url": "https://api.github.com/repos/octocat/Hello-World/issues/1347", "repository_url": "https://api.github.com/repos/octocat/Hello-World", "labels_url": "https://api.github.com/repos/octocat/Hello-World/issues/1347/labels{/name}", "comments_url": "https://api.github.com/repos/octocat/Hello-World/issues/1347/comments", "events_url": "https://api.github.com/repos/octocat/Hello-World/issues/1347/events", "html_url": "https://github.com/octocat/Hello-World/issues/1347", "number": 1347, "state": "open", "title": "Found a bug", "body": "I'm having a problem with this.", "user": { "login": "octocat", "id": 1, "node_id": "MDQ6VXNlcjE=", "avatar_url": "https://github.com/images/error/octocat_happy.gif", "gravatar_id": "", "url": "https://api.github.com/users/octocat", "html_url": "https://github.com/octocat", "followers_url": "https://api.github.com/users/octocat/followers", "following_url": "https://api.github.com/users/octocat/following{/other_user}", "gists_url": "https://api.github.com/users/octocat/gists{/gist_id}", "starred_url": "https://api.github.com/users/octocat/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/octocat/subscriptions", "organizations_url": "https://api.github.com/users/octocat/orgs", "repos_url": "https://api.github.com/users/octocat/repos", "events_url": "https://api.github.com/users/octocat/events{/privacy}", "received_events_url": "https://api.github.com/users/octocat/received_events", "type": "User", "site_admin": false }, "labels": [ { "id": 208045946, "node_id": "MDU6TGFiZWwyMDgwNDU5NDY=", "url": "https://api.github.com/repos/octocat/Hello-World/labels/bug", "name": "bug", "description": "Something isn't working", "color": "f29513", "default": true } ], "assignee": { "login": "octocat", "id": 1, "node_id": "MDQ6VXNlcjE=", "avatar_url": "https://github.com/images/error/octocat_happy.gif", "gravatar_id": "", "url": "https://api.github.com/users/octocat", "html_url": "https://github.com/octocat", "followers_url": "https://api.github.com/users/octocat/followers", "following_url": "https://api.github.com/users/octocat/following{/other_user}", "gists_url": "https://api.github.com/users/octocat/gists{/gist_id}", "starred_url": "https://api.github.com/users/octocat/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/octocat/subscriptions", "organizations_url": "https://api.github.com/users/octocat/orgs", "repos_url": "https://api.github.com/users/octocat/repos", "events_url": "https://api.github.com/users/octocat/events{/privacy}", "received_events_url": "https://api.github.com/users/octocat/received_events", "type": "User", "site_admin": false }, "assignees": [ { "login": "octocat", "id": 1, "node_id": "MDQ6VXNlcjE=", "avatar_url": "https://github.com/images/error/octocat_happy.gif", "gravatar_id": "", "url": "https://api.github.com/users/octocat", "html_url": "https://github.com/octocat", "followers_url": "https://api.github.com/users/octocat/followers", "following_url": "https://api.github.com/users/octocat/following{/other_user}", "gists_url": "https://api.github.com/users/octocat/gists{/gist_id}", "starred_url": "https://api.github.com/users/octocat/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/octocat/subscriptions", "organizations_url": "https://api.github.com/users/octocat/orgs", "repos_url": "https://api.github.com/users/octocat/repos", "events_url": "https://api.github.com/users/octocat/events{/privacy}", "received_events_url": "https://api.github.com/users/octocat/received_events", "type": "User", "site_admin": false } ], "milestone": { "url": "https://api.github.com/repos/octocat/Hello-World/milestones/1", "html_url": "https://github.com/octocat/Hello-World/milestones/v1.0", "labels_url": "https://api.github.com/repos/octocat/Hello-World/milestones/1/labels", "id": 1002604, "node_id": "MDk6TWlsZXN0b25lMTAwMjYwNA==", "number": 1, "state": "open", "title": "v1.0", "description": "Tracking milestone for version 1.0", "creator": { "login": "octocat", "id": 1, "node_id": "MDQ6VXNlcjE=", "avatar_url": "https://github.com/images/error/octocat_happy.gif", "gravatar_id": "", "url": "https://api.github.com/users/octocat", "html_url": "https://github.com/octocat", "followers_url": "https://api.github.com/users/octocat/followers", "following_url": "https://api.github.com/users/octocat/following{/other_user}", "gists_url": "https://api.github.com/users/octocat/gists{/gist_id}", "starred_url": "https://api.github.com/users/octocat/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/octocat/subscriptions", "organizations_url": "https://api.github.com/users/octocat/orgs", "repos_url": "https://api.github.com/users/octocat/repos", "events_url": "https://api.github.com/users/octocat/events{/privacy}", "received_events_url": "https://api.github.com/users/octocat/received_events", "type": "User", "site_admin": false }, "open_issues": 4, "closed_issues": 8, "created_at": "2011-04-10T20:09:31Z", "updated_at": "2014-03-03T18:58:10Z", "closed_at": "2013-02-12T13:22:01Z", "due_on": "2012-10-09T23:39:01Z" }, "locked": true, "active_lock_reason": "too heated", "comments": 0, "pull_request": { "url": "https://api.github.com/repos/octocat/Hello-World/pulls/1347", "html_url": "https://github.com/octocat/Hello-World/pull/1347", "diff_url": "https://github.com/octocat/Hello-World/pull/1347.diff", "patch_url": "https://github.com/octocat/Hello-World/pull/1347.patch" }, "closed_at": null, "created_at": "2011-04-22T13:33:48Z", "updated_at": "2011-04-22T13:33:48Z", "closed_by": { "login": "octocat", "id": 1, "node_id": "MDQ6VXNlcjE=", "avatar_url": "https://github.com/images/error/octocat_happy.gif", "gravatar_id": "", "url": "https://api.github.com/users/octocat", "html_url": "https://github.com/octocat", "followers_url": "https://api.github.com/users/octocat/followers", "following_url": "https://api.github.com/users/octocat/following{/other_user}", "gists_url": "https://api.github.com/users/octocat/gists{/gist_id}", "starred_url": "https://api.github.com/users/octocat/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/octocat/subscriptions", "organizations_url": "https://api.github.com/users/octocat/orgs", "repos_url": "https://api.github.com/users/octocat/repos", "events_url": "https://api.github.com/users/octocat/events{/privacy}", "received_events_url": "https://api.github.com/users/octocat/received_events", "type": "User", "site_admin": false }, "author_association": "COLLABORATOR" } }, "issue-comment-items": { "value": [ { "id": 1, "node_id": "MDEyOklzc3VlQ29tbWVudDE=", "url": "https://api.github.com/repos/octocat/Hello-World/issues/comments/1", "html_url": "https://github.com/octocat/Hello-World/issues/1347#issuecomment-1", "body": "Me too", "user": { "login": "octocat", "id": 1, "node_id": "MDQ6VXNlcjE=", "avatar_url": "https://github.com/images/error/octocat_happy.gif", "gravatar_id": "", "url": "https://api.github.com/users/octocat", "html_url": "https://github.com/octocat", "followers_url": "https://api.github.com/users/octocat/followers", "following_url": "https://api.github.com/users/octocat/following{/other_user}", "gists_url": "https://api.github.com/users/octocat/gists{/gist_id}", "starred_url": "https://api.github.com/users/octocat/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/octocat/subscriptions", "organizations_url": "https://api.github.com/users/octocat/orgs", "repos_url": "https://api.github.com/users/octocat/repos", "events_url": "https://api.github.com/users/octocat/events{/privacy}", "received_events_url": "https://api.github.com/users/octocat/received_events", "type": "User", "site_admin": false }, "created_at": "2011-04-14T16:00:49Z", "updated_at": "2011-04-14T16:00:49Z", "issue_url": "https://api.github.com/repos/octocat/Hello-World/issues/1347", "author_association": "COLLABORATOR" } ] }, "issue-comment": { "value": { "id": 1, "node_id": "MDEyOklzc3VlQ29tbWVudDE=", "url": "https://api.github.com/repos/octocat/Hello-World/issues/comments/1", "html_url": "https://github.com/octocat/Hello-World/issues/1347#issuecomment-1", "body": "Me too", "user": { "login": "octocat", "id": 1, "node_id": "MDQ6VXNlcjE=", "avatar_url": "https://github.com/images/error/octocat_happy.gif", "gravatar_id": "", "url": "https://api.github.com/users/octocat", "html_url": "https://github.com/octocat", "followers_url": "https://api.github.com/users/octocat/followers", "following_url": "https://api.github.com/users/octocat/following{/other_user}", "gists_url": "https://api.github.com/users/octocat/gists{/gist_id}", "starred_url": "https://api.github.com/users/octocat/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/octocat/subscriptions", "organizations_url": "https://api.github.com/users/octocat/orgs", "repos_url": "https://api.github.com/users/octocat/repos", "events_url": "https://api.github.com/users/octocat/events{/privacy}", "received_events_url": "https://api.github.com/users/octocat/received_events", "type": "User", "site_admin": false }, "created_at": "2011-04-14T16:00:49Z", "updated_at": "2011-04-14T16:00:49Z", "issue_url": "https://api.github.com/repos/octocat/Hello-World/issues/1347", "author_association": "COLLABORATOR" } }, "issue-event-items": { "value": [ { "id": 1, "node_id": "MDEwOklzc3VlRXZlbnQx", "url": "https://api.github.com/repos/octocat/Hello-World/issues/events/1", "actor": { "login": "octocat", "id": 1, "node_id": "MDQ6VXNlcjE=", "avatar_url": "https://github.com/images/error/octocat_happy.gif", "gravatar_id": "", "url": "https://api.github.com/users/octocat", "html_url": "https://github.com/octocat", "followers_url": "https://api.github.com/users/octocat/followers", "following_url": "https://api.github.com/users/octocat/following{/other_user}", "gists_url": "https://api.github.com/users/octocat/gists{/gist_id}", "starred_url": "https://api.github.com/users/octocat/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/octocat/subscriptions", "organizations_url": "https://api.github.com/users/octocat/orgs", "repos_url": "https://api.github.com/users/octocat/repos", "events_url": "https://api.github.com/users/octocat/events{/privacy}", "received_events_url": "https://api.github.com/users/octocat/received_events", "type": "User", "site_admin": false }, "event": "closed", "commit_id": "6dcb09b5b57875f334f61aebed695e2e4193db5e", "commit_url": "https://api.github.com/repos/octocat/Hello-World/commits/6dcb09b5b57875f334f61aebed695e2e4193db5e", "created_at": "2011-04-14T16:00:49Z", "issue": { "id": 1, "node_id": "MDU6SXNzdWUx", "url": "https://api.github.com/repos/octocat/Hello-World/issues/1347", "repository_url": "https://api.github.com/repos/octocat/Hello-World", "labels_url": "https://api.github.com/repos/octocat/Hello-World/issues/1347/labels{/name}", "comments_url": "https://api.github.com/repos/octocat/Hello-World/issues/1347/comments", "events_url": "https://api.github.com/repos/octocat/Hello-World/issues/1347/events", "html_url": "https://github.com/octocat/Hello-World/issues/1347", "number": 1347, "state": "open", "title": "Found a bug", "body": "I'm having a problem with this.", "user": { "login": "octocat", "id": 1, "node_id": "MDQ6VXNlcjE=", "avatar_url": "https://github.com/images/error/octocat_happy.gif", "gravatar_id": "", "url": "https://api.github.com/users/octocat", "html_url": "https://github.com/octocat", "followers_url": "https://api.github.com/users/octocat/followers", "following_url": "https://api.github.com/users/octocat/following{/other_user}", "gists_url": "https://api.github.com/users/octocat/gists{/gist_id}", "starred_url": "https://api.github.com/users/octocat/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/octocat/subscriptions", "organizations_url": "https://api.github.com/users/octocat/orgs", "repos_url": "https://api.github.com/users/octocat/repos", "events_url": "https://api.github.com/users/octocat/events{/privacy}", "received_events_url": "https://api.github.com/users/octocat/received_events", "type": "User", "site_admin": false }, "labels": [ { "id": 208045946, "node_id": "MDU6TGFiZWwyMDgwNDU5NDY=", "url": "https://api.github.com/repos/octocat/Hello-World/labels/bug", "name": "bug", "description": "Something isn't working", "color": "f29513", "default": true } ], "assignee": { "login": "octocat", "id": 1, "node_id": "MDQ6VXNlcjE=", "avatar_url": "https://github.com/images/error/octocat_happy.gif", "gravatar_id": "", "url": "https://api.github.com/users/octocat", "html_url": "https://github.com/octocat", "followers_url": "https://api.github.com/users/octocat/followers", "following_url": "https://api.github.com/users/octocat/following{/other_user}", "gists_url": "https://api.github.com/users/octocat/gists{/gist_id}", "starred_url": "https://api.github.com/users/octocat/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/octocat/subscriptions", "organizations_url": "https://api.github.com/users/octocat/orgs", "repos_url": "https://api.github.com/users/octocat/repos", "events_url": "https://api.github.com/users/octocat/events{/privacy}", "received_events_url": "https://api.github.com/users/octocat/received_events", "type": "User", "site_admin": false }, "assignees": [ { "login": "octocat", "id": 1, "node_id": "MDQ6VXNlcjE=", "avatar_url": "https://github.com/images/error/octocat_happy.gif", "gravatar_id": "", "url": "https://api.github.com/users/octocat", "html_url": "https://github.com/octocat", "followers_url": "https://api.github.com/users/octocat/followers", "following_url": "https://api.github.com/users/octocat/following{/other_user}", "gists_url": "https://api.github.com/users/octocat/gists{/gist_id}", "starred_url": "https://api.github.com/users/octocat/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/octocat/subscriptions", "organizations_url": "https://api.github.com/users/octocat/orgs", "repos_url": "https://api.github.com/users/octocat/repos", "events_url": "https://api.github.com/users/octocat/events{/privacy}", "received_events_url": "https://api.github.com/users/octocat/received_events", "type": "User", "site_admin": false } ], "milestone": { "url": "https://api.github.com/repos/octocat/Hello-World/milestones/1", "html_url": "https://github.com/octocat/Hello-World/milestones/v1.0", "labels_url": "https://api.github.com/repos/octocat/Hello-World/milestones/1/labels", "id": 1002604, "node_id": "MDk6TWlsZXN0b25lMTAwMjYwNA==", "number": 1, "state": "open", "title": "v1.0", "description": "Tracking milestone for version 1.0", "creator": { "login": "octocat", "id": 1, "node_id": "MDQ6VXNlcjE=", "avatar_url": "https://github.com/images/error/octocat_happy.gif", "gravatar_id": "", "url": "https://api.github.com/users/octocat", "html_url": "https://github.com/octocat", "followers_url": "https://api.github.com/users/octocat/followers", "following_url": "https://api.github.com/users/octocat/following{/other_user}", "gists_url": "https://api.github.com/users/octocat/gists{/gist_id}", "starred_url": "https://api.github.com/users/octocat/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/octocat/subscriptions", "organizations_url": "https://api.github.com/users/octocat/orgs", "repos_url": "https://api.github.com/users/octocat/repos", "events_url": "https://api.github.com/users/octocat/events{/privacy}", "received_events_url": "https://api.github.com/users/octocat/received_events", "type": "User", "site_admin": false }, "open_issues": 4, "closed_issues": 8, "created_at": "2011-04-10T20:09:31Z", "updated_at": "2014-03-03T18:58:10Z", "closed_at": "2013-02-12T13:22:01Z", "due_on": "2012-10-09T23:39:01Z" }, "locked": true, "active_lock_reason": "too heated", "comments": 0, "pull_request": { "url": "https://api.github.com/repos/octocat/Hello-World/pulls/1347", "html_url": "https://github.com/octocat/Hello-World/pull/1347", "diff_url": "https://github.com/octocat/Hello-World/pull/1347.diff", "patch_url": "https://github.com/octocat/Hello-World/pull/1347.patch" }, "closed_at": null, "created_at": "2011-04-22T13:33:48Z", "updated_at": "2011-04-22T13:33:48Z", "author_association": "COLLABORATOR" } } ] }, "issue-event": { "value": { "id": 1, "node_id": "MDEwOklzc3VlRXZlbnQx", "url": "https://api.github.com/repos/octocat/Hello-World/issues/events/1", "actor": { "login": "octocat", "id": 1, "node_id": "MDQ6VXNlcjE=", "avatar_url": "https://github.com/images/error/octocat_happy.gif", "gravatar_id": "", "url": "https://api.github.com/users/octocat", "html_url": "https://github.com/octocat", "followers_url": "https://api.github.com/users/octocat/followers", "following_url": "https://api.github.com/users/octocat/following{/other_user}", "gists_url": "https://api.github.com/users/octocat/gists{/gist_id}", "starred_url": "https://api.github.com/users/octocat/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/octocat/subscriptions", "organizations_url": "https://api.github.com/users/octocat/orgs", "repos_url": "https://api.github.com/users/octocat/repos", "events_url": "https://api.github.com/users/octocat/events{/privacy}", "received_events_url": "https://api.github.com/users/octocat/received_events", "type": "User", "site_admin": false }, "event": "closed", "commit_id": "6dcb09b5b57875f334f61aebed695e2e4193db5e", "commit_url": "https://api.github.com/repos/octocat/Hello-World/commits/6dcb09b5b57875f334f61aebed695e2e4193db5e", "created_at": "2011-04-14T16:00:49Z", "issue": { "id": 1, "node_id": "MDU6SXNzdWUx", "url": "https://api.github.com/repos/octocat/Hello-World/issues/1347", "repository_url": "https://api.github.com/repos/octocat/Hello-World", "labels_url": "https://api.github.com/repos/octocat/Hello-World/issues/1347/labels{/name}", "comments_url": "https://api.github.com/repos/octocat/Hello-World/issues/1347/comments", "events_url": "https://api.github.com/repos/octocat/Hello-World/issues/1347/events", "html_url": "https://github.com/octocat/Hello-World/issues/1347", "number": 1347, "state": "open", "title": "Found a bug", "body": "I'm having a problem with this.", "user": { "login": "octocat", "id": 1, "node_id": "MDQ6VXNlcjE=", "avatar_url": "https://github.com/images/error/octocat_happy.gif", "gravatar_id": "", "url": "https://api.github.com/users/octocat", "html_url": "https://github.com/octocat", "followers_url": "https://api.github.com/users/octocat/followers", "following_url": "https://api.github.com/users/octocat/following{/other_user}", "gists_url": "https://api.github.com/users/octocat/gists{/gist_id}", "starred_url": "https://api.github.com/users/octocat/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/octocat/subscriptions", "organizations_url": "https://api.github.com/users/octocat/orgs", "repos_url": "https://api.github.com/users/octocat/repos", "events_url": "https://api.github.com/users/octocat/events{/privacy}", "received_events_url": "https://api.github.com/users/octocat/received_events", "type": "User", "site_admin": false }, "labels": [ { "id": 208045946, "node_id": "MDU6TGFiZWwyMDgwNDU5NDY=", "url": "https://api.github.com/repos/octocat/Hello-World/labels/bug", "name": "bug", "description": "Something isn't working", "color": "f29513", "default": true } ], "assignee": { "login": "octocat", "id": 1, "node_id": "MDQ6VXNlcjE=", "avatar_url": "https://github.com/images/error/octocat_happy.gif", "gravatar_id": "", "url": "https://api.github.com/users/octocat", "html_url": "https://github.com/octocat", "followers_url": "https://api.github.com/users/octocat/followers", "following_url": "https://api.github.com/users/octocat/following{/other_user}", "gists_url": "https://api.github.com/users/octocat/gists{/gist_id}", "starred_url": "https://api.github.com/users/octocat/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/octocat/subscriptions", "organizations_url": "https://api.github.com/users/octocat/orgs", "repos_url": "https://api.github.com/users/octocat/repos", "events_url": "https://api.github.com/users/octocat/events{/privacy}", "received_events_url": "https://api.github.com/users/octocat/received_events", "type": "User", "site_admin": false }, "assignees": [ { "login": "octocat", "id": 1, "node_id": "MDQ6VXNlcjE=", "avatar_url": "https://github.com/images/error/octocat_happy.gif", "gravatar_id": "", "url": "https://api.github.com/users/octocat", "html_url": "https://github.com/octocat", "followers_url": "https://api.github.com/users/octocat/followers", "following_url": "https://api.github.com/users/octocat/following{/other_user}", "gists_url": "https://api.github.com/users/octocat/gists{/gist_id}", "starred_url": "https://api.github.com/users/octocat/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/octocat/subscriptions", "organizations_url": "https://api.github.com/users/octocat/orgs", "repos_url": "https://api.github.com/users/octocat/repos", "events_url": "https://api.github.com/users/octocat/events{/privacy}", "received_events_url": "https://api.github.com/users/octocat/received_events", "type": "User", "site_admin": false } ], "milestone": { "url": "https://api.github.com/repos/octocat/Hello-World/milestones/1", "html_url": "https://github.com/octocat/Hello-World/milestones/v1.0", "labels_url": "https://api.github.com/repos/octocat/Hello-World/milestones/1/labels", "id": 1002604, "node_id": "MDk6TWlsZXN0b25lMTAwMjYwNA==", "number": 1, "state": "open", "title": "v1.0", "description": "Tracking milestone for version 1.0", "creator": { "login": "octocat", "id": 1, "node_id": "MDQ6VXNlcjE=", "avatar_url": "https://github.com/images/error/octocat_happy.gif", "gravatar_id": "", "url": "https://api.github.com/users/octocat", "html_url": "https://github.com/octocat", "followers_url": "https://api.github.com/users/octocat/followers", "following_url": "https://api.github.com/users/octocat/following{/other_user}", "gists_url": "https://api.github.com/users/octocat/gists{/gist_id}", "starred_url": "https://api.github.com/users/octocat/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/octocat/subscriptions", "organizations_url": "https://api.github.com/users/octocat/orgs", "repos_url": "https://api.github.com/users/octocat/repos", "events_url": "https://api.github.com/users/octocat/events{/privacy}", "received_events_url": "https://api.github.com/users/octocat/received_events", "type": "User", "site_admin": false }, "open_issues": 4, "closed_issues": 8, "created_at": "2011-04-10T20:09:31Z", "updated_at": "2014-03-03T18:58:10Z", "closed_at": "2013-02-12T13:22:01Z", "due_on": "2012-10-09T23:39:01Z" }, "locked": true, "performed_via_github_app": { "id": 1, "slug": "octoapp", "node_id": "MDExOkludGVncmF0aW9uMQ==", "owner": { "login": "github", "id": 1, "node_id": "MDEyOk9yZ2FuaXphdGlvbjE=", "url": "https://api.github.com/orgs/github", "repos_url": "https://api.github.com/orgs/github/repos", "events_url": "https://api.github.com/orgs/github/events", "avatar_url": "https://github.com/images/error/octocat_happy.gif", "gravatar_id": "", "html_url": "https://github.com/octocat", "followers_url": "https://api.github.com/users/octocat/followers", "following_url": "https://api.github.com/users/octocat/following{/other_user}", "gists_url": "https://api.github.com/users/octocat/gists{/gist_id}", "starred_url": "https://api.github.com/users/octocat/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/octocat/subscriptions", "organizations_url": "https://api.github.com/users/octocat/orgs", "received_events_url": "https://api.github.com/users/octocat/received_events", "type": "User", "site_admin": true }, "name": "Octocat App", "description": "", "external_url": "https://example.com", "html_url": "https://github.com/apps/octoapp", "created_at": "2017-07-08T16:18:44-04:00", "updated_at": "2017-07-08T16:18:44-04:00", "permissions": { "metadata": "read", "contents": "read", "issues": "write", "single_file": "write" }, "events": [ "push", "pull_request" ] }, "comments": 0, "pull_request": { "url": "https://api.github.com/repos/octocat/Hello-World/pulls/1347", "html_url": "https://github.com/octocat/Hello-World/pull/1347", "diff_url": "https://github.com/octocat/Hello-World/pull/1347.diff", "patch_url": "https://github.com/octocat/Hello-World/pull/1347.patch" }, "closed_at": null, "created_at": "2011-04-22T13:33:48Z", "updated_at": "2011-04-22T13:33:48Z", "author_association": "COLLABORATOR" } } }, "issue-event-for-issue-items": { "value": [ { "id": 1, "node_id": "MDEwOklzc3VlRXZlbnQx", "url": "https://api.github.com/repos/octocat/Hello-World/issues/events/1", "actor": { "login": "octocat", "id": 1, "node_id": "MDQ6VXNlcjE=", "avatar_url": "https://github.com/images/error/octocat_happy.gif", "gravatar_id": "", "url": "https://api.github.com/users/octocat", "html_url": "https://github.com/octocat", "followers_url": "https://api.github.com/users/octocat/followers", "following_url": "https://api.github.com/users/octocat/following{/other_user}", "gists_url": "https://api.github.com/users/octocat/gists{/gist_id}", "starred_url": "https://api.github.com/users/octocat/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/octocat/subscriptions", "organizations_url": "https://api.github.com/users/octocat/orgs", "repos_url": "https://api.github.com/users/octocat/repos", "events_url": "https://api.github.com/users/octocat/events{/privacy}", "received_events_url": "https://api.github.com/users/octocat/received_events", "type": "User", "site_admin": false }, "event": "closed", "commit_id": "6dcb09b5b57875f334f61aebed695e2e4193db5e", "commit_url": "https://api.github.com/repos/octocat/Hello-World/commits/6dcb09b5b57875f334f61aebed695e2e4193db5e", "created_at": "2011-04-14T16:00:49Z", "performed_via_github_app": null, "label": { "name": "label", "color": "red" } } ] }, "label-items": { "value": [ { "id": 208045946, "node_id": "MDU6TGFiZWwyMDgwNDU5NDY=", "url": "https://api.github.com/repos/octocat/Hello-World/labels/bug", "name": "bug", "description": "Something isn't working", "color": "f29513", "default": true }, { "id": 208045947, "node_id": "MDU6TGFiZWwyMDgwNDU5NDc=", "url": "https://api.github.com/repos/octocat/Hello-World/labels/enhancement", "name": "enhancement", "description": "New feature or request", "color": "a2eeef", "default": false } ] }, "label-items-2": { "value": [ { "id": 208045946, "node_id": "MDU6TGFiZWwyMDgwNDU5NDY=", "url": "https://api.github.com/repos/octocat/Hello-World/labels/bug", "name": "bug", "description": "Something isn't working", "color": "f29513", "default": true } ] }, "deploy-key-items": { "value": [ { "id": 1, "key": "ssh-rsa AAA...", "url": "https://api.github.com/repos/octocat/Hello-World/keys/1", "title": "octocat@octomac", "verified": true, "created_at": "2014-12-10T15:53:42Z", "read_only": true } ] }, "deploy-key": { "value": { "id": 1, "key": "ssh-rsa AAA...", "url": "https://api.github.com/repos/octocat/Hello-World/keys/1", "title": "octocat@octomac", "verified": true, "created_at": "2014-12-10T15:53:42Z", "read_only": true } }, "label": { "value": { "id": 208045946, "node_id": "MDU6TGFiZWwyMDgwNDU5NDY=", "url": "https://api.github.com/repos/octocat/Hello-World/labels/bug", "name": "bug", "description": "Something isn't working", "color": "f29513", "default": true } }, "label-2": { "value": { "id": 208045946, "node_id": "MDU6TGFiZWwyMDgwNDU5NDY=", "url": "https://api.github.com/repos/octocat/Hello-World/labels/bug%20:bug:", "name": "bug :bug:", "description": "Small bug fix required", "color": "b01f26", "default": true } }, "language": { "value": { "C": 78769, "Python": 7769 } }, "license-content": { "value": { "name": "LICENSE", "path": "LICENSE", "sha": "401c59dcc4570b954dd6d345e76199e1f4e76266", "size": 1077, "url": "https://api.github.com/repos/benbalter/gman/contents/LICENSE?ref=master", "html_url": "https://github.com/benbalter/gman/blob/master/LICENSE", "git_url": "https://api.github.com/repos/benbalter/gman/git/blobs/401c59dcc4570b954dd6d345e76199e1f4e76266", "download_url": "https://raw.githubusercontent.com/benbalter/gman/master/LICENSE?lab=true", "type": "file", "content": "VGhlIE1JVCBMaWNlbnNlIChNSVQpCgpDb3B5cmlnaHQgKGMpIDIwMTMgQmVu\nIEJhbHRlcgoKUGVybWlzc2lvbiBpcyBoZXJlYnkgZ3JhbnRlZCwgZnJlZSBv\nZiBjaGFyZ2UsIHRvIGFueSBwZXJzb24gb2J0YWluaW5nIGEgY29weSBvZgp0\naGlzIHNvZnR3YXJlIGFuZCBhc3NvY2lhdGVkIGRvY3VtZW50YXRpb24gZmls\nZXMgKHRoZSAiU29mdHdhcmUiKSwgdG8gZGVhbCBpbgp0aGUgU29mdHdhcmUg\nd2l0aG91dCByZXN0cmljdGlvbiwgaW5jbHVkaW5nIHdpdGhvdXQgbGltaXRh\ndGlvbiB0aGUgcmlnaHRzIHRvCnVzZSwgY29weSwgbW9kaWZ5LCBtZXJnZSwg\ncHVibGlzaCwgZGlzdHJpYnV0ZSwgc3VibGljZW5zZSwgYW5kL29yIHNlbGwg\nY29waWVzIG9mCnRoZSBTb2Z0d2FyZSwgYW5kIHRvIHBlcm1pdCBwZXJzb25z\nIHRvIHdob20gdGhlIFNvZnR3YXJlIGlzIGZ1cm5pc2hlZCB0byBkbyBzbywK\nc3ViamVjdCB0byB0aGUgZm9sbG93aW5nIGNvbmRpdGlvbnM6CgpUaGUgYWJv\ndmUgY29weXJpZ2h0IG5vdGljZSBhbmQgdGhpcyBwZXJtaXNzaW9uIG5vdGlj\nZSBzaGFsbCBiZSBpbmNsdWRlZCBpbiBhbGwKY29waWVzIG9yIHN1YnN0YW50\naWFsIHBvcnRpb25zIG9mIHRoZSBTb2Z0d2FyZS4KClRIRSBTT0ZUV0FSRSBJ\nUyBQUk9WSURFRCAiQVMgSVMiLCBXSVRIT1VUIFdBUlJBTlRZIE9GIEFOWSBL\nSU5ELCBFWFBSRVNTIE9SCklNUExJRUQsIElOQ0xVRElORyBCVVQgTk9UIExJ\nTUlURUQgVE8gVEhFIFdBUlJBTlRJRVMgT0YgTUVSQ0hBTlRBQklMSVRZLCBG\nSVRORVNTCkZPUiBBIFBBUlRJQ1VMQVIgUFVSUE9TRSBBTkQgTk9OSU5GUklO\nR0VNRU5ULiBJTiBOTyBFVkVOVCBTSEFMTCBUSEUgQVVUSE9SUyBPUgpDT1BZ\nUklHSFQgSE9MREVSUyBCRSBMSUFCTEUgRk9SIEFOWSBDTEFJTSwgREFNQUdF\nUyBPUiBPVEhFUiBMSUFCSUxJVFksIFdIRVRIRVIKSU4gQU4gQUNUSU9OIE9G\nIENPTlRSQUNULCBUT1JUIE9SIE9USEVSV0lTRSwgQVJJU0lORyBGUk9NLCBP\nVVQgT0YgT1IgSU4KQ09OTkVDVElPTiBXSVRIIFRIRSBTT0ZUV0FSRSBPUiBU\nSEUgVVNFIE9SIE9USEVSIERFQUxJTkdTIElOIFRIRSBTT0ZUV0FSRS4K\n", "encoding": "base64", "_links": { "self": "https://api.github.com/repos/benbalter/gman/contents/LICENSE?ref=master", "git": "https://api.github.com/repos/benbalter/gman/git/blobs/401c59dcc4570b954dd6d345e76199e1f4e76266", "html": "https://github.com/benbalter/gman/blob/master/LICENSE" }, "license": { "key": "mit", "name": "MIT License", "spdx_id": "MIT", "url": "https://api.github.com/licenses/mit", "node_id": "MDc6TGljZW5zZW1pdA==" } } }, "milestone-items": { "value": [ { "url": "https://api.github.com/repos/octocat/Hello-World/milestones/1", "html_url": "https://github.com/octocat/Hello-World/milestones/v1.0", "labels_url": "https://api.github.com/repos/octocat/Hello-World/milestones/1/labels", "id": 1002604, "node_id": "MDk6TWlsZXN0b25lMTAwMjYwNA==", "number": 1, "state": "open", "title": "v1.0", "description": "Tracking milestone for version 1.0", "creator": { "login": "octocat", "id": 1, "node_id": "MDQ6VXNlcjE=", "avatar_url": "https://github.com/images/error/octocat_happy.gif", "gravatar_id": "", "url": "https://api.github.com/users/octocat", "html_url": "https://github.com/octocat", "followers_url": "https://api.github.com/users/octocat/followers", "following_url": "https://api.github.com/users/octocat/following{/other_user}", "gists_url": "https://api.github.com/users/octocat/gists{/gist_id}", "starred_url": "https://api.github.com/users/octocat/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/octocat/subscriptions", "organizations_url": "https://api.github.com/users/octocat/orgs", "repos_url": "https://api.github.com/users/octocat/repos", "events_url": "https://api.github.com/users/octocat/events{/privacy}", "received_events_url": "https://api.github.com/users/octocat/received_events", "type": "User", "site_admin": false }, "open_issues": 4, "closed_issues": 8, "created_at": "2011-04-10T20:09:31Z", "updated_at": "2014-03-03T18:58:10Z", "closed_at": "2013-02-12T13:22:01Z", "due_on": "2012-10-09T23:39:01Z" } ] }, "milestone": { "value": { "url": "https://api.github.com/repos/octocat/Hello-World/milestones/1", "html_url": "https://github.com/octocat/Hello-World/milestones/v1.0", "labels_url": "https://api.github.com/repos/octocat/Hello-World/milestones/1/labels", "id": 1002604, "node_id": "MDk6TWlsZXN0b25lMTAwMjYwNA==", "number": 1, "state": "open", "title": "v1.0", "description": "Tracking milestone for version 1.0", "creator": { "login": "octocat", "id": 1, "node_id": "MDQ6VXNlcjE=", "avatar_url": "https://github.com/images/error/octocat_happy.gif", "gravatar_id": "", "url": "https://api.github.com/users/octocat", "html_url": "https://github.com/octocat", "followers_url": "https://api.github.com/users/octocat/followers", "following_url": "https://api.github.com/users/octocat/following{/other_user}", "gists_url": "https://api.github.com/users/octocat/gists{/gist_id}", "starred_url": "https://api.github.com/users/octocat/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/octocat/subscriptions", "organizations_url": "https://api.github.com/users/octocat/orgs", "repos_url": "https://api.github.com/users/octocat/repos", "events_url": "https://api.github.com/users/octocat/events{/privacy}", "received_events_url": "https://api.github.com/users/octocat/received_events", "type": "User", "site_admin": false }, "open_issues": 4, "closed_issues": 8, "created_at": "2011-04-10T20:09:31Z", "updated_at": "2014-03-03T18:58:10Z", "closed_at": "2013-02-12T13:22:01Z", "due_on": "2012-10-09T23:39:01Z" } }, "page": { "value": { "url": "https://api.github.com/repos/github/developer.github.com/pages", "status": "built", "cname": "developer.github.com", "custom_404": false, "html_url": "https://developer.github.com", "source": { "branch": "master", "path": "/" }, "public": true, "https_certificate": { "state": "approved", "description": "Certificate is approved", "domains": [ "developer.github.com" ], "expires_at": "2021-05-22" }, "https_enforced": true } }, "page-build-items": { "value": [ { "url": "https://api.github.com/repos/github/developer.github.com/pages/builds/5472601", "status": "built", "error": { "message": null }, "pusher": { "login": "octocat", "id": 1, "node_id": "MDQ6VXNlcjE=", "avatar_url": "https://github.com/images/error/octocat_happy.gif", "gravatar_id": "", "url": "https://api.github.com/users/octocat", "html_url": "https://github.com/octocat", "followers_url": "https://api.github.com/users/octocat/followers", "following_url": "https://api.github.com/users/octocat/following{/other_user}", "gists_url": "https://api.github.com/users/octocat/gists{/gist_id}", "starred_url": "https://api.github.com/users/octocat/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/octocat/subscriptions", "organizations_url": "https://api.github.com/users/octocat/orgs", "repos_url": "https://api.github.com/users/octocat/repos", "events_url": "https://api.github.com/users/octocat/events{/privacy}", "received_events_url": "https://api.github.com/users/octocat/received_events", "type": "User", "site_admin": false }, "commit": "351391cdcb88ffae71ec3028c91f375a8036a26b", "duration": 2104, "created_at": "2014-02-10T19:00:49Z", "updated_at": "2014-02-10T19:00:51Z" } ] }, "page-build-status": { "value": { "url": "https://api.github.com/repos/github/developer.github.com/pages/builds/latest", "status": "queued" } }, "page-build": { "value": { "url": "https://api.github.com/repos/github/developer.github.com/pages/builds/5472601", "status": "built", "error": { "message": null }, "pusher": { "login": "octocat", "id": 1, "node_id": "MDQ6VXNlcjE=", "avatar_url": "https://github.com/images/error/octocat_happy.gif", "gravatar_id": "", "url": "https://api.github.com/users/octocat", "html_url": "https://github.com/octocat", "followers_url": "https://api.github.com/users/octocat/followers", "following_url": "https://api.github.com/users/octocat/following{/other_user}", "gists_url": "https://api.github.com/users/octocat/gists{/gist_id}", "starred_url": "https://api.github.com/users/octocat/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/octocat/subscriptions", "organizations_url": "https://api.github.com/users/octocat/orgs", "repos_url": "https://api.github.com/users/octocat/repos", "events_url": "https://api.github.com/users/octocat/events{/privacy}", "received_events_url": "https://api.github.com/users/octocat/received_events", "type": "User", "site_admin": false }, "commit": "351391cdcb88ffae71ec3028c91f375a8036a26b", "duration": 2104, "created_at": "2014-02-10T19:00:49Z", "updated_at": "2014-02-10T19:00:51Z" } }, "repository-pre-receive-hook-items": { "value": [ { "id": 42, "name": "Check Commits", "enforcement": "disabled", "configuration_url": "https://github.example.com/api/v3/orgs/octocat/pre-receive-hooks/42" } ] }, "repository-pre-receive-hook": { "value": { "id": 42, "name": "Check Commits", "enforcement": "disabled", "configuration_url": "https://github.example.com/api/v3/orgs/octocat/pre-receive-hooks/42" } }, "repository-pre-receive-hook-2": { "value": { "id": 42, "name": "Check Commits", "enforcement": "enabled", "configuration_url": "https://github.example.com/api/v3/repos/octocat/hello-world/pre-receive-hooks/42" } }, "project-items-2": { "value": [ { "owner_url": "https://api.github.com/repos/api-playground/projects-test", "url": "https://api.github.com/projects/1002604", "html_url": "https://github.com/api-playground/projects-test/projects/1", "columns_url": "https://api.github.com/projects/1002604/columns", "id": 1002604, "node_id": "MDc6UHJvamVjdDEwMDI2MDQ=", "name": "Projects Documentation", "body": "Developer documentation project for the developer site.", "number": 1, "state": "open", "creator": { "login": "octocat", "id": 1, "node_id": "MDQ6VXNlcjE=", "avatar_url": "https://github.com/images/error/octocat_happy.gif", "gravatar_id": "", "url": "https://api.github.com/users/octocat", "html_url": "https://github.com/octocat", "followers_url": "https://api.github.com/users/octocat/followers", "following_url": "https://api.github.com/users/octocat/following{/other_user}", "gists_url": "https://api.github.com/users/octocat/gists{/gist_id}", "starred_url": "https://api.github.com/users/octocat/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/octocat/subscriptions", "organizations_url": "https://api.github.com/users/octocat/orgs", "repos_url": "https://api.github.com/users/octocat/repos", "events_url": "https://api.github.com/users/octocat/events{/privacy}", "received_events_url": "https://api.github.com/users/octocat/received_events", "type": "User", "site_admin": false }, "created_at": "2011-04-10T20:09:31Z", "updated_at": "2014-03-03T18:58:10Z" } ] }, "pull-request": { "value": { "url": "https://api.github.com/repos/octocat/Hello-World/pulls/1347", "id": 1, "node_id": "MDExOlB1bGxSZXF1ZXN0MQ==", "html_url": "https://github.com/octocat/Hello-World/pull/1347", "diff_url": "https://github.com/octocat/Hello-World/pull/1347.diff", "patch_url": "https://github.com/octocat/Hello-World/pull/1347.patch", "issue_url": "https://api.github.com/repos/octocat/Hello-World/issues/1347", "commits_url": "https://api.github.com/repos/octocat/Hello-World/pulls/1347/commits", "review_comments_url": "https://api.github.com/repos/octocat/Hello-World/pulls/1347/comments", "review_comment_url": "https://api.github.com/repos/octocat/Hello-World/pulls/comments{/number}", "comments_url": "https://api.github.com/repos/octocat/Hello-World/issues/1347/comments", "statuses_url": "https://api.github.com/repos/octocat/Hello-World/statuses/6dcb09b5b57875f334f61aebed695e2e4193db5e", "number": 1347, "state": "open", "locked": true, "title": "Amazing new feature", "user": { "login": "octocat", "id": 1, "node_id": "MDQ6VXNlcjE=", "avatar_url": "https://github.com/images/error/octocat_happy.gif", "gravatar_id": "", "url": "https://api.github.com/users/octocat", "html_url": "https://github.com/octocat", "followers_url": "https://api.github.com/users/octocat/followers", "following_url": "https://api.github.com/users/octocat/following{/other_user}", "gists_url": "https://api.github.com/users/octocat/gists{/gist_id}", "starred_url": "https://api.github.com/users/octocat/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/octocat/subscriptions", "organizations_url": "https://api.github.com/users/octocat/orgs", "repos_url": "https://api.github.com/users/octocat/repos", "events_url": "https://api.github.com/users/octocat/events{/privacy}", "received_events_url": "https://api.github.com/users/octocat/received_events", "type": "User", "site_admin": false }, "body": "Please pull these awesome changes in!", "labels": [ { "id": 208045946, "node_id": "MDU6TGFiZWwyMDgwNDU5NDY=", "url": "https://api.github.com/repos/octocat/Hello-World/labels/bug", "name": "bug", "description": "Something isn't working", "color": "f29513", "default": true } ], "milestone": { "url": "https://api.github.com/repos/octocat/Hello-World/milestones/1", "html_url": "https://github.com/octocat/Hello-World/milestones/v1.0", "labels_url": "https://api.github.com/repos/octocat/Hello-World/milestones/1/labels", "id": 1002604, "node_id": "MDk6TWlsZXN0b25lMTAwMjYwNA==", "number": 1, "state": "open", "title": "v1.0", "description": "Tracking milestone for version 1.0", "creator": { "login": "octocat", "id": 1, "node_id": "MDQ6VXNlcjE=", "avatar_url": "https://github.com/images/error/octocat_happy.gif", "gravatar_id": "", "url": "https://api.github.com/users/octocat", "html_url": "https://github.com/octocat", "followers_url": "https://api.github.com/users/octocat/followers", "following_url": "https://api.github.com/users/octocat/following{/other_user}", "gists_url": "https://api.github.com/users/octocat/gists{/gist_id}", "starred_url": "https://api.github.com/users/octocat/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/octocat/subscriptions", "organizations_url": "https://api.github.com/users/octocat/orgs", "repos_url": "https://api.github.com/users/octocat/repos", "events_url": "https://api.github.com/users/octocat/events{/privacy}", "received_events_url": "https://api.github.com/users/octocat/received_events", "type": "User", "site_admin": false }, "open_issues": 4, "closed_issues": 8, "created_at": "2011-04-10T20:09:31Z", "updated_at": "2014-03-03T18:58:10Z", "closed_at": "2013-02-12T13:22:01Z", "due_on": "2012-10-09T23:39:01Z" }, "active_lock_reason": "too heated", "created_at": "2011-01-26T19:01:12Z", "updated_at": "2011-01-26T19:01:12Z", "closed_at": "2011-01-26T19:01:12Z", "merged_at": "2011-01-26T19:01:12Z", "merge_commit_sha": "e5bd3914e2e596debea16f433f57875b5b90bcd6", "assignee": { "login": "octocat", "id": 1, "node_id": "MDQ6VXNlcjE=", "avatar_url": "https://github.com/images/error/octocat_happy.gif", "gravatar_id": "", "url": "https://api.github.com/users/octocat", "html_url": "https://github.com/octocat", "followers_url": "https://api.github.com/users/octocat/followers", "following_url": "https://api.github.com/users/octocat/following{/other_user}", "gists_url": "https://api.github.com/users/octocat/gists{/gist_id}", "starred_url": "https://api.github.com/users/octocat/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/octocat/subscriptions", "organizations_url": "https://api.github.com/users/octocat/orgs", "repos_url": "https://api.github.com/users/octocat/repos", "events_url": "https://api.github.com/users/octocat/events{/privacy}", "received_events_url": "https://api.github.com/users/octocat/received_events", "type": "User", "site_admin": false }, "assignees": [ { "login": "octocat", "id": 1, "node_id": "MDQ6VXNlcjE=", "avatar_url": "https://github.com/images/error/octocat_happy.gif", "gravatar_id": "", "url": "https://api.github.com/users/octocat", "html_url": "https://github.com/octocat", "followers_url": "https://api.github.com/users/octocat/followers", "following_url": "https://api.github.com/users/octocat/following{/other_user}", "gists_url": "https://api.github.com/users/octocat/gists{/gist_id}", "starred_url": "https://api.github.com/users/octocat/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/octocat/subscriptions", "organizations_url": "https://api.github.com/users/octocat/orgs", "repos_url": "https://api.github.com/users/octocat/repos", "events_url": "https://api.github.com/users/octocat/events{/privacy}", "received_events_url": "https://api.github.com/users/octocat/received_events", "type": "User", "site_admin": false }, { "login": "hubot", "id": 1, "node_id": "MDQ6VXNlcjE=", "avatar_url": "https://github.com/images/error/hubot_happy.gif", "gravatar_id": "", "url": "https://api.github.com/users/hubot", "html_url": "https://github.com/hubot", "followers_url": "https://api.github.com/users/hubot/followers", "following_url": "https://api.github.com/users/hubot/following{/other_user}", "gists_url": "https://api.github.com/users/hubot/gists{/gist_id}", "starred_url": "https://api.github.com/users/hubot/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/hubot/subscriptions", "organizations_url": "https://api.github.com/users/hubot/orgs", "repos_url": "https://api.github.com/users/hubot/repos", "events_url": "https://api.github.com/users/hubot/events{/privacy}", "received_events_url": "https://api.github.com/users/hubot/received_events", "type": "User", "site_admin": true } ], "requested_reviewers": [ { "login": "other_user", "id": 1, "node_id": "MDQ6VXNlcjE=", "avatar_url": "https://github.com/images/error/other_user_happy.gif", "gravatar_id": "", "url": "https://api.github.com/users/other_user", "html_url": "https://github.com/other_user", "followers_url": "https://api.github.com/users/other_user/followers", "following_url": "https://api.github.com/users/other_user/following{/other_user}", "gists_url": "https://api.github.com/users/other_user/gists{/gist_id}", "starred_url": "https://api.github.com/users/other_user/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/other_user/subscriptions", "organizations_url": "https://api.github.com/users/other_user/orgs", "repos_url": "https://api.github.com/users/other_user/repos", "events_url": "https://api.github.com/users/other_user/events{/privacy}", "received_events_url": "https://api.github.com/users/other_user/received_events", "type": "User", "site_admin": false } ], "requested_teams": [ { "id": 1, "node_id": "MDQ6VGVhbTE=", "url": "https://api.github.com/teams/1", "html_url": "https://github.com/orgs/github/teams/justice-league", "name": "Justice League", "slug": "justice-league", "description": "A great team.", "privacy": "closed", "permission": "admin", "members_url": "https://api.github.com/teams/1/members{/member}", "repositories_url": "https://api.github.com/teams/1/repos" } ], "head": { "label": "octocat:new-topic", "ref": "new-topic", "sha": "6dcb09b5b57875f334f61aebed695e2e4193db5e", "user": { "login": "octocat", "id": 1, "node_id": "MDQ6VXNlcjE=", "avatar_url": "https://github.com/images/error/octocat_happy.gif", "gravatar_id": "", "url": "https://api.github.com/users/octocat", "html_url": "https://github.com/octocat", "followers_url": "https://api.github.com/users/octocat/followers", "following_url": "https://api.github.com/users/octocat/following{/other_user}", "gists_url": "https://api.github.com/users/octocat/gists{/gist_id}", "starred_url": "https://api.github.com/users/octocat/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/octocat/subscriptions", "organizations_url": "https://api.github.com/users/octocat/orgs", "repos_url": "https://api.github.com/users/octocat/repos", "events_url": "https://api.github.com/users/octocat/events{/privacy}", "received_events_url": "https://api.github.com/users/octocat/received_events", "type": "User", "site_admin": false }, "repo": { "id": 1296269, "node_id": "MDEwOlJlcG9zaXRvcnkxMjk2MjY5", "name": "Hello-World", "full_name": "octocat/Hello-World", "owner": { "login": "octocat", "id": 1, "node_id": "MDQ6VXNlcjE=", "avatar_url": "https://github.com/images/error/octocat_happy.gif", "gravatar_id": "", "url": "https://api.github.com/users/octocat", "html_url": "https://github.com/octocat", "followers_url": "https://api.github.com/users/octocat/followers", "following_url": "https://api.github.com/users/octocat/following{/other_user}", "gists_url": "https://api.github.com/users/octocat/gists{/gist_id}", "starred_url": "https://api.github.com/users/octocat/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/octocat/subscriptions", "organizations_url": "https://api.github.com/users/octocat/orgs", "repos_url": "https://api.github.com/users/octocat/repos", "events_url": "https://api.github.com/users/octocat/events{/privacy}", "received_events_url": "https://api.github.com/users/octocat/received_events", "type": "User", "site_admin": false }, "private": false, "html_url": "https://github.com/octocat/Hello-World", "description": "This your first repo!", "fork": false, "url": "https://api.github.com/repos/octocat/Hello-World", "archive_url": "https://api.github.com/repos/octocat/Hello-World/{archive_format}{/ref}", "assignees_url": "https://api.github.com/repos/octocat/Hello-World/assignees{/user}", "blobs_url": "https://api.github.com/repos/octocat/Hello-World/git/blobs{/sha}", "branches_url": "https://api.github.com/repos/octocat/Hello-World/branches{/branch}", "collaborators_url": "https://api.github.com/repos/octocat/Hello-World/collaborators{/collaborator}", "comments_url": "https://api.github.com/repos/octocat/Hello-World/comments{/number}", "commits_url": "https://api.github.com/repos/octocat/Hello-World/commits{/sha}", "compare_url": "https://api.github.com/repos/octocat/Hello-World/compare/{base}...{head}", "contents_url": "https://api.github.com/repos/octocat/Hello-World/contents/{+path}", "contributors_url": "https://api.github.com/repos/octocat/Hello-World/contributors", "deployments_url": "https://api.github.com/repos/octocat/Hello-World/deployments", "downloads_url": "https://api.github.com/repos/octocat/Hello-World/downloads", "events_url": "https://api.github.com/repos/octocat/Hello-World/events", "forks_url": "https://api.github.com/repos/octocat/Hello-World/forks", "git_commits_url": "https://api.github.com/repos/octocat/Hello-World/git/commits{/sha}", "git_refs_url": "https://api.github.com/repos/octocat/Hello-World/git/refs{/sha}", "git_tags_url": "https://api.github.com/repos/octocat/Hello-World/git/tags{/sha}", "git_url": "git:github.com/octocat/Hello-World.git", "issue_comment_url": "https://api.github.com/repos/octocat/Hello-World/issues/comments{/number}", "issue_events_url": "https://api.github.com/repos/octocat/Hello-World/issues/events{/number}", "issues_url": "https://api.github.com/repos/octocat/Hello-World/issues{/number}", "keys_url": "https://api.github.com/repos/octocat/Hello-World/keys{/key_id}", "labels_url": "https://api.github.com/repos/octocat/Hello-World/labels{/name}", "languages_url": "https://api.github.com/repos/octocat/Hello-World/languages", "merges_url": "https://api.github.com/repos/octocat/Hello-World/merges", "milestones_url": "https://api.github.com/repos/octocat/Hello-World/milestones{/number}", "notifications_url": "https://api.github.com/repos/octocat/Hello-World/notifications{?since,all,participating}", "pulls_url": "https://api.github.com/repos/octocat/Hello-World/pulls{/number}", "releases_url": "https://api.github.com/repos/octocat/Hello-World/releases{/id}", "ssh_url": "git@github.com:octocat/Hello-World.git", "stargazers_url": "https://api.github.com/repos/octocat/Hello-World/stargazers", "statuses_url": "https://api.github.com/repos/octocat/Hello-World/statuses/{sha}", "subscribers_url": "https://api.github.com/repos/octocat/Hello-World/subscribers", "subscription_url": "https://api.github.com/repos/octocat/Hello-World/subscription", "tags_url": "https://api.github.com/repos/octocat/Hello-World/tags", "teams_url": "https://api.github.com/repos/octocat/Hello-World/teams", "trees_url": "https://api.github.com/repos/octocat/Hello-World/git/trees{/sha}", "clone_url": "https://github.com/octocat/Hello-World.git", "mirror_url": "git:git.example.com/octocat/Hello-World", "hooks_url": "https://api.github.com/repos/octocat/Hello-World/hooks", "svn_url": "https://svn.github.com/octocat/Hello-World", "homepage": "https://github.com", "language": null, "forks_count": 9, "stargazers_count": 80, "watchers_count": 80, "size": 108, "default_branch": "master", "open_issues_count": 0, "topics": [ "octocat", "atom", "electron", "api" ], "has_issues": true, "has_projects": true, "has_wiki": true, "has_pages": false, "has_downloads": true, "archived": false, "disabled": false, "pushed_at": "2011-01-26T19:06:43Z", "created_at": "2011-01-26T19:01:12Z", "updated_at": "2011-01-26T19:14:43Z", "permissions": { "admin": false, "push": false, "pull": true }, "allow_rebase_merge": true, "temp_clone_token": "ABTLWHOULUVAXGTRYU7OC2876QJ2O", "allow_squash_merge": true, "allow_merge_commit": true, "allow_forking": true, "forks": 123, "open_issues": 123, "license": { "key": "mit", "name": "MIT License", "url": "https://api.github.com/licenses/mit", "spdx_id": "MIT", "node_id": "MDc6TGljZW5zZW1pdA==" }, "watchers": 123 } }, "base": { "label": "octocat:master", "ref": "master", "sha": "6dcb09b5b57875f334f61aebed695e2e4193db5e", "user": { "login": "octocat", "id": 1, "node_id": "MDQ6VXNlcjE=", "avatar_url": "https://github.com/images/error/octocat_happy.gif", "gravatar_id": "", "url": "https://api.github.com/users/octocat", "html_url": "https://github.com/octocat", "followers_url": "https://api.github.com/users/octocat/followers", "following_url": "https://api.github.com/users/octocat/following{/other_user}", "gists_url": "https://api.github.com/users/octocat/gists{/gist_id}", "starred_url": "https://api.github.com/users/octocat/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/octocat/subscriptions", "organizations_url": "https://api.github.com/users/octocat/orgs", "repos_url": "https://api.github.com/users/octocat/repos", "events_url": "https://api.github.com/users/octocat/events{/privacy}", "received_events_url": "https://api.github.com/users/octocat/received_events", "type": "User", "site_admin": false }, "repo": { "id": 1296269, "node_id": "MDEwOlJlcG9zaXRvcnkxMjk2MjY5", "name": "Hello-World", "full_name": "octocat/Hello-World", "owner": { "login": "octocat", "id": 1, "node_id": "MDQ6VXNlcjE=", "avatar_url": "https://github.com/images/error/octocat_happy.gif", "gravatar_id": "", "url": "https://api.github.com/users/octocat", "html_url": "https://github.com/octocat", "followers_url": "https://api.github.com/users/octocat/followers", "following_url": "https://api.github.com/users/octocat/following{/other_user}", "gists_url": "https://api.github.com/users/octocat/gists{/gist_id}", "starred_url": "https://api.github.com/users/octocat/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/octocat/subscriptions", "organizations_url": "https://api.github.com/users/octocat/orgs", "repos_url": "https://api.github.com/users/octocat/repos", "events_url": "https://api.github.com/users/octocat/events{/privacy}", "received_events_url": "https://api.github.com/users/octocat/received_events", "type": "User", "site_admin": false }, "private": false, "html_url": "https://github.com/octocat/Hello-World", "description": "This your first repo!", "fork": false, "url": "https://api.github.com/repos/octocat/Hello-World", "archive_url": "https://api.github.com/repos/octocat/Hello-World/{archive_format}{/ref}", "assignees_url": "https://api.github.com/repos/octocat/Hello-World/assignees{/user}", "blobs_url": "https://api.github.com/repos/octocat/Hello-World/git/blobs{/sha}", "branches_url": "https://api.github.com/repos/octocat/Hello-World/branches{/branch}", "collaborators_url": "https://api.github.com/repos/octocat/Hello-World/collaborators{/collaborator}", "comments_url": "https://api.github.com/repos/octocat/Hello-World/comments{/number}", "commits_url": "https://api.github.com/repos/octocat/Hello-World/commits{/sha}", "compare_url": "https://api.github.com/repos/octocat/Hello-World/compare/{base}...{head}", "contents_url": "https://api.github.com/repos/octocat/Hello-World/contents/{+path}", "contributors_url": "https://api.github.com/repos/octocat/Hello-World/contributors", "deployments_url": "https://api.github.com/repos/octocat/Hello-World/deployments", "downloads_url": "https://api.github.com/repos/octocat/Hello-World/downloads", "events_url": "https://api.github.com/repos/octocat/Hello-World/events", "forks_url": "https://api.github.com/repos/octocat/Hello-World/forks", "git_commits_url": "https://api.github.com/repos/octocat/Hello-World/git/commits{/sha}", "git_refs_url": "https://api.github.com/repos/octocat/Hello-World/git/refs{/sha}", "git_tags_url": "https://api.github.com/repos/octocat/Hello-World/git/tags{/sha}", "git_url": "git:github.com/octocat/Hello-World.git", "issue_comment_url": "https://api.github.com/repos/octocat/Hello-World/issues/comments{/number}", "issue_events_url": "https://api.github.com/repos/octocat/Hello-World/issues/events{/number}", "issues_url": "https://api.github.com/repos/octocat/Hello-World/issues{/number}", "keys_url": "https://api.github.com/repos/octocat/Hello-World/keys{/key_id}", "labels_url": "https://api.github.com/repos/octocat/Hello-World/labels{/name}", "languages_url": "https://api.github.com/repos/octocat/Hello-World/languages", "merges_url": "https://api.github.com/repos/octocat/Hello-World/merges", "milestones_url": "https://api.github.com/repos/octocat/Hello-World/milestones{/number}", "notifications_url": "https://api.github.com/repos/octocat/Hello-World/notifications{?since,all,participating}", "pulls_url": "https://api.github.com/repos/octocat/Hello-World/pulls{/number}", "releases_url": "https://api.github.com/repos/octocat/Hello-World/releases{/id}", "ssh_url": "git@github.com:octocat/Hello-World.git", "stargazers_url": "https://api.github.com/repos/octocat/Hello-World/stargazers", "statuses_url": "https://api.github.com/repos/octocat/Hello-World/statuses/{sha}", "subscribers_url": "https://api.github.com/repos/octocat/Hello-World/subscribers", "subscription_url": "https://api.github.com/repos/octocat/Hello-World/subscription", "tags_url": "https://api.github.com/repos/octocat/Hello-World/tags", "teams_url": "https://api.github.com/repos/octocat/Hello-World/teams", "trees_url": "https://api.github.com/repos/octocat/Hello-World/git/trees{/sha}", "clone_url": "https://github.com/octocat/Hello-World.git", "mirror_url": "git:git.example.com/octocat/Hello-World", "hooks_url": "https://api.github.com/repos/octocat/Hello-World/hooks", "svn_url": "https://svn.github.com/octocat/Hello-World", "homepage": "https://github.com", "language": null, "forks_count": 9, "stargazers_count": 80, "watchers_count": 80, "size": 108, "default_branch": "master", "open_issues_count": 0, "topics": [ "octocat", "atom", "electron", "api" ], "has_issues": true, "has_projects": true, "has_wiki": true, "has_pages": false, "has_downloads": true, "archived": false, "disabled": false, "pushed_at": "2011-01-26T19:06:43Z", "created_at": "2011-01-26T19:01:12Z", "updated_at": "2011-01-26T19:14:43Z", "permissions": { "admin": false, "push": false, "pull": true }, "allow_rebase_merge": true, "temp_clone_token": "ABTLWHOULUVAXGTRYU7OC2876QJ2O", "allow_squash_merge": true, "allow_merge_commit": true, "forks": 123, "open_issues": 123, "license": { "key": "mit", "name": "MIT License", "url": "https://api.github.com/licenses/mit", "spdx_id": "MIT", "node_id": "MDc6TGljZW5zZW1pdA==" }, "watchers": 123 } }, "_links": { "self": { "href": "https://api.github.com/repos/octocat/Hello-World/pulls/1347" }, "html": { "href": "https://github.com/octocat/Hello-World/pull/1347" }, "issue": { "href": "https://api.github.com/repos/octocat/Hello-World/issues/1347" }, "comments": { "href": "https://api.github.com/repos/octocat/Hello-World/issues/1347/comments" }, "review_comments": { "href": "https://api.github.com/repos/octocat/Hello-World/pulls/1347/comments" }, "review_comment": { "href": "https://api.github.com/repos/octocat/Hello-World/pulls/comments{/number}" }, "commits": { "href": "https://api.github.com/repos/octocat/Hello-World/pulls/1347/commits" }, "statuses": { "href": "https://api.github.com/repos/octocat/Hello-World/statuses/6dcb09b5b57875f334f61aebed695e2e4193db5e" } }, "author_association": "OWNER", "draft": false, "merged": false, "mergeable": true, "rebaseable": true, "mergeable_state": "clean", "merged_by": { "login": "octocat", "id": 1, "node_id": "MDQ6VXNlcjE=", "avatar_url": "https://github.com/images/error/octocat_happy.gif", "gravatar_id": "", "url": "https://api.github.com/users/octocat", "html_url": "https://github.com/octocat", "followers_url": "https://api.github.com/users/octocat/followers", "following_url": "https://api.github.com/users/octocat/following{/other_user}", "gists_url": "https://api.github.com/users/octocat/gists{/gist_id}", "starred_url": "https://api.github.com/users/octocat/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/octocat/subscriptions", "organizations_url": "https://api.github.com/users/octocat/orgs", "repos_url": "https://api.github.com/users/octocat/repos", "events_url": "https://api.github.com/users/octocat/events{/privacy}", "received_events_url": "https://api.github.com/users/octocat/received_events", "type": "User", "site_admin": false }, "comments": 10, "review_comments": 0, "maintainer_can_modify": true, "commits": 3, "additions": 100, "deletions": 3, "changed_files": 5 } }, "pull-request-review-comment-items": { "value": [ { "url": "https://api.github.com/repos/octocat/Hello-World/pulls/comments/1", "pull_request_review_id": 42, "id": 10, "node_id": "MDI0OlB1bGxSZXF1ZXN0UmV2aWV3Q29tbWVudDEw", "diff_hunk": "@@ -16,33 +16,40 @@ public class Connection : IConnection...", "path": "file1.txt", "position": 1, "original_position": 4, "commit_id": "6dcb09b5b57875f334f61aebed695e2e4193db5e", "original_commit_id": "9c48853fa3dc5c1c3d6f1f1cd1f2743e72652840", "in_reply_to_id": 8, "user": { "login": "octocat", "id": 1, "node_id": "MDQ6VXNlcjE=", "avatar_url": "https://github.com/images/error/octocat_happy.gif", "gravatar_id": "", "url": "https://api.github.com/users/octocat", "html_url": "https://github.com/octocat", "followers_url": "https://api.github.com/users/octocat/followers", "following_url": "https://api.github.com/users/octocat/following{/other_user}", "gists_url": "https://api.github.com/users/octocat/gists{/gist_id}", "starred_url": "https://api.github.com/users/octocat/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/octocat/subscriptions", "organizations_url": "https://api.github.com/users/octocat/orgs", "repos_url": "https://api.github.com/users/octocat/repos", "events_url": "https://api.github.com/users/octocat/events{/privacy}", "received_events_url": "https://api.github.com/users/octocat/received_events", "type": "User", "site_admin": false }, "body": "Great stuff!", "created_at": "2011-04-14T16:00:49Z", "updated_at": "2011-04-14T16:00:49Z", "html_url": "https://github.com/octocat/Hello-World/pull/1#discussion-diff-1", "pull_request_url": "https://api.github.com/repos/octocat/Hello-World/pulls/1", "author_association": "NONE", "_links": { "self": { "href": "https://api.github.com/repos/octocat/Hello-World/pulls/comments/1" }, "html": { "href": "https://github.com/octocat/Hello-World/pull/1#discussion-diff-1" }, "pull_request": { "href": "https://api.github.com/repos/octocat/Hello-World/pulls/1" } }, "start_line": 1, "original_start_line": 1, "start_side": "RIGHT", "line": 2, "original_line": 2, "side": "RIGHT" } ] }, "pull-request-review-comment-2": { "value": { "url": "https://api.github.com/repos/octocat/Hello-World/pulls/comments/1", "pull_request_review_id": 42, "id": 10, "node_id": "MDI0OlB1bGxSZXF1ZXN0UmV2aWV3Q29tbWVudDEw", "diff_hunk": "@@ -16,33 +16,40 @@ public class Connection : IConnection...", "path": "file1.txt", "position": 1, "original_position": 4, "commit_id": "6dcb09b5b57875f334f61aebed695e2e4193db5e", "original_commit_id": "9c48853fa3dc5c1c3d6f1f1cd1f2743e72652840", "in_reply_to_id": 8, "user": { "login": "octocat", "id": 1, "node_id": "MDQ6VXNlcjE=", "avatar_url": "https://github.com/images/error/octocat_happy.gif", "gravatar_id": "", "url": "https://api.github.com/users/octocat", "html_url": "https://github.com/octocat", "followers_url": "https://api.github.com/users/octocat/followers", "following_url": "https://api.github.com/users/octocat/following{/other_user}", "gists_url": "https://api.github.com/users/octocat/gists{/gist_id}", "starred_url": "https://api.github.com/users/octocat/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/octocat/subscriptions", "organizations_url": "https://api.github.com/users/octocat/orgs", "repos_url": "https://api.github.com/users/octocat/repos", "events_url": "https://api.github.com/users/octocat/events{/privacy}", "received_events_url": "https://api.github.com/users/octocat/received_events", "type": "User", "site_admin": false }, "body": "Great stuff!", "created_at": "2011-04-14T16:00:49Z", "updated_at": "2011-04-14T16:00:49Z", "html_url": "https://github.com/octocat/Hello-World/pull/1#discussion-diff-1", "pull_request_url": "https://api.github.com/repos/octocat/Hello-World/pulls/1", "author_association": "NONE", "_links": { "self": { "href": "https://api.github.com/repos/octocat/Hello-World/pulls/comments/1" }, "html": { "href": "https://github.com/octocat/Hello-World/pull/1#discussion-diff-1" }, "pull_request": { "href": "https://api.github.com/repos/octocat/Hello-World/pulls/1" } }, "start_line": 1, "original_start_line": 1, "start_side": "RIGHT", "line": 2, "original_line": 2, "side": "RIGHT" } }, "pull-request-review-comment-example-for-a-multi-line-comment": { "value": { "url": "https://api.github.com/repos/octocat/Hello-World/pulls/comments/1", "pull_request_review_id": 42, "id": 10, "node_id": "MDI0OlB1bGxSZXF1ZXN0UmV2aWV3Q29tbWVudDEw", "diff_hunk": "@@ -16,33 +16,40 @@ public class Connection : IConnection...", "path": "file1.txt", "position": 1, "original_position": 4, "commit_id": "6dcb09b5b57875f334f61aebed695e2e4193db5e", "original_commit_id": "9c48853fa3dc5c1c3d6f1f1cd1f2743e72652840", "in_reply_to_id": 8, "user": { "login": "octocat", "id": 1, "node_id": "MDQ6VXNlcjE=", "avatar_url": "https://github.com/images/error/octocat_happy.gif", "gravatar_id": "", "url": "https://api.github.com/users/octocat", "html_url": "https://github.com/octocat", "followers_url": "https://api.github.com/users/octocat/followers", "following_url": "https://api.github.com/users/octocat/following{/other_user}", "gists_url": "https://api.github.com/users/octocat/gists{/gist_id}", "starred_url": "https://api.github.com/users/octocat/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/octocat/subscriptions", "organizations_url": "https://api.github.com/users/octocat/orgs", "repos_url": "https://api.github.com/users/octocat/repos", "events_url": "https://api.github.com/users/octocat/events{/privacy}", "received_events_url": "https://api.github.com/users/octocat/received_events", "type": "User", "site_admin": false }, "body": "Great stuff!", "created_at": "2011-04-14T16:00:49Z", "updated_at": "2011-04-14T16:00:49Z", "html_url": "https://github.com/octocat/Hello-World/pull/1#discussion-diff-1", "pull_request_url": "https://api.github.com/repos/octocat/Hello-World/pulls/1", "author_association": "NONE", "_links": { "self": { "href": "https://api.github.com/repos/octocat/Hello-World/pulls/comments/1" }, "html": { "href": "https://github.com/octocat/Hello-World/pull/1#discussion-diff-1" }, "pull_request": { "href": "https://api.github.com/repos/octocat/Hello-World/pulls/1" } }, "start_line": 1, "original_start_line": 1, "start_side": "RIGHT", "line": 2, "original_line": 2, "side": "RIGHT" } }, "pull-request-review-comment": { "value": { "url": "https://api.github.com/repos/octocat/Hello-World/pulls/comments/1", "pull_request_review_id": 42, "id": 10, "node_id": "MDI0OlB1bGxSZXF1ZXN0UmV2aWV3Q29tbWVudDEw", "diff_hunk": "@@ -16,33 +16,40 @@ public class Connection : IConnection...", "path": "file1.txt", "position": 1, "original_position": 4, "commit_id": "6dcb09b5b57875f334f61aebed695e2e4193db5e", "original_commit_id": "9c48853fa3dc5c1c3d6f1f1cd1f2743e72652840", "in_reply_to_id": 426899381, "user": { "login": "octocat", "id": 1, "node_id": "MDQ6VXNlcjE=", "avatar_url": "https://github.com/images/error/octocat_happy.gif", "gravatar_id": "", "url": "https://api.github.com/users/octocat", "html_url": "https://github.com/octocat", "followers_url": "https://api.github.com/users/octocat/followers", "following_url": "https://api.github.com/users/octocat/following{/other_user}", "gists_url": "https://api.github.com/users/octocat/gists{/gist_id}", "starred_url": "https://api.github.com/users/octocat/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/octocat/subscriptions", "organizations_url": "https://api.github.com/users/octocat/orgs", "repos_url": "https://api.github.com/users/octocat/repos", "events_url": "https://api.github.com/users/octocat/events{/privacy}", "received_events_url": "https://api.github.com/users/octocat/received_events", "type": "User", "site_admin": false }, "body": "Great stuff!", "created_at": "2011-04-14T16:00:49Z", "updated_at": "2011-04-14T16:00:49Z", "html_url": "https://github.com/octocat/Hello-World/pull/1#discussion-diff-1", "pull_request_url": "https://api.github.com/repos/octocat/Hello-World/pulls/1", "author_association": "NONE", "_links": { "self": { "href": "https://api.github.com/repos/octocat/Hello-World/pulls/comments/1" }, "html": { "href": "https://github.com/octocat/Hello-World/pull/1#discussion-diff-1" }, "pull_request": { "href": "https://api.github.com/repos/octocat/Hello-World/pulls/1" } }, "start_line": 1, "original_start_line": 1, "start_side": "RIGHT", "line": 2, "original_line": 2, "side": "RIGHT" } }, "diff-entry-items": { "value": [ { "sha": "bbcd538c8e72b8c175046e27cc8f907076331401", "filename": "file1.txt", "status": "added", "additions": 103, "deletions": 21, "changes": 124, "blob_url": "https://github.com/octocat/Hello-World/blob/6dcb09b5b57875f334f61aebed695e2e4193db5e/file1.txt", "raw_url": "https://github.com/octocat/Hello-World/raw/6dcb09b5b57875f334f61aebed695e2e4193db5e/file1.txt", "contents_url": "https://api.github.com/repos/octocat/Hello-World/contents/file1.txt?ref=6dcb09b5b57875f334f61aebed695e2e4193db5e", "patch": "@@ -132,7 +132,7 @@ module Test @@ -1000,7 +1000,7 @@ module Test" } ] }, "pull-request-merge-result-response-if-merge-was-successful": { "value": { "sha": "6dcb09b5b57875f334f61aebed695e2e4193db5e", "merged": true, "message": "Pull Request successfully merged" } }, "simple-pull-request-review-request": { "value": { "users": [ { "login": "octocat", "id": 1, "node_id": "MDQ6VXNlcjE=", "avatar_url": "https://github.com/images/error/octocat_happy.gif", "gravatar_id": "", "url": "https://api.github.com/users/octocat", "html_url": "https://github.com/octocat", "followers_url": "https://api.github.com/users/octocat/followers", "following_url": "https://api.github.com/users/octocat/following{/other_user}", "gists_url": "https://api.github.com/users/octocat/gists{/gist_id}", "starred_url": "https://api.github.com/users/octocat/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/octocat/subscriptions", "organizations_url": "https://api.github.com/users/octocat/orgs", "repos_url": "https://api.github.com/users/octocat/repos", "events_url": "https://api.github.com/users/octocat/events{/privacy}", "received_events_url": "https://api.github.com/users/octocat/received_events", "type": "User", "site_admin": false } ], "teams": [ { "id": 1, "node_id": "MDQ6VGVhbTE=", "url": "https://api.github.com/teams/1", "html_url": "https://github.com/orgs/github/teams/justice-league", "name": "Justice League", "slug": "justice-league", "description": "A great team.", "privacy": "closed", "permission": "admin", "members_url": "https://api.github.com/teams/1/members{/member}", "repositories_url": "https://api.github.com/teams/1/repos", "parent": null } ] } }, "pull-request-review-request": { "value": { "url": "https://api.github.com/repos/octocat/Hello-World/pulls/1347", "id": 1, "node_id": "MDExOlB1bGxSZXF1ZXN0MQ==", "html_url": "https://github.com/octocat/Hello-World/pull/1347", "diff_url": "https://github.com/octocat/Hello-World/pull/1347.diff", "patch_url": "https://github.com/octocat/Hello-World/pull/1347.patch", "issue_url": "https://api.github.com/repos/octocat/Hello-World/issues/1347", "commits_url": "https://api.github.com/repos/octocat/Hello-World/pulls/1347/commits", "review_comments_url": "https://api.github.com/repos/octocat/Hello-World/pulls/1347/comments", "review_comment_url": "https://api.github.com/repos/octocat/Hello-World/pulls/comments{/number}", "comments_url": "https://api.github.com/repos/octocat/Hello-World/issues/1347/comments", "statuses_url": "https://api.github.com/repos/octocat/Hello-World/statuses/6dcb09b5b57875f334f61aebed695e2e4193db5e", "number": 1347, "state": "open", "locked": true, "title": "Amazing new feature", "user": { "login": "octocat", "id": 1, "node_id": "MDQ6VXNlcjE=", "avatar_url": "https://github.com/images/error/octocat_happy.gif", "gravatar_id": "", "url": "https://api.github.com/users/octocat", "html_url": "https://github.com/octocat", "followers_url": "https://api.github.com/users/octocat/followers", "following_url": "https://api.github.com/users/octocat/following{/other_user}", "gists_url": "https://api.github.com/users/octocat/gists{/gist_id}", "starred_url": "https://api.github.com/users/octocat/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/octocat/subscriptions", "organizations_url": "https://api.github.com/users/octocat/orgs", "repos_url": "https://api.github.com/users/octocat/repos", "events_url": "https://api.github.com/users/octocat/events{/privacy}", "received_events_url": "https://api.github.com/users/octocat/received_events", "type": "User", "site_admin": false }, "body": "Please pull these awesome changes in!", "labels": [ { "id": 208045946, "node_id": "MDU6TGFiZWwyMDgwNDU5NDY=", "url": "https://api.github.com/repos/octocat/Hello-World/labels/bug", "name": "bug", "description": "Something isn't working", "color": "f29513", "default": true } ], "milestone": { "url": "https://api.github.com/repos/octocat/Hello-World/milestones/1", "html_url": "https://github.com/octocat/Hello-World/milestones/v1.0", "labels_url": "https://api.github.com/repos/octocat/Hello-World/milestones/1/labels", "id": 1002604, "node_id": "MDk6TWlsZXN0b25lMTAwMjYwNA==", "number": 1, "state": "open", "title": "v1.0", "description": "Tracking milestone for version 1.0", "creator": { "login": "octocat", "id": 1, "node_id": "MDQ6VXNlcjE=", "avatar_url": "https://github.com/images/error/octocat_happy.gif", "gravatar_id": "", "url": "https://api.github.com/users/octocat", "html_url": "https://github.com/octocat", "followers_url": "https://api.github.com/users/octocat/followers", "following_url": "https://api.github.com/users/octocat/following{/other_user}", "gists_url": "https://api.github.com/users/octocat/gists{/gist_id}", "starred_url": "https://api.github.com/users/octocat/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/octocat/subscriptions", "organizations_url": "https://api.github.com/users/octocat/orgs", "repos_url": "https://api.github.com/users/octocat/repos", "events_url": "https://api.github.com/users/octocat/events{/privacy}", "received_events_url": "https://api.github.com/users/octocat/received_events", "type": "User", "site_admin": false }, "open_issues": 4, "closed_issues": 8, "created_at": "2011-04-10T20:09:31Z", "updated_at": "2014-03-03T18:58:10Z", "closed_at": "2013-02-12T13:22:01Z", "due_on": "2012-10-09T23:39:01Z" }, "active_lock_reason": "too heated", "created_at": "2011-01-26T19:01:12Z", "updated_at": "2011-01-26T19:01:12Z", "closed_at": "2011-01-26T19:01:12Z", "merged_at": "2011-01-26T19:01:12Z", "merge_commit_sha": "e5bd3914e2e596debea16f433f57875b5b90bcd6", "assignee": { "login": "octocat", "id": 1, "node_id": "MDQ6VXNlcjE=", "avatar_url": "https://github.com/images/error/octocat_happy.gif", "gravatar_id": "", "url": "https://api.github.com/users/octocat", "html_url": "https://github.com/octocat", "followers_url": "https://api.github.com/users/octocat/followers", "following_url": "https://api.github.com/users/octocat/following{/other_user}", "gists_url": "https://api.github.com/users/octocat/gists{/gist_id}", "starred_url": "https://api.github.com/users/octocat/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/octocat/subscriptions", "organizations_url": "https://api.github.com/users/octocat/orgs", "repos_url": "https://api.github.com/users/octocat/repos", "events_url": "https://api.github.com/users/octocat/events{/privacy}", "received_events_url": "https://api.github.com/users/octocat/received_events", "type": "User", "site_admin": false }, "assignees": [ { "login": "octocat", "id": 1, "node_id": "MDQ6VXNlcjE=", "avatar_url": "https://github.com/images/error/octocat_happy.gif", "gravatar_id": "", "url": "https://api.github.com/users/octocat", "html_url": "https://github.com/octocat", "followers_url": "https://api.github.com/users/octocat/followers", "following_url": "https://api.github.com/users/octocat/following{/other_user}", "gists_url": "https://api.github.com/users/octocat/gists{/gist_id}", "starred_url": "https://api.github.com/users/octocat/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/octocat/subscriptions", "organizations_url": "https://api.github.com/users/octocat/orgs", "repos_url": "https://api.github.com/users/octocat/repos", "events_url": "https://api.github.com/users/octocat/events{/privacy}", "received_events_url": "https://api.github.com/users/octocat/received_events", "type": "User", "site_admin": false }, { "login": "hubot", "id": 1, "node_id": "MDQ6VXNlcjE=", "avatar_url": "https://github.com/images/error/hubot_happy.gif", "gravatar_id": "", "url": "https://api.github.com/users/hubot", "html_url": "https://github.com/hubot", "followers_url": "https://api.github.com/users/hubot/followers", "following_url": "https://api.github.com/users/hubot/following{/other_user}", "gists_url": "https://api.github.com/users/hubot/gists{/gist_id}", "starred_url": "https://api.github.com/users/hubot/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/hubot/subscriptions", "organizations_url": "https://api.github.com/users/hubot/orgs", "repos_url": "https://api.github.com/users/hubot/repos", "events_url": "https://api.github.com/users/hubot/events{/privacy}", "received_events_url": "https://api.github.com/users/hubot/received_events", "type": "User", "site_admin": true } ], "requested_reviewers": [ { "login": "octocat", "id": 1, "node_id": "MDQ6VXNlcjE=", "avatar_url": "https://github.com/images/error/octocat_happy.gif", "gravatar_id": "", "url": "https://api.github.com/users/octocat", "html_url": "https://github.com/octocat", "followers_url": "https://api.github.com/users/octocat/followers", "following_url": "https://api.github.com/users/octocat/following{/other_user}", "gists_url": "https://api.github.com/users/octocat/gists{/gist_id}", "starred_url": "https://api.github.com/users/octocat/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/octocat/subscriptions", "organizations_url": "https://api.github.com/users/octocat/orgs", "repos_url": "https://api.github.com/users/octocat/repos", "events_url": "https://api.github.com/users/octocat/events{/privacy}", "received_events_url": "https://api.github.com/users/octocat/received_events", "type": "User", "site_admin": false }, { "login": "hubot", "id": 1, "node_id": "MDQ6VXNlcjE=", "avatar_url": "https://github.com/images/error/hubot_happy.gif", "gravatar_id": "", "url": "https://api.github.com/users/hubot", "html_url": "https://github.com/hubot", "followers_url": "https://api.github.com/users/hubot/followers", "following_url": "https://api.github.com/users/hubot/following{/other_user}", "gists_url": "https://api.github.com/users/hubot/gists{/gist_id}", "starred_url": "https://api.github.com/users/hubot/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/hubot/subscriptions", "organizations_url": "https://api.github.com/users/hubot/orgs", "repos_url": "https://api.github.com/users/hubot/repos", "events_url": "https://api.github.com/users/hubot/events{/privacy}", "received_events_url": "https://api.github.com/users/hubot/received_events", "type": "User", "site_admin": true }, { "login": "other_user", "id": 1, "node_id": "MDQ6VXNlcjE=", "avatar_url": "https://github.com/images/error/other_user_happy.gif", "gravatar_id": "", "url": "https://api.github.com/users/other_user", "html_url": "https://github.com/other_user", "followers_url": "https://api.github.com/users/other_user/followers", "following_url": "https://api.github.com/users/other_user/following{/other_user}", "gists_url": "https://api.github.com/users/other_user/gists{/gist_id}", "starred_url": "https://api.github.com/users/other_user/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/other_user/subscriptions", "organizations_url": "https://api.github.com/users/other_user/orgs", "repos_url": "https://api.github.com/users/other_user/repos", "events_url": "https://api.github.com/users/other_user/events{/privacy}", "received_events_url": "https://api.github.com/users/other_user/received_events", "type": "User", "site_admin": false } ], "requested_teams": [ { "id": 1, "node_id": "MDQ6VGVhbTE=", "url": "https://api.github.com/teams/1", "html_url": "https://github.com/orgs/github/teams/justice-league", "name": "Justice League", "slug": "justice-league", "description": "A great team.", "privacy": "closed", "permission": "admin", "members_url": "https://api.github.com/teams/1/members{/member}", "repositories_url": "https://api.github.com/teams/1/repos", "parent": null } ], "head": { "label": "octocat:new-topic", "ref": "new-topic", "sha": "6dcb09b5b57875f334f61aebed695e2e4193db5e", "user": { "login": "octocat", "id": 1, "node_id": "MDQ6VXNlcjE=", "avatar_url": "https://github.com/images/error/octocat_happy.gif", "gravatar_id": "", "url": "https://api.github.com/users/octocat", "html_url": "https://github.com/octocat", "followers_url": "https://api.github.com/users/octocat/followers", "following_url": "https://api.github.com/users/octocat/following{/other_user}", "gists_url": "https://api.github.com/users/octocat/gists{/gist_id}", "starred_url": "https://api.github.com/users/octocat/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/octocat/subscriptions", "organizations_url": "https://api.github.com/users/octocat/orgs", "repos_url": "https://api.github.com/users/octocat/repos", "events_url": "https://api.github.com/users/octocat/events{/privacy}", "received_events_url": "https://api.github.com/users/octocat/received_events", "type": "User", "site_admin": false }, "repo": { "id": 1296269, "node_id": "MDEwOlJlcG9zaXRvcnkxMjk2MjY5", "name": "Hello-World", "full_name": "octocat/Hello-World", "owner": { "login": "octocat", "id": 1, "node_id": "MDQ6VXNlcjE=", "avatar_url": "https://github.com/images/error/octocat_happy.gif", "gravatar_id": "", "url": "https://api.github.com/users/octocat", "html_url": "https://github.com/octocat", "followers_url": "https://api.github.com/users/octocat/followers", "following_url": "https://api.github.com/users/octocat/following{/other_user}", "gists_url": "https://api.github.com/users/octocat/gists{/gist_id}", "starred_url": "https://api.github.com/users/octocat/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/octocat/subscriptions", "organizations_url": "https://api.github.com/users/octocat/orgs", "repos_url": "https://api.github.com/users/octocat/repos", "events_url": "https://api.github.com/users/octocat/events{/privacy}", "received_events_url": "https://api.github.com/users/octocat/received_events", "type": "User", "site_admin": false }, "private": false, "html_url": "https://github.com/octocat/Hello-World", "description": "This your first repo!", "fork": false, "url": "https://api.github.com/repos/octocat/Hello-World", "archive_url": "https://api.github.com/repos/octocat/Hello-World/{archive_format}{/ref}", "assignees_url": "https://api.github.com/repos/octocat/Hello-World/assignees{/user}", "blobs_url": "https://api.github.com/repos/octocat/Hello-World/git/blobs{/sha}", "branches_url": "https://api.github.com/repos/octocat/Hello-World/branches{/branch}", "collaborators_url": "https://api.github.com/repos/octocat/Hello-World/collaborators{/collaborator}", "comments_url": "https://api.github.com/repos/octocat/Hello-World/comments{/number}", "commits_url": "https://api.github.com/repos/octocat/Hello-World/commits{/sha}", "compare_url": "https://api.github.com/repos/octocat/Hello-World/compare/{base}...{head}", "contents_url": "https://api.github.com/repos/octocat/Hello-World/contents/{+path}", "contributors_url": "https://api.github.com/repos/octocat/Hello-World/contributors", "deployments_url": "https://api.github.com/repos/octocat/Hello-World/deployments", "downloads_url": "https://api.github.com/repos/octocat/Hello-World/downloads", "events_url": "https://api.github.com/repos/octocat/Hello-World/events", "forks_url": "https://api.github.com/repos/octocat/Hello-World/forks", "git_commits_url": "https://api.github.com/repos/octocat/Hello-World/git/commits{/sha}", "git_refs_url": "https://api.github.com/repos/octocat/Hello-World/git/refs{/sha}", "git_tags_url": "https://api.github.com/repos/octocat/Hello-World/git/tags{/sha}", "git_url": "git:github.com/octocat/Hello-World.git", "issue_comment_url": "https://api.github.com/repos/octocat/Hello-World/issues/comments{/number}", "issue_events_url": "https://api.github.com/repos/octocat/Hello-World/issues/events{/number}", "issues_url": "https://api.github.com/repos/octocat/Hello-World/issues{/number}", "keys_url": "https://api.github.com/repos/octocat/Hello-World/keys{/key_id}", "labels_url": "https://api.github.com/repos/octocat/Hello-World/labels{/name}", "languages_url": "https://api.github.com/repos/octocat/Hello-World/languages", "merges_url": "https://api.github.com/repos/octocat/Hello-World/merges", "milestones_url": "https://api.github.com/repos/octocat/Hello-World/milestones{/number}", "notifications_url": "https://api.github.com/repos/octocat/Hello-World/notifications{?since,all,participating}", "pulls_url": "https://api.github.com/repos/octocat/Hello-World/pulls{/number}", "releases_url": "https://api.github.com/repos/octocat/Hello-World/releases{/id}", "ssh_url": "git@github.com:octocat/Hello-World.git", "stargazers_url": "https://api.github.com/repos/octocat/Hello-World/stargazers", "statuses_url": "https://api.github.com/repos/octocat/Hello-World/statuses/{sha}", "subscribers_url": "https://api.github.com/repos/octocat/Hello-World/subscribers", "subscription_url": "https://api.github.com/repos/octocat/Hello-World/subscription", "tags_url": "https://api.github.com/repos/octocat/Hello-World/tags", "teams_url": "https://api.github.com/repos/octocat/Hello-World/teams", "trees_url": "https://api.github.com/repos/octocat/Hello-World/git/trees{/sha}", "clone_url": "https://github.com/octocat/Hello-World.git", "mirror_url": "git:git.example.com/octocat/Hello-World", "hooks_url": "https://api.github.com/repos/octocat/Hello-World/hooks", "svn_url": "https://svn.github.com/octocat/Hello-World", "homepage": "https://github.com", "forks_count": 9, "stargazers_count": 80, "watchers_count": 80, "size": 108, "default_branch": "master", "open_issues_count": 0, "is_template": true, "topics": [ "octocat", "atom", "electron", "api" ], "has_issues": true, "has_projects": true, "has_wiki": true, "has_pages": false, "has_downloads": true, "archived": false, "disabled": false, "visibility": "public", "pushed_at": "2011-01-26T19:06:43Z", "created_at": "2011-01-26T19:01:12Z", "updated_at": "2011-01-26T19:14:43Z", "permissions": { "admin": false, "push": false, "pull": true }, "allow_rebase_merge": true, "temp_clone_token": "ABTLWHOULUVAXGTRYU7OC2876QJ2O", "allow_squash_merge": true, "delete_branch_on_merge": true, "allow_merge_commit": true, "subscribers_count": 42, "network_count": 0, "license": { "key": "mit", "name": "MIT License", "url": "https://api.github.com/licenses/mit", "spdx_id": "MIT", "node_id": "MDc6TGljZW5zZW1pdA==", "html_url": "https://github.com/licenses/mit" }, "forks": 1, "open_issues": 1, "watchers": 1 } }, "base": { "label": "octocat:master", "ref": "master", "sha": "6dcb09b5b57875f334f61aebed695e2e4193db5e", "user": { "login": "octocat", "id": 1, "node_id": "MDQ6VXNlcjE=", "avatar_url": "https://github.com/images/error/octocat_happy.gif", "gravatar_id": "", "url": "https://api.github.com/users/octocat", "html_url": "https://github.com/octocat", "followers_url": "https://api.github.com/users/octocat/followers", "following_url": "https://api.github.com/users/octocat/following{/other_user}", "gists_url": "https://api.github.com/users/octocat/gists{/gist_id}", "starred_url": "https://api.github.com/users/octocat/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/octocat/subscriptions", "organizations_url": "https://api.github.com/users/octocat/orgs", "repos_url": "https://api.github.com/users/octocat/repos", "events_url": "https://api.github.com/users/octocat/events{/privacy}", "received_events_url": "https://api.github.com/users/octocat/received_events", "type": "User", "site_admin": false }, "repo": { "id": 1296269, "node_id": "MDEwOlJlcG9zaXRvcnkxMjk2MjY5", "name": "Hello-World", "full_name": "octocat/Hello-World", "owner": { "login": "octocat", "id": 1, "node_id": "MDQ6VXNlcjE=", "avatar_url": "https://github.com/images/error/octocat_happy.gif", "gravatar_id": "", "url": "https://api.github.com/users/octocat", "html_url": "https://github.com/octocat", "followers_url": "https://api.github.com/users/octocat/followers", "following_url": "https://api.github.com/users/octocat/following{/other_user}", "gists_url": "https://api.github.com/users/octocat/gists{/gist_id}", "starred_url": "https://api.github.com/users/octocat/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/octocat/subscriptions", "organizations_url": "https://api.github.com/users/octocat/orgs", "repos_url": "https://api.github.com/users/octocat/repos", "events_url": "https://api.github.com/users/octocat/events{/privacy}", "received_events_url": "https://api.github.com/users/octocat/received_events", "type": "User", "site_admin": false }, "private": false, "html_url": "https://github.com/octocat/Hello-World", "description": "This your first repo!", "fork": false, "url": "https://api.github.com/repos/octocat/Hello-World", "archive_url": "https://api.github.com/repos/octocat/Hello-World/{archive_format}{/ref}", "assignees_url": "https://api.github.com/repos/octocat/Hello-World/assignees{/user}", "blobs_url": "https://api.github.com/repos/octocat/Hello-World/git/blobs{/sha}", "branches_url": "https://api.github.com/repos/octocat/Hello-World/branches{/branch}", "collaborators_url": "https://api.github.com/repos/octocat/Hello-World/collaborators{/collaborator}", "comments_url": "https://api.github.com/repos/octocat/Hello-World/comments{/number}", "commits_url": "https://api.github.com/repos/octocat/Hello-World/commits{/sha}", "compare_url": "https://api.github.com/repos/octocat/Hello-World/compare/{base}...{head}", "contents_url": "https://api.github.com/repos/octocat/Hello-World/contents/{+path}", "contributors_url": "https://api.github.com/repos/octocat/Hello-World/contributors", "deployments_url": "https://api.github.com/repos/octocat/Hello-World/deployments", "downloads_url": "https://api.github.com/repos/octocat/Hello-World/downloads", "events_url": "https://api.github.com/repos/octocat/Hello-World/events", "forks_url": "https://api.github.com/repos/octocat/Hello-World/forks", "git_commits_url": "https://api.github.com/repos/octocat/Hello-World/git/commits{/sha}", "git_refs_url": "https://api.github.com/repos/octocat/Hello-World/git/refs{/sha}", "git_tags_url": "https://api.github.com/repos/octocat/Hello-World/git/tags{/sha}", "git_url": "git:github.com/octocat/Hello-World.git", "issue_comment_url": "https://api.github.com/repos/octocat/Hello-World/issues/comments{/number}", "issue_events_url": "https://api.github.com/repos/octocat/Hello-World/issues/events{/number}", "issues_url": "https://api.github.com/repos/octocat/Hello-World/issues{/number}", "keys_url": "https://api.github.com/repos/octocat/Hello-World/keys{/key_id}", "labels_url": "https://api.github.com/repos/octocat/Hello-World/labels{/name}", "languages_url": "https://api.github.com/repos/octocat/Hello-World/languages", "merges_url": "https://api.github.com/repos/octocat/Hello-World/merges", "milestones_url": "https://api.github.com/repos/octocat/Hello-World/milestones{/number}", "notifications_url": "https://api.github.com/repos/octocat/Hello-World/notifications{?since,all,participating}", "pulls_url": "https://api.github.com/repos/octocat/Hello-World/pulls{/number}", "releases_url": "https://api.github.com/repos/octocat/Hello-World/releases{/id}", "ssh_url": "git@github.com:octocat/Hello-World.git", "stargazers_url": "https://api.github.com/repos/octocat/Hello-World/stargazers", "statuses_url": "https://api.github.com/repos/octocat/Hello-World/statuses/{sha}", "subscribers_url": "https://api.github.com/repos/octocat/Hello-World/subscribers", "subscription_url": "https://api.github.com/repos/octocat/Hello-World/subscription", "tags_url": "https://api.github.com/repos/octocat/Hello-World/tags", "teams_url": "https://api.github.com/repos/octocat/Hello-World/teams", "trees_url": "https://api.github.com/repos/octocat/Hello-World/git/trees{/sha}", "clone_url": "https://github.com/octocat/Hello-World.git", "mirror_url": "git:git.example.com/octocat/Hello-World", "hooks_url": "https://api.github.com/repos/octocat/Hello-World/hooks", "svn_url": "https://svn.github.com/octocat/Hello-World", "homepage": "https://github.com", "forks_count": 9, "stargazers_count": 80, "watchers_count": 80, "size": 108, "default_branch": "master", "open_issues_count": 0, "is_template": true, "topics": [ "octocat", "atom", "electron", "api" ], "has_issues": true, "has_projects": true, "has_wiki": true, "has_pages": false, "has_downloads": true, "archived": false, "disabled": false, "visibility": "public", "pushed_at": "2011-01-26T19:06:43Z", "created_at": "2011-01-26T19:01:12Z", "updated_at": "2011-01-26T19:14:43Z", "permissions": { "admin": false, "push": false, "pull": true }, "allow_rebase_merge": true, "temp_clone_token": "ABTLWHOULUVAXGTRYU7OC2876QJ2O", "allow_squash_merge": true, "delete_branch_on_merge": true, "allow_merge_commit": true, "subscribers_count": 42, "network_count": 0, "license": { "key": "mit", "name": "MIT License", "url": "https://api.github.com/licenses/mit", "spdx_id": "MIT", "node_id": "MDc6TGljZW5zZW1pdA==", "html_url": "https://api.github.com/licenses/mit" }, "forks": 1, "open_issues": 1, "watchers": 1 } }, "_links": { "self": { "href": "https://api.github.com/repos/octocat/Hello-World/pulls/1347" }, "html": { "href": "https://github.com/octocat/Hello-World/pull/1347" }, "issue": { "href": "https://api.github.com/repos/octocat/Hello-World/issues/1347" }, "comments": { "href": "https://api.github.com/repos/octocat/Hello-World/issues/1347/comments" }, "review_comments": { "href": "https://api.github.com/repos/octocat/Hello-World/pulls/1347/comments" }, "review_comment": { "href": "https://api.github.com/repos/octocat/Hello-World/pulls/comments{/number}" }, "commits": { "href": "https://api.github.com/repos/octocat/Hello-World/pulls/1347/commits" }, "statuses": { "href": "https://api.github.com/repos/octocat/Hello-World/statuses/6dcb09b5b57875f334f61aebed695e2e4193db5e" } }, "author_association": "OWNER", "draft": false } }, "pull-request-review-items": { "value": [ { "id": 80, "node_id": "MDE3OlB1bGxSZXF1ZXN0UmV2aWV3ODA=", "user": { "login": "octocat", "id": 1, "node_id": "MDQ6VXNlcjE=", "avatar_url": "https://github.com/images/error/octocat_happy.gif", "gravatar_id": "", "url": "https://api.github.com/users/octocat", "html_url": "https://github.com/octocat", "followers_url": "https://api.github.com/users/octocat/followers", "following_url": "https://api.github.com/users/octocat/following{/other_user}", "gists_url": "https://api.github.com/users/octocat/gists{/gist_id}", "starred_url": "https://api.github.com/users/octocat/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/octocat/subscriptions", "organizations_url": "https://api.github.com/users/octocat/orgs", "repos_url": "https://api.github.com/users/octocat/repos", "events_url": "https://api.github.com/users/octocat/events{/privacy}", "received_events_url": "https://api.github.com/users/octocat/received_events", "type": "User", "site_admin": false }, "body": "Here is the body for the review.", "state": "APPROVED", "html_url": "https://github.com/octocat/Hello-World/pull/12#pullrequestreview-80", "pull_request_url": "https://api.github.com/repos/octocat/Hello-World/pulls/12", "_links": { "html": { "href": "https://github.com/octocat/Hello-World/pull/12#pullrequestreview-80" }, "pull_request": { "href": "https://api.github.com/repos/octocat/Hello-World/pulls/12" } }, "submitted_at": "2019-11-17T17:43:43Z", "commit_id": "ecdd80bb57125d7ba9641ffaa4d7d2c19d3f3091", "author_association": "COLLABORATOR" } ] }, "pull-request-review": { "value": { "id": 80, "node_id": "MDE3OlB1bGxSZXF1ZXN0UmV2aWV3ODA=", "user": { "login": "octocat", "id": 1, "node_id": "MDQ6VXNlcjE=", "avatar_url": "https://github.com/images/error/octocat_happy.gif", "gravatar_id": "", "url": "https://api.github.com/users/octocat", "html_url": "https://github.com/octocat", "followers_url": "https://api.github.com/users/octocat/followers", "following_url": "https://api.github.com/users/octocat/following{/other_user}", "gists_url": "https://api.github.com/users/octocat/gists{/gist_id}", "starred_url": "https://api.github.com/users/octocat/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/octocat/subscriptions", "organizations_url": "https://api.github.com/users/octocat/orgs", "repos_url": "https://api.github.com/users/octocat/repos", "events_url": "https://api.github.com/users/octocat/events{/privacy}", "received_events_url": "https://api.github.com/users/octocat/received_events", "type": "User", "site_admin": false }, "body": "This is close to perfect! Please address the suggested inline change.", "state": "CHANGES_REQUESTED", "html_url": "https://github.com/octocat/Hello-World/pull/12#pullrequestreview-80", "pull_request_url": "https://api.github.com/repos/octocat/Hello-World/pulls/12", "_links": { "html": { "href": "https://github.com/octocat/Hello-World/pull/12#pullrequestreview-80" }, "pull_request": { "href": "https://api.github.com/repos/octocat/Hello-World/pulls/12" } }, "submitted_at": "2019-11-17T17:43:43Z", "commit_id": "ecdd80bb57125d7ba9641ffaa4d7d2c19d3f3091", "author_association": "COLLABORATOR" } }, "pull-request-review-4": { "value": { "id": 80, "node_id": "MDE3OlB1bGxSZXF1ZXN0UmV2aWV3ODA=", "user": { "login": "octocat", "id": 1, "node_id": "MDQ6VXNlcjE=", "avatar_url": "https://github.com/images/error/octocat_happy.gif", "gravatar_id": "", "url": "https://api.github.com/users/octocat", "html_url": "https://github.com/octocat", "followers_url": "https://api.github.com/users/octocat/followers", "following_url": "https://api.github.com/users/octocat/following{/other_user}", "gists_url": "https://api.github.com/users/octocat/gists{/gist_id}", "starred_url": "https://api.github.com/users/octocat/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/octocat/subscriptions", "organizations_url": "https://api.github.com/users/octocat/orgs", "repos_url": "https://api.github.com/users/octocat/repos", "events_url": "https://api.github.com/users/octocat/events{/privacy}", "received_events_url": "https://api.github.com/users/octocat/received_events", "type": "User", "site_admin": false }, "body": "Here is the body for the review.", "state": "APPROVED", "html_url": "https://github.com/octocat/Hello-World/pull/12#pullrequestreview-80", "pull_request_url": "https://api.github.com/repos/octocat/Hello-World/pulls/12", "_links": { "html": { "href": "https://github.com/octocat/Hello-World/pull/12#pullrequestreview-80" }, "pull_request": { "href": "https://api.github.com/repos/octocat/Hello-World/pulls/12" } }, "submitted_at": "2019-11-17T17:43:43Z", "commit_id": "ecdd80bb57125d7ba9641ffaa4d7d2c19d3f3091", "author_association": "COLLABORATOR" } }, "pull-request-review-5": { "value": { "id": 80, "node_id": "MDE3OlB1bGxSZXF1ZXN0UmV2aWV3ODA=", "user": { "login": "octocat", "id": 1, "node_id": "MDQ6VXNlcjE=", "avatar_url": "https://github.com/images/error/octocat_happy.gif", "gravatar_id": "", "url": "https://api.github.com/users/octocat", "html_url": "https://github.com/octocat", "followers_url": "https://api.github.com/users/octocat/followers", "following_url": "https://api.github.com/users/octocat/following{/other_user}", "gists_url": "https://api.github.com/users/octocat/gists{/gist_id}", "starred_url": "https://api.github.com/users/octocat/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/octocat/subscriptions", "organizations_url": "https://api.github.com/users/octocat/orgs", "repos_url": "https://api.github.com/users/octocat/repos", "events_url": "https://api.github.com/users/octocat/events{/privacy}", "received_events_url": "https://api.github.com/users/octocat/received_events", "type": "User", "site_admin": false }, "body": "This is close to perfect! Please address the suggested inline change. And add more about this.", "state": "CHANGES_REQUESTED", "html_url": "https://github.com/octocat/Hello-World/pull/12#pullrequestreview-80", "pull_request_url": "https://api.github.com/repos/octocat/Hello-World/pulls/12", "_links": { "html": { "href": "https://github.com/octocat/Hello-World/pull/12#pullrequestreview-80" }, "pull_request": { "href": "https://api.github.com/repos/octocat/Hello-World/pulls/12" } }, "submitted_at": "2019-11-17T17:43:43Z", "commit_id": "ecdd80bb57125d7ba9641ffaa4d7d2c19d3f3091", "author_association": "COLLABORATOR" } }, "review-comment-items": { "value": [ { "url": "https://api.github.com/repos/octocat/Hello-World/pulls/comments/1", "pull_request_review_id": 42, "id": 10, "node_id": "MDI0OlB1bGxSZXF1ZXN0UmV2aWV3Q29tbWVudDEw", "diff_hunk": "@@ -16,33 +16,40 @@ public class Connection : IConnection...", "path": "file1.txt", "position": 1, "original_position": 4, "commit_id": "6dcb09b5b57875f334f61aebed695e2e4193db5e", "original_commit_id": "9c48853fa3dc5c1c3d6f1f1cd1f2743e72652840", "in_reply_to_id": 8, "user": { "login": "octocat", "id": 1, "node_id": "MDQ6VXNlcjE=", "avatar_url": "https://github.com/images/error/octocat_happy.gif", "gravatar_id": "", "url": "https://api.github.com/users/octocat", "html_url": "https://github.com/octocat", "followers_url": "https://api.github.com/users/octocat/followers", "following_url": "https://api.github.com/users/octocat/following{/other_user}", "gists_url": "https://api.github.com/users/octocat/gists{/gist_id}", "starred_url": "https://api.github.com/users/octocat/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/octocat/subscriptions", "organizations_url": "https://api.github.com/users/octocat/orgs", "repos_url": "https://api.github.com/users/octocat/repos", "events_url": "https://api.github.com/users/octocat/events{/privacy}", "received_events_url": "https://api.github.com/users/octocat/received_events", "type": "User", "site_admin": false }, "body": "Great stuff!", "created_at": "2011-04-14T16:00:49Z", "updated_at": "2011-04-14T16:00:49Z", "html_url": "https://github.com/octocat/Hello-World/pull/1#discussion-diff-1", "pull_request_url": "https://api.github.com/repos/octocat/Hello-World/pulls/1", "author_association": "NONE", "_links": { "self": { "href": "https://api.github.com/repos/octocat/Hello-World/pulls/comments/1" }, "html": { "href": "https://github.com/octocat/Hello-World/pull/1#discussion-diff-1" }, "pull_request": { "href": "https://api.github.com/repos/octocat/Hello-World/pulls/1" } } } ] }, "pull-request-review-3": { "value": { "id": 80, "node_id": "MDE3OlB1bGxSZXF1ZXN0UmV2aWV3ODA=", "user": { "login": "octocat", "id": 1, "node_id": "MDQ6VXNlcjE=", "avatar_url": "https://github.com/images/error/octocat_happy.gif", "gravatar_id": "", "url": "https://api.github.com/users/octocat", "html_url": "https://github.com/octocat", "followers_url": "https://api.github.com/users/octocat/followers", "following_url": "https://api.github.com/users/octocat/following{/other_user}", "gists_url": "https://api.github.com/users/octocat/gists{/gist_id}", "starred_url": "https://api.github.com/users/octocat/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/octocat/subscriptions", "organizations_url": "https://api.github.com/users/octocat/orgs", "repos_url": "https://api.github.com/users/octocat/repos", "events_url": "https://api.github.com/users/octocat/events{/privacy}", "received_events_url": "https://api.github.com/users/octocat/received_events", "type": "User", "site_admin": false }, "body": "Here is the body for the review.", "state": "DISMISSED", "html_url": "https://github.com/octocat/Hello-World/pull/12#pullrequestreview-80", "pull_request_url": "https://api.github.com/repos/octocat/Hello-World/pulls/12", "_links": { "html": { "href": "https://github.com/octocat/Hello-World/pull/12#pullrequestreview-80" }, "pull_request": { "href": "https://api.github.com/repos/octocat/Hello-World/pulls/12" } }, "submitted_at": "2019-11-17T17:43:43Z", "commit_id": "ecdd80bb57125d7ba9641ffaa4d7d2c19d3f3091", "author_association": "COLLABORATOR" } }, "content-file": { "value": { "type": "file", "encoding": "base64", "size": 5362, "name": "README.md", "path": "README.md", "content": "encoded content ...", "sha": "3d21ec53a331a6f037a91c368710b99387d012c1", "url": "https://api.github.com/repos/octokit/octokit.rb/contents/README.md", "git_url": "https://api.github.com/repos/octokit/octokit.rb/git/blobs/3d21ec53a331a6f037a91c368710b99387d012c1", "html_url": "https://github.com/octokit/octokit.rb/blob/master/README.md", "download_url": "https://raw.githubusercontent.com/octokit/octokit.rb/master/README.md", "_links": { "git": "https://api.github.com/repos/octokit/octokit.rb/git/blobs/3d21ec53a331a6f037a91c368710b99387d012c1", "self": "https://api.github.com/repos/octokit/octokit.rb/contents/README.md", "html": "https://github.com/octokit/octokit.rb/blob/master/README.md" } } }, "release-items": { "value": [ { "url": "https://api.github.com/repos/octocat/Hello-World/releases/1", "html_url": "https://github.com/octocat/Hello-World/releases/v1.0.0", "assets_url": "https://api.github.com/repos/octocat/Hello-World/releases/1/assets", "upload_url": "https://uploads.github.com/repos/octocat/Hello-World/releases/1/assets{?name,label}", "tarball_url": "https://api.github.com/repos/octocat/Hello-World/tarball/v1.0.0", "zipball_url": "https://api.github.com/repos/octocat/Hello-World/zipball/v1.0.0", "id": 1, "node_id": "MDc6UmVsZWFzZTE=", "tag_name": "v1.0.0", "target_commitish": "master", "name": "v1.0.0", "body": "Description of the release", "draft": false, "prerelease": false, "created_at": "2013-02-27T19:35:32Z", "published_at": "2013-02-27T19:35:32Z", "author": { "login": "octocat", "id": 1, "node_id": "MDQ6VXNlcjE=", "avatar_url": "https://github.com/images/error/octocat_happy.gif", "gravatar_id": "", "url": "https://api.github.com/users/octocat", "html_url": "https://github.com/octocat", "followers_url": "https://api.github.com/users/octocat/followers", "following_url": "https://api.github.com/users/octocat/following{/other_user}", "gists_url": "https://api.github.com/users/octocat/gists{/gist_id}", "starred_url": "https://api.github.com/users/octocat/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/octocat/subscriptions", "organizations_url": "https://api.github.com/users/octocat/orgs", "repos_url": "https://api.github.com/users/octocat/repos", "events_url": "https://api.github.com/users/octocat/events{/privacy}", "received_events_url": "https://api.github.com/users/octocat/received_events", "type": "User", "site_admin": false }, "assets": [ { "url": "https://api.github.com/repos/octocat/Hello-World/releases/assets/1", "browser_download_url": "https://github.com/octocat/Hello-World/releases/download/v1.0.0/example.zip", "id": 1, "node_id": "MDEyOlJlbGVhc2VBc3NldDE=", "name": "example.zip", "label": "short description", "state": "uploaded", "content_type": "application/zip", "size": 1024, "download_count": 42, "created_at": "2013-02-27T19:35:32Z", "updated_at": "2013-02-27T19:35:32Z", "uploader": { "login": "octocat", "id": 1, "node_id": "MDQ6VXNlcjE=", "avatar_url": "https://github.com/images/error/octocat_happy.gif", "gravatar_id": "", "url": "https://api.github.com/users/octocat", "html_url": "https://github.com/octocat", "followers_url": "https://api.github.com/users/octocat/followers", "following_url": "https://api.github.com/users/octocat/following{/other_user}", "gists_url": "https://api.github.com/users/octocat/gists{/gist_id}", "starred_url": "https://api.github.com/users/octocat/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/octocat/subscriptions", "organizations_url": "https://api.github.com/users/octocat/orgs", "repos_url": "https://api.github.com/users/octocat/repos", "events_url": "https://api.github.com/users/octocat/events{/privacy}", "received_events_url": "https://api.github.com/users/octocat/received_events", "type": "User", "site_admin": false } } ] } ] }, "release": { "value": { "url": "https://api.github.com/repos/octocat/Hello-World/releases/1", "html_url": "https://github.com/octocat/Hello-World/releases/v1.0.0", "assets_url": "https://api.github.com/repos/octocat/Hello-World/releases/1/assets", "upload_url": "https://uploads.github.com/repos/octocat/Hello-World/releases/1/assets{?name,label}", "tarball_url": "https://api.github.com/repos/octocat/Hello-World/tarball/v1.0.0", "zipball_url": "https://api.github.com/repos/octocat/Hello-World/zipball/v1.0.0", "discussion_url": "https://github.com/octocat/Hello-World/discussions/90", "id": 1, "node_id": "MDc6UmVsZWFzZTE=", "tag_name": "v1.0.0", "target_commitish": "master", "name": "v1.0.0", "body": "Description of the release", "draft": false, "prerelease": false, "created_at": "2013-02-27T19:35:32Z", "published_at": "2013-02-27T19:35:32Z", "author": { "login": "octocat", "id": 1, "node_id": "MDQ6VXNlcjE=", "avatar_url": "https://github.com/images/error/octocat_happy.gif", "gravatar_id": "", "url": "https://api.github.com/users/octocat", "html_url": "https://github.com/octocat", "followers_url": "https://api.github.com/users/octocat/followers", "following_url": "https://api.github.com/users/octocat/following{/other_user}", "gists_url": "https://api.github.com/users/octocat/gists{/gist_id}", "starred_url": "https://api.github.com/users/octocat/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/octocat/subscriptions", "organizations_url": "https://api.github.com/users/octocat/orgs", "repos_url": "https://api.github.com/users/octocat/repos", "events_url": "https://api.github.com/users/octocat/events{/privacy}", "received_events_url": "https://api.github.com/users/octocat/received_events", "type": "User", "site_admin": false }, "assets": [ { "url": "https://api.github.com/repos/octocat/Hello-World/releases/assets/1", "browser_download_url": "https://github.com/octocat/Hello-World/releases/download/v1.0.0/example.zip", "id": 1, "node_id": "MDEyOlJlbGVhc2VBc3NldDE=", "name": "example.zip", "label": "short description", "state": "uploaded", "content_type": "application/zip", "size": 1024, "download_count": 42, "created_at": "2013-02-27T19:35:32Z", "updated_at": "2013-02-27T19:35:32Z", "uploader": { "login": "octocat", "id": 1, "node_id": "MDQ6VXNlcjE=", "avatar_url": "https://github.com/images/error/octocat_happy.gif", "gravatar_id": "", "url": "https://api.github.com/users/octocat", "html_url": "https://github.com/octocat", "followers_url": "https://api.github.com/users/octocat/followers", "following_url": "https://api.github.com/users/octocat/following{/other_user}", "gists_url": "https://api.github.com/users/octocat/gists{/gist_id}", "starred_url": "https://api.github.com/users/octocat/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/octocat/subscriptions", "organizations_url": "https://api.github.com/users/octocat/orgs", "repos_url": "https://api.github.com/users/octocat/repos", "events_url": "https://api.github.com/users/octocat/events{/privacy}", "received_events_url": "https://api.github.com/users/octocat/received_events", "type": "User", "site_admin": false } } ] } }, "release-asset": { "value": { "url": "https://api.github.com/repos/octocat/Hello-World/releases/assets/1", "browser_download_url": "https://github.com/octocat/Hello-World/releases/download/v1.0.0/example.zip", "id": 1, "node_id": "MDEyOlJlbGVhc2VBc3NldDE=", "name": "example.zip", "label": "short description", "state": "uploaded", "content_type": "application/zip", "size": 1024, "download_count": 42, "created_at": "2013-02-27T19:35:32Z", "updated_at": "2013-02-27T19:35:32Z", "uploader": { "login": "octocat", "id": 1, "node_id": "MDQ6VXNlcjE=", "avatar_url": "https://github.com/images/error/octocat_happy.gif", "gravatar_id": "", "url": "https://api.github.com/users/octocat", "html_url": "https://github.com/octocat", "followers_url": "https://api.github.com/users/octocat/followers", "following_url": "https://api.github.com/users/octocat/following{/other_user}", "gists_url": "https://api.github.com/users/octocat/gists{/gist_id}", "starred_url": "https://api.github.com/users/octocat/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/octocat/subscriptions", "organizations_url": "https://api.github.com/users/octocat/orgs", "repos_url": "https://api.github.com/users/octocat/repos", "events_url": "https://api.github.com/users/octocat/events{/privacy}", "received_events_url": "https://api.github.com/users/octocat/received_events", "type": "User", "site_admin": false } } }, "release-asset-items": { "value": [ { "url": "https://api.github.com/repos/octocat/Hello-World/releases/assets/1", "browser_download_url": "https://github.com/octocat/Hello-World/releases/download/v1.0.0/example.zip", "id": 1, "node_id": "MDEyOlJlbGVhc2VBc3NldDE=", "name": "example.zip", "label": "short description", "state": "uploaded", "content_type": "application/zip", "size": 1024, "download_count": 42, "created_at": "2013-02-27T19:35:32Z", "updated_at": "2013-02-27T19:35:32Z", "uploader": { "login": "octocat", "id": 1, "node_id": "MDQ6VXNlcjE=", "avatar_url": "https://github.com/images/error/octocat_happy.gif", "gravatar_id": "", "url": "https://api.github.com/users/octocat", "html_url": "https://github.com/octocat", "followers_url": "https://api.github.com/users/octocat/followers", "following_url": "https://api.github.com/users/octocat/following{/other_user}", "gists_url": "https://api.github.com/users/octocat/gists{/gist_id}", "starred_url": "https://api.github.com/users/octocat/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/octocat/subscriptions", "organizations_url": "https://api.github.com/users/octocat/orgs", "repos_url": "https://api.github.com/users/octocat/repos", "events_url": "https://api.github.com/users/octocat/events{/privacy}", "received_events_url": "https://api.github.com/users/octocat/received_events", "type": "User", "site_admin": false } } ] }, "release-asset-response-for-successful-upload": { "value": { "url": "https://api.github.com/repos/octocat/Hello-World/releases/assets/1", "browser_download_url": "https://github.com/octocat/Hello-World/releases/download/v1.0.0/example.zip", "id": 1, "node_id": "MDEyOlJlbGVhc2VBc3NldDE=", "name": "example.zip", "label": "short description", "state": "uploaded", "content_type": "application/zip", "size": 1024, "download_count": 42, "created_at": "2013-02-27T19:35:32Z", "updated_at": "2013-02-27T19:35:32Z", "uploader": { "login": "octocat", "id": 1, "node_id": "MDQ6VXNlcjE=", "avatar_url": "https://github.com/images/error/octocat_happy.gif", "gravatar_id": "", "url": "https://api.github.com/users/octocat", "html_url": "https://github.com/octocat", "followers_url": "https://api.github.com/users/octocat/followers", "following_url": "https://api.github.com/users/octocat/following{/other_user}", "gists_url": "https://api.github.com/users/octocat/gists{/gist_id}", "starred_url": "https://api.github.com/users/octocat/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/octocat/subscriptions", "organizations_url": "https://api.github.com/users/octocat/orgs", "repos_url": "https://api.github.com/users/octocat/repos", "events_url": "https://api.github.com/users/octocat/events{/privacy}", "received_events_url": "https://api.github.com/users/octocat/received_events", "type": "User", "site_admin": false } } }, "simple-user-items-default-response": { "summary": "Default response", "value": [ { "login": "octocat", "id": 1, "node_id": "MDQ6VXNlcjE=", "avatar_url": "https://github.com/images/error/octocat_happy.gif", "gravatar_id": "", "url": "https://api.github.com/users/octocat", "html_url": "https://github.com/octocat", "followers_url": "https://api.github.com/users/octocat/followers", "following_url": "https://api.github.com/users/octocat/following{/other_user}", "gists_url": "https://api.github.com/users/octocat/gists{/gist_id}", "starred_url": "https://api.github.com/users/octocat/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/octocat/subscriptions", "organizations_url": "https://api.github.com/users/octocat/orgs", "repos_url": "https://api.github.com/users/octocat/repos", "events_url": "https://api.github.com/users/octocat/events{/privacy}", "received_events_url": "https://api.github.com/users/octocat/received_events", "type": "User", "site_admin": false } ] }, "stargazer-items-alternative-response-with-star-creation-timestamps": { "summary": "Alternative response with star creation timestamps", "value": [ { "starred_at": "2011-01-16T19:06:43Z", "user": { "login": "octocat", "id": 1, "node_id": "MDQ6VXNlcjE=", "avatar_url": "https://github.com/images/error/octocat_happy.gif", "gravatar_id": "", "url": "https://api.github.com/users/octocat", "html_url": "https://github.com/octocat", "followers_url": "https://api.github.com/users/octocat/followers", "following_url": "https://api.github.com/users/octocat/following{/other_user}", "gists_url": "https://api.github.com/users/octocat/gists{/gist_id}", "starred_url": "https://api.github.com/users/octocat/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/octocat/subscriptions", "organizations_url": "https://api.github.com/users/octocat/orgs", "repos_url": "https://api.github.com/users/octocat/repos", "events_url": "https://api.github.com/users/octocat/events{/privacy}", "received_events_url": "https://api.github.com/users/octocat/received_events", "type": "User", "site_admin": false } } ] }, "code-frequency-stat-items": { "value": [ [ 1302998400, 1124, -435 ] ] }, "commit-activity-items": { "value": [ { "days": [ 0, 3, 26, 20, 39, 1, 0 ], "total": 89, "week": 1336280400 } ] }, "contributor-activity-items": { "value": [ { "author": { "login": "octocat", "id": 1, "node_id": "MDQ6VXNlcjE=", "avatar_url": "https://github.com/images/error/octocat_happy.gif", "gravatar_id": "", "url": "https://api.github.com/users/octocat", "html_url": "https://github.com/octocat", "followers_url": "https://api.github.com/users/octocat/followers", "following_url": "https://api.github.com/users/octocat/following{/other_user}", "gists_url": "https://api.github.com/users/octocat/gists{/gist_id}", "starred_url": "https://api.github.com/users/octocat/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/octocat/subscriptions", "organizations_url": "https://api.github.com/users/octocat/orgs", "repos_url": "https://api.github.com/users/octocat/repos", "events_url": "https://api.github.com/users/octocat/events{/privacy}", "received_events_url": "https://api.github.com/users/octocat/received_events", "type": "User", "site_admin": false }, "total": 135, "weeks": [ { "w": 1367712000, "a": 6898, "d": 77, "c": 10 } ] } ] }, "participation-stats": { "value": { "all": [ 11, 21, 15, 2, 8, 1, 8, 23, 17, 21, 11, 10, 33, 91, 38, 34, 22, 23, 32, 3, 43, 87, 71, 18, 13, 5, 13, 16, 66, 27, 12, 45, 110, 117, 13, 8, 18, 9, 19, 26, 39, 12, 20, 31, 46, 91, 45, 10, 24, 9, 29, 7 ], "owner": [ 3, 2, 3, 0, 2, 0, 5, 14, 7, 9, 1, 5, 0, 48, 19, 2, 0, 1, 10, 2, 23, 40, 35, 8, 8, 2, 10, 6, 30, 0, 2, 9, 53, 104, 3, 3, 10, 4, 7, 11, 21, 4, 4, 22, 26, 63, 11, 2, 14, 1, 10, 3 ] } }, "code-frequency-stat-items-2": { "value": [ [ 0, 0, 5 ], [ 0, 1, 43 ], [ 0, 2, 21 ] ] }, "status": { "value": { "url": "https://api.github.com/repos/octocat/Hello-World/statuses/6dcb09b5b57875f334f61aebed695e2e4193db5e", "avatar_url": "https://github.com/images/error/hubot_happy.gif", "id": 1, "node_id": "MDY6U3RhdHVzMQ==", "state": "success", "description": "Build has completed successfully", "target_url": "https://ci.example.com/1000/output", "context": "continuous-integration/jenkins", "created_at": "2012-07-20T01:19:13Z", "updated_at": "2012-07-20T01:19:13Z", "creator": { "login": "octocat", "id": 1, "node_id": "MDQ6VXNlcjE=", "avatar_url": "https://github.com/images/error/octocat_happy.gif", "gravatar_id": "", "url": "https://api.github.com/users/octocat", "html_url": "https://github.com/octocat", "followers_url": "https://api.github.com/users/octocat/followers", "following_url": "https://api.github.com/users/octocat/following{/other_user}", "gists_url": "https://api.github.com/users/octocat/gists{/gist_id}", "starred_url": "https://api.github.com/users/octocat/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/octocat/subscriptions", "organizations_url": "https://api.github.com/users/octocat/orgs", "repos_url": "https://api.github.com/users/octocat/repos", "events_url": "https://api.github.com/users/octocat/events{/privacy}", "received_events_url": "https://api.github.com/users/octocat/received_events", "type": "User", "site_admin": false } } }, "repository-subscription-response-if-you-subscribe-to-the-repository": { "value": { "subscribed": true, "ignored": false, "reason": null, "created_at": "2012-10-06T21:34:12Z", "url": "https://api.github.com/repos/octocat/example/subscription", "repository_url": "https://api.github.com/repos/octocat/example" } }, "repository-subscription": { "value": { "subscribed": true, "ignored": false, "reason": null, "created_at": "2012-10-06T21:34:12Z", "url": "https://api.github.com/repos/octocat/example/subscription", "repository_url": "https://api.github.com/repos/octocat/example" } }, "tag-items": { "value": [ { "name": "v0.1", "commit": { "sha": "c5b97d5ae6c19d5c5df71a34c7fbeeda2479ccbc", "url": "https://api.github.com/repos/octocat/Hello-World/commits/c5b97d5ae6c19d5c5df71a34c7fbeeda2479ccbc" }, "zipball_url": "https://github.com/octocat/Hello-World/zipball/v0.1", "tarball_url": "https://github.com/octocat/Hello-World/tarball/v0.1", "node_id": "MDQ6VXNlcjE=" } ] }, "topic": { "value": { "names": [ "octocat", "atom", "electron", "api" ] } }, "minimal-repository": { "value": { "id": 1296269, "node_id": "MDEwOlJlcG9zaXRvcnkxMjk2MjY5", "name": "Hello-World", "full_name": "octocat/Hello-World", "owner": { "login": "octocat", "id": 1, "node_id": "MDQ6VXNlcjE=", "avatar_url": "https://github.com/images/error/octocat_happy.gif", "gravatar_id": "", "url": "https://api.github.com/users/octocat", "html_url": "https://github.com/octocat", "followers_url": "https://api.github.com/users/octocat/followers", "following_url": "https://api.github.com/users/octocat/following{/other_user}", "gists_url": "https://api.github.com/users/octocat/gists{/gist_id}", "starred_url": "https://api.github.com/users/octocat/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/octocat/subscriptions", "organizations_url": "https://api.github.com/users/octocat/orgs", "repos_url": "https://api.github.com/users/octocat/repos", "events_url": "https://api.github.com/users/octocat/events{/privacy}", "received_events_url": "https://api.github.com/users/octocat/received_events", "type": "User", "site_admin": false }, "private": false, "html_url": "https://github.com/octocat/Hello-World", "description": "This your first repo!", "fork": false, "url": "https://api.github.com/repos/octocat/Hello-World", "archive_url": "https://api.github.com/repos/octocat/Hello-World/{archive_format}{/ref}", "assignees_url": "https://api.github.com/repos/octocat/Hello-World/assignees{/user}", "blobs_url": "https://api.github.com/repos/octocat/Hello-World/git/blobs{/sha}", "branches_url": "https://api.github.com/repos/octocat/Hello-World/branches{/branch}", "collaborators_url": "https://api.github.com/repos/octocat/Hello-World/collaborators{/collaborator}", "comments_url": "https://api.github.com/repos/octocat/Hello-World/comments{/number}", "commits_url": "https://api.github.com/repos/octocat/Hello-World/commits{/sha}", "compare_url": "https://api.github.com/repos/octocat/Hello-World/compare/{base}...{head}", "contents_url": "https://api.github.com/repos/octocat/Hello-World/contents/{+path}", "contributors_url": "https://api.github.com/repos/octocat/Hello-World/contributors", "deployments_url": "https://api.github.com/repos/octocat/Hello-World/deployments", "downloads_url": "https://api.github.com/repos/octocat/Hello-World/downloads", "events_url": "https://api.github.com/repos/octocat/Hello-World/events", "forks_url": "https://api.github.com/repos/octocat/Hello-World/forks", "git_commits_url": "https://api.github.com/repos/octocat/Hello-World/git/commits{/sha}", "git_refs_url": "https://api.github.com/repos/octocat/Hello-World/git/refs{/sha}", "git_tags_url": "https://api.github.com/repos/octocat/Hello-World/git/tags{/sha}", "git_url": "git:github.com/octocat/Hello-World.git", "issue_comment_url": "https://api.github.com/repos/octocat/Hello-World/issues/comments{/number}", "issue_events_url": "https://api.github.com/repos/octocat/Hello-World/issues/events{/number}", "issues_url": "https://api.github.com/repos/octocat/Hello-World/issues{/number}", "keys_url": "https://api.github.com/repos/octocat/Hello-World/keys{/key_id}", "labels_url": "https://api.github.com/repos/octocat/Hello-World/labels{/name}", "languages_url": "https://api.github.com/repos/octocat/Hello-World/languages", "merges_url": "https://api.github.com/repos/octocat/Hello-World/merges", "milestones_url": "https://api.github.com/repos/octocat/Hello-World/milestones{/number}", "notifications_url": "https://api.github.com/repos/octocat/Hello-World/notifications{?since,all,participating}", "pulls_url": "https://api.github.com/repos/octocat/Hello-World/pulls{/number}", "releases_url": "https://api.github.com/repos/octocat/Hello-World/releases{/id}", "ssh_url": "git@github.com:octocat/Hello-World.git", "stargazers_url": "https://api.github.com/repos/octocat/Hello-World/stargazers", "statuses_url": "https://api.github.com/repos/octocat/Hello-World/statuses/{sha}", "subscribers_url": "https://api.github.com/repos/octocat/Hello-World/subscribers", "subscription_url": "https://api.github.com/repos/octocat/Hello-World/subscription", "tags_url": "https://api.github.com/repos/octocat/Hello-World/tags", "teams_url": "https://api.github.com/repos/octocat/Hello-World/teams", "trees_url": "https://api.github.com/repos/octocat/Hello-World/git/trees{/sha}", "clone_url": "https://github.com/octocat/Hello-World.git", "mirror_url": "git:git.example.com/octocat/Hello-World", "hooks_url": "https://api.github.com/repos/octocat/Hello-World/hooks", "svn_url": "https://svn.github.com/octocat/Hello-World", "homepage": "https://github.com", "forks_count": 9, "stargazers_count": 80, "watchers_count": 80, "size": 108, "default_branch": "master", "open_issues_count": 0, "is_template": false, "topics": [ "octocat", "atom", "electron", "api" ], "has_issues": true, "has_projects": true, "has_wiki": true, "has_pages": false, "has_downloads": true, "archived": false, "disabled": false, "visibility": "public", "pushed_at": "2011-01-26T19:06:43Z", "created_at": "2011-01-26T19:01:12Z", "updated_at": "2011-01-26T19:14:43Z", "permissions": { "admin": false, "push": false, "pull": true }, "template_repository": { "id": 1296269, "node_id": "MDEwOlJlcG9zaXRvcnkxMjk2MjY5", "name": "Hello-World-Template", "full_name": "octocat/Hello-World-Template", "owner": { "login": "octocat", "id": 1, "node_id": "MDQ6VXNlcjE=", "avatar_url": "https://github.com/images/error/octocat_happy.gif", "gravatar_id": "", "url": "https://api.github.com/users/octocat", "html_url": "https://github.com/octocat", "followers_url": "https://api.github.com/users/octocat/followers", "following_url": "https://api.github.com/users/octocat/following{/other_user}", "gists_url": "https://api.github.com/users/octocat/gists{/gist_id}", "starred_url": "https://api.github.com/users/octocat/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/octocat/subscriptions", "organizations_url": "https://api.github.com/users/octocat/orgs", "repos_url": "https://api.github.com/users/octocat/repos", "events_url": "https://api.github.com/users/octocat/events{/privacy}", "received_events_url": "https://api.github.com/users/octocat/received_events", "type": "User", "site_admin": false }, "private": false, "html_url": "https://github.com/octocat/Hello-World-Template", "description": "This your first repo!", "fork": false, "url": "https://api.github.com/repos/octocat/Hello-World-Template", "archive_url": "https://api.github.com/repos/octocat/Hello-World-Template/{archive_format}{/ref}", "assignees_url": "https://api.github.com/repos/octocat/Hello-World-Template/assignees{/user}", "blobs_url": "https://api.github.com/repos/octocat/Hello-World-Template/git/blobs{/sha}", "branches_url": "https://api.github.com/repos/octocat/Hello-World-Template/branches{/branch}", "collaborators_url": "https://api.github.com/repos/octocat/Hello-World-Template/collaborators{/collaborator}", "comments_url": "https://api.github.com/repos/octocat/Hello-World-Template/comments{/number}", "commits_url": "https://api.github.com/repos/octocat/Hello-World-Template/commits{/sha}", "compare_url": "https://api.github.com/repos/octocat/Hello-World-Template/compare/{base}...{head}", "contents_url": "https://api.github.com/repos/octocat/Hello-World-Template/contents/{+path}", "contributors_url": "https://api.github.com/repos/octocat/Hello-World-Template/contributors", "deployments_url": "https://api.github.com/repos/octocat/Hello-World-Template/deployments", "downloads_url": "https://api.github.com/repos/octocat/Hello-World-Template/downloads", "events_url": "https://api.github.com/repos/octocat/Hello-World-Template/events", "forks_url": "https://api.github.com/repos/octocat/Hello-World-Template/forks", "git_commits_url": "https://api.github.com/repos/octocat/Hello-World-Template/git/commits{/sha}", "git_refs_url": "https://api.github.com/repos/octocat/Hello-World-Template/git/refs{/sha}", "git_tags_url": "https://api.github.com/repos/octocat/Hello-World-Template/git/tags{/sha}", "git_url": "git:github.com/octocat/Hello-World-Template.git", "issue_comment_url": "https://api.github.com/repos/octocat/Hello-World-Template/issues/comments{/number}", "issue_events_url": "https://api.github.com/repos/octocat/Hello-World-Template/issues/events{/number}", "issues_url": "https://api.github.com/repos/octocat/Hello-World-Template/issues{/number}", "keys_url": "https://api.github.com/repos/octocat/Hello-World-Template/keys{/key_id}", "labels_url": "https://api.github.com/repos/octocat/Hello-World-Template/labels{/name}", "languages_url": "https://api.github.com/repos/octocat/Hello-World-Template/languages", "merges_url": "https://api.github.com/repos/octocat/Hello-World-Template/merges", "milestones_url": "https://api.github.com/repos/octocat/Hello-World-Template/milestones{/number}", "notifications_url": "https://api.github.com/repos/octocat/Hello-World-Template/notifications{?since,all,participating}", "pulls_url": "https://api.github.com/repos/octocat/Hello-World-Template/pulls{/number}", "releases_url": "https://api.github.com/repos/octocat/Hello-World-Template/releases{/id}", "ssh_url": "git@github.com:octocat/Hello-World-Template.git", "stargazers_url": "https://api.github.com/repos/octocat/Hello-World-Template/stargazers", "statuses_url": "https://api.github.com/repos/octocat/Hello-World-Template/statuses/{sha}", "subscribers_url": "https://api.github.com/repos/octocat/Hello-World-Template/subscribers", "subscription_url": "https://api.github.com/repos/octocat/Hello-World-Template/subscription", "tags_url": "https://api.github.com/repos/octocat/Hello-World-Template/tags", "teams_url": "https://api.github.com/repos/octocat/Hello-World-Template/teams", "trees_url": "https://api.github.com/repos/octocat/Hello-World-Template/git/trees{/sha}", "clone_url": "https://github.com/octocat/Hello-World-Template.git", "mirror_url": "git:git.example.com/octocat/Hello-World-Template", "hooks_url": "https://api.github.com/repos/octocat/Hello-World-Template/hooks", "svn_url": "https://svn.github.com/octocat/Hello-World-Template", "homepage": "https://github.com", "forks": 9, "forks_count": 9, "stargazers_count": 80, "watchers_count": 80, "watchers": 80, "size": 108, "default_branch": "master", "open_issues": 0, "open_issues_count": 0, "is_template": true, "license": { "key": "mit", "name": "MIT License", "url": "https://api.github.com/licenses/mit", "spdx_id": "MIT", "node_id": "MDc6TGljZW5zZW1pdA==", "html_url": "https://api.github.com/licenses/mit" }, "topics": [ "octocat", "atom", "electron", "api" ], "has_issues": true, "has_projects": true, "has_wiki": true, "has_pages": false, "has_downloads": true, "archived": false, "disabled": false, "visibility": "public", "pushed_at": "2011-01-26T19:06:43Z", "created_at": "2011-01-26T19:01:12Z", "updated_at": "2011-01-26T19:14:43Z", "permissions": { "admin": false, "push": false, "pull": true }, "allow_rebase_merge": true, "temp_clone_token": "ABTLWHOULUVAXGTRYU7OC2876QJ2O", "allow_squash_merge": true, "delete_branch_on_merge": true, "allow_merge_commit": true, "allow_forking": true, "subscribers_count": 42, "network_count": 0 } } }, "repository-3": { "value": { "id": 1296269, "node_id": "MDEwOlJlcG9zaXRvcnkxMjk2MjY5", "name": "Hello-World", "full_name": "octocat/Hello-World", "owner": { "login": "octocat", "id": 1, "node_id": "MDQ6VXNlcjE=", "avatar_url": "https://github.com/images/error/octocat_happy.gif", "gravatar_id": "", "url": "https://api.github.com/users/octocat", "html_url": "https://github.com/octocat", "followers_url": "https://api.github.com/users/octocat/followers", "following_url": "https://api.github.com/users/octocat/following{/other_user}", "gists_url": "https://api.github.com/users/octocat/gists{/gist_id}", "starred_url": "https://api.github.com/users/octocat/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/octocat/subscriptions", "organizations_url": "https://api.github.com/users/octocat/orgs", "repos_url": "https://api.github.com/users/octocat/repos", "events_url": "https://api.github.com/users/octocat/events{/privacy}", "received_events_url": "https://api.github.com/users/octocat/received_events", "type": "User", "site_admin": false }, "private": false, "html_url": "https://github.com/octocat/Hello-World", "description": "This your first repo!", "fork": false, "url": "https://api.github.com/repos/octocat/Hello-World", "archive_url": "https://api.github.com/repos/octocat/Hello-World/{archive_format}{/ref}", "assignees_url": "https://api.github.com/repos/octocat/Hello-World/assignees{/user}", "blobs_url": "https://api.github.com/repos/octocat/Hello-World/git/blobs{/sha}", "branches_url": "https://api.github.com/repos/octocat/Hello-World/branches{/branch}", "collaborators_url": "https://api.github.com/repos/octocat/Hello-World/collaborators{/collaborator}", "comments_url": "https://api.github.com/repos/octocat/Hello-World/comments{/number}", "commits_url": "https://api.github.com/repos/octocat/Hello-World/commits{/sha}", "compare_url": "https://api.github.com/repos/octocat/Hello-World/compare/{base}...{head}", "contents_url": "https://api.github.com/repos/octocat/Hello-World/contents/{+path}", "contributors_url": "https://api.github.com/repos/octocat/Hello-World/contributors", "deployments_url": "https://api.github.com/repos/octocat/Hello-World/deployments", "downloads_url": "https://api.github.com/repos/octocat/Hello-World/downloads", "events_url": "https://api.github.com/repos/octocat/Hello-World/events", "forks_url": "https://api.github.com/repos/octocat/Hello-World/forks", "git_commits_url": "https://api.github.com/repos/octocat/Hello-World/git/commits{/sha}", "git_refs_url": "https://api.github.com/repos/octocat/Hello-World/git/refs{/sha}", "git_tags_url": "https://api.github.com/repos/octocat/Hello-World/git/tags{/sha}", "git_url": "git:github.com/octocat/Hello-World.git", "issue_comment_url": "https://api.github.com/repos/octocat/Hello-World/issues/comments{/number}", "issue_events_url": "https://api.github.com/repos/octocat/Hello-World/issues/events{/number}", "issues_url": "https://api.github.com/repos/octocat/Hello-World/issues{/number}", "keys_url": "https://api.github.com/repos/octocat/Hello-World/keys{/key_id}", "labels_url": "https://api.github.com/repos/octocat/Hello-World/labels{/name}", "languages_url": "https://api.github.com/repos/octocat/Hello-World/languages", "merges_url": "https://api.github.com/repos/octocat/Hello-World/merges", "milestones_url": "https://api.github.com/repos/octocat/Hello-World/milestones{/number}", "notifications_url": "https://api.github.com/repos/octocat/Hello-World/notifications{?since,all,participating}", "pulls_url": "https://api.github.com/repos/octocat/Hello-World/pulls{/number}", "releases_url": "https://api.github.com/repos/octocat/Hello-World/releases{/id}", "ssh_url": "git@github.com:octocat/Hello-World.git", "stargazers_url": "https://api.github.com/repos/octocat/Hello-World/stargazers", "statuses_url": "https://api.github.com/repos/octocat/Hello-World/statuses/{sha}", "subscribers_url": "https://api.github.com/repos/octocat/Hello-World/subscribers", "subscription_url": "https://api.github.com/repos/octocat/Hello-World/subscription", "tags_url": "https://api.github.com/repos/octocat/Hello-World/tags", "teams_url": "https://api.github.com/repos/octocat/Hello-World/teams", "trees_url": "https://api.github.com/repos/octocat/Hello-World/git/trees{/sha}", "clone_url": "https://github.com/octocat/Hello-World.git", "mirror_url": "git:git.example.com/octocat/Hello-World", "hooks_url": "https://api.github.com/repos/octocat/Hello-World/hooks", "svn_url": "https://svn.github.com/octocat/Hello-World", "homepage": "https://github.com", "forks_count": 9, "forks": 9, "stargazers_count": 80, "watchers_count": 80, "watchers": 80, "size": 108, "default_branch": "master", "open_issues_count": 0, "open_issues": 0, "is_template": false, "topics": [ "octocat", "atom", "electron", "api" ], "has_issues": true, "has_projects": true, "has_wiki": true, "has_pages": false, "has_downloads": true, "archived": false, "disabled": false, "visibility": "public", "pushed_at": "2011-01-26T19:06:43Z", "created_at": "2011-01-26T19:01:12Z", "updated_at": "2011-01-26T19:14:43Z", "permissions": { "admin": false, "push": false, "pull": true }, "allow_rebase_merge": true, "license": { "key": "mit", "name": "MIT License", "url": "https://api.github.com/licenses/mit", "spdx_id": "MIT", "node_id": "MDc6TGljZW5zZW1pdA==", "html_url": "https://github.com/licenses/mit" }, "template_repository": { } } }, "public-repository-items": { "value": [ { "id": 1296269, "node_id": "MDEwOlJlcG9zaXRvcnkxMjk2MjY5", "name": "Hello-World", "full_name": "octocat/Hello-World", "owner": { "login": "octocat", "id": 1, "node_id": "MDQ6VXNlcjE=", "avatar_url": "https://github.com/images/error/octocat_happy.gif", "gravatar_id": "", "url": "https://api.github.com/users/octocat", "html_url": "https://github.com/octocat", "followers_url": "https://api.github.com/users/octocat/followers", "following_url": "https://api.github.com/users/octocat/following{/other_user}", "gists_url": "https://api.github.com/users/octocat/gists{/gist_id}", "starred_url": "https://api.github.com/users/octocat/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/octocat/subscriptions", "organizations_url": "https://api.github.com/users/octocat/orgs", "repos_url": "https://api.github.com/users/octocat/repos", "events_url": "https://api.github.com/users/octocat/events{/privacy}", "received_events_url": "https://api.github.com/users/octocat/received_events", "type": "User", "site_admin": false }, "private": false, "html_url": "https://github.com/octocat/Hello-World", "description": "This your first repo!", "fork": false, "url": "https://api.github.com/repos/octocat/Hello-World", "archive_url": "https://api.github.com/repos/octocat/Hello-World/{archive_format}{/ref}", "assignees_url": "https://api.github.com/repos/octocat/Hello-World/assignees{/user}", "blobs_url": "https://api.github.com/repos/octocat/Hello-World/git/blobs{/sha}", "branches_url": "https://api.github.com/repos/octocat/Hello-World/branches{/branch}", "collaborators_url": "https://api.github.com/repos/octocat/Hello-World/collaborators{/collaborator}", "comments_url": "https://api.github.com/repos/octocat/Hello-World/comments{/number}", "commits_url": "https://api.github.com/repos/octocat/Hello-World/commits{/sha}", "compare_url": "https://api.github.com/repos/octocat/Hello-World/compare/{base}...{head}", "contents_url": "https://api.github.com/repos/octocat/Hello-World/contents/{+path}", "contributors_url": "https://api.github.com/repos/octocat/Hello-World/contributors", "deployments_url": "https://api.github.com/repos/octocat/Hello-World/deployments", "downloads_url": "https://api.github.com/repos/octocat/Hello-World/downloads", "events_url": "https://api.github.com/repos/octocat/Hello-World/events", "forks_url": "https://api.github.com/repos/octocat/Hello-World/forks", "git_commits_url": "https://api.github.com/repos/octocat/Hello-World/git/commits{/sha}", "git_refs_url": "https://api.github.com/repos/octocat/Hello-World/git/refs{/sha}", "git_tags_url": "https://api.github.com/repos/octocat/Hello-World/git/tags{/sha}", "git_url": "git:github.com/octocat/Hello-World.git", "issue_comment_url": "https://api.github.com/repos/octocat/Hello-World/issues/comments{/number}", "issue_events_url": "https://api.github.com/repos/octocat/Hello-World/issues/events{/number}", "issues_url": "https://api.github.com/repos/octocat/Hello-World/issues{/number}", "keys_url": "https://api.github.com/repos/octocat/Hello-World/keys{/key_id}", "labels_url": "https://api.github.com/repos/octocat/Hello-World/labels{/name}", "languages_url": "https://api.github.com/repos/octocat/Hello-World/languages", "merges_url": "https://api.github.com/repos/octocat/Hello-World/merges", "milestones_url": "https://api.github.com/repos/octocat/Hello-World/milestones{/number}", "notifications_url": "https://api.github.com/repos/octocat/Hello-World/notifications{?since,all,participating}", "pulls_url": "https://api.github.com/repos/octocat/Hello-World/pulls{/number}", "releases_url": "https://api.github.com/repos/octocat/Hello-World/releases{/id}", "ssh_url": "git@github.com:octocat/Hello-World.git", "stargazers_url": "https://api.github.com/repos/octocat/Hello-World/stargazers", "statuses_url": "https://api.github.com/repos/octocat/Hello-World/statuses/{sha}", "subscribers_url": "https://api.github.com/repos/octocat/Hello-World/subscribers", "subscription_url": "https://api.github.com/repos/octocat/Hello-World/subscription", "tags_url": "https://api.github.com/repos/octocat/Hello-World/tags", "teams_url": "https://api.github.com/repos/octocat/Hello-World/teams", "trees_url": "https://api.github.com/repos/octocat/Hello-World/git/trees{/sha}", "hooks_url": "http://api.github.com/repos/octocat/Hello-World/hooks" } ] }, "code-search-result-item-paginated": { "value": { "total_count": 7, "incomplete_results": false, "items": [ { "name": "classes.js", "path": "src/attributes/classes.js", "sha": "d7212f9dee2dcc18f084d7df8f417b80846ded5a", "url": "https://api.github.com/repositories/167174/contents/src/attributes/classes.js?ref=825ac3773694e0cd23ee74895fd5aeb535b27da4", "git_url": "https://api.github.com/repositories/167174/git/blobs/d7212f9dee2dcc18f084d7df8f417b80846ded5a", "html_url": "https://github.com/jquery/jquery/blob/825ac3773694e0cd23ee74895fd5aeb535b27da4/src/attributes/classes.js", "repository": { "id": 167174, "node_id": "MDEwOlJlcG9zaXRvcnkxNjcxNzQ=", "name": "jquery", "full_name": "jquery/jquery", "owner": { "login": "jquery", "id": 70142, "node_id": "MDQ6VXNlcjcwMTQy", "avatar_url": "https://0.gravatar.com/avatar/6906f317a4733f4379b06c32229ef02f?d=https%3A%2F%2Fidenticons.github.com%2Ff426f04f2f9813718fb806b30e0093de.png", "gravatar_id": "", "url": "https://api.github.com/users/jquery", "html_url": "https://github.com/jquery", "followers_url": "https://api.github.com/users/jquery/followers", "following_url": "https://api.github.com/users/jquery/following{/other_user}", "gists_url": "https://api.github.com/users/jquery/gists{/gist_id}", "starred_url": "https://api.github.com/users/jquery/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/jquery/subscriptions", "organizations_url": "https://api.github.com/users/jquery/orgs", "repos_url": "https://api.github.com/users/jquery/repos", "events_url": "https://api.github.com/users/jquery/events{/privacy}", "received_events_url": "https://api.github.com/users/jquery/received_events", "type": "Organization", "site_admin": false }, "private": false, "html_url": "https://github.com/jquery/jquery", "description": "jQuery JavaScript Library", "fork": false, "url": "https://api.github.com/repos/jquery/jquery", "forks_url": "https://api.github.com/repos/jquery/jquery/forks", "keys_url": "https://api.github.com/repos/jquery/jquery/keys{/key_id}", "collaborators_url": "https://api.github.com/repos/jquery/jquery/collaborators{/collaborator}", "teams_url": "https://api.github.com/repos/jquery/jquery/teams", "hooks_url": "https://api.github.com/repos/jquery/jquery/hooks", "issue_events_url": "https://api.github.com/repos/jquery/jquery/issues/events{/number}", "events_url": "https://api.github.com/repos/jquery/jquery/events", "assignees_url": "https://api.github.com/repos/jquery/jquery/assignees{/user}", "branches_url": "https://api.github.com/repos/jquery/jquery/branches{/branch}", "tags_url": "https://api.github.com/repos/jquery/jquery/tags", "blobs_url": "https://api.github.com/repos/jquery/jquery/git/blobs{/sha}", "git_tags_url": "https://api.github.com/repos/jquery/jquery/git/tags{/sha}", "git_refs_url": "https://api.github.com/repos/jquery/jquery/git/refs{/sha}", "trees_url": "https://api.github.com/repos/jquery/jquery/git/trees{/sha}", "statuses_url": "https://api.github.com/repos/jquery/jquery/statuses/{sha}", "languages_url": "https://api.github.com/repos/jquery/jquery/languages", "stargazers_url": "https://api.github.com/repos/jquery/jquery/stargazers", "contributors_url": "https://api.github.com/repos/jquery/jquery/contributors", "subscribers_url": "https://api.github.com/repos/jquery/jquery/subscribers", "subscription_url": "https://api.github.com/repos/jquery/jquery/subscription", "commits_url": "https://api.github.com/repos/jquery/jquery/commits{/sha}", "git_commits_url": "https://api.github.com/repos/jquery/jquery/git/commits{/sha}", "comments_url": "https://api.github.com/repos/jquery/jquery/comments{/number}", "issue_comment_url": "https://api.github.com/repos/jquery/jquery/issues/comments/{number}", "contents_url": "https://api.github.com/repos/jquery/jquery/contents/{+path}", "compare_url": "https://api.github.com/repos/jquery/jquery/compare/{base}...{head}", "merges_url": "https://api.github.com/repos/jquery/jquery/merges", "archive_url": "https://api.github.com/repos/jquery/jquery/{archive_format}{/ref}", "downloads_url": "https://api.github.com/repos/jquery/jquery/downloads", "issues_url": "https://api.github.com/repos/jquery/jquery/issues{/number}", "pulls_url": "https://api.github.com/repos/jquery/jquery/pulls{/number}", "milestones_url": "https://api.github.com/repos/jquery/jquery/milestones{/number}", "notifications_url": "https://api.github.com/repos/jquery/jquery/notifications{?since,all,participating}", "labels_url": "https://api.github.com/repos/jquery/jquery/labels{/name}", "deployments_url": "http://api.github.com/repos/octocat/Hello-World/deployments", "releases_url": "http://api.github.com/repos/octocat/Hello-World/releases{/id}" }, "score": 1 } ] } }, "commit-search-result-item-paginated": { "value": { "total_count": 1, "incomplete_results": false, "items": [ { "url": "https://api.github.com/repos/octocat/Spoon-Knife/commits/bb4cc8d3b2e14b3af5df699876dd4ff3acd00b7f", "sha": "bb4cc8d3b2e14b3af5df699876dd4ff3acd00b7f", "html_url": "https://github.com/octocat/Spoon-Knife/commit/bb4cc8d3b2e14b3af5df699876dd4ff3acd00b7f", "comments_url": "https://api.github.com/repos/octocat/Spoon-Knife/commits/bb4cc8d3b2e14b3af5df699876dd4ff3acd00b7f/comments", "commit": { "url": "https://api.github.com/repos/octocat/Spoon-Knife/git/commits/bb4cc8d3b2e14b3af5df699876dd4ff3acd00b7f", "author": { "date": "2014-02-04T14:38:36-08:00", "name": "The Octocat", "email": "octocat@nowhere.com" }, "committer": { "date": "2014-02-12T15:18:55-08:00", "name": "The Octocat", "email": "octocat@nowhere.com" }, "message": "Create styles.css and updated README", "tree": { "url": "https://api.github.com/repos/octocat/Spoon-Knife/git/trees/a639e96f9038797fba6e0469f94a4b0cc459fa68", "sha": "a639e96f9038797fba6e0469f94a4b0cc459fa68" }, "comment_count": 8 }, "author": { "login": "octocat", "id": 583231, "node_id": "MDQ6VXNlcjU4MzIzMQ==", "avatar_url": "https://avatars.githubusercontent.com/u/583231?v=3", "gravatar_id": "", "url": "https://api.github.com/users/octocat", "html_url": "https://github.com/octocat", "followers_url": "https://api.github.com/users/octocat/followers", "following_url": "https://api.github.com/users/octocat/following{/other_user}", "gists_url": "https://api.github.com/users/octocat/gists{/gist_id}", "starred_url": "https://api.github.com/users/octocat/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/octocat/subscriptions", "organizations_url": "https://api.github.com/users/octocat/orgs", "repos_url": "https://api.github.com/users/octocat/repos", "events_url": "https://api.github.com/users/octocat/events{/privacy}", "received_events_url": "https://api.github.com/users/octocat/received_events", "type": "User", "site_admin": false }, "committer": { }, "parents": [ { "url": "https://api.github.com/repos/octocat/Spoon-Knife/commits/a30c19e3f13765a3b48829788bc1cb8b4e95cee4", "html_url": "https://github.com/octocat/Spoon-Knife/commit/a30c19e3f13765a3b48829788bc1cb8b4e95cee4", "sha": "a30c19e3f13765a3b48829788bc1cb8b4e95cee4" } ], "repository": { "id": 1300192, "node_id": "MDEwOlJlcG9zaXRvcnkxMzAwMTky", "name": "Spoon-Knife", "full_name": "octocat/Spoon-Knife", "owner": { "login": "octocat", "id": 583231, "node_id": "MDQ6VXNlcjU4MzIzMQ==", "avatar_url": "https://avatars.githubusercontent.com/u/583231?v=3", "gravatar_id": "", "url": "https://api.github.com/users/octocat", "html_url": "https://github.com/octocat", "followers_url": "https://api.github.com/users/octocat/followers", "following_url": "https://api.github.com/users/octocat/following{/other_user}", "gists_url": "https://api.github.com/users/octocat/gists{/gist_id}", "starred_url": "https://api.github.com/users/octocat/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/octocat/subscriptions", "organizations_url": "https://api.github.com/users/octocat/orgs", "repos_url": "https://api.github.com/users/octocat/repos", "events_url": "https://api.github.com/users/octocat/events{/privacy}", "received_events_url": "https://api.github.com/users/octocat/received_events", "type": "User", "site_admin": false }, "private": false, "html_url": "https://github.com/octocat/Spoon-Knife", "description": "This repo is for demonstration purposes only.", "fork": false, "url": "https://api.github.com/repos/octocat/Spoon-Knife", "forks_url": "https://api.github.com/repos/octocat/Spoon-Knife/forks", "keys_url": "https://api.github.com/repos/octocat/Spoon-Knife/keys{/key_id}", "collaborators_url": "https://api.github.com/repos/octocat/Spoon-Knife/collaborators{/collaborator}", "teams_url": "https://api.github.com/repos/octocat/Spoon-Knife/teams", "hooks_url": "https://api.github.com/repos/octocat/Spoon-Knife/hooks", "issue_events_url": "https://api.github.com/repos/octocat/Spoon-Knife/issues/events{/number}", "events_url": "https://api.github.com/repos/octocat/Spoon-Knife/events", "assignees_url": "https://api.github.com/repos/octocat/Spoon-Knife/assignees{/user}", "branches_url": "https://api.github.com/repos/octocat/Spoon-Knife/branches{/branch}", "tags_url": "https://api.github.com/repos/octocat/Spoon-Knife/tags", "blobs_url": "https://api.github.com/repos/octocat/Spoon-Knife/git/blobs{/sha}", "git_tags_url": "https://api.github.com/repos/octocat/Spoon-Knife/git/tags{/sha}", "git_refs_url": "https://api.github.com/repos/octocat/Spoon-Knife/git/refs{/sha}", "trees_url": "https://api.github.com/repos/octocat/Spoon-Knife/git/trees{/sha}", "statuses_url": "https://api.github.com/repos/octocat/Spoon-Knife/statuses/{sha}", "languages_url": "https://api.github.com/repos/octocat/Spoon-Knife/languages", "stargazers_url": "https://api.github.com/repos/octocat/Spoon-Knife/stargazers", "contributors_url": "https://api.github.com/repos/octocat/Spoon-Knife/contributors", "subscribers_url": "https://api.github.com/repos/octocat/Spoon-Knife/subscribers", "subscription_url": "https://api.github.com/repos/octocat/Spoon-Knife/subscription", "commits_url": "https://api.github.com/repos/octocat/Spoon-Knife/commits{/sha}", "git_commits_url": "https://api.github.com/repos/octocat/Spoon-Knife/git/commits{/sha}", "comments_url": "https://api.github.com/repos/octocat/Spoon-Knife/comments{/number}", "issue_comment_url": "https://api.github.com/repos/octocat/Spoon-Knife/issues/comments{/number}", "contents_url": "https://api.github.com/repos/octocat/Spoon-Knife/contents/{+path}", "compare_url": "https://api.github.com/repos/octocat/Spoon-Knife/compare/{base}...{head}", "merges_url": "https://api.github.com/repos/octocat/Spoon-Knife/merges", "archive_url": "https://api.github.com/repos/octocat/Spoon-Knife/{archive_format}{/ref}", "downloads_url": "https://api.github.com/repos/octocat/Spoon-Knife/downloads", "issues_url": "https://api.github.com/repos/octocat/Spoon-Knife/issues{/number}", "pulls_url": "https://api.github.com/repos/octocat/Spoon-Knife/pulls{/number}", "milestones_url": "https://api.github.com/repos/octocat/Spoon-Knife/milestones{/number}", "notifications_url": "https://api.github.com/repos/octocat/Spoon-Knife/notifications{?since,all,participating}", "labels_url": "https://api.github.com/repos/octocat/Spoon-Knife/labels{/name}", "releases_url": "https://api.github.com/repos/octocat/Spoon-Knife/releases{/id}", "deployments_url": "https://api.github.com/repos/octocat/Spoon-Knife/deployments" }, "score": 1, "node_id": "MDQ6VXNlcjU4MzIzMQ==" } ] } }, "issue-search-result-item-paginated": { "value": { "total_count": 280, "incomplete_results": false, "items": [ { "url": "https://api.github.com/repos/batterseapower/pinyin-toolkit/issues/132", "repository_url": "https://api.github.com/repos/batterseapower/pinyin-toolkit", "labels_url": "https://api.github.com/repos/batterseapower/pinyin-toolkit/issues/132/labels{/name}", "comments_url": "https://api.github.com/repos/batterseapower/pinyin-toolkit/issues/132/comments", "events_url": "https://api.github.com/repos/batterseapower/pinyin-toolkit/issues/132/events", "html_url": "https://github.com/batterseapower/pinyin-toolkit/issues/132", "id": 35802, "node_id": "MDU6SXNzdWUzNTgwMg==", "number": 132, "title": "Line Number Indexes Beyond 20 Not Displayed", "user": { "login": "Nick3C", "id": 90254, "node_id": "MDQ6VXNlcjkwMjU0", "avatar_url": "https://secure.gravatar.com/avatar/934442aadfe3b2f4630510de416c5718?d=https://a248.e.akamai.net/assets.github.com%2Fimages%2Fgravatars%2Fgravatar-user-420.png", "gravatar_id": "", "url": "https://api.github.com/users/Nick3C", "html_url": "https://github.com/Nick3C", "followers_url": "https://api.github.com/users/Nick3C/followers", "following_url": "https://api.github.com/users/Nick3C/following{/other_user}", "gists_url": "https://api.github.com/users/Nick3C/gists{/gist_id}", "starred_url": "https://api.github.com/users/Nick3C/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/Nick3C/subscriptions", "organizations_url": "https://api.github.com/users/Nick3C/orgs", "repos_url": "https://api.github.com/users/Nick3C/repos", "events_url": "https://api.github.com/users/Nick3C/events{/privacy}", "received_events_url": "https://api.github.com/users/Nick3C/received_events", "type": "User", "site_admin": true }, "labels": [ { "id": 4, "node_id": "MDU6TGFiZWw0", "url": "https://api.github.com/repos/batterseapower/pinyin-toolkit/labels/bug", "name": "bug", "color": "ff0000" } ], "state": "open", "assignee": null, "milestone": { "url": "https://api.github.com/repos/octocat/Hello-World/milestones/1", "html_url": "https://github.com/octocat/Hello-World/milestones/v1.0", "labels_url": "https://api.github.com/repos/octocat/Hello-World/milestones/1/labels", "id": 1002604, "node_id": "MDk6TWlsZXN0b25lMTAwMjYwNA==", "number": 1, "state": "open", "title": "v1.0", "description": "Tracking milestone for version 1.0", "creator": { "login": "octocat", "id": 1, "node_id": "MDQ6VXNlcjE=", "avatar_url": "https://github.com/images/error/octocat_happy.gif", "gravatar_id": "", "url": "https://api.github.com/users/octocat", "html_url": "https://github.com/octocat", "followers_url": "https://api.github.com/users/octocat/followers", "following_url": "https://api.github.com/users/octocat/following{/other_user}", "gists_url": "https://api.github.com/users/octocat/gists{/gist_id}", "starred_url": "https://api.github.com/users/octocat/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/octocat/subscriptions", "organizations_url": "https://api.github.com/users/octocat/orgs", "repos_url": "https://api.github.com/users/octocat/repos", "events_url": "https://api.github.com/users/octocat/events{/privacy}", "received_events_url": "https://api.github.com/users/octocat/received_events", "type": "User", "site_admin": false }, "open_issues": 4, "closed_issues": 8, "created_at": "2011-04-10T20:09:31Z", "updated_at": "2014-03-03T18:58:10Z", "closed_at": "2013-02-12T13:22:01Z", "due_on": "2012-10-09T23:39:01Z" }, "comments": 15, "created_at": "2009-07-12T20:10:41Z", "updated_at": "2009-07-19T09:23:43Z", "closed_at": null, "pull_request": { "url": "https://api/github.com/repos/octocat/Hello-World/pull/1347", "html_url": "https://github.com/octocat/Hello-World/pull/1347", "diff_url": "https://github.com/octocat/Hello-World/pull/1347.diff", "patch_url": "https://api.github.com/repos/octocat/Hello-World/pulls/1347" }, "body": "...", "score": 1, "locked": true, "author_association": "COLLABORATOR" } ] } }, "label-search-result-item-paginated": { "value": { "total_count": 2, "incomplete_results": false, "items": [ { "id": 418327088, "node_id": "MDU6TGFiZWw0MTgzMjcwODg=", "url": "https://api.github.com/repos/octocat/linguist/labels/enhancement", "name": "enhancement", "color": "84b6eb", "default": true, "description": "New feature or request.", "score": 1 }, { "id": 418327086, "node_id": "MDU6TGFiZWw0MTgzMjcwODY=", "url": "https://api.github.com/repos/octocat/linguist/labels/bug", "name": "bug", "color": "ee0701", "default": true, "description": "Something isn't working.", "score": 1 } ] } }, "repo-search-result-item-paginated": { "value": { "total_count": 40, "incomplete_results": false, "items": [ { "id": 3081286, "node_id": "MDEwOlJlcG9zaXRvcnkzMDgxMjg2", "name": "Tetris", "full_name": "dtrupenn/Tetris", "owner": { "login": "dtrupenn", "id": 872147, "node_id": "MDQ6VXNlcjg3MjE0Nw==", "avatar_url": "https://secure.gravatar.com/avatar/e7956084e75f239de85d3a31bc172ace?d=https://a248.e.akamai.net/assets.github.com%2Fimages%2Fgravatars%2Fgravatar-user-420.png", "gravatar_id": "", "url": "https://api.github.com/users/dtrupenn", "received_events_url": "https://api.github.com/users/dtrupenn/received_events", "type": "User", "html_url": "https://github.com/octocat", "followers_url": "https://api.github.com/users/octocat/followers", "following_url": "https://api.github.com/users/octocat/following{/other_user}", "gists_url": "https://api.github.com/users/octocat/gists{/gist_id}", "starred_url": "https://api.github.com/users/octocat/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/octocat/subscriptions", "organizations_url": "https://api.github.com/users/octocat/orgs", "repos_url": "https://api.github.com/users/octocat/repos", "events_url": "https://api.github.com/users/octocat/events{/privacy}", "site_admin": true }, "private": false, "html_url": "https://github.com/dtrupenn/Tetris", "description": "A C implementation of Tetris using Pennsim through LC4", "fork": false, "url": "https://api.github.com/repos/dtrupenn/Tetris", "created_at": "2012-01-01T00:31:50Z", "updated_at": "2013-01-05T17:58:47Z", "pushed_at": "2012-01-01T00:37:02Z", "homepage": "https://github.com", "size": 524, "stargazers_count": 1, "watchers_count": 1, "language": "Assembly", "forks_count": 0, "open_issues_count": 0, "master_branch": "master", "default_branch": "master", "score": 1, "archive_url": "https://api.github.com/repos/dtrupenn/Tetris/{archive_format}{/ref}", "assignees_url": "https://api.github.com/repos/dtrupenn/Tetris/assignees{/user}", "blobs_url": "https://api.github.com/repos/dtrupenn/Tetris/git/blobs{/sha}", "branches_url": "https://api.github.com/repos/dtrupenn/Tetris/branches{/branch}", "collaborators_url": "https://api.github.com/repos/dtrupenn/Tetris/collaborators{/collaborator}", "comments_url": "https://api.github.com/repos/dtrupenn/Tetris/comments{/number}", "commits_url": "https://api.github.com/repos/dtrupenn/Tetris/commits{/sha}", "compare_url": "https://api.github.com/repos/dtrupenn/Tetris/compare/{base}...{head}", "contents_url": "https://api.github.com/repos/dtrupenn/Tetris/contents/{+path}", "contributors_url": "https://api.github.com/repos/dtrupenn/Tetris/contributors", "deployments_url": "https://api.github.com/repos/dtrupenn/Tetris/deployments", "downloads_url": "https://api.github.com/repos/dtrupenn/Tetris/downloads", "events_url": "https://api.github.com/repos/dtrupenn/Tetris/events", "forks_url": "https://api.github.com/repos/dtrupenn/Tetris/forks", "git_commits_url": "https://api.github.com/repos/dtrupenn/Tetris/git/commits{/sha}", "git_refs_url": "https://api.github.com/repos/dtrupenn/Tetris/git/refs{/sha}", "git_tags_url": "https://api.github.com/repos/dtrupenn/Tetris/git/tags{/sha}", "git_url": "git:github.com/dtrupenn/Tetris.git", "issue_comment_url": "https://api.github.com/repos/dtrupenn/Tetris/issues/comments{/number}", "issue_events_url": "https://api.github.com/repos/dtrupenn/Tetris/issues/events{/number}", "issues_url": "https://api.github.com/repos/dtrupenn/Tetris/issues{/number}", "keys_url": "https://api.github.com/repos/dtrupenn/Tetris/keys{/key_id}", "labels_url": "https://api.github.com/repos/dtrupenn/Tetris/labels{/name}", "languages_url": "https://api.github.com/repos/dtrupenn/Tetris/languages", "merges_url": "https://api.github.com/repos/dtrupenn/Tetris/merges", "milestones_url": "https://api.github.com/repos/dtrupenn/Tetris/milestones{/number}", "notifications_url": "https://api.github.com/repos/dtrupenn/Tetris/notifications{?since,all,participating}", "pulls_url": "https://api.github.com/repos/dtrupenn/Tetris/pulls{/number}", "releases_url": "https://api.github.com/repos/dtrupenn/Tetris/releases{/id}", "ssh_url": "git@github.com:dtrupenn/Tetris.git", "stargazers_url": "https://api.github.com/repos/dtrupenn/Tetris/stargazers", "statuses_url": "https://api.github.com/repos/dtrupenn/Tetris/statuses/{sha}", "subscribers_url": "https://api.github.com/repos/dtrupenn/Tetris/subscribers", "subscription_url": "https://api.github.com/repos/dtrupenn/Tetris/subscription", "tags_url": "https://api.github.com/repos/dtrupenn/Tetris/tags", "teams_url": "https://api.github.com/repos/dtrupenn/Tetris/teams", "trees_url": "https://api.github.com/repos/dtrupenn/Tetris/git/trees{/sha}", "clone_url": "https://github.com/dtrupenn/Tetris.git", "mirror_url": "git:git.example.com/dtrupenn/Tetris", "hooks_url": "https://api.github.com/repos/dtrupenn/Tetris/hooks", "svn_url": "https://svn.github.com/dtrupenn/Tetris", "forks": 1, "open_issues": 1, "watchers": 1, "has_issues": true, "has_projects": true, "has_pages": true, "has_wiki": true, "has_downloads": true, "archived": true, "disabled": true, "visibility": "private", "license": { "key": "mit", "name": "MIT License", "url": "https://api.github.com/licenses/mit", "spdx_id": "MIT", "node_id": "MDc6TGljZW5zZW1pdA==", "html_url": "https://api.github.com/licenses/mit" } } ] } }, "topic-search-result-item-paginated": { "value": { "total_count": 6, "incomplete_results": false, "items": [ { "name": "ruby", "display_name": "Ruby", "short_description": "Ruby is a scripting language designed for simplified object-oriented programming.", "description": "Ruby was developed by Yukihiro \"Matz\" Matsumoto in 1995 with the intent of having an easily readable programming language. It is integrated with the Rails framework to create dynamic web-applications. Ruby's syntax is similar to that of Perl and Python.", "created_by": "Yukihiro Matsumoto", "released": "December 21, 1995", "created_at": "2016-11-28T22:03:59Z", "updated_at": "2017-10-30T18:16:32Z", "featured": true, "curated": true, "score": 1 }, { "name": "rails", "display_name": "Rails", "short_description": "Ruby on Rails (Rails) is a web application framework written in Ruby.", "description": "Ruby on Rails (Rails) is a web application framework written in Ruby. It is meant to help simplify the building of complex websites.", "created_by": "David Heinemeier Hansson", "released": "December 13 2005", "created_at": "2016-12-09T17:03:50Z", "updated_at": "2017-10-30T16:20:19Z", "featured": true, "curated": true, "score": 1 }, { "name": "python", "display_name": "Python", "short_description": "Python is a dynamically typed programming language.", "description": "Python is a dynamically typed programming language designed by Guido Van Rossum. Much like the programming language Ruby, Python was designed to be easily read by programmers. Because of its large following and many libraries, Python can be implemented and used to do anything from webpages to scientific research.", "created_by": "Guido van Rossum", "released": "February 20, 1991", "created_at": "2016-12-07T00:07:02Z", "updated_at": "2017-10-27T22:45:43Z", "featured": true, "curated": true, "score": 1 }, { "name": "jekyll", "display_name": "Jekyll", "short_description": "Jekyll is a simple, blog-aware static site generator.", "description": "Jekyll is a blog-aware, site generator written in Ruby. It takes raw text files, runs it through a renderer and produces a publishable static website.", "created_by": "Tom Preston-Werner", "released": "2008", "created_at": "2016-12-16T21:53:08Z", "updated_at": "2017-10-27T19:00:24Z", "featured": true, "curated": true, "score": 1 }, { "name": "sass", "display_name": "Sass", "short_description": "Sass is a stable extension to classic CSS.", "description": "Sass is a stylesheet language with a main implementation in Ruby. It is an extension of CSS that makes improvements to the old stylesheet format, such as being able to declare variables and using a cleaner nesting syntax.", "created_by": "Hampton Catlin, Natalie Weizenbaum, Chris Eppstein", "released": "November 28, 2006", "created_at": "2016-12-16T21:53:45Z", "updated_at": "2018-01-16T16:30:40Z", "featured": true, "curated": true, "score": 1 }, { "name": "homebrew", "display_name": "Homebrew", "short_description": "Homebrew is a package manager for macOS.", "description": "Homebrew is a package manager for Apple's macOS operating system. It simplifies the installation of software and is popular in the Ruby on Rails community.", "created_by": "Max Howell", "released": "2009", "created_at": "2016-12-17T20:30:44Z", "updated_at": "2018-02-06T16:14:56Z", "featured": true, "curated": true, "score": 1 } ] } }, "user-search-result-item-paginated": { "value": { "total_count": 12, "incomplete_results": false, "items": [ { "login": "mojombo", "id": 1, "node_id": "MDQ6VXNlcjE=", "avatar_url": "https://secure.gravatar.com/avatar/25c7c18223fb42a4c6ae1c8db6f50f9b?d=https://a248.e.akamai.net/assets.github.com%2Fimages%2Fgravatars%2Fgravatar-user-420.png", "gravatar_id": "", "url": "https://api.github.com/users/mojombo", "html_url": "https://github.com/mojombo", "followers_url": "https://api.github.com/users/mojombo/followers", "subscriptions_url": "https://api.github.com/users/mojombo/subscriptions", "organizations_url": "https://api.github.com/users/mojombo/orgs", "repos_url": "https://api.github.com/users/mojombo/repos", "received_events_url": "https://api.github.com/users/mojombo/received_events", "type": "User", "score": 1, "following_url": "https://api.github.com/users/mojombo/following{/other_user}", "gists_url": "https://api.github.com/users/mojombo/gists{/gist_id}", "starred_url": "https://api.github.com/users/mojombo/starred{/owner}{/repo}", "events_url": "https://api.github.com/users/mojombo/events{/privacy}", "site_admin": true } ] } }, "configuration-status": { "value": { "status": "running", "progress": [ { "status": "DONE", "key": "Appliance core components" }, { "status": "DONE", "key": "GitHub utilities" }, { "status": "DONE", "key": "GitHub applications" }, { "status": "CONFIGURING", "key": "GitHub services" }, { "status": "PENDING", "key": "Reloading appliance services" } ] } }, "maintenance-status": { "value": { "status": "scheduled", "scheduled_time": "Tuesday, January 22 at 15:34 -0800", "connection_services": [ { "name": "git operations", "number": 0 }, { "name": "mysql queries", "number": 233 }, { "name": "resque jobs", "number": 54 } ] } }, "enterprise-settings": { "value": { "enterprise": { "private_mode": false, "public_pages": false, "subdomain_isolation": true, "signup_enabled": false, "github_hostname": "ghe.local", "identicons_host": "dotcom", "http_proxy": null, "auth_mode": "default", "expire_sessions": false, "admin_password": null, "configuration_id": 1401777404, "configuration_run_count": 4, "avatar": { "enabled": false, "uri": "" }, "customer": { "name": "GitHub", "email": "stannis@themannis.biz", "uuid": "af6cac80-e4e1-012e-d822-1231380e52e9", "secret_key_data": "-----BEGIN PGP PRIVATE KEY BLOCK-----\nVersion: GnuPG v1.4.10 (GNU/Linux)\n\nlQcYBE5TCgsBEACk4yHpUcapplebaumBMXYMiLF+nCQ0lxpx...\n-----END PGP PRIVATE KEY BLOCK-----\n", "public_key_data": "-----BEGIN PGP PUBLIC KEY BLOCK-----\nVersion: GnuPG v1.4.10 (GNU/Linux)\n\nmI0ETqzZYgEEALSe6snowdenXyqvLfSQ34HWD6C7....\n-----END PGP PUBLIC KEY BLOCK-----\n" }, "license": { "seats": 0, "evaluation": false, "perpetual": false, "unlimited_seating": true, "support_key": "ssh-rsa AAAAB3N....", "ssh_allowed": true, "cluster_support": false, "expire_at": "2016-04-27T00:00:00-07:00" }, "github_ssl": { "enabled": false, "cert": null, "key": null }, "ldap": { "host": null, "port": 0, "base": [ ], "uid": null, "bind_dn": null, "password": null, "method": "Plain", "search_strategy": "detect", "user_groups": [ ], "admin_group": null, "virtual_attribute_enabled": false, "recursive_group_search": false, "posix_support": true, "user_sync_emails": false, "user_sync_keys": false, "user_sync_interval": 4, "team_sync_interval": 4, "sync_enabled": false, "reconciliation": { "user": null, "org": null }, "profile": { "uid": "uid", "name": null, "mail": null, "key": null } }, "cas": { "url": null }, "saml": { "sso_url": null, "certificate": null, "certificate_path": null, "issuer": null, "idp_initiated_sso": false, "disable_admin_demote": false }, "github_oauth": { "client_id": "12313412", "client_secret": "kj123131132", "organization_name": "Homestar Runners", "organization_team": "homestarrunners/characters" }, "smtp": { "enabled": true, "address": "smtp.example.com", "authentication": "plain", "port": "1234", "domain": "blah", "username": "foo", "user_name": "mr_foo", "enable_starttls_auto": true, "password": "bar", "discard-to-noreply-address": true, "support_address": "enterprise@github.com", "support_address_type": "email", "noreply_address": "noreply@github.com" }, "ntp": { "primary_server": "0.pool.ntp.org", "secondary_server": "1.pool.ntp.org" }, "timezone": null, "snmp": { "enabled": false, "community": "" }, "syslog": { "enabled": false, "server": null, "protocol_name": "udp" }, "assets": null, "pages": { "enabled": true }, "collectd": { "enabled": false, "server": null, "port": 0, "encryption": null, "username": null, "password": null }, "mapping": { "enabled": true, "tileserver": null, "basemap": "company.map-qsz2zrvs", "token": null }, "load_balancer": null }, "run_list": [ "recipe[enterprise-configure]" ] } }, "ssh-key-items": { "value": [ { "key": "ssh-rsa AAAAB3NzaC1yc2EAAAAB...", "pretty-print": "ssh-rsa 01:14:0f:f2:0f:e2:fe:e8:f4:72:62:af:75:f7:1a:88:3e:04:92:64" }, { "key": "ssh-rsa AAAAB3NzaC1yc2EAAAAB...", "pretty-print": "ssh-rsa 01:14:0f:f2:0f:e2:fe:e8:f4:72:62:af:75:f7:1a:88:3e:04:92:64" }, { "key": "ssh-rsa AAAAB3NzaC1yc2EAAAAB...", "pretty-print": "ssh-rsa 01:14:0f:f2:0f:e2:fe:e8:f4:72:62:af:75:f7:1a:88:3e:04:92:64" } ] }, "team-repository-alternative-response-with-extra-repository-information": { "value": { "id": 1296269, "node_id": "MDEwOlJlcG9zaXRvcnkxMjk2MjY5", "name": "Hello-World", "full_name": "octocat/Hello-World", "owner": { "login": "octocat", "id": 1, "node_id": "MDQ6VXNlcjE=", "avatar_url": "https://github.com/images/error/octocat_happy.gif", "gravatar_id": "", "url": "https://api.github.com/users/octocat", "html_url": "https://github.com/octocat", "followers_url": "https://api.github.com/users/octocat/followers", "following_url": "https://api.github.com/users/octocat/following{/other_user}", "gists_url": "https://api.github.com/users/octocat/gists{/gist_id}", "starred_url": "https://api.github.com/users/octocat/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/octocat/subscriptions", "organizations_url": "https://api.github.com/users/octocat/orgs", "repos_url": "https://api.github.com/users/octocat/repos", "events_url": "https://api.github.com/users/octocat/events{/privacy}", "received_events_url": "https://api.github.com/users/octocat/received_events", "type": "User", "site_admin": false }, "private": false, "html_url": "https://github.com/octocat/Hello-World", "description": "This your first repo!", "fork": false, "url": "https://api.github.com/repos/octocat/Hello-World", "archive_url": "https://api.github.com/repos/octocat/Hello-World/{archive_format}{/ref}", "assignees_url": "https://api.github.com/repos/octocat/Hello-World/assignees{/user}", "blobs_url": "https://api.github.com/repos/octocat/Hello-World/git/blobs{/sha}", "branches_url": "https://api.github.com/repos/octocat/Hello-World/branches{/branch}", "collaborators_url": "https://api.github.com/repos/octocat/Hello-World/collaborators{/collaborator}", "comments_url": "https://api.github.com/repos/octocat/Hello-World/comments{/number}", "commits_url": "https://api.github.com/repos/octocat/Hello-World/commits{/sha}", "compare_url": "https://api.github.com/repos/octocat/Hello-World/compare/{base}...{head}", "contents_url": "https://api.github.com/repos/octocat/Hello-World/contents/{+path}", "contributors_url": "https://api.github.com/repos/octocat/Hello-World/contributors", "deployments_url": "https://api.github.com/repos/octocat/Hello-World/deployments", "downloads_url": "https://api.github.com/repos/octocat/Hello-World/downloads", "events_url": "https://api.github.com/repos/octocat/Hello-World/events", "forks_url": "https://api.github.com/repos/octocat/Hello-World/forks", "git_commits_url": "https://api.github.com/repos/octocat/Hello-World/git/commits{/sha}", "git_refs_url": "https://api.github.com/repos/octocat/Hello-World/git/refs{/sha}", "git_tags_url": "https://api.github.com/repos/octocat/Hello-World/git/tags{/sha}", "git_url": "git:github.com/octocat/Hello-World.git", "issue_comment_url": "https://api.github.com/repos/octocat/Hello-World/issues/comments{/number}", "issue_events_url": "https://api.github.com/repos/octocat/Hello-World/issues/events{/number}", "issues_url": "https://api.github.com/repos/octocat/Hello-World/issues{/number}", "keys_url": "https://api.github.com/repos/octocat/Hello-World/keys{/key_id}", "labels_url": "https://api.github.com/repos/octocat/Hello-World/labels{/name}", "languages_url": "https://api.github.com/repos/octocat/Hello-World/languages", "merges_url": "https://api.github.com/repos/octocat/Hello-World/merges", "milestones_url": "https://api.github.com/repos/octocat/Hello-World/milestones{/number}", "notifications_url": "https://api.github.com/repos/octocat/Hello-World/notifications{?since,all,participating}", "pulls_url": "https://api.github.com/repos/octocat/Hello-World/pulls{/number}", "releases_url": "https://api.github.com/repos/octocat/Hello-World/releases{/id}", "ssh_url": "git@github.com:octocat/Hello-World.git", "stargazers_url": "https://api.github.com/repos/octocat/Hello-World/stargazers", "statuses_url": "https://api.github.com/repos/octocat/Hello-World/statuses/{sha}", "subscribers_url": "https://api.github.com/repos/octocat/Hello-World/subscribers", "subscription_url": "https://api.github.com/repos/octocat/Hello-World/subscription", "tags_url": "https://api.github.com/repos/octocat/Hello-World/tags", "teams_url": "https://api.github.com/repos/octocat/Hello-World/teams", "trees_url": "https://api.github.com/repos/octocat/Hello-World/git/trees{/sha}", "clone_url": "https://github.com/octocat/Hello-World.git", "mirror_url": "git:git.example.com/octocat/Hello-World", "hooks_url": "https://api.github.com/repos/octocat/Hello-World/hooks", "svn_url": "https://svn.github.com/octocat/Hello-World", "homepage": "https://github.com", "forks_count": 9, "stargazers_count": 80, "watchers_count": 80, "size": 108, "default_branch": "master", "open_issues_count": 0, "is_template": false, "topics": [ "octocat", "atom", "electron", "api" ], "has_issues": true, "has_projects": true, "has_wiki": true, "has_pages": false, "has_downloads": true, "archived": false, "disabled": false, "visibility": "public", "pushed_at": "2011-01-26T19:06:43Z", "created_at": "2011-01-26T19:01:12Z", "updated_at": "2011-01-26T19:14:43Z", "permissions": { "admin": false, "maintain": false, "push": false, "triage": false, "pull": true }, "allow_rebase_merge": true, "template_repository": { "id": 1296269, "node_id": "MDEwOlJlcG9zaXRvcnkxMjk2MjY5", "name": "Hello-World-Template", "full_name": "octocat/Hello-World-Template", "owner": { "login": "octocat", "id": 1, "node_id": "MDQ6VXNlcjE=", "avatar_url": "https://github.com/images/error/octocat_happy.gif", "gravatar_id": "", "url": "https://api.github.com/users/octocat", "html_url": "https://github.com/octocat", "followers_url": "https://api.github.com/users/octocat/followers", "following_url": "https://api.github.com/users/octocat/following{/other_user}", "gists_url": "https://api.github.com/users/octocat/gists{/gist_id}", "starred_url": "https://api.github.com/users/octocat/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/octocat/subscriptions", "organizations_url": "https://api.github.com/users/octocat/orgs", "repos_url": "https://api.github.com/users/octocat/repos", "events_url": "https://api.github.com/users/octocat/events{/privacy}", "received_events_url": "https://api.github.com/users/octocat/received_events", "type": "User", "site_admin": false }, "private": false, "html_url": "https://github.com/octocat/Hello-World-Template", "description": "This your first repo!", "fork": false, "url": "https://api.github.com/repos/octocat/Hello-World-Template", "archive_url": "https://api.github.com/repos/octocat/Hello-World-Template/{archive_format}{/ref}", "assignees_url": "https://api.github.com/repos/octocat/Hello-World-Template/assignees{/user}", "blobs_url": "https://api.github.com/repos/octocat/Hello-World-Template/git/blobs{/sha}", "branches_url": "https://api.github.com/repos/octocat/Hello-World-Template/branches{/branch}", "collaborators_url": "https://api.github.com/repos/octocat/Hello-World-Template/collaborators{/collaborator}", "comments_url": "https://api.github.com/repos/octocat/Hello-World-Template/comments{/number}", "commits_url": "https://api.github.com/repos/octocat/Hello-World-Template/commits{/sha}", "compare_url": "https://api.github.com/repos/octocat/Hello-World-Template/compare/{base}...{head}", "contents_url": "https://api.github.com/repos/octocat/Hello-World-Template/contents/{+path}", "contributors_url": "https://api.github.com/repos/octocat/Hello-World-Template/contributors", "deployments_url": "https://api.github.com/repos/octocat/Hello-World-Template/deployments", "downloads_url": "https://api.github.com/repos/octocat/Hello-World-Template/downloads", "events_url": "https://api.github.com/repos/octocat/Hello-World-Template/events", "forks_url": "https://api.github.com/repos/octocat/Hello-World-Template/forks", "git_commits_url": "https://api.github.com/repos/octocat/Hello-World-Template/git/commits{/sha}", "git_refs_url": "https://api.github.com/repos/octocat/Hello-World-Template/git/refs{/sha}", "git_tags_url": "https://api.github.com/repos/octocat/Hello-World-Template/git/tags{/sha}", "git_url": "git:github.com/octocat/Hello-World-Template.git", "issue_comment_url": "https://api.github.com/repos/octocat/Hello-World-Template/issues/comments{/number}", "issue_events_url": "https://api.github.com/repos/octocat/Hello-World-Template/issues/events{/number}", "issues_url": "https://api.github.com/repos/octocat/Hello-World-Template/issues{/number}", "keys_url": "https://api.github.com/repos/octocat/Hello-World-Template/keys{/key_id}", "labels_url": "https://api.github.com/repos/octocat/Hello-World-Template/labels{/name}", "languages_url": "https://api.github.com/repos/octocat/Hello-World-Template/languages", "merges_url": "https://api.github.com/repos/octocat/Hello-World-Template/merges", "milestones_url": "https://api.github.com/repos/octocat/Hello-World-Template/milestones{/number}", "notifications_url": "https://api.github.com/repos/octocat/Hello-World-Template/notifications{?since,all,participating}", "pulls_url": "https://api.github.com/repos/octocat/Hello-World-Template/pulls{/number}", "releases_url": "https://api.github.com/repos/octocat/Hello-World-Template/releases{/id}", "ssh_url": "git@github.com:octocat/Hello-World-Template.git", "stargazers_url": "https://api.github.com/repos/octocat/Hello-World-Template/stargazers", "statuses_url": "https://api.github.com/repos/octocat/Hello-World-Template/statuses/{sha}", "subscribers_url": "https://api.github.com/repos/octocat/Hello-World-Template/subscribers", "subscription_url": "https://api.github.com/repos/octocat/Hello-World-Template/subscription", "tags_url": "https://api.github.com/repos/octocat/Hello-World-Template/tags", "teams_url": "https://api.github.com/repos/octocat/Hello-World-Template/teams", "trees_url": "https://api.github.com/repos/octocat/Hello-World-Template/git/trees{/sha}", "clone_url": "https://github.com/octocat/Hello-World-Template.git", "mirror_url": "git:git.example.com/octocat/Hello-World-Template", "hooks_url": "https://api.github.com/repos/octocat/Hello-World-Template/hooks", "svn_url": "https://svn.github.com/octocat/Hello-World-Template", "homepage": "https://github.com", "forks": 9, "forks_count": 9, "stargazers_count": 80, "watchers_count": 80, "watchers": 80, "size": 108, "default_branch": "master", "open_issues": 0, "open_issues_count": 0, "is_template": true, "license": { "key": "mit", "name": "MIT License", "url": "https://api.github.com/licenses/mit", "spdx_id": "MIT", "node_id": "MDc6TGljZW5zZW1pdA==", "html_url": "https://api.github.com/licenses/mit" }, "topics": [ "octocat", "atom", "electron", "api" ], "has_issues": true, "has_projects": true, "has_wiki": true, "has_pages": false, "has_downloads": true, "archived": false, "disabled": false, "visibility": "public", "pushed_at": "2011-01-26T19:06:43Z", "created_at": "2011-01-26T19:01:12Z", "updated_at": "2011-01-26T19:14:43Z", "permissions": { "pull": true, "triage": false, "push": false, "maintain": false, "admin": false }, "allow_rebase_merge": true, "temp_clone_token": "ABTLWHOULUVAXGTRYU7OC2876QJ2O", "allow_squash_merge": true, "delete_branch_on_merge": true, "allow_merge_commit": true, "subscribers_count": 42, "network_count": 0 }, "temp_clone_token": "ABTLWHOULUVAXGTRYU7OC2876QJ2O", "allow_squash_merge": true, "delete_branch_on_merge": true, "allow_merge_commit": true, "subscribers_count": 42, "network_count": 0, "license": { "key": "mit", "name": "MIT License", "url": "https://api.github.com/licenses/mit", "spdx_id": "MIT", "node_id": "MDc6TGljZW5zZW1pdA==", "html_url": "https://api.github.com/licenses/mit" }, "forks": 1, "open_issues": 1, "watchers": 1 } }, "private-user-response-with-public-and-private-profile-information": { "summary": "Response with public and private profile information", "value": { "login": "octocat", "id": 1, "node_id": "MDQ6VXNlcjE=", "avatar_url": "https://github.com/images/error/octocat_happy.gif", "gravatar_id": "", "url": "https://api.github.com/users/octocat", "html_url": "https://github.com/octocat", "followers_url": "https://api.github.com/users/octocat/followers", "following_url": "https://api.github.com/users/octocat/following{/other_user}", "gists_url": "https://api.github.com/users/octocat/gists{/gist_id}", "starred_url": "https://api.github.com/users/octocat/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/octocat/subscriptions", "organizations_url": "https://api.github.com/users/octocat/orgs", "repos_url": "https://api.github.com/users/octocat/repos", "events_url": "https://api.github.com/users/octocat/events{/privacy}", "received_events_url": "https://api.github.com/users/octocat/received_events", "type": "User", "site_admin": false, "name": "monalisa octocat", "company": "GitHub", "blog": "https://github.com/blog", "location": "San Francisco", "email": "octocat@github.com", "hireable": false, "bio": "There once was...", "public_repos": 2, "public_gists": 1, "followers": 20, "following": 0, "created_at": "2008-01-14T04:33:35Z", "updated_at": "2008-01-14T04:33:35Z", "private_gists": 81, "total_private_repos": 100, "owned_private_repos": 100, "disk_usage": 10000, "collaborators": 8, "two_factor_authentication": true, "plan": { "name": "Medium", "space": 400, "private_repos": 20, "collaborators": 0 } } }, "private-user-response-with-public-profile-information": { "summary": "Response with public profile information", "value": { "login": "octocat", "id": 1, "node_id": "MDQ6VXNlcjE=", "avatar_url": "https://github.com/images/error/octocat_happy.gif", "gravatar_id": "", "url": "https://api.github.com/users/octocat", "html_url": "https://github.com/octocat", "followers_url": "https://api.github.com/users/octocat/followers", "following_url": "https://api.github.com/users/octocat/following{/other_user}", "gists_url": "https://api.github.com/users/octocat/gists{/gist_id}", "starred_url": "https://api.github.com/users/octocat/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/octocat/subscriptions", "organizations_url": "https://api.github.com/users/octocat/orgs", "repos_url": "https://api.github.com/users/octocat/repos", "events_url": "https://api.github.com/users/octocat/events{/privacy}", "received_events_url": "https://api.github.com/users/octocat/received_events", "type": "User", "site_admin": false, "name": "monalisa octocat", "company": "GitHub", "blog": "https://github.com/blog", "location": "San Francisco", "email": "octocat@github.com", "hireable": false, "bio": "There once was...", "public_repos": 2, "public_gists": 1, "followers": 20, "following": 0, "created_at": "2008-01-14T04:33:35Z", "updated_at": "2008-01-14T04:33:35Z" } }, "private-user": { "value": { "login": "octocat", "id": 1, "node_id": "MDQ6VXNlcjE=", "avatar_url": "https://github.com/images/error/octocat_happy.gif", "gravatar_id": "", "url": "https://api.github.com/users/octocat", "html_url": "https://github.com/octocat", "followers_url": "https://api.github.com/users/octocat/followers", "following_url": "https://api.github.com/users/octocat/following{/other_user}", "gists_url": "https://api.github.com/users/octocat/gists{/gist_id}", "starred_url": "https://api.github.com/users/octocat/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/octocat/subscriptions", "organizations_url": "https://api.github.com/users/octocat/orgs", "repos_url": "https://api.github.com/users/octocat/repos", "events_url": "https://api.github.com/users/octocat/events{/privacy}", "received_events_url": "https://api.github.com/users/octocat/received_events", "type": "User", "site_admin": false, "name": "monalisa octocat", "company": "GitHub", "blog": "https://github.com/blog", "location": "San Francisco", "email": "octocat@github.com", "hireable": false, "bio": "There once was...", "public_repos": 2, "public_gists": 1, "followers": 20, "following": 0, "created_at": "2008-01-14T04:33:35Z", "updated_at": "2008-01-14T04:33:35Z", "private_gists": 81, "total_private_repos": 100, "owned_private_repos": 100, "disk_usage": 10000, "collaborators": 8, "two_factor_authentication": true, "plan": { "name": "Medium", "space": 400, "private_repos": 20, "collaborators": 0 } } }, "email-items-2": { "value": [ { "email": "octocat@github.com", "verified": true, "primary": true, "visibility": "public" } ] }, "email-items": { "value": [ { "email": "octocat@octocat.org", "primary": false, "verified": false, "visibility": "public" }, { "email": "octocat@github.com", "primary": false, "verified": false, "visibility": null }, { "email": "mona@github.com", "primary": false, "verified": false, "visibility": null } ] }, "gpg-key-items": { "value": [ { "id": 3, "primary_key_id": 2, "key_id": "3262EFF25BA0D270", "public_key": "xsBNBFayYZ...", "emails": [ { "email": "mastahyeti@users.noreply.github.com", "verified": true } ], "subkeys": [ { "id": 4, "primary_key_id": 3, "key_id": "4A595D4C72EE49C7", "public_key": "zsBNBFayYZ...", "emails": [ ], "subkeys": [ ], "can_sign": false, "can_encrypt_comms": true, "can_encrypt_storage": true, "can_certify": false, "created_at": "2016-03-24T11:31:04-06:00", "expires_at": "2016-03-24T11:31:04-07:00" } ], "can_sign": true, "can_encrypt_comms": false, "can_encrypt_storage": false, "can_certify": true, "created_at": "2016-03-24T11:31:04-06:00", "expires_at": "2016-03-24T11:31:04-07:00", "raw_key": "string" } ] }, "gpg-key": { "value": { "id": 3, "primary_key_id": 2, "key_id": "3262EFF25BA0D270", "public_key": "xsBNBFayYZ...", "emails": [ { "email": "mastahyeti@users.noreply.github.com", "verified": true } ], "subkeys": [ { "id": 4, "primary_key_id": 3, "key_id": "4A595D4C72EE49C7", "public_key": "zsBNBFayYZ...", "emails": [ ], "subkeys": [ ], "can_sign": false, "can_encrypt_comms": true, "can_encrypt_storage": true, "can_certify": false, "created_at": "2016-03-24T11:31:04-06:00", "expires_at": "2016-03-24T11:31:04-07:00" } ], "can_sign": true, "can_encrypt_comms": false, "can_encrypt_storage": false, "can_certify": true, "created_at": "2016-03-24T11:31:04-06:00", "expires_at": "2016-03-24T11:31:04-07:00", "raw_key": "\"-----BEGIN PGP PUBLIC KEY BLOCK-----\\nVersion: GnuPG v2\\n\\nmQENBFayYZ0BCAC4hScoJXXpyR+MXGcrBxElqw3FzCVvkViuyeko+Jp76QJhg8kr\\nucRTxbnOoHfda/FmilEa/wxf9ch5/PSrrL26FxEoPHhJolp8fnIDLQeITn94NYdB\\nZtnnEKslpPrG97qSUWIchvyqCPtvOb8+8fWvGx9K/ZWcEEdh1X8+WFR2jMENMeoX\\nwxHWQoPnS7LpX/85/M7VUcJxvDVfv+eHsnQupmE5bGarKNih0oMe3LbdN3qA5PTz\\nSCm6Iudar1VsQ+xTz08ymL7t4pnEtLguQ7EyatFHCjxNblv5RzxoL0tDgN3HqoDz\\nc7TEA+q4RtDQl9amcvQ95emnXmZ974u7UkYdABEBAAG0HlNvbWUgVXNlciA8c29t\\nZXVzZXJAZ21haWwuY29tPokBOAQTAQIAIgUCVrJhnQIbAwYLCQgHAwIGFQgCCQoL\\nBBYCAwECHgECF4AACgkQMmLv8lug0nAViQgArWjI55+7p48URr2z9Jvak+yrBTx1\\nzkufltQAnHTJkq+Kl9dySSmTnOop8o3rE4++IOpYV5Y36PkKf9EZMk4n1RQiDPKE\\nAFtRVTkRaoWzOir9KQXJPfhKrl01j/QzY+utfiMvUoBJZ9ybq8Pa885SljW9lbaX\\nIYw+hl8ZdJ2KStvGrEyfQvRyq3aN5c9TV//4BdGnwx7Qabq/U+G18lizG6f/yq15\\ned7t0KELaCfeKPvytp4VE9/z/Ksah/h3+Qilx07/oG2Ae5kC1bEC9coD/ogPUhbv\\nb2bsBIoY9E9YwsLoif2lU+o1t76zLgUktuNscRRUKobW028H1zuFS/XQhrkBDQRW\\nsmGdAQgApnyyv3i144OLYy0O4UKQxd3e10Y3WpDwfnGIBefAI1m7RxnUxBag/DsU\\n7gi9qLEC4VHSfq4eiNfr1LJOyCL2edTgCWFgBhVjbXjZe6YAOrAnhxwCErnN0Y7N\\n6s8wVh9fObSOyf8ZE6G7JeKpcq9Q6gd/KxagfD48a1v+fyRHpyQc6J9pUEmtrDJ7\\nBjmsd2VWzLBvNWdHyxDNtZweIaqIO9VUYYpr1mtTliNBOZLUelmgrt7HBRcJpWMA\\nS8muVVbuP5MK0trLBq/JB8qUH3zRzB/PhMgzmkIfjEK1VYDWm4E8DYyTWEJcHqkb\\neqFsNjrIlwPaA122BWC6gUOPwwH+oQARAQABiQEfBBgBAgAJBQJWsmGdAhsMAAoJ\\nEDJi7/JboNJwAyAIALd4xcdmGbZD98gScJzqwzkOMcO8zFHqHNvJ42xIFvGny7c0\\n1Rx7iyrdypOby5AxE+viQcjG4rpLZW/xKYBNGrCfDyQO7511I0v8x20EICMlMfD/\\nNrWQCzesEPcUlKTP07d+sFyP8AyseOidbzY/92CpskTgdSBjY/ntLSaoknl/fjJE\\nQM8OkPqU7IraO1Jzzdnm20d5PZL9+PIwIWdSTedU/vBMTJyNcoqvSfKf1wNC66XP\\nhqfYgXJE564AdWZKA3C0IyCqiv+LHwxLnUHio1a4/r91C8KPzxs6tGxRDjXLd7ms\\nuYFGWymiUGOE/giHlcxdYcHzwLnPDliMQOLiTkK5AQ0EVuxMygEIAOD+bW1cDTmE\\nBxh5JECoqeHuwgl6DlLhnubWPkQ4ZeRzBRAsFcEJQlwlJjrzFDicL+lnm6Qq4tt0\\n560TwHdf15/AKTZIZu7H25axvGNzgeaUkJEJdYAq9zTKWwX7wKyzBszi485nQg97\\nMfAqwhMpDW0Qqf8+7Ug+WEmfBSGv9uL3aQC6WEeIsHfri0n0n8v4XgwhfShXguxO\\nCsOztEsuW7WWKW9P4TngKKv4lCHdPlV6FwxeMzODBJvc2fkHVHnqc0PqszJ5xcF8\\n6gZCpMM027SbpeYWCAD5zwJyYP9ntfO1p2HjnQ1dZaP9FeNcO7uIV1Lnd1eGCu6I\\nsrVp5k1f3isAEQEAAYkCPgQYAQIACQUCVuxMygIbAgEpCRAyYu/yW6DScMBdIAQZ\\nAQIABgUCVuxMygAKCRCKohN4dhq2b4tcCACHxmOHVXNpu47OvUGYQydLgMACUlXN\\nlj+HfE0VReqShxdDmpasAY9IRpuMB2RsGK8GbNP+4SlOlAiPf5SMhS7nZNkNDgQQ\\naZ3HFpgrFmFwmE10BKT4iQtoxELLM57z0qGOAfTsEjWFQa4sF+6IHAQR/ptkdkkI\\nBUEXiMnAwVwBysLIJiLO8qdjB6qp52QkT074JVrwywT/P+DkMfC2k4r/AfEbf6eF\\ndmPDuPk6KD87+hJZsSa5MaMUBQVvRO/mgEkhJRITVu58eWGaBOcQJ8gqurhCqM5P\\nDfUA4TJ7wiqM6sS764vV1rOioTTXkszzhClQqET7hPVnVQjenYgv0EZHNyQH/1f1\\n/CYqvV1vFjM9vJjMbxXsATCkZe6wvBVKD8vLsJAr8N+onKQz+4OPc3kmKq7aESu3\\nCi/iuie5KKVwnuNhr9AzT61vEkKxwHcVFEvHB77F6ZAAInhRvjzmQbD2dlPLLQCC\\nqDj71ODSSAPTEmUy6969bgD9PfWei7kNkBIx7s3eBv8yzytSc2EcuUgopqFazquw\\nFs1+tqGHjBvQfTo6bqbJjp/9Ci2pvde3ElV2rAgUlb3lqXyXjRDqrXosh5GcRPQj\\nK8Nhj1BNhnrCVskE4BP0LYbOHuzgm86uXwGCFsY+w2VOsSm16Jx5GHyG5S5WU3+D\\nIts/HFYRLiFgDLmTlxo=\\n=+OzK\\n-----END PGP PUBLIC KEY BLOCK-----\"" } }, "base-installation-for-auth-user-paginated": { "value": { "total_count": 2, "installations": [ { "id": 1, "account": { "login": "octocat", "id": 1, "node_id": "MDQ6VXNlcjE=", "avatar_url": "https://github.com/images/error/octocat_happy.gif", "gravatar_id": "", "url": "https://api.github.com/users/octocat", "html_url": "https://github.com/octocat", "followers_url": "https://api.github.com/users/octocat/followers", "following_url": "https://api.github.com/users/octocat/following{/other_user}", "gists_url": "https://api.github.com/users/octocat/gists{/gist_id}", "starred_url": "https://api.github.com/users/octocat/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/octocat/subscriptions", "organizations_url": "https://api.github.com/users/octocat/orgs", "repos_url": "https://api.github.com/users/octocat/repos", "events_url": "https://api.github.com/users/octocat/events{/privacy}", "received_events_url": "https://api.github.com/users/octocat/received_events", "type": "User", "site_admin": false }, "access_tokens_url": "https://api.github.com/installations/1/access_tokens", "repositories_url": "https://api.github.com/installation/repositories", "html_url": "https://github.com/organizations/github/settings/installations/1", "app_id": 1, "target_id": 1, "target_type": "Organization", "permissions": { "checks": "write", "metadata": "read", "contents": "read" }, "events": [ "push", "pull_request" ], "single_file_name": "config.yaml", "has_multiple_single_files": true, "single_file_paths": [ "config.yml", ".github/issue_TEMPLATE.md" ], "repository_selection": "all", "created_at": "2017-07-08T16:18:44-04:00", "updated_at": "2017-07-08T16:18:44-04:00", "app_slug": "github-actions", "suspended_at": null, "suspended_by": null }, { "id": 3, "account": { "login": "octocat", "id": 2, "node_id": "MDQ6VXNlcjE=", "avatar_url": "https://github.com/images/error/octocat_happy.gif", "gravatar_id": "", "url": "https://api.github.com/users/octocat", "html_url": "https://github.com/octocat", "followers_url": "https://api.github.com/users/octocat/followers", "following_url": "https://api.github.com/users/octocat/following{/other_user}", "gists_url": "https://api.github.com/users/octocat/gists{/gist_id}", "starred_url": "https://api.github.com/users/octocat/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/octocat/subscriptions", "organizations_url": "https://api.github.com/users/octocat/orgs", "repos_url": "https://api.github.com/users/octocat/repos", "events_url": "https://api.github.com/users/octocat/events{/privacy}", "received_events_url": "https://api.github.com/users/octocat/received_events", "type": "User", "site_admin": false }, "access_tokens_url": "https://api.github.com/installations/1/access_tokens", "repositories_url": "https://api.github.com/installation/repositories", "html_url": "https://github.com/organizations/github/settings/installations/1", "app_id": 1, "target_id": 1, "target_type": "Organization", "permissions": { "checks": "write", "metadata": "read", "contents": "read" }, "events": [ "push", "pull_request" ], "single_file_name": "config.yaml", "has_multiple_single_files": true, "single_file_paths": [ "config.yml", ".github/issue_TEMPLATE.md" ], "repository_selection": "all", "created_at": "2017-07-08T16:18:44-04:00", "updated_at": "2017-07-08T16:18:44-04:00", "app_slug": "github-actions", "suspended_at": null, "suspended_by": null } ] } }, "key-items": { "value": [ { "key": "2Sg8iYjAxxmI2LvUXpJjkYrMxURPc8r+dB7TJyvv1234", "id": 2, "url": "https://api.github.com/user/keys/2", "title": "ssh-rsa AAAAB3NzaC1yc2EAAA", "created_at": "2020-06-11T21:31:57Z", "verified": false, "read_only": false }, { "key": "2Sg8iYjAxxmI2LvUXpJjkYrMxURPc8r+dB7TJy931234", "id": 3, "url": "https://api.github.com/user/keys/3", "title": "ssh-rsa AAAAB3NzaC1yc2EAAB", "created_at": "2020-07-11T21:31:57Z", "verified": false, "read_only": false } ] }, "key": { "value": { "key": "2Sg8iYjAxxmI2LvUXpJjkYrMxURPc8r+dB7TJyvv1234", "id": 2, "url": "https://api.github.com/user/keys/2", "title": "ssh-rsa AAAAB3NzaC1yc2EAAA", "created_at": "2020-06-11T21:31:57Z", "verified": false, "read_only": false } }, "org-membership-items": { "value": [ { "url": "https://api.github.com/orgs/octocat/memberships/defunkt", "state": "active", "role": "admin", "organization_url": "https://api.github.com/orgs/octocat", "organization": { "login": "github", "id": 1, "node_id": "MDEyOk9yZ2FuaXphdGlvbjE=", "url": "https://api.github.com/orgs/github", "repos_url": "https://api.github.com/orgs/github/repos", "events_url": "https://api.github.com/orgs/github/events", "hooks_url": "https://api.github.com/orgs/github/hooks", "issues_url": "https://api.github.com/orgs/github/issues", "members_url": "https://api.github.com/orgs/github/members{/member}", "public_members_url": "https://api.github.com/orgs/github/public_members{/member}", "avatar_url": "https://github.com/images/error/octocat_happy.gif", "description": "A great organization" }, "user": { "login": "octocat", "id": 1, "node_id": "MDQ6VXNlcjE=", "avatar_url": "https://github.com/images/error/octocat_happy.gif", "gravatar_id": "", "url": "https://api.github.com/users/octocat", "html_url": "https://github.com/octocat", "followers_url": "https://api.github.com/users/octocat/followers", "following_url": "https://api.github.com/users/octocat/following{/other_user}", "gists_url": "https://api.github.com/users/octocat/gists{/gist_id}", "starred_url": "https://api.github.com/users/octocat/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/octocat/subscriptions", "organizations_url": "https://api.github.com/users/octocat/orgs", "repos_url": "https://api.github.com/users/octocat/repos", "events_url": "https://api.github.com/users/octocat/events{/privacy}", "received_events_url": "https://api.github.com/users/octocat/received_events", "type": "User", "site_admin": false } }, { "url": "https://api.github.com/orgs/invitocat/memberships/defunkt", "state": "pending", "role": "admin", "organization_url": "https://api.github.com/orgs/invitocat", "organization": { "login": "github", "id": 1, "node_id": "MDEyOk9yZ2FuaXphdGlvbjE=", "url": "https://api.github.com/orgs/github", "repos_url": "https://api.github.com/orgs/github/repos", "events_url": "https://api.github.com/orgs/github/events", "hooks_url": "https://api.github.com/orgs/github/hooks", "issues_url": "https://api.github.com/orgs/github/issues", "members_url": "https://api.github.com/orgs/github/members{/member}", "public_members_url": "https://api.github.com/orgs/github/public_members{/member}", "avatar_url": "https://github.com/images/error/octocat_happy.gif", "description": "A great organization" }, "user": { "login": "octocat", "id": 1, "node_id": "MDQ6VXNlcjE=", "avatar_url": "https://github.com/images/error/octocat_happy.gif", "gravatar_id": "", "url": "https://api.github.com/users/octocat", "html_url": "https://github.com/octocat", "followers_url": "https://api.github.com/users/octocat/followers", "following_url": "https://api.github.com/users/octocat/following{/other_user}", "gists_url": "https://api.github.com/users/octocat/gists{/gist_id}", "starred_url": "https://api.github.com/users/octocat/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/octocat/subscriptions", "organizations_url": "https://api.github.com/users/octocat/orgs", "repos_url": "https://api.github.com/users/octocat/repos", "events_url": "https://api.github.com/users/octocat/events{/privacy}", "received_events_url": "https://api.github.com/users/octocat/received_events", "type": "User", "site_admin": false } } ] }, "org-membership": { "value": { "url": "https://api.github.com/orgs/invitocat/memberships/defunkt", "state": "pending", "role": "admin", "organization_url": "https://api.github.com/orgs/invitocat", "organization": { "login": "github", "id": 1, "node_id": "MDEyOk9yZ2FuaXphdGlvbjE=", "url": "https://api.github.com/orgs/github", "repos_url": "https://api.github.com/orgs/github/repos", "events_url": "https://api.github.com/orgs/github/events", "hooks_url": "https://api.github.com/orgs/github/hooks", "issues_url": "https://api.github.com/orgs/github/issues", "members_url": "https://api.github.com/orgs/github/members{/member}", "public_members_url": "https://api.github.com/orgs/github/public_members{/member}", "avatar_url": "https://github.com/images/error/octocat_happy.gif", "description": "A great organization" }, "user": { "login": "octocat", "id": 1, "node_id": "MDQ6VXNlcjE=", "avatar_url": "https://github.com/images/error/octocat_happy.gif", "gravatar_id": "", "url": "https://api.github.com/users/octocat", "html_url": "https://github.com/octocat", "followers_url": "https://api.github.com/users/octocat/followers", "following_url": "https://api.github.com/users/octocat/following{/other_user}", "gists_url": "https://api.github.com/users/octocat/gists{/gist_id}", "starred_url": "https://api.github.com/users/octocat/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/octocat/subscriptions", "organizations_url": "https://api.github.com/users/octocat/orgs", "repos_url": "https://api.github.com/users/octocat/repos", "events_url": "https://api.github.com/users/octocat/events{/privacy}", "received_events_url": "https://api.github.com/users/octocat/received_events", "type": "User", "site_admin": false } } }, "org-membership-2": { "value": { "url": "https://api.github.com/orgs/octocat/memberships/defunkt", "state": "active", "role": "admin", "organization_url": "https://api.github.com/orgs/octocat", "organization": { "login": "github", "id": 1, "node_id": "MDEyOk9yZ2FuaXphdGlvbjE=", "url": "https://api.github.com/orgs/github", "repos_url": "https://api.github.com/orgs/github/repos", "events_url": "https://api.github.com/orgs/github/events", "hooks_url": "https://api.github.com/orgs/github/hooks", "issues_url": "https://api.github.com/orgs/github/issues", "members_url": "https://api.github.com/orgs/github/members{/member}", "public_members_url": "https://api.github.com/orgs/github/public_members{/member}", "avatar_url": "https://github.com/images/error/octocat_happy.gif", "description": "A great organization" }, "user": { "login": "octocat", "id": 1, "node_id": "MDQ6VXNlcjE=", "avatar_url": "https://github.com/images/error/octocat_happy.gif", "gravatar_id": "", "url": "https://api.github.com/users/octocat", "html_url": "https://github.com/octocat", "followers_url": "https://api.github.com/users/octocat/followers", "following_url": "https://api.github.com/users/octocat/following{/other_user}", "gists_url": "https://api.github.com/users/octocat/gists{/gist_id}", "starred_url": "https://api.github.com/users/octocat/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/octocat/subscriptions", "organizations_url": "https://api.github.com/users/octocat/orgs", "repos_url": "https://api.github.com/users/octocat/repos", "events_url": "https://api.github.com/users/octocat/events{/privacy}", "received_events_url": "https://api.github.com/users/octocat/received_events", "type": "User", "site_admin": false } } }, "project": { "value": { "owner_url": "https://api.github.com/users/octocat", "url": "https://api.github.com/projects/1002603", "html_url": "https://github.com/users/octocat/projects/1", "columns_url": "https://api.github.com/projects/1002603/columns", "id": 1002603, "node_id": "MDc6UHJvamVjdDEwMDI2MDM=", "name": "My Projects", "body": "A board to manage my personal projects.", "number": 1, "state": "open", "creator": { "login": "octocat", "id": 1, "node_id": "MDQ6VXNlcjE=", "avatar_url": "https://github.com/images/error/octocat_happy.gif", "gravatar_id": "", "url": "https://api.github.com/users/octocat", "html_url": "https://github.com/octocat", "followers_url": "https://api.github.com/users/octocat/followers", "following_url": "https://api.github.com/users/octocat/following{/other_user}", "gists_url": "https://api.github.com/users/octocat/gists{/gist_id}", "starred_url": "https://api.github.com/users/octocat/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/octocat/subscriptions", "organizations_url": "https://api.github.com/users/octocat/orgs", "repos_url": "https://api.github.com/users/octocat/repos", "events_url": "https://api.github.com/users/octocat/events{/privacy}", "received_events_url": "https://api.github.com/users/octocat/received_events", "type": "User", "site_admin": false }, "created_at": "2011-04-10T20:09:31Z", "updated_at": "2014-03-03T18:58:10Z" } }, "repository-items-default-response": { "summary": "Default response", "value": [ { "id": 1296269, "node_id": "MDEwOlJlcG9zaXRvcnkxMjk2MjY5", "name": "Hello-World", "full_name": "octocat/Hello-World", "owner": { "login": "octocat", "id": 1, "node_id": "MDQ6VXNlcjE=", "avatar_url": "https://github.com/images/error/octocat_happy.gif", "gravatar_id": "", "url": "https://api.github.com/users/octocat", "html_url": "https://github.com/octocat", "followers_url": "https://api.github.com/users/octocat/followers", "following_url": "https://api.github.com/users/octocat/following{/other_user}", "gists_url": "https://api.github.com/users/octocat/gists{/gist_id}", "starred_url": "https://api.github.com/users/octocat/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/octocat/subscriptions", "organizations_url": "https://api.github.com/users/octocat/orgs", "repos_url": "https://api.github.com/users/octocat/repos", "events_url": "https://api.github.com/users/octocat/events{/privacy}", "received_events_url": "https://api.github.com/users/octocat/received_events", "type": "User", "site_admin": false }, "private": false, "html_url": "https://github.com/octocat/Hello-World", "description": "This your first repo!", "fork": false, "url": "https://api.github.com/repos/octocat/Hello-World", "archive_url": "https://api.github.com/repos/octocat/Hello-World/{archive_format}{/ref}", "assignees_url": "https://api.github.com/repos/octocat/Hello-World/assignees{/user}", "blobs_url": "https://api.github.com/repos/octocat/Hello-World/git/blobs{/sha}", "branches_url": "https://api.github.com/repos/octocat/Hello-World/branches{/branch}", "collaborators_url": "https://api.github.com/repos/octocat/Hello-World/collaborators{/collaborator}", "comments_url": "https://api.github.com/repos/octocat/Hello-World/comments{/number}", "commits_url": "https://api.github.com/repos/octocat/Hello-World/commits{/sha}", "compare_url": "https://api.github.com/repos/octocat/Hello-World/compare/{base}...{head}", "contents_url": "https://api.github.com/repos/octocat/Hello-World/contents/{+path}", "contributors_url": "https://api.github.com/repos/octocat/Hello-World/contributors", "deployments_url": "https://api.github.com/repos/octocat/Hello-World/deployments", "downloads_url": "https://api.github.com/repos/octocat/Hello-World/downloads", "events_url": "https://api.github.com/repos/octocat/Hello-World/events", "forks_url": "https://api.github.com/repos/octocat/Hello-World/forks", "git_commits_url": "https://api.github.com/repos/octocat/Hello-World/git/commits{/sha}", "git_refs_url": "https://api.github.com/repos/octocat/Hello-World/git/refs{/sha}", "git_tags_url": "https://api.github.com/repos/octocat/Hello-World/git/tags{/sha}", "git_url": "git:github.com/octocat/Hello-World.git", "issue_comment_url": "https://api.github.com/repos/octocat/Hello-World/issues/comments{/number}", "issue_events_url": "https://api.github.com/repos/octocat/Hello-World/issues/events{/number}", "issues_url": "https://api.github.com/repos/octocat/Hello-World/issues{/number}", "keys_url": "https://api.github.com/repos/octocat/Hello-World/keys{/key_id}", "labels_url": "https://api.github.com/repos/octocat/Hello-World/labels{/name}", "languages_url": "https://api.github.com/repos/octocat/Hello-World/languages", "merges_url": "https://api.github.com/repos/octocat/Hello-World/merges", "milestones_url": "https://api.github.com/repos/octocat/Hello-World/milestones{/number}", "notifications_url": "https://api.github.com/repos/octocat/Hello-World/notifications{?since,all,participating}", "pulls_url": "https://api.github.com/repos/octocat/Hello-World/pulls{/number}", "releases_url": "https://api.github.com/repos/octocat/Hello-World/releases{/id}", "ssh_url": "git@github.com:octocat/Hello-World.git", "stargazers_url": "https://api.github.com/repos/octocat/Hello-World/stargazers", "statuses_url": "https://api.github.com/repos/octocat/Hello-World/statuses/{sha}", "subscribers_url": "https://api.github.com/repos/octocat/Hello-World/subscribers", "subscription_url": "https://api.github.com/repos/octocat/Hello-World/subscription", "tags_url": "https://api.github.com/repos/octocat/Hello-World/tags", "teams_url": "https://api.github.com/repos/octocat/Hello-World/teams", "trees_url": "https://api.github.com/repos/octocat/Hello-World/git/trees{/sha}", "clone_url": "https://github.com/octocat/Hello-World.git", "mirror_url": "git:git.example.com/octocat/Hello-World", "hooks_url": "https://api.github.com/repos/octocat/Hello-World/hooks", "svn_url": "https://svn.github.com/octocat/Hello-World", "homepage": "https://github.com", "language": null, "forks_count": 9, "stargazers_count": 80, "watchers_count": 80, "size": 108, "default_branch": "master", "open_issues_count": 0, "is_template": true, "topics": [ "octocat", "atom", "electron", "api" ], "has_issues": true, "has_projects": true, "has_wiki": true, "has_pages": false, "has_downloads": true, "archived": false, "disabled": false, "visibility": "public", "pushed_at": "2011-01-26T19:06:43Z", "created_at": "2011-01-26T19:01:12Z", "updated_at": "2011-01-26T19:14:43Z", "permissions": { "admin": false, "push": false, "pull": true }, "allow_rebase_merge": true, "template_repository": null, "temp_clone_token": "ABTLWHOULUVAXGTRYU7OC2876QJ2O", "allow_squash_merge": true, "delete_branch_on_merge": true, "allow_merge_commit": true, "subscribers_count": 42, "network_count": 0, "license": { "key": "mit", "name": "MIT License", "url": "https://api.github.com/licenses/mit", "spdx_id": "MIT", "node_id": "MDc6TGljZW5zZW1pdA==", "html_url": "https://github.com/licenses/mit" }, "forks": 1, "open_issues": 1, "watchers": 1 } ] }, "starred-repository-items-alternative-response-with-star-creation-timestamps": { "summary": "Alternative response with star creation timestamps", "value": [ { "starred_at": "2011-01-16T19:06:43Z", "repo": { "id": 1296269, "node_id": "MDEwOlJlcG9zaXRvcnkxMjk2MjY5", "name": "Hello-World", "full_name": "octocat/Hello-World", "owner": { "login": "octocat", "id": 1, "node_id": "MDQ6VXNlcjE=", "avatar_url": "https://github.com/images/error/octocat_happy.gif", "gravatar_id": "", "url": "https://api.github.com/users/octocat", "html_url": "https://github.com/octocat", "followers_url": "https://api.github.com/users/octocat/followers", "following_url": "https://api.github.com/users/octocat/following{/other_user}", "gists_url": "https://api.github.com/users/octocat/gists{/gist_id}", "starred_url": "https://api.github.com/users/octocat/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/octocat/subscriptions", "organizations_url": "https://api.github.com/users/octocat/orgs", "repos_url": "https://api.github.com/users/octocat/repos", "events_url": "https://api.github.com/users/octocat/events{/privacy}", "received_events_url": "https://api.github.com/users/octocat/received_events", "type": "User", "site_admin": false }, "private": false, "html_url": "https://github.com/octocat/Hello-World", "description": "This your first repo!", "fork": false, "url": "https://api.github.com/repos/octocat/Hello-World", "archive_url": "https://api.github.com/repos/octocat/Hello-World/{archive_format}{/ref}", "assignees_url": "https://api.github.com/repos/octocat/Hello-World/assignees{/user}", "blobs_url": "https://api.github.com/repos/octocat/Hello-World/git/blobs{/sha}", "branches_url": "https://api.github.com/repos/octocat/Hello-World/branches{/branch}", "collaborators_url": "https://api.github.com/repos/octocat/Hello-World/collaborators{/collaborator}", "comments_url": "https://api.github.com/repos/octocat/Hello-World/comments{/number}", "commits_url": "https://api.github.com/repos/octocat/Hello-World/commits{/sha}", "compare_url": "https://api.github.com/repos/octocat/Hello-World/compare/{base}...{head}", "contents_url": "https://api.github.com/repos/octocat/Hello-World/contents/{+path}", "contributors_url": "https://api.github.com/repos/octocat/Hello-World/contributors", "deployments_url": "https://api.github.com/repos/octocat/Hello-World/deployments", "downloads_url": "https://api.github.com/repos/octocat/Hello-World/downloads", "events_url": "https://api.github.com/repos/octocat/Hello-World/events", "forks_url": "https://api.github.com/repos/octocat/Hello-World/forks", "git_commits_url": "https://api.github.com/repos/octocat/Hello-World/git/commits{/sha}", "git_refs_url": "https://api.github.com/repos/octocat/Hello-World/git/refs{/sha}", "git_tags_url": "https://api.github.com/repos/octocat/Hello-World/git/tags{/sha}", "git_url": "git:github.com/octocat/Hello-World.git", "issue_comment_url": "https://api.github.com/repos/octocat/Hello-World/issues/comments{/number}", "issue_events_url": "https://api.github.com/repos/octocat/Hello-World/issues/events{/number}", "issues_url": "https://api.github.com/repos/octocat/Hello-World/issues{/number}", "keys_url": "https://api.github.com/repos/octocat/Hello-World/keys{/key_id}", "labels_url": "https://api.github.com/repos/octocat/Hello-World/labels{/name}", "languages_url": "https://api.github.com/repos/octocat/Hello-World/languages", "merges_url": "https://api.github.com/repos/octocat/Hello-World/merges", "milestones_url": "https://api.github.com/repos/octocat/Hello-World/milestones{/number}", "notifications_url": "https://api.github.com/repos/octocat/Hello-World/notifications{?since,all,participating}", "pulls_url": "https://api.github.com/repos/octocat/Hello-World/pulls{/number}", "releases_url": "https://api.github.com/repos/octocat/Hello-World/releases{/id}", "ssh_url": "git@github.com:octocat/Hello-World.git", "stargazers_url": "https://api.github.com/repos/octocat/Hello-World/stargazers", "statuses_url": "https://api.github.com/repos/octocat/Hello-World/statuses/{sha}", "subscribers_url": "https://api.github.com/repos/octocat/Hello-World/subscribers", "subscription_url": "https://api.github.com/repos/octocat/Hello-World/subscription", "tags_url": "https://api.github.com/repos/octocat/Hello-World/tags", "teams_url": "https://api.github.com/repos/octocat/Hello-World/teams", "trees_url": "https://api.github.com/repos/octocat/Hello-World/git/trees{/sha}", "clone_url": "https://github.com/octocat/Hello-World.git", "mirror_url": "git:git.example.com/octocat/Hello-World", "hooks_url": "https://api.github.com/repos/octocat/Hello-World/hooks", "svn_url": "https://svn.github.com/octocat/Hello-World", "homepage": "https://github.com", "language": null, "forks_count": 9, "stargazers_count": 80, "watchers_count": 80, "size": 108, "default_branch": "master", "open_issues_count": 0, "is_template": true, "topics": [ "octocat", "atom", "electron", "api" ], "has_issues": true, "has_projects": true, "has_wiki": true, "has_pages": false, "has_downloads": true, "archived": false, "disabled": false, "visibility": "public", "pushed_at": "2011-01-26T19:06:43Z", "created_at": "2011-01-26T19:01:12Z", "updated_at": "2011-01-26T19:14:43Z", "permissions": { "admin": false, "push": false, "pull": true }, "allow_rebase_merge": true, "template_repository": null, "temp_clone_token": "ABTLWHOULUVAXGTRYU7OC2876QJ2O", "allow_squash_merge": true, "delete_branch_on_merge": true, "allow_merge_commit": true, "subscribers_count": 42, "network_count": 0, "license": { "key": "mit", "name": "MIT License", "url": "https://api.github.com/licenses/mit", "spdx_id": "MIT", "node_id": "MDc6TGljZW5zZW1pdA==", "html_url": "https://github.com/licenses/mit" }, "forks": 1, "open_issues": 1, "watchers": 1 } } ] }, "team-full-items": { "value": [ { "id": 1, "node_id": "MDQ6VGVhbTE=", "url": "https://api.github.com/teams/1", "html_url": "https://github.com/orgs/github/teams/justice-league", "name": "Justice League", "slug": "justice-league", "description": "A great team.", "privacy": "closed", "permission": "admin", "members_url": "https://api.github.com/teams/1/members{/member}", "repositories_url": "https://api.github.com/teams/1/repos", "parent": null, "members_count": 3, "repos_count": 10, "created_at": "2017-07-14T16:53:42Z", "updated_at": "2017-08-17T12:37:15Z", "organization": { "login": "github", "id": 1, "node_id": "MDEyOk9yZ2FuaXphdGlvbjE=", "url": "https://api.github.com/orgs/github", "repos_url": "https://api.github.com/orgs/github/repos", "events_url": "https://api.github.com/orgs/github/events", "hooks_url": "https://api.github.com/orgs/github/hooks", "issues_url": "https://api.github.com/orgs/github/issues", "members_url": "https://api.github.com/orgs/github/members{/member}", "public_members_url": "https://api.github.com/orgs/github/public_members{/member}", "avatar_url": "https://github.com/images/error/octocat_happy.gif", "description": "A great organization", "name": "github", "company": "GitHub", "blog": "https://github.com/blog", "location": "San Francisco", "email": "octocat@github.com", "has_organization_projects": true, "has_repository_projects": true, "public_repos": 2, "public_gists": 1, "followers": 20, "following": 0, "html_url": "https://github.com/octocat", "created_at": "2008-01-14T04:33:35Z", "type": "Organization" }, "ldap_dn": "uid=asdf,ou=users,dc=github,dc=com" } ] }, "public-user-default-response": { "summary": "Default response", "value": { "login": "octocat", "id": 1, "node_id": "MDQ6VXNlcjE=", "avatar_url": "https://github.com/images/error/octocat_happy.gif", "gravatar_id": "", "url": "https://api.github.com/users/octocat", "html_url": "https://github.com/octocat", "followers_url": "https://api.github.com/users/octocat/followers", "following_url": "https://api.github.com/users/octocat/following{/other_user}", "gists_url": "https://api.github.com/users/octocat/gists{/gist_id}", "starred_url": "https://api.github.com/users/octocat/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/octocat/subscriptions", "organizations_url": "https://api.github.com/users/octocat/orgs", "repos_url": "https://api.github.com/users/octocat/repos", "events_url": "https://api.github.com/users/octocat/events{/privacy}", "received_events_url": "https://api.github.com/users/octocat/received_events", "type": "User", "site_admin": false, "name": "monalisa octocat", "company": "GitHub", "blog": "https://github.com/blog", "location": "San Francisco", "email": "octocat@github.com", "hireable": false, "bio": "There once was...", "twitter_username": "monatheoctocat", "public_repos": 2, "public_gists": 1, "followers": 20, "following": 0, "created_at": "2008-01-14T04:33:35Z", "updated_at": "2008-01-14T04:33:35Z" } }, "public-user-response-with-git-hub-plan-information": { "summary": "Response with GitHub plan information", "value": { "login": "octocat", "id": 1, "node_id": "MDQ6VXNlcjE=", "avatar_url": "https://github.com/images/error/octocat_happy.gif", "gravatar_id": "", "url": "https://api.github.com/users/octocat", "html_url": "https://github.com/octocat", "followers_url": "https://api.github.com/users/octocat/followers", "following_url": "https://api.github.com/users/octocat/following{/other_user}", "gists_url": "https://api.github.com/users/octocat/gists{/gist_id}", "starred_url": "https://api.github.com/users/octocat/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/octocat/subscriptions", "organizations_url": "https://api.github.com/users/octocat/orgs", "repos_url": "https://api.github.com/users/octocat/repos", "events_url": "https://api.github.com/users/octocat/events{/privacy}", "received_events_url": "https://api.github.com/users/octocat/received_events", "type": "User", "site_admin": false, "name": "monalisa octocat", "company": "GitHub", "blog": "https://github.com/blog", "location": "San Francisco", "email": "octocat@github.com", "hireable": false, "bio": "There once was...", "twitter_username": "monatheoctocat", "public_repos": 2, "public_gists": 1, "followers": 20, "following": 0, "created_at": "2008-01-14T04:33:35Z", "updated_at": "2008-01-14T04:33:35Z", "plan": { "name": "pro", "space": 976562499, "collaborators": 0, "private_repos": 9999 } } }, "hovercard": { "value": { "contexts": [ { "message": "Owns this repository", "octicon": "repo" } ] } }, "key-simple-items": { "value": [ { "id": 1, "key": "ssh-rsa AAA..." } ] }, "project-items-3": { "value": [ { "owner_url": "https://api.github.com/users/octocat", "url": "https://api.github.com/projects/1002603", "html_url": "https://github.com/users/octocat/projects/1", "columns_url": "https://api.github.com/projects/1002603/columns", "id": 1002603, "node_id": "MDc6UHJvamVjdDEwMDI2MDM=", "name": "My Projects", "body": "A board to manage my personal projects.", "number": 1, "state": "open", "creator": { "login": "octocat", "id": 1, "node_id": "MDQ6VXNlcjE=", "avatar_url": "https://github.com/images/error/octocat_happy.gif", "gravatar_id": "", "url": "https://api.github.com/users/octocat", "html_url": "https://github.com/octocat", "followers_url": "https://api.github.com/users/octocat/followers", "following_url": "https://api.github.com/users/octocat/following{/other_user}", "gists_url": "https://api.github.com/users/octocat/gists{/gist_id}", "starred_url": "https://api.github.com/users/octocat/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/octocat/subscriptions", "organizations_url": "https://api.github.com/users/octocat/orgs", "repos_url": "https://api.github.com/users/octocat/repos", "events_url": "https://api.github.com/users/octocat/events{/privacy}", "received_events_url": "https://api.github.com/users/octocat/received_events", "type": "User", "site_admin": false }, "created_at": "2011-04-10T20:09:31Z", "updated_at": "2014-03-03T18:58:10Z" } ] } }, "headers": { "link": { "example": "; rel=\"next\", ; rel=\"last\"", "schema": { "type": "string" } }, "content-type": { "example": "text/html", "schema": { "type": "string" } }, "x-common-marker-version": { "example": "0.17.4", "schema": { "type": "string" } }, "x-rate-limit-limit": { "example": 5000, "schema": { "type": "integer" } }, "x-rate-limit-remaining": { "example": 4999, "schema": { "type": "integer" } }, "x-rate-limit-reset": { "example": 1590701888, "schema": { "type": "integer", "format": "timestamp" } }, "location": { "example": "https://pipelines.actions.githubusercontent.com/OhgS4QRKqmgx7bKC27GKU83jnQjyeqG8oIMTge8eqtheppcmw8/_apis/pipelines/1/runs/176/signedlogcontent?urlExpires=2020-01-24T18%3A10%3A31.5729946Z&urlSigningMethod=HMACV1&urlSignature=agG73JakPYkHrh06seAkvmH7rBR4Ji4c2%2B6a2ejYh3E%3D", "schema": { "type": "string" } } }, "responses": { "not_found": { "description": "Resource not found", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/basic-error" } } } }, "validation_failed_simple": { "description": "Validation failed", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/validation-error-simple" } } } }, "preview_header_missing": { "description": "Preview header missing", "content": { "application/json": { "schema": { "type": "object", "required": [ "message", "documentation_url" ], "properties": { "message": { "type": "string" }, "documentation_url": { "type": "string" } } } } } }, "forbidden": { "description": "Forbidden", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/basic-error" } } } }, "requires_authentication": { "description": "Requires authentication", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/basic-error" } } } }, "validation_failed": { "description": "Validation failed", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/validation-error" } } } }, "not_modified": { "description": "Not modified" }, "gone": { "description": "Gone", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/basic-error" } } } }, "service_unavailable": { "description": "Service unavailable", "content": { "application/json": { "schema": { "type": "object", "properties": { "code": { "type": "string" }, "message": { "type": "string" }, "documentation_url": { "type": "string" } } } } } }, "forbidden_gist": { "description": "Forbidden Gist", "content": { "application/json": { "schema": { "type": "object", "properties": { "block": { "type": "object", "properties": { "reason": { "type": "string" }, "created_at": { "type": "string" }, "html_url": { "type": [ "string", "null" ] } } }, "message": { "type": "string" }, "documentation_url": { "type": "string" } } } } } }, "moved_permanently": { "description": "Moved permanently", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/basic-error" } } } }, "conflict": { "description": "Conflict", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/basic-error" } } } }, "temporary_redirect": { "description": "Temporary Redirect", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/basic-error" } } } }, "internal_error": { "description": "Internal Error", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/basic-error" } } } }, "code_scanning_forbidden_read": { "description": "Response if GitHub Advanced Security is not enabled for this repository", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/basic-error" } } } }, "code_scanning_forbidden_write": { "description": "Response if the repository is archived or if github advanced security is not enabled for this repository", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/basic-error" } } } }, "bad_request": { "description": "Bad Request", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/basic-error" } }, "application/scim+json": { "schema": { "$ref": "#/components/schemas/scim-error" } } } }, "found": { "description": "Found" }, "accepted": { "description": "Accepted", "content": { "application/json": { "schema": { "type": "object" } } } }, "no_content": { "description": "A header with no content is returned." } } } } ================================================ FILE: python/tests/data/ghes-3.0.yaml ================================================ --- openapi: 3.1.0 info: version: 1.1.4 title: GitHub v3 REST API description: GitHub's v3 REST API. license: name: MIT url: https://spdx.org/licenses/MIT termsOfService: https://docs.github.com/articles/github-terms-of-service contact: name: Support url: https://support.github.com/contact?tags=dotcom-rest-api tags: - name: actions description: Endpoints to manage GitHub Actions using the REST API. - name: activity description: Activity APIs provide access to notifications, subscriptions, and timelines. - name: apps description: Information for integrations and installations. - name: billing description: Monitor charges and usage from Actions and Packages. - name: checks description: Rich interactions with checks run by your integrations. - name: code-scanning description: Retrieve code scanning alerts from a repository. - name: codes-of-conduct description: Insight into codes of conduct for your communities. - name: codespaces description: Endpoints to manage Codespaces using the REST API. - name: emojis description: List emojis available to use on GitHub. - name: enterprise-admin description: Administer a GitHub enterprise. - name: dependabot description: Endpoints to manage Dependabot. - name: gists description: View, modify your gists. - name: git description: Raw Git functionality. - name: gitignore description: View gitignore templates - name: interactions description: Owner or admin management of users interactions. - name: issues description: Interact with GitHub Issues. - name: licenses description: View various OSS licenses. - name: markdown description: Render GitHub flavored markdown - name: meta description: Endpoints that give information about the API. - name: migrations description: Move projects to or from GitHub. - name: oauth-authorizations description: Manage access of OAuth applications - name: orgs description: Interact with GitHub Orgs. - name: packages description: Manage packages for authenticated users and organizations. - name: projects description: Interact with GitHub Projects. - name: pulls description: Interact with GitHub Pull Requests. - name: rate-limit description: Check your current rate limit status - name: reactions description: Interact with reactions to various GitHub entities. - name: repos description: Interact with GitHub Repos. - name: scim description: Provisioning of GitHub organization membership for SCIM-enabled providers. - name: search description: Look for stuff on GitHub. - name: secret-scanning description: Retrieve secret scanning alerts from a repository. - name: server-statistics description: GHES statistics - name: teams description: Interact with GitHub Teams. - name: users description: Interact with and view information about users and also current user. servers: - url: "{protocol}://{hostname}/api/v3" variables: hostname: description: Self-hosted Enterprise Server or Enterprise Cloud hostname default: HOSTNAME protocol: description: Self-hosted Enterprise Server or Enterprise Cloud protocol default: http externalDocs: description: GitHub Enterprise Developer Docs url: https://docs.github.com/enterprise-server@3.0/rest/ paths: "/": get: summary: GitHub API Root description: Get Hypermedia links to resources accessible in GitHub's REST API tags: - meta operationId: meta/root responses: '200': description: Response content: application/json: schema: type: object properties: current_user_url: type: string format: uri-template current_user_authorizations_html_url: type: string format: uri-template authorizations_url: type: string format: uri-template code_search_url: type: string format: uri-template commit_search_url: type: string format: uri-template emails_url: type: string format: uri-template emojis_url: type: string format: uri-template events_url: type: string format: uri-template feeds_url: type: string format: uri-template followers_url: type: string format: uri-template following_url: type: string format: uri-template gists_url: type: string format: uri-template hub_url: type: string format: uri-template issue_search_url: type: string format: uri-template issues_url: type: string format: uri-template keys_url: type: string format: uri-template label_search_url: type: string format: uri-template notifications_url: type: string format: uri-template organization_url: type: string format: uri-template organization_repositories_url: type: string format: uri-template organization_teams_url: type: string format: uri-template public_gists_url: type: string format: uri-template rate_limit_url: type: string format: uri-template repository_url: type: string format: uri-template repository_search_url: type: string format: uri-template current_user_repositories_url: type: string format: uri-template starred_url: type: string format: uri-template starred_gists_url: type: string format: uri-template topic_search_url: type: string format: uri-template user_url: type: string format: uri-template user_organizations_url: type: string format: uri-template user_repositories_url: type: string format: uri-template user_search_url: type: string format: uri-template required: - current_user_url - current_user_authorizations_html_url - authorizations_url - code_search_url - commit_search_url - emails_url - emojis_url - events_url - feeds_url - followers_url - following_url - gists_url - hub_url - issue_search_url - issues_url - keys_url - label_search_url - notifications_url - organization_url - organization_repositories_url - organization_teams_url - public_gists_url - rate_limit_url - repository_url - repository_search_url - current_user_repositories_url - starred_url - starred_gists_url - user_url - user_organizations_url - user_repositories_url - user_search_url x-github: githubCloudOnly: false enabledForGitHubApps: true category: meta externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/overview/resources-in-the-rest-api#root-endpoint "/admin/hooks": get: summary: List global webhooks description: '' operationId: enterprise-admin/list-global-webhooks tags: - enterprise-admin externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/enterprise-admin#list-global-webhooks parameters: - name: accept description: This API is under preview and subject to change. in: header schema: type: string default: application/vnd.github.superpro-preview+json required: true - "$ref": "#/components/parameters/per-page" - "$ref": "#/components/parameters/page" responses: '200': description: Response content: application/json: schema: type: array items: "$ref": "#/components/schemas/global-hook" examples: default: "$ref": "#/components/examples/global-hook-items" headers: Link: "$ref": "#/components/headers/link" x-github: githubCloudOnly: false enabledForGitHubApps: false category: enterprise-admin subcategory: global-webhooks previews: - required: true name: superpro note: |- The [Global Webhooks API](https://docs.github.com/enterprise-server@3.0/rest/reference/enterprise-admin#global-webhooks) is currently available for developers to preview. To access the API during the preview period, you must provide a custom [media type](https://docs.github.com/enterprise-server@3.0/rest/overview/media-types) in the `Accept` header: ```shell application/vnd.github.superpro-preview+json ``` post: summary: Create a global webhook description: '' operationId: enterprise-admin/create-global-webhook tags: - enterprise-admin externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/enterprise-admin#create-a-global-webhook responses: '201': description: Response content: application/json: schema: "$ref": "#/components/schemas/global-hook" examples: default: "$ref": "#/components/examples/global-hook" requestBody: required: true content: application/json: schema: type: object properties: name: type: string description: Must be passed as "web". config: type: object description: Key/value pairs to provide settings for this webhook. properties: url: type: string description: The URL to which the payloads will be delivered. content_type: type: string description: The media type used to serialize the payloads. Supported values include `json` and `form`. The default is `form`. secret: type: string description: If provided, the `secret` will be used as the `key` to generate the HMAC hex digest value in the [`X-Hub-Signature`](https://docs.github.com/enterprise-server@3.0/webhooks/event-payloads/#delivery-headers) header. insecure_ssl: type: string description: Determines whether the SSL certificate of the host for `url` will be verified when delivering payloads. Supported values include `0` (verification is performed) and `1` (verification is not performed). The default is `0`. **We strongly recommend not setting this to `1` as you are subject to man-in-the-middle and other attacks.** required: - url events: type: array description: 'The [events](https://docs.github.com/enterprise-server@3.0/webhooks/event-payloads) that trigger this webhook. A global webhook can be triggered by `user` and `organization` events. Default: `user` and `organization`.' items: type: string active: type: boolean description: Determines if notifications are sent when the webhook is triggered. Set to `true` to send notifications. default: true required: - name - config example: name: web events: - organization - user config: url: https://example.com/webhook content_type: json secret: secret x-github: githubCloudOnly: false enabledForGitHubApps: false category: enterprise-admin subcategory: global-webhooks previews: - required: true name: superpro note: |- The [Global Webhooks API](https://docs.github.com/enterprise-server@3.0/rest/reference/enterprise-admin#global-webhooks) is currently available for developers to preview. To access the API during the preview period, you must provide a custom [media type](https://docs.github.com/enterprise-server@3.0/rest/overview/media-types) in the `Accept` header: ```shell application/vnd.github.superpro-preview+json ``` parameters: - name: accept description: This API is under preview and subject to change. in: header schema: type: string default: application/vnd.github.superpro-preview+json required: true "/admin/hooks/{hook_id}": get: summary: Get a global webhook description: '' operationId: enterprise-admin/get-global-webhook tags: - enterprise-admin externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/enterprise-admin#get-a-global-webhook parameters: - name: accept description: This API is under preview and subject to change. in: header schema: type: string default: application/vnd.github.superpro-preview+json required: true - "$ref": "#/components/parameters/hook-id" responses: '200': description: Response content: application/json: schema: "$ref": "#/components/schemas/global-hook" examples: default: "$ref": "#/components/examples/global-hook" x-github: githubCloudOnly: false enabledForGitHubApps: false category: enterprise-admin subcategory: global-webhooks previews: - required: true name: superpro note: |- The [Global Webhooks API](https://docs.github.com/enterprise-server@3.0/rest/reference/enterprise-admin#global-webhooks) is currently available for developers to preview. To access the API during the preview period, you must provide a custom [media type](https://docs.github.com/enterprise-server@3.0/rest/overview/media-types) in the `Accept` header: ```shell application/vnd.github.superpro-preview+json ``` patch: summary: Update a global webhook description: Parameters that are not provided will be overwritten with the default value or removed if no default exists. operationId: enterprise-admin/update-global-webhook tags: - enterprise-admin externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/enterprise-admin#update-a-global-webhook parameters: - name: accept description: This API is under preview and subject to change. in: header schema: type: string default: application/vnd.github.superpro-preview+json required: true - "$ref": "#/components/parameters/hook-id" responses: '200': description: Response content: application/json: schema: "$ref": "#/components/schemas/global-hook-2" examples: default: "$ref": "#/components/examples/global-hook-2" requestBody: content: application/json: schema: type: object properties: config: type: object description: Key/value pairs to provide settings for this webhook. properties: url: type: string description: The URL to which the payloads will be delivered. content_type: type: string description: The media type used to serialize the payloads. Supported values include `json` and `form`. The default is `form`. secret: type: string description: If provided, the `secret` will be used as the `key` to generate the HMAC hex digest value in the [`X-Hub-Signature`](https://docs.github.com/enterprise-server@3.0/webhooks/event-payloads/#delivery-headers) header. insecure_ssl: type: string description: Determines whether the SSL certificate of the host for `url` will be verified when delivering payloads. Supported values include `0` (verification is performed) and `1` (verification is not performed). The default is `0`. **We strongly recommend not setting this to `1` as you are subject to man-in-the-middle and other attacks.** required: - url events: type: array description: 'The [events](https://docs.github.com/enterprise-server@3.0/webhooks/event-payloads) that trigger this webhook. A global webhook can be triggered by `user` and `organization` events. Default: `user` and `organization`.' items: type: string active: type: boolean description: Determines if notifications are sent when the webhook is triggered. Set to `true` to send notifications. default: true example: events: - organization config: url: https://example.com/webhook x-github: githubCloudOnly: false enabledForGitHubApps: false category: enterprise-admin subcategory: global-webhooks previews: - required: true name: superpro note: |- The [Global Webhooks API](https://docs.github.com/enterprise-server@3.0/rest/reference/enterprise-admin#global-webhooks) is currently available for developers to preview. To access the API during the preview period, you must provide a custom [media type](https://docs.github.com/enterprise-server@3.0/rest/overview/media-types) in the `Accept` header: ```shell application/vnd.github.superpro-preview+json ``` delete: summary: Delete a global webhook description: '' operationId: enterprise-admin/delete-global-webhook tags: - enterprise-admin externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/enterprise-admin#delete-a-global-webhook parameters: - name: accept description: This API is under preview and subject to change. in: header schema: type: string default: application/vnd.github.superpro-preview+json required: true - "$ref": "#/components/parameters/hook-id" responses: '204': description: Response x-github: githubCloudOnly: false enabledForGitHubApps: false category: enterprise-admin subcategory: global-webhooks previews: - required: true name: superpro note: |- The [Global Webhooks API](https://docs.github.com/enterprise-server@3.0/rest/reference/enterprise-admin#global-webhooks) is currently available for developers to preview. To access the API during the preview period, you must provide a custom [media type](https://docs.github.com/enterprise-server@3.0/rest/overview/media-types) in the `Accept` header: ```shell application/vnd.github.superpro-preview+json ``` "/admin/hooks/{hook_id}/pings": post: summary: Ping a global webhook description: This will trigger a [ping event](https://docs.github.com/enterprise-server@3.0/webhooks/#ping-event) to be sent to the webhook. operationId: enterprise-admin/ping-global-webhook tags: - enterprise-admin externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/enterprise-admin#ping-a-global-webhook parameters: - name: accept description: This API is under preview and subject to change. in: header schema: type: string default: application/vnd.github.superpro-preview+json required: true - "$ref": "#/components/parameters/hook-id" responses: '204': description: Response x-github: githubCloudOnly: false enabledForGitHubApps: false category: enterprise-admin subcategory: global-webhooks previews: - required: true name: superpro note: |- The [Global Webhooks API](https://docs.github.com/enterprise-server@3.0/rest/reference/enterprise-admin#global-webhooks) is currently available for developers to preview. To access the API during the preview period, you must provide a custom [media type](https://docs.github.com/enterprise-server@3.0/rest/overview/media-types) in the `Accept` header: ```shell application/vnd.github.superpro-preview+json ``` "/admin/keys": get: summary: List public keys description: '' operationId: enterprise-admin/list-public-keys tags: - enterprise-admin externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/enterprise-admin#list-public-keys parameters: - "$ref": "#/components/parameters/per-page" - "$ref": "#/components/parameters/page" - "$ref": "#/components/parameters/direction" - name: sort in: query required: false schema: type: string enum: - created - updated - accessed default: created - name: since description: Only show public keys accessed after the given time. in: query required: false schema: type: string responses: '200': description: Response content: application/json: schema: type: array items: "$ref": "#/components/schemas/public-key-full" examples: default: "$ref": "#/components/examples/enterprise-public-key-items" headers: Link: "$ref": "#/components/headers/link" x-github: githubCloudOnly: false enabledForGitHubApps: false category: enterprise-admin subcategory: users "/admin/keys/{key_ids}": delete: summary: Delete a public key description: '' operationId: enterprise-admin/delete-public-key tags: - enterprise-admin externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/enterprise-admin#delete-a-public-key parameters: - "$ref": "#/components/parameters/key-ids" responses: '204': description: Response x-github: githubCloudOnly: false enabledForGitHubApps: false category: enterprise-admin subcategory: users "/admin/ldap/teams/{team_id}/mapping": patch: summary: Update LDAP mapping for a team description: |- Updates the [distinguished name](https://www.ldap.com/ldap-dns-and-rdns) (DN) of the LDAP entry to map to a team. [LDAP synchronization](https://docs.github.com/enterprise/admin/guides/user-management/using-ldap/#enabling-ldap-sync) must be enabled to map LDAP entries to a team. Use the [Create a team](https://docs.github.com/enterprise-server@3.0/rest/reference/teams/#create-a-team) endpoint to create a team with LDAP mapping. If you pass the `hellcat-preview` media type, you can also update the LDAP mapping of a child team. operationId: enterprise-admin/update-ldap-mapping-for-team tags: - enterprise-admin externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/enterprise-admin#update-ldap-mapping-for-a-team parameters: - "$ref": "#/components/parameters/team-id" responses: '200': description: Response content: application/json: schema: "$ref": "#/components/schemas/ldap-mapping-team" examples: default: "$ref": "#/components/examples/ldap-mapping-team" requestBody: required: true content: application/json: schema: type: object properties: ldap_dn: type: string description: The [distinguished name](https://www.ldap.com/ldap-dns-and-rdns) (DN) of the LDAP entry to map to a team. required: - ldap_dn example: ldap_dn: cn=Enterprise Ops,ou=teams,dc=github,dc=com x-github: githubCloudOnly: false enabledForGitHubApps: false category: enterprise-admin subcategory: ldap previews: - required: false name: hellcat note: |- The Nested Teams API is currently available for developers to preview. See the [blog post](https://developer.github.com/changes/2017-08-30-preview-nested-teams) for full details. To access the API, you must provide a custom [media type](https://docs.github.com/enterprise-server@3.0/rest/overview/media-types) in the `Accept` header: ```shell application/vnd.github.hellcat-preview+json ``` "/admin/ldap/teams/{team_id}/sync": post: summary: Sync LDAP mapping for a team description: Note that this API call does not automatically initiate an LDAP sync. Rather, if a `201` is returned, the sync job is queued successfully, and is performed when the instance is ready. operationId: enterprise-admin/sync-ldap-mapping-for-team tags: - enterprise-admin externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/enterprise-admin#sync-ldap-mapping-for-a-team parameters: - "$ref": "#/components/parameters/team-id" responses: '201': description: Response content: application/json: schema: type: object properties: status: type: string example: status: queued x-github: githubCloudOnly: false enabledForGitHubApps: false category: enterprise-admin subcategory: ldap "/admin/ldap/users/{username}/mapping": patch: summary: Update LDAP mapping for a user description: '' operationId: enterprise-admin/update-ldap-mapping-for-user tags: - enterprise-admin externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/enterprise-admin#update-ldap-mapping-for-a-user parameters: - "$ref": "#/components/parameters/username" responses: '200': description: Response content: application/json: schema: "$ref": "#/components/schemas/ldap-mapping-user" examples: default: "$ref": "#/components/examples/ldap-mapping-user" requestBody: required: true content: application/json: schema: type: object properties: ldap_dn: type: string description: The [distinguished name](https://www.ldap.com/ldap-dns-and-rdns) (DN) of the LDAP entry to map to a team. required: - ldap_dn example: ldap_dn: uid=asdf,ou=users,dc=github,dc=com x-github: githubCloudOnly: false enabledForGitHubApps: false category: enterprise-admin subcategory: ldap "/admin/ldap/users/{username}/sync": post: summary: Sync LDAP mapping for a user description: Note that this API call does not automatically initiate an LDAP sync. Rather, if a `201` is returned, the sync job is queued successfully, and is performed when the instance is ready. operationId: enterprise-admin/sync-ldap-mapping-for-user tags: - enterprise-admin externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/enterprise-admin#sync-ldap-mapping-for-a-user parameters: - "$ref": "#/components/parameters/username" responses: '201': description: Response content: application/json: schema: type: object properties: status: type: string example: status: queued x-github: githubCloudOnly: false enabledForGitHubApps: false category: enterprise-admin subcategory: ldap "/admin/organizations": post: summary: Create an organization description: '' operationId: enterprise-admin/create-org tags: - enterprise-admin externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/enterprise-admin#create-an-organization responses: '201': description: Response content: application/json: schema: "$ref": "#/components/schemas/organization-simple" examples: default: "$ref": "#/components/examples/organization-simple" requestBody: required: true content: application/json: schema: type: object properties: login: type: string description: The organization's username. admin: type: string description: The login of the user who will manage this organization. profile_name: type: string description: The organization's display name. required: - login - admin example: login: github profile_name: GitHub, Inc. admin: monalisaoctocat x-github: githubCloudOnly: false enabledForGitHubApps: false category: enterprise-admin subcategory: orgs "/admin/organizations/{org}": patch: summary: Update an organization name description: '' operationId: enterprise-admin/update-org-name tags: - enterprise-admin externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/enterprise-admin#update-an-organization-name parameters: - "$ref": "#/components/parameters/org" responses: '202': description: Response content: application/json: schema: type: object properties: message: type: string url: type: string example: message: Job queued to rename organization. It may take a few minutes to complete. url: https:///api/v3/organizations/1 requestBody: required: true content: application/json: schema: type: object properties: login: type: string description: The organization's new name. required: - login example: login: the-new-octocats x-github: githubCloudOnly: false enabledForGitHubApps: false category: enterprise-admin subcategory: orgs "/admin/pre-receive-environments": get: summary: List pre-receive environments description: '' operationId: enterprise-admin/list-pre-receive-environments tags: - enterprise-admin externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/enterprise-admin#list-pre-receive-environments parameters: - "$ref": "#/components/parameters/per-page" - "$ref": "#/components/parameters/page" - "$ref": "#/components/parameters/direction" - name: sort in: query required: false schema: type: string enum: - created - updated - name default: created responses: '200': description: Response content: application/json: schema: type: array items: "$ref": "#/components/schemas/pre-receive-environment" examples: default: "$ref": "#/components/examples/pre-receive-environment-items" x-github: githubCloudOnly: false enabledForGitHubApps: false category: enterprise-admin subcategory: pre-receive-environments previews: - required: true name: eye-scream note: |- APIs for managing pre-receive hooks are currently available for developers to preview. During the preview period, the APIs may change without advance notice. To access the API you must provide a custom [media type](/rest/overview/media-types) in the `Accept` header: ```shell application/vnd.github.eye-scream-preview ``` post: summary: Create a pre-receive environment description: '' operationId: enterprise-admin/create-pre-receive-environment tags: - enterprise-admin externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/enterprise-admin#create-a-pre-receive-environment responses: '201': description: Response content: application/json: schema: "$ref": "#/components/schemas/pre-receive-environment" examples: default: "$ref": "#/components/examples/pre-receive-environment" requestBody: required: true content: application/json: schema: type: object properties: name: type: string description: The new pre-receive environment's name. image_url: type: string description: URL from which to download a tarball of this environment. required: - name - image_url example: name: DevTools Hook Env image_url: https://my_file_server/path/to/devtools_env.tar.gz x-github: githubCloudOnly: false enabledForGitHubApps: false category: enterprise-admin subcategory: pre-receive-environments previews: - required: true name: eye-scream note: |- APIs for managing pre-receive hooks are currently available for developers to preview. During the preview period, the APIs may change without advance notice. To access the API you must provide a custom [media type](/rest/overview/media-types) in the `Accept` header: ```shell application/vnd.github.eye-scream-preview ``` "/admin/pre-receive-environments/{pre_receive_environment_id}": get: summary: Get a pre-receive environment description: '' operationId: enterprise-admin/get-pre-receive-environment tags: - enterprise-admin externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/enterprise-admin#get-a-pre-receive-environment parameters: - "$ref": "#/components/parameters/pre-receive-environment-id" responses: '200': description: Response content: application/json: schema: "$ref": "#/components/schemas/pre-receive-environment" examples: default: "$ref": "#/components/examples/pre-receive-environment" x-github: githubCloudOnly: false enabledForGitHubApps: false category: enterprise-admin subcategory: pre-receive-environments previews: - required: true name: eye-scream note: |- APIs for managing pre-receive hooks are currently available for developers to preview. During the preview period, the APIs may change without advance notice. To access the API you must provide a custom [media type](/rest/overview/media-types) in the `Accept` header: ```shell application/vnd.github.eye-scream-preview ``` patch: summary: Update a pre-receive environment description: You cannot modify the default environment. If you attempt to modify the default environment, you will receive a `422 Unprocessable Entity` response. operationId: enterprise-admin/update-pre-receive-environment tags: - enterprise-admin externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/enterprise-admin#update-a-pre-receive-environment parameters: - "$ref": "#/components/parameters/pre-receive-environment-id" responses: '200': description: Response content: application/json: schema: "$ref": "#/components/schemas/pre-receive-environment" examples: default-response: "$ref": "#/components/examples/pre-receive-environment-default-response" '422': description: Client Errors content: application/json: schema: type: object properties: message: type: string errors: type: array items: type: object properties: resource: type: string code: type: string message: type: string examples: client-errors: value: message: Validation Failed errors: - resource: PreReceiveEnvironment code: custom message: Cannot modify or delete the default environment requestBody: content: application/json: schema: type: object properties: name: type: string description: This pre-receive environment's new name. image_url: type: string description: URL from which to download a tarball of this environment. x-github: githubCloudOnly: false enabledForGitHubApps: false category: enterprise-admin subcategory: pre-receive-environments previews: - required: true name: eye-scream note: |- APIs for managing pre-receive hooks are currently available for developers to preview. During the preview period, the APIs may change without advance notice. To access the API you must provide a custom [media type](/rest/overview/media-types) in the `Accept` header: ```shell application/vnd.github.eye-scream-preview ``` delete: summary: Delete a pre-receive environment description: |- If you attempt to delete an environment that cannot be deleted, you will receive a `422 Unprocessable Entity` response. The possible error messages are: * _Cannot modify or delete the default environment_ * _Cannot delete environment that has hooks_ * _Cannot delete environment when download is in progress_ operationId: enterprise-admin/delete-pre-receive-environment tags: - enterprise-admin externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/enterprise-admin#delete-a-pre-receive-environment parameters: - "$ref": "#/components/parameters/pre-receive-environment-id" responses: '204': description: Response '422': description: Client Errors content: application/json: schema: type: object properties: message: type: string errors: type: array items: type: object properties: resource: type: string code: type: string message: type: string examples: client-errors: value: message: Validation Failed errors: - resource: PreReceiveEnvironment code: custom message: Cannot modify or delete the default environment x-github: githubCloudOnly: false enabledForGitHubApps: false category: enterprise-admin subcategory: pre-receive-environments previews: - required: true name: eye-scream note: |- APIs for managing pre-receive hooks are currently available for developers to preview. During the preview period, the APIs may change without advance notice. To access the API you must provide a custom [media type](/rest/overview/media-types) in the `Accept` header: ```shell application/vnd.github.eye-scream-preview ``` "/admin/pre-receive-environments/{pre_receive_environment_id}/downloads": post: summary: Start a pre-receive environment download description: |- Triggers a new download of the environment tarball from the environment's `image_url`. When the download is finished, the newly downloaded tarball will overwrite the existing environment. If a download cannot be triggered, you will receive a `422 Unprocessable Entity` response. The possible error messages are: * _Cannot modify or delete the default environment_ * _Can not start a new download when a download is in progress_ operationId: enterprise-admin/start-pre-receive-environment-download tags: - enterprise-admin externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/enterprise-admin#start-a-pre-receive-environment-download parameters: - "$ref": "#/components/parameters/pre-receive-environment-id" responses: '202': description: Response content: application/json: schema: "$ref": "#/components/schemas/pre-receive-environment-download-status" examples: default-response: "$ref": "#/components/examples/pre-receive-environment-download-status-default-response" '422': description: Client Errors content: application/json: schema: type: object properties: message: type: string errors: type: array items: type: object properties: resource: type: string code: type: string message: type: string examples: client-errors: value: message: Validation Failed errors: - resource: PreReceiveEnvironment code: custom message: Can not start a new download when a download is in progress x-github: githubCloudOnly: false enabledForGitHubApps: false category: enterprise-admin subcategory: pre-receive-environments previews: - required: true name: eye-scream note: |- APIs for managing pre-receive hooks are currently available for developers to preview. During the preview period, the APIs may change without advance notice. To access the API you must provide a custom [media type](/rest/overview/media-types) in the `Accept` header: ```shell application/vnd.github.eye-scream-preview ``` "/admin/pre-receive-environments/{pre_receive_environment_id}/downloads/latest": get: summary: Get the download status for a pre-receive environment description: In addition to seeing the download status at the "[Get a pre-receive environment](#get-a-pre-receive-environment)" endpoint, there is also this separate endpoint for just the download status. operationId: enterprise-admin/get-download-status-for-pre-receive-environment tags: - enterprise-admin externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/enterprise-admin#get-the-download-status-for-a-pre-receive-environment parameters: - "$ref": "#/components/parameters/pre-receive-environment-id" responses: '200': description: Response content: application/json: schema: "$ref": "#/components/schemas/pre-receive-environment-download-status" examples: default: "$ref": "#/components/examples/pre-receive-environment-download-status" x-github: githubCloudOnly: false enabledForGitHubApps: false category: enterprise-admin subcategory: pre-receive-environments previews: - required: true name: eye-scream note: |- APIs for managing pre-receive hooks are currently available for developers to preview. During the preview period, the APIs may change without advance notice. To access the API you must provide a custom [media type](/rest/overview/media-types) in the `Accept` header: ```shell application/vnd.github.eye-scream-preview ``` "/admin/pre-receive-hooks": get: summary: List pre-receive hooks description: '' operationId: enterprise-admin/list-pre-receive-hooks tags: - enterprise-admin externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/enterprise-admin#list-pre-receive-hooks parameters: - "$ref": "#/components/parameters/per-page" - "$ref": "#/components/parameters/page" - "$ref": "#/components/parameters/direction" - name: sort description: One of `created` (when the repository was starred) or `updated` (when it was last pushed to) or `name`. in: query required: false schema: type: string enum: - created - updated - name default: created responses: '200': description: Response content: application/json: schema: type: array items: "$ref": "#/components/schemas/pre-receive-hook" examples: default: "$ref": "#/components/examples/pre-receive-hook-items" x-github: githubCloudOnly: false enabledForGitHubApps: false category: enterprise-admin subcategory: pre-receive-hooks previews: - required: true name: eye-scream note: |- APIs for managing pre-receive hooks are currently available for developers to preview. During the preview period, the APIs may change without advance notice. To access the API you must provide a custom [media type](/rest/overview/media-types) in the `Accept` header: ```shell application/vnd.github.eye-scream-preview ``` post: summary: Create a pre-receive hook description: '' operationId: enterprise-admin/create-pre-receive-hook tags: - enterprise-admin externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/enterprise-admin#create-a-pre-receive-hook responses: '201': description: Response content: application/json: schema: "$ref": "#/components/schemas/pre-receive-hook" examples: default: "$ref": "#/components/examples/pre-receive-hook" requestBody: required: true content: application/json: schema: type: object properties: name: type: string description: The name of the hook. script: type: string description: The script that the hook runs. script_repository: type: object description: The GitHub repository where the script is kept. properties: {} additionalProperties: true environment: type: object description: The pre-receive environment where the script is executed. properties: {} additionalProperties: true enforcement: type: string description: 'The state of enforcement for this hook. default: `disabled`' allow_downstream_configuration: type: boolean description: 'Whether enforcement can be overridden at the org or repo level. default: `false`' required: - name - script - script_repository - environment example: name: Check Commits script: scripts/commit_check.sh enforcement: disabled allow_downstream_configuration: false script_repository: full_name: DevIT/hooks environment: id: 2 x-github: githubCloudOnly: false enabledForGitHubApps: false category: enterprise-admin subcategory: pre-receive-hooks previews: - required: true name: eye-scream note: |- APIs for managing pre-receive hooks are currently available for developers to preview. During the preview period, the APIs may change without advance notice. To access the API you must provide a custom [media type](/rest/overview/media-types) in the `Accept` header: ```shell application/vnd.github.eye-scream-preview ``` "/admin/pre-receive-hooks/{pre_receive_hook_id}": get: summary: Get a pre-receive hook description: '' operationId: enterprise-admin/get-pre-receive-hook tags: - enterprise-admin externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/enterprise-admin#get-a-pre-receive-hook parameters: - "$ref": "#/components/parameters/pre-receive-hook-id" responses: '200': description: Response content: application/json: schema: "$ref": "#/components/schemas/pre-receive-hook" examples: default: "$ref": "#/components/examples/pre-receive-hook" x-github: githubCloudOnly: false enabledForGitHubApps: false category: enterprise-admin subcategory: pre-receive-hooks previews: - required: true name: eye-scream note: |- APIs for managing pre-receive hooks are currently available for developers to preview. During the preview period, the APIs may change without advance notice. To access the API you must provide a custom [media type](/rest/overview/media-types) in the `Accept` header: ```shell application/vnd.github.eye-scream-preview ``` patch: summary: Update a pre-receive hook description: '' operationId: enterprise-admin/update-pre-receive-hook tags: - enterprise-admin externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/enterprise-admin#update-a-pre-receive-hook parameters: - "$ref": "#/components/parameters/pre-receive-hook-id" responses: '200': description: Response content: application/json: schema: "$ref": "#/components/schemas/pre-receive-hook" examples: default: "$ref": "#/components/examples/pre-receive-hook-2" requestBody: content: application/json: schema: type: object properties: name: type: string description: The name of the hook. script: type: string description: The script that the hook runs. script_repository: type: object description: The GitHub repository where the script is kept. properties: {} additionalProperties: true environment: type: object description: The pre-receive environment where the script is executed. properties: {} additionalProperties: true enforcement: type: string description: The state of enforcement for this hook. allow_downstream_configuration: type: boolean description: Whether enforcement can be overridden at the org or repo level. example: name: Check Commits environment: id: 1 allow_downstream_configuration: true x-github: githubCloudOnly: false enabledForGitHubApps: false category: enterprise-admin subcategory: pre-receive-hooks previews: - required: true name: eye-scream note: |- APIs for managing pre-receive hooks are currently available for developers to preview. During the preview period, the APIs may change without advance notice. To access the API you must provide a custom [media type](/rest/overview/media-types) in the `Accept` header: ```shell application/vnd.github.eye-scream-preview ``` delete: summary: Delete a pre-receive hook description: '' operationId: enterprise-admin/delete-pre-receive-hook tags: - enterprise-admin externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/enterprise-admin#delete-a-pre-receive-hook parameters: - "$ref": "#/components/parameters/pre-receive-hook-id" responses: '204': description: Response x-github: githubCloudOnly: false enabledForGitHubApps: false category: enterprise-admin subcategory: pre-receive-hooks previews: - required: true name: eye-scream note: |- APIs for managing pre-receive hooks are currently available for developers to preview. During the preview period, the APIs may change without advance notice. To access the API you must provide a custom [media type](/rest/overview/media-types) in the `Accept` header: ```shell application/vnd.github.eye-scream-preview ``` "/admin/tokens": get: summary: List personal access tokens description: Lists personal access tokens for all users, including admin users. operationId: enterprise-admin/list-personal-access-tokens tags: - enterprise-admin externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/enterprise-admin#list-personal-access-tokens parameters: - "$ref": "#/components/parameters/per-page" - "$ref": "#/components/parameters/page" responses: '200': description: Response content: application/json: schema: type: array items: "$ref": "#/components/schemas/authorization" examples: default: "$ref": "#/components/examples/authorization-items" headers: Link: "$ref": "#/components/headers/link" x-github: githubCloudOnly: false enabledForGitHubApps: false category: enterprise-admin subcategory: users "/admin/tokens/{token_id}": delete: summary: Delete a personal access token description: Deletes a personal access token. Returns a `403 - Forbidden` status when a personal access token is in use. For example, if you access this endpoint with the same personal access token that you are trying to delete, you will receive this error. operationId: enterprise-admin/delete-personal-access-token tags: - enterprise-admin externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/enterprise-admin#delete-a-personal-access-token parameters: - "$ref": "#/components/parameters/token-id" responses: '204': description: Response x-github: githubCloudOnly: false enabledForGitHubApps: false category: enterprise-admin subcategory: users "/admin/users": post: summary: Create a user description: |- If an external authentication mechanism is used, the login name should match the login name in the external system. If you are using LDAP authentication, you should also [update the LDAP mapping](https://docs.github.com/enterprise-server@3.0/rest/reference/enterprise-admin#update-ldap-mapping-for-a-user) for the user. The login name will be normalized to only contain alphanumeric characters or single hyphens. For example, if you send `"octo_cat"` as the login, a user named `"octo-cat"` will be created. If the login name or email address is already associated with an account, the server will return a `422` response. operationId: enterprise-admin/create-user tags: - enterprise-admin externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/enterprise-admin#create-a-user responses: '201': description: Response content: application/json: schema: "$ref": "#/components/schemas/simple-user" examples: default: "$ref": "#/components/examples/simple-user" requestBody: required: true content: application/json: schema: type: object properties: login: type: string description: The user's username. email: type: string description: "**Required for built-in authentication.** The user's email address. This parameter can be omitted when using CAS, LDAP, or SAML. For details on built-in and centrally-managed authentication, see the the [GitHub authentication guide](https://docs.github.com/enterprise/2.18/admin/guides/user-management/authenticating-users-for-your-github-enterprise-server-instance/)." required: - login example: login: monalisa email: octocat@github.com x-github: githubCloudOnly: false enabledForGitHubApps: false category: enterprise-admin subcategory: users "/admin/users/{username}": patch: summary: Update the username for a user description: '' operationId: enterprise-admin/update-username-for-user tags: - enterprise-admin externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/enterprise-admin#update-the-username-for-a-user parameters: - "$ref": "#/components/parameters/username" responses: '202': description: Response content: application/json: schema: type: object properties: message: type: string url: type: string example: message: Job queued to rename user. It may take a few minutes to complete. url: https://api.github.com/user/1 requestBody: required: true content: application/json: schema: type: object properties: login: type: string description: The user's new username. required: - login example: login: thenewmonalisa x-github: githubCloudOnly: false enabledForGitHubApps: false category: enterprise-admin subcategory: users delete: summary: Delete a user description: |- Deleting a user will delete all their repositories, gists, applications, and personal settings. [Suspending a user](https://docs.github.com/enterprise-server@3.0/rest/reference/enterprise-admin#suspend-a-user) is often a better option. You can delete any user account except your own. operationId: enterprise-admin/delete-user tags: - enterprise-admin externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/enterprise-admin#delete-a-user parameters: - "$ref": "#/components/parameters/username" responses: '204': description: Response x-github: githubCloudOnly: false enabledForGitHubApps: false category: enterprise-admin subcategory: users "/admin/users/{username}/authorizations": post: summary: Create an impersonation OAuth token description: '' operationId: enterprise-admin/create-impersonation-o-auth-token tags: - enterprise-admin externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/enterprise-admin#create-an-impersonation-oauth-token parameters: - "$ref": "#/components/parameters/username" responses: '201': description: Response content: application/json: schema: "$ref": "#/components/schemas/authorization" examples: default: "$ref": "#/components/examples/authorization" requestBody: required: true content: application/json: schema: type: object properties: scopes: type: array description: A list of [scopes](https://docs.github.com/enterprise-server@3.0/apps/building-oauth-apps/understanding-scopes-for-oauth-apps/). items: type: string x-github: githubCloudOnly: false enabledForGitHubApps: false category: enterprise-admin subcategory: users delete: summary: Delete an impersonation OAuth token description: '' operationId: enterprise-admin/delete-impersonation-o-auth-token tags: - enterprise-admin externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/enterprise-admin#delete-an-impersonation-oauth-token parameters: - "$ref": "#/components/parameters/username" responses: '204': description: Response x-github: githubCloudOnly: false enabledForGitHubApps: false category: enterprise-admin subcategory: users "/app": get: summary: Get the authenticated app description: |- Returns the GitHub App associated with the authentication credentials used. To see how many app installations are associated with this GitHub App, see the `installations_count` in the response. For more details about your app's installations, see the "[List installations for the authenticated app](https://docs.github.com/enterprise-server@3.0/rest/reference/apps#list-installations-for-the-authenticated-app)" endpoint. You must use a [JWT](https://docs.github.com/enterprise-server@3.0/apps/building-github-apps/authenticating-with-github-apps/#authenticating-as-a-github-app) to access this endpoint. tags: - apps operationId: apps/get-authenticated externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/apps#get-the-authenticated-app parameters: [] responses: '200': description: Response content: application/json: schema: "$ref": "#/components/schemas/integration" examples: default: "$ref": "#/components/examples/integration" x-github: githubCloudOnly: false enabledForGitHubApps: true category: apps subcategory: "/app-manifests/{code}/conversions": post: summary: Create a GitHub App from a manifest description: Use this endpoint to complete the handshake necessary when implementing the [GitHub App Manifest flow](https://docs.github.com/enterprise-server@3.0/apps/building-github-apps/creating-github-apps-from-a-manifest/). When you create a GitHub App with the manifest flow, you receive a temporary `code` used to retrieve the GitHub App's `id`, `pem` (private key), and `webhook_secret`. tags: - apps operationId: apps/create-from-manifest externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/apps#create-a-github-app-from-a-manifest parameters: - name: code in: path required: true schema: type: string requestBody: required: false content: application/json: schema: type: object additionalProperties: false responses: '201': description: Response content: application/json: schema: allOf: - "$ref": "#/components/schemas/integration" - type: object properties: client_id: type: string client_secret: type: string webhook_secret: type: - string - 'null' pem: type: string required: - client_id - client_secret - webhook_secret - pem additionalProperties: true examples: default: "$ref": "#/components/examples/integration-from-manifest" '404': "$ref": "#/components/responses/not_found" '422': "$ref": "#/components/responses/validation_failed_simple" x-github: githubCloudOnly: false enabledForGitHubApps: false category: apps subcategory: "/app/hook/config": get: summary: Get a webhook configuration for an app description: |- Returns the webhook configuration for a GitHub App. For more information about configuring a webhook for your app, see "[Creating a GitHub App](/developers/apps/creating-a-github-app)." You must use a [JWT](https://docs.github.com/enterprise-server@3.0/apps/building-github-apps/authenticating-with-github-apps/#authenticating-as-a-github-app) to access this endpoint. tags: - apps operationId: apps/get-webhook-config-for-app externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/apps#get-a-webhook-configuration-for-an-app responses: '200': description: Response content: application/json: schema: "$ref": "#/components/schemas/webhook-config" examples: default: "$ref": "#/components/examples/webhook-config" x-github: githubCloudOnly: false enabledForGitHubApps: false category: apps subcategory: webhooks patch: summary: Update a webhook configuration for an app description: |- Updates the webhook configuration for a GitHub App. For more information about configuring a webhook for your app, see "[Creating a GitHub App](/developers/apps/creating-a-github-app)." You must use a [JWT](https://docs.github.com/enterprise-server@3.0/apps/building-github-apps/authenticating-with-github-apps/#authenticating-as-a-github-app) to access this endpoint. tags: - apps operationId: apps/update-webhook-config-for-app externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/apps#update-a-webhook-configuration-for-an-app requestBody: required: false content: application/json: schema: type: object properties: url: "$ref": "#/components/schemas/webhook-config-url" content_type: "$ref": "#/components/schemas/webhook-config-content-type" secret: "$ref": "#/components/schemas/webhook-config-secret" insecure_ssl: "$ref": "#/components/schemas/webhook-config-insecure-ssl" example: content_type: json insecure_ssl: '0' secret: "********" url: https://example.com/webhook responses: '200': description: Response content: application/json: schema: "$ref": "#/components/schemas/webhook-config" examples: default: "$ref": "#/components/examples/webhook-config" x-github: githubCloudOnly: false enabledForGitHubApps: false category: apps subcategory: webhooks "/app/installations": get: summary: List installations for the authenticated app description: |- You must use a [JWT](https://docs.github.com/enterprise-server@3.0/apps/building-github-apps/authenticating-with-github-apps/#authenticating-as-a-github-app) to access this endpoint. The permissions the installation has are included under the `permissions` key. tags: - apps operationId: apps/list-installations externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/apps#list-installations-for-the-authenticated-app parameters: - "$ref": "#/components/parameters/per-page" - "$ref": "#/components/parameters/page" - "$ref": "#/components/parameters/since" - name: outdated in: query required: false schema: type: string responses: '200': description: The permissions the installation has are included under the `permissions` key. content: application/json: schema: type: array items: "$ref": "#/components/schemas/installation" examples: default: "$ref": "#/components/examples/base-installation-items" headers: Link: "$ref": "#/components/headers/link" x-github: githubCloudOnly: false enabledForGitHubApps: true category: apps subcategory: "/app/installations/{installation_id}": get: summary: Get an installation for the authenticated app description: |- Enables an authenticated GitHub App to find an installation's information using the installation id. You must use a [JWT](https://docs.github.com/enterprise-server@3.0/apps/building-github-apps/authenticating-with-github-apps/#authenticating-as-a-github-app) to access this endpoint. tags: - apps operationId: apps/get-installation externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/apps#get-an-installation-for-the-authenticated-app parameters: - "$ref": "#/components/parameters/installation-id" responses: '200': description: Response content: application/json: schema: "$ref": "#/components/schemas/installation" examples: default: "$ref": "#/components/examples/base-installation" '404': "$ref": "#/components/responses/not_found" '415': "$ref": "#/components/responses/preview_header_missing" x-github: githubCloudOnly: false enabledForGitHubApps: true category: apps subcategory: delete: summary: Delete an installation for the authenticated app description: |- Uninstalls a GitHub App on a user, organization, or business account. If you prefer to temporarily suspend an app's access to your account's resources, then we recommend the "[Suspend an app installation](https://docs.github.com/enterprise-server@3.0/rest/reference/apps/#suspend-an-app-installation)" endpoint. You must use a [JWT](https://docs.github.com/enterprise-server@3.0/apps/building-github-apps/authenticating-with-github-apps/#authenticating-as-a-github-app) to access this endpoint. tags: - apps operationId: apps/delete-installation externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/apps#delete-an-installation-for-the-authenticated-app parameters: - "$ref": "#/components/parameters/installation-id" responses: '204': description: Response '404': "$ref": "#/components/responses/not_found" x-github: githubCloudOnly: false enabledForGitHubApps: false category: apps subcategory: "/app/installations/{installation_id}/access_tokens": post: summary: Create an installation access token for an app description: |- Creates an installation access token that enables a GitHub App to make authenticated API requests for the app's installation on an organization or individual account. Installation tokens expire one hour from the time you create them. Using an expired token produces a status code of `401 - Unauthorized`, and requires creating a new installation token. By default the installation token has access to all repositories that the installation can access. To restrict the access to specific repositories, you can provide the `repository_ids` when creating the token. When you omit `repository_ids`, the response does not contain the `repositories` key. You must use a [JWT](https://docs.github.com/enterprise-server@3.0/apps/building-github-apps/authenticating-with-github-apps/#authenticating-as-a-github-app) to access this endpoint. tags: - apps operationId: apps/create-installation-access-token externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/apps/#create-an-installation-access-token-for-an-app parameters: - "$ref": "#/components/parameters/installation-id" requestBody: required: false content: application/json: schema: type: object properties: repositories: description: List of repository names that the token should have access to type: array items: type: string examples: - rails repository_ids: description: List of repository IDs that the token should have access to type: array items: type: integer examples: - 1 permissions: "$ref": "#/components/schemas/app-permissions" responses: '201': description: Response content: application/json: schema: "$ref": "#/components/schemas/installation-token" examples: default: "$ref": "#/components/examples/installation-token" '403': "$ref": "#/components/responses/forbidden" '415': "$ref": "#/components/responses/preview_header_missing" '401': "$ref": "#/components/responses/requires_authentication" '404': "$ref": "#/components/responses/not_found" '422': "$ref": "#/components/responses/validation_failed" x-github: githubCloudOnly: false enabledForGitHubApps: true category: apps subcategory: "/app/installations/{installation_id}/suspended": put: summary: Suspend an app installation description: |- Suspends a GitHub App on a user, organization, or business account, which blocks the app from accessing the account's resources. When a GitHub App is suspended, the app's access to the GitHub Enterprise Server API or webhook events is blocked for that account. You must use a [JWT](https://docs.github.com/enterprise-server@3.0/apps/building-github-apps/authenticating-with-github-apps/#authenticating-as-a-github-app) to access this endpoint. tags: - apps operationId: apps/suspend-installation externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/apps#suspend-an-app-installation parameters: - "$ref": "#/components/parameters/installation-id" responses: '204': description: Response '404': "$ref": "#/components/responses/not_found" x-github: githubCloudOnly: false enabledForGitHubApps: false category: apps subcategory: delete: summary: Unsuspend an app installation description: |- Removes a GitHub App installation suspension. You must use a [JWT](https://docs.github.com/enterprise-server@3.0/apps/building-github-apps/authenticating-with-github-apps/#authenticating-as-a-github-app) to access this endpoint. tags: - apps operationId: apps/unsuspend-installation externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/apps#unsuspend-an-app-installation parameters: - "$ref": "#/components/parameters/installation-id" responses: '204': description: Response '404': "$ref": "#/components/responses/not_found" x-github: githubCloudOnly: false enabledForGitHubApps: false category: apps subcategory: "/applications/grants": get: summary: List your grants description: |- **Deprecation Notice:** GitHub Enterprise Server will discontinue the [OAuth Authorizations API](https://docs.github.com/enterprise-server@3.0/rest/reference/oauth-authorizations/), which is used by integrations to create personal access tokens and OAuth tokens, and you must now create these tokens using our [web application flow](https://docs.github.com/enterprise-server@3.0/developers/apps/authorizing-oauth-apps#web-application-flow). The [OAuth Authorizations API](https://docs.github.com/enterprise-server@3.0/rest/reference/oauth-authorizations) will be removed on November, 13, 2020. For more information, including scheduled brownouts, see the [blog post](https://developer.github.com/changes/2020-02-14-deprecating-oauth-auth-endpoint/). You can use this API to list the set of OAuth applications that have been granted access to your account. Unlike the [list your authorizations](https://docs.github.com/enterprise-server@3.0/rest/reference/oauth-authorizations#list-your-authorizations) API, this API does not manage individual tokens. This API will return one entry for each OAuth application that has been granted access to your account, regardless of the number of tokens an application has generated for your user. The list of OAuth applications returned matches what is shown on [the application authorizations settings screen within GitHub](https://github.com/settings/applications#authorized). The `scopes` returned are the union of scopes authorized for the application. For example, if an application has one token with `repo` scope and another token with `user` scope, the grant will return `["repo", "user"]`. tags: - oauth-authorizations operationId: oauth-authorizations/list-grants externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/oauth-authorizations#list-your-grants parameters: - "$ref": "#/components/parameters/per-page" - "$ref": "#/components/parameters/page" - name: client_id in: query required: false description: The client ID of your GitHub app. schema: type: string responses: '200': description: Response content: application/json: schema: type: array items: "$ref": "#/components/schemas/application-grant" examples: default: "$ref": "#/components/examples/application-grant-items" headers: Link: "$ref": "#/components/headers/link" '304': "$ref": "#/components/responses/not_modified" '403': "$ref": "#/components/responses/forbidden" '401': "$ref": "#/components/responses/requires_authentication" '404': "$ref": "#/components/responses/not_found" x-github: githubCloudOnly: false enabledForGitHubApps: false removalDate: '2020-11-13' deprecationDate: '2020-02-14' category: oauth-authorizations subcategory: deprecated: true "/applications/grants/{grant_id}": get: summary: Get a single grant description: "**Deprecation Notice:** GitHub Enterprise Server will discontinue the [OAuth Authorizations API](https://docs.github.com/enterprise-server@3.0/rest/reference/oauth-authorizations), which is used by integrations to create personal access tokens and OAuth tokens, and you must now create these tokens using our [web application flow](https://docs.github.com/enterprise-server@3.0/apps/building-oauth-apps/authorizing-oauth-apps/#web-application-flow). The [OAuth Authorizations API](https://docs.github.com/enterprise-server@3.0/rest/reference/oauth-authorizations) will be removed on November, 13, 2020. For more information, including scheduled brownouts, see the [blog post](https://developer.github.com/changes/2020-02-14-deprecating-oauth-auth-endpoint/)." tags: - oauth-authorizations operationId: oauth-authorizations/get-grant externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/oauth-authorizations#get-a-single-grant parameters: - "$ref": "#/components/parameters/grant-id" responses: '200': description: Response content: application/json: schema: "$ref": "#/components/schemas/application-grant" examples: default: "$ref": "#/components/examples/application-grant" '304': "$ref": "#/components/responses/not_modified" '403': "$ref": "#/components/responses/forbidden" '401': "$ref": "#/components/responses/requires_authentication" x-github: githubCloudOnly: false enabledForGitHubApps: false removalDate: '2020-11-13' deprecationDate: '2020-02-14' category: oauth-authorizations subcategory: deprecated: true delete: summary: Delete a grant description: |- **Deprecation Notice:** GitHub Enterprise Server will discontinue the [OAuth Authorizations API](https://docs.github.com/enterprise-server@3.0/rest/reference/oauth-authorizations/), which is used by integrations to create personal access tokens and OAuth tokens, and you must now create these tokens using our [web application flow](https://docs.github.com/enterprise-server@3.0/developers/apps/authorizing-oauth-apps#web-application-flow). The [OAuth Authorizations API](https://docs.github.com/enterprise-server@3.0/rest/reference/oauth-authorizations/) will be removed on November, 13, 2020. For more information, including scheduled brownouts, see the [blog post](https://developer.github.com/changes/2020-02-14-deprecating-oauth-auth-endpoint/). Deleting an OAuth application's grant will also delete all OAuth tokens associated with the application for your user. Once deleted, the application has no access to your account and is no longer listed on [the application authorizations settings screen within GitHub](https://github.com/settings/applications#authorized). tags: - oauth-authorizations operationId: oauth-authorizations/delete-grant externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/oauth-authorizations#delete-a-grant parameters: - "$ref": "#/components/parameters/grant-id" responses: '204': description: Response '304': "$ref": "#/components/responses/not_modified" '403': "$ref": "#/components/responses/forbidden" '401': "$ref": "#/components/responses/requires_authentication" x-github: githubCloudOnly: false enabledForGitHubApps: false removalDate: '2020-11-13' deprecationDate: '2020-02-14' category: oauth-authorizations subcategory: deprecated: true "/applications/{client_id}/grant": delete: summary: Delete an app authorization description: |- OAuth application owners can revoke a grant for their OAuth application and a specific user. You must use [Basic Authentication](https://docs.github.com/enterprise-server@3.0/rest/overview/other-authentication-methods#basic-authentication) when accessing this endpoint, using the OAuth application's `client_id` and `client_secret` as the username and password. You must also provide a valid OAuth `access_token` as an input parameter and the grant for the token's owner will be deleted. Deleting an OAuth application's grant will also delete all OAuth tokens associated with the application for the user. Once deleted, the application will have no access to the user's account and will no longer be listed on [the application authorizations settings screen within GitHub](https://github.com/settings/applications#authorized). operationId: apps/delete-authorization tags: - apps externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/apps#delete-an-app-authorization parameters: - "$ref": "#/components/parameters/client-id" requestBody: required: true content: application/json: schema: type: object properties: access_token: type: string description: The OAuth access token used to authenticate to the GitHub API. required: - access_token example: access_token: e72e16c7e42f292c6912e7710c838347ae178b4a responses: '204': description: Response '422': "$ref": "#/components/responses/validation_failed" x-github: githubCloudOnly: false enabledForGitHubApps: false category: apps subcategory: oauth-applications "/applications/{client_id}/grants/{access_token}": delete: summary: Revoke a grant for an application description: |- **Deprecation Notice:** GitHub Enterprise Server will discontinue OAuth endpoints that contain `access_token` in the path parameter. We have introduced new endpoints that allow you to securely manage tokens for OAuth Apps by moving `access_token` to the request body. For more information, see the [blog post](https://developer.github.com/changes/2020-02-14-deprecating-oauth-app-endpoint/). OAuth application owners can revoke a grant for their OAuth application and a specific user. You must use [Basic Authentication](https://docs.github.com/enterprise-server@3.0/rest/overview/other-authentication-methods#basic-authentication) when accessing this endpoint, using the OAuth application's `client_id` and `client_secret` as the username and password. You must also provide a valid token as `:access_token` and the grant for the token's owner will be deleted. Deleting an OAuth application's grant will also delete all OAuth tokens associated with the application for the user. Once deleted, the application will have no access to the user's account and will no longer be listed on [the Applications settings page under "Authorized OAuth Apps" on GitHub Enterprise Server](https://github.com/settings/applications#authorized). tags: - apps operationId: apps/revoke-grant-for-application externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/apps#revoke-a-grant-for-an-application parameters: - "$ref": "#/components/parameters/client-id" - "$ref": "#/components/parameters/access-token" responses: '204': description: Response x-github: githubCloudOnly: false enabledForGitHubApps: false removalDate: '2021-05-05' deprecationDate: '2020-02-14' category: apps subcategory: oauth-applications deprecated: true "/applications/{client_id}/token": post: summary: Check a token description: OAuth applications can use a special API method for checking OAuth token validity without exceeding the normal rate limits for failed login attempts. Authentication works differently with this particular endpoint. You must use [Basic Authentication](https://docs.github.com/enterprise-server@3.0/rest/overview/other-authentication-methods#basic-authentication) to use this endpoint, where the username is the OAuth application `client_id` and the password is its `client_secret`. Invalid tokens will return `404 NOT FOUND`. tags: - apps operationId: apps/check-token externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/apps#check-a-token parameters: - "$ref": "#/components/parameters/client-id" requestBody: required: true content: application/json: schema: properties: access_token: description: The access_token of the OAuth application. type: string required: - access_token type: object responses: '200': description: Response content: application/json: schema: "$ref": "#/components/schemas/authorization" examples: default: "$ref": "#/components/examples/authorization-with-user" '422': "$ref": "#/components/responses/validation_failed" '404': "$ref": "#/components/responses/not_found" x-github: githubCloudOnly: false enabledForGitHubApps: false category: apps subcategory: oauth-applications patch: summary: Reset a token description: OAuth applications can use this API method to reset a valid OAuth token without end-user involvement. Applications must save the "token" property in the response because changes take effect immediately. You must use [Basic Authentication](https://docs.github.com/enterprise-server@3.0/rest/overview/other-authentication-methods#basic-authentication) when accessing this endpoint, using the OAuth application's `client_id` and `client_secret` as the username and password. Invalid tokens will return `404 NOT FOUND`. tags: - apps operationId: apps/reset-token externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/apps#reset-a-token parameters: - "$ref": "#/components/parameters/client-id" requestBody: required: true content: application/json: schema: properties: access_token: description: The access_token of the OAuth application. type: string required: - access_token type: object responses: '200': description: Response content: application/json: schema: "$ref": "#/components/schemas/authorization" examples: default: "$ref": "#/components/examples/authorization-with-user" '422': "$ref": "#/components/responses/validation_failed" x-github: githubCloudOnly: false enabledForGitHubApps: false category: apps subcategory: oauth-applications delete: summary: Delete an app token description: OAuth application owners can revoke a single token for an OAuth application. You must use [Basic Authentication](https://docs.github.com/enterprise-server@3.0/rest/overview/other-authentication-methods#basic-authentication) when accessing this endpoint, using the OAuth application's `client_id` and `client_secret` as the username and password. tags: - apps operationId: apps/delete-token externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/apps#delete-an-app-token parameters: - "$ref": "#/components/parameters/client-id" requestBody: required: true content: application/json: schema: type: object properties: access_token: type: string description: The OAuth access token used to authenticate to the GitHub API. required: - access_token example: access_token: e72e16c7e42f292c6912e7710c838347ae178b4a responses: '204': description: Response '422': "$ref": "#/components/responses/validation_failed" x-github: githubCloudOnly: false enabledForGitHubApps: false category: apps subcategory: oauth-applications "/applications/{client_id}/token/scoped": post: summary: Create a scoped access token description: Use a non-scoped user-to-server OAuth access token to create a repository scoped and/or permission scoped user-to-server OAuth access token. You can specify which repositories the token can access and which permissions are granted to the token. You must use [Basic Authentication](https://docs.github.com/enterprise-server@3.0/rest/overview/other-authentication-methods#basic-authentication) when accessing this endpoint, using the OAuth application's `client_id` and `client_secret` as the username and password. Invalid tokens will return `404 NOT FOUND`. tags: - apps operationId: apps/scope-token externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/apps#create-a-scoped-access-token parameters: - "$ref": "#/components/parameters/client-id" requestBody: required: true content: application/json: schema: type: object properties: access_token: type: string description: The OAuth access token used to authenticate to the GitHub API. examples: - e72e16c7e42f292c6912e7710c838347ae178b4a target: description: The name of the user or organization to scope the user-to-server access token to. **Required** unless `target_id` is specified. type: string examples: - octocat target_id: description: The ID of the user or organization to scope the user-to-server access token to. **Required** unless `target` is specified. type: integer examples: - 1 repositories: description: The list of repository names to scope the user-to-server access token to. `repositories` may not be specified if `repository_ids` is specified. type: array items: type: string examples: - rails repository_ids: description: The list of repository IDs to scope the user-to-server access token to. `repository_ids` may not be specified if `repositories` is specified. type: array items: type: integer examples: - 1 permissions: "$ref": "#/components/schemas/app-permissions" required: - access_token responses: '200': description: Response content: application/json: schema: "$ref": "#/components/schemas/authorization" examples: default: "$ref": "#/components/examples/scope-token" '401': "$ref": "#/components/responses/requires_authentication" '403': "$ref": "#/components/responses/forbidden" '404': "$ref": "#/components/responses/not_found" '422': "$ref": "#/components/responses/validation_failed" x-github: githubCloudOnly: false enabledForGitHubApps: false category: apps subcategory: oauth-applications "/applications/{client_id}/tokens/{access_token}": get: summary: Check an authorization description: |- **Deprecation Notice:** GitHub Enterprise Server will discontinue OAuth endpoints that contain `access_token` in the path parameter. We have introduced new endpoints that allow you to securely manage tokens for OAuth Apps by moving `access_token` to the request body. For more information, see the [blog post](https://developer.github.com/changes/2020-02-14-deprecating-oauth-app-endpoint/). OAuth applications can use a special API method for checking OAuth token validity without exceeding the normal rate limits for failed login attempts. Authentication works differently with this particular endpoint. You must use [Basic Authentication](https://docs.github.com/enterprise-server@3.0/rest/overview/other-authentication-methods#basic-authentication) when accessing this endpoint, using the OAuth application's `client_id` and `client_secret` as the username and password. Invalid tokens will return `404 NOT FOUND`. tags: - apps operationId: apps/check-authorization externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/apps#check-an-authorization parameters: - "$ref": "#/components/parameters/client-id" - "$ref": "#/components/parameters/access-token" responses: '200': description: Response content: application/json: schema: anyOf: - type: 'null' - "$ref": "#/components/schemas/authorization" examples: default: "$ref": "#/components/examples/authorization-with-user" '404': "$ref": "#/components/responses/not_found" x-github: githubCloudOnly: false enabledForGitHubApps: false removalDate: '2021-05-05' deprecationDate: '2020-02-14' category: apps subcategory: oauth-applications deprecated: true post: summary: Reset an authorization description: |- **Deprecation Notice:** GitHub Enterprise Server will discontinue OAuth endpoints that contain `access_token` in the path parameter. We have introduced new endpoints that allow you to securely manage tokens for OAuth Apps by moving `access_token` to the request body. For more information, see the [blog post](https://developer.github.com/changes/2020-02-14-deprecating-oauth-app-endpoint/). OAuth applications can use this API method to reset a valid OAuth token without end-user involvement. Applications must save the "token" property in the response because changes take effect immediately. You must use [Basic Authentication](https://docs.github.com/enterprise-server@3.0/rest/overview/other-authentication-methods#basic-authentication) when accessing this endpoint, using the OAuth application's `client_id` and `client_secret` as the username and password. Invalid tokens will return `404 NOT FOUND`. tags: - apps operationId: apps/reset-authorization externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/apps#reset-an-authorization parameters: - "$ref": "#/components/parameters/client-id" - "$ref": "#/components/parameters/access-token" responses: '200': description: Response content: application/json: schema: "$ref": "#/components/schemas/authorization" examples: default: "$ref": "#/components/examples/authorization-with-user" x-github: githubCloudOnly: false enabledForGitHubApps: false removalDate: '2021-05-05' deprecationDate: '2020-02-14' category: apps subcategory: oauth-applications deprecated: true delete: summary: Revoke an authorization for an application description: |- **Deprecation Notice:** GitHub Enterprise Server will discontinue OAuth endpoints that contain `access_token` in the path parameter. We have introduced new endpoints that allow you to securely manage tokens for OAuth Apps by moving `access_token` to the request body. For more information, see the [blog post](https://developer.github.com/changes/2020-02-14-deprecating-oauth-app-endpoint/). OAuth application owners can revoke a single token for an OAuth application. You must use [Basic Authentication](https://docs.github.com/enterprise-server@3.0/rest/overview/other-authentication-methods#basic-authentication) when accessing this endpoint, using the OAuth application's `client_id` and `client_secret` as the username and password. tags: - apps operationId: apps/revoke-authorization-for-application externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/apps#revoke-an-authorization-for-an-application parameters: - "$ref": "#/components/parameters/client-id" - "$ref": "#/components/parameters/access-token" responses: '204': description: Response x-github: githubCloudOnly: false enabledForGitHubApps: false removalDate: '2021-05-05' deprecationDate: '2020-02-14' category: apps subcategory: oauth-applications deprecated: true "/apps/{app_slug}": get: summary: Get an app description: |- **Note**: The `:app_slug` is just the URL-friendly name of your GitHub App. You can find this on the settings page for your GitHub App (e.g., `https://github.com/settings/apps/:app_slug`). If the GitHub App you specify is public, you can access this endpoint without authenticating. If the GitHub App you specify is private, you must authenticate with a [personal access token](https://docs.github.com/articles/creating-a-personal-access-token-for-the-command-line/) or an [installation access token](https://docs.github.com/enterprise-server@3.0/apps/building-github-apps/authenticating-with-github-apps/#authenticating-as-an-installation) to access this endpoint. tags: - apps operationId: apps/get-by-slug externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/apps/#get-an-app parameters: - "$ref": "#/components/parameters/app-slug" responses: '200': description: Response content: application/json: schema: "$ref": "#/components/schemas/integration" examples: default: "$ref": "#/components/examples/integration" '403': "$ref": "#/components/responses/forbidden" '404': "$ref": "#/components/responses/not_found" '415': "$ref": "#/components/responses/preview_header_missing" x-github: githubCloudOnly: false enabledForGitHubApps: true category: apps subcategory: "/authorizations": get: summary: List your authorizations description: "**Deprecation Notice:** GitHub Enterprise Server will discontinue the [OAuth Authorizations API](https://docs.github.com/enterprise-server@3.0/rest/reference/oauth-authorizations), which is used by integrations to create personal access tokens and OAuth tokens, and you must now create these tokens using our [web application flow](https://docs.github.com/enterprise-server@3.0/apps/building-oauth-apps/authorizing-oauth-apps/#web-application-flow). The [OAuth Authorizations API](https://docs.github.com/enterprise-server@3.0/rest/reference/oauth-authorizations) will be removed on November, 13, 2020. For more information, including scheduled brownouts, see the [blog post](https://developer.github.com/changes/2020-02-14-deprecating-oauth-auth-endpoint/)." tags: - oauth-authorizations operationId: oauth-authorizations/list-authorizations externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/oauth-authorizations#list-your-authorizations parameters: - "$ref": "#/components/parameters/per-page" - "$ref": "#/components/parameters/page" - name: client_id in: query required: false description: The client ID of your GitHub app. schema: type: string responses: '200': description: Response content: application/json: schema: type: array items: "$ref": "#/components/schemas/authorization" examples: default: "$ref": "#/components/examples/authorization-items" headers: Link: "$ref": "#/components/headers/link" '304': "$ref": "#/components/responses/not_modified" '403': "$ref": "#/components/responses/forbidden" '401': "$ref": "#/components/responses/requires_authentication" '404': "$ref": "#/components/responses/not_found" x-github: githubCloudOnly: false enabledForGitHubApps: false removalDate: '2020-11-13' deprecationDate: '2020-02-14' category: oauth-authorizations subcategory: deprecated: true post: summary: Create a new authorization description: |- **Deprecation Notice:** GitHub Enterprise Server will discontinue the [OAuth Authorizations API](https://docs.github.com/enterprise-server@3.0/rest/reference/oauth-authorizations), which is used by integrations to create personal access tokens and OAuth tokens, and you must now create these tokens using our [web application flow](https://docs.github.com/enterprise-server@3.0/developers/apps/authorizing-oauth-apps#web-application-flow). The [OAuth Authorizations API](https://docs.github.com/enterprise-server@3.0/rest/reference/oauth-authorizations) will be removed on November, 13, 2020. For more information, including scheduled brownouts, see the [blog post](https://developer.github.com/changes/2020-02-14-deprecating-oauth-auth-endpoint/). **Warning:** Apps must use the [web application flow](https://docs.github.com/enterprise-server@3.0/apps/building-oauth-apps/authorizing-oauth-apps/#web-application-flow) to obtain OAuth tokens that work with GitHub Enterprise Server SAML organizations. OAuth tokens created using the Authorizations API will be unable to access GitHub Enterprise Server SAML organizations. For more information, see the [blog post](https://developer.github.com/changes/2019-11-05-deprecated-passwords-and-authorizations-api). Creates OAuth tokens using [Basic Authentication](https://docs.github.com/enterprise-server@3.0/rest/overview/other-authentication-methods#basic-authentication). If you have two-factor authentication setup, Basic Authentication for this endpoint requires that you use a one-time password (OTP) and your username and password instead of tokens. For more information, see "[Working with two-factor authentication](https://docs.github.com/enterprise-server@3.0/rest/overview/other-authentication-methods#working-with-two-factor-authentication)." To create tokens for a particular OAuth application using this endpoint, you must authenticate as the user you want to create an authorization for and provide the app's client ID and secret, found on your OAuth application's settings page. If your OAuth application intends to create multiple tokens for one user, use `fingerprint` to differentiate between them. You can also create tokens on GitHub Enterprise Server from the [personal access tokens settings](https://github.com/settings/tokens) page. Read more about these tokens in [the GitHub Help documentation](https://docs.github.com/articles/creating-an-access-token-for-command-line-use). Organizations that enforce SAML SSO require personal access tokens to be allowed. Read more about allowing tokens in [the GitHub Help documentation](https://docs.github.com/articles/about-identity-and-access-management-with-saml-single-sign-on). tags: - oauth-authorizations operationId: oauth-authorizations/create-authorization externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/oauth-authorizations#create-a-new-authorization parameters: [] requestBody: required: false content: application/json: schema: type: object properties: scopes: description: A list of scopes that this authorization is in. type: - array - 'null' items: type: string examples: - public_repo - user note: description: A note to remind you what the OAuth token is for. type: string examples: - Update all gems note_url: description: A URL to remind you what app the OAuth token is for. type: string client_id: description: The OAuth app client key for which to create the token. maxLength: 20 type: string client_secret: description: The OAuth app client secret for which to create the token. maxLength: 40 type: string fingerprint: description: A unique string to distinguish an authorization from others created for the same client ID and user. type: string responses: '201': description: Response content: application/json: schema: "$ref": "#/components/schemas/authorization" examples: default: "$ref": "#/components/examples/authorization" headers: Location: example: https://api.github.com/authorizations/1 schema: type: string '422': "$ref": "#/components/responses/validation_failed" '410': "$ref": "#/components/responses/gone" '304': "$ref": "#/components/responses/not_modified" '403': "$ref": "#/components/responses/forbidden" '401': "$ref": "#/components/responses/requires_authentication" x-github: githubCloudOnly: false enabledForGitHubApps: false removalDate: '2020-11-13' deprecationDate: '2020-02-14' category: oauth-authorizations subcategory: deprecated: true "/authorizations/clients/{client_id}": put: summary: Get-or-create an authorization for a specific app description: |- **Deprecation Notice:** GitHub Enterprise Server will discontinue the [OAuth Authorizations API](https://docs.github.com/enterprise-server@3.0/rest/reference/oauth-authorizations/), which is used by integrations to create personal access tokens and OAuth tokens, and you must now create these tokens using our [web application flow](https://docs.github.com/enterprise-server@3.0/developers/apps/authorizing-oauth-apps#web-application-flow). The [OAuth Authorizations API](https://docs.github.com/enterprise-server@3.0/rest/reference/oauth-authorizations) will be removed on November, 13, 2020. For more information, including scheduled brownouts, see the [blog post](https://developer.github.com/changes/2020-02-14-deprecating-oauth-auth-endpoint/). **Warning:** Apps must use the [web application flow](https://docs.github.com/enterprise-server@3.0/apps/building-oauth-apps/authorizing-oauth-apps/#web-application-flow) to obtain OAuth tokens that work with GitHub Enterprise Server SAML organizations. OAuth tokens created using the Authorizations API will be unable to access GitHub Enterprise Server SAML organizations. For more information, see the [blog post](https://developer.github.com/changes/2019-11-05-deprecated-passwords-and-authorizations-api). Creates a new authorization for the specified OAuth application, only if an authorization for that application doesn't already exist for the user. The URL includes the 20 character client ID for the OAuth app that is requesting the token. It returns the user's existing authorization for the application if one is present. Otherwise, it creates and returns a new one. If you have two-factor authentication setup, Basic Authentication for this endpoint requires that you use a one-time password (OTP) and your username and password instead of tokens. For more information, see "[Working with two-factor authentication](https://docs.github.com/enterprise-server@3.0/rest/overview/other-authentication-methods#working-with-two-factor-authentication)." **Deprecation Notice:** GitHub Enterprise Server will discontinue the [OAuth Authorizations API](https://docs.github.com/enterprise-server@3.0/rest/reference/oauth-authorizations/), which is used by integrations to create personal access tokens and OAuth tokens, and you must now create these tokens using our [web application flow](https://docs.github.com/enterprise-server@3.0/developers/apps/authorizing-oauth-apps#web-application-flow). The [OAuth Authorizations API](https://docs.github.com/enterprise-server@3.0/rest/reference/oauth-authorizations) will be removed on November, 13, 2020. For more information, including scheduled brownouts, see the [blog post](https://developer.github.com/changes/2020-02-14-deprecating-oauth-auth-endpoint/). tags: - oauth-authorizations operationId: oauth-authorizations/get-or-create-authorization-for-app externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/oauth-authorizations#get-or-create-an-authorization-for-a-specific-app parameters: - "$ref": "#/components/parameters/client-id" requestBody: required: true content: application/json: schema: properties: client_secret: description: The OAuth app client secret for which to create the token. maxLength: 40 type: string scopes: description: A list of scopes that this authorization is in. type: - array - 'null' items: type: string examples: - public_repo - user note: description: A note to remind you what the OAuth token is for. type: string examples: - Update all gems note_url: description: A URL to remind you what app the OAuth token is for. type: string fingerprint: description: A unique string to distinguish an authorization from others created for the same client ID and user. type: string required: - client_secret type: object responses: '200': description: if returning an existing token content: application/json: schema: "$ref": "#/components/schemas/authorization" examples: response-if-returning-an-existing-token: "$ref": "#/components/examples/authorization-response-if-returning-an-existing-token-2" headers: Location: example: https://api.github.com/authorizations/1 schema: type: string '201': description: "**Deprecation Notice:** GitHub will discontinue the [OAuth Authorizations API](https://docs.github.com/enterprise-server@3.0/rest/reference/oauth-authorizations), which is used by integrations to create personal access tokens and OAuth tokens, and you must now create these tokens using our [web application flow](https://docs.github.com/enterprise-server@3.0/apps/building-oauth-apps/authorizing-oauth-apps/#web-application-flow). The [OAuth Authorizations API](https://docs.github.com/enterprise-server@3.0/rest/reference/oauth-authorizations) will be removed on November, 13, 2020. For more information, including scheduled brownouts, see the [blog post](https://developer.github.com/changes/2020-02-14-deprecating-oauth-auth-endpoint/)." content: application/json: schema: "$ref": "#/components/schemas/authorization" examples: default: "$ref": "#/components/examples/authorization" headers: Location: example: https://api.github.com/authorizations/1 schema: type: string '422': "$ref": "#/components/responses/validation_failed" '304': "$ref": "#/components/responses/not_modified" '403': "$ref": "#/components/responses/forbidden" '401': "$ref": "#/components/responses/requires_authentication" x-github: githubCloudOnly: false enabledForGitHubApps: false removalDate: '2020-11-13' deprecationDate: '2020-02-14' category: oauth-authorizations subcategory: deprecated: true "/authorizations/clients/{client_id}/{fingerprint}": put: summary: Get-or-create an authorization for a specific app and fingerprint description: |- **Deprecation Notice:** GitHub Enterprise Server will discontinue the [OAuth Authorizations API](https://docs.github.com/enterprise-server@3.0/rest/reference/oauth-authorizations/), which is used by integrations to create personal access tokens and OAuth tokens, and you must now create these tokens using our [web application flow](https://docs.github.com/enterprise-server@3.0/developers/apps/authorizing-oauth-apps#web-application-flow). The [OAuth Authorizations API](https://docs.github.com/enterprise-server@3.0/rest/reference/oauth-authorizations) will be removed on November, 13, 2020. For more information, including scheduled brownouts, see the [blog post](https://developer.github.com/changes/2020-02-14-deprecating-oauth-auth-endpoint/). **Warning:** Apps must use the [web application flow](https://docs.github.com/enterprise-server@3.0/apps/building-oauth-apps/authorizing-oauth-apps/#web-application-flow) to obtain OAuth tokens that work with GitHub Enterprise Server SAML organizations. OAuth tokens created using the Authorizations API will be unable to access GitHub Enterprise Server SAML organizations. For more information, see the [blog post](https://developer.github.com/changes/2019-11-05-deprecated-passwords-and-authorizations-api). This method will create a new authorization for the specified OAuth application, only if an authorization for that application and fingerprint do not already exist for the user. The URL includes the 20 character client ID for the OAuth app that is requesting the token. `fingerprint` is a unique string to distinguish an authorization from others created for the same client ID and user. It returns the user's existing authorization for the application if one is present. Otherwise, it creates and returns a new one. If you have two-factor authentication setup, Basic Authentication for this endpoint requires that you use a one-time password (OTP) and your username and password instead of tokens. For more information, see "[Working with two-factor authentication](https://docs.github.com/enterprise-server@3.0/rest/overview/other-authentication-methods#working-with-two-factor-authentication)." tags: - oauth-authorizations operationId: oauth-authorizations/get-or-create-authorization-for-app-and-fingerprint externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/oauth-authorizations#get-or-create-an-authorization-for-a-specific-app-and-fingerprint parameters: - "$ref": "#/components/parameters/client-id" - name: fingerprint in: path required: true schema: type: string requestBody: required: true content: application/json: schema: properties: client_secret: description: The OAuth app client secret for which to create the token. maxLength: 40 type: string scopes: description: A list of scopes that this authorization is in. type: - array - 'null' items: type: string examples: - public_repo - user note: description: A note to remind you what the OAuth token is for. type: string examples: - Update all gems note_url: description: A URL to remind you what app the OAuth token is for. type: string required: - client_secret type: object responses: '200': description: if returning an existing token content: application/json: schema: "$ref": "#/components/schemas/authorization" examples: response-if-returning-an-existing-token: "$ref": "#/components/examples/authorization-response-if-returning-an-existing-token" headers: Location: example: https://api.github.com/authorizations/1 schema: type: string '201': description: Response if returning a new token content: application/json: schema: "$ref": "#/components/schemas/authorization" examples: default: "$ref": "#/components/examples/authorization-3" headers: Location: example: https://api.github.com/authorizations/1 schema: type: string '422': "$ref": "#/components/responses/validation_failed" x-github: githubCloudOnly: false enabledForGitHubApps: false removalDate: '2020-11-13' deprecationDate: '2020-02-14' category: oauth-authorizations subcategory: deprecated: true "/authorizations/{authorization_id}": get: summary: Get a single authorization description: "**Deprecation Notice:** GitHub Enterprise Server will discontinue the [OAuth Authorizations API](https://docs.github.com/enterprise-server@3.0/rest/reference/oauth-authorizations), which is used by integrations to create personal access tokens and OAuth tokens, and you must now create these tokens using our [web application flow](https://docs.github.com/enterprise-server@3.0/apps/building-oauth-apps/authorizing-oauth-apps/#web-application-flow). The [OAuth Authorizations API](https://docs.github.com/enterprise-server@3.0/rest/reference/oauth-authorizations) will be removed on November, 13, 2020. For more information, including scheduled brownouts, see the [blog post](https://developer.github.com/changes/2020-02-14-deprecating-oauth-auth-endpoint/)." tags: - oauth-authorizations operationId: oauth-authorizations/get-authorization externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/oauth-authorizations#get-a-single-authorization parameters: - "$ref": "#/components/parameters/authorization-id" responses: '200': description: Response content: application/json: schema: "$ref": "#/components/schemas/authorization" examples: default: "$ref": "#/components/examples/authorization-2" '304': "$ref": "#/components/responses/not_modified" '403': "$ref": "#/components/responses/forbidden" '401': "$ref": "#/components/responses/requires_authentication" x-github: githubCloudOnly: false enabledForGitHubApps: false removalDate: '2020-11-13' deprecationDate: '2020-02-14' category: oauth-authorizations subcategory: deprecated: true patch: summary: Update an existing authorization description: |- **Deprecation Notice:** GitHub Enterprise Server will discontinue the [OAuth Authorizations API](https://docs.github.com/enterprise-server@3.0/rest/reference/oauth-authorizations/), which is used by integrations to create personal access tokens and OAuth tokens, and you must now create these tokens using our [web application flow](https://docs.github.com/enterprise-server@3.0/developers/apps/authorizing-oauth-apps#web-application-flow). The [OAuth Authorizations API](https://docs.github.com/enterprise-server@3.0/rest/reference/oauth-authorizations) will be removed on November, 13, 2020. For more information, including scheduled brownouts, see the [blog post](https://developer.github.com/changes/2020-02-14-deprecating-oauth-auth-endpoint/). If you have two-factor authentication setup, Basic Authentication for this endpoint requires that you use a one-time password (OTP) and your username and password instead of tokens. For more information, see "[Working with two-factor authentication](https://docs.github.com/enterprise-server@3.0/rest/overview/other-authentication-methods#working-with-two-factor-authentication)." You can only send one of these scope keys at a time. tags: - oauth-authorizations operationId: oauth-authorizations/update-authorization externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/oauth-authorizations#update-an-existing-authorization parameters: - "$ref": "#/components/parameters/authorization-id" requestBody: required: false content: application/json: schema: type: object properties: scopes: description: A list of scopes that this authorization is in. type: - array - 'null' items: type: string examples: - public_repo - user add_scopes: description: A list of scopes to add to this authorization. type: array items: type: string remove_scopes: description: A list of scopes to remove from this authorization. type: array items: type: string note: description: A note to remind you what the OAuth token is for. type: string examples: - Update all gems note_url: description: A URL to remind you what app the OAuth token is for. type: string fingerprint: description: A unique string to distinguish an authorization from others created for the same client ID and user. type: string responses: '200': description: Response content: application/json: schema: "$ref": "#/components/schemas/authorization" examples: default: "$ref": "#/components/examples/authorization-2" '422': "$ref": "#/components/responses/validation_failed" x-github: githubCloudOnly: false enabledForGitHubApps: false removalDate: '2020-11-13' deprecationDate: '2020-02-14' category: oauth-authorizations subcategory: deprecated: true delete: summary: Delete an authorization description: "**Deprecation Notice:** GitHub Enterprise Server will discontinue the [OAuth Authorizations API](https://docs.github.com/enterprise-server@3.0/rest/reference/oauth-authorizations), which is used by integrations to create personal access tokens and OAuth tokens, and you must now create these tokens using our [web application flow](https://docs.github.com/enterprise-server@3.0/apps/building-oauth-apps/authorizing-oauth-apps/#web-application-flow). The [OAuth Authorizations API](https://docs.github.com/enterprise-server@3.0/rest/reference/oauth-authorizations) will be removed on November, 13, 2020. For more information, including scheduled brownouts, see the [blog post](https://developer.github.com/changes/2020-02-14-deprecating-oauth-auth-endpoint/)." tags: - oauth-authorizations operationId: oauth-authorizations/delete-authorization externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/oauth-authorizations#delete-an-authorization parameters: - "$ref": "#/components/parameters/authorization-id" responses: '204': description: Response '304': "$ref": "#/components/responses/not_modified" '403': "$ref": "#/components/responses/forbidden" '401': "$ref": "#/components/responses/requires_authentication" x-github: githubCloudOnly: false enabledForGitHubApps: false removalDate: '2020-11-13' deprecationDate: '2020-02-14' category: oauth-authorizations subcategory: deprecated: true "/codes_of_conduct": get: summary: Get all codes of conduct description: '' tags: - codes-of-conduct operationId: codes-of-conduct/get-all-codes-of-conduct externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/codes-of-conduct#get-all-codes-of-conduct parameters: [] responses: '200': description: Response content: application/json: schema: type: array items: "$ref": "#/components/schemas/code-of-conduct" examples: default: "$ref": "#/components/examples/code-of-conduct-simple-items" '304': "$ref": "#/components/responses/not_modified" x-github: githubCloudOnly: false enabledForGitHubApps: true category: codes-of-conduct subcategory: "/codes_of_conduct/{key}": get: summary: Get a code of conduct description: '' tags: - codes-of-conduct operationId: codes-of-conduct/get-conduct-code externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/codes-of-conduct#get-a-code-of-conduct parameters: - name: key in: path required: true schema: type: string responses: '200': description: Response content: application/json: schema: "$ref": "#/components/schemas/code-of-conduct" examples: default: "$ref": "#/components/examples/code-of-conduct" '404': "$ref": "#/components/responses/not_found" '304': "$ref": "#/components/responses/not_modified" x-github: githubCloudOnly: false enabledForGitHubApps: true category: codes-of-conduct subcategory: "/emojis": get: summary: Get emojis description: Lists all the emojis available to use on GitHub Enterprise Server. operationId: emojis/get tags: - emojis externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/emojis#get-emojis parameters: [] responses: '200': content: application/json: schema: type: object additionalProperties: type: string description: Response '304': "$ref": "#/components/responses/not_modified" x-github: githubCloudOnly: false enabledForGitHubApps: true category: emojis subcategory: "/enterprise/announcement": get: summary: Get the global announcement banner description: Gets the current message and expiration date of the global announcement banner in your enterprise. tags: - enterprise-admin operationId: enterprise-admin/get-announcement responses: '200': description: Response content: application/json: schema: "$ref": "#/components/schemas/announcement" examples: default: "$ref": "#/components/examples/announcement" x-github: githubCloudOnly: false enabledForGitHubApps: false category: enterprise-admin subcategory: announcement patch: summary: Set the global announcement banner description: Sets the message and expiration time for the global announcement banner in your enterprise. tags: - enterprise-admin operationId: enterprise-admin/set-announcement requestBody: required: true content: application/json: schema: "$ref": "#/components/schemas/announcement" responses: '200': description: Response content: application/json: schema: "$ref": "#/components/schemas/announcement" examples: default: "$ref": "#/components/examples/announcement" x-github: githubCloudOnly: false enabledForGitHubApps: false category: enterprise-admin subcategory: announcement delete: summary: Remove the global announcement banner description: Removes the global announcement banner in your enterprise. tags: - enterprise-admin operationId: enterprise-admin/remove-announcement responses: '204': description: Response x-github: githubCloudOnly: false enabledForGitHubApps: false category: enterprise-admin subcategory: announcement "/enterprise/settings/license": get: summary: Get license information description: '' operationId: enterprise-admin/get-license-information tags: - enterprise-admin externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/enterprise-admin#get-license-information responses: '200': description: Response content: application/json: schema: "$ref": "#/components/schemas/license-info" examples: default: "$ref": "#/components/examples/license-info" x-github: githubCloudOnly: false enabledForGitHubApps: false category: enterprise-admin subcategory: license "/enterprise/stats/all": get: summary: Get all statistics description: '' operationId: enterprise-admin/get-all-stats tags: - enterprise-admin externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/enterprise-admin#get-statistics responses: '200': description: Response content: application/json: schema: "$ref": "#/components/schemas/enterprise-overview" examples: default: "$ref": "#/components/examples/enterprise-overview" x-github: githubCloudOnly: false enabledForGitHubApps: false category: enterprise-admin subcategory: admin-stats "/enterprise/stats/comments": get: summary: Get comment statistics description: '' operationId: enterprise-admin/get-comment-stats tags: - enterprise-admin externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/enterprise-admin#get-comment-statistics responses: '200': description: Response content: application/json: schema: "$ref": "#/components/schemas/enterprise-comment-overview" x-github: githubCloudOnly: false enabledForGitHubApps: false category: enterprise-admin subcategory: admin-stats "/enterprise/stats/gists": get: summary: Get gist statistics description: '' operationId: enterprise-admin/get-gist-stats tags: - enterprise-admin externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/enterprise-admin#get-gist-statistics responses: '200': description: Response content: application/json: schema: "$ref": "#/components/schemas/enterprise-gist-overview" x-github: githubCloudOnly: false enabledForGitHubApps: false category: enterprise-admin subcategory: admin-stats "/enterprise/stats/hooks": get: summary: Get hooks statistics operationId: enterprise-admin/get-hooks-stats tags: - enterprise-admin externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/enterprise-admin#get-hooks-statistics responses: '200': description: Response content: application/json: schema: "$ref": "#/components/schemas/enterprise-hook-overview" x-github: githubCloudOnly: false enabledForGitHubApps: false category: enterprise-admin subcategory: admin-stats "/enterprise/stats/issues": get: summary: Get issue statistics description: '' operationId: enterprise-admin/get-issue-stats tags: - enterprise-admin externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/enterprise-admin#get-issues-statistics responses: '200': description: Response content: application/json: schema: "$ref": "#/components/schemas/enterprise-issue-overview" x-github: githubCloudOnly: false enabledForGitHubApps: false category: enterprise-admin subcategory: admin-stats "/enterprise/stats/milestones": get: summary: Get milestone statistics description: '' operationId: enterprise-admin/get-milestone-stats tags: - enterprise-admin externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/enterprise-admin#get-milestone-statistics responses: '200': description: Response content: application/json: schema: "$ref": "#/components/schemas/enterprise-milestone-overview" x-github: githubCloudOnly: false enabledForGitHubApps: false category: enterprise-admin subcategory: admin-stats "/enterprise/stats/orgs": get: summary: Get organization statistics description: '' operationId: enterprise-admin/get-org-stats tags: - enterprise-admin externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/enterprise-admin#get-organization-statistics responses: '200': description: Response content: application/json: schema: "$ref": "#/components/schemas/enterprise-organization-overview" x-github: githubCloudOnly: false enabledForGitHubApps: false category: enterprise-admin subcategory: admin-stats "/enterprise/stats/pages": get: summary: Get pages statistics description: '' operationId: enterprise-admin/get-pages-stats tags: - enterprise-admin externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/enterprise-admin#get-pages-statistics responses: '200': description: Response content: application/json: schema: "$ref": "#/components/schemas/enterprise-page-overview" x-github: githubCloudOnly: false enabledForGitHubApps: false category: enterprise-admin subcategory: admin-stats "/enterprise/stats/pulls": get: summary: Get pull request statistics description: '' operationId: enterprise-admin/get-pull-request-stats tags: - enterprise-admin externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/enterprise-admin#get-pull-requests-statistics responses: '200': description: Response content: application/json: schema: "$ref": "#/components/schemas/enterprise-pull-request-overview" x-github: githubCloudOnly: false enabledForGitHubApps: false category: enterprise-admin subcategory: admin-stats "/enterprise/stats/repos": get: summary: Get repository statistics operationId: enterprise-admin/get-repo-stats tags: - enterprise-admin externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/enterprise-admin#get-repository-statistics responses: '200': description: Response content: application/json: schema: "$ref": "#/components/schemas/enterprise-repository-overview" x-github: githubCloudOnly: false enabledForGitHubApps: false category: enterprise-admin subcategory: admin-stats "/enterprise/stats/users": get: summary: Get users statistics description: '' operationId: enterprise-admin/get-user-stats tags: - enterprise-admin externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/enterprise-admin#get-users-statistics responses: '200': description: Response content: application/json: schema: "$ref": "#/components/schemas/enterprise-user-overview" x-github: githubCloudOnly: false enabledForGitHubApps: false category: enterprise-admin subcategory: admin-stats "/enterprises/{enterprise}/actions/permissions": get: summary: Get GitHub Actions permissions for an enterprise description: |- Gets the GitHub Actions permissions policy for organizations and allowed actions in an enterprise. You must authenticate using an access token with the `admin:enterprise` scope to use this endpoint. operationId: enterprise-admin/get-github-actions-permissions-enterprise tags: - enterprise-admin externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/actions#get-github-actions-permissions-for-an-enterprise parameters: - "$ref": "#/components/parameters/enterprise" responses: '200': description: Response content: application/json: schema: "$ref": "#/components/schemas/actions-enterprise-permissions" examples: default: "$ref": "#/components/examples/actions-enterprise-permissions" x-github: enabledForGitHubApps: false githubCloudOnly: false category: actions subcategory: permissions put: summary: Set GitHub Actions permissions for an enterprise description: |- Sets the GitHub Actions permissions policy for organizations and allowed actions in an enterprise. You must authenticate using an access token with the `admin:enterprise` scope to use this endpoint. operationId: enterprise-admin/set-github-actions-permissions-enterprise tags: - enterprise-admin externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/actions#set-github-actions-permissions-for-an-enterprise parameters: - "$ref": "#/components/parameters/enterprise" responses: '204': description: Response requestBody: required: true content: application/json: schema: type: object properties: enabled_organizations: "$ref": "#/components/schemas/enabled-organizations" allowed_actions: "$ref": "#/components/schemas/allowed-actions" required: - enabled_organizations example: enabled_organizations: all allowed_actions: selected x-github: enabledForGitHubApps: false githubCloudOnly: false category: actions subcategory: permissions "/enterprises/{enterprise}/actions/permissions/organizations": get: summary: List selected organizations enabled for GitHub Actions in an enterprise description: |- Lists the organizations that are selected to have GitHub Actions enabled in an enterprise. To use this endpoint, the enterprise permission policy for `enabled_organizations` must be configured to `selected`. For more information, see "[Set GitHub Actions permissions for an enterprise](#set-github-actions-permissions-for-an-enterprise)." You must authenticate using an access token with the `admin:enterprise` scope to use this endpoint. operationId: enterprise-admin/list-selected-organizations-enabled-github-actions-enterprise tags: - enterprise-admin externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/actions#list-selected-organizations-enabled-for-github-actions-in-an-enterprise parameters: - "$ref": "#/components/parameters/enterprise" - "$ref": "#/components/parameters/per-page" - "$ref": "#/components/parameters/page" responses: '200': description: Response content: application/json: schema: type: object properties: total_count: type: number organizations: type: array items: "$ref": "#/components/schemas/organization-simple" required: - total_count - organizations examples: default: "$ref": "#/components/examples/organization-targets" x-github: enabledForGitHubApps: false githubCloudOnly: false category: actions subcategory: permissions put: summary: Set selected organizations enabled for GitHub Actions in an enterprise description: |- Replaces the list of selected organizations that are enabled for GitHub Actions in an enterprise. To use this endpoint, the enterprise permission policy for `enabled_organizations` must be configured to `selected`. For more information, see "[Set GitHub Actions permissions for an enterprise](#set-github-actions-permissions-for-an-enterprise)." You must authenticate using an access token with the `admin:enterprise` scope to use this endpoint. operationId: enterprise-admin/set-selected-organizations-enabled-github-actions-enterprise tags: - enterprise-admin externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/actions#set-selected-organizations-enabled-for-github-actions-in-an-enterprise parameters: - "$ref": "#/components/parameters/enterprise" responses: '204': description: Response requestBody: required: true content: application/json: schema: type: object properties: selected_organization_ids: description: List of organization IDs to enable for GitHub Actions. type: array items: type: integer description: Unique identifier of the organization. required: - selected_organization_ids example: selected_organization_ids: - 32 - 91 x-github: enabledForGitHubApps: false githubCloudOnly: false category: actions subcategory: permissions "/enterprises/{enterprise}/actions/permissions/organizations/{org_id}": put: summary: Enable a selected organization for GitHub Actions in an enterprise description: |- Adds an organization to the list of selected organizations that are enabled for GitHub Actions in an enterprise. To use this endpoint, the enterprise permission policy for `enabled_organizations` must be configured to `selected`. For more information, see "[Set GitHub Actions permissions for an enterprise](#set-github-actions-permissions-for-an-enterprise)." You must authenticate using an access token with the `admin:enterprise` scope to use this endpoint. operationId: enterprise-admin/enable-selected-organization-github-actions-enterprise tags: - enterprise-admin externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/actions#enable-a-selected-organization-for-github-actions-in-an-enterprise parameters: - "$ref": "#/components/parameters/enterprise" - "$ref": "#/components/parameters/org-id" responses: '204': description: Response x-github: enabledForGitHubApps: false githubCloudOnly: false category: actions subcategory: permissions delete: summary: Disable a selected organization for GitHub Actions in an enterprise description: |- Removes an organization from the list of selected organizations that are enabled for GitHub Actions in an enterprise. To use this endpoint, the enterprise permission policy for `enabled_organizations` must be configured to `selected`. For more information, see "[Set GitHub Actions permissions for an enterprise](#set-github-actions-permissions-for-an-enterprise)." You must authenticate using an access token with the `admin:enterprise` scope to use this endpoint. operationId: enterprise-admin/disable-selected-organization-github-actions-enterprise tags: - enterprise-admin externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/actions#disable-a-selected-organization-for-github-actions-in-an-enterprise parameters: - "$ref": "#/components/parameters/enterprise" - "$ref": "#/components/parameters/org-id" responses: '204': description: Response x-github: enabledForGitHubApps: false githubCloudOnly: false category: actions subcategory: permissions "/enterprises/{enterprise}/actions/permissions/selected-actions": get: summary: Get allowed actions for an enterprise description: |- Gets the selected actions that are allowed in an enterprise. To use this endpoint, the enterprise permission policy for `allowed_actions` must be configured to `selected`. For more information, see "[Set GitHub Actions permissions for an enterprise](#set-github-actions-permissions-for-an-enterprise)." You must authenticate using an access token with the `admin:enterprise` scope to use this endpoint. operationId: enterprise-admin/get-allowed-actions-enterprise tags: - enterprise-admin externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/actions#get-allowed-actions-for-an-enterprise parameters: - "$ref": "#/components/parameters/enterprise" responses: '200': description: Response content: application/json: schema: "$ref": "#/components/schemas/selected-actions" examples: default: "$ref": "#/components/examples/selected-actions" x-github: enabledForGitHubApps: false githubCloudOnly: false category: actions subcategory: permissions put: summary: Set allowed actions for an enterprise description: |- Sets the actions that are allowed in an enterprise. To use this endpoint, the enterprise permission policy for `allowed_actions` must be configured to `selected`. For more information, see "[Set GitHub Actions permissions for an enterprise](#set-github-actions-permissions-for-an-enterprise)." You must authenticate using an access token with the `admin:enterprise` scope to use this endpoint. operationId: enterprise-admin/set-allowed-actions-enterprise tags: - enterprise-admin externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/actions#set-allowed-actions-for-an-enterprise parameters: - "$ref": "#/components/parameters/enterprise" responses: '204': description: Response requestBody: required: true content: application/json: schema: "$ref": "#/components/schemas/selected-actions" examples: selected_actions: "$ref": "#/components/examples/selected-actions" x-github: enabledForGitHubApps: false githubCloudOnly: false category: actions subcategory: permissions "/enterprises/{enterprise}/actions/runner-groups": get: summary: List self-hosted runner groups for an enterprise description: |- Lists all self-hosted runner groups for an enterprise. You must authenticate using an access token with the `admin:enterprise` scope to use this endpoint. operationId: enterprise-admin/list-self-hosted-runner-groups-for-enterprise tags: - enterprise-admin externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/actions#list-self-hosted-runner-groups-for-an-enterprise parameters: - "$ref": "#/components/parameters/enterprise" - "$ref": "#/components/parameters/per-page" - "$ref": "#/components/parameters/page" responses: '200': description: Response content: application/json: schema: type: object properties: total_count: type: number runner_groups: type: array items: "$ref": "#/components/schemas/runner-groups-enterprise" required: - total_count - runner_groups examples: default: "$ref": "#/components/examples/runner-groups-enterprise" x-github: enabledForGitHubApps: false githubCloudOnly: false category: actions subcategory: self-hosted-runner-groups post: summary: Create a self-hosted runner group for an enterprise description: |- Creates a new self-hosted runner group for an enterprise. You must authenticate using an access token with the `admin:enterprise` scope to use this endpoint. operationId: enterprise-admin/create-self-hosted-runner-group-for-enterprise tags: - enterprise-admin externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/actions#create-self-hosted-runner-group-for-an-enterprise parameters: - "$ref": "#/components/parameters/enterprise" requestBody: required: true content: application/json: schema: type: object properties: name: description: Name of the runner group. type: string visibility: description: 'Visibility of a runner group. You can select all organizations or select individual organization. Can be one of: `all` or `selected`' type: string enum: - selected - all selected_organization_ids: description: List of organization IDs that can access the runner group. type: array items: type: integer description: Unique identifier of the organization. runners: description: List of runner IDs to add to the runner group. type: array items: type: integer description: Unique identifier of the runner. allows_public_repositories: description: Whether the runner group can be used by `public` repositories. type: boolean default: false required: - name example: name: Expensive hardware runners visibility: selected selected_organization_ids: - 32 - 91 runners: - 9 - 2 responses: '201': description: Response content: application/json: schema: "$ref": "#/components/schemas/runner-groups-enterprise" examples: default: "$ref": "#/components/examples/runner-group-enterprise" x-github: enabledForGitHubApps: false githubCloudOnly: false category: actions subcategory: self-hosted-runner-groups "/enterprises/{enterprise}/actions/runner-groups/{runner_group_id}": get: summary: Get a self-hosted runner group for an enterprise description: |- Gets a specific self-hosted runner group for an enterprise. You must authenticate using an access token with the `admin:enterprise` scope to use this endpoint. operationId: enterprise-admin/get-self-hosted-runner-group-for-enterprise tags: - enterprise-admin externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/actions#get-a-self-hosted-runner-group-for-an-enterprise parameters: - "$ref": "#/components/parameters/enterprise" - "$ref": "#/components/parameters/runner-group-id" responses: '200': description: Response content: application/json: schema: "$ref": "#/components/schemas/runner-groups-enterprise" examples: default: "$ref": "#/components/examples/runner-group-enterprise" x-github: enabledForGitHubApps: false githubCloudOnly: false category: actions subcategory: self-hosted-runner-groups patch: summary: Update a self-hosted runner group for an enterprise description: |- Updates the `name` and `visibility` of a self-hosted runner group in an enterprise. You must authenticate using an access token with the `admin:enterprise` scope to use this endpoint. operationId: enterprise-admin/update-self-hosted-runner-group-for-enterprise tags: - enterprise-admin externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/actions#update-a-self-hosted-runner-group-for-an-enterprise parameters: - "$ref": "#/components/parameters/enterprise" - "$ref": "#/components/parameters/runner-group-id" requestBody: required: false content: application/json: schema: type: object properties: name: description: Name of the runner group. type: string visibility: description: 'Visibility of a runner group. You can select all organizations or select individual organizations. Can be one of: `all` or `selected`' type: string enum: - selected - all default: all allows_public_repositories: description: Whether the runner group can be used by `public` repositories. type: boolean default: false example: name: Expensive hardware runners visibility: selected responses: '200': description: Response content: application/json: schema: "$ref": "#/components/schemas/runner-groups-enterprise" examples: default: "$ref": "#/components/examples/runner-group-update-enterprise" x-github: enabledForGitHubApps: false githubCloudOnly: false category: actions subcategory: self-hosted-runner-groups delete: summary: Delete a self-hosted runner group from an enterprise description: |- Deletes a self-hosted runner group for an enterprise. You must authenticate using an access token with the `admin:enterprise` scope to use this endpoint. operationId: enterprise-admin/delete-self-hosted-runner-group-from-enterprise tags: - enterprise-admin externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/actions#delete-a-self-hosted-runner-group-from-an-enterprise parameters: - "$ref": "#/components/parameters/enterprise" - "$ref": "#/components/parameters/runner-group-id" responses: '204': description: Response x-github: enabledForGitHubApps: false githubCloudOnly: false category: actions subcategory: self-hosted-runner-groups "/enterprises/{enterprise}/actions/runner-groups/{runner_group_id}/organizations": get: summary: List organization access to a self-hosted runner group in an enterprise description: |- Lists the organizations with access to a self-hosted runner group. You must authenticate using an access token with the `admin:enterprise` scope to use this endpoint. operationId: enterprise-admin/list-org-access-to-self-hosted-runner-group-in-enterprise tags: - enterprise-admin externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/actions#list-organization-access-to-a-self-hosted-runner-group-in-a-enterprise parameters: - "$ref": "#/components/parameters/enterprise" - "$ref": "#/components/parameters/runner-group-id" - "$ref": "#/components/parameters/per-page" - "$ref": "#/components/parameters/page" responses: '200': description: Response content: application/json: schema: type: object properties: total_count: type: number organizations: type: array items: "$ref": "#/components/schemas/organization-simple" required: - total_count - organizations examples: default: "$ref": "#/components/examples/organization-targets" x-github: enabledForGitHubApps: false githubCloudOnly: false category: actions subcategory: self-hosted-runner-groups put: summary: Set organization access for a self-hosted runner group in an enterprise description: |- Replaces the list of organizations that have access to a self-hosted runner configured in an enterprise. You must authenticate using an access token with the `admin:enterprise` scope to use this endpoint. operationId: enterprise-admin/set-org-access-to-self-hosted-runner-group-in-enterprise tags: - enterprise-admin externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/actions#set-organization-access-to-a-self-hosted-runner-group-in-an-enterprise parameters: - "$ref": "#/components/parameters/enterprise" - "$ref": "#/components/parameters/runner-group-id" requestBody: required: true content: application/json: schema: type: object properties: selected_organization_ids: description: List of organization IDs that can access the runner group. type: array items: type: integer description: Unique identifier of the organization. required: - selected_organization_ids example: selected_organization_ids: - 32 - 91 responses: '204': description: Response x-github: enabledForGitHubApps: false githubCloudOnly: false category: actions subcategory: self-hosted-runner-groups "/enterprises/{enterprise}/actions/runner-groups/{runner_group_id}/organizations/{org_id}": put: summary: Add organization access to a self-hosted runner group in an enterprise description: |- Adds an organization to the list of selected organizations that can access a self-hosted runner group. The runner group must have `visibility` set to `selected`. For more information, see "[Create a self-hosted runner group for an enterprise](#create-a-self-hosted-runner-group-for-an-enterprise)." You must authenticate using an access token with the `admin:enterprise` scope to use this endpoint. operationId: enterprise-admin/add-org-access-to-self-hosted-runner-group-in-enterprise tags: - enterprise-admin externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/actions#add-organization-access-to-a-self-hosted-runner-group-in-an-enterprise parameters: - "$ref": "#/components/parameters/enterprise" - "$ref": "#/components/parameters/runner-group-id" - "$ref": "#/components/parameters/org-id" responses: '204': description: Response x-github: enabledForGitHubApps: false githubCloudOnly: false category: actions subcategory: self-hosted-runner-groups delete: summary: Remove organization access to a self-hosted runner group in an enterprise description: |- Removes an organization from the list of selected organizations that can access a self-hosted runner group. The runner group must have `visibility` set to `selected`. For more information, see "[Create a self-hosted runner group for an enterprise](#create-a-self-hosted-runner-group-for-an-enterprise)." You must authenticate using an access token with the `admin:enterprise` scope to use this endpoint. operationId: enterprise-admin/remove-org-access-to-self-hosted-runner-group-in-enterprise tags: - enterprise-admin externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/actions#remove-organization-access-to-a-self-hosted-runner-group-in-an-enterprise parameters: - "$ref": "#/components/parameters/enterprise" - "$ref": "#/components/parameters/runner-group-id" - "$ref": "#/components/parameters/org-id" responses: '204': description: Response x-github: enabledForGitHubApps: false githubCloudOnly: false category: actions subcategory: self-hosted-runner-groups "/enterprises/{enterprise}/actions/runner-groups/{runner_group_id}/runners": get: summary: List self-hosted runners in a group for an enterprise description: |- Lists the self-hosted runners that are in a specific enterprise group. You must authenticate using an access token with the `admin:enterprise` scope to use this endpoint. operationId: enterprise-admin/list-self-hosted-runners-in-group-for-enterprise tags: - enterprise-admin externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/actions#list-self-hosted-runners-in-a-group-for-an-enterprise parameters: - "$ref": "#/components/parameters/enterprise" - "$ref": "#/components/parameters/runner-group-id" - "$ref": "#/components/parameters/per-page" - "$ref": "#/components/parameters/page" responses: '200': description: Response content: application/json: schema: type: object properties: total_count: type: number runners: type: array items: "$ref": "#/components/schemas/runner" required: - total_count - runners examples: default: "$ref": "#/components/examples/runner-paginated" headers: Link: "$ref": "#/components/headers/link" x-github: enabledForGitHubApps: false githubCloudOnly: false category: actions subcategory: self-hosted-runner-groups put: summary: Set self-hosted runners in a group for an enterprise description: |- Replaces the list of self-hosted runners that are part of an enterprise runner group. You must authenticate using an access token with the `admin:enterprise` scope to use this endpoint. operationId: enterprise-admin/set-self-hosted-runners-in-group-for-enterprise tags: - enterprise-admin externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/actions#set-self-hosted-runners-in-a-group-for-an-enterprise parameters: - "$ref": "#/components/parameters/enterprise" - "$ref": "#/components/parameters/runner-group-id" requestBody: required: true content: application/json: schema: type: object properties: runners: description: List of runner IDs to add to the runner group. type: array items: type: integer description: Unique identifier of the runner. required: - runners example: runners: - 9 - 2 responses: '204': description: Response x-github: enabledForGitHubApps: false githubCloudOnly: false category: actions subcategory: self-hosted-runner-groups "/enterprises/{enterprise}/actions/runner-groups/{runner_group_id}/runners/{runner_id}": put: summary: Add a self-hosted runner to a group for an enterprise description: |- Adds a self-hosted runner to a runner group configured in an enterprise. You must authenticate using an access token with the `admin:enterprise` scope to use this endpoint. operationId: enterprise-admin/add-self-hosted-runner-to-group-for-enterprise tags: - enterprise-admin externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/actions#add-a-self-hosted-runner-to-a-group-for-an-enterprise parameters: - "$ref": "#/components/parameters/enterprise" - "$ref": "#/components/parameters/runner-group-id" - "$ref": "#/components/parameters/runner-id" responses: '204': description: Response x-github: enabledForGitHubApps: false githubCloudOnly: false category: actions subcategory: self-hosted-runner-groups delete: summary: Remove a self-hosted runner from a group for an enterprise description: |- Removes a self-hosted runner from a group configured in an enterprise. The runner is then returned to the default group. You must authenticate using an access token with the `admin:enterprise` scope to use this endpoint. operationId: enterprise-admin/remove-self-hosted-runner-from-group-for-enterprise tags: - enterprise-admin externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/actions#remove-a-self-hosted-runner-from-a-group-for-an-enterprise parameters: - "$ref": "#/components/parameters/enterprise" - "$ref": "#/components/parameters/runner-group-id" - "$ref": "#/components/parameters/runner-id" responses: '204': description: Response x-github: enabledForGitHubApps: false githubCloudOnly: false category: actions subcategory: self-hosted-runner-groups "/enterprises/{enterprise}/actions/runners": get: summary: List self-hosted runners for an enterprise description: |- Lists all self-hosted runners configured for an enterprise. You must authenticate using an access token with the `admin:enterprise` scope to use this endpoint. operationId: enterprise-admin/list-self-hosted-runners-for-enterprise tags: - enterprise-admin externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/actions#list-self-hosted-runners-for-an-enterprise parameters: - "$ref": "#/components/parameters/enterprise" - "$ref": "#/components/parameters/per-page" - "$ref": "#/components/parameters/page" responses: '200': description: Response content: application/json: schema: type: object properties: total_count: type: number runners: type: array items: "$ref": "#/components/schemas/runner" examples: default: "$ref": "#/components/examples/runner-paginated" headers: Link: "$ref": "#/components/headers/link" x-github: enabledForGitHubApps: false githubCloudOnly: false category: actions subcategory: self-hosted-runners "/enterprises/{enterprise}/actions/runners/downloads": get: summary: List runner applications for an enterprise description: |- Lists binaries for the runner application that you can download and run. You must authenticate using an access token with the `admin:enterprise` scope to use this endpoint. operationId: enterprise-admin/list-runner-applications-for-enterprise tags: - enterprise-admin externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/actions#list-runner-applications-for-an-enterprise parameters: - "$ref": "#/components/parameters/enterprise" responses: '200': description: Response content: application/json: schema: type: array items: "$ref": "#/components/schemas/runner-application" examples: default: "$ref": "#/components/examples/runner-application-items" x-github: enabledForGitHubApps: false githubCloudOnly: false category: actions subcategory: self-hosted-runners "/enterprises/{enterprise}/actions/runners/registration-token": post: summary: Create a registration token for an enterprise description: |- Returns a token that you can pass to the `config` script. The token expires after one hour. You must authenticate using an access token with the `admin:enterprise` scope to use this endpoint. #### Example using registration token Configure your self-hosted runner, replacing `TOKEN` with the registration token provided by this endpoint. ``` ./config.sh --url https://github.com/enterprises/octo-enterprise --token TOKEN ``` operationId: enterprise-admin/create-registration-token-for-enterprise tags: - enterprise-admin externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/actions#create-a-registration-token-for-an-enterprise parameters: - "$ref": "#/components/parameters/enterprise" responses: '201': description: Response content: application/json: schema: "$ref": "#/components/schemas/authentication-token" examples: default: "$ref": "#/components/examples/authentication-token" x-github: enabledForGitHubApps: false githubCloudOnly: false category: actions subcategory: self-hosted-runners "/enterprises/{enterprise}/actions/runners/remove-token": post: summary: Create a remove token for an enterprise description: |- Returns a token that you can pass to the `config` script to remove a self-hosted runner from an enterprise. The token expires after one hour. You must authenticate using an access token with the `admin:enterprise` scope to use this endpoint. #### Example using remove token To remove your self-hosted runner from an enterprise, replace `TOKEN` with the remove token provided by this endpoint. ``` ./config.sh remove --token TOKEN ``` operationId: enterprise-admin/create-remove-token-for-enterprise tags: - enterprise-admin externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/actions#create-a-remove-token-for-an-enterprise parameters: - "$ref": "#/components/parameters/enterprise" responses: '201': description: Response content: application/json: schema: "$ref": "#/components/schemas/authentication-token" examples: default: "$ref": "#/components/examples/authentication-token-2" x-github: enabledForGitHubApps: false githubCloudOnly: false category: actions subcategory: self-hosted-runners "/enterprises/{enterprise}/actions/runners/{runner_id}": get: summary: Get a self-hosted runner for an enterprise description: |- Gets a specific self-hosted runner configured in an enterprise. You must authenticate using an access token with the `admin:enterprise` scope to use this endpoint. operationId: enterprise-admin/get-self-hosted-runner-for-enterprise tags: - enterprise-admin externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/actions#get-a-self-hosted-runner-for-an-enterprise parameters: - "$ref": "#/components/parameters/enterprise" - "$ref": "#/components/parameters/runner-id" responses: '200': description: Response content: application/json: schema: "$ref": "#/components/schemas/runner" examples: default: "$ref": "#/components/examples/runner" x-github: enabledForGitHubApps: false githubCloudOnly: false category: actions subcategory: self-hosted-runners delete: summary: Delete a self-hosted runner from an enterprise description: |- Forces the removal of a self-hosted runner from an enterprise. You can use this endpoint to completely remove the runner when the machine you were using no longer exists. You must authenticate using an access token with the `admin:enterprise` scope to use this endpoint. operationId: enterprise-admin/delete-self-hosted-runner-from-enterprise tags: - enterprise-admin externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/actions#delete-self-hosted-runner-from-an-enterprise parameters: - "$ref": "#/components/parameters/enterprise" - "$ref": "#/components/parameters/runner-id" responses: '204': description: Response x-github: enabledForGitHubApps: false githubCloudOnly: false category: actions subcategory: self-hosted-runners "/events": get: summary: List public events description: We delay the public events feed by five minutes, which means the most recent event returned by the public events API actually occurred at least five minutes ago. tags: - activity operationId: activity/list-public-events externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/activity#list-public-events parameters: - "$ref": "#/components/parameters/per-page" - "$ref": "#/components/parameters/page" responses: '200': description: Response content: application/json: schema: type: array items: "$ref": "#/components/schemas/event" '304': "$ref": "#/components/responses/not_modified" '403': "$ref": "#/components/responses/forbidden" '503': "$ref": "#/components/responses/service_unavailable" x-github: githubCloudOnly: false enabledForGitHubApps: true category: activity subcategory: events "/feeds": get: summary: Get feeds description: |- GitHub Enterprise Server provides several timeline resources in [Atom](http://en.wikipedia.org/wiki/Atom_(standard)) format. The Feeds API lists all the feeds available to the authenticated user: * **Timeline**: The GitHub Enterprise Server global public timeline * **User**: The public timeline for any user, using [URI template](https://docs.github.com/enterprise-server@3.0/rest/overview/resources-in-the-rest-api#hypermedia) * **Current user public**: The public timeline for the authenticated user * **Current user**: The private timeline for the authenticated user * **Current user actor**: The private timeline for activity created by the authenticated user * **Current user organizations**: The private timeline for the organizations the authenticated user is a member of. * **Security advisories**: A collection of public announcements that provide information about security-related vulnerabilities in software on GitHub Enterprise Server. **Note**: Private feeds are only returned when [authenticating via Basic Auth](https://docs.github.com/enterprise-server@3.0/rest/overview/other-authentication-methods#basic-authentication) since current feed URIs use the older, non revocable auth tokens. tags: - activity operationId: activity/get-feeds externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/activity#get-feeds parameters: [] responses: '200': description: Response content: application/json: schema: "$ref": "#/components/schemas/feed" examples: default: "$ref": "#/components/examples/feed" x-github: githubCloudOnly: false enabledForGitHubApps: true category: activity subcategory: feeds "/gists": get: summary: List gists for the authenticated user description: 'Lists the authenticated user''s gists or if called anonymously, this endpoint returns all public gists:' tags: - gists operationId: gists/list externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/gists#list-gists-for-the-authenticated-user parameters: - "$ref": "#/components/parameters/since" - "$ref": "#/components/parameters/per-page" - "$ref": "#/components/parameters/page" responses: '200': description: Response content: application/json: schema: type: array items: "$ref": "#/components/schemas/base-gist" examples: default: "$ref": "#/components/examples/base-gist-items" headers: Link: "$ref": "#/components/headers/link" '304': "$ref": "#/components/responses/not_modified" '403': "$ref": "#/components/responses/forbidden" x-github: githubCloudOnly: false enabledForGitHubApps: false category: gists subcategory: post: summary: Create a gist description: |- Allows you to add a new gist with one or more files. **Note:** Don't name your files "gistfile" with a numerical suffix. This is the format of the automatic naming scheme that Gist uses internally. operationId: gists/create tags: - gists externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/gists#create-a-gist parameters: [] requestBody: required: true content: application/json: schema: properties: description: description: Description of the gist type: string examples: - Example Ruby script files: description: Names and content for the files that make up the gist type: object additionalProperties: type: object properties: content: description: Content of the file readOnly: false type: string required: - content examples: - hello.rb: content: puts "Hello, World!" public: oneOf: - description: Flag indicating whether the gist is public type: boolean default: false examples: - true - type: string default: 'false' enum: - 'true' - 'false' examples: - 'true' required: - files type: object responses: '201': description: Response content: application/json: schema: "$ref": "#/components/schemas/gist-simple" examples: default: "$ref": "#/components/examples/gist" headers: Location: example: https://api.github.com/gists/aa5a315d61ae9438b18d schema: type: string '422': "$ref": "#/components/responses/validation_failed" '304': "$ref": "#/components/responses/not_modified" '404': "$ref": "#/components/responses/not_found" '403': "$ref": "#/components/responses/forbidden" x-github: githubCloudOnly: false enabledForGitHubApps: false category: gists subcategory: "/gists/public": get: summary: List public gists description: |- List public gists sorted by most recently updated to least recently updated. Note: With [pagination](https://docs.github.com/enterprise-server@3.0/rest/overview/resources-in-the-rest-api#pagination), you can fetch up to 3000 gists. For example, you can fetch 100 pages with 30 gists per page or 30 pages with 100 gists per page. tags: - gists operationId: gists/list-public externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/gists#list-public-gists parameters: - "$ref": "#/components/parameters/since" - "$ref": "#/components/parameters/per-page" - "$ref": "#/components/parameters/page" responses: '200': description: Response content: application/json: schema: type: array items: "$ref": "#/components/schemas/base-gist" examples: default: "$ref": "#/components/examples/base-gist-items" headers: Link: "$ref": "#/components/headers/link" '422': "$ref": "#/components/responses/validation_failed" '304': "$ref": "#/components/responses/not_modified" '403': "$ref": "#/components/responses/forbidden" x-github: githubCloudOnly: false enabledForGitHubApps: false category: gists subcategory: "/gists/starred": get: summary: List starred gists description: 'List the authenticated user''s starred gists:' tags: - gists operationId: gists/list-starred externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/gists#list-starred-gists parameters: - "$ref": "#/components/parameters/since" - "$ref": "#/components/parameters/per-page" - "$ref": "#/components/parameters/page" responses: '200': description: Response content: application/json: schema: type: array items: "$ref": "#/components/schemas/base-gist" examples: default: "$ref": "#/components/examples/base-gist-items" headers: Link: "$ref": "#/components/headers/link" '401': "$ref": "#/components/responses/requires_authentication" '304': "$ref": "#/components/responses/not_modified" '403': "$ref": "#/components/responses/forbidden" x-github: githubCloudOnly: false enabledForGitHubApps: false category: gists subcategory: "/gists/{gist_id}": get: summary: Get a gist description: '' tags: - gists operationId: gists/get externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/gists#get-a-gist parameters: - "$ref": "#/components/parameters/gist-id" responses: '200': description: Response content: application/json: schema: "$ref": "#/components/schemas/gist-simple" examples: default: "$ref": "#/components/examples/gist" '403': "$ref": "#/components/responses/forbidden_gist" '404': "$ref": "#/components/responses/not_found" '304': "$ref": "#/components/responses/not_modified" x-github: githubCloudOnly: false enabledForGitHubApps: false category: gists subcategory: patch: summary: Update a gist description: Allows you to update or delete a gist file and rename gist files. Files from the previous version of the gist that aren't explicitly changed during an edit are unchanged. tags: - gists operationId: gists/update externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/gists/#update-a-gist parameters: - "$ref": "#/components/parameters/gist-id" requestBody: required: true content: application/json: schema: properties: description: description: Description of the gist type: string examples: - Example Ruby script files: description: Names of files to be updated type: object additionalProperties: type: - object - 'null' properties: content: description: The new content of the file type: string filename: description: The new filename for the file type: - string - 'null' anyOf: - required: - content - required: - filename - type: object maxProperties: 0 examples: - hello.rb: content: blah filename: goodbye.rb anyOf: - required: - description - required: - files type: - object - 'null' responses: '200': description: Response content: application/json: schema: "$ref": "#/components/schemas/gist-simple" examples: default: "$ref": "#/components/examples/gist" '422': "$ref": "#/components/responses/validation_failed" '404': "$ref": "#/components/responses/not_found" x-github: githubCloudOnly: false enabledForGitHubApps: false category: gists subcategory: delete: summary: Delete a gist description: '' tags: - gists operationId: gists/delete externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/gists#delete-a-gist parameters: - "$ref": "#/components/parameters/gist-id" responses: '204': description: Response '404': "$ref": "#/components/responses/not_found" '304': "$ref": "#/components/responses/not_modified" '403': "$ref": "#/components/responses/forbidden" x-github: githubCloudOnly: false enabledForGitHubApps: false category: gists subcategory: "/gists/{gist_id}/comments": get: summary: List gist comments description: '' tags: - gists operationId: gists/list-comments externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/gists#list-gist-comments parameters: - "$ref": "#/components/parameters/gist-id" - "$ref": "#/components/parameters/per-page" - "$ref": "#/components/parameters/page" responses: '200': description: Response content: application/json: schema: type: array items: "$ref": "#/components/schemas/gist-comment" examples: default: "$ref": "#/components/examples/gist-comment-items" headers: Link: "$ref": "#/components/headers/link" '304': "$ref": "#/components/responses/not_modified" '404': "$ref": "#/components/responses/not_found" '403': "$ref": "#/components/responses/forbidden" x-github: githubCloudOnly: false enabledForGitHubApps: false category: gists subcategory: comments post: summary: Create a gist comment description: '' tags: - gists operationId: gists/create-comment externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/gists#create-a-gist-comment parameters: - "$ref": "#/components/parameters/gist-id" requestBody: required: true content: application/json: schema: properties: body: description: The comment text. type: string maxLength: 65535 examples: - Body of the attachment type: object required: - body responses: '201': description: Response content: application/json: schema: "$ref": "#/components/schemas/gist-comment" examples: default: "$ref": "#/components/examples/gist-comment" headers: Location: example: https://api.github.com/gists/a6db0bec360bb87e9418/comments/1 schema: type: string '304': "$ref": "#/components/responses/not_modified" '404': "$ref": "#/components/responses/not_found" '403': "$ref": "#/components/responses/forbidden" x-github: githubCloudOnly: false enabledForGitHubApps: false category: gists subcategory: comments "/gists/{gist_id}/comments/{comment_id}": get: summary: Get a gist comment description: '' tags: - gists operationId: gists/get-comment externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/gists#get-a-gist-comment parameters: - "$ref": "#/components/parameters/gist-id" - "$ref": "#/components/parameters/comment-id" responses: '200': description: Response content: application/json: schema: "$ref": "#/components/schemas/gist-comment" examples: default: "$ref": "#/components/examples/gist-comment" '304': "$ref": "#/components/responses/not_modified" '404': "$ref": "#/components/responses/not_found" '403': "$ref": "#/components/responses/forbidden_gist" x-github: githubCloudOnly: false enabledForGitHubApps: false category: gists subcategory: comments patch: summary: Update a gist comment description: '' tags: - gists operationId: gists/update-comment externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/gists#update-a-gist-comment parameters: - "$ref": "#/components/parameters/gist-id" - "$ref": "#/components/parameters/comment-id" requestBody: required: true content: application/json: schema: properties: body: description: The comment text. type: string maxLength: 65535 examples: - Body of the attachment type: object required: - body responses: '200': description: Response content: application/json: schema: "$ref": "#/components/schemas/gist-comment" examples: default: "$ref": "#/components/examples/gist-comment" '404': "$ref": "#/components/responses/not_found" x-github: githubCloudOnly: false enabledForGitHubApps: false category: gists subcategory: comments delete: summary: Delete a gist comment description: '' tags: - gists operationId: gists/delete-comment externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/gists#delete-a-gist-comment parameters: - "$ref": "#/components/parameters/gist-id" - "$ref": "#/components/parameters/comment-id" responses: '204': description: Response '304': "$ref": "#/components/responses/not_modified" '404': "$ref": "#/components/responses/not_found" '403': "$ref": "#/components/responses/forbidden" x-github: githubCloudOnly: false enabledForGitHubApps: false category: gists subcategory: comments "/gists/{gist_id}/commits": get: summary: List gist commits description: '' tags: - gists operationId: gists/list-commits externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/gists#list-gist-commits parameters: - "$ref": "#/components/parameters/gist-id" - "$ref": "#/components/parameters/per-page" - "$ref": "#/components/parameters/page" responses: '200': description: Response content: application/json: schema: type: array items: "$ref": "#/components/schemas/gist-commit" examples: default: "$ref": "#/components/examples/gist-commit-items" headers: Link: example: ; rel="next" schema: type: string '404': "$ref": "#/components/responses/not_found" '304': "$ref": "#/components/responses/not_modified" '403': "$ref": "#/components/responses/forbidden" x-github: githubCloudOnly: false enabledForGitHubApps: false category: gists subcategory: "/gists/{gist_id}/forks": get: summary: List gist forks description: '' tags: - gists operationId: gists/list-forks externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/gists#list-gist-forks parameters: - "$ref": "#/components/parameters/gist-id" - "$ref": "#/components/parameters/per-page" - "$ref": "#/components/parameters/page" responses: '200': description: Response content: application/json: schema: type: array items: "$ref": "#/components/schemas/gist-simple" examples: default: "$ref": "#/components/examples/gist-fork-items" headers: Link: "$ref": "#/components/headers/link" '404': "$ref": "#/components/responses/not_found" '304': "$ref": "#/components/responses/not_modified" '403': "$ref": "#/components/responses/forbidden" x-github: githubCloudOnly: false enabledForGitHubApps: false category: gists subcategory: post: summary: Fork a gist description: "**Note**: This was previously `/gists/:gist_id/fork`." tags: - gists operationId: gists/fork externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/gists#fork-a-gist parameters: - "$ref": "#/components/parameters/gist-id" responses: '201': description: Response content: application/json: schema: "$ref": "#/components/schemas/base-gist" examples: default: "$ref": "#/components/examples/base-gist" headers: Location: example: https://api.github.com/gists/aa5a315d61ae9438b18d schema: type: string '404': "$ref": "#/components/responses/not_found" '422': "$ref": "#/components/responses/validation_failed" '304': "$ref": "#/components/responses/not_modified" '403': "$ref": "#/components/responses/forbidden" x-github: githubCloudOnly: false enabledForGitHubApps: false category: gists subcategory: "/gists/{gist_id}/star": get: summary: Check if a gist is starred description: '' tags: - gists operationId: gists/check-is-starred externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/gists#check-if-a-gist-is-starred parameters: - "$ref": "#/components/parameters/gist-id" responses: '204': description: Response if gist is starred '404': description: Not Found if gist is not starred content: application/json: schema: type: object properties: {} additionalProperties: false '304': "$ref": "#/components/responses/not_modified" '403': "$ref": "#/components/responses/forbidden" x-github: githubCloudOnly: false enabledForGitHubApps: false category: gists subcategory: put: summary: Star a gist description: Note that you'll need to set `Content-Length` to zero when calling out to this endpoint. For more information, see "[HTTP verbs](https://docs.github.com/enterprise-server@3.0/rest/overview/resources-in-the-rest-api#http-verbs)." tags: - gists operationId: gists/star externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/gists#star-a-gist parameters: - "$ref": "#/components/parameters/gist-id" responses: '204': description: Response '404': "$ref": "#/components/responses/not_found" '304': "$ref": "#/components/responses/not_modified" '403': "$ref": "#/components/responses/forbidden" x-github: githubCloudOnly: false enabledForGitHubApps: false category: gists subcategory: delete: summary: Unstar a gist description: '' tags: - gists operationId: gists/unstar externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/gists#unstar-a-gist parameters: - "$ref": "#/components/parameters/gist-id" responses: '204': description: Response '304': "$ref": "#/components/responses/not_modified" '404': "$ref": "#/components/responses/not_found" '403': "$ref": "#/components/responses/forbidden" x-github: githubCloudOnly: false enabledForGitHubApps: false category: gists subcategory: "/gists/{gist_id}/{sha}": get: summary: Get a gist revision description: '' tags: - gists operationId: gists/get-revision externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/gists#get-a-gist-revision parameters: - "$ref": "#/components/parameters/gist-id" - name: sha in: path required: true schema: type: string responses: '200': description: Response content: application/json: schema: "$ref": "#/components/schemas/gist-simple" examples: default: "$ref": "#/components/examples/gist" '422': "$ref": "#/components/responses/validation_failed" '404': "$ref": "#/components/responses/not_found" '403': "$ref": "#/components/responses/forbidden" x-github: githubCloudOnly: false enabledForGitHubApps: false category: gists subcategory: "/gitignore/templates": get: summary: Get all gitignore templates description: List all templates available to pass as an option when [creating a repository](https://docs.github.com/enterprise-server@3.0/rest/reference/repos#create-a-repository-for-the-authenticated-user). operationId: gitignore/get-all-templates tags: - gitignore externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/gitignore#get-all-gitignore-templates parameters: [] responses: '200': description: Response content: application/json: schema: type: array items: type: string example: - Actionscript - Android - AppceleratorTitanium - Autotools - Bancha - C - C++ '304': "$ref": "#/components/responses/not_modified" x-github: githubCloudOnly: false enabledForGitHubApps: true category: gitignore subcategory: "/gitignore/templates/{name}": get: summary: Get a gitignore template description: |- The API also allows fetching the source of a single template. Use the raw [media type](https://docs.github.com/enterprise-server@3.0/rest/overview/media-types/) to get the raw contents. operationId: gitignore/get-template tags: - gitignore externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/gitignore#get-a-gitignore-template parameters: - name: name in: path required: true schema: type: string responses: '200': description: Response content: application/json: schema: "$ref": "#/components/schemas/gitignore-template" examples: default: "$ref": "#/components/examples/gitignore-template" '304': "$ref": "#/components/responses/not_modified" x-github: githubCloudOnly: false enabledForGitHubApps: true category: gitignore subcategory: "/installation/repositories": get: summary: List repositories accessible to the app installation description: |- List repositories that an app installation can access. You must use an [installation access token](https://docs.github.com/enterprise-server@3.0/apps/building-github-apps/authenticating-with-github-apps/#authenticating-as-an-installation) to access this endpoint. tags: - apps operationId: apps/list-repos-accessible-to-installation externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/apps#list-repositories-accessible-to-the-app-installation parameters: - "$ref": "#/components/parameters/per-page" - "$ref": "#/components/parameters/page" responses: '200': description: Response content: application/json: schema: type: object required: - total_count - repositories properties: total_count: type: integer repositories: type: array items: "$ref": "#/components/schemas/repository" repository_selection: type: string examples: - selected examples: default: "$ref": "#/components/examples/repository-paginated-2" headers: Link: "$ref": "#/components/headers/link" '403': "$ref": "#/components/responses/forbidden" '304': "$ref": "#/components/responses/not_modified" '401': "$ref": "#/components/responses/requires_authentication" x-github: githubCloudOnly: false enabledForGitHubApps: true category: apps subcategory: installations previews: - required: false name: mercy note: |- The `topics` property for repositories on GitHub is currently available for developers to preview. To view the `topics` property in calls that return repository results, you must provide a custom [media type](https://docs.github.com/enterprise-server@3.0/rest/overview/media-types) in the `Accept` header: ```shell application/vnd.github.mercy-preview+json ``` "/installation/token": delete: summary: Revoke an installation access token description: |- Revokes the installation token you're using to authenticate as an installation and access this endpoint. Once an installation token is revoked, the token is invalidated and cannot be used. Other endpoints that require the revoked installation token must have a new installation token to work. You can create a new token using the "[Create an installation access token for an app](https://docs.github.com/enterprise-server@3.0/rest/reference/apps#create-an-installation-access-token-for-an-app)" endpoint. You must use an [installation access token](https://docs.github.com/enterprise-server@3.0/apps/building-github-apps/authenticating-with-github-apps/#authenticating-as-an-installation) to access this endpoint. tags: - apps operationId: apps/revoke-installation-access-token externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/apps#revoke-an-installation-access-token parameters: [] responses: '204': description: Response x-github: githubCloudOnly: false enabledForGitHubApps: true category: apps subcategory: installations "/issues": get: summary: List issues assigned to the authenticated user description: |- List issues assigned to the authenticated user across all visible repositories including owned repositories, member repositories, and organization repositories. You can use the `filter` query parameter to fetch issues that are not necessarily assigned to you. **Note**: GitHub's REST API v3 considers every pull request an issue, but not every issue is a pull request. For this reason, "Issues" endpoints may return both issues and pull requests in the response. You can identify pull requests by the `pull_request` key. Be aware that the `id` of a pull request returned from "Issues" endpoints will be an _issue id_. To find out the pull request id, use the "[List pull requests](https://docs.github.com/enterprise-server@3.0/rest/reference/pulls#list-pull-requests)" endpoint. tags: - issues operationId: issues/list externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/issues#list-issues-assigned-to-the-authenticated-user parameters: - name: filter description: "Indicates which sorts of issues to return. Can be one of: \n\\* `assigned`: Issues assigned to you \n\\* `created`: Issues created by you \ \n\\* `mentioned`: Issues mentioning you \n\\* `subscribed`: Issues you're subscribed to updates for \n\\* `all` or `repos`: All issues the authenticated user can see, regardless of participation or creation" in: query required: false schema: type: string enum: - assigned - created - mentioned - subscribed - repos - all default: assigned - name: state description: Indicates the state of the issues to return. Can be either `open`, `closed`, or `all`. in: query required: false schema: type: string enum: - open - closed - all default: open - "$ref": "#/components/parameters/labels" - name: sort description: What to sort results by. Can be either `created`, `updated`, `comments`. in: query required: false schema: type: string enum: - created - updated - comments default: created - "$ref": "#/components/parameters/direction" - "$ref": "#/components/parameters/since" - name: collab in: query required: false schema: type: boolean - name: orgs in: query required: false schema: type: boolean - name: owned in: query required: false schema: type: boolean - name: pulls in: query required: false schema: type: boolean - "$ref": "#/components/parameters/per-page" - "$ref": "#/components/parameters/page" responses: '200': description: Response content: application/json: schema: type: array items: "$ref": "#/components/schemas/issue" examples: default: "$ref": "#/components/examples/issue-with-repo-items" headers: Link: "$ref": "#/components/headers/link" '422': "$ref": "#/components/responses/validation_failed" '304': "$ref": "#/components/responses/not_modified" '404': "$ref": "#/components/responses/not_found" x-github: githubCloudOnly: false enabledForGitHubApps: false category: issues previews: - required: false name: machine-man note: "If an issue event is created via a GitHub App, the response will include the `performed_via_github_app` object with\tinformation about the GitHub App. For more information, see the [related blog\tpost](https://developer.github.com/changes/2016-09-14-Integrations-Early-Access).\nTo receive the `performed_via_github_app` object in the response, you must provide a custom [media type](https://docs.github.com/enterprise-server@3.0/rest/overview/media-types) in the `Accept` header:\n```shell\napplication/vnd.github.machine-man-preview\n```" - required: false name: squirrel-girl note: |- An additional `reactions` object in the issue comment payload is currently available for developers to preview. During the preview period, the APIs may change without advance notice. Please see the [blog post](https://developer.github.com/changes/2016-05-12-reactions-api-preview) for full details. To access the API you must provide a custom [media type](https://docs.github.com/enterprise-server@3.0/rest/overview/media-types) in the `Accept` header: ```shell application/vnd.github.squirrel-girl-preview ``` The `reactions` key will have the following payload where `url` can be used to construct the API location for [listing and creating](https://docs.github.com/enterprise-server@3.0/rest/reference/reactions) reactions. "/licenses": get: summary: Get all commonly used licenses description: '' tags: - licenses operationId: licenses/get-all-commonly-used externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/licenses#get-all-commonly-used-licenses parameters: - name: featured in: query required: false schema: type: boolean - "$ref": "#/components/parameters/per-page" - "$ref": "#/components/parameters/page" responses: '200': description: Response content: application/json: schema: type: array items: "$ref": "#/components/schemas/license-simple" examples: default: "$ref": "#/components/examples/license-simple-items" '304': "$ref": "#/components/responses/not_modified" x-github: githubCloudOnly: false enabledForGitHubApps: true category: licenses subcategory: "/licenses/{license}": get: summary: Get a license description: '' tags: - licenses operationId: licenses/get externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/licenses#get-a-license parameters: - name: license in: path required: true schema: type: string responses: '200': description: Response content: application/json: schema: "$ref": "#/components/schemas/license" examples: default: "$ref": "#/components/examples/license" '403': "$ref": "#/components/responses/forbidden" '404': "$ref": "#/components/responses/not_found" '304': "$ref": "#/components/responses/not_modified" x-github: githubCloudOnly: false enabledForGitHubApps: true category: licenses subcategory: "/markdown": post: summary: Render a Markdown document description: '' operationId: markdown/render tags: - markdown externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/markdown#render-a-markdown-document parameters: [] requestBody: required: true content: application/json: schema: properties: text: description: The Markdown text to render in HTML. type: string mode: description: The rendering mode. Can be either `markdown` or `gfm`. enum: - markdown - gfm default: markdown type: string examples: - markdown context: description: The repository context to use when creating references in `gfm` mode. For example, setting `context` to `octo-org/octo-repo` will change the text `#42` into an HTML link to issue 42 in the `octo-org/octo-repo` repository. type: string required: - text type: object responses: '200': description: Response headers: Content-Type: "$ref": "#/components/headers/content-type" Content-Length: example: '279' schema: type: string X-CommonMarker-Version: "$ref": "#/components/headers/x-common-marker-version" content: text/html: schema: type: string '304': "$ref": "#/components/responses/not_modified" x-github: githubCloudOnly: false enabledForGitHubApps: true category: markdown subcategory: "/markdown/raw": post: summary: Render a Markdown document in raw mode description: You must send Markdown as plain text (using a `Content-Type` header of `text/plain` or `text/x-markdown`) to this endpoint, rather than using JSON format. In raw mode, [GitHub Flavored Markdown](https://github.github.com/gfm/) is not supported and Markdown will be rendered in plain format like a README.md file. Markdown content must be 400 KB or less. operationId: markdown/render-raw tags: - markdown externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/markdown#render-a-markdown-document-in-raw-mode parameters: [] requestBody: required: false content: text/plain: schema: type: string text/x-markdown: schema: type: string responses: '200': description: Response headers: X-CommonMarker-Version: "$ref": "#/components/headers/x-common-marker-version" content: text/html: schema: type: string '304': "$ref": "#/components/responses/not_modified" x-github: githubCloudOnly: false enabledForGitHubApps: true category: markdown subcategory: "/meta": get: summary: Get GitHub Enterprise Server meta information description: '' tags: - meta operationId: meta/get externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/meta#get-github-meta-information parameters: [] responses: '200': description: Response content: application/json: schema: "$ref": "#/components/schemas/api-overview" examples: default: "$ref": "#/components/examples/api-overview" '304': "$ref": "#/components/responses/not_modified" x-github: githubCloudOnly: false enabledForGitHubApps: true category: meta subcategory: "/networks/{owner}/{repo}/events": get: summary: List public events for a network of repositories description: '' tags: - activity operationId: activity/list-public-events-for-repo-network externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/activity#list-public-events-for-a-network-of-repositories parameters: - "$ref": "#/components/parameters/owner" - "$ref": "#/components/parameters/repo" - "$ref": "#/components/parameters/per-page" - "$ref": "#/components/parameters/page" responses: '200': description: Response content: application/json: schema: type: array items: "$ref": "#/components/schemas/event" '404': "$ref": "#/components/responses/not_found" '403': "$ref": "#/components/responses/forbidden" '304': "$ref": "#/components/responses/not_modified" '301': "$ref": "#/components/responses/moved_permanently" x-github: githubCloudOnly: false enabledForGitHubApps: true category: activity subcategory: events "/notifications": get: summary: List notifications for the authenticated user description: List all notifications for the current user, sorted by most recently updated. tags: - activity operationId: activity/list-notifications-for-authenticated-user externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/activity#list-notifications-for-the-authenticated-user parameters: - "$ref": "#/components/parameters/all" - "$ref": "#/components/parameters/participating" - "$ref": "#/components/parameters/since" - "$ref": "#/components/parameters/before" - "$ref": "#/components/parameters/per-page" - "$ref": "#/components/parameters/page" responses: '200': description: Response content: application/json: schema: type: array items: "$ref": "#/components/schemas/thread" examples: default: "$ref": "#/components/examples/thread-items" headers: Link: "$ref": "#/components/headers/link" '304': "$ref": "#/components/responses/not_modified" '403': "$ref": "#/components/responses/forbidden" '401': "$ref": "#/components/responses/requires_authentication" '422': "$ref": "#/components/responses/validation_failed" x-github: githubCloudOnly: false enabledForGitHubApps: false category: activity subcategory: notifications put: summary: Mark notifications as read description: Marks all notifications as "read" removes it from the [default view on GitHub Enterprise Server](https://github.com/notifications). If the number of notifications is too large to complete in one request, you will receive a `202 Accepted` status and GitHub Enterprise Server will run an asynchronous process to mark notifications as "read." To check whether any "unread" notifications remain, you can use the [List notifications for the authenticated user](https://docs.github.com/enterprise-server@3.0/rest/reference/activity#list-notifications-for-the-authenticated-user) endpoint and pass the query parameter `all=false`. tags: - activity operationId: activity/mark-notifications-as-read externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/activity#mark-notifications-as-read parameters: [] requestBody: required: false content: application/json: schema: type: object properties: last_read_at: description: Describes the last point that notifications were checked. type: string format: date-time read: description: Whether the notification has been read. type: boolean responses: '202': description: Response content: application/json: schema: type: object properties: message: type: string '205': description: Reset Content '304': "$ref": "#/components/responses/not_modified" '403': "$ref": "#/components/responses/forbidden" '401': "$ref": "#/components/responses/requires_authentication" x-github: githubCloudOnly: false enabledForGitHubApps: false category: activity subcategory: notifications "/notifications/threads/{thread_id}": get: summary: Get a thread description: '' tags: - activity operationId: activity/get-thread externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/activity#get-a-thread parameters: - "$ref": "#/components/parameters/thread-id" responses: '200': description: Response content: application/json: schema: "$ref": "#/components/schemas/thread" examples: default: "$ref": "#/components/examples/thread" '304': "$ref": "#/components/responses/not_modified" '403': "$ref": "#/components/responses/forbidden" '401': "$ref": "#/components/responses/requires_authentication" x-github: githubCloudOnly: false enabledForGitHubApps: false category: activity subcategory: notifications patch: summary: Mark a thread as read description: '' tags: - activity operationId: activity/mark-thread-as-read externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/activity#mark-a-thread-as-read parameters: - "$ref": "#/components/parameters/thread-id" responses: '205': description: Reset Content '304': "$ref": "#/components/responses/not_modified" '403': "$ref": "#/components/responses/forbidden" x-github: githubCloudOnly: false enabledForGitHubApps: false category: activity subcategory: notifications "/notifications/threads/{thread_id}/subscription": get: summary: Get a thread subscription for the authenticated user description: |- This checks to see if the current user is subscribed to a thread. You can also [get a repository subscription](https://docs.github.com/enterprise-server@3.0/rest/reference/activity#get-a-repository-subscription). Note that subscriptions are only generated if a user is participating in a conversation--for example, they've replied to the thread, were **@mentioned**, or manually subscribe to a thread. tags: - activity operationId: activity/get-thread-subscription-for-authenticated-user externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/activity#get-a-thread-subscription-for-the-authenticated-user parameters: - "$ref": "#/components/parameters/thread-id" responses: '200': description: Response content: application/json: schema: "$ref": "#/components/schemas/thread-subscription" examples: default: "$ref": "#/components/examples/thread-subscription" '304': "$ref": "#/components/responses/not_modified" '403': "$ref": "#/components/responses/forbidden" '401': "$ref": "#/components/responses/requires_authentication" x-github: githubCloudOnly: false enabledForGitHubApps: false category: activity subcategory: notifications put: summary: Set a thread subscription description: |- If you are watching a repository, you receive notifications for all threads by default. Use this endpoint to ignore future notifications for threads until you comment on the thread or get an **@mention**. You can also use this endpoint to subscribe to threads that you are currently not receiving notifications for or to subscribed to threads that you have previously ignored. Unsubscribing from a conversation in a repository that you are not watching is functionally equivalent to the [Delete a thread subscription](https://docs.github.com/enterprise-server@3.0/rest/reference/activity#delete-a-thread-subscription) endpoint. tags: - activity operationId: activity/set-thread-subscription externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/activity#set-a-thread-subscription parameters: - "$ref": "#/components/parameters/thread-id" requestBody: required: false content: application/json: schema: properties: ignored: description: Whether to block all notifications from a thread. default: false type: boolean type: object responses: '200': description: Response content: application/json: schema: "$ref": "#/components/schemas/thread-subscription" examples: default: "$ref": "#/components/examples/thread-subscription" '304': "$ref": "#/components/responses/not_modified" '403': "$ref": "#/components/responses/forbidden" '401': "$ref": "#/components/responses/requires_authentication" x-github: githubCloudOnly: false enabledForGitHubApps: false category: activity subcategory: notifications delete: summary: Delete a thread subscription description: Mutes all future notifications for a conversation until you comment on the thread or get an **@mention**. If you are watching the repository of the thread, you will still receive notifications. To ignore future notifications for a repository you are watching, use the [Set a thread subscription](https://docs.github.com/enterprise-server@3.0/rest/reference/activity#set-a-thread-subscription) endpoint and set `ignore` to `true`. tags: - activity operationId: activity/delete-thread-subscription externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/activity#delete-a-thread-subscription parameters: - "$ref": "#/components/parameters/thread-id" responses: '204': description: Response '304': "$ref": "#/components/responses/not_modified" '403': "$ref": "#/components/responses/forbidden" '401': "$ref": "#/components/responses/requires_authentication" x-github: githubCloudOnly: false enabledForGitHubApps: false category: activity subcategory: notifications "/octocat": get: summary: Get Octocat description: Get the octocat as ASCII art tags: - meta operationId: meta/get-octocat parameters: - name: s in: query description: The words to show in Octocat's speech bubble schema: type: string required: false responses: '200': description: Response content: application/octocat-stream: schema: type: string externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/meta#get-octocat x-github: githubCloudOnly: false enabledForGitHubApps: true category: meta "/organizations": get: summary: List organizations description: |- Lists all organizations, in the order that they were created on GitHub Enterprise Server. **Note:** Pagination is powered exclusively by the `since` parameter. Use the [Link header](https://docs.github.com/enterprise-server@3.0/rest/overview/resources-in-the-rest-api#link-header) to get the URL for the next page of organizations. tags: - orgs operationId: orgs/list externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/orgs#list-organizations parameters: - "$ref": "#/components/parameters/since-org" - "$ref": "#/components/parameters/per-page" responses: '200': description: Response content: application/json: schema: type: array items: "$ref": "#/components/schemas/organization-simple" examples: default: "$ref": "#/components/examples/organization-simple-items" headers: Link: example: ; rel="next" schema: type: string '304': "$ref": "#/components/responses/not_modified" x-github: githubCloudOnly: false enabledForGitHubApps: true category: orgs subcategory: "/orgs/{org}": get: summary: Get an organization description: |- To see many of the organization response values, you need to be an authenticated organization owner with the `admin:org` scope. When the value of `two_factor_requirement_enabled` is `true`, the organization requires all members, billing managers, and outside collaborators to enable [two-factor authentication](https://docs.github.com/articles/securing-your-account-with-two-factor-authentication-2fa/). GitHub Apps with the `Organization plan` permission can use this endpoint to retrieve information about an organization's GitHub Enterprise Server plan. See "[Authenticating with GitHub Apps](https://docs.github.com/enterprise-server@3.0/apps/building-github-apps/authenticating-with-github-apps/)" for details. For an example response, see 'Response with GitHub Enterprise Server plan information' below." tags: - orgs operationId: orgs/get externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/orgs#get-an-organization parameters: - "$ref": "#/components/parameters/org" responses: '200': description: Response content: application/json: schema: "$ref": "#/components/schemas/organization-full" examples: default-response: "$ref": "#/components/examples/organization-full-default-response" '404': "$ref": "#/components/responses/not_found" x-github: githubCloudOnly: false enabledForGitHubApps: true category: orgs previews: - required: false name: surtur note: |- New repository creation permissions are available to preview. You can now use `members_can_create_public_repositories`, `members_can_create_private_repositories`, and `members_can_create_internal_repositories`. You can only allow members to create internal repositories if your organization is associated with an enterprise account using GitHub Enterprise Cloud or GitHub Enterprise Server 2.20+. These parameters provide more granular permissions to configure the type of repositories organization members can create. To access these new parameters during the preview period, you must provide a custom [media type](https://docs.github.com/enterprise-server@3.0/rest/overview/media-types) in the `Accept` header: ```shell application/vnd.github.surtur-preview+json ``` patch: summary: Update an organization description: |- **Parameter Deprecation Notice:** GitHub Enterprise Server will replace and discontinue `members_allowed_repository_creation_type` in favor of more granular permissions. The new input parameters are `members_can_create_public_repositories`, `members_can_create_private_repositories` for all organizations and `members_can_create_internal_repositories` for organizations associated with an enterprise account using GitHub Enterprise Cloud or GitHub Enterprise Server 2.20+. For more information, see the [blog post](https://developer.github.com/changes/2019-12-03-internal-visibility-changes). Enables an authenticated organization owner with the `admin:org` scope to update the organization's profile and member privileges. tags: - orgs operationId: orgs/update externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/orgs/#update-an-organization parameters: - "$ref": "#/components/parameters/org" requestBody: required: false content: application/json: schema: type: object properties: billing_email: type: string description: Billing email address. This address is not publicized. company: type: string description: The company name. email: type: string description: The publicly visible email address. twitter_username: type: string description: The Twitter username of the company. location: type: string description: The location. name: type: string description: The shorthand name of the company. description: type: string description: The description of the company. has_organization_projects: type: boolean description: Toggles whether an organization can use organization projects. has_repository_projects: type: boolean description: Toggles whether repositories that belong to the organization can use repository projects. default_repository_permission: type: string description: "Default permission level members have for organization repositories: \n\\* `read` - can pull, but not push to or administer this repository. \n\\* `write` - can pull and push, but not administer this repository. \n\\* `admin` - can pull, push, and administer this repository. \n\\* `none` - no permissions granted by default." enum: - read - write - admin - none default: read members_can_create_repositories: type: boolean description: "Toggles the ability of non-admin organization members to create repositories. Can be one of: \n\\* `true` - all organization members can create repositories. \n\\* `false` - only organization owners can create repositories. \nDefault: `true` \n**Note:** A parameter can override this parameter. See `members_allowed_repository_creation_type` in this table for details. **Note:** A parameter can override this parameter. See `members_allowed_repository_creation_type` in this table for details." default: true members_can_create_internal_repositories: type: boolean description: "Toggles whether organization members can create internal repositories, which are visible to all enterprise members. You can only allow members to create internal repositories if your organization is associated with an enterprise account using GitHub Enterprise Cloud or GitHub Enterprise Server 2.20+. Can be one of: \n\\* `true` - all organization members can create internal repositories. \n\\* `false` - only organization owners can create internal repositories. \nDefault: `true`. For more information, see \"[Restricting repository creation in your organization](https://docs.github.com/github/setting-up-and-managing-organizations-and-teams/restricting-repository-creation-in-your-organization)\" in the GitHub Help documentation." members_can_create_private_repositories: type: boolean description: "Toggles whether organization members can create private repositories, which are visible to organization members with permission. Can be one of: \n\\* `true` - all organization members can create private repositories. \n\\* `false` - only organization owners can create private repositories. \nDefault: `true`. For more information, see \"[Restricting repository creation in your organization](https://docs.github.com/github/setting-up-and-managing-organizations-and-teams/restricting-repository-creation-in-your-organization)\" in the GitHub Help documentation." members_can_create_public_repositories: type: boolean description: "Toggles whether organization members can create public repositories, which are visible to anyone. Can be one of: \n\\* `true` - all organization members can create public repositories. \ \n\\* `false` - only organization owners can create public repositories. \ \nDefault: `true`. For more information, see \"[Restricting repository creation in your organization](https://docs.github.com/github/setting-up-and-managing-organizations-and-teams/restricting-repository-creation-in-your-organization)\" in the GitHub Help documentation." members_allowed_repository_creation_type: type: string description: "Specifies which types of repositories non-admin organization members can create. Can be one of: \n\\* `all` - all organization members can create public and private repositories. \n\\* `private` - members can create private repositories. This option is only available to repositories that are part of an organization on GitHub Enterprise Cloud. \n\\* `none` - only admin members can create repositories. \n**Note:** This parameter is deprecated and will be removed in the future. Its return value ignores internal repositories. Using this parameter overrides values set in `members_can_create_repositories`. See the parameter deprecation notice in the operation description for details." enum: - all - private - none members_can_create_pages: type: boolean description: "Toggles whether organization members can create GitHub Pages sites. Can be one of: \n\\* `true` - all organization members can create GitHub Pages sites. \n\\* `false` - no organization members can create GitHub Pages sites. Existing published sites will not be impacted." default: true members_can_fork_private_repositories: type: boolean description: "Toggles whether organization members can fork private organization repositories. Can be one of: \n\\* `true` - all organization members can fork private repositories within the organization. \n\\* `false` - no organization members can fork private repositories within the organization." default: false blog: type: string examples: - '"http://github.blog"' example: billing_email: mona@github.com company: GitHub email: mona@github.com twitter_username: github location: San Francisco name: github description: GitHub, the company. default_repository_permission: read members_can_create_repositories: true members_allowed_repository_creation_type: all responses: '200': description: Response content: application/json: schema: "$ref": "#/components/schemas/organization-full" examples: default: "$ref": "#/components/examples/organization-full" '422': description: Validation failed content: application/json: schema: oneOf: - "$ref": "#/components/schemas/validation-error" - "$ref": "#/components/schemas/validation-error-simple" '409': "$ref": "#/components/responses/conflict" x-github: githubCloudOnly: false enabledForGitHubApps: true category: orgs previews: - required: false name: surtur note: |- New repository creation permissions are available to preview. You can now use `members_can_create_public_repositories`, `members_can_create_private_repositories`, and `members_can_create_internal_repositories`. You can only allow members to create internal repositories if your organization is associated with an enterprise account using GitHub Enterprise Cloud or GitHub Enterprise Server 2.20+. These parameters provide more granular permissions to configure the type of repositories organization members can create. To access these new parameters during the preview period, you must provide a custom [media type](https://docs.github.com/enterprise-server@3.0/rest/overview/media-types) in the `Accept` header: ```shell application/vnd.github.surtur-preview+json ``` "/orgs/{org}/actions/permissions": get: summary: Get GitHub Actions permissions for an organization description: |- Gets the GitHub Actions permissions policy for repositories and allowed actions in an organization. You must authenticate using an access token with the `admin:org` scope to use this endpoint. GitHub Apps must have the `administration` organization permission to use this API. operationId: actions/get-github-actions-permissions-organization tags: - actions externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/actions#get-github-actions-permissions-for-an-organization parameters: - "$ref": "#/components/parameters/org" responses: '200': description: Response content: application/json: schema: "$ref": "#/components/schemas/actions-organization-permissions" examples: default: "$ref": "#/components/examples/actions-organization-permissions" x-github: enabledForGitHubApps: true githubCloudOnly: false category: actions subcategory: permissions put: summary: Set GitHub Actions permissions for an organization description: |- Sets the GitHub Actions permissions policy for repositories and allowed actions in an organization. If the organization belongs to an enterprise that has set restrictive permissions at the enterprise level, such as `allowed_actions` to `selected` actions, then you cannot override them for the organization. You must authenticate using an access token with the `admin:org` scope to use this endpoint. GitHub Apps must have the `administration` organization permission to use this API. operationId: actions/set-github-actions-permissions-organization tags: - actions externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/actions#set-github-actions-permissions-for-an-organization parameters: - "$ref": "#/components/parameters/org" responses: '204': description: Response requestBody: required: true content: application/json: schema: type: object properties: enabled_repositories: "$ref": "#/components/schemas/enabled-repositories" allowed_actions: "$ref": "#/components/schemas/allowed-actions" required: - enabled_repositories example: enabled_repositories: all allowed_actions: selected x-github: enabledForGitHubApps: true githubCloudOnly: false category: actions subcategory: permissions "/orgs/{org}/actions/permissions/repositories": get: summary: List selected repositories enabled for GitHub Actions in an organization description: |- Lists the selected repositories that are enabled for GitHub Actions in an organization. To use this endpoint, the organization permission policy for `enabled_repositories` must be configured to `selected`. For more information, see "[Set GitHub Actions permissions for an organization](#set-github-actions-permissions-for-an-organization)." You must authenticate using an access token with the `admin:org` scope to use this endpoint. GitHub Apps must have the `administration` organization permission to use this API. operationId: actions/list-selected-repositories-enabled-github-actions-organization tags: - actions externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/actions#list-selected-repositories-enabled-for-github-actions-in-an-organization parameters: - "$ref": "#/components/parameters/org" - "$ref": "#/components/parameters/per-page" - "$ref": "#/components/parameters/page" responses: '200': description: Response content: application/json: schema: type: object required: - total_count - repositories properties: total_count: type: number repositories: type: array items: "$ref": "#/components/schemas/repository" examples: default: "$ref": "#/components/examples/repository-paginated" x-github: enabledForGitHubApps: true githubCloudOnly: false category: actions subcategory: permissions put: summary: Set selected repositories enabled for GitHub Actions in an organization description: |- Replaces the list of selected repositories that are enabled for GitHub Actions in an organization. To use this endpoint, the organization permission policy for `enabled_repositories` must be configured to `selected`. For more information, see "[Set GitHub Actions permissions for an organization](#set-github-actions-permissions-for-an-organization)." You must authenticate using an access token with the `admin:org` scope to use this endpoint. GitHub Apps must have the `administration` organization permission to use this API. operationId: actions/set-selected-repositories-enabled-github-actions-organization tags: - actions externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/actions#set-selected-repositories-enabled-for-github-actions-in-an-organization parameters: - "$ref": "#/components/parameters/org" responses: '204': description: Response requestBody: required: true content: application/json: schema: type: object properties: selected_repository_ids: description: List of repository IDs to enable for GitHub Actions. type: array items: type: integer description: Unique identifier of the repository. required: - selected_repository_ids example: selected_repository_ids: - 32 - 42 x-github: enabledForGitHubApps: true githubCloudOnly: false category: actions subcategory: permissions "/orgs/{org}/actions/permissions/repositories/{repository_id}": put: summary: Enable a selected repository for GitHub Actions in an organization description: |- Adds a repository to the list of selected repositories that are enabled for GitHub Actions in an organization. To use this endpoint, the organization permission policy for `enabled_repositories` must be must be configured to `selected`. For more information, see "[Set GitHub Actions permissions for an organization](#set-github-actions-permissions-for-an-organization)." You must authenticate using an access token with the `admin:org` scope to use this endpoint. GitHub Apps must have the `administration` organization permission to use this API. operationId: actions/enable-selected-repository-github-actions-organization tags: - actions externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/actions#enable-a-selected-repository-for-github-actions-in-an-organization parameters: - "$ref": "#/components/parameters/org" - "$ref": "#/components/parameters/repository-id" responses: '204': description: Response x-github: enabledForGitHubApps: true githubCloudOnly: false category: actions subcategory: permissions delete: summary: Disable a selected repository for GitHub Actions in an organization description: |- Removes a repository from the list of selected repositories that are enabled for GitHub Actions in an organization. To use this endpoint, the organization permission policy for `enabled_repositories` must be configured to `selected`. For more information, see "[Set GitHub Actions permissions for an organization](#set-github-actions-permissions-for-an-organization)." You must authenticate using an access token with the `admin:org` scope to use this endpoint. GitHub Apps must have the `administration` organization permission to use this API. operationId: actions/disable-selected-repository-github-actions-organization tags: - actions externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/actions#disable-a-selected-repository-for-github-actions-in-an-organization parameters: - "$ref": "#/components/parameters/org" - "$ref": "#/components/parameters/repository-id" responses: '204': description: Response x-github: enabledForGitHubApps: true githubCloudOnly: false category: actions subcategory: permissions "/orgs/{org}/actions/permissions/selected-actions": get: summary: Get allowed actions for an organization description: |- Gets the selected actions that are allowed in an organization. To use this endpoint, the organization permission policy for `allowed_actions` must be configured to `selected`. For more information, see "[Set GitHub Actions permissions for an organization](#set-github-actions-permissions-for-an-organization)."" You must authenticate using an access token with the `admin:org` scope to use this endpoint. GitHub Apps must have the `administration` organization permission to use this API. operationId: actions/get-allowed-actions-organization tags: - actions externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/actions#get-allowed-actions-for-an-organization parameters: - "$ref": "#/components/parameters/org" responses: '200': description: Response content: application/json: schema: "$ref": "#/components/schemas/selected-actions" examples: default: "$ref": "#/components/examples/selected-actions" x-github: enabledForGitHubApps: true githubCloudOnly: false category: actions subcategory: permissions put: summary: Set allowed actions for an organization description: |- Sets the actions that are allowed in an organization. To use this endpoint, the organization permission policy for `allowed_actions` must be configured to `selected`. For more information, see "[Set GitHub Actions permissions for an organization](#set-github-actions-permissions-for-an-organization)." If the organization belongs to an enterprise that has `selected` actions set at the enterprise level, then you cannot override any of the enterprise's allowed actions settings. To use the `patterns_allowed` setting for private repositories, the organization must belong to an enterprise. If the organization does not belong to an enterprise, then the `patterns_allowed` setting only applies to public repositories in the organization. You must authenticate using an access token with the `admin:org` scope to use this endpoint. GitHub Apps must have the `administration` organization permission to use this API. operationId: actions/set-allowed-actions-organization tags: - actions externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/actions#set-allowed-actions-for-an-organization parameters: - "$ref": "#/components/parameters/org" responses: '204': description: Response requestBody: required: false content: application/json: schema: "$ref": "#/components/schemas/selected-actions" examples: selected_actions: "$ref": "#/components/examples/selected-actions" x-github: enabledForGitHubApps: true githubCloudOnly: false category: actions subcategory: permissions "/orgs/{org}/actions/runner-groups": get: summary: List self-hosted runner groups for an organization description: |- Lists all self-hosted runner groups configured in an organization and inherited from an enterprise. You must authenticate using an access token with the `admin:org` scope to use this endpoint. operationId: actions/list-self-hosted-runner-groups-for-org tags: - actions externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/actions#list-self-hosted-runner-groups-for-an-organization parameters: - "$ref": "#/components/parameters/org" - "$ref": "#/components/parameters/per-page" - "$ref": "#/components/parameters/page" responses: '200': description: Response content: application/json: schema: type: object required: - total_count - runner_groups properties: total_count: type: number runner_groups: type: array items: "$ref": "#/components/schemas/runner-groups-org" examples: default: "$ref": "#/components/examples/runner-groups-org" x-github: enabledForGitHubApps: true githubCloudOnly: false category: actions subcategory: self-hosted-runner-groups post: summary: Create a self-hosted runner group for an organization description: |- The self-hosted runner groups REST API is available with GitHub Enterprise Cloud and GitHub Enterprise Server. For more information, see "[GitHub's products](https://docs.github.com/github/getting-started-with-github/githubs-products)." Creates a new self-hosted runner group for an organization. You must authenticate using an access token with the `admin:org` scope to use this endpoint. operationId: actions/create-self-hosted-runner-group-for-org tags: - actions externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/actions#create-a-self-hosted-runner-group-for-an-organization parameters: - "$ref": "#/components/parameters/org" requestBody: required: true content: application/json: schema: type: object properties: name: description: Name of the runner group. type: string visibility: description: 'Visibility of a runner group. You can select all repositories, select individual repositories, or limit access to private repositories. Can be one of: `all`, `selected`, or `private`.' type: string enum: - selected - all - private default: all selected_repository_ids: description: List of repository IDs that can access the runner group. type: array items: type: integer description: Unique identifier of the repository. runners: description: List of runner IDs to add to the runner group. type: array items: type: integer description: Unique identifier of the runner. allows_public_repositories: description: Whether the runner group can be used by `public` repositories. type: boolean default: false required: - name example: name: Expensive hardware runners visibility: selected selected_repository_ids: - 32 - 91 runners: - 9 - 2 responses: '201': description: Response content: application/json: schema: "$ref": "#/components/schemas/runner-groups-org" examples: default: "$ref": "#/components/examples/runner-group" x-github: enabledForGitHubApps: true githubCloudOnly: false category: actions subcategory: self-hosted-runner-groups "/orgs/{org}/actions/runner-groups/{runner_group_id}": get: summary: Get a self-hosted runner group for an organization description: |- Gets a specific self-hosted runner group for an organization. You must authenticate using an access token with the `admin:org` scope to use this endpoint. operationId: actions/get-self-hosted-runner-group-for-org tags: - actions externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/actions#get-a-self-hosted-runner-group-for-an-organization parameters: - "$ref": "#/components/parameters/org" - "$ref": "#/components/parameters/runner-group-id" responses: '200': description: Response content: application/json: schema: "$ref": "#/components/schemas/runner-groups-org" examples: default: "$ref": "#/components/examples/runner-group-item" x-github: enabledForGitHubApps: true githubCloudOnly: false category: actions subcategory: self-hosted-runner-groups patch: summary: Update a self-hosted runner group for an organization description: |- Updates the `name` and `visibility` of a self-hosted runner group in an organization. You must authenticate using an access token with the `admin:org` scope to use this endpoint. operationId: actions/update-self-hosted-runner-group-for-org tags: - actions externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/actions#update-a-self-hosted-runner-group-for-an-organization parameters: - "$ref": "#/components/parameters/org" - "$ref": "#/components/parameters/runner-group-id" requestBody: required: true content: application/json: schema: type: object properties: name: description: Name of the runner group. type: string visibility: description: 'Visibility of a runner group. You can select all repositories, select individual repositories, or all private repositories. Can be one of: `all`, `selected`, or `private`.' type: string enum: - selected - all - private allows_public_repositories: description: Whether the runner group can be used by `public` repositories. type: boolean default: false required: - name example: name: Expensive hardware runners visibility: selected responses: '200': description: Response content: application/json: schema: "$ref": "#/components/schemas/runner-groups-org" examples: default: "$ref": "#/components/examples/runner-group" x-github: enabledForGitHubApps: true githubCloudOnly: false category: actions subcategory: self-hosted-runner-groups delete: summary: Delete a self-hosted runner group from an organization description: |- Deletes a self-hosted runner group for an organization. You must authenticate using an access token with the `admin:org` scope to use this endpoint. operationId: actions/delete-self-hosted-runner-group-from-org tags: - actions externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/actions#delete-a-self-hosted-runner-group-from-an-organization parameters: - "$ref": "#/components/parameters/org" - "$ref": "#/components/parameters/runner-group-id" responses: '204': description: Response x-github: enabledForGitHubApps: true githubCloudOnly: false category: actions subcategory: self-hosted-runner-groups "/orgs/{org}/actions/runner-groups/{runner_group_id}/repositories": get: summary: List repository access to a self-hosted runner group in an organization description: |- The self-hosted runner groups REST API is available with GitHub Enterprise Cloud and GitHub Enterprise Server. For more information, see "[GitHub's products](https://docs.github.com/github/getting-started-with-github/githubs-products)." Lists the repositories with access to a self-hosted runner group configured in an organization. You must authenticate using an access token with the `admin:org` scope to use this endpoint. operationId: actions/list-repo-access-to-self-hosted-runner-group-in-org tags: - actions externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/actions#list-repository-access-to-a-self-hosted-runner-group-in-an-organization parameters: - "$ref": "#/components/parameters/org" - "$ref": "#/components/parameters/runner-group-id" - "$ref": "#/components/parameters/page" - "$ref": "#/components/parameters/per-page" responses: '200': description: Response content: application/json: schema: type: object required: - total_count - repositories properties: total_count: type: number repositories: type: array items: "$ref": "#/components/schemas/minimal-repository" examples: default: "$ref": "#/components/examples/minimal-repository-paginated" x-github: enabledForGitHubApps: true githubCloudOnly: false category: actions subcategory: self-hosted-runner-groups put: summary: Set repository access for a self-hosted runner group in an organization description: |- Replaces the list of repositories that have access to a self-hosted runner group configured in an organization. You must authenticate using an access token with the `admin:org` scope to use this endpoint. operationId: actions/set-repo-access-to-self-hosted-runner-group-in-org tags: - actions externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/actions#set-repository-access-to-a-self-hosted-runner-group-in-an-organization parameters: - "$ref": "#/components/parameters/org" - "$ref": "#/components/parameters/runner-group-id" requestBody: required: true content: application/json: schema: type: object properties: selected_repository_ids: description: List of repository IDs that can access the runner group. type: array items: type: integer description: Unique identifier of the repository. required: - selected_repository_ids example: selected_repository_ids: - 32 - 91 responses: '204': description: Response x-github: enabledForGitHubApps: true githubCloudOnly: false category: actions subcategory: self-hosted-runner-groups "/orgs/{org}/actions/runner-groups/{runner_group_id}/repositories/{repository_id}": put: summary: Add repository access to a self-hosted runner group in an organization description: |- Adds a repository to the list of selected repositories that can access a self-hosted runner group. The runner group must have `visibility` set to `selected`. For more information, see "[Create a self-hosted runner group for an organization](#create-a-self-hosted-runner-group-for-an-organization)." You must authenticate using an access token with the `admin:org` scope to use this endpoint. operationId: actions/add-repo-access-to-self-hosted-runner-group-in-org tags: - actions externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/actions#add-repository-acess-to-a-self-hosted-runner-group-in-an-organization parameters: - "$ref": "#/components/parameters/org" - "$ref": "#/components/parameters/runner-group-id" - "$ref": "#/components/parameters/repository-id" responses: '204': description: Response x-github: enabledForGitHubApps: true githubCloudOnly: true category: actions subcategory: self-hosted-runner-groups delete: summary: Remove repository access to a self-hosted runner group in an organization description: |- Removes a repository from the list of selected repositories that can access a self-hosted runner group. The runner group must have `visibility` set to `selected`. For more information, see "[Create a self-hosted runner group for an organization](#create-a-self-hosted-runner-group-for-an-organization)." You must authenticate using an access token with the `admin:org` scope to use this endpoint. operationId: actions/remove-repo-access-to-self-hosted-runner-group-in-org tags: - actions externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/actions#remove-repository-access-to-a-self-hosted-runner-group-in-an-organization parameters: - "$ref": "#/components/parameters/org" - "$ref": "#/components/parameters/runner-group-id" - "$ref": "#/components/parameters/repository-id" responses: '204': description: Response x-github: enabledForGitHubApps: true githubCloudOnly: false category: actions subcategory: self-hosted-runner-groups "/orgs/{org}/actions/runner-groups/{runner_group_id}/runners": get: summary: List self-hosted runners in a group for an organization description: |- Lists self-hosted runners that are in a specific organization group. You must authenticate using an access token with the `admin:org` scope to use this endpoint. operationId: actions/list-self-hosted-runners-in-group-for-org tags: - actions externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/actions#list-self-hosted-runners-in-a-group-for-an-organization parameters: - "$ref": "#/components/parameters/org" - "$ref": "#/components/parameters/runner-group-id" - "$ref": "#/components/parameters/per-page" - "$ref": "#/components/parameters/page" responses: '200': description: Response content: application/json: schema: type: object required: - total_count - runners properties: total_count: type: number runners: type: array items: "$ref": "#/components/schemas/runner" examples: default: "$ref": "#/components/examples/runner-paginated" headers: Link: "$ref": "#/components/headers/link" x-github: enabledForGitHubApps: true githubCloudOnly: false category: actions subcategory: self-hosted-runner-groups put: summary: Set self-hosted runners in a group for an organization description: |- Replaces the list of self-hosted runners that are part of an organization runner group. You must authenticate using an access token with the `admin:org` scope to use this endpoint. operationId: actions/set-self-hosted-runners-in-group-for-org tags: - actions externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/actions#set-self-hosted-runners-in-a-group-for-an-organization parameters: - "$ref": "#/components/parameters/org" - "$ref": "#/components/parameters/runner-group-id" requestBody: required: true content: application/json: schema: type: object properties: runners: description: List of runner IDs to add to the runner group. type: array items: type: integer description: Unique identifier of the runner. required: - runners example: runners: - 9 - 2 responses: '204': description: Response x-github: enabledForGitHubApps: true githubCloudOnly: false category: actions subcategory: self-hosted-runner-groups "/orgs/{org}/actions/runner-groups/{runner_group_id}/runners/{runner_id}": put: summary: Add a self-hosted runner to a group for an organization description: |- Adds a self-hosted runner to a runner group configured in an organization. You must authenticate using an access token with the `admin:org` scope to use this endpoint. operationId: actions/add-self-hosted-runner-to-group-for-org tags: - actions externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/actions#add-a-self-hosted-runner-to-a-group-for-an-organization parameters: - "$ref": "#/components/parameters/org" - "$ref": "#/components/parameters/runner-group-id" - "$ref": "#/components/parameters/runner-id" responses: '204': description: Response x-github: enabledForGitHubApps: true githubCloudOnly: false category: actions subcategory: self-hosted-runner-groups delete: summary: Remove a self-hosted runner from a group for an organization description: |- Removes a self-hosted runner from a group configured in an organization. The runner is then returned to the default group. You must authenticate using an access token with the `admin:org` scope to use this endpoint. operationId: actions/remove-self-hosted-runner-from-group-for-org tags: - actions externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/actions#remove-a-self-hosted-runner-from-a-group-for-an-organization parameters: - "$ref": "#/components/parameters/org" - "$ref": "#/components/parameters/runner-group-id" - "$ref": "#/components/parameters/runner-id" responses: '204': description: Response x-github: enabledForGitHubApps: true githubCloudOnly: false category: actions subcategory: self-hosted-runner-groups "/orgs/{org}/actions/runners": get: summary: List self-hosted runners for an organization description: |- Lists all self-hosted runners configured in an organization. You must authenticate using an access token with the `admin:org` scope to use this endpoint. tags: - actions operationId: actions/list-self-hosted-runners-for-org externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/actions#list-self-hosted-runners-for-an-organization parameters: - "$ref": "#/components/parameters/org" - "$ref": "#/components/parameters/per-page" - "$ref": "#/components/parameters/page" responses: '200': description: Response content: application/json: schema: type: object required: - total_count - runners properties: total_count: type: integer runners: type: array items: "$ref": "#/components/schemas/runner" examples: default: "$ref": "#/components/examples/runner-paginated" headers: Link: "$ref": "#/components/headers/link" x-github: githubCloudOnly: false enabledForGitHubApps: true category: actions subcategory: self-hosted-runners "/orgs/{org}/actions/runners/downloads": get: summary: List runner applications for an organization description: |- Lists binaries for the runner application that you can download and run. You must authenticate using an access token with the `admin:org` scope to use this endpoint. tags: - actions operationId: actions/list-runner-applications-for-org externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/actions#list-runner-applications-for-an-organization parameters: - "$ref": "#/components/parameters/org" responses: '200': description: Response content: application/json: schema: type: array items: "$ref": "#/components/schemas/runner-application" examples: default: "$ref": "#/components/examples/runner-application-items" x-github: githubCloudOnly: false enabledForGitHubApps: true category: actions subcategory: self-hosted-runners "/orgs/{org}/actions/runners/registration-token": post: summary: Create a registration token for an organization description: |- Returns a token that you can pass to the `config` script. The token expires after one hour. You must authenticate using an access token with the `admin:org` scope to use this endpoint. #### Example using registration token Configure your self-hosted runner, replacing `TOKEN` with the registration token provided by this endpoint. ``` ./config.sh --url https://github.com/octo-org --token TOKEN ``` tags: - actions operationId: actions/create-registration-token-for-org externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/actions#create-a-registration-token-for-an-organization parameters: - "$ref": "#/components/parameters/org" responses: '201': description: Response content: application/json: schema: "$ref": "#/components/schemas/authentication-token" examples: default: "$ref": "#/components/examples/authentication-token" x-github: githubCloudOnly: false enabledForGitHubApps: true category: actions subcategory: self-hosted-runners "/orgs/{org}/actions/runners/remove-token": post: summary: Create a remove token for an organization description: |- Returns a token that you can pass to the `config` script to remove a self-hosted runner from an organization. The token expires after one hour. You must authenticate using an access token with the `admin:org` scope to use this endpoint. #### Example using remove token To remove your self-hosted runner from an organization, replace `TOKEN` with the remove token provided by this endpoint. ``` ./config.sh remove --token TOKEN ``` tags: - actions operationId: actions/create-remove-token-for-org externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/actions#create-a-remove-token-for-an-organization parameters: - "$ref": "#/components/parameters/org" responses: '201': description: Response content: application/json: schema: "$ref": "#/components/schemas/authentication-token" examples: default: "$ref": "#/components/examples/authentication-token-2" x-github: githubCloudOnly: false enabledForGitHubApps: true category: actions subcategory: self-hosted-runners "/orgs/{org}/actions/runners/{runner_id}": get: summary: Get a self-hosted runner for an organization description: |- Gets a specific self-hosted runner configured in an organization. You must authenticate using an access token with the `admin:org` scope to use this endpoint. tags: - actions operationId: actions/get-self-hosted-runner-for-org externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/actions#get-a-self-hosted-runner-for-an-organization parameters: - "$ref": "#/components/parameters/org" - "$ref": "#/components/parameters/runner-id" responses: '200': description: Response content: application/json: schema: "$ref": "#/components/schemas/runner" examples: default: "$ref": "#/components/examples/runner" x-github: githubCloudOnly: false enabledForGitHubApps: true category: actions subcategory: self-hosted-runners delete: summary: Delete a self-hosted runner from an organization description: |- Forces the removal of a self-hosted runner from an organization. You can use this endpoint to completely remove the runner when the machine you were using no longer exists. You must authenticate using an access token with the `admin:org` scope to use this endpoint. tags: - actions operationId: actions/delete-self-hosted-runner-from-org externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/actions#delete-a-self-hosted-runner-from-an-organization parameters: - "$ref": "#/components/parameters/org" - "$ref": "#/components/parameters/runner-id" responses: '204': description: Response x-github: githubCloudOnly: false enabledForGitHubApps: true category: actions subcategory: self-hosted-runners "/orgs/{org}/actions/secrets": get: summary: List organization secrets description: Lists all secrets available in an organization without revealing their encrypted values. You must authenticate using an access token with the `admin:org` scope to use this endpoint. GitHub Apps must have the `secrets` organization permission to use this endpoint. tags: - actions operationId: actions/list-org-secrets externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/actions#list-organization-secrets parameters: - "$ref": "#/components/parameters/org" - "$ref": "#/components/parameters/per-page" - "$ref": "#/components/parameters/page" responses: '200': description: Response content: application/json: schema: type: object required: - total_count - secrets properties: total_count: type: integer secrets: type: array items: "$ref": "#/components/schemas/organization-actions-secret" examples: default: "$ref": "#/components/examples/organization-actions-secret-paginated" headers: Link: "$ref": "#/components/headers/link" x-github: githubCloudOnly: false enabledForGitHubApps: true category: actions subcategory: secrets "/orgs/{org}/actions/secrets/public-key": get: summary: Get an organization public key description: Gets your public key, which you need to encrypt secrets. You need to encrypt a secret before you can create or update secrets. You must authenticate using an access token with the `admin:org` scope to use this endpoint. GitHub Apps must have the `secrets` organization permission to use this endpoint. tags: - actions operationId: actions/get-org-public-key externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/actions#get-an-organization-public-key parameters: - "$ref": "#/components/parameters/org" responses: '200': description: Response content: application/json: schema: "$ref": "#/components/schemas/actions-public-key" examples: default: "$ref": "#/components/examples/actions-public-key" x-github: githubCloudOnly: false enabledForGitHubApps: true category: actions subcategory: secrets "/orgs/{org}/actions/secrets/{secret_name}": get: summary: Get an organization secret description: Gets a single organization secret without revealing its encrypted value. You must authenticate using an access token with the `admin:org` scope to use this endpoint. GitHub Apps must have the `secrets` organization permission to use this endpoint. tags: - actions operationId: actions/get-org-secret externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/actions#get-an-organization-secret parameters: - "$ref": "#/components/parameters/org" - "$ref": "#/components/parameters/secret-name" responses: '200': description: Response content: application/json: schema: "$ref": "#/components/schemas/organization-actions-secret" examples: default: "$ref": "#/components/examples/organization-actions-secret" x-github: githubCloudOnly: false enabledForGitHubApps: true category: actions subcategory: secrets put: summary: Create or update an organization secret description: |- Creates or updates an organization secret with an encrypted value. Encrypt your secret using [LibSodium](https://libsodium.gitbook.io/doc/bindings_for_other_languages). You must authenticate using an access token with the `admin:org` scope to use this endpoint. GitHub Apps must have the `secrets` organization permission to use this endpoint. #### Example encrypting a secret using Node.js Encrypt your secret using the [tweetsodium](https://github.com/github/tweetsodium) library. ``` const sodium = require('tweetsodium'); const key = "base64-encoded-public-key"; const value = "plain-text-secret"; // Convert the message and key to Uint8Array's (Buffer implements that interface) const messageBytes = Buffer.from(value); const keyBytes = Buffer.from(key, 'base64'); // Encrypt using LibSodium. const encryptedBytes = sodium.seal(messageBytes, keyBytes); // Base64 the encrypted secret const encrypted = Buffer.from(encryptedBytes).toString('base64'); console.log(encrypted); ``` #### Example encrypting a secret using Python Encrypt your secret using [pynacl](https://pynacl.readthedocs.io/en/latest/public/#nacl-public-sealedbox) with Python 3. ``` from base64 import b64encode from nacl import encoding, public def encrypt(public_key: str, secret_value: str) -> str: """Encrypt a Unicode string using the public key.""" public_key = public.PublicKey(public_key.encode("utf-8"), encoding.Base64Encoder()) sealed_box = public.SealedBox(public_key) encrypted = sealed_box.encrypt(secret_value.encode("utf-8")) return b64encode(encrypted).decode("utf-8") ``` #### Example encrypting a secret using C# Encrypt your secret using the [Sodium.Core](https://www.nuget.org/packages/Sodium.Core/) package. ``` var secretValue = System.Text.Encoding.UTF8.GetBytes("mySecret"); var publicKey = Convert.FromBase64String("2Sg8iYjAxxmI2LvUXpJjkYrMxURPc8r+dB7TJyvvcCU="); var sealedPublicKeyBox = Sodium.SealedPublicKeyBox.Create(secretValue, publicKey); Console.WriteLine(Convert.ToBase64String(sealedPublicKeyBox)); ``` #### Example encrypting a secret using Ruby Encrypt your secret using the [rbnacl](https://github.com/RubyCrypto/rbnacl) gem. ```ruby require "rbnacl" require "base64" key = Base64.decode64("+ZYvJDZMHUfBkJdyq5Zm9SKqeuBQ4sj+6sfjlH4CgG0=") public_key = RbNaCl::PublicKey.new(key) box = RbNaCl::Boxes::Sealed.from_public_key(public_key) encrypted_secret = box.encrypt("my_secret") # Print the base64 encoded secret puts Base64.strict_encode64(encrypted_secret) ``` tags: - actions operationId: actions/create-or-update-org-secret externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/actions#create-or-update-an-organization-secret parameters: - "$ref": "#/components/parameters/org" - "$ref": "#/components/parameters/secret-name" requestBody: required: true content: application/json: schema: type: object properties: encrypted_value: type: string description: Value for your secret, encrypted with [LibSodium](https://libsodium.gitbook.io/doc/bindings_for_other_languages) using the public key retrieved from the [Get an organization public key](https://docs.github.com/enterprise-server@3.0/rest/reference/actions#get-an-organization-public-key) endpoint. pattern: "^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=|[A-Za-z0-9+/]{4})$" key_id: type: string description: ID of the key you used to encrypt the secret. visibility: type: string description: "Configures the access that repositories have to the organization secret. Can be one of: \n\\- `all` - All repositories in an organization can access the secret. \n\\- `private` - Private repositories in an organization can access the secret. \n\\- `selected` - Only specific repositories can access the secret." enum: - all - private - selected selected_repository_ids: type: array description: An array of repository ids that can access the organization secret. You can only provide a list of repository ids when the `visibility` is set to `selected`. You can manage the list of selected repositories using the [List selected repositories for an organization secret](https://docs.github.com/enterprise-server@3.0/rest/reference/actions#list-selected-repositories-for-an-organization-secret), [Set selected repositories for an organization secret](https://docs.github.com/enterprise-server@3.0/rest/reference/actions#set-selected-repositories-for-an-organization-secret), and [Remove selected repository from an organization secret](https://docs.github.com/enterprise-server@3.0/rest/reference/actions#remove-selected-repository-from-an-organization-secret) endpoints. items: type: string required: - visibility example: encrypted_value: c2VjcmV0 key_id: '012345678912345678' visibility: selected selected_repository_ids: - '1296269' - '1296280' responses: '201': description: Response when creating a secret content: application/json: schema: "$ref": "#/components/schemas/empty-object" '204': description: Response when updating a secret x-github: githubCloudOnly: false enabledForGitHubApps: true category: actions subcategory: secrets delete: summary: Delete an organization secret description: Deletes a secret in an organization using the secret name. You must authenticate using an access token with the `admin:org` scope to use this endpoint. GitHub Apps must have the `secrets` organization permission to use this endpoint. tags: - actions operationId: actions/delete-org-secret externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/actions#delete-an-organization-secret parameters: - "$ref": "#/components/parameters/org" - "$ref": "#/components/parameters/secret-name" responses: '204': description: Response x-github: githubCloudOnly: false enabledForGitHubApps: true category: actions subcategory: secrets "/orgs/{org}/actions/secrets/{secret_name}/repositories": get: summary: List selected repositories for an organization secret description: Lists all repositories that have been selected when the `visibility` for repository access to a secret is set to `selected`. You must authenticate using an access token with the `admin:org` scope to use this endpoint. GitHub Apps must have the `secrets` organization permission to use this endpoint. tags: - actions operationId: actions/list-selected-repos-for-org-secret externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/actions#list-selected-repositories-for-an-organization-secret parameters: - "$ref": "#/components/parameters/org" - "$ref": "#/components/parameters/secret-name" - "$ref": "#/components/parameters/page" - "$ref": "#/components/parameters/per-page" responses: '200': description: Response content: application/json: schema: type: object required: - total_count - repositories properties: total_count: type: integer repositories: type: array items: "$ref": "#/components/schemas/minimal-repository" examples: default: "$ref": "#/components/examples/public-repository-paginated" x-github: githubCloudOnly: false enabledForGitHubApps: true category: actions subcategory: secrets put: summary: Set selected repositories for an organization secret description: Replaces all repositories for an organization secret when the `visibility` for repository access is set to `selected`. The visibility is set when you [Create or update an organization secret](https://docs.github.com/enterprise-server@3.0/rest/reference/actions#create-or-update-an-organization-secret). You must authenticate using an access token with the `admin:org` scope to use this endpoint. GitHub Apps must have the `secrets` organization permission to use this endpoint. tags: - actions operationId: actions/set-selected-repos-for-org-secret externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/actions#set-selected-repositories-for-an-organization-secret parameters: - "$ref": "#/components/parameters/org" - "$ref": "#/components/parameters/secret-name" requestBody: required: true content: application/json: schema: type: object properties: selected_repository_ids: type: array description: An array of repository ids that can access the organization secret. You can only provide a list of repository ids when the `visibility` is set to `selected`. You can add and remove individual repositories using the [Set selected repositories for an organization secret](https://docs.github.com/enterprise-server@3.0/rest/reference/actions#set-selected-repositories-for-an-organization-secret) and [Remove selected repository from an organization secret](https://docs.github.com/enterprise-server@3.0/rest/reference/actions#remove-selected-repository-from-an-organization-secret) endpoints. items: type: integer required: - selected_repository_ids example: selected_repository_ids: - 64780797 responses: '204': description: Response x-github: githubCloudOnly: false enabledForGitHubApps: true category: actions subcategory: secrets "/orgs/{org}/actions/secrets/{secret_name}/repositories/{repository_id}": put: summary: Add selected repository to an organization secret description: Adds a repository to an organization secret when the `visibility` for repository access is set to `selected`. The visibility is set when you [Create or update an organization secret](https://docs.github.com/enterprise-server@3.0/rest/reference/actions#create-or-update-an-organization-secret). You must authenticate using an access token with the `admin:org` scope to use this endpoint. GitHub Apps must have the `secrets` organization permission to use this endpoint. tags: - actions operationId: actions/add-selected-repo-to-org-secret externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/actions#add-selected-repository-to-an-organization-secret parameters: - "$ref": "#/components/parameters/org" - "$ref": "#/components/parameters/secret-name" - name: repository_id in: path required: true schema: type: integer responses: '204': description: No Content when repository was added to the selected list '409': description: Conflict when visibility type is not set to selected x-github: githubCloudOnly: false enabledForGitHubApps: true category: actions subcategory: secrets delete: summary: Remove selected repository from an organization secret description: Removes a repository from an organization secret when the `visibility` for repository access is set to `selected`. The visibility is set when you [Create or update an organization secret](https://docs.github.com/enterprise-server@3.0/rest/reference/actions#create-or-update-an-organization-secret). You must authenticate using an access token with the `admin:org` scope to use this endpoint. GitHub Apps must have the `secrets` organization permission to use this endpoint. tags: - actions operationId: actions/remove-selected-repo-from-org-secret externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/actions#remove-selected-repository-from-an-organization-secret parameters: - "$ref": "#/components/parameters/org" - "$ref": "#/components/parameters/secret-name" - name: repository_id in: path required: true schema: type: integer responses: '204': description: Response when repository was removed from the selected list '409': description: Conflict when visibility type not set to selected x-github: githubCloudOnly: false enabledForGitHubApps: true category: actions subcategory: secrets "/orgs/{org}/events": get: summary: List public organization events description: '' tags: - activity operationId: activity/list-public-org-events externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/activity#list-public-organization-events parameters: - "$ref": "#/components/parameters/org" - "$ref": "#/components/parameters/per-page" - "$ref": "#/components/parameters/page" responses: '200': description: Response content: application/json: schema: type: array items: "$ref": "#/components/schemas/event" x-github: githubCloudOnly: false enabledForGitHubApps: true category: activity subcategory: events "/orgs/{org}/hooks": get: summary: List organization webhooks description: '' tags: - orgs operationId: orgs/list-webhooks externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/orgs#list-organization-webhooks parameters: - "$ref": "#/components/parameters/org" - "$ref": "#/components/parameters/per-page" - "$ref": "#/components/parameters/page" responses: '200': description: Response content: application/json: schema: type: array items: "$ref": "#/components/schemas/org-hook" examples: default: "$ref": "#/components/examples/org-hook-items" headers: Link: "$ref": "#/components/headers/link" '404': "$ref": "#/components/responses/not_found" x-github: githubCloudOnly: false enabledForGitHubApps: true category: orgs subcategory: webhooks post: summary: Create an organization webhook description: 'Here''s how you can create a hook that posts payloads in JSON format:' tags: - orgs operationId: orgs/create-webhook externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/orgs#create-an-organization-webhook parameters: - "$ref": "#/components/parameters/org" requestBody: required: true content: application/json: schema: type: object properties: name: type: string description: Must be passed as "web". config: type: object description: Key/value pairs to provide settings for this webhook. [These are defined below](https://docs.github.com/enterprise-server@3.0/rest/reference/orgs#create-hook-config-params). properties: url: "$ref": "#/components/schemas/webhook-config-url" content_type: "$ref": "#/components/schemas/webhook-config-content-type" secret: "$ref": "#/components/schemas/webhook-config-secret" insecure_ssl: "$ref": "#/components/schemas/webhook-config-insecure-ssl" username: type: string examples: - '"kdaigle"' password: type: string examples: - '"password"' required: - url events: type: array description: Determines what [events](https://docs.github.com/enterprise-server@3.0/webhooks/event-payloads) the hook is triggered for. default: - push items: type: string active: type: boolean description: Determines if notifications are sent when the webhook is triggered. Set to `true` to send notifications. default: true required: - name - config example: name: web active: true events: - push - pull_request config: url: http://example.com/webhook content_type: json responses: '201': description: Response content: application/json: schema: "$ref": "#/components/schemas/org-hook" examples: default: "$ref": "#/components/examples/org-hook" headers: Location: example: https://api.github.com/orgs/octocat/hooks/1 schema: type: string '422': "$ref": "#/components/responses/validation_failed" '404': "$ref": "#/components/responses/not_found" x-github: githubCloudOnly: false enabledForGitHubApps: true category: orgs subcategory: webhooks "/orgs/{org}/hooks/{hook_id}": get: summary: Get an organization webhook description: Returns a webhook configured in an organization. To get only the webhook `config` properties, see "[Get a webhook configuration for an organization](/rest/reference/orgs#get-a-webhook-configuration-for-an-organization)." tags: - orgs operationId: orgs/get-webhook externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/orgs#get-an-organization-webhook parameters: - "$ref": "#/components/parameters/org" - "$ref": "#/components/parameters/hook-id" responses: '200': description: Response content: application/json: schema: "$ref": "#/components/schemas/org-hook" examples: default: "$ref": "#/components/examples/org-hook" '404': "$ref": "#/components/responses/not_found" x-github: githubCloudOnly: false enabledForGitHubApps: true category: orgs subcategory: webhooks patch: summary: Update an organization webhook description: Updates a webhook configured in an organization. When you update a webhook, the `secret` will be overwritten. If you previously had a `secret` set, you must provide the same `secret` or set a new `secret` or the secret will be removed. If you are only updating individual webhook `config` properties, use "[Update a webhook configuration for an organization](/rest/reference/orgs#update-a-webhook-configuration-for-an-organization)." tags: - orgs operationId: orgs/update-webhook externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/orgs#update-an-organization-webhook parameters: - "$ref": "#/components/parameters/org" - "$ref": "#/components/parameters/hook-id" requestBody: required: false content: application/json: schema: type: object properties: config: type: object description: Key/value pairs to provide settings for this webhook. [These are defined below](https://docs.github.com/enterprise-server@3.0/rest/reference/orgs#update-hook-config-params). properties: url: "$ref": "#/components/schemas/webhook-config-url" content_type: "$ref": "#/components/schemas/webhook-config-content-type" secret: "$ref": "#/components/schemas/webhook-config-secret" insecure_ssl: "$ref": "#/components/schemas/webhook-config-insecure-ssl" required: - url events: type: array description: Determines what [events](https://docs.github.com/enterprise-server@3.0/webhooks/event-payloads) the hook is triggered for. default: - push items: type: string active: type: boolean description: Determines if notifications are sent when the webhook is triggered. Set to `true` to send notifications. default: true name: type: string examples: - '"web"' example: active: true events: - pull_request responses: '200': description: Response content: application/json: schema: "$ref": "#/components/schemas/org-hook" examples: default: "$ref": "#/components/examples/org-hook-2" '422': "$ref": "#/components/responses/validation_failed" '404': "$ref": "#/components/responses/not_found" x-github: githubCloudOnly: false enabledForGitHubApps: true category: orgs subcategory: webhooks delete: summary: Delete an organization webhook description: '' tags: - orgs operationId: orgs/delete-webhook externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/orgs#delete-an-organization-webhook parameters: - "$ref": "#/components/parameters/org" - "$ref": "#/components/parameters/hook-id" responses: '204': description: Response '404': "$ref": "#/components/responses/not_found" x-github: githubCloudOnly: false enabledForGitHubApps: true category: orgs subcategory: webhooks "/orgs/{org}/hooks/{hook_id}/config": get: summary: Get a webhook configuration for an organization description: |- Returns the webhook configuration for an organization. To get more information about the webhook, including the `active` state and `events`, use "[Get an organization webhook ](/rest/reference/orgs#get-an-organization-webhook)." Access tokens must have the `admin:org_hook` scope, and GitHub Apps must have the `organization_hooks:read` permission. tags: - orgs operationId: orgs/get-webhook-config-for-org externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/orgs#get-a-webhook-configuration-for-an-organization parameters: - "$ref": "#/components/parameters/org" - "$ref": "#/components/parameters/hook-id" responses: '200': description: Response content: application/json: schema: "$ref": "#/components/schemas/webhook-config" examples: default: "$ref": "#/components/examples/webhook-config" x-github: githubCloudOnly: false enabledForGitHubApps: true category: orgs subcategory: webhooks patch: summary: Update a webhook configuration for an organization description: |- Updates the webhook configuration for an organization. To update more information about the webhook, including the `active` state and `events`, use "[Update an organization webhook ](/rest/reference/orgs#update-an-organization-webhook)." Access tokens must have the `admin:org_hook` scope, and GitHub Apps must have the `organization_hooks:write` permission. tags: - orgs operationId: orgs/update-webhook-config-for-org externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/orgs#update-a-webhook-configuration-for-an-organization parameters: - "$ref": "#/components/parameters/org" - "$ref": "#/components/parameters/hook-id" requestBody: required: false content: application/json: schema: type: object properties: url: "$ref": "#/components/schemas/webhook-config-url" content_type: "$ref": "#/components/schemas/webhook-config-content-type" secret: "$ref": "#/components/schemas/webhook-config-secret" insecure_ssl: "$ref": "#/components/schemas/webhook-config-insecure-ssl" example: content_type: json insecure_ssl: '0' secret: "********" url: https://example.com/webhook additionalProperties: false responses: '200': description: Response content: application/json: schema: "$ref": "#/components/schemas/webhook-config" examples: default: "$ref": "#/components/examples/webhook-config" x-github: githubCloudOnly: false enabledForGitHubApps: true category: orgs subcategory: webhooks "/orgs/{org}/hooks/{hook_id}/pings": post: summary: Ping an organization webhook description: This will trigger a [ping event](https://docs.github.com/enterprise-server@3.0/webhooks/#ping-event) to be sent to the hook. tags: - orgs operationId: orgs/ping-webhook externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/orgs#ping-an-organization-webhook parameters: - "$ref": "#/components/parameters/org" - "$ref": "#/components/parameters/hook-id" responses: '204': description: Response '404': "$ref": "#/components/responses/not_found" x-github: githubCloudOnly: false enabledForGitHubApps: true category: orgs subcategory: webhooks "/orgs/{org}/installation": get: summary: Get an organization installation for the authenticated app description: |- Enables an authenticated GitHub App to find the organization's installation information. You must use a [JWT](https://docs.github.com/enterprise-server@3.0/apps/building-github-apps/authenticating-with-github-apps/#authenticating-as-a-github-app) to access this endpoint. tags: - apps operationId: apps/get-org-installation externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/apps#get-an-organization-installation-for-the-authenticated-app parameters: - "$ref": "#/components/parameters/org" responses: '200': description: Response content: application/json: schema: "$ref": "#/components/schemas/installation" examples: default: "$ref": "#/components/examples/installation" x-github: githubCloudOnly: false enabledForGitHubApps: false category: apps subcategory: "/orgs/{org}/installations": get: summary: List app installations for an organization description: Lists all GitHub Apps in an organization. The installation count includes all GitHub Apps installed on repositories in the organization. You must be an organization owner with `admin:read` scope to use this endpoint. tags: - orgs operationId: orgs/list-app-installations externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/orgs#list-app-installations-for-an-organization parameters: - "$ref": "#/components/parameters/org" - "$ref": "#/components/parameters/per-page" - "$ref": "#/components/parameters/page" responses: '200': description: Response content: application/json: schema: type: object required: - total_count - installations properties: total_count: type: integer installations: type: array items: "$ref": "#/components/schemas/installation" examples: default: "$ref": "#/components/examples/installation-paginated" headers: Link: "$ref": "#/components/headers/link" x-github: githubCloudOnly: false enabledForGitHubApps: true category: orgs subcategory: "/orgs/{org}/issues": get: summary: List organization issues assigned to the authenticated user description: |- List issues in an organization assigned to the authenticated user. **Note**: GitHub's REST API v3 considers every pull request an issue, but not every issue is a pull request. For this reason, "Issues" endpoints may return both issues and pull requests in the response. You can identify pull requests by the `pull_request` key. Be aware that the `id` of a pull request returned from "Issues" endpoints will be an _issue id_. To find out the pull request id, use the "[List pull requests](https://docs.github.com/enterprise-server@3.0/rest/reference/pulls#list-pull-requests)" endpoint. tags: - issues operationId: issues/list-for-org externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/issues#list-organization-issues-assigned-to-the-authenticated-user parameters: - "$ref": "#/components/parameters/org" - name: filter description: "Indicates which sorts of issues to return. Can be one of: \n\\* `assigned`: Issues assigned to you \n\\* `created`: Issues created by you \ \n\\* `mentioned`: Issues mentioning you \n\\* `subscribed`: Issues you're subscribed to updates for \n\\* `all` or `repos`: All issues the authenticated user can see, regardless of participation or creation" in: query required: false schema: type: string enum: - assigned - created - mentioned - subscribed - repos - all default: assigned - name: state description: Indicates the state of the issues to return. Can be either `open`, `closed`, or `all`. in: query required: false schema: type: string enum: - open - closed - all default: open - "$ref": "#/components/parameters/labels" - name: sort description: What to sort results by. Can be either `created`, `updated`, `comments`. in: query required: false schema: type: string enum: - created - updated - comments default: created - "$ref": "#/components/parameters/direction" - "$ref": "#/components/parameters/since" - "$ref": "#/components/parameters/per-page" - "$ref": "#/components/parameters/page" responses: '200': description: Response content: application/json: schema: type: array items: "$ref": "#/components/schemas/issue" examples: default: "$ref": "#/components/examples/issue-with-repo-items" headers: Link: "$ref": "#/components/headers/link" '404': "$ref": "#/components/responses/not_found" x-github: githubCloudOnly: false enabledForGitHubApps: false category: issues previews: - required: false name: machine-man note: "If an issue event is created via a GitHub App, the response will include the `performed_via_github_app` object with\tinformation about the GitHub App. For more information, see the [related blog\tpost](https://developer.github.com/changes/2016-09-14-Integrations-Early-Access).\nTo receive the `performed_via_github_app` object in the response, you must provide a custom [media type](https://docs.github.com/enterprise-server@3.0/rest/overview/media-types) in the `Accept` header:\n```shell\napplication/vnd.github.machine-man-preview\n```" - required: false name: squirrel-girl note: |- An additional `reactions` object in the issue comment payload is currently available for developers to preview. During the preview period, the APIs may change without advance notice. Please see the [blog post](https://developer.github.com/changes/2016-05-12-reactions-api-preview) for full details. To access the API you must provide a custom [media type](https://docs.github.com/enterprise-server@3.0/rest/overview/media-types) in the `Accept` header: ```shell application/vnd.github.squirrel-girl-preview ``` The `reactions` key will have the following payload where `url` can be used to construct the API location for [listing and creating](https://docs.github.com/enterprise-server@3.0/rest/reference/reactions) reactions. "/orgs/{org}/members": get: summary: List organization members description: List all users who are members of an organization. If the authenticated user is also a member of this organization then both concealed and public members will be returned. tags: - orgs operationId: orgs/list-members externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/orgs#list-organization-members parameters: - "$ref": "#/components/parameters/org" - name: filter description: "Filter members returned in the list. Can be one of: \n\\* `2fa_disabled` - Members without [two-factor authentication](https://github.com/blog/1614-two-factor-authentication) enabled. Available for organization owners. \n\\* `all` - All members the authenticated user can see." in: query required: false schema: type: string enum: - 2fa_disabled - all default: all - name: role description: "Filter members returned by their role. Can be one of: \n\\* `all` - All members of the organization, regardless of role. \n\\* `admin` - Organization owners. \n\\* `member` - Non-owner organization members." in: query required: false schema: type: string enum: - all - admin - member default: all - "$ref": "#/components/parameters/per-page" - "$ref": "#/components/parameters/page" responses: '200': description: Response content: application/json: schema: type: array items: "$ref": "#/components/schemas/simple-user" examples: default: "$ref": "#/components/examples/simple-user-items" headers: Link: "$ref": "#/components/headers/link" '302': description: Response if requester is not an organization member headers: Location: example: https://api.github.com/orgs/github/public_members schema: type: string '422': "$ref": "#/components/responses/validation_failed" x-github: githubCloudOnly: false enabledForGitHubApps: true category: orgs subcategory: members "/orgs/{org}/members/{username}": get: summary: Check organization membership for a user description: Check if a user is, publicly or privately, a member of the organization. tags: - orgs operationId: orgs/check-membership-for-user externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/orgs#check-organization-membership-for-a-user parameters: - "$ref": "#/components/parameters/org" - "$ref": "#/components/parameters/username" responses: '204': description: Response if requester is an organization member and user is a member '302': description: Response if requester is not an organization member headers: Location: example: https://api.github.com/orgs/github/public_members/pezra schema: type: string '404': description: Not Found if requester is an organization member and user is not a member x-github: githubCloudOnly: false enabledForGitHubApps: true category: orgs subcategory: members delete: summary: Remove an organization member description: Removing a user from this list will remove them from all teams and they will no longer have any access to the organization's repositories. tags: - orgs operationId: orgs/remove-member externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/orgs#remove-an-organization-member parameters: - "$ref": "#/components/parameters/org" - "$ref": "#/components/parameters/username" responses: '204': description: Response '403': "$ref": "#/components/responses/forbidden" x-github: githubCloudOnly: false enabledForGitHubApps: true category: orgs subcategory: members "/orgs/{org}/memberships/{username}": get: summary: Get organization membership for a user description: In order to get a user's membership with an organization, the authenticated user must be an organization member. The `state` parameter in the response can be used to identify the user's membership status. tags: - orgs operationId: orgs/get-membership-for-user externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/orgs#get-organization-membership-for-a-user parameters: - "$ref": "#/components/parameters/org" - "$ref": "#/components/parameters/username" responses: '200': description: Response content: application/json: schema: "$ref": "#/components/schemas/org-membership" examples: response-if-user-has-an-active-admin-membership-with-organization: "$ref": "#/components/examples/org-membership-response-if-user-has-an-active-admin-membership-with-organization" '404': "$ref": "#/components/responses/not_found" '403': "$ref": "#/components/responses/forbidden" x-github: githubCloudOnly: false enabledForGitHubApps: true category: orgs subcategory: members put: summary: Set organization membership for a user description: "Only authenticated organization owners can add a member to the organization or update the member's role.\n\n* If the authenticated user is _adding_ a member to the organization, the invited user will receive an email inviting them to the organization. The user's [membership status](https://docs.github.com/enterprise-server@3.0/rest/reference/orgs#get-organization-membership-for-a-user) will be `pending` until they accept the invitation.\n \n* Authenticated users can _update_ a user's membership by passing the `role` parameter. If the authenticated user changes a member's role to `admin`, the affected user will receive an email notifying them that they've been made an organization owner. If the authenticated user changes an owner's role to `member`, no email will be sent.\n\n**Rate limits**\n\nTo prevent abuse, the authenticated user is limited to 50 organization invitations per 24 hour period. If the organization is more than one month old or on a paid plan, the limit is 500 invitations per 24 hour period." tags: - orgs operationId: orgs/set-membership-for-user externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/orgs#set-organization-membership-for-a-user parameters: - "$ref": "#/components/parameters/org" - "$ref": "#/components/parameters/username" requestBody: required: false content: application/json: schema: type: object properties: role: type: string description: "The role to give the user in the organization. Can be one of: \n\\* `admin` - The user will become an owner of the organization. \n\\* `member` - The user will become a non-owner member of the organization." enum: - admin - member default: member responses: '200': description: Response content: application/json: schema: "$ref": "#/components/schemas/org-membership" examples: response-if-user-already-had-membership-with-organization: "$ref": "#/components/examples/org-membership-response-if-user-has-an-active-admin-membership-with-organization" '422': "$ref": "#/components/responses/validation_failed" '403': "$ref": "#/components/responses/forbidden" x-github: githubCloudOnly: false enabledForGitHubApps: true category: orgs subcategory: members delete: summary: Remove organization membership for a user description: |- In order to remove a user's membership with an organization, the authenticated user must be an organization owner. If the specified user is an active member of the organization, this will remove them from the organization. If the specified user has been invited to the organization, this will cancel their invitation. The specified user will receive an email notification in both cases. tags: - orgs operationId: orgs/remove-membership-for-user externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/orgs#remove-organization-membership-for-a-user parameters: - "$ref": "#/components/parameters/org" - "$ref": "#/components/parameters/username" responses: '204': description: Response '403': "$ref": "#/components/responses/forbidden" '404': "$ref": "#/components/responses/not_found" x-github: githubCloudOnly: false enabledForGitHubApps: true category: orgs subcategory: members "/orgs/{org}/outside_collaborators": get: summary: List outside collaborators for an organization description: List all users who are outside collaborators of an organization. tags: - orgs operationId: orgs/list-outside-collaborators externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/orgs#list-outside-collaborators-for-an-organization parameters: - "$ref": "#/components/parameters/org" - name: filter description: "Filter the list of outside collaborators. Can be one of: \n\\* `2fa_disabled`: Outside collaborators without [two-factor authentication](https://github.com/blog/1614-two-factor-authentication) enabled. \n\\* `all`: All outside collaborators." in: query required: false schema: type: string enum: - 2fa_disabled - all default: all - "$ref": "#/components/parameters/per-page" - "$ref": "#/components/parameters/page" responses: '200': description: Response content: application/json: schema: type: array items: "$ref": "#/components/schemas/simple-user" examples: default: "$ref": "#/components/examples/simple-user-items" headers: Link: "$ref": "#/components/headers/link" x-github: githubCloudOnly: false enabledForGitHubApps: true category: orgs subcategory: outside-collaborators "/orgs/{org}/outside_collaborators/{username}": put: summary: Convert an organization member to outside collaborator description: When an organization member is converted to an outside collaborator, they'll only have access to the repositories that their current team membership allows. The user will no longer be a member of the organization. For more information, see "[Converting an organization member to an outside collaborator](https://docs.github.com/articles/converting-an-organization-member-to-an-outside-collaborator/)". tags: - orgs operationId: orgs/convert-member-to-outside-collaborator externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/orgs#convert-an-organization-member-to-outside-collaborator parameters: - "$ref": "#/components/parameters/org" - "$ref": "#/components/parameters/username" responses: '202': description: User is getting converted asynchronously content: application/json: schema: type: object properties: {} additionalProperties: false '204': description: User was converted '403': description: Forbidden if user is the last owner of the organization or not a member of the organization '404': "$ref": "#/components/responses/not_found" x-github: githubCloudOnly: false enabledForGitHubApps: true category: orgs subcategory: outside-collaborators delete: summary: Remove outside collaborator from an organization description: Removing a user from this list will remove them from all the organization's repositories. tags: - orgs operationId: orgs/remove-outside-collaborator externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/orgs#remove-outside-collaborator-from-an-organization parameters: - "$ref": "#/components/parameters/org" - "$ref": "#/components/parameters/username" responses: '204': description: Response '422': description: Unprocessable Entity if user is a member of the organization content: application/json: schema: type: object properties: message: type: string documentation_url: type: string examples: response-if-user-is-a-member-of-the-organization: value: message: You cannot specify an organization member to remove as an outside collaborator. documentation_url: https://docs.github.com/enterprise-server@3.0/rest/reference/orgs#remove-outside-collaborator x-github: githubCloudOnly: false enabledForGitHubApps: true category: orgs subcategory: outside-collaborators "/orgs/{org}/pre-receive-hooks": get: summary: List pre-receive hooks for an organization description: List all pre-receive hooks that are enabled or testing for this organization as well as any disabled hooks that can be configured at the organization level. Globally disabled pre-receive hooks that do not allow downstream configuration are not listed. operationId: enterprise-admin/list-pre-receive-hooks-for-org tags: - enterprise-admin externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/enterprise-admin#list-pre-receive-hooks-for-an-organization parameters: - "$ref": "#/components/parameters/org" - "$ref": "#/components/parameters/per-page" - "$ref": "#/components/parameters/page" - "$ref": "#/components/parameters/direction" - name: sort description: The sort order for the response collection. in: query required: false schema: type: string enum: - created - updated - name default: created responses: '200': description: Response content: application/json: schema: type: array items: "$ref": "#/components/schemas/org-pre-receive-hook" examples: default: "$ref": "#/components/examples/org-pre-receive-hook-items" x-github: githubCloudOnly: false enabledForGitHubApps: true category: enterprise-admin subcategory: org-pre-receive-hooks previews: - required: true name: eye-scream note: |- APIs for managing pre-receive hooks are currently available for developers to preview. During the preview period, the APIs may change without advance notice. To access the API you must provide a custom [media type](/rest/overview/media-types) in the `Accept` header: ```shell application/vnd.github.eye-scream-preview ``` "/orgs/{org}/pre-receive-hooks/{pre_receive_hook_id}": get: summary: Get a pre-receive hook for an organization description: '' operationId: enterprise-admin/get-pre-receive-hook-for-org tags: - enterprise-admin externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/enterprise-admin#get-a-pre-receive-hook-for-an-organization parameters: - "$ref": "#/components/parameters/org" - "$ref": "#/components/parameters/pre-receive-hook-id" responses: '200': description: Response content: application/json: schema: "$ref": "#/components/schemas/org-pre-receive-hook" examples: default: "$ref": "#/components/examples/org-pre-receive-hook" x-github: githubCloudOnly: false enabledForGitHubApps: true category: enterprise-admin subcategory: org-pre-receive-hooks previews: - required: true name: eye-scream note: |- APIs for managing pre-receive hooks are currently available for developers to preview. During the preview period, the APIs may change without advance notice. To access the API you must provide a custom [media type](/rest/overview/media-types) in the `Accept` header: ```shell application/vnd.github.eye-scream-preview ``` patch: summary: Update pre-receive hook enforcement for an organization description: For pre-receive hooks which are allowed to be configured at the org level, you can set `enforcement` and `allow_downstream_configuration` operationId: enterprise-admin/update-pre-receive-hook-enforcement-for-org tags: - enterprise-admin externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/enterprise-admin#update-pre-receive-hook-enforcement-for-an-organization parameters: - "$ref": "#/components/parameters/org" - "$ref": "#/components/parameters/pre-receive-hook-id" responses: '200': description: Response content: application/json: schema: "$ref": "#/components/schemas/org-pre-receive-hook" examples: default: "$ref": "#/components/examples/org-pre-receive-hook-2" requestBody: content: application/json: schema: type: object properties: enforcement: description: The state of enforcement for the hook on this repository. type: string allow_downstream_configuration: description: Whether repositories can override enforcement. type: boolean example: enforcement: enabled allow_downstream_configuration: false x-github: githubCloudOnly: false enabledForGitHubApps: true category: enterprise-admin subcategory: org-pre-receive-hooks previews: - required: true name: eye-scream note: |- APIs for managing pre-receive hooks are currently available for developers to preview. During the preview period, the APIs may change without advance notice. To access the API you must provide a custom [media type](/rest/overview/media-types) in the `Accept` header: ```shell application/vnd.github.eye-scream-preview ``` delete: summary: Remove pre-receive hook enforcement for an organization description: Removes any overrides for this hook at the org level for this org. operationId: enterprise-admin/remove-pre-receive-hook-enforcement-for-org tags: - enterprise-admin externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/enterprise-admin#remove-pre-receive-hook-enforcement-for-an-organization parameters: - "$ref": "#/components/parameters/org" - "$ref": "#/components/parameters/pre-receive-hook-id" responses: '200': description: Response content: application/json: schema: "$ref": "#/components/schemas/org-pre-receive-hook" examples: default: "$ref": "#/components/examples/org-pre-receive-hook" x-github: githubCloudOnly: false enabledForGitHubApps: true category: enterprise-admin subcategory: org-pre-receive-hooks previews: - required: true name: eye-scream note: |- APIs for managing pre-receive hooks are currently available for developers to preview. During the preview period, the APIs may change without advance notice. To access the API you must provide a custom [media type](/rest/overview/media-types) in the `Accept` header: ```shell application/vnd.github.eye-scream-preview ``` "/orgs/{org}/projects": get: summary: List organization projects description: Lists the projects in an organization. Returns a `404 Not Found` status if projects are disabled in the organization. If you do not have sufficient privileges to perform this action, a `401 Unauthorized` or `410 Gone` status is returned. tags: - projects operationId: projects/list-for-org externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/projects#list-organization-projects parameters: - "$ref": "#/components/parameters/org" - name: state description: Indicates the state of the projects to return. Can be either `open`, `closed`, or `all`. in: query required: false schema: type: string enum: - open - closed - all default: open - "$ref": "#/components/parameters/per-page" - "$ref": "#/components/parameters/page" responses: '200': description: Response content: application/json: schema: type: array items: "$ref": "#/components/schemas/project" examples: default: "$ref": "#/components/examples/project-items" headers: Link: "$ref": "#/components/headers/link" '422': "$ref": "#/components/responses/validation_failed_simple" x-github: githubCloudOnly: false enabledForGitHubApps: true category: projects previews: - required: true name: inertia note: |- The Projects API is currently available for developers to preview. During the preview period, the API may change without advance notice. Please see the [blog post](https://developer.github.com/changes/2016-10-27-changes-to-projects-api) for full details. To access the API during the preview period, you must provide a custom [media type](https://docs.github.com/enterprise-server@3.0/rest/overview/media-types) in the `Accept` header: ```shell application/vnd.github.inertia-preview+json ``` post: summary: Create an organization project description: Creates an organization project board. Returns a `404 Not Found` status if projects are disabled in the organization. If you do not have sufficient privileges to perform this action, a `401 Unauthorized` or `410 Gone` status is returned. tags: - projects operationId: projects/create-for-org externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/projects#create-an-organization-project parameters: - "$ref": "#/components/parameters/org" requestBody: required: true content: application/json: schema: type: object properties: name: type: string description: The name of the project. body: type: string description: The description of the project. required: - name example: name: Organization Roadmap body: High-level roadmap for the upcoming year. responses: '201': description: Response content: application/json: schema: "$ref": "#/components/schemas/project" examples: default: "$ref": "#/components/examples/project-2" '401': "$ref": "#/components/responses/requires_authentication" '403': "$ref": "#/components/responses/forbidden" '404': "$ref": "#/components/responses/not_found" '410': "$ref": "#/components/responses/gone" '422': "$ref": "#/components/responses/validation_failed_simple" x-github: githubCloudOnly: false enabledForGitHubApps: true category: projects previews: - required: true name: inertia note: |- The Projects API is currently available for developers to preview. During the preview period, the API may change without advance notice. Please see the [blog post](https://developer.github.com/changes/2016-10-27-changes-to-projects-api) for full details. To access the API during the preview period, you must provide a custom [media type](https://docs.github.com/enterprise-server@3.0/rest/overview/media-types) in the `Accept` header: ```shell application/vnd.github.inertia-preview+json ``` "/orgs/{org}/public_members": get: summary: List public organization members description: Members of an organization can choose to have their membership publicized or not. tags: - orgs operationId: orgs/list-public-members externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/orgs#list-public-organization-members parameters: - "$ref": "#/components/parameters/org" - "$ref": "#/components/parameters/per-page" - "$ref": "#/components/parameters/page" responses: '200': description: Response content: application/json: schema: type: array items: "$ref": "#/components/schemas/simple-user" examples: default: "$ref": "#/components/examples/simple-user-items" headers: Link: "$ref": "#/components/headers/link" x-github: githubCloudOnly: false enabledForGitHubApps: true category: orgs subcategory: members "/orgs/{org}/public_members/{username}": get: summary: Check public organization membership for a user description: '' tags: - orgs operationId: orgs/check-public-membership-for-user externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/orgs#check-public-organization-membership-for-a-user parameters: - "$ref": "#/components/parameters/org" - "$ref": "#/components/parameters/username" responses: '204': description: Response if user is a public member '404': description: Not Found if user is not a public member x-github: githubCloudOnly: false enabledForGitHubApps: true category: orgs subcategory: members put: summary: Set public organization membership for the authenticated user description: |- The user can publicize their own membership. (A user cannot publicize the membership for another user.) Note that you'll need to set `Content-Length` to zero when calling out to this endpoint. For more information, see "[HTTP verbs](https://docs.github.com/enterprise-server@3.0/rest/overview/resources-in-the-rest-api#http-verbs)." tags: - orgs operationId: orgs/set-public-membership-for-authenticated-user externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/orgs#set-public-organization-membership-for-the-authenticated-user parameters: - "$ref": "#/components/parameters/org" - "$ref": "#/components/parameters/username" responses: '204': description: Response '403': "$ref": "#/components/responses/forbidden" x-github: githubCloudOnly: false enabledForGitHubApps: false category: orgs subcategory: members delete: summary: Remove public organization membership for the authenticated user description: '' tags: - orgs operationId: orgs/remove-public-membership-for-authenticated-user externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/orgs#remove-public-organization-membership-for-the-authenticated-user parameters: - "$ref": "#/components/parameters/org" - "$ref": "#/components/parameters/username" responses: '204': description: Response x-github: githubCloudOnly: false enabledForGitHubApps: false category: orgs subcategory: members "/orgs/{org}/repos": get: summary: List organization repositories description: Lists repositories for the specified organization. tags: - repos operationId: repos/list-for-org externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/repos#list-organization-repositories parameters: - "$ref": "#/components/parameters/org" - name: type description: 'Specifies the types of repositories you want returned. Can be one of `all`, `public`, `private`, `forks`, `sources`, `member`, `internal`. Note: For GitHub AE, can be one of `all`, `private`, `forks`, `sources`, `member`, `internal`. Default: `all`. If your organization is associated with an enterprise account using GitHub Enterprise Cloud or GitHub Enterprise Server 2.20+, `type` can also be `internal`. However, the `internal` value is not yet supported when a GitHub App calls this API with an installation access token.' in: query required: false schema: type: string enum: - all - public - private - forks - sources - member - internal - name: sort description: Can be one of `created`, `updated`, `pushed`, `full_name`. in: query required: false schema: type: string enum: - created - updated - pushed - full_name default: created - name: direction description: 'Can be one of `asc` or `desc`. Default: when using `full_name`: `asc`, otherwise `desc`' in: query required: false schema: type: string enum: - asc - desc - "$ref": "#/components/parameters/per-page" - "$ref": "#/components/parameters/page" responses: '200': description: Response content: application/json: schema: type: array items: "$ref": "#/components/schemas/minimal-repository" examples: default: "$ref": "#/components/examples/minimal-repository-items" headers: Link: "$ref": "#/components/headers/link" x-github: githubCloudOnly: false enabledForGitHubApps: true category: repos previews: - required: false name: nebula note: |- You can set the visibility of a repository using the new `visibility` parameter in the [Repositories API](https://docs.github.com/enterprise-server@3.0/rest/reference/repos/), and get a repository's visibility with a new response key. For more information, see the [blog post](https://developer.github.com/changes/2019-12-03-internal-visibility-changes/). To access repository visibility during the preview period, you must provide a custom [media type](https://docs.github.com/enterprise-server@3.0/rest/overview/media-types) in the `Accept` header: ```shell application/vnd.github.nebula-preview+json ``` - required: false name: baptiste note: |- The `is_template` and `template_repository` keys are currently available for developer to preview. See [Create a repository using a template](https://docs.github.com/enterprise-server@3.0/rest/reference/repos#create-a-repository-using-a-template) to learn how to create template repositories. To access these new response keys during the preview period, you must provide a custom [media type](https://docs.github.com/enterprise-server@3.0/rest/overview/media-types) in the `Accept` header: ```shell application/vnd.github.baptiste-preview+json ``` post: summary: Create an organization repository description: |- Creates a new repository in the specified organization. The authenticated user must be a member of the organization. **OAuth scope requirements** When using [OAuth](https://docs.github.com/enterprise-server@3.0/apps/building-oauth-apps/understanding-scopes-for-oauth-apps/), authorizations must include: * `public_repo` scope or `repo` scope to create a public repository. Note: For GitHub AE, use `repo` scope to create an internal repository. * `repo` scope to create a private repository tags: - repos operationId: repos/create-in-org externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/repos#create-an-organization-repository parameters: - "$ref": "#/components/parameters/org" requestBody: required: true content: application/json: schema: type: object properties: name: type: string description: The name of the repository. description: type: string description: A short description of the repository. homepage: type: string description: A URL with more information about the repository. private: type: boolean description: Whether the repository is private. default: false visibility: type: string description: "Can be `public` or `private`. If your organization is associated with an enterprise account using GitHub Enterprise Cloud or GitHub Enterprise Server 2.20+, `visibility` can also be `internal`. Note: For GitHub Enterprise Server and GitHub AE, this endpoint will only list repositories available to all users on the enterprise. For more information, see \"[Creating an internal repository](https://docs.github.com/en/github/creating-cloning-and-archiving-repositories/about-repository-visibility#about-internal-repositories)\" in the GitHub Help documentation. \nThe `visibility` parameter overrides the `private` parameter when you use both parameters with the `nebula-preview` preview header." enum: - public - private - internal has_issues: type: boolean description: Either `true` to enable issues for this repository or `false` to disable them. default: true has_projects: type: boolean description: Either `true` to enable projects for this repository or `false` to disable them. **Note:** If you're creating a repository in an organization that has disabled repository projects, the default is `false`, and if you pass `true`, the API returns an error. default: true has_wiki: type: boolean description: Either `true` to enable the wiki for this repository or `false` to disable it. default: true is_template: type: boolean description: Either `true` to make this repo available as a template repository or `false` to prevent it. default: false team_id: type: integer description: The id of the team that will be granted access to this repository. This is only valid when creating a repository in an organization. auto_init: type: boolean description: Pass `true` to create an initial commit with empty README. default: false gitignore_template: type: string description: Desired language or platform [.gitignore template](https://github.com/github/gitignore) to apply. Use the name of the template without the extension. For example, "Haskell". license_template: type: string description: Choose an [open source license template](https://choosealicense.com/) that best suits your needs, and then use the [license keyword](https://docs.github.com/articles/licensing-a-repository/#searching-github-by-license-type) as the `license_template` string. For example, "mit" or "mpl-2.0". allow_squash_merge: type: boolean description: Either `true` to allow squash-merging pull requests, or `false` to prevent squash-merging. default: true allow_merge_commit: type: boolean description: Either `true` to allow merging pull requests with a merge commit, or `false` to prevent merging pull requests with merge commits. default: true allow_rebase_merge: type: boolean description: Either `true` to allow rebase-merging pull requests, or `false` to prevent rebase-merging. default: true delete_branch_on_merge: type: boolean description: Either `true` to allow automatically deleting head branches when pull requests are merged, or `false` to prevent automatic deletion. default: false required: - name example: name: Hello-World description: This is your first repository homepage: https://github.com private: false has_issues: true has_projects: true has_wiki: true responses: '201': description: Response content: application/json: schema: "$ref": "#/components/schemas/repository" examples: default: "$ref": "#/components/examples/repository" headers: Location: example: https://api.github.com/repos/octocat/Hello-World schema: type: string '403': "$ref": "#/components/responses/forbidden" '422': "$ref": "#/components/responses/validation_failed" x-github: githubCloudOnly: false enabledForGitHubApps: true category: repos previews: - required: false name: nebula note: |- You can set the visibility of a repository using the new `visibility` parameter in the [Repositories API](https://docs.github.com/enterprise-server@3.0/rest/reference/repos/), and get a repository's visibility with a new response key. For more information, see the [blog post](https://developer.github.com/changes/2019-12-03-internal-visibility-changes/). To access repository visibility during the preview period, you must provide a custom [media type](https://docs.github.com/enterprise-server@3.0/rest/overview/media-types) in the `Accept` header: ```shell application/vnd.github.nebula-preview+json ``` - required: false name: baptiste note: |- The `is_template` and `template_repository` keys are currently available for developer to preview. See [Create a repository using a template](https://docs.github.com/enterprise-server@3.0/rest/reference/repos#create-a-repository-using-a-template) to learn how to create template repositories. To access these new response keys during the preview period, you must provide a custom [media type](https://docs.github.com/enterprise-server@3.0/rest/overview/media-types) in the `Accept` header: ```shell application/vnd.github.baptiste-preview+json ``` "/orgs/{org}/teams": get: summary: List teams description: Lists all teams in an organization that are visible to the authenticated user. tags: - teams operationId: teams/list externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/teams#list-teams parameters: - "$ref": "#/components/parameters/org" - "$ref": "#/components/parameters/per-page" - "$ref": "#/components/parameters/page" responses: '200': description: Response content: application/json: schema: type: array items: "$ref": "#/components/schemas/team" examples: default: "$ref": "#/components/examples/team-items" headers: Link: "$ref": "#/components/headers/link" '403': "$ref": "#/components/responses/forbidden" x-github: githubCloudOnly: false enabledForGitHubApps: true category: teams subcategory: post: summary: Create a team description: |- To create a team, the authenticated user must be a member or owner of `{org}`. By default, organization members can create teams. Organization owners can limit team creation to organization owners. For more information, see "[Setting team creation permissions](https://docs.github.com/en/articles/setting-team-creation-permissions-in-your-organization)." When you create a new team, you automatically become a team maintainer without explicitly adding yourself to the optional array of `maintainers`. For more information, see "[About teams](https://docs.github.com/en/github/setting-up-and-managing-organizations-and-teams/about-teams)". tags: - teams operationId: teams/create externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/teams#create-a-team parameters: - "$ref": "#/components/parameters/org" requestBody: required: true content: application/json: schema: type: object properties: name: type: string description: The name of the team. description: type: string description: The description of the team. maintainers: type: array description: List GitHub IDs for organization members who will become team maintainers. items: type: string repo_names: type: array description: The full name (e.g., "organization-name/repository-name") of repositories to add the team to. items: type: string privacy: type: string description: "The level of privacy this team should have. The options are: \n**For a non-nested team:** \n\\* `secret` - only visible to organization owners and members of this team. \n\\* `closed` - visible to all members of this organization. \nDefault: `secret` \ \n**For a parent or child team:** \n\\* `closed` - visible to all members of this organization. \nDefault for child team: `closed`" enum: - secret - closed permission: type: string description: "**Deprecated**. The permission that new repositories will be added to the team with when none is specified. Can be one of: \n\\* `pull` - team members can pull, but not push to or administer newly-added repositories. \n\\* `push` - team members can pull and push, but not administer newly-added repositories." enum: - pull - push default: pull parent_team_id: type: integer description: The ID of a team to set as the parent team. ldap_dn: type: string description: The [distinguished name](https://www.ldap.com/ldap-dns-and-rdns) (DN) of the LDAP entry to map to a team. LDAP synchronization must be enabled to map LDAP entries to a team. Use the "[Update LDAP mapping for a team](https://docs.github.com/enterprise-server@3.0/rest/reference/enterprise-admin#update-ldap-mapping-for-a-team)" endpoint to change the LDAP DN. For more information, see "[Using LDAP](https://docs.github.com/enterprise-server@3.0/admin/identity-and-access-management/authenticating-users-for-your-github-enterprise-server-instance/using-ldap#enabling-ldap-sync)." required: - name example: name: Justice League description: A great team permission: push privacy: closed responses: '201': description: Response content: application/json: schema: "$ref": "#/components/schemas/team-full" examples: default: "$ref": "#/components/examples/team-full" '422': "$ref": "#/components/responses/validation_failed" '403': "$ref": "#/components/responses/forbidden" x-github: githubCloudOnly: false enabledForGitHubApps: true category: teams subcategory: "/orgs/{org}/teams/{team_slug}": get: summary: Get a team by name description: |- Gets a team using the team's `slug`. GitHub Enterprise Server generates the `slug` from the team `name`. **Note:** You can also specify a team by `org_id` and `team_id` using the route `GET /organizations/{org_id}/team/{team_id}`. tags: - teams operationId: teams/get-by-name externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/teams#get-a-team-by-name parameters: - "$ref": "#/components/parameters/org" - "$ref": "#/components/parameters/team-slug" responses: '200': description: Response content: application/json: schema: "$ref": "#/components/schemas/team-full" examples: default: "$ref": "#/components/examples/team-full" '404': "$ref": "#/components/responses/not_found" x-github: githubCloudOnly: false enabledForGitHubApps: true category: teams subcategory: patch: summary: Update a team description: |- To edit a team, the authenticated user must either be an organization owner or a team maintainer. **Note:** You can also specify a team by `org_id` and `team_id` using the route `PATCH /organizations/{org_id}/team/{team_id}`. tags: - teams operationId: teams/update-in-org externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/teams#update-a-team parameters: - "$ref": "#/components/parameters/org" - "$ref": "#/components/parameters/team-slug" requestBody: required: false content: application/json: schema: type: object properties: name: type: string description: The name of the team. description: type: string description: The description of the team. privacy: type: string description: "The level of privacy this team should have. Editing teams without specifying this parameter leaves `privacy` intact. When a team is nested, the `privacy` for parent teams cannot be `secret`. The options are: \n**For a non-nested team:** \n\\* `secret` - only visible to organization owners and members of this team. \n\\* `closed` - visible to all members of this organization. \ \n**For a parent or child team:** \n\\* `closed` - visible to all members of this organization." enum: - secret - closed permission: type: string description: "**Deprecated**. The permission that new repositories will be added to the team with when none is specified. Can be one of: \n\\* `pull` - team members can pull, but not push to or administer newly-added repositories. \n\\* `push` - team members can pull and push, but not administer newly-added repositories. \ \n\\* `admin` - team members can pull, push and administer newly-added repositories." enum: - pull - push - admin default: pull parent_team_id: type: - integer - 'null' description: The ID of a team to set as the parent team. example: name: new team name description: new team description privacy: closed responses: '201': description: Response content: application/json: schema: "$ref": "#/components/schemas/team-full" examples: default: "$ref": "#/components/examples/team-full" x-github: githubCloudOnly: false enabledForGitHubApps: true category: teams subcategory: delete: summary: Delete a team description: |- To delete a team, the authenticated user must be an organization owner or team maintainer. If you are an organization owner, deleting a parent team will delete all of its child teams as well. **Note:** You can also specify a team by `org_id` and `team_id` using the route `DELETE /organizations/{org_id}/team/{team_id}`. tags: - teams operationId: teams/delete-in-org externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/teams#delete-a-team parameters: - "$ref": "#/components/parameters/org" - "$ref": "#/components/parameters/team-slug" responses: '204': description: Response x-github: githubCloudOnly: false enabledForGitHubApps: true category: teams subcategory: "/orgs/{org}/teams/{team_slug}/discussions": get: summary: List discussions description: |- List all discussions on a team's page. OAuth access tokens require the `read:discussion` [scope](https://docs.github.com/enterprise-server@3.0/apps/building-oauth-apps/understanding-scopes-for-oauth-apps/). **Note:** You can also specify a team by `org_id` and `team_id` using the route `GET /organizations/{org_id}/team/{team_id}/discussions`. tags: - teams operationId: teams/list-discussions-in-org externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/teams#list-discussions parameters: - "$ref": "#/components/parameters/org" - "$ref": "#/components/parameters/team-slug" - "$ref": "#/components/parameters/direction" - "$ref": "#/components/parameters/per-page" - "$ref": "#/components/parameters/page" - name: pinned in: query required: false description: Pinned discussions only filter schema: type: string responses: '200': description: Response content: application/json: schema: type: array items: "$ref": "#/components/schemas/team-discussion" examples: default: "$ref": "#/components/examples/team-discussion-items" headers: Link: "$ref": "#/components/headers/link" x-github: githubCloudOnly: false enabledForGitHubApps: true category: teams subcategory: discussions previews: - required: false name: squirrel-girl note: |- An additional `reactions` object in the issue comment payload is currently available for developers to preview. During the preview period, the APIs may change without advance notice. Please see the [blog post](https://developer.github.com/changes/2016-05-12-reactions-api-preview) for full details. To access the API you must provide a custom [media type](https://docs.github.com/enterprise-server@3.0/rest/overview/media-types) in the `Accept` header: ```shell application/vnd.github.squirrel-girl-preview ``` The `reactions` key will have the following payload where `url` can be used to construct the API location for [listing and creating](https://docs.github.com/enterprise-server@3.0/rest/reference/reactions) reactions. post: summary: Create a discussion description: |- Creates a new discussion post on a team's page. OAuth access tokens require the `write:discussion` [scope](https://docs.github.com/enterprise-server@3.0/apps/building-oauth-apps/understanding-scopes-for-oauth-apps/). This endpoint triggers [notifications](https://docs.github.com/en/github/managing-subscriptions-and-notifications-on-github/about-notifications). Creating content too quickly using this endpoint may result in secondary rate limiting. See "[Secondary rate limits](https://docs.github.com/enterprise-server@3.0/rest/overview/resources-in-the-rest-api#secondary-rate-limits)" and "[Dealing with secondary rate limits](https://docs.github.com/enterprise-server@3.0/rest/guides/best-practices-for-integrators#dealing-with-secondary-rate-limits)" for details. **Note:** You can also specify a team by `org_id` and `team_id` using the route `POST /organizations/{org_id}/team/{team_id}/discussions`. tags: - teams operationId: teams/create-discussion-in-org externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/teams#create-a-discussion parameters: - "$ref": "#/components/parameters/org" - "$ref": "#/components/parameters/team-slug" requestBody: required: true content: application/json: schema: type: object properties: title: type: string description: The discussion post's title. body: type: string description: The discussion post's body text. private: type: boolean description: Private posts are only visible to team members, organization owners, and team maintainers. Public posts are visible to all members of the organization. Set to `true` to create a private post. default: false required: - title - body example: title: Our first team post body: Hi! This is an area for us to collaborate as a team. responses: '201': description: Response content: application/json: schema: "$ref": "#/components/schemas/team-discussion" examples: default: "$ref": "#/components/examples/team-discussion" x-github: triggersNotification: true githubCloudOnly: false enabledForGitHubApps: true category: teams subcategory: discussions previews: - required: false name: squirrel-girl note: |- An additional `reactions` object in the issue comment payload is currently available for developers to preview. During the preview period, the APIs may change without advance notice. Please see the [blog post](https://developer.github.com/changes/2016-05-12-reactions-api-preview) for full details. To access the API you must provide a custom [media type](https://docs.github.com/enterprise-server@3.0/rest/overview/media-types) in the `Accept` header: ```shell application/vnd.github.squirrel-girl-preview ``` The `reactions` key will have the following payload where `url` can be used to construct the API location for [listing and creating](https://docs.github.com/enterprise-server@3.0/rest/reference/reactions) reactions. "/orgs/{org}/teams/{team_slug}/discussions/{discussion_number}": get: summary: Get a discussion description: |- Get a specific discussion on a team's page. OAuth access tokens require the `read:discussion` [scope](https://docs.github.com/enterprise-server@3.0/apps/building-oauth-apps/understanding-scopes-for-oauth-apps/). **Note:** You can also specify a team by `org_id` and `team_id` using the route `GET /organizations/{org_id}/team/{team_id}/discussions/{discussion_number}`. tags: - teams operationId: teams/get-discussion-in-org externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/teams#get-a-discussion parameters: - "$ref": "#/components/parameters/org" - "$ref": "#/components/parameters/team-slug" - "$ref": "#/components/parameters/discussion-number" responses: '200': description: Response content: application/json: schema: "$ref": "#/components/schemas/team-discussion" examples: default: "$ref": "#/components/examples/team-discussion" x-github: githubCloudOnly: false enabledForGitHubApps: true category: teams subcategory: discussions previews: - required: false name: squirrel-girl note: |- An additional `reactions` object in the issue comment payload is currently available for developers to preview. During the preview period, the APIs may change without advance notice. Please see the [blog post](https://developer.github.com/changes/2016-05-12-reactions-api-preview) for full details. To access the API you must provide a custom [media type](https://docs.github.com/enterprise-server@3.0/rest/overview/media-types) in the `Accept` header: ```shell application/vnd.github.squirrel-girl-preview ``` The `reactions` key will have the following payload where `url` can be used to construct the API location for [listing and creating](https://docs.github.com/enterprise-server@3.0/rest/reference/reactions) reactions. patch: summary: Update a discussion description: |- Edits the title and body text of a discussion post. Only the parameters you provide are updated. OAuth access tokens require the `write:discussion` [scope](https://docs.github.com/enterprise-server@3.0/apps/building-oauth-apps/understanding-scopes-for-oauth-apps/). **Note:** You can also specify a team by `org_id` and `team_id` using the route `PATCH /organizations/{org_id}/team/{team_id}/discussions/{discussion_number}`. tags: - teams operationId: teams/update-discussion-in-org externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/teams#update-a-discussion parameters: - "$ref": "#/components/parameters/org" - "$ref": "#/components/parameters/team-slug" - "$ref": "#/components/parameters/discussion-number" requestBody: required: false content: application/json: schema: type: object properties: title: type: string description: The discussion post's title. body: type: string description: The discussion post's body text. example: title: Welcome to our first team post responses: '200': description: Response content: application/json: schema: "$ref": "#/components/schemas/team-discussion" examples: default: "$ref": "#/components/examples/team-discussion-2" x-github: githubCloudOnly: false enabledForGitHubApps: true category: teams subcategory: discussions previews: - required: false name: squirrel-girl note: |- An additional `reactions` object in the issue comment payload is currently available for developers to preview. During the preview period, the APIs may change without advance notice. Please see the [blog post](https://developer.github.com/changes/2016-05-12-reactions-api-preview) for full details. To access the API you must provide a custom [media type](https://docs.github.com/enterprise-server@3.0/rest/overview/media-types) in the `Accept` header: ```shell application/vnd.github.squirrel-girl-preview ``` The `reactions` key will have the following payload where `url` can be used to construct the API location for [listing and creating](https://docs.github.com/enterprise-server@3.0/rest/reference/reactions) reactions. delete: summary: Delete a discussion description: |- Delete a discussion from a team's page. OAuth access tokens require the `write:discussion` [scope](https://docs.github.com/enterprise-server@3.0/apps/building-oauth-apps/understanding-scopes-for-oauth-apps/). **Note:** You can also specify a team by `org_id` and `team_id` using the route `DELETE /organizations/{org_id}/team/{team_id}/discussions/{discussion_number}`. tags: - teams operationId: teams/delete-discussion-in-org externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/teams#delete-a-discussion parameters: - "$ref": "#/components/parameters/org" - "$ref": "#/components/parameters/team-slug" - "$ref": "#/components/parameters/discussion-number" responses: '204': description: Response x-github: githubCloudOnly: false enabledForGitHubApps: true category: teams subcategory: discussions "/orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments": get: summary: List discussion comments description: |- List all comments on a team discussion. OAuth access tokens require the `read:discussion` [scope](https://docs.github.com/enterprise-server@3.0/apps/building-oauth-apps/understanding-scopes-for-oauth-apps/). **Note:** You can also specify a team by `org_id` and `team_id` using the route `GET /organizations/{org_id}/team/{team_id}/discussions/{discussion_number}/comments`. tags: - teams operationId: teams/list-discussion-comments-in-org externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/teams#list-discussion-comments parameters: - "$ref": "#/components/parameters/org" - "$ref": "#/components/parameters/team-slug" - "$ref": "#/components/parameters/discussion-number" - "$ref": "#/components/parameters/direction" - "$ref": "#/components/parameters/per-page" - "$ref": "#/components/parameters/page" responses: '200': description: Response content: application/json: schema: type: array items: "$ref": "#/components/schemas/team-discussion-comment" examples: default: "$ref": "#/components/examples/team-discussion-comment-items" headers: Link: "$ref": "#/components/headers/link" x-github: githubCloudOnly: false enabledForGitHubApps: true category: teams subcategory: discussion-comments previews: - required: false name: squirrel-girl note: |- An additional `reactions` object in the issue comment payload is currently available for developers to preview. During the preview period, the APIs may change without advance notice. Please see the [blog post](https://developer.github.com/changes/2016-05-12-reactions-api-preview) for full details. To access the API you must provide a custom [media type](https://docs.github.com/enterprise-server@3.0/rest/overview/media-types) in the `Accept` header: ```shell application/vnd.github.squirrel-girl-preview ``` The `reactions` key will have the following payload where `url` can be used to construct the API location for [listing and creating](https://docs.github.com/enterprise-server@3.0/rest/reference/reactions) reactions. post: summary: Create a discussion comment description: |- Creates a new comment on a team discussion. OAuth access tokens require the `write:discussion` [scope](https://docs.github.com/enterprise-server@3.0/apps/building-oauth-apps/understanding-scopes-for-oauth-apps/). This endpoint triggers [notifications](https://docs.github.com/en/github/managing-subscriptions-and-notifications-on-github/about-notifications). Creating content too quickly using this endpoint may result in secondary rate limiting. See "[Secondary rate limits](https://docs.github.com/enterprise-server@3.0/rest/overview/resources-in-the-rest-api#secondary-rate-limits)" and "[Dealing with secondary rate limits](https://docs.github.com/enterprise-server@3.0/rest/guides/best-practices-for-integrators#dealing-with-secondary-rate-limits)" for details. **Note:** You can also specify a team by `org_id` and `team_id` using the route `POST /organizations/{org_id}/team/{team_id}/discussions/{discussion_number}/comments`. tags: - teams operationId: teams/create-discussion-comment-in-org externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/teams#create-a-discussion-comment parameters: - "$ref": "#/components/parameters/org" - "$ref": "#/components/parameters/team-slug" - "$ref": "#/components/parameters/discussion-number" requestBody: required: true content: application/json: schema: type: object properties: body: type: string description: The discussion comment's body text. required: - body example: body: Do you like apples? responses: '201': description: Response content: application/json: schema: "$ref": "#/components/schemas/team-discussion-comment" examples: default: "$ref": "#/components/examples/team-discussion-comment" x-github: triggersNotification: true githubCloudOnly: false enabledForGitHubApps: true category: teams subcategory: discussion-comments previews: - required: false name: squirrel-girl note: |- An additional `reactions` object in the issue comment payload is currently available for developers to preview. During the preview period, the APIs may change without advance notice. Please see the [blog post](https://developer.github.com/changes/2016-05-12-reactions-api-preview) for full details. To access the API you must provide a custom [media type](https://docs.github.com/enterprise-server@3.0/rest/overview/media-types) in the `Accept` header: ```shell application/vnd.github.squirrel-girl-preview ``` The `reactions` key will have the following payload where `url` can be used to construct the API location for [listing and creating](https://docs.github.com/enterprise-server@3.0/rest/reference/reactions) reactions. "/orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments/{comment_number}": get: summary: Get a discussion comment description: |- Get a specific comment on a team discussion. OAuth access tokens require the `read:discussion` [scope](https://docs.github.com/enterprise-server@3.0/apps/building-oauth-apps/understanding-scopes-for-oauth-apps/). **Note:** You can also specify a team by `org_id` and `team_id` using the route `GET /organizations/{org_id}/team/{team_id}/discussions/{discussion_number}/comments/{comment_number}`. tags: - teams operationId: teams/get-discussion-comment-in-org externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/teams#get-a-discussion-comment parameters: - "$ref": "#/components/parameters/org" - "$ref": "#/components/parameters/team-slug" - "$ref": "#/components/parameters/discussion-number" - "$ref": "#/components/parameters/comment-number" responses: '200': description: Response content: application/json: schema: "$ref": "#/components/schemas/team-discussion-comment" examples: default: "$ref": "#/components/examples/team-discussion-comment" x-github: githubCloudOnly: false enabledForGitHubApps: true category: teams subcategory: discussion-comments previews: - required: false name: squirrel-girl note: |- An additional `reactions` object in the issue comment payload is currently available for developers to preview. During the preview period, the APIs may change without advance notice. Please see the [blog post](https://developer.github.com/changes/2016-05-12-reactions-api-preview) for full details. To access the API you must provide a custom [media type](https://docs.github.com/enterprise-server@3.0/rest/overview/media-types) in the `Accept` header: ```shell application/vnd.github.squirrel-girl-preview ``` The `reactions` key will have the following payload where `url` can be used to construct the API location for [listing and creating](https://docs.github.com/enterprise-server@3.0/rest/reference/reactions) reactions. patch: summary: Update a discussion comment description: |- Edits the body text of a discussion comment. OAuth access tokens require the `write:discussion` [scope](https://docs.github.com/enterprise-server@3.0/apps/building-oauth-apps/understanding-scopes-for-oauth-apps/). **Note:** You can also specify a team by `org_id` and `team_id` using the route `PATCH /organizations/{org_id}/team/{team_id}/discussions/{discussion_number}/comments/{comment_number}`. tags: - teams operationId: teams/update-discussion-comment-in-org externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/teams#update-a-discussion-comment parameters: - "$ref": "#/components/parameters/org" - "$ref": "#/components/parameters/team-slug" - "$ref": "#/components/parameters/discussion-number" - "$ref": "#/components/parameters/comment-number" requestBody: required: true content: application/json: schema: type: object properties: body: type: string description: The discussion comment's body text. required: - body example: body: Do you like pineapples? responses: '200': description: Response content: application/json: schema: "$ref": "#/components/schemas/team-discussion-comment" examples: default: "$ref": "#/components/examples/team-discussion-comment-2" x-github: githubCloudOnly: false enabledForGitHubApps: true category: teams subcategory: discussion-comments previews: - required: false name: squirrel-girl note: |- An additional `reactions` object in the issue comment payload is currently available for developers to preview. During the preview period, the APIs may change without advance notice. Please see the [blog post](https://developer.github.com/changes/2016-05-12-reactions-api-preview) for full details. To access the API you must provide a custom [media type](https://docs.github.com/enterprise-server@3.0/rest/overview/media-types) in the `Accept` header: ```shell application/vnd.github.squirrel-girl-preview ``` The `reactions` key will have the following payload where `url` can be used to construct the API location for [listing and creating](https://docs.github.com/enterprise-server@3.0/rest/reference/reactions) reactions. delete: summary: Delete a discussion comment description: |- Deletes a comment on a team discussion. OAuth access tokens require the `write:discussion` [scope](https://docs.github.com/enterprise-server@3.0/apps/building-oauth-apps/understanding-scopes-for-oauth-apps/). **Note:** You can also specify a team by `org_id` and `team_id` using the route `DELETE /organizations/{org_id}/team/{team_id}/discussions/{discussion_number}/comments/{comment_number}`. tags: - teams operationId: teams/delete-discussion-comment-in-org externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/teams#delete-a-discussion-comment parameters: - "$ref": "#/components/parameters/org" - "$ref": "#/components/parameters/team-slug" - "$ref": "#/components/parameters/discussion-number" - "$ref": "#/components/parameters/comment-number" responses: '204': description: Response x-github: githubCloudOnly: false enabledForGitHubApps: true category: teams subcategory: discussion-comments "/orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments/{comment_number}/reactions": get: summary: List reactions for a team discussion comment description: |- List the reactions to a [team discussion comment](https://docs.github.com/enterprise-server@3.0/rest/reference/teams#discussion-comments/). OAuth access tokens require the `read:discussion` [scope](https://docs.github.com/enterprise-server@3.0/apps/building-oauth-apps/understanding-scopes-for-oauth-apps/). **Note:** You can also specify a team by `org_id` and `team_id` using the route `GET /organizations/:org_id/team/:team_id/discussions/:discussion_number/comments/:comment_number/reactions`. tags: - reactions operationId: reactions/list-for-team-discussion-comment-in-org externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/reactions#list-reactions-for-a-team-discussion-comment parameters: - "$ref": "#/components/parameters/org" - "$ref": "#/components/parameters/team-slug" - "$ref": "#/components/parameters/discussion-number" - "$ref": "#/components/parameters/comment-number" - name: content description: Returns a single [reaction type](https://docs.github.com/enterprise-server@3.0/rest/reference/reactions#reaction-types). Omit this parameter to list all reactions to a team discussion comment. in: query required: false schema: type: string enum: - "+1" - "-1" - laugh - confused - heart - hooray - rocket - eyes - "$ref": "#/components/parameters/per-page" - "$ref": "#/components/parameters/page" responses: '200': description: Response content: application/json: schema: type: array items: "$ref": "#/components/schemas/reaction" examples: default: "$ref": "#/components/examples/reaction-items" headers: Link: "$ref": "#/components/headers/link" x-github: githubCloudOnly: false enabledForGitHubApps: true category: reactions previews: - required: true name: squirrel-girl note: |- An additional `reactions` object in the issue comment payload is currently available for developers to preview. During the preview period, the APIs may change without advance notice. Please see the [blog post](https://developer.github.com/changes/2016-05-12-reactions-api-preview) for full details. To access the API you must provide a custom [media type](https://docs.github.com/enterprise-server@3.0/rest/overview/media-types) in the `Accept` header: ```shell application/vnd.github.squirrel-girl-preview ``` The `reactions` key will have the following payload where `url` can be used to construct the API location for [listing and creating](https://docs.github.com/enterprise-server@3.0/rest/reference/reactions) reactions. post: summary: Create reaction for a team discussion comment description: |- Create a reaction to a [team discussion comment](https://docs.github.com/enterprise-server@3.0/rest/reference/teams#discussion-comments). OAuth access tokens require the `write:discussion` [scope](https://docs.github.com/enterprise-server@3.0/apps/building-oauth-apps/understanding-scopes-for-oauth-apps/). A response with an HTTP `200` status means that you already added the reaction type to this team discussion comment. **Note:** You can also specify a team by `org_id` and `team_id` using the route `POST /organizations/:org_id/team/:team_id/discussions/:discussion_number/comments/:comment_number/reactions`. tags: - reactions operationId: reactions/create-for-team-discussion-comment-in-org externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/reactions#create-reaction-for-a-team-discussion-comment parameters: - "$ref": "#/components/parameters/org" - "$ref": "#/components/parameters/team-slug" - "$ref": "#/components/parameters/discussion-number" - "$ref": "#/components/parameters/comment-number" requestBody: required: true content: application/json: schema: type: object properties: content: type: string description: The [reaction type](https://docs.github.com/enterprise-server@3.0/rest/reference/reactions#reaction-types) to add to the team discussion comment. enum: - "+1" - "-1" - laugh - confused - heart - hooray - rocket - eyes required: - content example: content: heart responses: '200': description: Response content: application/json: schema: "$ref": "#/components/schemas/reaction" examples: default: "$ref": "#/components/examples/reaction" '201': description: Response content: application/json: schema: "$ref": "#/components/schemas/reaction" examples: default: "$ref": "#/components/examples/reaction" x-github: githubCloudOnly: false enabledForGitHubApps: true category: reactions previews: - required: true name: squirrel-girl note: |- An additional `reactions` object in the issue comment payload is currently available for developers to preview. During the preview period, the APIs may change without advance notice. Please see the [blog post](https://developer.github.com/changes/2016-05-12-reactions-api-preview) for full details. To access the API you must provide a custom [media type](https://docs.github.com/enterprise-server@3.0/rest/overview/media-types) in the `Accept` header: ```shell application/vnd.github.squirrel-girl-preview ``` The `reactions` key will have the following payload where `url` can be used to construct the API location for [listing and creating](https://docs.github.com/enterprise-server@3.0/rest/reference/reactions) reactions. "/orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments/{comment_number}/reactions/{reaction_id}": delete: summary: Delete team discussion comment reaction description: |- **Note:** You can also specify a team or organization with `team_id` and `org_id` using the route `DELETE /organizations/:org_id/team/:team_id/discussions/:discussion_number/comments/:comment_number/reactions/:reaction_id`. Delete a reaction to a [team discussion comment](https://docs.github.com/enterprise-server@3.0/rest/reference/teams#discussion-comments). OAuth access tokens require the `write:discussion` [scope](https://docs.github.com/enterprise-server@3.0/apps/building-oauth-apps/understanding-scopes-for-oauth-apps/). tags: - reactions operationId: reactions/delete-for-team-discussion-comment externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/reactions#delete-team-discussion-comment-reaction parameters: - "$ref": "#/components/parameters/org" - "$ref": "#/components/parameters/team-slug" - "$ref": "#/components/parameters/discussion-number" - "$ref": "#/components/parameters/comment-number" - "$ref": "#/components/parameters/reaction-id" responses: '204': description: Response x-github: githubCloudOnly: false enabledForGitHubApps: true category: reactions previews: - required: true name: squirrel-girl note: |- An additional `reactions` object in the issue comment payload is currently available for developers to preview. During the preview period, the APIs may change without advance notice. Please see the [blog post](https://developer.github.com/changes/2016-05-12-reactions-api-preview) for full details. To access the API you must provide a custom [media type](https://docs.github.com/enterprise-server@3.0/rest/overview/media-types) in the `Accept` header: ```shell application/vnd.github.squirrel-girl-preview ``` The `reactions` key will have the following payload where `url` can be used to construct the API location for [listing and creating](https://docs.github.com/enterprise-server@3.0/rest/reference/reactions) reactions. "/orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/reactions": get: summary: List reactions for a team discussion description: |- List the reactions to a [team discussion](https://docs.github.com/enterprise-server@3.0/rest/reference/teams#discussions). OAuth access tokens require the `read:discussion` [scope](https://docs.github.com/enterprise-server@3.0/apps/building-oauth-apps/understanding-scopes-for-oauth-apps/). **Note:** You can also specify a team by `org_id` and `team_id` using the route `GET /organizations/:org_id/team/:team_id/discussions/:discussion_number/reactions`. tags: - reactions operationId: reactions/list-for-team-discussion-in-org externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/reactions#list-reactions-for-a-team-discussion parameters: - "$ref": "#/components/parameters/org" - "$ref": "#/components/parameters/team-slug" - "$ref": "#/components/parameters/discussion-number" - name: content description: Returns a single [reaction type](https://docs.github.com/enterprise-server@3.0/rest/reference/reactions#reaction-types). Omit this parameter to list all reactions to a team discussion. in: query required: false schema: type: string enum: - "+1" - "-1" - laugh - confused - heart - hooray - rocket - eyes - "$ref": "#/components/parameters/per-page" - "$ref": "#/components/parameters/page" responses: '200': description: Response content: application/json: schema: type: array items: "$ref": "#/components/schemas/reaction" examples: default: "$ref": "#/components/examples/reaction-items" headers: Link: "$ref": "#/components/headers/link" x-github: githubCloudOnly: false enabledForGitHubApps: true category: reactions previews: - required: true name: squirrel-girl note: |- An additional `reactions` object in the issue comment payload is currently available for developers to preview. During the preview period, the APIs may change without advance notice. Please see the [blog post](https://developer.github.com/changes/2016-05-12-reactions-api-preview) for full details. To access the API you must provide a custom [media type](https://docs.github.com/enterprise-server@3.0/rest/overview/media-types) in the `Accept` header: ```shell application/vnd.github.squirrel-girl-preview ``` The `reactions` key will have the following payload where `url` can be used to construct the API location for [listing and creating](https://docs.github.com/enterprise-server@3.0/rest/reference/reactions) reactions. post: summary: Create reaction for a team discussion description: |- Create a reaction to a [team discussion](https://docs.github.com/enterprise-server@3.0/rest/reference/teams#discussions). OAuth access tokens require the `write:discussion` [scope](https://docs.github.com/enterprise-server@3.0/apps/building-oauth-apps/understanding-scopes-for-oauth-apps/). A response with an HTTP `200` status means that you already added the reaction type to this team discussion. **Note:** You can also specify a team by `org_id` and `team_id` using the route `POST /organizations/:org_id/team/:team_id/discussions/:discussion_number/reactions`. tags: - reactions operationId: reactions/create-for-team-discussion-in-org externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/reactions#create-reaction-for-a-team-discussion parameters: - "$ref": "#/components/parameters/org" - "$ref": "#/components/parameters/team-slug" - "$ref": "#/components/parameters/discussion-number" requestBody: required: true content: application/json: schema: type: object properties: content: type: string description: The [reaction type](https://docs.github.com/enterprise-server@3.0/rest/reference/reactions#reaction-types) to add to the team discussion. enum: - "+1" - "-1" - laugh - confused - heart - hooray - rocket - eyes required: - content example: content: heart responses: '200': description: Response content: application/json: schema: "$ref": "#/components/schemas/reaction" examples: default: "$ref": "#/components/examples/reaction" '201': description: Response content: application/json: schema: "$ref": "#/components/schemas/reaction" examples: default: "$ref": "#/components/examples/reaction" x-github: githubCloudOnly: false enabledForGitHubApps: false category: reactions previews: - required: true name: squirrel-girl note: |- An additional `reactions` object in the issue comment payload is currently available for developers to preview. During the preview period, the APIs may change without advance notice. Please see the [blog post](https://developer.github.com/changes/2016-05-12-reactions-api-preview) for full details. To access the API you must provide a custom [media type](https://docs.github.com/enterprise-server@3.0/rest/overview/media-types) in the `Accept` header: ```shell application/vnd.github.squirrel-girl-preview ``` The `reactions` key will have the following payload where `url` can be used to construct the API location for [listing and creating](https://docs.github.com/enterprise-server@3.0/rest/reference/reactions) reactions. "/orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/reactions/{reaction_id}": delete: summary: Delete team discussion reaction description: |- **Note:** You can also specify a team or organization with `team_id` and `org_id` using the route `DELETE /organizations/:org_id/team/:team_id/discussions/:discussion_number/reactions/:reaction_id`. Delete a reaction to a [team discussion](https://docs.github.com/enterprise-server@3.0/rest/reference/teams#discussions). OAuth access tokens require the `write:discussion` [scope](https://docs.github.com/enterprise-server@3.0/apps/building-oauth-apps/understanding-scopes-for-oauth-apps/). tags: - reactions operationId: reactions/delete-for-team-discussion externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/reactions#delete-team-discussion-reaction parameters: - "$ref": "#/components/parameters/org" - "$ref": "#/components/parameters/team-slug" - "$ref": "#/components/parameters/discussion-number" - "$ref": "#/components/parameters/reaction-id" responses: '204': description: Response x-github: githubCloudOnly: false enabledForGitHubApps: true category: reactions previews: - required: true name: squirrel-girl note: |- An additional `reactions` object in the issue comment payload is currently available for developers to preview. During the preview period, the APIs may change without advance notice. Please see the [blog post](https://developer.github.com/changes/2016-05-12-reactions-api-preview) for full details. To access the API you must provide a custom [media type](https://docs.github.com/enterprise-server@3.0/rest/overview/media-types) in the `Accept` header: ```shell application/vnd.github.squirrel-girl-preview ``` The `reactions` key will have the following payload where `url` can be used to construct the API location for [listing and creating](https://docs.github.com/enterprise-server@3.0/rest/reference/reactions) reactions. "/orgs/{org}/teams/{team_slug}/members": get: summary: List team members description: |- Team members will include the members of child teams. To list members in a team, the team must be visible to the authenticated user. tags: - teams operationId: teams/list-members-in-org externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/teams#list-team-members parameters: - "$ref": "#/components/parameters/org" - "$ref": "#/components/parameters/team-slug" - name: role description: "Filters members returned by their role in the team. Can be one of: \n\\* `member` - normal members of the team. \n\\* `maintainer` - team maintainers. \n\\* `all` - all members of the team." in: query required: false schema: type: string enum: - member - maintainer - all default: all - "$ref": "#/components/parameters/per-page" - "$ref": "#/components/parameters/page" responses: '200': description: Response content: application/json: schema: type: array items: "$ref": "#/components/schemas/simple-user" examples: default: "$ref": "#/components/examples/simple-user-items" headers: Link: "$ref": "#/components/headers/link" x-github: githubCloudOnly: false enabledForGitHubApps: true category: teams subcategory: members "/orgs/{org}/teams/{team_slug}/memberships/{username}": get: summary: Get team membership for a user description: |- Team members will include the members of child teams. To get a user's membership with a team, the team must be visible to the authenticated user. **Note:** You can also specify a team by `org_id` and `team_id` using the route `GET /organizations/{org_id}/team/{team_id}/memberships/{username}`. **Note:** The response contains the `state` of the membership and the member's `role`. The `role` for organization owners is set to `maintainer`. For more information about `maintainer` roles, see see [Create a team](https://docs.github.com/enterprise-server@3.0/rest/reference/teams#create-a-team). tags: - teams operationId: teams/get-membership-for-user-in-org externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/teams#get-team-membership-for-a-user parameters: - "$ref": "#/components/parameters/org" - "$ref": "#/components/parameters/team-slug" - "$ref": "#/components/parameters/username" responses: '200': description: Response content: application/json: schema: "$ref": "#/components/schemas/team-membership" examples: response-if-user-is-a-team-maintainer: "$ref": "#/components/examples/team-membership-response-if-user-is-a-team-maintainer" '404': description: if user has no team membership x-github: githubCloudOnly: false enabledForGitHubApps: true category: teams subcategory: members put: summary: Add or update team membership for a user description: |- Team synchronization is available for organizations using GitHub Enterprise Cloud. For more information, see [GitHub's products](https://docs.github.com/github/getting-started-with-github/githubs-products) in the GitHub Help documentation. Adds an organization member to a team. An authenticated organization owner or team maintainer can add organization members to a team. **Note:** When you have team synchronization set up for a team with your organization's identity provider (IdP), you will see an error if you attempt to use the API for making changes to the team's membership. If you have access to manage group membership in your IdP, you can manage GitHub Enterprise Server team membership through your identity provider, which automatically adds and removes team members in an organization. For more information, see "[Synchronizing teams between your identity provider and GitHub Enterprise Server](https://docs.github.com/articles/synchronizing-teams-between-your-identity-provider-and-github/)." An organization owner can add someone who is not part of the team's organization to a team. When an organization owner adds someone to a team who is not an organization member, this endpoint will send an invitation to the person via email. This newly-created membership will be in the "pending" state until the person accepts the invitation, at which point the membership will transition to the "active" state and the user will be added as a member of the team. If the user is already a member of the team, this endpoint will update the role of the team member's role. To update the membership of a team member, the authenticated user must be an organization owner or a team maintainer. **Note:** You can also specify a team by `org_id` and `team_id` using the route `PUT /organizations/{org_id}/team/{team_id}/memberships/{username}`. tags: - teams operationId: teams/add-or-update-membership-for-user-in-org externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/teams#add-or-update-team-membership-for-a-user parameters: - "$ref": "#/components/parameters/org" - "$ref": "#/components/parameters/team-slug" - "$ref": "#/components/parameters/username" requestBody: required: false content: application/json: schema: type: object properties: role: type: string description: "The role that this user should have in the team. Can be one of: \n\\* `member` - a normal member of the team. \n\\* `maintainer` - a team maintainer. Able to add/remove other team members, promote other team members to team maintainer, and edit the team's name and description." enum: - member - maintainer default: member responses: '200': description: Response content: application/json: schema: "$ref": "#/components/schemas/team-membership" examples: response-if-users-membership-with-team-is-now-pending: "$ref": "#/components/examples/team-membership-response-if-users-membership-with-team-is-now-pending" '403': description: Forbidden if team synchronization is set up '422': description: Unprocessable Entity if you attempt to add an organization to a team x-github: githubCloudOnly: false enabledForGitHubApps: true category: teams subcategory: members delete: summary: Remove team membership for a user description: |- Team synchronization is available for organizations using GitHub Enterprise Cloud. For more information, see [GitHub's products](https://docs.github.com/github/getting-started-with-github/githubs-products) in the GitHub Help documentation. To remove a membership between a user and a team, the authenticated user must have 'admin' permissions to the team or be an owner of the organization that the team is associated with. Removing team membership does not delete the user, it just removes their membership from the team. **Note:** When you have team synchronization set up for a team with your organization's identity provider (IdP), you will see an error if you attempt to use the API for making changes to the team's membership. If you have access to manage group membership in your IdP, you can manage GitHub Enterprise Server team membership through your identity provider, which automatically adds and removes team members in an organization. For more information, see "[Synchronizing teams between your identity provider and GitHub Enterprise Server](https://docs.github.com/articles/synchronizing-teams-between-your-identity-provider-and-github/)." **Note:** You can also specify a team by `org_id` and `team_id` using the route `DELETE /organizations/{org_id}/team/{team_id}/memberships/{username}`. tags: - teams operationId: teams/remove-membership-for-user-in-org externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/teams#remove-team-membership-for-a-user parameters: - "$ref": "#/components/parameters/org" - "$ref": "#/components/parameters/team-slug" - "$ref": "#/components/parameters/username" responses: '204': description: Response '403': description: Forbidden if team synchronization is set up x-github: githubCloudOnly: false enabledForGitHubApps: true category: teams subcategory: members "/orgs/{org}/teams/{team_slug}/projects": get: summary: List team projects description: |- Lists the organization projects for a team. **Note:** You can also specify a team by `org_id` and `team_id` using the route `GET /organizations/{org_id}/team/{team_id}/projects`. tags: - teams operationId: teams/list-projects-in-org externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/teams#list-team-projects parameters: - "$ref": "#/components/parameters/org" - "$ref": "#/components/parameters/team-slug" - "$ref": "#/components/parameters/per-page" - "$ref": "#/components/parameters/page" responses: '200': description: Response content: application/json: schema: type: array items: "$ref": "#/components/schemas/team-project" examples: default: "$ref": "#/components/examples/team-project-items" headers: Link: "$ref": "#/components/headers/link" x-github: githubCloudOnly: false enabledForGitHubApps: true category: teams previews: - required: true name: inertia note: |- The Projects API is currently available for developers to preview. During the preview period, the API may change without advance notice. Please see the [blog post](https://developer.github.com/changes/2016-10-27-changes-to-projects-api) for full details. To access the API during the preview period, you must provide a custom [media type](https://docs.github.com/enterprise-server@3.0/rest/overview/media-types) in the `Accept` header: ```shell application/vnd.github.inertia-preview+json ``` "/orgs/{org}/teams/{team_slug}/projects/{project_id}": get: summary: Check team permissions for a project description: |- Checks whether a team has `read`, `write`, or `admin` permissions for an organization project. The response includes projects inherited from a parent team. **Note:** You can also specify a team by `org_id` and `team_id` using the route `GET /organizations/{org_id}/team/{team_id}/projects/{project_id}`. tags: - teams operationId: teams/check-permissions-for-project-in-org externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/teams#check-team-permissions-for-a-project parameters: - "$ref": "#/components/parameters/org" - "$ref": "#/components/parameters/team-slug" - "$ref": "#/components/parameters/project-id" responses: '200': description: Response content: application/json: schema: "$ref": "#/components/schemas/team-project" examples: default: "$ref": "#/components/examples/team-project" '404': description: Not Found if project is not managed by this team x-github: githubCloudOnly: false enabledForGitHubApps: true category: teams previews: - required: true name: inertia note: |- The Projects API is currently available for developers to preview. During the preview period, the API may change without advance notice. Please see the [blog post](https://developer.github.com/changes/2016-10-27-changes-to-projects-api) for full details. To access the API during the preview period, you must provide a custom [media type](https://docs.github.com/enterprise-server@3.0/rest/overview/media-types) in the `Accept` header: ```shell application/vnd.github.inertia-preview+json ``` put: summary: Add or update team project permissions description: |- Adds an organization project to a team. To add a project to a team or update the team's permission on a project, the authenticated user must have `admin` permissions for the project. The project and team must be part of the same organization. **Note:** You can also specify a team by `org_id` and `team_id` using the route `PUT /organizations/{org_id}/team/{team_id}/projects/{project_id}`. tags: - teams operationId: teams/add-or-update-project-permissions-in-org externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/teams#add-or-update-team-project-permissions parameters: - "$ref": "#/components/parameters/org" - "$ref": "#/components/parameters/team-slug" - "$ref": "#/components/parameters/project-id" requestBody: required: false content: application/json: schema: type: - object - 'null' properties: permission: type: string description: "The permission to grant to the team for this project. Can be one of: \n\\* `read` - team members can read, but not write to or administer this project. \n\\* `write` - team members can read and write, but not administer this project. \n\\* `admin` - team members can read, write and administer this project. \nDefault: the team's `permission` attribute will be used to determine what permission to grant the team on this project. Note that, if you choose not to pass any parameters, you'll need to set `Content-Length` to zero when calling out to this endpoint. For more information, see \"[HTTP verbs](https://docs.github.com/enterprise-server@3.0/rest/overview/resources-in-the-rest-api#http-verbs).\"" enum: - read - write - admin responses: '204': description: Response '403': description: Forbidden if the project is not owned by the organization content: application/json: schema: type: object properties: message: type: string documentation_url: type: string examples: response-if-the-project-is-not-owned-by-the-organization: value: message: Must have admin rights to Repository. documentation_url: https://docs.github.com/enterprise-server@3.0/rest/reference/teams#add-or-update-team-project-permissions x-github: githubCloudOnly: false enabledForGitHubApps: true category: teams previews: - required: true name: inertia note: |- The Projects API is currently available for developers to preview. During the preview period, the API may change without advance notice. Please see the [blog post](https://developer.github.com/changes/2016-10-27-changes-to-projects-api) for full details. To access the API during the preview period, you must provide a custom [media type](https://docs.github.com/enterprise-server@3.0/rest/overview/media-types) in the `Accept` header: ```shell application/vnd.github.inertia-preview+json ``` delete: summary: Remove a project from a team description: |- Removes an organization project from a team. An organization owner or a team maintainer can remove any project from the team. To remove a project from a team as an organization member, the authenticated user must have `read` access to both the team and project, or `admin` access to the team or project. This endpoint removes the project from the team, but does not delete the project. **Note:** You can also specify a team by `org_id` and `team_id` using the route `DELETE /organizations/{org_id}/team/{team_id}/projects/{project_id}`. tags: - teams operationId: teams/remove-project-in-org externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/teams#remove-a-project-from-a-team parameters: - "$ref": "#/components/parameters/org" - "$ref": "#/components/parameters/team-slug" - "$ref": "#/components/parameters/project-id" responses: '204': description: Response x-github: githubCloudOnly: false enabledForGitHubApps: true category: teams subcategory: "/orgs/{org}/teams/{team_slug}/repos": get: summary: List team repositories description: |- Lists a team's repositories visible to the authenticated user. **Note:** You can also specify a team by `org_id` and `team_id` using the route `GET /organizations/{org_id}/team/{team_id}/repos`. tags: - teams operationId: teams/list-repos-in-org externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/teams#list-team-repositories parameters: - "$ref": "#/components/parameters/org" - "$ref": "#/components/parameters/team-slug" - "$ref": "#/components/parameters/per-page" - "$ref": "#/components/parameters/page" responses: '200': description: Response content: application/json: schema: type: array items: "$ref": "#/components/schemas/minimal-repository" examples: default: "$ref": "#/components/examples/minimal-repository-items" headers: Link: "$ref": "#/components/headers/link" x-github: githubCloudOnly: false enabledForGitHubApps: true category: teams subcategory: "/orgs/{org}/teams/{team_slug}/repos/{owner}/{repo}": get: summary: Check team permissions for a repository description: |- Checks whether a team has `admin`, `push`, `maintain`, `triage`, or `pull` permission for a repository. Repositories inherited through a parent team will also be checked. You can also get information about the specified repository, including what permissions the team grants on it, by passing the following custom [media type](https://docs.github.com/enterprise-server@3.0/rest/overview/media-types/) via the `application/vnd.github.v3.repository+json` accept header. If a team doesn't have permission for the repository, you will receive a `404 Not Found` response status. **Note:** You can also specify a team by `org_id` and `team_id` using the route `GET /organizations/{org_id}/team/{team_id}/repos/{owner}/{repo}`. tags: - teams operationId: teams/check-permissions-for-repo-in-org externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/teams/#check-team-permissions-for-a-repository parameters: - "$ref": "#/components/parameters/org" - "$ref": "#/components/parameters/team-slug" - "$ref": "#/components/parameters/owner" - "$ref": "#/components/parameters/repo" responses: '200': description: Alternative response with repository permissions content: application/json: schema: "$ref": "#/components/schemas/team-repository" examples: alternative-response-with-repository-permissions: "$ref": "#/components/examples/team-repository-alternative-response-with-repository-permissions" '204': description: Response if team has permission for the repository. This is the response when the repository media type hasn't been provded in the Accept header. '404': description: Not Found if team does not have permission for the repository x-github: githubCloudOnly: false enabledForGitHubApps: true category: teams subcategory: put: summary: Add or update team repository permissions description: |- To add a repository to a team or update the team's permission on a repository, the authenticated user must have admin access to the repository, and must be able to see the team. The repository must be owned by the organization, or a direct fork of a repository owned by the organization. You will get a `422 Unprocessable Entity` status if you attempt to add a repository to a team that is not owned by the organization. Note that, if you choose not to pass any parameters, you'll need to set `Content-Length` to zero when calling out to this endpoint. For more information, see "[HTTP verbs](https://docs.github.com/enterprise-server@3.0/rest/overview/resources-in-the-rest-api#http-verbs)." **Note:** You can also specify a team by `org_id` and `team_id` using the route `PUT /organizations/{org_id}/team/{team_id}/repos/{owner}/{repo}`. For more information about the permission levels, see "[Repository permission levels for an organization](https://docs.github.com/en/github/setting-up-and-managing-organizations-and-teams/repository-permission-levels-for-an-organization#permission-levels-for-repositories-owned-by-an-organization)". tags: - teams operationId: teams/add-or-update-repo-permissions-in-org externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/teams/#add-or-update-team-repository-permissions parameters: - "$ref": "#/components/parameters/org" - "$ref": "#/components/parameters/team-slug" - "$ref": "#/components/parameters/owner" - "$ref": "#/components/parameters/repo" requestBody: required: false content: application/json: schema: type: object properties: permission: type: string description: "The permission to grant the team on this repository. Can be one of: \n\\* `pull` - team members can pull, but not push to or administer this repository. \n\\* `push` - team members can pull and push, but not administer this repository. \n\\* `admin` - team members can pull, push and administer this repository. \ \n\\* `maintain` - team members can manage the repository without access to sensitive or destructive actions. Recommended for project managers. Only applies to repositories owned by organizations. \ \n\\* `triage` - team members can proactively manage issues and pull requests without write access. Recommended for contributors who triage a repository. Only applies to repositories owned by organizations. \n \nIf no permission is specified, the team's `permission` attribute will be used to determine what permission to grant the team on this repository." enum: - pull - push - admin - maintain - triage default: push responses: '204': description: Response x-github: githubCloudOnly: false enabledForGitHubApps: true category: teams subcategory: delete: summary: Remove a repository from a team description: |- If the authenticated user is an organization owner or a team maintainer, they can remove any repositories from the team. To remove a repository from a team as an organization member, the authenticated user must have admin access to the repository and must be able to see the team. This does not delete the repository, it just removes it from the team. **Note:** You can also specify a team by `org_id` and `team_id` using the route `DELETE /organizations/{org_id}/team/{team_id}/repos/{owner}/{repo}`. tags: - teams operationId: teams/remove-repo-in-org externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/teams/#remove-a-repository-from-a-team parameters: - "$ref": "#/components/parameters/org" - "$ref": "#/components/parameters/team-slug" - "$ref": "#/components/parameters/owner" - "$ref": "#/components/parameters/repo" responses: '204': description: Response x-github: githubCloudOnly: false enabledForGitHubApps: true category: teams subcategory: "/orgs/{org}/teams/{team_slug}/teams": get: summary: List child teams description: |- Lists the child teams of the team specified by `{team_slug}`. **Note:** You can also specify a team by `org_id` and `team_id` using the route `GET /organizations/{org_id}/team/{team_id}/teams`. tags: - teams operationId: teams/list-child-in-org externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/teams#list-child-teams parameters: - "$ref": "#/components/parameters/org" - "$ref": "#/components/parameters/team-slug" - "$ref": "#/components/parameters/per-page" - "$ref": "#/components/parameters/page" responses: '200': description: if child teams exist content: application/json: schema: type: array items: "$ref": "#/components/schemas/team" examples: response-if-child-teams-exist: "$ref": "#/components/examples/team-items-response-if-child-teams-exist" headers: Link: "$ref": "#/components/headers/link" x-github: githubCloudOnly: false enabledForGitHubApps: true category: teams subcategory: "/projects/columns/cards/{card_id}": get: summary: Get a project card description: '' tags: - projects operationId: projects/get-card externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/projects#get-a-project-card parameters: - "$ref": "#/components/parameters/card-id" responses: '200': description: Response content: application/json: schema: "$ref": "#/components/schemas/project-card" examples: default: "$ref": "#/components/examples/project-card" '304': "$ref": "#/components/responses/not_modified" '403': "$ref": "#/components/responses/forbidden" '401': "$ref": "#/components/responses/requires_authentication" '404': "$ref": "#/components/responses/not_found" x-github: githubCloudOnly: false enabledForGitHubApps: true category: projects subcategory: cards previews: - required: true name: inertia note: |- The Projects API is currently available for developers to preview. During the preview period, the API may change without advance notice. Please see the [blog post](https://developer.github.com/changes/2016-10-27-changes-to-projects-api) for full details. To access the API during the preview period, you must provide a custom [media type](https://docs.github.com/enterprise-server@3.0/rest/overview/media-types) in the `Accept` header: ```shell application/vnd.github.inertia-preview+json ``` patch: summary: Update an existing project card description: '' tags: - projects operationId: projects/update-card externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/projects#update-a-project-card parameters: - "$ref": "#/components/parameters/card-id" requestBody: required: false content: application/json: schema: type: object properties: note: description: The project card's note type: - string - 'null' examples: - Update all gems archived: description: Whether or not the card is archived type: boolean examples: - false responses: '200': description: Response content: application/json: schema: "$ref": "#/components/schemas/project-card" examples: default: "$ref": "#/components/examples/project-card" '304': "$ref": "#/components/responses/not_modified" '403': "$ref": "#/components/responses/forbidden" '401': "$ref": "#/components/responses/requires_authentication" '404': "$ref": "#/components/responses/not_found" '422': "$ref": "#/components/responses/validation_failed_simple" x-github: githubCloudOnly: false enabledForGitHubApps: true category: projects subcategory: cards previews: - required: true name: inertia note: |- The Projects API is currently available for developers to preview. During the preview period, the API may change without advance notice. Please see the [blog post](https://developer.github.com/changes/2016-10-27-changes-to-projects-api) for full details. To access the API during the preview period, you must provide a custom [media type](https://docs.github.com/enterprise-server@3.0/rest/overview/media-types) in the `Accept` header: ```shell application/vnd.github.inertia-preview+json ``` delete: summary: Delete a project card description: '' tags: - projects operationId: projects/delete-card externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/projects#delete-a-project-card parameters: - "$ref": "#/components/parameters/card-id" responses: '204': description: Response '304': "$ref": "#/components/responses/not_modified" '403': description: Forbidden content: application/json: schema: type: object properties: message: type: string documentation_url: type: string errors: type: array items: type: string '401': "$ref": "#/components/responses/requires_authentication" '404': "$ref": "#/components/responses/not_found" x-github: githubCloudOnly: false enabledForGitHubApps: true category: projects subcategory: cards previews: - required: true name: inertia note: |- The Projects API is currently available for developers to preview. During the preview period, the API may change without advance notice. Please see the [blog post](https://developer.github.com/changes/2016-10-27-changes-to-projects-api) for full details. To access the API during the preview period, you must provide a custom [media type](https://docs.github.com/enterprise-server@3.0/rest/overview/media-types) in the `Accept` header: ```shell application/vnd.github.inertia-preview+json ``` "/projects/columns/cards/{card_id}/moves": post: summary: Move a project card description: '' tags: - projects operationId: projects/move-card externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/projects#move-a-project-card parameters: - "$ref": "#/components/parameters/card-id" requestBody: required: true content: application/json: schema: properties: position: description: 'The position of the card in a column. Can be one of: `top`, `bottom`, or `after:` to place after the specified card.' type: string pattern: "^(?:top|bottom|after:\\d+)$" examples: - bottom column_id: description: The unique identifier of the column the card should be moved to type: integer examples: - 42 required: - position type: object responses: '201': description: Response content: application/json: schema: type: object properties: {} additionalProperties: false '304': "$ref": "#/components/responses/not_modified" '403': description: Forbidden content: application/json: schema: type: object properties: message: type: string documentation_url: type: string errors: type: array items: type: object properties: code: type: string message: type: string resource: type: string field: type: string '401': "$ref": "#/components/responses/requires_authentication" '503': description: Response content: application/json: schema: type: object properties: code: type: string message: type: string documentation_url: type: string errors: type: array items: type: object properties: code: type: string message: type: string '422': "$ref": "#/components/responses/validation_failed" x-github: githubCloudOnly: false enabledForGitHubApps: true category: projects subcategory: cards previews: - required: true name: inertia note: |- The Projects API is currently available for developers to preview. During the preview period, the API may change without advance notice. Please see the [blog post](https://developer.github.com/changes/2016-10-27-changes-to-projects-api) for full details. To access the API during the preview period, you must provide a custom [media type](https://docs.github.com/enterprise-server@3.0/rest/overview/media-types) in the `Accept` header: ```shell application/vnd.github.inertia-preview+json ``` "/projects/columns/{column_id}": get: summary: Get a project column description: '' tags: - projects operationId: projects/get-column externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/projects#get-a-project-column parameters: - "$ref": "#/components/parameters/column-id" responses: '200': description: Response content: application/json: schema: "$ref": "#/components/schemas/project-column" examples: default: "$ref": "#/components/examples/project-column" '304': "$ref": "#/components/responses/not_modified" '403': "$ref": "#/components/responses/forbidden" '404': "$ref": "#/components/responses/not_found" '401': "$ref": "#/components/responses/requires_authentication" x-github: githubCloudOnly: false enabledForGitHubApps: true category: projects subcategory: columns previews: - required: true name: inertia note: |- The Projects API is currently available for developers to preview. During the preview period, the API may change without advance notice. Please see the [blog post](https://developer.github.com/changes/2016-10-27-changes-to-projects-api) for full details. To access the API during the preview period, you must provide a custom [media type](https://docs.github.com/enterprise-server@3.0/rest/overview/media-types) in the `Accept` header: ```shell application/vnd.github.inertia-preview+json ``` patch: summary: Update an existing project column description: '' tags: - projects operationId: projects/update-column externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/projects#update-a-project-column parameters: - "$ref": "#/components/parameters/column-id" requestBody: required: true content: application/json: schema: properties: name: description: Name of the project column type: string examples: - Remaining tasks required: - name type: object responses: '200': description: Response content: application/json: schema: "$ref": "#/components/schemas/project-column" examples: default: "$ref": "#/components/examples/project-column" '304': "$ref": "#/components/responses/not_modified" '403': "$ref": "#/components/responses/forbidden" '401': "$ref": "#/components/responses/requires_authentication" x-github: githubCloudOnly: false enabledForGitHubApps: true category: projects subcategory: columns previews: - required: true name: inertia note: |- The Projects API is currently available for developers to preview. During the preview period, the API may change without advance notice. Please see the [blog post](https://developer.github.com/changes/2016-10-27-changes-to-projects-api) for full details. To access the API during the preview period, you must provide a custom [media type](https://docs.github.com/enterprise-server@3.0/rest/overview/media-types) in the `Accept` header: ```shell application/vnd.github.inertia-preview+json ``` delete: summary: Delete a project column description: '' tags: - projects operationId: projects/delete-column externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/projects#delete-a-project-column parameters: - "$ref": "#/components/parameters/column-id" responses: '204': description: Response '304': "$ref": "#/components/responses/not_modified" '403': "$ref": "#/components/responses/forbidden" '401': "$ref": "#/components/responses/requires_authentication" x-github: githubCloudOnly: false enabledForGitHubApps: true category: projects subcategory: columns previews: - required: true name: inertia note: |- The Projects API is currently available for developers to preview. During the preview period, the API may change without advance notice. Please see the [blog post](https://developer.github.com/changes/2016-10-27-changes-to-projects-api) for full details. To access the API during the preview period, you must provide a custom [media type](https://docs.github.com/enterprise-server@3.0/rest/overview/media-types) in the `Accept` header: ```shell application/vnd.github.inertia-preview+json ``` "/projects/columns/{column_id}/cards": get: summary: List project cards description: '' tags: - projects operationId: projects/list-cards externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/projects#list-project-cards parameters: - "$ref": "#/components/parameters/column-id" - name: archived_state description: Filters the project cards that are returned by the card's state. Can be one of `all`,`archived`, or `not_archived`. in: query required: false schema: type: string enum: - all - archived - not_archived default: not_archived - "$ref": "#/components/parameters/per-page" - "$ref": "#/components/parameters/page" responses: '200': description: Response content: application/json: schema: type: array items: "$ref": "#/components/schemas/project-card" examples: default: "$ref": "#/components/examples/project-card-items" headers: Link: "$ref": "#/components/headers/link" '304': "$ref": "#/components/responses/not_modified" '403': "$ref": "#/components/responses/forbidden" '401': "$ref": "#/components/responses/requires_authentication" x-github: githubCloudOnly: false enabledForGitHubApps: true category: projects subcategory: cards previews: - required: true name: inertia note: |- The Projects API is currently available for developers to preview. During the preview period, the API may change without advance notice. Please see the [blog post](https://developer.github.com/changes/2016-10-27-changes-to-projects-api) for full details. To access the API during the preview period, you must provide a custom [media type](https://docs.github.com/enterprise-server@3.0/rest/overview/media-types) in the `Accept` header: ```shell application/vnd.github.inertia-preview+json ``` post: summary: Create a project card description: '' tags: - projects operationId: projects/create-card externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/projects#create-a-project-card parameters: - "$ref": "#/components/parameters/column-id" requestBody: required: true content: application/json: schema: oneOf: - type: object properties: note: description: The project card's note type: - string - 'null' examples: - Update all gems required: - note - type: object properties: content_id: description: The unique identifier of the content associated with the card type: integer examples: - 42 content_type: description: The piece of content associated with the card type: string examples: - PullRequest required: - content_id - content_type responses: '201': description: Response content: application/json: schema: "$ref": "#/components/schemas/project-card" examples: default: "$ref": "#/components/examples/project-card" '304': "$ref": "#/components/responses/not_modified" '403': "$ref": "#/components/responses/forbidden" '401': "$ref": "#/components/responses/requires_authentication" '422': description: Validation failed content: application/json: schema: oneOf: - "$ref": "#/components/schemas/validation-error" - "$ref": "#/components/schemas/validation-error-simple" '503': description: Response content: application/json: schema: type: object properties: code: type: string message: type: string documentation_url: type: string errors: type: array items: type: object properties: code: type: string message: type: string x-github: githubCloudOnly: false enabledForGitHubApps: true category: projects subcategory: cards previews: - required: true name: inertia note: |- The Projects API is currently available for developers to preview. During the preview period, the API may change without advance notice. Please see the [blog post](https://developer.github.com/changes/2016-10-27-changes-to-projects-api) for full details. To access the API during the preview period, you must provide a custom [media type](https://docs.github.com/enterprise-server@3.0/rest/overview/media-types) in the `Accept` header: ```shell application/vnd.github.inertia-preview+json ``` "/projects/columns/{column_id}/moves": post: summary: Move a project column description: '' tags: - projects operationId: projects/move-column externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/projects#move-a-project-column parameters: - "$ref": "#/components/parameters/column-id" requestBody: required: true content: application/json: schema: properties: position: description: 'The position of the column in a project. Can be one of: `first`, `last`, or `after:` to place after the specified column.' type: string pattern: "^(?:first|last|after:\\d+)$" examples: - last required: - position type: object responses: '201': description: Response content: application/json: schema: type: object properties: {} additionalProperties: false '304': "$ref": "#/components/responses/not_modified" '403': "$ref": "#/components/responses/forbidden" '422': "$ref": "#/components/responses/validation_failed_simple" '401': "$ref": "#/components/responses/requires_authentication" x-github: githubCloudOnly: false enabledForGitHubApps: true category: projects subcategory: columns previews: - required: true name: inertia note: |- The Projects API is currently available for developers to preview. During the preview period, the API may change without advance notice. Please see the [blog post](https://developer.github.com/changes/2016-10-27-changes-to-projects-api) for full details. To access the API during the preview period, you must provide a custom [media type](https://docs.github.com/enterprise-server@3.0/rest/overview/media-types) in the `Accept` header: ```shell application/vnd.github.inertia-preview+json ``` "/projects/{project_id}": get: summary: Get a project description: Gets a project by its `id`. Returns a `404 Not Found` status if projects are disabled. If you do not have sufficient privileges to perform this action, a `401 Unauthorized` or `410 Gone` status is returned. tags: - projects operationId: projects/get externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/projects#get-a-project parameters: - "$ref": "#/components/parameters/project-id" responses: '200': description: Response content: application/json: schema: "$ref": "#/components/schemas/project" examples: default: "$ref": "#/components/examples/project-3" '304': "$ref": "#/components/responses/not_modified" '403': "$ref": "#/components/responses/forbidden" '401': "$ref": "#/components/responses/requires_authentication" x-github: githubCloudOnly: false enabledForGitHubApps: true category: projects previews: - required: true name: inertia note: |- The Projects API is currently available for developers to preview. During the preview period, the API may change without advance notice. Please see the [blog post](https://developer.github.com/changes/2016-10-27-changes-to-projects-api) for full details. To access the API during the preview period, you must provide a custom [media type](https://docs.github.com/enterprise-server@3.0/rest/overview/media-types) in the `Accept` header: ```shell application/vnd.github.inertia-preview+json ``` patch: summary: Update a project description: Updates a project board's information. Returns a `404 Not Found` status if projects are disabled. If you do not have sufficient privileges to perform this action, a `401 Unauthorized` or `410 Gone` status is returned. operationId: projects/update tags: - projects externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/projects#update-a-project parameters: - "$ref": "#/components/parameters/project-id" requestBody: required: false content: application/json: schema: properties: name: description: Name of the project type: string examples: - Week One Sprint body: description: Body of the project type: - string - 'null' examples: - This project represents the sprint of the first week in January state: description: State of the project; either 'open' or 'closed' type: string examples: - open organization_permission: description: The baseline permission that all organization members have on this project type: string enum: - read - write - admin - none private: description: Whether or not this project can be seen by everyone. type: boolean type: object responses: '200': description: Response content: application/json: schema: "$ref": "#/components/schemas/project" examples: default: "$ref": "#/components/examples/project-3" '404': description: Not Found if the authenticated user does not have access to the project '304': "$ref": "#/components/responses/not_modified" '403': description: Forbidden content: application/json: schema: type: object properties: message: type: string documentation_url: type: string errors: type: array items: type: string '401': "$ref": "#/components/responses/requires_authentication" '410': "$ref": "#/components/responses/gone" '422': "$ref": "#/components/responses/validation_failed_simple" x-github: githubCloudOnly: false enabledForGitHubApps: true category: projects previews: - required: true name: inertia note: |- The Projects API is currently available for developers to preview. During the preview period, the API may change without advance notice. Please see the [blog post](https://developer.github.com/changes/2016-10-27-changes-to-projects-api) for full details. To access the API during the preview period, you must provide a custom [media type](https://docs.github.com/enterprise-server@3.0/rest/overview/media-types) in the `Accept` header: ```shell application/vnd.github.inertia-preview+json ``` delete: summary: Delete a project description: Deletes a project board. Returns a `404 Not Found` status if projects are disabled. operationId: projects/delete tags: - projects externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/projects#delete-a-project parameters: - "$ref": "#/components/parameters/project-id" responses: '204': description: Delete Success '304': "$ref": "#/components/responses/not_modified" '403': description: Forbidden content: application/json: schema: type: object properties: message: type: string documentation_url: type: string errors: type: array items: type: string '401': "$ref": "#/components/responses/requires_authentication" '410': "$ref": "#/components/responses/gone" '404': "$ref": "#/components/responses/not_found" x-github: githubCloudOnly: false enabledForGitHubApps: true category: projects previews: - required: true name: inertia note: |- The Projects API is currently available for developers to preview. During the preview period, the API may change without advance notice. Please see the [blog post](https://developer.github.com/changes/2016-10-27-changes-to-projects-api) for full details. To access the API during the preview period, you must provide a custom [media type](https://docs.github.com/enterprise-server@3.0/rest/overview/media-types) in the `Accept` header: ```shell application/vnd.github.inertia-preview+json ``` "/projects/{project_id}/collaborators": get: summary: List project collaborators description: Lists the collaborators for an organization project. For a project, the list of collaborators includes outside collaborators, organization members that are direct collaborators, organization members with access through team memberships, organization members with access through default organization permissions, and organization owners. You must be an organization owner or a project `admin` to list collaborators. tags: - projects operationId: projects/list-collaborators externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/projects#list-project-collaborators parameters: - "$ref": "#/components/parameters/project-id" - name: affiliation description: "Filters the collaborators by their affiliation. Can be one of: \ \n\\* `outside`: Outside collaborators of a project that are not a member of the project's organization. \n\\* `direct`: Collaborators with permissions to a project, regardless of organization membership status. \n\\* `all`: All collaborators the authenticated user can see." in: query required: false schema: type: string enum: - outside - direct - all default: all - "$ref": "#/components/parameters/per-page" - "$ref": "#/components/parameters/page" responses: '200': description: Response content: application/json: schema: type: array items: "$ref": "#/components/schemas/simple-user" examples: default: "$ref": "#/components/examples/simple-user-items" headers: Link: "$ref": "#/components/headers/link" '404': "$ref": "#/components/responses/not_found" '422': "$ref": "#/components/responses/validation_failed" '304': "$ref": "#/components/responses/not_modified" '403': "$ref": "#/components/responses/forbidden" '401': "$ref": "#/components/responses/requires_authentication" x-github: githubCloudOnly: false enabledForGitHubApps: true category: projects subcategory: collaborators previews: - required: true name: inertia note: |- The Projects API is currently available for developers to preview. During the preview period, the API may change without advance notice. Please see the [blog post](https://developer.github.com/changes/2016-10-27-changes-to-projects-api) for full details. To access the API during the preview period, you must provide a custom [media type](https://docs.github.com/enterprise-server@3.0/rest/overview/media-types) in the `Accept` header: ```shell application/vnd.github.inertia-preview+json ``` "/projects/{project_id}/collaborators/{username}": put: summary: Add project collaborator description: Adds a collaborator to an organization project and sets their permission level. You must be an organization owner or a project `admin` to add a collaborator. tags: - projects operationId: projects/add-collaborator externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/projects#add-project-collaborator parameters: - "$ref": "#/components/parameters/project-id" - "$ref": "#/components/parameters/username" requestBody: required: false content: application/json: schema: type: - object - 'null' properties: permission: description: The permission to grant the collaborator. enum: - read - write - admin default: write type: string examples: - write responses: '204': description: Response '404': "$ref": "#/components/responses/not_found" '422': "$ref": "#/components/responses/validation_failed" '304': "$ref": "#/components/responses/not_modified" '403': "$ref": "#/components/responses/forbidden" '401': "$ref": "#/components/responses/requires_authentication" x-github: githubCloudOnly: false enabledForGitHubApps: true category: projects subcategory: collaborators previews: - required: true name: inertia note: |- The Projects API is currently available for developers to preview. During the preview period, the API may change without advance notice. Please see the [blog post](https://developer.github.com/changes/2016-10-27-changes-to-projects-api) for full details. To access the API during the preview period, you must provide a custom [media type](https://docs.github.com/enterprise-server@3.0/rest/overview/media-types) in the `Accept` header: ```shell application/vnd.github.inertia-preview+json ``` delete: summary: Remove user as a collaborator description: Removes a collaborator from an organization project. You must be an organization owner or a project `admin` to remove a collaborator. tags: - projects operationId: projects/remove-collaborator externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/projects#remove-project-collaborator parameters: - "$ref": "#/components/parameters/project-id" - "$ref": "#/components/parameters/username" responses: '204': description: Response '304': "$ref": "#/components/responses/not_modified" '404': "$ref": "#/components/responses/not_found" '403': "$ref": "#/components/responses/forbidden" '422': "$ref": "#/components/responses/validation_failed" '401': "$ref": "#/components/responses/requires_authentication" x-github: githubCloudOnly: false enabledForGitHubApps: true category: projects subcategory: collaborators previews: - required: true name: inertia note: |- The Projects API is currently available for developers to preview. During the preview period, the API may change without advance notice. Please see the [blog post](https://developer.github.com/changes/2016-10-27-changes-to-projects-api) for full details. To access the API during the preview period, you must provide a custom [media type](https://docs.github.com/enterprise-server@3.0/rest/overview/media-types) in the `Accept` header: ```shell application/vnd.github.inertia-preview+json ``` "/projects/{project_id}/collaborators/{username}/permission": get: summary: Get project permission for a user description: 'Returns the collaborator''s permission level for an organization project. Possible values for the `permission` key: `admin`, `write`, `read`, `none`. You must be an organization owner or a project `admin` to review a user''s permission level.' tags: - projects operationId: projects/get-permission-for-user externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/projects#get-project-permission-for-a-user parameters: - "$ref": "#/components/parameters/project-id" - "$ref": "#/components/parameters/username" responses: '200': description: Response content: application/json: schema: "$ref": "#/components/schemas/project-collaborator-permission" examples: default: "$ref": "#/components/examples/project-collaborator-permission" '404': "$ref": "#/components/responses/not_found" '422': "$ref": "#/components/responses/validation_failed" '304': "$ref": "#/components/responses/not_modified" '403': "$ref": "#/components/responses/forbidden" '401': "$ref": "#/components/responses/requires_authentication" x-github: githubCloudOnly: false enabledForGitHubApps: true category: projects subcategory: collaborators previews: - required: true name: inertia note: |- The Projects API is currently available for developers to preview. During the preview period, the API may change without advance notice. Please see the [blog post](https://developer.github.com/changes/2016-10-27-changes-to-projects-api) for full details. To access the API during the preview period, you must provide a custom [media type](https://docs.github.com/enterprise-server@3.0/rest/overview/media-types) in the `Accept` header: ```shell application/vnd.github.inertia-preview+json ``` "/projects/{project_id}/columns": get: summary: List project columns description: '' tags: - projects operationId: projects/list-columns externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/projects#list-project-columns parameters: - "$ref": "#/components/parameters/project-id" - "$ref": "#/components/parameters/per-page" - "$ref": "#/components/parameters/page" responses: '200': description: Response content: application/json: schema: type: array items: "$ref": "#/components/schemas/project-column" examples: default: "$ref": "#/components/examples/project-column-items" headers: Link: "$ref": "#/components/headers/link" '304': "$ref": "#/components/responses/not_modified" '403': "$ref": "#/components/responses/forbidden" '401': "$ref": "#/components/responses/requires_authentication" x-github: githubCloudOnly: false enabledForGitHubApps: true category: projects subcategory: columns previews: - required: true name: inertia note: |- The Projects API is currently available for developers to preview. During the preview period, the API may change without advance notice. Please see the [blog post](https://developer.github.com/changes/2016-10-27-changes-to-projects-api) for full details. To access the API during the preview period, you must provide a custom [media type](https://docs.github.com/enterprise-server@3.0/rest/overview/media-types) in the `Accept` header: ```shell application/vnd.github.inertia-preview+json ``` post: summary: Create a project column description: '' tags: - projects operationId: projects/create-column externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/projects#create-a-project-column parameters: - "$ref": "#/components/parameters/project-id" requestBody: required: true content: application/json: schema: properties: name: description: Name of the project column type: string examples: - Remaining tasks required: - name type: object responses: '201': description: Response content: application/json: schema: "$ref": "#/components/schemas/project-column" example: url: https://api.github.com/projects/columns/367 project_url: https://api.github.com/projects/120 cards_url: https://api.github.com/projects/columns/367/cards id: 367 node_id: MDEzOlByb2plY3RDb2x1bW4zNjc= name: To Do created_at: '2016-09-05T14:18:44Z' updated_at: '2016-09-05T14:22:28Z' '304': "$ref": "#/components/responses/not_modified" '403': "$ref": "#/components/responses/forbidden" '422': "$ref": "#/components/responses/validation_failed_simple" '401': "$ref": "#/components/responses/requires_authentication" x-github: githubCloudOnly: false enabledForGitHubApps: true category: projects subcategory: columns previews: - required: true name: inertia note: |- The Projects API is currently available for developers to preview. During the preview period, the API may change without advance notice. Please see the [blog post](https://developer.github.com/changes/2016-10-27-changes-to-projects-api) for full details. To access the API during the preview period, you must provide a custom [media type](https://docs.github.com/enterprise-server@3.0/rest/overview/media-types) in the `Accept` header: ```shell application/vnd.github.inertia-preview+json ``` "/rate_limit": get: summary: Get rate limit status for the authenticated user description: |- **Note:** Accessing this endpoint does not count against your REST API rate limit. **Note:** The `rate` object is deprecated. If you're writing new API client code or updating existing code, you should use the `core` object instead of the `rate` object. The `core` object contains the same information that is present in the `rate` object. tags: - rate-limit operationId: rate-limit/get externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/rate-limit#get-rate-limit-status-for-the-authenticated-user parameters: [] responses: '200': description: Response content: application/json: schema: "$ref": "#/components/schemas/rate-limit-overview" examples: default: "$ref": "#/components/examples/rate-limit-overview" headers: X-RateLimit-Limit: "$ref": "#/components/headers/x-rate-limit-limit" X-RateLimit-Remaining: "$ref": "#/components/headers/x-rate-limit-remaining" X-RateLimit-Reset: "$ref": "#/components/headers/x-rate-limit-reset" '304': "$ref": "#/components/responses/not_modified" '404': "$ref": "#/components/responses/not_found" x-github: githubCloudOnly: false enabledForGitHubApps: true category: rate-limit subcategory: "/reactions/{reaction_id}": delete: summary: Delete a reaction (Legacy) description: |- **Deprecation Notice:** This endpoint route is deprecated and will be removed from the Reactions API. We recommend migrating your existing code to use the new delete reactions endpoints. For more information, see this [blog post](https://developer.github.com/changes/2020-02-26-new-delete-reactions-endpoints/). OAuth access tokens require the `write:discussion` [scope](https://docs.github.com/enterprise-server@3.0/apps/building-oauth-apps/understanding-scopes-for-oauth-apps/), when deleting a [team discussion](https://docs.github.com/enterprise-server@3.0/rest/reference/teams#discussions) or [team discussion comment](https://docs.github.com/enterprise-server@3.0/rest/reference/teams#discussion-comments). tags: - reactions operationId: reactions/delete-legacy externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/reactions/#delete-a-reaction-legacy parameters: - "$ref": "#/components/parameters/reaction-id" responses: '204': description: Response '304': "$ref": "#/components/responses/not_modified" '403': "$ref": "#/components/responses/forbidden" '401': "$ref": "#/components/responses/requires_authentication" '410': "$ref": "#/components/responses/gone" x-github: githubCloudOnly: false enabledForGitHubApps: true removalDate: '2021-02-21' deprecationDate: '2020-02-26' category: reactions previews: - required: true name: squirrel-girl note: |- An additional `reactions` object in the issue comment payload is currently available for developers to preview. During the preview period, the APIs may change without advance notice. Please see the [blog post](https://developer.github.com/changes/2016-05-12-reactions-api-preview) for full details. To access the API you must provide a custom [media type](https://docs.github.com/enterprise-server@3.0/rest/overview/media-types) in the `Accept` header: ```shell application/vnd.github.squirrel-girl-preview ``` The `reactions` key will have the following payload where `url` can be used to construct the API location for [listing and creating](https://docs.github.com/enterprise-server@3.0/rest/reference/reactions) reactions. deprecated: true "/repos/{owner}/{repo}": get: summary: Get a repository description: |- When you pass the `scarlet-witch-preview` media type, requests to get a repository will also return the repository's code of conduct if it can be detected from the repository's code of conduct file. The `parent` and `source` objects are present when the repository is a fork. `parent` is the repository this repository was forked from, `source` is the ultimate source for the network. tags: - repos operationId: repos/get externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/repos#get-a-repository parameters: - "$ref": "#/components/parameters/owner" - "$ref": "#/components/parameters/repo" responses: '200': description: Response content: application/json: schema: "$ref": "#/components/schemas/full-repository" examples: default-response: "$ref": "#/components/examples/full-repository-default-response" response-with-scarlet-witch-preview-media-type: "$ref": "#/components/examples/full-repository-response-with-scarlet-witch-preview-media-type" '403': "$ref": "#/components/responses/forbidden" '404': "$ref": "#/components/responses/not_found" '301': "$ref": "#/components/responses/moved_permanently" x-github: githubCloudOnly: false enabledForGitHubApps: true category: repos previews: - required: false name: nebula note: |- You can set the visibility of a repository using the new `visibility` parameter in the [Repositories API](https://docs.github.com/enterprise-server@3.0/rest/reference/repos/), and get a repository's visibility with a new response key. For more information, see the [blog post](https://developer.github.com/changes/2019-12-03-internal-visibility-changes/). To access repository visibility during the preview period, you must provide a custom [media type](https://docs.github.com/enterprise-server@3.0/rest/overview/media-types) in the `Accept` header: ```shell application/vnd.github.nebula-preview+json ``` - required: false name: scarlet-witch note: |- The Codes of Conduct API is currently available for developers to preview. To access the API during the preview period, you must provide a custom [media type](https://docs.github.com/enterprise-server@3.0/rest/overview/media-types) in the `Accept` header: ```shell application/vnd.github.scarlet-witch-preview+json ``` patch: summary: Update a repository description: "**Note**: To edit a repository's topics, use the [Replace all repository topics](https://docs.github.com/enterprise-server@3.0/rest/reference/repos#replace-all-repository-topics) endpoint." tags: - repos operationId: repos/update externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/repos/#update-a-repository parameters: - "$ref": "#/components/parameters/owner" - "$ref": "#/components/parameters/repo" requestBody: required: false content: application/json: schema: type: object properties: name: type: string description: The name of the repository. description: type: string description: A short description of the repository. homepage: type: string description: A URL with more information about the repository. private: type: boolean description: "Either `true` to make the repository private or `false` to make it public. Default: `false`. \n**Note**: You will get a `422` error if the organization restricts [changing repository visibility](https://docs.github.com/articles/repository-permission-levels-for-an-organization#changing-the-visibility-of-repositories) to organization owners and a non-owner tries to change the value of private. **Note**: You will get a `422` error if the organization restricts [changing repository visibility](https://docs.github.com/articles/repository-permission-levels-for-an-organization#changing-the-visibility-of-repositories) to organization owners and a non-owner tries to change the value of private." default: false visibility: type: string description: Can be `public` or `private`. If your organization is associated with an enterprise account using GitHub Enterprise Cloud or GitHub Enterprise Server 2.20+, `visibility` can also be `internal`." enum: - public - private - internal has_issues: type: boolean description: Either `true` to enable issues for this repository or `false` to disable them. default: true has_projects: type: boolean description: Either `true` to enable projects for this repository or `false` to disable them. **Note:** If you're creating a repository in an organization that has disabled repository projects, the default is `false`, and if you pass `true`, the API returns an error. default: true has_wiki: type: boolean description: Either `true` to enable the wiki for this repository or `false` to disable it. default: true is_template: type: boolean description: Either `true` to make this repo available as a template repository or `false` to prevent it. default: false default_branch: type: string description: Updates the default branch for this repository. allow_squash_merge: type: boolean description: Either `true` to allow squash-merging pull requests, or `false` to prevent squash-merging. default: true allow_merge_commit: type: boolean description: Either `true` to allow merging pull requests with a merge commit, or `false` to prevent merging pull requests with merge commits. default: true allow_rebase_merge: type: boolean description: Either `true` to allow rebase-merging pull requests, or `false` to prevent rebase-merging. default: true delete_branch_on_merge: type: boolean description: Either `true` to allow automatically deleting head branches when pull requests are merged, or `false` to prevent automatic deletion. default: false archived: type: boolean description: "`true` to archive this repository. **Note**: You cannot unarchive repositories through the API." default: false allow_forking: type: boolean description: Either `true` to allow private forks, or `false` to prevent private forks. default: false example: name: Hello-World description: This is your first repository homepage: https://github.com private: true has_issues: true has_projects: true has_wiki: true responses: '200': description: Response content: application/json: schema: "$ref": "#/components/schemas/full-repository" examples: default: "$ref": "#/components/examples/full-repository" '307': "$ref": "#/components/responses/temporary_redirect" '403': "$ref": "#/components/responses/forbidden" '422': "$ref": "#/components/responses/validation_failed" '404': "$ref": "#/components/responses/not_found" x-github: githubCloudOnly: false enabledForGitHubApps: true category: repos previews: - required: false name: nebula note: |- You can set the visibility of a repository using the new `visibility` parameter in the [Repositories API](https://docs.github.com/enterprise-server@3.0/rest/reference/repos/), and get a repository's visibility with a new response key. For more information, see the [blog post](https://developer.github.com/changes/2019-12-03-internal-visibility-changes/). To access repository visibility during the preview period, you must provide a custom [media type](https://docs.github.com/enterprise-server@3.0/rest/overview/media-types) in the `Accept` header: ```shell application/vnd.github.nebula-preview+json ``` - required: false name: baptiste note: |- The `is_template` and `template_repository` keys are currently available for developer to preview. See [Create a repository using a template](https://docs.github.com/enterprise-server@3.0/rest/reference/repos#create-a-repository-using-a-template) to learn how to create template repositories. To access these new response keys during the preview period, you must provide a custom [media type](https://docs.github.com/enterprise-server@3.0/rest/overview/media-types) in the `Accept` header: ```shell application/vnd.github.baptiste-preview+json ``` delete: summary: Delete a repository description: |- Deleting a repository requires admin access. If OAuth is used, the `delete_repo` scope is required. If an organization owner has configured the organization to prevent members from deleting organization-owned repositories, you will get a `403 Forbidden` response. tags: - repos operationId: repos/delete externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/repos#delete-a-repository parameters: - "$ref": "#/components/parameters/owner" - "$ref": "#/components/parameters/repo" responses: '204': description: Response '403': description: 'If an organization owner has configured the organization to prevent members from deleting organization-owned repositories, a member will get this response:' content: application/json: schema: type: object properties: message: type: string documentation_url: type: string example: message: Organization members cannot delete repositories. documentation_url: https://docs.github.com/enterprise-server@3.0/rest/reference/repos#delete-a-repository '307': "$ref": "#/components/responses/temporary_redirect" '404': "$ref": "#/components/responses/not_found" x-github: githubCloudOnly: false enabledForGitHubApps: true category: repos subcategory: "/repos/{owner}/{repo}/actions/artifacts": get: summary: List artifacts for a repository description: Lists all artifacts for a repository. Anyone with read access to the repository can use this endpoint. If the repository is private you must use an access token with the `repo` scope. GitHub Apps must have the `actions:read` permission to use this endpoint. tags: - actions operationId: actions/list-artifacts-for-repo externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/actions#list-artifacts-for-a-repository parameters: - "$ref": "#/components/parameters/owner" - "$ref": "#/components/parameters/repo" - "$ref": "#/components/parameters/per-page" - "$ref": "#/components/parameters/page" responses: '200': description: Response content: application/json: schema: type: object required: - total_count - artifacts properties: total_count: type: integer artifacts: type: array items: "$ref": "#/components/schemas/artifact" examples: default: "$ref": "#/components/examples/artifact-paginated" headers: Link: "$ref": "#/components/headers/link" x-github: githubCloudOnly: false enabledForGitHubApps: true category: actions subcategory: artifacts "/repos/{owner}/{repo}/actions/artifacts/{artifact_id}": get: summary: Get an artifact description: Gets a specific artifact for a workflow run. Anyone with read access to the repository can use this endpoint. If the repository is private you must use an access token with the `repo` scope. GitHub Apps must have the `actions:read` permission to use this endpoint. tags: - actions operationId: actions/get-artifact externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/actions#get-an-artifact parameters: - "$ref": "#/components/parameters/owner" - "$ref": "#/components/parameters/repo" - "$ref": "#/components/parameters/artifact-id" responses: '200': description: Response content: application/json: schema: "$ref": "#/components/schemas/artifact" examples: default: "$ref": "#/components/examples/artifact" x-github: githubCloudOnly: false enabledForGitHubApps: true category: actions subcategory: artifacts delete: summary: Delete an artifact description: Deletes an artifact for a workflow run. You must authenticate using an access token with the `repo` scope to use this endpoint. GitHub Apps must have the `actions:write` permission to use this endpoint. tags: - actions operationId: actions/delete-artifact externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/actions#delete-an-artifact parameters: - "$ref": "#/components/parameters/owner" - "$ref": "#/components/parameters/repo" - "$ref": "#/components/parameters/artifact-id" responses: '204': description: Response x-github: githubCloudOnly: false enabledForGitHubApps: true category: actions subcategory: artifacts "/repos/{owner}/{repo}/actions/artifacts/{artifact_id}/{archive_format}": get: summary: Download an artifact description: |- Gets a redirect URL to download an archive for a repository. This URL expires after 1 minute. Look for `Location:` in the response header to find the URL for the download. The `:archive_format` must be `zip`. Anyone with read access to the repository can use this endpoint. If the repository is private you must use an access token with the `repo` scope. GitHub Apps must have the `actions:read` permission to use this endpoint. tags: - actions operationId: actions/download-artifact externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/actions#download-an-artifact parameters: - "$ref": "#/components/parameters/owner" - "$ref": "#/components/parameters/repo" - "$ref": "#/components/parameters/artifact-id" - name: archive_format in: path required: true schema: type: string responses: '302': description: Response headers: Location: "$ref": "#/components/headers/location" x-github: githubCloudOnly: false enabledForGitHubApps: true category: actions subcategory: artifacts "/repos/{owner}/{repo}/actions/jobs/{job_id}": get: summary: Get a job for a workflow run description: Gets a specific job in a workflow run. Anyone with read access to the repository can use this endpoint. If the repository is private you must use an access token with the `repo` scope. GitHub Apps must have the `actions:read` permission to use this endpoint. tags: - actions operationId: actions/get-job-for-workflow-run externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/actions#get-a-job-for-a-workflow-run parameters: - "$ref": "#/components/parameters/owner" - "$ref": "#/components/parameters/repo" - "$ref": "#/components/parameters/job-id" responses: '200': description: Response content: application/json: schema: "$ref": "#/components/schemas/job" examples: default: "$ref": "#/components/examples/job" x-github: githubCloudOnly: false enabledForGitHubApps: true category: actions subcategory: workflow-jobs "/repos/{owner}/{repo}/actions/jobs/{job_id}/logs": get: summary: Download job logs for a workflow run description: |- Gets a redirect URL to download a plain text file of logs for a workflow job. This link expires after 1 minute. Look for `Location:` in the response header to find the URL for the download. Anyone with read access to the repository can use this endpoint. If the repository is private you must use an access token with the `repo` scope. GitHub Apps must have the `actions:read` permission to use this endpoint. tags: - actions operationId: actions/download-job-logs-for-workflow-run externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/actions#download-job-logs-for-a-workflow-run parameters: - "$ref": "#/components/parameters/owner" - "$ref": "#/components/parameters/repo" - "$ref": "#/components/parameters/job-id" responses: '302': description: Response headers: Location: example: https://pipelines.actions.githubusercontent.com/ab1f3cCFPB34Nd6imvFxpGZH5hNlDp2wijMwl2gDoO0bcrrlJj/_apis/pipelines/1/jobs/19/signedlogcontent?urlExpires=2020-01-22T22%3A44%3A54.1389777Z&urlSigningMethod=HMACV1&urlSignature=2TUDfIg4fm36OJmfPy6km5QD5DLCOkBVzvhWZM8B%2BUY%3D schema: type: string x-github: githubCloudOnly: false enabledForGitHubApps: true category: actions subcategory: workflow-jobs "/repos/{owner}/{repo}/actions/permissions": get: summary: Get GitHub Actions permissions for a repository description: |- Gets the GitHub Actions permissions policy for a repository, including whether GitHub Actions is enabled and the actions allowed to run in the repository. You must authenticate using an access token with the `repo` scope to use this endpoint. GitHub Apps must have the `administration` repository permission to use this API. operationId: actions/get-github-actions-permissions-repository tags: - actions externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/actions#get-github-actions-permissions-for-a-repository parameters: - "$ref": "#/components/parameters/owner" - "$ref": "#/components/parameters/repo" responses: '200': description: Response content: application/json: schema: "$ref": "#/components/schemas/actions-repository-permissions" examples: default: "$ref": "#/components/examples/actions-repository-permissions" x-github: enabledForGitHubApps: true githubCloudOnly: false category: actions subcategory: permissions put: summary: Set GitHub Actions permissions for a repository description: |- Sets the GitHub Actions permissions policy for enabling GitHub Actions and allowed actions in the repository. If the repository belongs to an organization or enterprise that has set restrictive permissions at the organization or enterprise levels, such as `allowed_actions` to `selected` actions, then you cannot override them for the repository. You must authenticate using an access token with the `repo` scope to use this endpoint. GitHub Apps must have the `administration` repository permission to use this API. operationId: actions/set-github-actions-permissions-repository tags: - actions externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/actions#set-github-actions-permissions-for-a-repository parameters: - "$ref": "#/components/parameters/owner" - "$ref": "#/components/parameters/repo" responses: '204': description: Response requestBody: required: true content: application/json: schema: type: object properties: enabled: "$ref": "#/components/schemas/actions-enabled" allowed_actions: "$ref": "#/components/schemas/allowed-actions" required: - enabled example: enabled: true allowed_actions: selected x-github: enabledForGitHubApps: true githubCloudOnly: false category: actions subcategory: permissions "/repos/{owner}/{repo}/actions/permissions/selected-actions": get: summary: Get allowed actions for a repository description: |- Gets the settings for selected actions that are allowed in a repository. To use this endpoint, the repository policy for `allowed_actions` must be configured to `selected`. For more information, see "[Set GitHub Actions permissions for a repository](#set-github-actions-permissions-for-a-repository)." You must authenticate using an access token with the `repo` scope to use this endpoint. GitHub Apps must have the `administration` repository permission to use this API. operationId: actions/get-allowed-actions-repository tags: - actions externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/actions#get-allowed-actions-for-a-repository parameters: - "$ref": "#/components/parameters/owner" - "$ref": "#/components/parameters/repo" responses: '200': description: Response content: application/json: schema: "$ref": "#/components/schemas/selected-actions" examples: default: "$ref": "#/components/examples/selected-actions" x-github: enabledForGitHubApps: true githubCloudOnly: false category: actions subcategory: permissions put: summary: Set allowed actions for a repository description: |- Sets the actions that are allowed in a repository. To use this endpoint, the repository permission policy for `allowed_actions` must be configured to `selected`. For more information, see "[Set GitHub Actions permissions for a repository](#set-github-actions-permissions-for-a-repository)." If the repository belongs to an organization or enterprise that has `selected` actions set at the organization or enterprise levels, then you cannot override any of the allowed actions settings. To use the `patterns_allowed` setting for private repositories, the repository must belong to an enterprise. If the repository does not belong to an enterprise, then the `patterns_allowed` setting only applies to public repositories. You must authenticate using an access token with the `repo` scope to use this endpoint. GitHub Apps must have the `administration` repository permission to use this API. operationId: actions/set-allowed-actions-repository tags: - actions externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/actions#set-allowed-actions-for-a-repository parameters: - "$ref": "#/components/parameters/owner" - "$ref": "#/components/parameters/repo" responses: '204': description: Response requestBody: required: false content: application/json: schema: "$ref": "#/components/schemas/selected-actions" examples: selected_actions: "$ref": "#/components/examples/selected-actions" x-github: enabledForGitHubApps: true githubCloudOnly: false category: actions subcategory: permissions "/repos/{owner}/{repo}/actions/runners": get: summary: List self-hosted runners for a repository description: Lists all self-hosted runners configured in a repository. You must authenticate using an access token with the `repo` scope to use this endpoint. tags: - actions operationId: actions/list-self-hosted-runners-for-repo externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/actions#list-self-hosted-runners-for-a-repository parameters: - "$ref": "#/components/parameters/owner" - "$ref": "#/components/parameters/repo" - "$ref": "#/components/parameters/per-page" - "$ref": "#/components/parameters/page" responses: '200': description: Response content: application/json: schema: type: object required: - total_count - runners properties: total_count: type: integer runners: type: array items: "$ref": "#/components/schemas/runner" examples: default: "$ref": "#/components/examples/runner-paginated" headers: Link: "$ref": "#/components/headers/link" x-github: githubCloudOnly: false enabledForGitHubApps: true category: actions subcategory: self-hosted-runners "/repos/{owner}/{repo}/actions/runners/downloads": get: summary: List runner applications for a repository description: |- Lists binaries for the runner application that you can download and run. You must authenticate using an access token with the `repo` scope to use this endpoint. tags: - actions operationId: actions/list-runner-applications-for-repo externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/actions#list-runner-applications-for-a-repository parameters: - "$ref": "#/components/parameters/owner" - "$ref": "#/components/parameters/repo" responses: '200': description: Response content: application/json: schema: type: array items: "$ref": "#/components/schemas/runner-application" examples: default: "$ref": "#/components/examples/runner-application-items" x-github: githubCloudOnly: false enabledForGitHubApps: true category: actions subcategory: self-hosted-runners "/repos/{owner}/{repo}/actions/runners/registration-token": post: summary: Create a registration token for a repository description: "Returns a token that you can pass to the `config` script. The token expires after one hour. You must authenticate\nusing an access token with the `repo` scope to use this endpoint.\n\n#### Example using registration token\n \nConfigure your self-hosted runner, replacing `TOKEN` with the registration token provided by this endpoint.\n\n```\n./config.sh --url https://github.com/octo-org/octo-repo-artifacts --token TOKEN\n```" tags: - actions operationId: actions/create-registration-token-for-repo externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/actions#create-a-registration-token-for-a-repository parameters: - "$ref": "#/components/parameters/owner" - "$ref": "#/components/parameters/repo" responses: '201': description: Response content: application/json: schema: "$ref": "#/components/schemas/authentication-token" examples: default: "$ref": "#/components/examples/authentication-token" x-github: githubCloudOnly: false enabledForGitHubApps: true category: actions subcategory: self-hosted-runners "/repos/{owner}/{repo}/actions/runners/remove-token": post: summary: Create a remove token for a repository description: "Returns a token that you can pass to remove a self-hosted runner from a repository. The token expires after one hour.\nYou must authenticate using an access token with the `repo` scope to use this endpoint.\n\n#### Example using remove token\n \nTo remove your self-hosted runner from a repository, replace TOKEN with the remove token provided by this endpoint.\n\n```\n./config.sh remove --token TOKEN\n```" tags: - actions operationId: actions/create-remove-token-for-repo externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/actions#create-a-remove-token-for-a-repository parameters: - "$ref": "#/components/parameters/owner" - "$ref": "#/components/parameters/repo" responses: '201': description: Response content: application/json: schema: "$ref": "#/components/schemas/authentication-token" examples: default: "$ref": "#/components/examples/authentication-token-2" x-github: githubCloudOnly: false enabledForGitHubApps: true category: actions subcategory: self-hosted-runners "/repos/{owner}/{repo}/actions/runners/{runner_id}": get: summary: Get a self-hosted runner for a repository description: |- Gets a specific self-hosted runner configured in a repository. You must authenticate using an access token with the `repo` scope to use this endpoint. tags: - actions operationId: actions/get-self-hosted-runner-for-repo externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/actions#get-a-self-hosted-runner-for-a-repository parameters: - "$ref": "#/components/parameters/owner" - "$ref": "#/components/parameters/repo" - "$ref": "#/components/parameters/runner-id" responses: '200': description: Response content: application/json: schema: "$ref": "#/components/schemas/runner" examples: default: "$ref": "#/components/examples/runner" x-github: githubCloudOnly: false enabledForGitHubApps: true category: actions subcategory: self-hosted-runners delete: summary: Delete a self-hosted runner from a repository description: |- Forces the removal of a self-hosted runner from a repository. You can use this endpoint to completely remove the runner when the machine you were using no longer exists. You must authenticate using an access token with the `repo` scope to use this endpoint. tags: - actions operationId: actions/delete-self-hosted-runner-from-repo externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/actions#delete-a-self-hosted-runner-from-a-repository parameters: - "$ref": "#/components/parameters/owner" - "$ref": "#/components/parameters/repo" - "$ref": "#/components/parameters/runner-id" responses: '204': description: Response x-github: githubCloudOnly: false enabledForGitHubApps: true category: actions subcategory: self-hosted-runners "/repos/{owner}/{repo}/actions/runs": get: summary: List workflow runs for a repository description: |- Lists all workflow runs for a repository. You can use parameters to narrow the list of results. For more information about using parameters, see [Parameters](https://docs.github.com/enterprise-server@3.0/rest/overview/resources-in-the-rest-api#parameters). Anyone with read access to the repository can use this endpoint. If the repository is private you must use an access token with the `repo` scope. GitHub Apps must have the `actions:read` permission to use this endpoint. tags: - actions operationId: actions/list-workflow-runs-for-repo externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/actions#list-workflow-runs-for-a-repository parameters: - "$ref": "#/components/parameters/owner" - "$ref": "#/components/parameters/repo" - "$ref": "#/components/parameters/actor" - "$ref": "#/components/parameters/workflow-run-branch" - "$ref": "#/components/parameters/event" - "$ref": "#/components/parameters/workflow-run-status" - "$ref": "#/components/parameters/per-page" - "$ref": "#/components/parameters/page" - "$ref": "#/components/parameters/created" - "$ref": "#/components/parameters/exclude-pull-requests" responses: '200': description: Response content: application/json: schema: type: object required: - total_count - workflow_runs properties: total_count: type: integer workflow_runs: type: array items: "$ref": "#/components/schemas/workflow-run" examples: default: "$ref": "#/components/examples/workflow-run-paginated" headers: Link: "$ref": "#/components/headers/link" x-github: githubCloudOnly: false enabledForGitHubApps: true category: actions subcategory: workflow-runs "/repos/{owner}/{repo}/actions/runs/{run_id}": get: summary: Get a workflow run description: Gets a specific workflow run. Anyone with read access to the repository can use this endpoint. If the repository is private you must use an access token with the `repo` scope. GitHub Apps must have the `actions:read` permission to use this endpoint. tags: - actions operationId: actions/get-workflow-run externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/actions#get-a-workflow-run parameters: - "$ref": "#/components/parameters/owner" - "$ref": "#/components/parameters/repo" - "$ref": "#/components/parameters/run-id" - "$ref": "#/components/parameters/exclude-pull-requests" responses: '200': description: Response content: application/json: schema: "$ref": "#/components/schemas/workflow-run" examples: default: "$ref": "#/components/examples/workflow-run" x-github: githubCloudOnly: false enabledForGitHubApps: true category: actions subcategory: workflow-runs delete: summary: Delete a workflow run description: |- Delete a specific workflow run. Anyone with write access to the repository can use this endpoint. If the repository is private you must use an access token with the `repo` scope. GitHub Apps must have the `actions:write` permission to use this endpoint. operationId: actions/delete-workflow-run tags: - actions externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/actions#delete-a-workflow-run parameters: - "$ref": "#/components/parameters/owner" - "$ref": "#/components/parameters/repo" - "$ref": "#/components/parameters/run-id" responses: '204': description: Response x-github: githubCloudOnly: false enabledForGitHubApps: true category: actions subcategory: workflow-runs "/repos/{owner}/{repo}/actions/runs/{run_id}/artifacts": get: summary: List workflow run artifacts description: Lists artifacts for a workflow run. Anyone with read access to the repository can use this endpoint. If the repository is private you must use an access token with the `repo` scope. GitHub Apps must have the `actions:read` permission to use this endpoint. tags: - actions operationId: actions/list-workflow-run-artifacts externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/actions#list-workflow-run-artifacts parameters: - "$ref": "#/components/parameters/owner" - "$ref": "#/components/parameters/repo" - "$ref": "#/components/parameters/run-id" - "$ref": "#/components/parameters/per-page" - "$ref": "#/components/parameters/page" responses: '200': description: Response content: application/json: schema: type: object required: - total_count - artifacts properties: total_count: type: integer artifacts: type: array items: "$ref": "#/components/schemas/artifact" examples: default: "$ref": "#/components/examples/artifact-paginated" headers: Link: "$ref": "#/components/headers/link" x-github: githubCloudOnly: false enabledForGitHubApps: true category: actions subcategory: artifacts "/repos/{owner}/{repo}/actions/runs/{run_id}/cancel": post: summary: Cancel a workflow run description: Cancels a workflow run using its `id`. You must authenticate using an access token with the `repo` scope to use this endpoint. GitHub Apps must have the `actions:write` permission to use this endpoint. tags: - actions operationId: actions/cancel-workflow-run externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/actions#cancel-a-workflow-run parameters: - "$ref": "#/components/parameters/owner" - "$ref": "#/components/parameters/repo" - "$ref": "#/components/parameters/run-id" responses: '202': description: Response content: application/json: schema: type: object properties: {} additionalProperties: false x-github: githubCloudOnly: false enabledForGitHubApps: true category: actions subcategory: workflow-runs "/repos/{owner}/{repo}/actions/runs/{run_id}/jobs": get: summary: List jobs for a workflow run description: Lists jobs for a workflow run. Anyone with read access to the repository can use this endpoint. If the repository is private you must use an access token with the `repo` scope. GitHub Apps must have the `actions:read` permission to use this endpoint. You can use parameters to narrow the list of results. For more information about using parameters, see [Parameters](https://docs.github.com/enterprise-server@3.0/rest/overview/resources-in-the-rest-api#parameters). tags: - actions operationId: actions/list-jobs-for-workflow-run externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/actions#list-jobs-for-a-workflow-run parameters: - "$ref": "#/components/parameters/owner" - "$ref": "#/components/parameters/repo" - "$ref": "#/components/parameters/run-id" - name: filter description: "Filters jobs by their `completed_at` timestamp. Can be one of: \ \n\\* `latest`: Returns jobs from the most recent execution of the workflow run. \n\\* `all`: Returns all jobs for a workflow run, including from old executions of the workflow run." in: query required: false schema: type: string enum: - latest - all default: latest - "$ref": "#/components/parameters/per-page" - "$ref": "#/components/parameters/page" responses: '200': description: Response content: application/json: schema: type: object required: - total_count - jobs properties: total_count: type: integer jobs: type: array items: "$ref": "#/components/schemas/job" examples: default: "$ref": "#/components/examples/job-paginated" headers: Link: "$ref": "#/components/headers/link" x-github: githubCloudOnly: false enabledForGitHubApps: true category: actions subcategory: workflow-jobs "/repos/{owner}/{repo}/actions/runs/{run_id}/logs": get: summary: Download workflow run logs description: |- Gets a redirect URL to download an archive of log files for a workflow run. This link expires after 1 minute. Look for `Location:` in the response header to find the URL for the download. Anyone with read access to the repository can use this endpoint. If the repository is private you must use an access token with the `repo` scope. GitHub Apps must have the `actions:read` permission to use this endpoint. tags: - actions operationId: actions/download-workflow-run-logs externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/actions#download-workflow-run-logs parameters: - "$ref": "#/components/parameters/owner" - "$ref": "#/components/parameters/repo" - "$ref": "#/components/parameters/run-id" responses: '302': description: Response headers: Location: example: https://pipelines.actions.githubusercontent.com/ab1f3cCFPB34Nd6imvFxpGZH5hNlDp2wijMwl2gDoO0bcrrlJj/_apis/pipelines/1/runs/19/signedlogcontent?urlExpires=2020-01-22T22%3A44%3A54.1389777Z&urlSigningMethod=HMACV1&urlSignature=2TUDfIg4fm36OJmfPy6km5QD5DLCOkBVzvhWZM8B%2BUY%3D schema: type: string x-github: githubCloudOnly: false enabledForGitHubApps: true category: actions subcategory: workflow-runs delete: summary: Delete workflow run logs description: Deletes all logs for a workflow run. You must authenticate using an access token with the `repo` scope to use this endpoint. GitHub Apps must have the `actions:write` permission to use this endpoint. tags: - actions operationId: actions/delete-workflow-run-logs externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/actions#delete-workflow-run-logs parameters: - "$ref": "#/components/parameters/owner" - "$ref": "#/components/parameters/repo" - "$ref": "#/components/parameters/run-id" responses: '204': description: Response '403': "$ref": "#/components/responses/forbidden" '500': "$ref": "#/components/responses/internal_error" x-github: githubCloudOnly: false enabledForGitHubApps: true category: actions subcategory: workflow-runs "/repos/{owner}/{repo}/actions/runs/{run_id}/rerun": post: summary: Re-run a workflow description: Re-runs your workflow run using its `id`. You must authenticate using an access token with the `repo` scope to use this endpoint. GitHub Apps must have the `actions:write` permission to use this endpoint. tags: - actions operationId: actions/re-run-workflow externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/actions#re-run-a-workflow parameters: - "$ref": "#/components/parameters/owner" - "$ref": "#/components/parameters/repo" - "$ref": "#/components/parameters/run-id" responses: '201': description: Response content: application/json: schema: type: object properties: {} additionalProperties: false x-github: githubCloudOnly: false enabledForGitHubApps: false deprecationDate: '2021-09-14' category: actions subcategory: workflow-runs deprecated: true "/repos/{owner}/{repo}/actions/secrets": get: summary: List repository secrets description: Lists all secrets available in a repository without revealing their encrypted values. You must authenticate using an access token with the `repo` scope to use this endpoint. GitHub Apps must have the `secrets` repository permission to use this endpoint. tags: - actions operationId: actions/list-repo-secrets externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/actions#list-repository-secrets parameters: - "$ref": "#/components/parameters/owner" - "$ref": "#/components/parameters/repo" - "$ref": "#/components/parameters/per-page" - "$ref": "#/components/parameters/page" responses: '200': description: Response content: application/json: schema: type: object required: - total_count - secrets properties: total_count: type: integer secrets: type: array items: "$ref": "#/components/schemas/actions-secret" examples: default: "$ref": "#/components/examples/actions-secret-paginated" headers: Link: "$ref": "#/components/headers/link" x-github: githubCloudOnly: false enabledForGitHubApps: true category: actions subcategory: secrets "/repos/{owner}/{repo}/actions/secrets/public-key": get: summary: Get a repository public key description: Gets your public key, which you need to encrypt secrets. You need to encrypt a secret before you can create or update secrets. Anyone with read access to the repository can use this endpoint. If the repository is private you must use an access token with the `repo` scope. GitHub Apps must have the `secrets` repository permission to use this endpoint. tags: - actions operationId: actions/get-repo-public-key externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/actions#get-a-repository-public-key parameters: - "$ref": "#/components/parameters/owner" - "$ref": "#/components/parameters/repo" responses: '200': description: Response content: application/json: schema: "$ref": "#/components/schemas/actions-public-key" examples: default: "$ref": "#/components/examples/actions-public-key" x-github: githubCloudOnly: false enabledForGitHubApps: true category: actions subcategory: secrets "/repos/{owner}/{repo}/actions/secrets/{secret_name}": get: summary: Get a repository secret description: Gets a single repository secret without revealing its encrypted value. You must authenticate using an access token with the `repo` scope to use this endpoint. GitHub Apps must have the `secrets` repository permission to use this endpoint. tags: - actions operationId: actions/get-repo-secret externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/actions#get-a-repository-secret parameters: - "$ref": "#/components/parameters/owner" - "$ref": "#/components/parameters/repo" - "$ref": "#/components/parameters/secret-name" responses: '200': description: Response content: application/json: schema: "$ref": "#/components/schemas/actions-secret" examples: default: "$ref": "#/components/examples/actions-secret" x-github: githubCloudOnly: false enabledForGitHubApps: true category: actions subcategory: secrets put: summary: Create or update a repository secret description: |- Creates or updates a repository secret with an encrypted value. Encrypt your secret using [LibSodium](https://libsodium.gitbook.io/doc/bindings_for_other_languages). You must authenticate using an access token with the `repo` scope to use this endpoint. GitHub Apps must have the `secrets` repository permission to use this endpoint. #### Example encrypting a secret using Node.js Encrypt your secret using the [tweetsodium](https://github.com/github/tweetsodium) library. ``` const sodium = require('tweetsodium'); const key = "base64-encoded-public-key"; const value = "plain-text-secret"; // Convert the message and key to Uint8Array's (Buffer implements that interface) const messageBytes = Buffer.from(value); const keyBytes = Buffer.from(key, 'base64'); // Encrypt using LibSodium. const encryptedBytes = sodium.seal(messageBytes, keyBytes); // Base64 the encrypted secret const encrypted = Buffer.from(encryptedBytes).toString('base64'); console.log(encrypted); ``` #### Example encrypting a secret using Python Encrypt your secret using [pynacl](https://pynacl.readthedocs.io/en/latest/public/#nacl-public-sealedbox) with Python 3. ``` from base64 import b64encode from nacl import encoding, public def encrypt(public_key: str, secret_value: str) -> str: """Encrypt a Unicode string using the public key.""" public_key = public.PublicKey(public_key.encode("utf-8"), encoding.Base64Encoder()) sealed_box = public.SealedBox(public_key) encrypted = sealed_box.encrypt(secret_value.encode("utf-8")) return b64encode(encrypted).decode("utf-8") ``` #### Example encrypting a secret using C# Encrypt your secret using the [Sodium.Core](https://www.nuget.org/packages/Sodium.Core/) package. ``` var secretValue = System.Text.Encoding.UTF8.GetBytes("mySecret"); var publicKey = Convert.FromBase64String("2Sg8iYjAxxmI2LvUXpJjkYrMxURPc8r+dB7TJyvvcCU="); var sealedPublicKeyBox = Sodium.SealedPublicKeyBox.Create(secretValue, publicKey); Console.WriteLine(Convert.ToBase64String(sealedPublicKeyBox)); ``` #### Example encrypting a secret using Ruby Encrypt your secret using the [rbnacl](https://github.com/RubyCrypto/rbnacl) gem. ```ruby require "rbnacl" require "base64" key = Base64.decode64("+ZYvJDZMHUfBkJdyq5Zm9SKqeuBQ4sj+6sfjlH4CgG0=") public_key = RbNaCl::PublicKey.new(key) box = RbNaCl::Boxes::Sealed.from_public_key(public_key) encrypted_secret = box.encrypt("my_secret") # Print the base64 encoded secret puts Base64.strict_encode64(encrypted_secret) ``` tags: - actions operationId: actions/create-or-update-repo-secret externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/actions#create-or-update-a-repository-secret parameters: - "$ref": "#/components/parameters/owner" - "$ref": "#/components/parameters/repo" - "$ref": "#/components/parameters/secret-name" requestBody: required: true content: application/json: schema: type: object properties: encrypted_value: type: string description: Value for your secret, encrypted with [LibSodium](https://libsodium.gitbook.io/doc/bindings_for_other_languages) using the public key retrieved from the [Get a repository public key](https://docs.github.com/enterprise-server@3.0/rest/reference/actions#get-a-repository-public-key) endpoint. pattern: "^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=|[A-Za-z0-9+/]{4})$" key_id: type: string description: ID of the key you used to encrypt the secret. example: encrypted_value: c2VjcmV0 key_id: '012345678912345678' responses: '201': description: Response when creating a secret content: application/json: schema: type: object properties: {} additionalProperties: false '204': description: Response when updating a secret x-github: githubCloudOnly: false enabledForGitHubApps: true category: actions subcategory: secrets delete: summary: Delete a repository secret description: Deletes a secret in a repository using the secret name. You must authenticate using an access token with the `repo` scope to use this endpoint. GitHub Apps must have the `secrets` repository permission to use this endpoint. tags: - actions operationId: actions/delete-repo-secret externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/actions#delete-a-repository-secret parameters: - "$ref": "#/components/parameters/owner" - "$ref": "#/components/parameters/repo" - "$ref": "#/components/parameters/secret-name" responses: '204': description: Response x-github: githubCloudOnly: false enabledForGitHubApps: true category: actions subcategory: secrets "/repos/{owner}/{repo}/actions/workflows": get: summary: List repository workflows description: Lists the workflows in a repository. Anyone with read access to the repository can use this endpoint. If the repository is private you must use an access token with the `repo` scope. GitHub Apps must have the `actions:read` permission to use this endpoint. tags: - actions operationId: actions/list-repo-workflows externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/actions#list-repository-workflows parameters: - "$ref": "#/components/parameters/owner" - "$ref": "#/components/parameters/repo" - "$ref": "#/components/parameters/per-page" - "$ref": "#/components/parameters/page" responses: '200': description: Response content: application/json: schema: type: object required: - total_count - workflows properties: total_count: type: integer workflows: type: array items: "$ref": "#/components/schemas/workflow" examples: default: "$ref": "#/components/examples/workflow-paginated" headers: Link: "$ref": "#/components/headers/link" x-github: githubCloudOnly: false enabledForGitHubApps: true category: actions subcategory: workflows "/repos/{owner}/{repo}/actions/workflows/{workflow_id}": get: summary: Get a workflow description: Gets a specific workflow. You can replace `workflow_id` with the workflow file name. For example, you could use `main.yaml`. Anyone with read access to the repository can use this endpoint. If the repository is private you must use an access token with the `repo` scope. GitHub Apps must have the `actions:read` permission to use this endpoint. tags: - actions operationId: actions/get-workflow externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/actions#get-a-workflow parameters: - "$ref": "#/components/parameters/owner" - "$ref": "#/components/parameters/repo" - "$ref": "#/components/parameters/workflow-id" responses: '200': description: Response content: application/json: schema: "$ref": "#/components/schemas/workflow" examples: default: "$ref": "#/components/examples/workflow" x-github: githubCloudOnly: false enabledForGitHubApps: true category: actions subcategory: workflows "/repos/{owner}/{repo}/actions/workflows/{workflow_id}/disable": put: summary: Disable a workflow description: |- Disables a workflow and sets the `state` of the workflow to `disabled_manually`. You can replace `workflow_id` with the workflow file name. For example, you could use `main.yaml`. You must authenticate using an access token with the `repo` scope to use this endpoint. GitHub Apps must have the `actions:write` permission to use this endpoint. tags: - actions operationId: actions/disable-workflow externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/actions#disable-a-workflow parameters: - "$ref": "#/components/parameters/owner" - "$ref": "#/components/parameters/repo" - "$ref": "#/components/parameters/workflow-id" responses: '204': description: Response x-github: githubCloudOnly: false enabledForGitHubApps: true category: actions subcategory: workflows "/repos/{owner}/{repo}/actions/workflows/{workflow_id}/dispatches": post: summary: Create a workflow dispatch event description: |- You can use this endpoint to manually trigger a GitHub Actions workflow run. You can replace `workflow_id` with the workflow file name. For example, you could use `main.yaml`. You must configure your GitHub Actions workflow to run when the [`workflow_dispatch` webhook](/developers/webhooks-and-events/webhook-events-and-payloads#workflow_dispatch) event occurs. The `inputs` are configured in the workflow file. For more information about how to configure the `workflow_dispatch` event in the workflow file, see "[Events that trigger workflows](/actions/reference/events-that-trigger-workflows#workflow_dispatch)." You must authenticate using an access token with the `repo` scope to use this endpoint. GitHub Apps must have the `actions:write` permission to use this endpoint. For more information, see "[Creating a personal access token for the command line](https://docs.github.com/articles/creating-a-personal-access-token-for-the-command-line)." operationId: actions/create-workflow-dispatch tags: - actions externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/actions#create-a-workflow-dispatch-event parameters: - "$ref": "#/components/parameters/owner" - "$ref": "#/components/parameters/repo" - "$ref": "#/components/parameters/workflow-id" responses: '204': description: Response requestBody: required: true content: application/json: schema: type: object properties: ref: type: string description: The git reference for the workflow. The reference can be a branch or tag name. inputs: type: object description: Input keys and values configured in the workflow file. The maximum number of properties is 10. Any default properties configured in the workflow file will be used when `inputs` are omitted. additionalProperties: type: string maxProperties: 10 required: - ref example: ref: topic-branch inputs: name: Mona the Octocat home: San Francisco, CA x-github: githubCloudOnly: false enabledForGitHubApps: true category: actions subcategory: workflows "/repos/{owner}/{repo}/actions/workflows/{workflow_id}/enable": put: summary: Enable a workflow description: |- Enables a workflow and sets the `state` of the workflow to `active`. You can replace `workflow_id` with the workflow file name. For example, you could use `main.yaml`. You must authenticate using an access token with the `repo` scope to use this endpoint. GitHub Apps must have the `actions:write` permission to use this endpoint. tags: - actions operationId: actions/enable-workflow externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/actions#enable-a-workflow parameters: - "$ref": "#/components/parameters/owner" - "$ref": "#/components/parameters/repo" - "$ref": "#/components/parameters/workflow-id" responses: '204': description: Response x-github: githubCloudOnly: false enabledForGitHubApps: true category: actions subcategory: workflows "/repos/{owner}/{repo}/actions/workflows/{workflow_id}/runs": get: summary: List workflow runs description: |- List all workflow runs for a workflow. You can replace `workflow_id` with the workflow file name. For example, you could use `main.yaml`. You can use parameters to narrow the list of results. For more information about using parameters, see [Parameters](https://docs.github.com/enterprise-server@3.0/rest/overview/resources-in-the-rest-api#parameters). Anyone with read access to the repository can use this endpoint. If the repository is private you must use an access token with the `repo` scope. tags: - actions operationId: actions/list-workflow-runs externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/actions#list-workflow-runs parameters: - "$ref": "#/components/parameters/owner" - "$ref": "#/components/parameters/repo" - "$ref": "#/components/parameters/workflow-id" - "$ref": "#/components/parameters/actor" - "$ref": "#/components/parameters/workflow-run-branch" - "$ref": "#/components/parameters/event" - "$ref": "#/components/parameters/workflow-run-status" - "$ref": "#/components/parameters/per-page" - "$ref": "#/components/parameters/page" - "$ref": "#/components/parameters/created" - "$ref": "#/components/parameters/exclude-pull-requests" responses: '200': description: Response content: application/json: schema: type: object required: - total_count - workflow_runs properties: total_count: type: integer workflow_runs: type: array items: "$ref": "#/components/schemas/workflow-run" examples: default: "$ref": "#/components/examples/workflow-run-paginated" headers: Link: "$ref": "#/components/headers/link" x-github: githubCloudOnly: false enabledForGitHubApps: true category: actions subcategory: workflow-runs "/repos/{owner}/{repo}/assignees": get: summary: List assignees description: Lists the [available assignees](https://docs.github.com/articles/assigning-issues-and-pull-requests-to-other-github-users/) for issues in a repository. tags: - issues operationId: issues/list-assignees externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/issues#list-assignees parameters: - "$ref": "#/components/parameters/owner" - "$ref": "#/components/parameters/repo" - "$ref": "#/components/parameters/per-page" - "$ref": "#/components/parameters/page" responses: '200': description: Response content: application/json: schema: type: array items: "$ref": "#/components/schemas/simple-user" examples: default: "$ref": "#/components/examples/simple-user-items" headers: Link: "$ref": "#/components/headers/link" '404': "$ref": "#/components/responses/not_found" x-github: githubCloudOnly: false enabledForGitHubApps: true category: issues subcategory: assignees "/repos/{owner}/{repo}/assignees/{assignee}": get: summary: Check if a user can be assigned description: |- Checks if a user has permission to be assigned to an issue in this repository. If the `assignee` can be assigned to issues in the repository, a `204` header with no content is returned. Otherwise a `404` status code is returned. tags: - issues operationId: issues/check-user-can-be-assigned externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/issues#check-if-a-user-can-be-assigned parameters: - "$ref": "#/components/parameters/owner" - "$ref": "#/components/parameters/repo" - name: assignee in: path required: true schema: type: string responses: '204': description: If the `assignee` can be assigned to issues in the repository, a `204` header with no content is returned. '404': description: Otherwise a `404` status code is returned. content: application/json: schema: "$ref": "#/components/schemas/basic-error" x-github: githubCloudOnly: false enabledForGitHubApps: true category: issues subcategory: assignees "/repos/{owner}/{repo}/branches": get: summary: List branches description: '' tags: - repos operationId: repos/list-branches externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/repos#list-branches parameters: - "$ref": "#/components/parameters/owner" - "$ref": "#/components/parameters/repo" - name: protected description: Setting to `true` returns only protected branches. When set to `false`, only unprotected branches are returned. Omitting this parameter returns all branches. in: query required: false schema: type: boolean - "$ref": "#/components/parameters/per-page" - "$ref": "#/components/parameters/page" responses: '200': description: Response content: application/json: schema: type: array items: "$ref": "#/components/schemas/short-branch" examples: default: "$ref": "#/components/examples/short-branch-with-protection-items" headers: Link: "$ref": "#/components/headers/link" '404': "$ref": "#/components/responses/not_found" x-github: githubCloudOnly: false enabledForGitHubApps: true category: repos subcategory: branches "/repos/{owner}/{repo}/branches/{branch}": get: summary: Get a branch description: '' tags: - repos operationId: repos/get-branch externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/repos#get-a-branch parameters: - "$ref": "#/components/parameters/owner" - "$ref": "#/components/parameters/repo" - "$ref": "#/components/parameters/branch" responses: '200': description: Response content: application/json: schema: "$ref": "#/components/schemas/branch-with-protection" '301': "$ref": "#/components/responses/moved_permanently" '415': "$ref": "#/components/responses/preview_header_missing" '404': "$ref": "#/components/responses/not_found" x-github: githubCloudOnly: false enabledForGitHubApps: true category: repos subcategory: branches "/repos/{owner}/{repo}/branches/{branch}/protection": get: summary: Get branch protection description: Protected branches are available in public repositories with GitHub Free and GitHub Free for organizations, and in public and private repositories with GitHub Pro, GitHub Team, GitHub Enterprise Cloud, and GitHub Enterprise Server. For more information, see [GitHub's products](https://docs.github.com/github/getting-started-with-github/githubs-products) in the GitHub Help documentation. tags: - repos operationId: repos/get-branch-protection externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/repos#get-branch-protection parameters: - "$ref": "#/components/parameters/owner" - "$ref": "#/components/parameters/repo" - "$ref": "#/components/parameters/branch" responses: '200': description: Response content: application/json: schema: "$ref": "#/components/schemas/branch-protection" examples: default: "$ref": "#/components/examples/branch-protection" '404': "$ref": "#/components/responses/not_found" x-github: githubCloudOnly: false enabledForGitHubApps: true category: repos subcategory: branches previews: - required: false name: luke-cage note: |- The Protected Branches API now has a setting for requiring a specified number of approving pull request reviews before merging. This feature is currently available for developers to preview. See the [blog post](https://developer.github.com/changes/2018-03-16-protected-branches-required-approving-reviews) for full details. To access the API during the preview period, you must provide a custom [media type](https://docs.github.com/enterprise-server@3.0/rest/overview/media-types) in the `Accept` header: ```shell application/vnd.github.luke-cage-preview+json ``` put: summary: Update branch protection description: |- Protected branches are available in public repositories with GitHub Free and GitHub Free for organizations, and in public and private repositories with GitHub Pro, GitHub Team, GitHub Enterprise Cloud, and GitHub Enterprise Server. For more information, see [GitHub's products](https://docs.github.com/github/getting-started-with-github/githubs-products) in the GitHub Help documentation. Protecting a branch requires admin or owner permissions to the repository. **Note**: Passing new arrays of `users` and `teams` replaces their previous values. **Note**: The list of users, apps, and teams in total is limited to 100 items. tags: - repos operationId: repos/update-branch-protection externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/repos#update-branch-protection parameters: - "$ref": "#/components/parameters/owner" - "$ref": "#/components/parameters/repo" - "$ref": "#/components/parameters/branch" requestBody: required: true content: application/json: schema: type: object properties: required_status_checks: type: - object - 'null' description: Require status checks to pass before merging. Set to `null` to disable. properties: strict: type: boolean description: Require branches to be up to date before merging. contexts: type: array deprecated: true description: "**Deprecated**: The list of status checks to require in order to merge into this branch. If any of these checks have recently been set by a particular GitHub App, they will be required to come from that app in future for the branch to merge. Use `checks` instead of `contexts` for more fine-grained control.\n" items: type: string checks: type: array description: The list of status checks to require in order to merge into this branch. items: type: object required: - context properties: context: type: string description: The name of the required check app_id: type: integer description: The ID of the GitHub App that must provide this check. Omit this field to automatically select the GitHub App that has recently provided this check, or any app if it was not set by a GitHub App. Pass -1 to explicitly allow any app to set the status. required: - strict - contexts enforce_admins: type: - boolean - 'null' description: Enforce all configured restrictions for administrators. Set to `true` to enforce required status checks for repository administrators. Set to `null` to disable. required_pull_request_reviews: type: - object - 'null' description: Require at least one approving review on a pull request, before merging. Set to `null` to disable. properties: dismissal_restrictions: type: object description: Specify which users and teams can dismiss pull request reviews. Pass an empty `dismissal_restrictions` object to disable. User and team `dismissal_restrictions` are only available for organization-owned repositories. Omit this parameter for personal repositories. properties: users: type: array description: The list of user `login`s with dismissal access items: type: string teams: type: array description: The list of team `slug`s with dismissal access items: type: string dismiss_stale_reviews: type: boolean description: Set to `true` if you want to automatically dismiss approving reviews when someone pushes a new commit. require_code_owner_reviews: type: boolean description: Blocks merging pull requests until [code owners](https://docs.github.com/articles/about-code-owners/) review them. required_approving_review_count: type: integer description: Specify the number of reviewers required to approve pull requests. Use a number between 1 and 6. restrictions: type: - object - 'null' description: Restrict who can push to the protected branch. User, app, and team `restrictions` are only available for organization-owned repositories. Set to `null` to disable. properties: users: type: array description: The list of user `login`s with push access items: type: string teams: type: array description: The list of team `slug`s with push access items: type: string apps: type: array description: The list of app `slug`s with push access items: type: string required: - users - teams required_linear_history: type: boolean description: 'Enforces a linear commit Git history, which prevents anyone from pushing merge commits to a branch. Set to `true` to enforce a linear commit history. Set to `false` to disable a linear commit Git history. Your repository must allow squash merging or rebase merging before you can enable a linear commit history. Default: `false`. For more information, see "[Requiring a linear commit history](https://docs.github.com/github/administering-a-repository/requiring-a-linear-commit-history)" in the GitHub Help documentation.' allow_force_pushes: type: - boolean - 'null' description: 'Permits force pushes to the protected branch by anyone with write access to the repository. Set to `true` to allow force pushes. Set to `false` or `null` to block force pushes. Default: `false`. For more information, see "[Enabling force pushes to a protected branch](https://docs.github.com/en/github/administering-a-repository/enabling-force-pushes-to-a-protected-branch)" in the GitHub Help documentation."' allow_deletions: type: boolean description: 'Allows deletion of the protected branch by anyone with write access to the repository. Set to `false` to prevent deletion of the protected branch. Default: `false`. For more information, see "[Enabling force pushes to a protected branch](https://docs.github.com/en/github/administering-a-repository/enabling-force-pushes-to-a-protected-branch)" in the GitHub Help documentation.' required_conversation_resolution: type: boolean description: 'Requires all conversations on code to be resolved before a pull request can be merged into a branch that matches this rule. Set to `false` to disable. Default: `false`.' contexts: type: array description: The list of status checks to require in order to merge into this branch. items: type: string required: - required_status_checks - enforce_admins - required_pull_request_reviews - restrictions example: required_status_checks: strict: true contexts: - continuous-integration/travis-ci enforce_admins: true required_pull_request_reviews: dismissal_restrictions: users: - octocat teams: - justice-league dismiss_stale_reviews: true require_code_owner_reviews: true required_approving_review_count: 2 bypass_pull_request_allowances: users: - octocat teams: - justice-league restrictions: users: - octocat teams: - justice-league apps: - super-ci required_linear_history: true allow_force_pushes: true allow_deletions: true required_conversation_resolution: true responses: '200': description: Response content: application/json: schema: "$ref": "#/components/schemas/protected-branch" '403': "$ref": "#/components/responses/forbidden" '422': "$ref": "#/components/responses/validation_failed_simple" '404': "$ref": "#/components/responses/not_found" x-github: githubCloudOnly: false enabledForGitHubApps: true category: repos subcategory: branches previews: - required: false name: luke-cage note: |- The Protected Branches API now has a setting for requiring a specified number of approving pull request reviews before merging. This feature is currently available for developers to preview. See the [blog post](https://developer.github.com/changes/2018-03-16-protected-branches-required-approving-reviews) for full details. To access the API during the preview period, you must provide a custom [media type](https://docs.github.com/enterprise-server@3.0/rest/overview/media-types) in the `Accept` header: ```shell application/vnd.github.luke-cage-preview+json ``` delete: summary: Delete branch protection description: Protected branches are available in public repositories with GitHub Free and GitHub Free for organizations, and in public and private repositories with GitHub Pro, GitHub Team, GitHub Enterprise Cloud, and GitHub Enterprise Server. For more information, see [GitHub's products](https://docs.github.com/github/getting-started-with-github/githubs-products) in the GitHub Help documentation. tags: - repos operationId: repos/delete-branch-protection externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/repos#delete-branch-protection parameters: - "$ref": "#/components/parameters/owner" - "$ref": "#/components/parameters/repo" - "$ref": "#/components/parameters/branch" responses: '204': description: Response '403': "$ref": "#/components/responses/forbidden" x-github: githubCloudOnly: false enabledForGitHubApps: true category: repos subcategory: branches "/repos/{owner}/{repo}/branches/{branch}/protection/enforce_admins": get: summary: Get admin branch protection description: Protected branches are available in public repositories with GitHub Free and GitHub Free for organizations, and in public and private repositories with GitHub Pro, GitHub Team, GitHub Enterprise Cloud, and GitHub Enterprise Server. For more information, see [GitHub's products](https://docs.github.com/github/getting-started-with-github/githubs-products) in the GitHub Help documentation. tags: - repos operationId: repos/get-admin-branch-protection externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/repos#get-admin-branch-protection parameters: - "$ref": "#/components/parameters/owner" - "$ref": "#/components/parameters/repo" - "$ref": "#/components/parameters/branch" responses: '200': description: Response content: application/json: schema: "$ref": "#/components/schemas/protected-branch-admin-enforced" examples: default: "$ref": "#/components/examples/protected-branch-admin-enforced-2" x-github: githubCloudOnly: false enabledForGitHubApps: true category: repos subcategory: branches post: summary: Set admin branch protection description: |- Protected branches are available in public repositories with GitHub Free and GitHub Free for organizations, and in public and private repositories with GitHub Pro, GitHub Team, GitHub Enterprise Cloud, and GitHub Enterprise Server. For more information, see [GitHub's products](https://docs.github.com/github/getting-started-with-github/githubs-products) in the GitHub Help documentation. Adding admin enforcement requires admin or owner permissions to the repository and branch protection to be enabled. tags: - repos operationId: repos/set-admin-branch-protection externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/repos#set-admin-branch-protection parameters: - "$ref": "#/components/parameters/owner" - "$ref": "#/components/parameters/repo" - "$ref": "#/components/parameters/branch" responses: '200': description: Response content: application/json: schema: "$ref": "#/components/schemas/protected-branch-admin-enforced" examples: default: "$ref": "#/components/examples/protected-branch-admin-enforced-2" x-github: githubCloudOnly: false enabledForGitHubApps: true category: repos subcategory: branches delete: summary: Delete admin branch protection description: |- Protected branches are available in public repositories with GitHub Free and GitHub Free for organizations, and in public and private repositories with GitHub Pro, GitHub Team, GitHub Enterprise Cloud, and GitHub Enterprise Server. For more information, see [GitHub's products](https://docs.github.com/github/getting-started-with-github/githubs-products) in the GitHub Help documentation. Removing admin enforcement requires admin or owner permissions to the repository and branch protection to be enabled. tags: - repos operationId: repos/delete-admin-branch-protection externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/repos#delete-admin-branch-protection parameters: - "$ref": "#/components/parameters/owner" - "$ref": "#/components/parameters/repo" - "$ref": "#/components/parameters/branch" responses: '204': description: Response '404': "$ref": "#/components/responses/not_found" x-github: githubCloudOnly: false enabledForGitHubApps: true category: repos subcategory: branches "/repos/{owner}/{repo}/branches/{branch}/protection/required_pull_request_reviews": get: summary: Get pull request review protection description: Protected branches are available in public repositories with GitHub Free and GitHub Free for organizations, and in public and private repositories with GitHub Pro, GitHub Team, GitHub Enterprise Cloud, and GitHub Enterprise Server. For more information, see [GitHub's products](https://docs.github.com/github/getting-started-with-github/githubs-products) in the GitHub Help documentation. tags: - repos operationId: repos/get-pull-request-review-protection externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/repos#get-pull-request-review-protection parameters: - "$ref": "#/components/parameters/owner" - "$ref": "#/components/parameters/repo" - "$ref": "#/components/parameters/branch" responses: '200': description: Response content: application/json: schema: "$ref": "#/components/schemas/protected-branch-pull-request-review" examples: default: "$ref": "#/components/examples/protected-branch-pull-request-review" x-github: githubCloudOnly: false enabledForGitHubApps: true category: repos subcategory: branches previews: - required: false name: luke-cage note: |- The Protected Branches API now has a setting for requiring a specified number of approving pull request reviews before merging. This feature is currently available for developers to preview. See the [blog post](https://developer.github.com/changes/2018-03-16-protected-branches-required-approving-reviews) for full details. To access the API during the preview period, you must provide a custom [media type](https://docs.github.com/enterprise-server@3.0/rest/overview/media-types) in the `Accept` header: ```shell application/vnd.github.luke-cage-preview+json ``` patch: summary: Update pull request review protection description: |- Protected branches are available in public repositories with GitHub Free and GitHub Free for organizations, and in public and private repositories with GitHub Pro, GitHub Team, GitHub Enterprise Cloud, and GitHub Enterprise Server. For more information, see [GitHub's products](https://docs.github.com/github/getting-started-with-github/githubs-products) in the GitHub Help documentation. Updating pull request review enforcement requires admin or owner permissions to the repository and branch protection to be enabled. **Note**: Passing new arrays of `users` and `teams` replaces their previous values. tags: - repos operationId: repos/update-pull-request-review-protection externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/repos#update-pull-request-review-protection parameters: - "$ref": "#/components/parameters/owner" - "$ref": "#/components/parameters/repo" - "$ref": "#/components/parameters/branch" requestBody: required: false content: application/json: schema: type: object properties: dismissal_restrictions: type: object description: Specify which users and teams can dismiss pull request reviews. Pass an empty `dismissal_restrictions` object to disable. User and team `dismissal_restrictions` are only available for organization-owned repositories. Omit this parameter for personal repositories. properties: users: type: array description: The list of user `login`s with dismissal access items: type: string teams: type: array description: The list of team `slug`s with dismissal access items: type: string dismiss_stale_reviews: type: boolean description: Set to `true` if you want to automatically dismiss approving reviews when someone pushes a new commit. require_code_owner_reviews: type: boolean description: Blocks merging pull requests until [code owners](https://docs.github.com/articles/about-code-owners/) have reviewed. required_approving_review_count: type: integer description: Specifies the number of reviewers required to approve pull requests. Use a number between 1 and 6. example: dismissal_restrictions: users: - octocat teams: - justice-league bypass_pull_request_allowances: users: - octocat teams: - justice-league dismiss_stale_reviews: true require_code_owner_reviews: true required_approving_review_count: 2 responses: '200': description: Response content: application/json: schema: "$ref": "#/components/schemas/protected-branch-pull-request-review" examples: default: "$ref": "#/components/examples/protected-branch-pull-request-review" '422': "$ref": "#/components/responses/validation_failed" x-github: githubCloudOnly: false enabledForGitHubApps: true category: repos subcategory: branches previews: - required: false name: luke-cage note: |- The Protected Branches API now has a setting for requiring a specified number of approving pull request reviews before merging. This feature is currently available for developers to preview. See the [blog post](https://developer.github.com/changes/2018-03-16-protected-branches-required-approving-reviews) for full details. To access the API during the preview period, you must provide a custom [media type](https://docs.github.com/enterprise-server@3.0/rest/overview/media-types) in the `Accept` header: ```shell application/vnd.github.luke-cage-preview+json ``` delete: summary: Delete pull request review protection description: Protected branches are available in public repositories with GitHub Free and GitHub Free for organizations, and in public and private repositories with GitHub Pro, GitHub Team, GitHub Enterprise Cloud, and GitHub Enterprise Server. For more information, see [GitHub's products](https://docs.github.com/github/getting-started-with-github/githubs-products) in the GitHub Help documentation. tags: - repos operationId: repos/delete-pull-request-review-protection externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/repos#delete-pull-request-review-protection parameters: - "$ref": "#/components/parameters/owner" - "$ref": "#/components/parameters/repo" - "$ref": "#/components/parameters/branch" responses: '204': description: Response '404': "$ref": "#/components/responses/not_found" x-github: githubCloudOnly: false enabledForGitHubApps: true category: repos subcategory: branches "/repos/{owner}/{repo}/branches/{branch}/protection/required_signatures": get: summary: Get commit signature protection description: |- Protected branches are available in public repositories with GitHub Free and GitHub Free for organizations, and in public and private repositories with GitHub Pro, GitHub Team, GitHub Enterprise Cloud, and GitHub Enterprise Server. For more information, see [GitHub's products](https://docs.github.com/github/getting-started-with-github/githubs-products) in the GitHub Help documentation. When authenticated with admin or owner permissions to the repository, you can use this endpoint to check whether a branch requires signed commits. An enabled status of `true` indicates you must sign commits on this branch. For more information, see [Signing commits with GPG](https://docs.github.com/articles/signing-commits-with-gpg) in GitHub Help. **Note**: You must enable branch protection to require signed commits. tags: - repos operationId: repos/get-commit-signature-protection externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/repos#get-commit-signature-protection parameters: - "$ref": "#/components/parameters/owner" - "$ref": "#/components/parameters/repo" - "$ref": "#/components/parameters/branch" responses: '200': description: Response content: application/json: schema: "$ref": "#/components/schemas/protected-branch-admin-enforced" examples: default: "$ref": "#/components/examples/protected-branch-admin-enforced" '404': "$ref": "#/components/responses/not_found" x-github: githubCloudOnly: false enabledForGitHubApps: true category: repos subcategory: branches previews: - required: true name: zzzax note: |- Protected Branches API can now manage a setting for requiring signed commits. This feature is currently available for developers to preview. See the [blog post](https://developer.github.com/changes/2018-02-22-protected-branches-required-signatures) for full details. To access the API during the preview period, you must provide a custom [media type](https://docs.github.com/enterprise-server@3.0/rest/overview/media-types) in the `Accept` header: ```shell application/vnd.github.zzzax-preview+json ``` post: summary: Create commit signature protection description: |- Protected branches are available in public repositories with GitHub Free and GitHub Free for organizations, and in public and private repositories with GitHub Pro, GitHub Team, GitHub Enterprise Cloud, and GitHub Enterprise Server. For more information, see [GitHub's products](https://docs.github.com/github/getting-started-with-github/githubs-products) in the GitHub Help documentation. When authenticated with admin or owner permissions to the repository, you can use this endpoint to require signed commits on a branch. You must enable branch protection to require signed commits. tags: - repos operationId: repos/create-commit-signature-protection externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/repos#create-commit-signature-protection parameters: - "$ref": "#/components/parameters/owner" - "$ref": "#/components/parameters/repo" - "$ref": "#/components/parameters/branch" responses: '200': description: Response content: application/json: schema: "$ref": "#/components/schemas/protected-branch-admin-enforced" examples: default: "$ref": "#/components/examples/protected-branch-admin-enforced" '404': "$ref": "#/components/responses/not_found" x-github: githubCloudOnly: false enabledForGitHubApps: true category: repos subcategory: branches previews: - required: true name: zzzax note: |- Protected Branches API can now manage a setting for requiring signed commits. This feature is currently available for developers to preview. See the [blog post](https://developer.github.com/changes/2018-02-22-protected-branches-required-signatures) for full details. To access the API during the preview period, you must provide a custom [media type](https://docs.github.com/enterprise-server@3.0/rest/overview/media-types) in the `Accept` header: ```shell application/vnd.github.zzzax-preview+json ``` delete: summary: Delete commit signature protection description: |- Protected branches are available in public repositories with GitHub Free and GitHub Free for organizations, and in public and private repositories with GitHub Pro, GitHub Team, GitHub Enterprise Cloud, and GitHub Enterprise Server. For more information, see [GitHub's products](https://docs.github.com/github/getting-started-with-github/githubs-products) in the GitHub Help documentation. When authenticated with admin or owner permissions to the repository, you can use this endpoint to disable required signed commits on a branch. You must enable branch protection to require signed commits. tags: - repos operationId: repos/delete-commit-signature-protection externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/repos#delete-commit-signature-protection parameters: - "$ref": "#/components/parameters/owner" - "$ref": "#/components/parameters/repo" - "$ref": "#/components/parameters/branch" responses: '204': description: Response '404': "$ref": "#/components/responses/not_found" x-github: githubCloudOnly: false enabledForGitHubApps: true category: repos subcategory: branches previews: - required: true name: zzzax note: |- Protected Branches API can now manage a setting for requiring signed commits. This feature is currently available for developers to preview. See the [blog post](https://developer.github.com/changes/2018-02-22-protected-branches-required-signatures) for full details. To access the API during the preview period, you must provide a custom [media type](https://docs.github.com/enterprise-server@3.0/rest/overview/media-types) in the `Accept` header: ```shell application/vnd.github.zzzax-preview+json ``` "/repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks": get: summary: Get status checks protection description: Protected branches are available in public repositories with GitHub Free and GitHub Free for organizations, and in public and private repositories with GitHub Pro, GitHub Team, GitHub Enterprise Cloud, and GitHub Enterprise Server. For more information, see [GitHub's products](https://docs.github.com/github/getting-started-with-github/githubs-products) in the GitHub Help documentation. tags: - repos operationId: repos/get-status-checks-protection externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/repos#get-status-checks-protection parameters: - "$ref": "#/components/parameters/owner" - "$ref": "#/components/parameters/repo" - "$ref": "#/components/parameters/branch" responses: '200': description: Response content: application/json: schema: "$ref": "#/components/schemas/status-check-policy" examples: default: "$ref": "#/components/examples/status-check-policy" '404': "$ref": "#/components/responses/not_found" x-github: githubCloudOnly: false enabledForGitHubApps: true category: repos subcategory: branches patch: summary: Update status check protection description: |- Protected branches are available in public repositories with GitHub Free and GitHub Free for organizations, and in public and private repositories with GitHub Pro, GitHub Team, GitHub Enterprise Cloud, and GitHub Enterprise Server. For more information, see [GitHub's products](https://docs.github.com/github/getting-started-with-github/githubs-products) in the GitHub Help documentation. Updating required status checks requires admin or owner permissions to the repository and branch protection to be enabled. tags: - repos operationId: repos/update-status-check-protection externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/repos#update-status-check-protection parameters: - "$ref": "#/components/parameters/owner" - "$ref": "#/components/parameters/repo" - "$ref": "#/components/parameters/branch" requestBody: required: false content: application/json: schema: type: object properties: strict: type: boolean description: Require branches to be up to date before merging. contexts: type: array deprecated: true description: The list of status checks to require in order to merge into this branch items: type: string example: strict: true contexts: - continuous-integration/travis-ci responses: '200': description: Response content: application/json: schema: "$ref": "#/components/schemas/status-check-policy" examples: default: "$ref": "#/components/examples/status-check-policy" '404': "$ref": "#/components/responses/not_found" '422': "$ref": "#/components/responses/validation_failed" x-github: githubCloudOnly: false enabledForGitHubApps: true category: repos subcategory: branches delete: summary: Remove status check protection description: Protected branches are available in public repositories with GitHub Free and GitHub Free for organizations, and in public and private repositories with GitHub Pro, GitHub Team, GitHub Enterprise Cloud, and GitHub Enterprise Server. For more information, see [GitHub's products](https://docs.github.com/github/getting-started-with-github/githubs-products) in the GitHub Help documentation. tags: - repos operationId: repos/remove-status-check-protection externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/repos#remove-status-check-protection parameters: - "$ref": "#/components/parameters/owner" - "$ref": "#/components/parameters/repo" - "$ref": "#/components/parameters/branch" responses: '204': description: Response x-github: githubCloudOnly: false enabledForGitHubApps: true category: repos subcategory: branches "/repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks/contexts": get: summary: Get all status check contexts description: Protected branches are available in public repositories with GitHub Free and GitHub Free for organizations, and in public and private repositories with GitHub Pro, GitHub Team, GitHub Enterprise Cloud, and GitHub Enterprise Server. For more information, see [GitHub's products](https://docs.github.com/github/getting-started-with-github/githubs-products) in the GitHub Help documentation. tags: - repos operationId: repos/get-all-status-check-contexts externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/repos#get-all-status-check-contexts parameters: - "$ref": "#/components/parameters/owner" - "$ref": "#/components/parameters/repo" - "$ref": "#/components/parameters/branch" responses: '200': description: Response content: application/json: schema: type: array items: type: string example: - continuous-integration/travis-ci '404': "$ref": "#/components/responses/not_found" x-github: githubCloudOnly: false enabledForGitHubApps: true category: repos subcategory: branches post: summary: Add status check contexts description: Protected branches are available in public repositories with GitHub Free and GitHub Free for organizations, and in public and private repositories with GitHub Pro, GitHub Team, GitHub Enterprise Cloud, and GitHub Enterprise Server. For more information, see [GitHub's products](https://docs.github.com/github/getting-started-with-github/githubs-products) in the GitHub Help documentation. tags: - repos operationId: repos/add-status-check-contexts externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/repos#add-status-check-contexts parameters: - "$ref": "#/components/parameters/owner" - "$ref": "#/components/parameters/repo" - "$ref": "#/components/parameters/branch" requestBody: required: false content: application/json: schema: oneOf: - type: object properties: contexts: type: array description: contexts parameter items: type: string required: - contexts example: contexts: - contexts - type: array description: contexts parameter items: type: string responses: '200': description: Response content: application/json: schema: type: array items: type: string example: - continuous-integration/travis-ci - continuous-integration/jenkins '422': "$ref": "#/components/responses/validation_failed" '403': "$ref": "#/components/responses/forbidden" '404': "$ref": "#/components/responses/not_found" x-github: githubCloudOnly: false enabledForGitHubApps: true requestBodyParameterName: contexts category: repos subcategory: branches put: summary: Set status check contexts description: Protected branches are available in public repositories with GitHub Free and GitHub Free for organizations, and in public and private repositories with GitHub Pro, GitHub Team, GitHub Enterprise Cloud, and GitHub Enterprise Server. For more information, see [GitHub's products](https://docs.github.com/github/getting-started-with-github/githubs-products) in the GitHub Help documentation. tags: - repos operationId: repos/set-status-check-contexts externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/repos#set-status-check-contexts parameters: - "$ref": "#/components/parameters/owner" - "$ref": "#/components/parameters/repo" - "$ref": "#/components/parameters/branch" requestBody: required: false content: application/json: schema: oneOf: - type: object properties: contexts: type: array description: contexts parameter items: type: string required: - contexts example: contexts: - contexts - type: array description: contexts parameter items: type: string responses: '200': description: Response content: application/json: schema: type: array items: type: string example: - continuous-integration/travis-ci '422': "$ref": "#/components/responses/validation_failed" '404': "$ref": "#/components/responses/not_found" x-github: githubCloudOnly: false enabledForGitHubApps: true requestBodyParameterName: contexts category: repos subcategory: branches delete: summary: Remove status check contexts description: Protected branches are available in public repositories with GitHub Free and GitHub Free for organizations, and in public and private repositories with GitHub Pro, GitHub Team, GitHub Enterprise Cloud, and GitHub Enterprise Server. For more information, see [GitHub's products](https://docs.github.com/github/getting-started-with-github/githubs-products) in the GitHub Help documentation. tags: - repos operationId: repos/remove-status-check-contexts externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/repos#remove-status-check-contexts parameters: - "$ref": "#/components/parameters/owner" - "$ref": "#/components/parameters/repo" - "$ref": "#/components/parameters/branch" requestBody: content: application/json: schema: oneOf: - type: object properties: contexts: type: array description: contexts parameter items: type: string required: - contexts example: contexts: - contexts - type: array description: contexts parameter items: type: string responses: '200': description: Response content: application/json: schema: type: array items: type: string example: - continuous-integration/travis-ci '404': "$ref": "#/components/responses/not_found" '422': "$ref": "#/components/responses/validation_failed" x-github: githubCloudOnly: false enabledForGitHubApps: true requestBodyParameterName: contexts category: repos subcategory: branches "/repos/{owner}/{repo}/branches/{branch}/protection/restrictions": get: summary: Get access restrictions description: |- Protected branches are available in public repositories with GitHub Free and GitHub Free for organizations, and in public and private repositories with GitHub Pro, GitHub Team, GitHub Enterprise Cloud, and GitHub Enterprise Server. For more information, see [GitHub's products](https://docs.github.com/github/getting-started-with-github/githubs-products) in the GitHub Help documentation. Lists who has access to this protected branch. **Note**: Users, apps, and teams `restrictions` are only available for organization-owned repositories. tags: - repos operationId: repos/get-access-restrictions externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/repos#get-access-restrictions parameters: - "$ref": "#/components/parameters/owner" - "$ref": "#/components/parameters/repo" - "$ref": "#/components/parameters/branch" responses: '200': description: Response content: application/json: schema: "$ref": "#/components/schemas/branch-restriction-policy" examples: default: "$ref": "#/components/examples/branch-restriction-policy" '404': "$ref": "#/components/responses/not_found" x-github: githubCloudOnly: false enabledForGitHubApps: true category: repos subcategory: branches delete: summary: Delete access restrictions description: |- Protected branches are available in public repositories with GitHub Free and GitHub Free for organizations, and in public and private repositories with GitHub Pro, GitHub Team, GitHub Enterprise Cloud, and GitHub Enterprise Server. For more information, see [GitHub's products](https://docs.github.com/github/getting-started-with-github/githubs-products) in the GitHub Help documentation. Disables the ability to restrict who can push to this branch. tags: - repos operationId: repos/delete-access-restrictions externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/repos#delete-access-restrictions parameters: - "$ref": "#/components/parameters/owner" - "$ref": "#/components/parameters/repo" - "$ref": "#/components/parameters/branch" responses: '204': description: Response x-github: githubCloudOnly: false enabledForGitHubApps: true category: repos subcategory: branches "/repos/{owner}/{repo}/branches/{branch}/protection/restrictions/apps": get: summary: Get apps with access to the protected branch description: |- Protected branches are available in public repositories with GitHub Free and GitHub Free for organizations, and in public and private repositories with GitHub Pro, GitHub Team, GitHub Enterprise Cloud, and GitHub Enterprise Server. For more information, see [GitHub's products](https://docs.github.com/github/getting-started-with-github/githubs-products) in the GitHub Help documentation. Lists the GitHub Apps that have push access to this branch. Only installed GitHub Apps with `write` access to the `contents` permission can be added as authorized actors on a protected branch. tags: - repos operationId: repos/get-apps-with-access-to-protected-branch externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/repos#list-apps-with-access-to-the-protected-branch parameters: - "$ref": "#/components/parameters/owner" - "$ref": "#/components/parameters/repo" - "$ref": "#/components/parameters/branch" responses: '200': description: Response content: application/json: schema: type: array items: "$ref": "#/components/schemas/integration" examples: default: "$ref": "#/components/examples/integration-items" '404': "$ref": "#/components/responses/not_found" x-github: githubCloudOnly: false enabledForGitHubApps: true category: repos subcategory: branches post: summary: Add app access restrictions description: |- Protected branches are available in public repositories with GitHub Free and GitHub Free for organizations, and in public and private repositories with GitHub Pro, GitHub Team, GitHub Enterprise Cloud, and GitHub Enterprise Server. For more information, see [GitHub's products](https://docs.github.com/github/getting-started-with-github/githubs-products) in the GitHub Help documentation. Grants the specified apps push access for this branch. Only installed GitHub Apps with `write` access to the `contents` permission can be added as authorized actors on a protected branch. | Type | Description | | ------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------- | | `array` | The GitHub Apps that have push access to this branch. Use the app's `slug`. **Note**: The list of users, apps, and teams in total is limited to 100 items. | tags: - repos operationId: repos/add-app-access-restrictions externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/repos#add-app-access-restrictions parameters: - "$ref": "#/components/parameters/owner" - "$ref": "#/components/parameters/repo" - "$ref": "#/components/parameters/branch" requestBody: required: false content: application/json: schema: oneOf: - type: object properties: apps: type: array description: apps parameter items: type: string required: - apps example: apps: - my-app - type: array items: type: string responses: '200': description: Response content: application/json: schema: type: array items: "$ref": "#/components/schemas/integration" examples: default: "$ref": "#/components/examples/integration-items" '422': "$ref": "#/components/responses/validation_failed" x-github: githubCloudOnly: false enabledForGitHubApps: true requestBodyParameterName: apps category: repos subcategory: branches put: summary: Set app access restrictions description: |- Protected branches are available in public repositories with GitHub Free and GitHub Free for organizations, and in public and private repositories with GitHub Pro, GitHub Team, GitHub Enterprise Cloud, and GitHub Enterprise Server. For more information, see [GitHub's products](https://docs.github.com/github/getting-started-with-github/githubs-products) in the GitHub Help documentation. Replaces the list of apps that have push access to this branch. This removes all apps that previously had push access and grants push access to the new list of apps. Only installed GitHub Apps with `write` access to the `contents` permission can be added as authorized actors on a protected branch. | Type | Description | | ------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------- | | `array` | The GitHub Apps that have push access to this branch. Use the app's `slug`. **Note**: The list of users, apps, and teams in total is limited to 100 items. | tags: - repos operationId: repos/set-app-access-restrictions externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/repos#set-app-access-restrictions parameters: - "$ref": "#/components/parameters/owner" - "$ref": "#/components/parameters/repo" - "$ref": "#/components/parameters/branch" requestBody: required: false content: application/json: schema: oneOf: - type: object properties: apps: type: array description: apps parameter items: type: string required: - apps example: apps: - my-app - type: array items: type: string responses: '200': description: Response content: application/json: schema: type: array items: "$ref": "#/components/schemas/integration" examples: default: "$ref": "#/components/examples/integration-items" '422': "$ref": "#/components/responses/validation_failed" x-github: githubCloudOnly: false enabledForGitHubApps: true requestBodyParameterName: apps category: repos subcategory: branches delete: summary: Remove app access restrictions description: |- Protected branches are available in public repositories with GitHub Free and GitHub Free for organizations, and in public and private repositories with GitHub Pro, GitHub Team, GitHub Enterprise Cloud, and GitHub Enterprise Server. For more information, see [GitHub's products](https://docs.github.com/github/getting-started-with-github/githubs-products) in the GitHub Help documentation. Removes the ability of an app to push to this branch. Only installed GitHub Apps with `write` access to the `contents` permission can be added as authorized actors on a protected branch. | Type | Description | | ------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------- | | `array` | The GitHub Apps that have push access to this branch. Use the app's `slug`. **Note**: The list of users, apps, and teams in total is limited to 100 items. | tags: - repos operationId: repos/remove-app-access-restrictions externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/repos#remove-app-access-restrictions parameters: - "$ref": "#/components/parameters/owner" - "$ref": "#/components/parameters/repo" - "$ref": "#/components/parameters/branch" requestBody: content: application/json: schema: oneOf: - type: object properties: apps: type: array description: apps parameter items: type: string required: - apps example: apps: - my-app - type: array items: type: string responses: '200': description: Response content: application/json: schema: type: array items: "$ref": "#/components/schemas/integration" examples: default: "$ref": "#/components/examples/integration-items" '422': "$ref": "#/components/responses/validation_failed" x-github: githubCloudOnly: false enabledForGitHubApps: true requestBodyParameterName: apps category: repos subcategory: branches "/repos/{owner}/{repo}/branches/{branch}/protection/restrictions/teams": get: summary: Get teams with access to the protected branch description: |- Protected branches are available in public repositories with GitHub Free and GitHub Free for organizations, and in public and private repositories with GitHub Pro, GitHub Team, GitHub Enterprise Cloud, and GitHub Enterprise Server. For more information, see [GitHub's products](https://docs.github.com/github/getting-started-with-github/githubs-products) in the GitHub Help documentation. Lists the teams who have push access to this branch. The list includes child teams. tags: - repos operationId: repos/get-teams-with-access-to-protected-branch externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/repos#list-teams-with-access-to-the-protected-branch parameters: - "$ref": "#/components/parameters/owner" - "$ref": "#/components/parameters/repo" - "$ref": "#/components/parameters/branch" responses: '200': description: Response content: application/json: schema: type: array items: "$ref": "#/components/schemas/team" examples: default: "$ref": "#/components/examples/team-items" '404': "$ref": "#/components/responses/not_found" x-github: githubCloudOnly: false enabledForGitHubApps: true category: repos subcategory: branches post: summary: Add team access restrictions description: |- Protected branches are available in public repositories with GitHub Free and GitHub Free for organizations, and in public and private repositories with GitHub Pro, GitHub Team, GitHub Enterprise Cloud, and GitHub Enterprise Server. For more information, see [GitHub's products](https://docs.github.com/github/getting-started-with-github/githubs-products) in the GitHub Help documentation. Grants the specified teams push access for this branch. You can also give push access to child teams. | Type | Description | | ------- | ------------------------------------------------------------------------------------------------------------------------------------------ | | `array` | The teams that can have push access. Use the team's `slug`. **Note**: The list of users, apps, and teams in total is limited to 100 items. | tags: - repos operationId: repos/add-team-access-restrictions externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/repos#add-team-access-restrictions parameters: - "$ref": "#/components/parameters/owner" - "$ref": "#/components/parameters/repo" - "$ref": "#/components/parameters/branch" requestBody: required: false content: application/json: schema: oneOf: - type: object properties: teams: type: array description: teams parameter items: type: string required: - teams example: teams: - my-team - type: array description: teams parameter items: type: string responses: '200': description: Response content: application/json: schema: type: array items: "$ref": "#/components/schemas/team" examples: default: "$ref": "#/components/examples/team-items" '422': "$ref": "#/components/responses/validation_failed" x-github: githubCloudOnly: false enabledForGitHubApps: true requestBodyParameterName: teams category: repos subcategory: branches put: summary: Set team access restrictions description: |- Protected branches are available in public repositories with GitHub Free and GitHub Free for organizations, and in public and private repositories with GitHub Pro, GitHub Team, GitHub Enterprise Cloud, and GitHub Enterprise Server. For more information, see [GitHub's products](https://docs.github.com/github/getting-started-with-github/githubs-products) in the GitHub Help documentation. Replaces the list of teams that have push access to this branch. This removes all teams that previously had push access and grants push access to the new list of teams. Team restrictions include child teams. | Type | Description | | ------- | ------------------------------------------------------------------------------------------------------------------------------------------ | | `array` | The teams that can have push access. Use the team's `slug`. **Note**: The list of users, apps, and teams in total is limited to 100 items. | tags: - repos operationId: repos/set-team-access-restrictions externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/repos#set-team-access-restrictions parameters: - "$ref": "#/components/parameters/owner" - "$ref": "#/components/parameters/repo" - "$ref": "#/components/parameters/branch" requestBody: required: false content: application/json: schema: oneOf: - type: object properties: teams: type: array description: teams parameter items: type: string required: - teams example: teams: - my-team - type: array description: teams parameter items: type: string responses: '200': description: Response content: application/json: schema: type: array items: "$ref": "#/components/schemas/team" examples: default: "$ref": "#/components/examples/team-items" '422': "$ref": "#/components/responses/validation_failed" x-github: githubCloudOnly: false enabledForGitHubApps: true requestBodyParameterName: teams category: repos subcategory: branches delete: summary: Remove team access restrictions description: |- Protected branches are available in public repositories with GitHub Free and GitHub Free for organizations, and in public and private repositories with GitHub Pro, GitHub Team, GitHub Enterprise Cloud, and GitHub Enterprise Server. For more information, see [GitHub's products](https://docs.github.com/github/getting-started-with-github/githubs-products) in the GitHub Help documentation. Removes the ability of a team to push to this branch. You can also remove push access for child teams. | Type | Description | | ------- | --------------------------------------------------------------------------------------------------------------------------------------------------- | | `array` | Teams that should no longer have push access. Use the team's `slug`. **Note**: The list of users, apps, and teams in total is limited to 100 items. | tags: - repos operationId: repos/remove-team-access-restrictions externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/repos#remove-team-access-restrictions parameters: - "$ref": "#/components/parameters/owner" - "$ref": "#/components/parameters/repo" - "$ref": "#/components/parameters/branch" requestBody: content: application/json: schema: oneOf: - type: object properties: teams: type: array description: teams parameter items: type: string required: - teams example: teams: - my-team - type: array description: teams parameter items: type: string responses: '200': description: Response content: application/json: schema: type: array items: "$ref": "#/components/schemas/team" examples: default: "$ref": "#/components/examples/team-items" '422': "$ref": "#/components/responses/validation_failed" x-github: githubCloudOnly: false enabledForGitHubApps: true requestBodyParameterName: teams category: repos subcategory: branches "/repos/{owner}/{repo}/branches/{branch}/protection/restrictions/users": get: summary: Get users with access to the protected branch description: |- Protected branches are available in public repositories with GitHub Free and GitHub Free for organizations, and in public and private repositories with GitHub Pro, GitHub Team, GitHub Enterprise Cloud, and GitHub Enterprise Server. For more information, see [GitHub's products](https://docs.github.com/github/getting-started-with-github/githubs-products) in the GitHub Help documentation. Lists the people who have push access to this branch. tags: - repos operationId: repos/get-users-with-access-to-protected-branch externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/repos#list-users-with-access-to-the-protected-branch parameters: - "$ref": "#/components/parameters/owner" - "$ref": "#/components/parameters/repo" - "$ref": "#/components/parameters/branch" responses: '200': description: Response content: application/json: schema: type: array items: "$ref": "#/components/schemas/simple-user" examples: default: "$ref": "#/components/examples/simple-user-items" '404': "$ref": "#/components/responses/not_found" x-github: githubCloudOnly: false enabledForGitHubApps: true category: repos subcategory: branches post: summary: Add user access restrictions description: |- Protected branches are available in public repositories with GitHub Free and GitHub Free for organizations, and in public and private repositories with GitHub Pro, GitHub Team, GitHub Enterprise Cloud, and GitHub Enterprise Server. For more information, see [GitHub's products](https://docs.github.com/github/getting-started-with-github/githubs-products) in the GitHub Help documentation. Grants the specified people push access for this branch. | Type | Description | | ------- | ----------------------------------------------------------------------------------------------------------------------------- | | `array` | Usernames for people who can have push access. **Note**: The list of users, apps, and teams in total is limited to 100 items. | tags: - repos operationId: repos/add-user-access-restrictions externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/repos#add-user-access-restrictions parameters: - "$ref": "#/components/parameters/owner" - "$ref": "#/components/parameters/repo" - "$ref": "#/components/parameters/branch" requestBody: required: false content: application/json: schema: oneOf: - type: object properties: users: type: array description: users parameter items: type: string required: - users example: users: - mona - type: array items: type: string responses: '200': description: Response content: application/json: schema: type: array items: "$ref": "#/components/schemas/simple-user" examples: default: "$ref": "#/components/examples/simple-user-items" '422': "$ref": "#/components/responses/validation_failed" x-github: githubCloudOnly: false enabledForGitHubApps: true requestBodyParameterName: users category: repos subcategory: branches put: summary: Set user access restrictions description: |- Protected branches are available in public repositories with GitHub Free and GitHub Free for organizations, and in public and private repositories with GitHub Pro, GitHub Team, GitHub Enterprise Cloud, and GitHub Enterprise Server. For more information, see [GitHub's products](https://docs.github.com/github/getting-started-with-github/githubs-products) in the GitHub Help documentation. Replaces the list of people that have push access to this branch. This removes all people that previously had push access and grants push access to the new list of people. | Type | Description | | ------- | ----------------------------------------------------------------------------------------------------------------------------- | | `array` | Usernames for people who can have push access. **Note**: The list of users, apps, and teams in total is limited to 100 items. | tags: - repos operationId: repos/set-user-access-restrictions externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/repos#set-user-access-restrictions parameters: - "$ref": "#/components/parameters/owner" - "$ref": "#/components/parameters/repo" - "$ref": "#/components/parameters/branch" requestBody: required: false content: application/json: schema: oneOf: - type: object properties: users: type: array description: users parameter items: type: string required: - users example: users: - mona - type: array items: type: string responses: '200': description: Response content: application/json: schema: type: array items: "$ref": "#/components/schemas/simple-user" examples: default: "$ref": "#/components/examples/simple-user-items" '422': "$ref": "#/components/responses/validation_failed" x-github: githubCloudOnly: false enabledForGitHubApps: true requestBodyParameterName: users category: repos subcategory: branches delete: summary: Remove user access restrictions description: |- Protected branches are available in public repositories with GitHub Free and GitHub Free for organizations, and in public and private repositories with GitHub Pro, GitHub Team, GitHub Enterprise Cloud, and GitHub Enterprise Server. For more information, see [GitHub's products](https://docs.github.com/github/getting-started-with-github/githubs-products) in the GitHub Help documentation. Removes the ability of a user to push to this branch. | Type | Description | | ------- | --------------------------------------------------------------------------------------------------------------------------------------------- | | `array` | Usernames of the people who should no longer have push access. **Note**: The list of users, apps, and teams in total is limited to 100 items. | tags: - repos operationId: repos/remove-user-access-restrictions externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/repos#remove-user-access-restrictions parameters: - "$ref": "#/components/parameters/owner" - "$ref": "#/components/parameters/repo" - "$ref": "#/components/parameters/branch" requestBody: content: application/json: schema: oneOf: - type: object properties: users: type: array description: users parameter items: type: string required: - users example: users: - mona - type: array items: type: string responses: '200': description: Response content: application/json: schema: type: array items: "$ref": "#/components/schemas/simple-user" examples: default: "$ref": "#/components/examples/simple-user-items" '422': "$ref": "#/components/responses/validation_failed" x-github: githubCloudOnly: false enabledForGitHubApps: true requestBodyParameterName: users category: repos subcategory: branches "/repos/{owner}/{repo}/check-runs": post: summary: Create a check run description: |- **Note:** The Checks API only looks for pushes in the repository where the check suite or check run were created. Pushes to a branch in a forked repository are not detected and return an empty `pull_requests` array. Creates a new check run for a specific commit in a repository. Your GitHub App must have the `checks:write` permission to create check runs. In a check suite, GitHub limits the number of check runs with the same name to 1000. Once these check runs exceed 1000, GitHub will start to automatically delete older check runs. tags: - checks operationId: checks/create externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/checks#create-a-check-run parameters: - "$ref": "#/components/parameters/owner" - "$ref": "#/components/parameters/repo" requestBody: required: true content: application/json: schema: type: object properties: name: type: string description: The name of the check. For example, "code-coverage". head_sha: type: string description: The SHA of the commit. details_url: type: string description: The URL of the integrator's site that has the full details of the check. If the integrator does not provide this, then the homepage of the GitHub app is used. external_id: type: string description: A reference for the run on the integrator's system. status: type: string description: The current status. Can be one of `queued`, `in_progress`, or `completed`. enum: - queued - in_progress - completed default: queued started_at: type: string format: date-time description: 'The time that the check run began. This is a timestamp in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format: `YYYY-MM-DDTHH:MM:SSZ`.' conclusion: type: string description: "**Required if you provide `completed_at` or a `status` of `completed`**. The final conclusion of the check. Can be one of `action_required`, `cancelled`, `failure`, `neutral`, `success`, `skipped`, `stale`, or `timed_out`. When the conclusion is `action_required`, additional details should be provided on the site specified by `details_url`. \n**Note:** Providing `conclusion` will automatically set the `status` parameter to `completed`. You cannot change a check run conclusion to `stale`, only GitHub can set this." enum: - action_required - cancelled - failure - neutral - success - skipped - stale - timed_out completed_at: type: string format: date-time description: 'The time the check completed. This is a timestamp in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format: `YYYY-MM-DDTHH:MM:SSZ`.' output: type: object description: Check runs can accept a variety of data in the `output` object, including a `title` and `summary` and can optionally provide descriptive details about the run. See the [`output` object](https://docs.github.com/enterprise-server@3.0/rest/reference/checks#output-object) description. properties: title: type: string description: The title of the check run. summary: type: string maxLength: 65535 description: The summary of the check run. This parameter supports Markdown. text: type: string maxLength: 65535 description: The details of the check run. This parameter supports Markdown. annotations: type: array description: Adds information from your analysis to specific lines of code. Annotations are visible on GitHub in the **Checks** and **Files changed** tab of the pull request. The Checks API limits the number of annotations to a maximum of 50 per API request. To create more than 50 annotations, you have to make multiple requests to the [Update a check run](https://docs.github.com/enterprise-server@3.0/rest/reference/checks#update-a-check-run) endpoint. Each time you update the check run, annotations are appended to the list of annotations that already exist for the check run. For details about how you can view annotations on GitHub, see "[About status checks](https://docs.github.com/articles/about-status-checks#checks)". See the [`annotations` object](https://docs.github.com/enterprise-server@3.0/rest/reference/checks#annotations-object) description for details about how to use this parameter. maxItems: 50 items: type: object properties: path: type: string description: The path of the file to add an annotation to. For example, `assets/css/main.css`. start_line: type: integer description: The start line of the annotation. end_line: type: integer description: The end line of the annotation. start_column: type: integer description: The start column of the annotation. Annotations only support `start_column` and `end_column` on the same line. Omit this parameter if `start_line` and `end_line` have different values. end_column: type: integer description: The end column of the annotation. Annotations only support `start_column` and `end_column` on the same line. Omit this parameter if `start_line` and `end_line` have different values. annotation_level: type: string description: The level of the annotation. Can be one of `notice`, `warning`, or `failure`. enum: - notice - warning - failure message: type: string description: A short description of the feedback for these lines of code. The maximum size is 64 KB. title: type: string description: The title that represents the annotation. The maximum size is 255 characters. raw_details: type: string description: Details about this annotation. The maximum size is 64 KB. required: - path - start_line - end_line - annotation_level - message images: type: array description: Adds images to the output displayed in the GitHub pull request UI. See the [`images` object](https://docs.github.com/enterprise-server@3.0/rest/reference/checks#images-object) description for details. items: type: object properties: alt: type: string description: The alternative text for the image. image_url: type: string description: The full URL of the image. caption: type: string description: A short image description. required: - alt - image_url required: - title - summary actions: type: array description: Displays a button on GitHub that can be clicked to alert your app to do additional tasks. For example, a code linting app can display a button that automatically fixes detected errors. The button created in this object is displayed after the check run completes. When a user clicks the button, GitHub sends the [`check_run.requested_action` webhook](https://docs.github.com/enterprise-server@3.0/webhooks/event-payloads/#check_run) to your app. Each action includes a `label`, `identifier` and `description`. A maximum of three actions are accepted. See the [`actions` object](https://docs.github.com/enterprise-server@3.0/rest/reference/checks#actions-object) description. To learn more about check runs and requested actions, see "[Check runs and requested actions](https://docs.github.com/enterprise-server@3.0/rest/reference/checks#check-runs-and-requested-actions)." maxItems: 3 items: type: object properties: label: type: string maxLength: 20 description: The text to be displayed on a button in the web UI. The maximum size is 20 characters. description: type: string maxLength: 40 description: A short explanation of what this action would do. The maximum size is 40 characters. identifier: type: string maxLength: 20 description: A reference for the action on the integrator's system. The maximum size is 20 characters. required: - label - description - identifier required: - name - head_sha oneOf: - properties: status: enum: - completed required: - status - conclusion additionalProperties: true - properties: status: enum: - queued - in_progress additionalProperties: true examples: example-of-in-progress-conclusion: summary: Response for in_progress conclusion value: name: mighty_readme head_sha: ce587453ced02b1526dfb4cb910479d431683101 status: in_progress external_id: '42' started_at: '2018-05-04T01:14:52Z' output: title: Mighty Readme report summary: '' text: '' example-of-completed-conclusion: summary: Response for completed conclusion value: name: mighty_readme head_sha: ce587453ced02b1526dfb4cb910479d431683101 status: completed started_at: '2017-11-30T19:39:10Z' conclusion: success completed_at: '2017-11-30T19:49:10Z' output: title: Mighty Readme report summary: There are 0 failures, 2 warnings, and 1 notices. text: You may have some misspelled words on lines 2 and 4. You also may want to add a section in your README about how to install your app. annotations: - path: README.md annotation_level: warning title: Spell Checker message: Check your spelling for 'banaas'. raw_details: Do you mean 'bananas' or 'banana'? start_line: 2 end_line: 2 - path: README.md annotation_level: warning title: Spell Checker message: Check your spelling for 'aples' raw_details: Do you mean 'apples' or 'Naples' start_line: 4 end_line: 4 images: - alt: Super bananas image_url: http://example.com/images/42 actions: - label: Fix identifier: fix_errors description: Allow us to fix these errors for you responses: '201': description: Response content: application/json: schema: "$ref": "#/components/schemas/check-run" examples: example-of-completed-conclusion: "$ref": "#/components/examples/check-run-example-of-completed-conclusion" x-github: githubCloudOnly: false enabledForGitHubApps: true category: checks subcategory: runs "/repos/{owner}/{repo}/check-runs/{check_run_id}": get: summary: Get a check run description: |- **Note:** The Checks API only looks for pushes in the repository where the check suite or check run were created. Pushes to a branch in a forked repository are not detected and return an empty `pull_requests` array. Gets a single check run using its `id`. GitHub Apps must have the `checks:read` permission on a private repository or pull access to a public repository to get check runs. OAuth Apps and authenticated users must have the `repo` scope to get check runs in a private repository. tags: - checks operationId: checks/get externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/checks#get-a-check-run parameters: - "$ref": "#/components/parameters/owner" - "$ref": "#/components/parameters/repo" - "$ref": "#/components/parameters/check-run-id" responses: '200': description: Response content: application/json: schema: "$ref": "#/components/schemas/check-run" examples: default: "$ref": "#/components/examples/check-run" x-github: githubCloudOnly: false enabledForGitHubApps: true category: checks subcategory: runs patch: summary: Update a check run description: |- **Note:** The Checks API only looks for pushes in the repository where the check suite or check run were created. Pushes to a branch in a forked repository are not detected and return an empty `pull_requests` array. Updates a check run for a specific commit in a repository. Your GitHub App must have the `checks:write` permission to edit check runs. tags: - checks operationId: checks/update externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/checks#update-a-check-run parameters: - "$ref": "#/components/parameters/owner" - "$ref": "#/components/parameters/repo" - "$ref": "#/components/parameters/check-run-id" requestBody: required: true content: application/json: schema: type: object properties: name: type: string description: The name of the check. For example, "code-coverage". details_url: type: string description: The URL of the integrator's site that has the full details of the check. external_id: type: string description: A reference for the run on the integrator's system. started_at: type: string format: date-time description: 'This is a timestamp in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format: `YYYY-MM-DDTHH:MM:SSZ`.' status: type: string description: The current status. Can be one of `queued`, `in_progress`, or `completed`. enum: - queued - in_progress - completed conclusion: type: string description: "**Required if you provide `completed_at` or a `status` of `completed`**. The final conclusion of the check. Can be one of `action_required`, `cancelled`, `failure`, `neutral`, `success`, `skipped`, `stale`, or `timed_out`. \n**Note:** Providing `conclusion` will automatically set the `status` parameter to `completed`. You cannot change a check run conclusion to `stale`, only GitHub can set this." enum: - action_required - cancelled - failure - neutral - success - skipped - stale - timed_out completed_at: type: string format: date-time description: 'The time the check completed. This is a timestamp in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format: `YYYY-MM-DDTHH:MM:SSZ`.' output: type: object description: Check runs can accept a variety of data in the `output` object, including a `title` and `summary` and can optionally provide descriptive details about the run. See the [`output` object](https://docs.github.com/enterprise-server@3.0/rest/reference/checks#output-object-1) description. properties: title: type: string description: "**Required**." summary: type: string description: Can contain Markdown. maxLength: 65535 text: type: string description: Can contain Markdown. maxLength: 65535 annotations: type: array description: Adds information from your analysis to specific lines of code. Annotations are visible in GitHub's pull request UI. Annotations are visible in GitHub's pull request UI. The Checks API limits the number of annotations to a maximum of 50 per API request. To create more than 50 annotations, you have to make multiple requests to the [Update a check run](https://docs.github.com/enterprise-server@3.0/rest/reference/checks#update-a-check-run) endpoint. Each time you update the check run, annotations are appended to the list of annotations that already exist for the check run. For details about annotations in the UI, see "[About status checks](https://docs.github.com/articles/about-status-checks#checks)". See the [`annotations` object](https://docs.github.com/enterprise-server@3.0/rest/reference/checks#annotations-object-1) description for details. maxItems: 50 items: type: object properties: path: type: string description: The path of the file to add an annotation to. For example, `assets/css/main.css`. start_line: type: integer description: The start line of the annotation. end_line: type: integer description: The end line of the annotation. start_column: type: integer description: The start column of the annotation. Annotations only support `start_column` and `end_column` on the same line. Omit this parameter if `start_line` and `end_line` have different values. end_column: type: integer description: The end column of the annotation. Annotations only support `start_column` and `end_column` on the same line. Omit this parameter if `start_line` and `end_line` have different values. annotation_level: type: string description: The level of the annotation. Can be one of `notice`, `warning`, or `failure`. enum: - notice - warning - failure message: type: string description: A short description of the feedback for these lines of code. The maximum size is 64 KB. title: type: string description: The title that represents the annotation. The maximum size is 255 characters. raw_details: type: string description: Details about this annotation. The maximum size is 64 KB. required: - path - start_line - end_line - annotation_level - message images: type: array description: Adds images to the output displayed in the GitHub pull request UI. See the [`images` object](https://docs.github.com/enterprise-server@3.0/rest/reference/checks#annotations-object-1) description for details. items: type: object properties: alt: type: string description: The alternative text for the image. image_url: type: string description: The full URL of the image. caption: type: string description: A short image description. required: - alt - image_url required: - summary actions: type: array description: Possible further actions the integrator can perform, which a user may trigger. Each action includes a `label`, `identifier` and `description`. A maximum of three actions are accepted. See the [`actions` object](https://docs.github.com/enterprise-server@3.0/rest/reference/checks#actions-object) description. To learn more about check runs and requested actions, see "[Check runs and requested actions](https://docs.github.com/enterprise-server@3.0/rest/reference/checks#check-runs-and-requested-actions)." maxItems: 3 items: type: object properties: label: type: string maxLength: 20 description: The text to be displayed on a button in the web UI. The maximum size is 20 characters. description: type: string maxLength: 40 description: A short explanation of what this action would do. The maximum size is 40 characters. identifier: type: string maxLength: 20 description: A reference for the action on the integrator's system. The maximum size is 20 characters. required: - label - description - identifier anyOf: - properties: status: enum: - completed required: - conclusion additionalProperties: true - properties: status: enum: - queued - in_progress additionalProperties: true example: name: mighty_readme started_at: '2018-05-04T01:14:52Z' status: completed conclusion: success completed_at: '2018-05-04T01:14:52Z' output: title: Mighty Readme report summary: There are 0 failures, 2 warnings, and 1 notices. text: You may have some misspelled words on lines 2 and 4. You also may want to add a section in your README about how to install your app. annotations: - path: README.md annotation_level: warning title: Spell Checker message: Check your spelling for 'banaas'. raw_details: Do you mean 'bananas' or 'banana'? start_line: 2 end_line: 2 - path: README.md annotation_level: warning title: Spell Checker message: Check your spelling for 'aples' raw_details: Do you mean 'apples' or 'Naples' start_line: 4 end_line: 4 images: - alt: Super bananas image_url: http://example.com/images/42 responses: '200': description: Response content: application/json: schema: "$ref": "#/components/schemas/check-run" examples: default: "$ref": "#/components/examples/check-run" x-github: githubCloudOnly: false enabledForGitHubApps: true category: checks subcategory: runs "/repos/{owner}/{repo}/check-runs/{check_run_id}/annotations": get: summary: List check run annotations description: Lists annotations for a check run using the annotation `id`. GitHub Apps must have the `checks:read` permission on a private repository or pull access to a public repository to get annotations for a check run. OAuth Apps and authenticated users must have the `repo` scope to get annotations for a check run in a private repository. tags: - checks operationId: checks/list-annotations externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/checks#list-check-run-annotations parameters: - "$ref": "#/components/parameters/owner" - "$ref": "#/components/parameters/repo" - "$ref": "#/components/parameters/check-run-id" - "$ref": "#/components/parameters/per-page" - "$ref": "#/components/parameters/page" responses: '200': description: Response content: application/json: schema: type: array items: "$ref": "#/components/schemas/check-annotation" examples: default: "$ref": "#/components/examples/check-annotation-items" headers: Link: "$ref": "#/components/headers/link" x-github: githubCloudOnly: false enabledForGitHubApps: true category: checks subcategory: runs "/repos/{owner}/{repo}/check-suites": post: summary: Create a check suite description: |- **Note:** The Checks API only looks for pushes in the repository where the check suite or check run were created. Pushes to a branch in a forked repository are not detected and return an empty `pull_requests` array and a `null` value for `head_branch`. By default, check suites are automatically created when you create a [check run](https://docs.github.com/enterprise-server@3.0/rest/reference/checks#check-runs). You only need to use this endpoint for manually creating check suites when you've disabled automatic creation using "[Update repository preferences for check suites](https://docs.github.com/enterprise-server@3.0/rest/reference/checks#update-repository-preferences-for-check-suites)". Your GitHub App must have the `checks:write` permission to create check suites. tags: - checks operationId: checks/create-suite externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/checks#create-a-check-suite parameters: - "$ref": "#/components/parameters/owner" - "$ref": "#/components/parameters/repo" requestBody: required: true content: application/json: schema: type: object properties: head_sha: type: string description: The sha of the head commit. required: - head_sha example: head_sha: d6fde92930d4715a2b49857d24b940956b26d2d3 responses: '200': description: when the suite already existed content: application/json: schema: "$ref": "#/components/schemas/check-suite" examples: default: "$ref": "#/components/examples/check-suite" '201': description: Response when the suite was created content: application/json: schema: "$ref": "#/components/schemas/check-suite" examples: default: "$ref": "#/components/examples/check-suite" x-github: githubCloudOnly: false enabledForGitHubApps: true category: checks subcategory: suites "/repos/{owner}/{repo}/check-suites/preferences": patch: summary: Update repository preferences for check suites description: Changes the default automatic flow when creating check suites. By default, a check suite is automatically created each time code is pushed to a repository. When you disable the automatic creation of check suites, you can manually [Create a check suite](https://docs.github.com/enterprise-server@3.0/rest/reference/checks#create-a-check-suite). You must have admin permissions in the repository to set preferences for check suites. tags: - checks operationId: checks/set-suites-preferences externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/checks#update-repository-preferences-for-check-suites parameters: - "$ref": "#/components/parameters/owner" - "$ref": "#/components/parameters/repo" requestBody: required: true content: application/json: schema: type: object properties: auto_trigger_checks: type: array description: Enables or disables automatic creation of CheckSuite events upon pushes to the repository. Enabled by default. See the [`auto_trigger_checks` object](https://docs.github.com/enterprise-server@3.0/rest/reference/checks#auto_trigger_checks-object) description for details. items: type: object properties: app_id: type: integer description: The `id` of the GitHub App. setting: type: boolean description: Set to `true` to enable automatic creation of CheckSuite events upon pushes to the repository, or `false` to disable them. default: true required: - app_id - setting example: auto_trigger_checks: - app_id: 4 setting: false responses: '200': description: Response content: application/json: schema: "$ref": "#/components/schemas/check-suite-preference" examples: default: "$ref": "#/components/examples/check-suite-preference" x-github: githubCloudOnly: false enabledForGitHubApps: true category: checks subcategory: suites "/repos/{owner}/{repo}/check-suites/{check_suite_id}": get: summary: Get a check suite description: |- **Note:** The Checks API only looks for pushes in the repository where the check suite or check run were created. Pushes to a branch in a forked repository are not detected and return an empty `pull_requests` array and a `null` value for `head_branch`. Gets a single check suite using its `id`. GitHub Apps must have the `checks:read` permission on a private repository or pull access to a public repository to get check suites. OAuth Apps and authenticated users must have the `repo` scope to get check suites in a private repository. tags: - checks operationId: checks/get-suite externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/checks#get-a-check-suite parameters: - "$ref": "#/components/parameters/owner" - "$ref": "#/components/parameters/repo" - "$ref": "#/components/parameters/check-suite-id" responses: '200': description: Response content: application/json: schema: "$ref": "#/components/schemas/check-suite" examples: default: "$ref": "#/components/examples/check-suite" x-github: githubCloudOnly: false enabledForGitHubApps: true category: checks subcategory: suites "/repos/{owner}/{repo}/check-suites/{check_suite_id}/check-runs": get: summary: List check runs in a check suite description: |- **Note:** The Checks API only looks for pushes in the repository where the check suite or check run were created. Pushes to a branch in a forked repository are not detected and return an empty `pull_requests` array. Lists check runs for a check suite using its `id`. GitHub Apps must have the `checks:read` permission on a private repository or pull access to a public repository to get check runs. OAuth Apps and authenticated users must have the `repo` scope to get check runs in a private repository. tags: - checks operationId: checks/list-for-suite externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/checks#list-check-runs-in-a-check-suite parameters: - "$ref": "#/components/parameters/owner" - "$ref": "#/components/parameters/repo" - "$ref": "#/components/parameters/check-suite-id" - "$ref": "#/components/parameters/check-name" - "$ref": "#/components/parameters/status" - name: filter description: Filters check runs by their `completed_at` timestamp. Can be one of `latest` (returning the most recent check runs) or `all`. in: query required: false schema: type: string enum: - latest - all default: latest - "$ref": "#/components/parameters/per-page" - "$ref": "#/components/parameters/page" responses: '200': description: Response content: application/json: schema: type: object required: - total_count - check_runs properties: total_count: type: integer check_runs: type: array items: "$ref": "#/components/schemas/check-run" examples: default: "$ref": "#/components/examples/check-run-paginated" headers: Link: "$ref": "#/components/headers/link" x-github: githubCloudOnly: false enabledForGitHubApps: true category: checks subcategory: runs "/repos/{owner}/{repo}/check-suites/{check_suite_id}/rerequest": post: summary: Rerequest a check suite description: |- Triggers GitHub to rerequest an existing check suite, without pushing new code to a repository. This endpoint will trigger the [`check_suite` webhook](https://docs.github.com/enterprise-server@3.0/webhooks/event-payloads/#check_suite) event with the action `rerequested`. When a check suite is `rerequested`, its `status` is reset to `queued` and the `conclusion` is cleared. To rerequest a check suite, your GitHub App must have the `checks:read` permission on a private repository or pull access to a public repository. tags: - checks operationId: checks/rerequest-suite externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/checks#rerequest-a-check-suite parameters: - "$ref": "#/components/parameters/owner" - "$ref": "#/components/parameters/repo" - "$ref": "#/components/parameters/check-suite-id" responses: '201': description: Response content: application/json: schema: type: object properties: {} additionalProperties: false x-github: githubCloudOnly: false enabledForGitHubApps: true category: checks subcategory: suites "/repos/{owner}/{repo}/code-scanning/alerts": get: summary: List code scanning alerts for a repository description: |- Lists all open code scanning alerts for the default branch (usually `main` or `master`). You must use an access token with the `security_events` scope to use this endpoint. GitHub Apps must have the `security_events` read permission to use this endpoint. The response includes a `most_recent_instance` object. This provides details of the most recent instance of this alert for the default branch or for the specified Git reference (if you used `ref` in the request). tags: - code-scanning operationId: code-scanning/list-alerts-for-repo externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/code-scanning#list-code-scanning-alerts-for-a-repository parameters: - "$ref": "#/components/parameters/owner" - "$ref": "#/components/parameters/repo" - "$ref": "#/components/parameters/tool-name" - "$ref": "#/components/parameters/tool-guid" - "$ref": "#/components/parameters/page" - "$ref": "#/components/parameters/per-page" - "$ref": "#/components/parameters/git-ref" - name: state description: Set to `open`, `fixed`, or `dismissed` to list code scanning alerts in a specific state. in: query required: false schema: "$ref": "#/components/schemas/code-scanning-alert-state" responses: '200': description: Response content: application/json: schema: type: array items: "$ref": "#/components/schemas/code-scanning-alert-items" examples: default: "$ref": "#/components/examples/code-scanning-alert-items" '403': "$ref": "#/components/responses/code_scanning_forbidden_read" '404': "$ref": "#/components/responses/not_found" '503': "$ref": "#/components/responses/service_unavailable" x-github: githubCloudOnly: false enabledForGitHubApps: true category: code-scanning subcategory: "/repos/{owner}/{repo}/code-scanning/alerts/{alert_number}": get: summary: Get a code scanning alert description: |- Gets a single code scanning alert. You must use an access token with the `security_events` scope to use this endpoint. GitHub Apps must have the `security_events` read permission to use this endpoint. **Deprecation notice**: The instances field is deprecated and will, in future, not be included in the response for this endpoint. The example response reflects this change. The same information can now be retrieved via a GET request to the URL specified by `instances_url`. tags: - code-scanning operationId: code-scanning/get-alert externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/code-scanning#get-a-code-scanning-alert parameters: - "$ref": "#/components/parameters/owner" - "$ref": "#/components/parameters/repo" - "$ref": "#/components/parameters/alert-number" responses: '200': description: Response content: application/json: schema: "$ref": "#/components/schemas/code-scanning-alert" examples: default: "$ref": "#/components/examples/code-scanning-alert" '403': "$ref": "#/components/responses/code_scanning_forbidden_read" '404': "$ref": "#/components/responses/not_found" '503': "$ref": "#/components/responses/service_unavailable" x-github: githubCloudOnly: false enabledForGitHubApps: true category: code-scanning subcategory: patch: summary: Update a code scanning alert description: Updates the status of a single code scanning alert. You must use an access token with the `security_events` scope to use this endpoint. GitHub Apps must have the `security_events` write permission to use this endpoint. operationId: code-scanning/update-alert tags: - code-scanning externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/code-scanning#update-a-code-scanning-alert parameters: - "$ref": "#/components/parameters/owner" - "$ref": "#/components/parameters/repo" - "$ref": "#/components/parameters/alert-number" requestBody: required: true content: application/json: schema: type: object properties: state: "$ref": "#/components/schemas/code-scanning-alert-set-state" dismissed_reason: "$ref": "#/components/schemas/code-scanning-alert-dismissed-reason" required: - state example: state: dismissed dismissed_reason: false positive responses: '200': description: Response content: application/json: schema: "$ref": "#/components/schemas/code-scanning-alert" examples: default: "$ref": "#/components/examples/code-scanning-alert-dismissed" '403': "$ref": "#/components/responses/code_scanning_forbidden_write" '404': "$ref": "#/components/responses/not_found" '503': "$ref": "#/components/responses/service_unavailable" x-github: enabledForGitHubApps: true githubCloudOnly: false category: code-scanning "/repos/{owner}/{repo}/code-scanning/analyses": get: summary: List code scanning analyses for a repository description: |- Lists the details of all code scanning analyses for a repository, starting with the most recent. The response is paginated and you can use the `page` and `per_page` parameters to list the analyses you're interested in. By default 30 analyses are listed per page. The `rules_count` field in the response give the number of rules that were run in the analysis. For very old analyses this data is not available, and `0` is returned in this field. You must use an access token with the `security_events` scope to use this endpoint. GitHub Apps must have the `security_events` read permission to use this endpoint. **Deprecation notice**: The `tool_name` field is deprecated and will, in future, not be included in the response for this endpoint. The example response reflects this change. The tool name can now be found inside the `tool` field. operationId: code-scanning/list-recent-analyses tags: - code-scanning externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/code-scanning#list-code-scanning-analyses-for-a-repository parameters: - "$ref": "#/components/parameters/owner" - "$ref": "#/components/parameters/repo" - "$ref": "#/components/parameters/tool-name" - "$ref": "#/components/parameters/tool-guid" - "$ref": "#/components/parameters/page" - "$ref": "#/components/parameters/per-page" - name: ref in: query description: The Git reference for the analyses you want to list. The `ref` for a branch can be formatted either as `refs/heads/` or simply ``. To reference a pull request use `refs/pull//merge`. required: false schema: "$ref": "#/components/schemas/code-scanning-ref" - name: sarif_id in: query description: Filter analyses belonging to the same SARIF upload. required: false schema: "$ref": "#/components/schemas/code-scanning-analysis-sarif-id" responses: '200': description: Response content: application/json: schema: type: array items: "$ref": "#/components/schemas/code-scanning-analysis" examples: default: "$ref": "#/components/examples/code-scanning-analysis-items" '403': "$ref": "#/components/responses/code_scanning_forbidden_read" '404': "$ref": "#/components/responses/not_found" '503': "$ref": "#/components/responses/service_unavailable" x-github: enabledForGitHubApps: true githubCloudOnly: false category: code-scanning "/repos/{owner}/{repo}/code-scanning/sarifs": post: summary: Upload an analysis as SARIF data description: |- Uploads SARIF data containing the results of a code scanning analysis to make the results available in a repository. You must use an access token with the `security_events` scope to use this endpoint. GitHub Apps must have the `security_events` write permission to use this endpoint. There are two places where you can upload code scanning results. - If you upload to a pull request, for example `--ref refs/pull/42/merge` or `--ref refs/pull/42/head`, then the results appear as alerts in a pull request check. For more information, see "[Triaging code scanning alerts in pull requests](/code-security/secure-coding/triaging-code-scanning-alerts-in-pull-requests)." - If you upload to a branch, for example `--ref refs/heads/my-branch`, then the results appear in the **Security** tab for your repository. For more information, see "[Managing code scanning alerts for your repository](/code-security/secure-coding/managing-code-scanning-alerts-for-your-repository#viewing-the-alerts-for-a-repository)." You must compress the SARIF-formatted analysis data that you want to upload, using `gzip`, and then encode it as a Base64 format string. For example: ``` gzip -c analysis-data.sarif | base64 -w0 ``` SARIF upload supports a maximum of 1000 results per analysis run. Any results over this limit are ignored. Typically, but not necessarily, a SARIF file contains a single run of a single tool. If a code scanning tool generates too many results, you should update the analysis configuration to run only the most important rules or queries. The `202 Accepted`, response includes an `id` value. You can use this ID to check the status of the upload by using this for the `/sarifs/{sarif_id}` endpoint. For more information, see "[Get information about a SARIF upload](/rest/reference/code-scanning#get-information-about-a-sarif-upload)." operationId: code-scanning/upload-sarif tags: - code-scanning externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/code-scanning#upload-a-sarif-file parameters: - "$ref": "#/components/parameters/owner" - "$ref": "#/components/parameters/repo" requestBody: required: true content: application/json: schema: type: object properties: commit_sha: "$ref": "#/components/schemas/code-scanning-analysis-commit-sha" ref: "$ref": "#/components/schemas/code-scanning-ref" sarif: "$ref": "#/components/schemas/code-scanning-analysis-sarif-file" checkout_uri: description: |- The base directory used in the analysis, as it appears in the SARIF file. This property is used to convert file paths from absolute to relative, so that alerts can be mapped to their correct location in the repository. type: string format: uri examples: - file:///github/workspace/ started_at: description: 'The time that the analysis run began. This is a timestamp in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format: `YYYY-MM-DDTHH:MM:SSZ`.' format: date-time type: string tool_name: description: The name of the tool used to generate the code scanning analysis. If this parameter is not used, the tool name defaults to "API". If the uploaded SARIF contains a tool GUID, this will be available for filtering using the `tool_guid` parameter of operations such as `GET /repos/{owner}/{repo}/code-scanning/alerts`. type: string required: - commit_sha - ref - sarif responses: '202': description: Response content: application/json: schema: "$ref": "#/components/schemas/code-scanning-sarifs-receipt" examples: default: "$ref": "#/components/examples/code-scanning-sarif-upload" '400': description: Bad Request if the sarif field is invalid '403': "$ref": "#/components/responses/code_scanning_forbidden_write" '404': "$ref": "#/components/responses/not_found" '413': description: Payload Too Large if the sarif field is too large '503': "$ref": "#/components/responses/service_unavailable" x-github: enabledForGitHubApps: true githubCloudOnly: false category: code-scanning "/repos/{owner}/{repo}/collaborators": get: summary: List repository collaborators description: |- For organization-owned repositories, the list of collaborators includes outside collaborators, organization members that are direct collaborators, organization members with access through team memberships, organization members with access through default organization permissions, and organization owners. Team members will include the members of child teams. You must authenticate using an access token with the `read:org` and `repo` scopes with push access to use this endpoint. GitHub Apps must have the `members` organization permission and `metadata` repository permission to use this endpoint. tags: - repos operationId: repos/list-collaborators externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/repos#list-repository-collaborators parameters: - "$ref": "#/components/parameters/owner" - "$ref": "#/components/parameters/repo" - name: affiliation description: "Filter collaborators returned by their affiliation. Can be one of: \n\\* `outside`: All outside collaborators of an organization-owned repository. \n\\* `direct`: All collaborators with permissions to an organization-owned repository, regardless of organization membership status. \n\\* `all`: All collaborators the authenticated user can see." in: query required: false schema: type: string enum: - outside - direct - all default: all - "$ref": "#/components/parameters/per-page" - "$ref": "#/components/parameters/page" responses: '200': description: Response content: application/json: schema: type: array items: "$ref": "#/components/schemas/collaborator" examples: default: "$ref": "#/components/examples/collaborator-items" headers: Link: "$ref": "#/components/headers/link" '404': "$ref": "#/components/responses/not_found" x-github: githubCloudOnly: false enabledForGitHubApps: true category: repos subcategory: collaborators "/repos/{owner}/{repo}/collaborators/{username}": get: summary: Check if a user is a repository collaborator description: |- For organization-owned repositories, the list of collaborators includes outside collaborators, organization members that are direct collaborators, organization members with access through team memberships, organization members with access through default organization permissions, and organization owners. Team members will include the members of child teams. You must authenticate using an access token with the `read:org` and `repo` scopes with push access to use this endpoint. GitHub Apps must have the `members` organization permission and `metadata` repository permission to use this endpoint. tags: - repos operationId: repos/check-collaborator externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/repos#check-if-a-user-is-a-repository-collaborator parameters: - "$ref": "#/components/parameters/owner" - "$ref": "#/components/parameters/repo" - "$ref": "#/components/parameters/username" responses: '204': description: Response if user is a collaborator '404': description: Not Found if user is not a collaborator x-github: githubCloudOnly: false enabledForGitHubApps: true category: repos subcategory: collaborators put: summary: Add a repository collaborator description: |- This endpoint triggers [notifications](https://docs.github.com/en/github/managing-subscriptions-and-notifications-on-github/about-notifications). Creating content too quickly using this endpoint may result in secondary rate limiting. See "[Secondary rate limits](https://docs.github.com/enterprise-server@3.0/rest/overview/resources-in-the-rest-api#secondary-rate-limits)" and "[Dealing with secondary rate limits](https://docs.github.com/enterprise-server@3.0/rest/guides/best-practices-for-integrators#dealing-with-secondary-rate-limits)" for details. For more information on permission levels, see "[Repository permission levels for an organization](https://docs.github.com/en/github/setting-up-and-managing-organizations-and-teams/repository-permission-levels-for-an-organization#permission-levels-for-repositories-owned-by-an-organization)". There are restrictions on which permissions can be granted to organization members when an organization base role is in place. In this case, the permission being given must be equal to or higher than the org base permission. Otherwise, the request will fail with: ``` Cannot assign {member} permission of {role name} ``` Note that, if you choose not to pass any parameters, you'll need to set `Content-Length` to zero when calling out to this endpoint. For more information, see "[HTTP verbs](https://docs.github.com/enterprise-server@3.0/rest/overview/resources-in-the-rest-api#http-verbs)." The invitee will receive a notification that they have been invited to the repository, which they must accept or decline. They may do this via the notifications page, the email they receive, or by using the [repository invitations API endpoints](https://docs.github.com/enterprise-server@3.0/rest/reference/repos#invitations). **Rate limits** You are limited to sending 50 invitations to a repository per 24 hour period. Note there is no limit if you are inviting organization members to an organization repository. tags: - repos operationId: repos/add-collaborator externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/repos#add-a-repository-collaborator parameters: - "$ref": "#/components/parameters/owner" - "$ref": "#/components/parameters/repo" - "$ref": "#/components/parameters/username" requestBody: required: false content: application/json: schema: type: object properties: permission: type: string description: "The permission to grant the collaborator. **Only valid on organization-owned repositories.** Can be one of: \n\\* `pull` - can pull, but not push to or administer this repository. \n\\* `push` - can pull and push, but not administer this repository. \ \n\\* `admin` - can pull, push and administer this repository. \ \n\\* `maintain` - Recommended for project managers who need to manage the repository without access to sensitive or destructive actions. \n\\* `triage` - Recommended for contributors who need to proactively manage issues and pull requests without write access." enum: - pull - push - admin - maintain - triage default: push permissions: type: string examples: - '"push"' responses: '201': description: Response when a new invitation is created content: application/json: schema: "$ref": "#/components/schemas/repository-invitation" examples: response-when-a-new-invitation-is-created: "$ref": "#/components/examples/repository-invitation-response-when-a-new-invitation-is-created" '204': description: Response when person is already a collaborator '422': "$ref": "#/components/responses/validation_failed" '403': "$ref": "#/components/responses/forbidden" x-github: triggersNotification: true githubCloudOnly: false enabledForGitHubApps: true category: repos subcategory: collaborators delete: summary: Remove a repository collaborator description: '' tags: - repos operationId: repos/remove-collaborator externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/repos#remove-a-repository-collaborator parameters: - "$ref": "#/components/parameters/owner" - "$ref": "#/components/parameters/repo" - "$ref": "#/components/parameters/username" responses: '204': description: Response x-github: githubCloudOnly: false enabledForGitHubApps: true category: repos subcategory: collaborators "/repos/{owner}/{repo}/collaborators/{username}/permission": get: summary: Get repository permissions for a user description: Checks the repository permission of a collaborator. The possible repository permissions are `admin`, `write`, `read`, and `none`. tags: - repos operationId: repos/get-collaborator-permission-level externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/repos#get-repository-permissions-for-a-user parameters: - "$ref": "#/components/parameters/owner" - "$ref": "#/components/parameters/repo" - "$ref": "#/components/parameters/username" responses: '200': description: if user has admin permissions content: application/json: schema: "$ref": "#/components/schemas/repository-collaborator-permission" examples: response-if-user-has-admin-permissions: "$ref": "#/components/examples/repository-collaborator-permission-response-if-user-has-admin-permissions" '404': "$ref": "#/components/responses/not_found" x-github: githubCloudOnly: false enabledForGitHubApps: true category: repos subcategory: collaborators "/repos/{owner}/{repo}/comments": get: summary: List commit comments for a repository description: |- Commit Comments use [these custom media types](https://docs.github.com/enterprise-server@3.0/rest/reference/repos#custom-media-types). You can read more about the use of media types in the API [here](https://docs.github.com/enterprise-server@3.0/rest/overview/media-types/). Comments are ordered by ascending ID. tags: - repos operationId: repos/list-commit-comments-for-repo externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/repos#list-commit-comments-for-a-repository parameters: - "$ref": "#/components/parameters/owner" - "$ref": "#/components/parameters/repo" - "$ref": "#/components/parameters/per-page" - "$ref": "#/components/parameters/page" responses: '200': description: Response content: application/json: schema: type: array items: "$ref": "#/components/schemas/commit-comment" examples: default: "$ref": "#/components/examples/commit-comment-items" headers: Link: "$ref": "#/components/headers/link" x-github: githubCloudOnly: false enabledForGitHubApps: true category: repos subcategory: comments previews: - required: false name: squirrel-girl note: |- An additional `reactions` object in the issue comment payload is currently available for developers to preview. During the preview period, the APIs may change without advance notice. Please see the [blog post](https://developer.github.com/changes/2016-05-12-reactions-api-preview) for full details. To access the API you must provide a custom [media type](https://docs.github.com/enterprise-server@3.0/rest/overview/media-types) in the `Accept` header: ```shell application/vnd.github.squirrel-girl-preview ``` The `reactions` key will have the following payload where `url` can be used to construct the API location for [listing and creating](https://docs.github.com/enterprise-server@3.0/rest/reference/reactions) reactions. "/repos/{owner}/{repo}/comments/{comment_id}": get: summary: Get a commit comment description: '' tags: - repos operationId: repos/get-commit-comment externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/repos#get-a-commit-comment parameters: - "$ref": "#/components/parameters/owner" - "$ref": "#/components/parameters/repo" - "$ref": "#/components/parameters/comment-id" responses: '200': description: Response content: application/json: schema: "$ref": "#/components/schemas/commit-comment" examples: default: "$ref": "#/components/examples/commit-comment" '404': "$ref": "#/components/responses/not_found" x-github: githubCloudOnly: false enabledForGitHubApps: true category: repos subcategory: comments previews: - required: false name: squirrel-girl note: |- An additional `reactions` object in the issue comment payload is currently available for developers to preview. During the preview period, the APIs may change without advance notice. Please see the [blog post](https://developer.github.com/changes/2016-05-12-reactions-api-preview) for full details. To access the API you must provide a custom [media type](https://docs.github.com/enterprise-server@3.0/rest/overview/media-types) in the `Accept` header: ```shell application/vnd.github.squirrel-girl-preview ``` The `reactions` key will have the following payload where `url` can be used to construct the API location for [listing and creating](https://docs.github.com/enterprise-server@3.0/rest/reference/reactions) reactions. patch: summary: Update a commit comment description: '' tags: - repos operationId: repos/update-commit-comment externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/repos#update-a-commit-comment parameters: - "$ref": "#/components/parameters/owner" - "$ref": "#/components/parameters/repo" - "$ref": "#/components/parameters/comment-id" requestBody: required: true content: application/json: schema: type: object properties: body: type: string description: The contents of the comment required: - body example: body: Nice change responses: '200': description: Response content: application/json: schema: "$ref": "#/components/schemas/commit-comment" examples: default: "$ref": "#/components/examples/commit-comment-2" '404': "$ref": "#/components/responses/not_found" x-github: githubCloudOnly: false enabledForGitHubApps: true category: repos subcategory: comments delete: summary: Delete a commit comment description: '' tags: - repos operationId: repos/delete-commit-comment externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/repos#delete-a-commit-comment parameters: - "$ref": "#/components/parameters/owner" - "$ref": "#/components/parameters/repo" - "$ref": "#/components/parameters/comment-id" responses: '204': description: Response '404': "$ref": "#/components/responses/not_found" x-github: githubCloudOnly: false enabledForGitHubApps: true category: repos subcategory: comments "/repos/{owner}/{repo}/comments/{comment_id}/reactions": get: summary: List reactions for a commit comment description: List the reactions to a [commit comment](https://docs.github.com/enterprise-server@3.0/rest/reference/repos#comments). tags: - reactions operationId: reactions/list-for-commit-comment externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/reactions#list-reactions-for-a-commit-comment parameters: - "$ref": "#/components/parameters/owner" - "$ref": "#/components/parameters/repo" - "$ref": "#/components/parameters/comment-id" - name: content description: Returns a single [reaction type](https://docs.github.com/enterprise-server@3.0/rest/reference/reactions#reaction-types). Omit this parameter to list all reactions to a commit comment. in: query required: false schema: type: string enum: - "+1" - "-1" - laugh - confused - heart - hooray - rocket - eyes - "$ref": "#/components/parameters/per-page" - "$ref": "#/components/parameters/page" responses: '200': description: Response content: application/json: schema: type: array items: "$ref": "#/components/schemas/reaction" examples: default: "$ref": "#/components/examples/reaction-items" headers: Link: "$ref": "#/components/headers/link" '404': "$ref": "#/components/responses/not_found" x-github: githubCloudOnly: false enabledForGitHubApps: true category: reactions previews: - required: true name: squirrel-girl note: |- An additional `reactions` object in the issue comment payload is currently available for developers to preview. During the preview period, the APIs may change without advance notice. Please see the [blog post](https://developer.github.com/changes/2016-05-12-reactions-api-preview) for full details. To access the API you must provide a custom [media type](https://docs.github.com/enterprise-server@3.0/rest/overview/media-types) in the `Accept` header: ```shell application/vnd.github.squirrel-girl-preview ``` The `reactions` key will have the following payload where `url` can be used to construct the API location for [listing and creating](https://docs.github.com/enterprise-server@3.0/rest/reference/reactions) reactions. post: summary: Create reaction for a commit comment description: Create a reaction to a [commit comment](https://docs.github.com/enterprise-server@3.0/rest/reference/repos#comments). A response with an HTTP `200` status means that you already added the reaction type to this commit comment. tags: - reactions operationId: reactions/create-for-commit-comment externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/reactions#create-reaction-for-a-commit-comment parameters: - "$ref": "#/components/parameters/owner" - "$ref": "#/components/parameters/repo" - "$ref": "#/components/parameters/comment-id" requestBody: required: true content: application/json: schema: type: object properties: content: type: string description: The [reaction type](https://docs.github.com/enterprise-server@3.0/rest/reference/reactions#reaction-types) to add to the commit comment. enum: - "+1" - "-1" - laugh - confused - heart - hooray - rocket - eyes required: - content example: content: heart responses: '200': description: Reaction exists content: application/json: schema: "$ref": "#/components/schemas/reaction" examples: default: "$ref": "#/components/examples/reaction" '201': description: Reaction created content: application/json: schema: "$ref": "#/components/schemas/reaction" examples: default: "$ref": "#/components/examples/reaction" '415': "$ref": "#/components/responses/preview_header_missing" '422': "$ref": "#/components/responses/validation_failed" x-github: githubCloudOnly: false enabledForGitHubApps: true category: reactions previews: - required: true name: squirrel-girl note: |- An additional `reactions` object in the issue comment payload is currently available for developers to preview. During the preview period, the APIs may change without advance notice. Please see the [blog post](https://developer.github.com/changes/2016-05-12-reactions-api-preview) for full details. To access the API you must provide a custom [media type](https://docs.github.com/enterprise-server@3.0/rest/overview/media-types) in the `Accept` header: ```shell application/vnd.github.squirrel-girl-preview ``` The `reactions` key will have the following payload where `url` can be used to construct the API location for [listing and creating](https://docs.github.com/enterprise-server@3.0/rest/reference/reactions) reactions. "/repos/{owner}/{repo}/comments/{comment_id}/reactions/{reaction_id}": delete: summary: Delete a commit comment reaction description: |- **Note:** You can also specify a repository by `repository_id` using the route `DELETE /repositories/:repository_id/comments/:comment_id/reactions/:reaction_id`. Delete a reaction to a [commit comment](https://docs.github.com/enterprise-server@3.0/rest/reference/repos#comments). tags: - reactions operationId: reactions/delete-for-commit-comment externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/reactions#delete-a-commit-comment-reaction parameters: - "$ref": "#/components/parameters/owner" - "$ref": "#/components/parameters/repo" - "$ref": "#/components/parameters/comment-id" - "$ref": "#/components/parameters/reaction-id" responses: '204': description: Response x-github: githubCloudOnly: false enabledForGitHubApps: true category: reactions previews: - required: true name: squirrel-girl note: |- An additional `reactions` object in the issue comment payload is currently available for developers to preview. During the preview period, the APIs may change without advance notice. Please see the [blog post](https://developer.github.com/changes/2016-05-12-reactions-api-preview) for full details. To access the API you must provide a custom [media type](https://docs.github.com/enterprise-server@3.0/rest/overview/media-types) in the `Accept` header: ```shell application/vnd.github.squirrel-girl-preview ``` The `reactions` key will have the following payload where `url` can be used to construct the API location for [listing and creating](https://docs.github.com/enterprise-server@3.0/rest/reference/reactions) reactions. "/repos/{owner}/{repo}/commits": get: summary: List commits description: |- **Signature verification object** The response will include a `verification` object that describes the result of verifying the commit's signature. The following fields are included in the `verification` object: | Name | Type | Description | | ---- | ---- | ----------- | | `verified` | `boolean` | Indicates whether GitHub considers the signature in this commit to be verified. | | `reason` | `string` | The reason for verified value. Possible values and their meanings are enumerated in table below. | | `signature` | `string` | The signature that was extracted from the commit. | | `payload` | `string` | The value that was signed. | These are the possible values for `reason` in the `verification` object: | Value | Description | | ----- | ----------- | | `expired_key` | The key that made the signature is expired. | | `not_signing_key` | The "signing" flag is not among the usage flags in the GPG key that made the signature. | | `gpgverify_error` | There was an error communicating with the signature verification service. | | `gpgverify_unavailable` | The signature verification service is currently unavailable. | | `unsigned` | The object does not include a signature. | | `unknown_signature_type` | A non-PGP signature was found in the commit. | | `no_user` | No user was associated with the `committer` email address in the commit. | | `unverified_email` | The `committer` email address in the commit was associated with a user, but the email address is not verified on her/his account. | | `bad_email` | The `committer` email address in the commit is not included in the identities of the PGP key that made the signature. | | `unknown_key` | The key that made the signature has not been registered with any user's account. | | `malformed_signature` | There was an error parsing the signature. | | `invalid` | The signature could not be cryptographically verified using the key whose key-id was found in the signature. | | `valid` | None of the above errors applied, so the signature is considered to be verified. | tags: - repos operationId: repos/list-commits externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/repos#list-commits parameters: - "$ref": "#/components/parameters/owner" - "$ref": "#/components/parameters/repo" - name: sha description: 'SHA or branch to start listing commits from. Default: the repository’s default branch (usually `master`).' in: query required: false schema: type: string - name: path description: Only commits containing this file path will be returned. in: query required: false schema: type: string - name: author description: GitHub login or email address by which to filter by commit author. in: query required: false schema: type: string - "$ref": "#/components/parameters/since" - name: until description: 'Only commits before this date will be returned. This is a timestamp in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format: `YYYY-MM-DDTHH:MM:SSZ`.' in: query required: false schema: type: string format: date-time - "$ref": "#/components/parameters/per-page" - "$ref": "#/components/parameters/page" responses: '200': description: Response content: application/json: schema: type: array items: "$ref": "#/components/schemas/commit" examples: default: "$ref": "#/components/examples/commit-items" headers: Link: "$ref": "#/components/headers/link" '500': "$ref": "#/components/responses/internal_error" '400': "$ref": "#/components/responses/bad_request" '404': "$ref": "#/components/responses/not_found" '409': "$ref": "#/components/responses/conflict" x-github: githubCloudOnly: false enabledForGitHubApps: true category: repos subcategory: commits "/repos/{owner}/{repo}/commits/{commit_sha}/branches-where-head": get: summary: List branches for HEAD commit description: |- Protected branches are available in public repositories with GitHub Free and GitHub Free for organizations, and in public and private repositories with GitHub Pro, GitHub Team, GitHub Enterprise Cloud, and GitHub Enterprise Server. For more information, see [GitHub's products](https://docs.github.com/github/getting-started-with-github/githubs-products) in the GitHub Help documentation. Returns all branches where the given commit SHA is the HEAD, or latest commit for the branch. tags: - repos operationId: repos/list-branches-for-head-commit externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/repos#list-branches-for-head-commit parameters: - "$ref": "#/components/parameters/owner" - "$ref": "#/components/parameters/repo" - "$ref": "#/components/parameters/commit-sha" responses: '200': description: Response content: application/json: schema: type: array items: "$ref": "#/components/schemas/branch-short" examples: default: "$ref": "#/components/examples/branch-short-items" '422': "$ref": "#/components/responses/validation_failed" x-github: githubCloudOnly: false enabledForGitHubApps: true category: repos subcategory: commits previews: - required: true name: groot note: |- Listing branches or pull requests for a commit in the Commits API is currently available for developers to preview. See the [blog post](https://developer.github.com/changes/2019-04-11-pulls-branches-for-commit/) for more details. To access the new endpoints during the preview period, you must provide a custom [media type](https://docs.github.com/enterprise-server@3.0/rest/overview/media-types) in the `Accept` header: ```shell application/vnd.github.groot-preview+json ``` "/repos/{owner}/{repo}/commits/{commit_sha}/comments": get: summary: List commit comments description: Use the `:commit_sha` to specify the commit that will have its comments listed. tags: - repos operationId: repos/list-comments-for-commit externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/repos#list-commit-comments parameters: - "$ref": "#/components/parameters/owner" - "$ref": "#/components/parameters/repo" - "$ref": "#/components/parameters/commit-sha" - "$ref": "#/components/parameters/per-page" - "$ref": "#/components/parameters/page" responses: '200': description: Response content: application/json: schema: type: array items: "$ref": "#/components/schemas/commit-comment" examples: default: "$ref": "#/components/examples/commit-comment-items" headers: Link: "$ref": "#/components/headers/link" x-github: githubCloudOnly: false enabledForGitHubApps: true category: repos subcategory: comments previews: - required: false name: squirrel-girl note: |- An additional `reactions` object in the issue comment payload is currently available for developers to preview. During the preview period, the APIs may change without advance notice. Please see the [blog post](https://developer.github.com/changes/2016-05-12-reactions-api-preview) for full details. To access the API you must provide a custom [media type](https://docs.github.com/enterprise-server@3.0/rest/overview/media-types) in the `Accept` header: ```shell application/vnd.github.squirrel-girl-preview ``` The `reactions` key will have the following payload where `url` can be used to construct the API location for [listing and creating](https://docs.github.com/enterprise-server@3.0/rest/reference/reactions) reactions. post: summary: Create a commit comment description: |- Create a comment for a commit using its `:commit_sha`. This endpoint triggers [notifications](https://docs.github.com/en/github/managing-subscriptions-and-notifications-on-github/about-notifications). Creating content too quickly using this endpoint may result in secondary rate limiting. See "[Secondary rate limits](https://docs.github.com/enterprise-server@3.0/rest/overview/resources-in-the-rest-api#secondary-rate-limits)" and "[Dealing with secondary rate limits](https://docs.github.com/enterprise-server@3.0/rest/guides/best-practices-for-integrators#dealing-with-secondary-rate-limits)" for details. tags: - repos operationId: repos/create-commit-comment externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/repos#create-a-commit-comment parameters: - "$ref": "#/components/parameters/owner" - "$ref": "#/components/parameters/repo" - "$ref": "#/components/parameters/commit-sha" requestBody: required: true content: application/json: schema: type: object properties: body: type: string description: The contents of the comment. path: type: string description: Relative path of the file to comment on. position: type: integer description: Line index in the diff to comment on. line: type: integer description: "**Deprecated**. Use **position** parameter instead. Line number in the file to comment on." required: - body example: body: Great stuff path: file1.txt position: 4 line: 1 responses: '201': description: Response content: application/json: schema: "$ref": "#/components/schemas/commit-comment" examples: default: "$ref": "#/components/examples/commit-comment" headers: Location: example: https://api.github.com/repos/octocat/Hello-World/comments/1 schema: type: string '403': "$ref": "#/components/responses/forbidden" '422': "$ref": "#/components/responses/validation_failed" x-github: triggersNotification: true githubCloudOnly: false enabledForGitHubApps: true category: repos subcategory: comments "/repos/{owner}/{repo}/commits/{commit_sha}/pulls": get: summary: List pull requests associated with a commit description: Lists the merged pull request that introduced the commit to the repository. If the commit is not present in the default branch, additionally returns open pull requests associated with the commit. The results may include open and closed pull requests. Additional preview headers may be required to see certain details for associated pull requests, such as whether a pull request is in a draft state. For more information about previews that might affect this endpoint, see the [List pull requests](https://docs.github.com/enterprise-server@3.0/rest/reference/pulls#list-pull-requests) endpoint. tags: - repos operationId: repos/list-pull-requests-associated-with-commit externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/repos#list-pull-requests-associated-with-a-commit parameters: - "$ref": "#/components/parameters/owner" - "$ref": "#/components/parameters/repo" - "$ref": "#/components/parameters/commit-sha" - "$ref": "#/components/parameters/per-page" - "$ref": "#/components/parameters/page" responses: '200': description: Response content: application/json: schema: type: array items: "$ref": "#/components/schemas/pull-request-simple" examples: default: "$ref": "#/components/examples/pull-request-simple-items" headers: Link: "$ref": "#/components/headers/link" x-github: githubCloudOnly: false enabledForGitHubApps: true category: repos subcategory: commits previews: - required: true name: groot note: |- Listing branches or pull requests for a commit in the Commits API is currently available for developers to preview. See the [blog post](https://developer.github.com/changes/2019-04-11-pulls-branches-for-commit/) for more details. To access the new endpoints during the preview period, you must provide a custom [media type](https://docs.github.com/enterprise-server@3.0/rest/overview/media-types) in the `Accept` header: ```shell application/vnd.github.groot-preview+json ``` "/repos/{owner}/{repo}/commits/{ref}": get: summary: Get a commit description: |- Returns the contents of a single commit reference. You must have `read` access for the repository to use this endpoint. **Note:** If there are more than 300 files in the commit diff, the response will include pagination link headers for the remaining files, up to a limit of 3000 files. Each page contains the static commit information, and the only changes are to the file listing. You can pass the appropriate [media type](https://docs.github.com/enterprise-server@3.0/rest/overview/media-types/#commits-commit-comparison-and-pull-requests) to fetch `diff` and `patch` formats. Diffs with binary data will have no `patch` property. To return only the SHA-1 hash of the commit reference, you can provide the `sha` custom [media type](https://docs.github.com/enterprise-server@3.0/rest/overview/media-types/#commits-commit-comparison-and-pull-requests) in the `Accept` header. You can use this endpoint to check if a remote reference's SHA-1 hash is the same as your local reference's SHA-1 hash by providing the local SHA-1 reference as the ETag. **Signature verification object** The response will include a `verification` object that describes the result of verifying the commit's signature. The following fields are included in the `verification` object: | Name | Type | Description | | ---- | ---- | ----------- | | `verified` | `boolean` | Indicates whether GitHub considers the signature in this commit to be verified. | | `reason` | `string` | The reason for verified value. Possible values and their meanings are enumerated in table below. | | `signature` | `string` | The signature that was extracted from the commit. | | `payload` | `string` | The value that was signed. | These are the possible values for `reason` in the `verification` object: | Value | Description | | ----- | ----------- | | `expired_key` | The key that made the signature is expired. | | `not_signing_key` | The "signing" flag is not among the usage flags in the GPG key that made the signature. | | `gpgverify_error` | There was an error communicating with the signature verification service. | | `gpgverify_unavailable` | The signature verification service is currently unavailable. | | `unsigned` | The object does not include a signature. | | `unknown_signature_type` | A non-PGP signature was found in the commit. | | `no_user` | No user was associated with the `committer` email address in the commit. | | `unverified_email` | The `committer` email address in the commit was associated with a user, but the email address is not verified on her/his account. | | `bad_email` | The `committer` email address in the commit is not included in the identities of the PGP key that made the signature. | | `unknown_key` | The key that made the signature has not been registered with any user's account. | | `malformed_signature` | There was an error parsing the signature. | | `invalid` | The signature could not be cryptographically verified using the key whose key-id was found in the signature. | | `valid` | None of the above errors applied, so the signature is considered to be verified. | tags: - repos operationId: repos/get-commit externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/repos#get-a-commit parameters: - "$ref": "#/components/parameters/owner" - "$ref": "#/components/parameters/repo" - "$ref": "#/components/parameters/page" - "$ref": "#/components/parameters/per-page" - name: ref description: ref parameter in: path required: true schema: type: string x-multi-segment: true responses: '200': description: Response content: application/json: schema: "$ref": "#/components/schemas/commit" examples: default: "$ref": "#/components/examples/commit" '422': "$ref": "#/components/responses/validation_failed" '404': "$ref": "#/components/responses/not_found" '500': "$ref": "#/components/responses/internal_error" x-github: githubCloudOnly: false enabledForGitHubApps: true category: repos subcategory: commits "/repos/{owner}/{repo}/commits/{ref}/check-runs": get: summary: List check runs for a Git reference description: |- **Note:** The Checks API only looks for pushes in the repository where the check suite or check run were created. Pushes to a branch in a forked repository are not detected and return an empty `pull_requests` array. Lists check runs for a commit ref. The `ref` can be a SHA, branch name, or a tag name. GitHub Apps must have the `checks:read` permission on a private repository or pull access to a public repository to get check runs. OAuth Apps and authenticated users must have the `repo` scope to get check runs in a private repository. tags: - checks operationId: checks/list-for-ref externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/checks#list-check-runs-for-a-git-reference parameters: - "$ref": "#/components/parameters/owner" - "$ref": "#/components/parameters/repo" - name: ref description: ref parameter in: path required: true schema: type: string x-multi-segment: true - "$ref": "#/components/parameters/check-name" - "$ref": "#/components/parameters/status" - name: filter description: Filters check runs by their `completed_at` timestamp. Can be one of `latest` (returning the most recent check runs) or `all`. in: query required: false schema: type: string enum: - latest - all default: latest - "$ref": "#/components/parameters/per-page" - "$ref": "#/components/parameters/page" - name: app_id in: query required: false schema: type: integer responses: '200': description: Response content: application/json: schema: type: object required: - total_count - check_runs properties: total_count: type: integer check_runs: type: array items: "$ref": "#/components/schemas/check-run" examples: default: "$ref": "#/components/examples/check-run-paginated" headers: Link: "$ref": "#/components/headers/link" x-github: githubCloudOnly: false enabledForGitHubApps: true category: checks subcategory: runs "/repos/{owner}/{repo}/commits/{ref}/check-suites": get: summary: List check suites for a Git reference description: |- **Note:** The Checks API only looks for pushes in the repository where the check suite or check run were created. Pushes to a branch in a forked repository are not detected and return an empty `pull_requests` array and a `null` value for `head_branch`. Lists check suites for a commit `ref`. The `ref` can be a SHA, branch name, or a tag name. GitHub Apps must have the `checks:read` permission on a private repository or pull access to a public repository to list check suites. OAuth Apps and authenticated users must have the `repo` scope to get check suites in a private repository. tags: - checks operationId: checks/list-suites-for-ref externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/checks#list-check-suites-for-a-git-reference parameters: - "$ref": "#/components/parameters/owner" - "$ref": "#/components/parameters/repo" - name: ref description: ref parameter in: path required: true schema: type: string x-multi-segment: true - name: app_id description: Filters check suites by GitHub App `id`. in: query required: false schema: type: integer example: 1 - "$ref": "#/components/parameters/check-name" - "$ref": "#/components/parameters/per-page" - "$ref": "#/components/parameters/page" responses: '200': description: Response content: application/json: schema: type: object required: - total_count - check_suites properties: total_count: type: integer check_suites: type: array items: "$ref": "#/components/schemas/check-suite" examples: default: "$ref": "#/components/examples/check-suite-paginated" headers: Link: "$ref": "#/components/headers/link" x-github: githubCloudOnly: false enabledForGitHubApps: true category: checks subcategory: suites "/repos/{owner}/{repo}/commits/{ref}/status": get: summary: Get the combined status for a specific reference description: |- Users with pull access in a repository can access a combined view of commit statuses for a given ref. The ref can be a SHA, a branch name, or a tag name. Additionally, a combined `state` is returned. The `state` is one of: * **failure** if any of the contexts report as `error` or `failure` * **pending** if there are no statuses or a context is `pending` * **success** if the latest status for all contexts is `success` tags: - repos operationId: repos/get-combined-status-for-ref externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/repos#get-the-combined-status-for-a-specific-reference parameters: - "$ref": "#/components/parameters/owner" - "$ref": "#/components/parameters/repo" - name: ref description: ref parameter in: path required: true schema: type: string x-multi-segment: true - "$ref": "#/components/parameters/per-page" - "$ref": "#/components/parameters/page" responses: '200': description: Response content: application/json: schema: "$ref": "#/components/schemas/combined-commit-status" examples: default: "$ref": "#/components/examples/combined-commit-status" '404': "$ref": "#/components/responses/not_found" x-github: githubCloudOnly: false enabledForGitHubApps: true category: repos subcategory: statuses "/repos/{owner}/{repo}/commits/{ref}/statuses": get: summary: List commit statuses for a reference description: |- Users with pull access in a repository can view commit statuses for a given ref. The ref can be a SHA, a branch name, or a tag name. Statuses are returned in reverse chronological order. The first status in the list will be the latest one. This resource is also available via a legacy route: `GET /repos/:owner/:repo/statuses/:ref`. tags: - repos operationId: repos/list-commit-statuses-for-ref externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/repos#list-commit-statuses-for-a-reference parameters: - "$ref": "#/components/parameters/owner" - "$ref": "#/components/parameters/repo" - name: ref description: ref parameter in: path required: true schema: type: string x-multi-segment: true - "$ref": "#/components/parameters/per-page" - "$ref": "#/components/parameters/page" responses: '200': description: Response content: application/json: schema: type: array items: "$ref": "#/components/schemas/status" examples: default: "$ref": "#/components/examples/status-items" headers: Link: "$ref": "#/components/headers/link" '301': "$ref": "#/components/responses/moved_permanently" x-github: githubCloudOnly: false enabledForGitHubApps: true category: repos subcategory: statuses "/repos/{owner}/{repo}/compare/{basehead}": get: summary: Compare two commits description: |- The `basehead` param is comprised of two parts: `base` and `head`. Both must be branch names in `repo`. To compare branches across other repositories in the same network as `repo`, use the format `:branch`. The response from the API is equivalent to running the `git log base..head` command; however, commits are returned in chronological order. Pass the appropriate [media type](https://docs.github.com/enterprise-server@3.0/rest/overview/media-types/#commits-commit-comparison-and-pull-requests) to fetch diff and patch formats. The response also includes details on the files that were changed between the two commits. This includes the status of the change (for example, if a file was added, removed, modified, or renamed), and details of the change itself. For example, files with a `renamed` status have a `previous_filename` field showing the previous filename of the file, and files with a `modified` status have a `patch` field showing the changes made to the file. **Working with large comparisons** The response will include a comparison of up to 250 commits. If you are working with a larger commit range, you can use the [List commits](https://docs.github.com/enterprise-server@3.0/rest/reference/repos#list-commits) to enumerate all commits in the range. For comparisons with extremely large diffs, you may receive an error response indicating that the diff took too long to generate. You can typically resolve this error by using a smaller commit range. **Signature verification object** The response will include a `verification` object that describes the result of verifying the commit's signature. The following fields are included in the `verification` object: | Name | Type | Description | | ---- | ---- | ----------- | | `verified` | `boolean` | Indicates whether GitHub considers the signature in this commit to be verified. | | `reason` | `string` | The reason for verified value. Possible values and their meanings are enumerated in table below. | | `signature` | `string` | The signature that was extracted from the commit. | | `payload` | `string` | The value that was signed. | These are the possible values for `reason` in the `verification` object: | Value | Description | | ----- | ----------- | | `expired_key` | The key that made the signature is expired. | | `not_signing_key` | The "signing" flag is not among the usage flags in the GPG key that made the signature. | | `gpgverify_error` | There was an error communicating with the signature verification service. | | `gpgverify_unavailable` | The signature verification service is currently unavailable. | | `unsigned` | The object does not include a signature. | | `unknown_signature_type` | A non-PGP signature was found in the commit. | | `no_user` | No user was associated with the `committer` email address in the commit. | | `unverified_email` | The `committer` email address in the commit was associated with a user, but the email address is not verified on her/his account. | | `bad_email` | The `committer` email address in the commit is not included in the identities of the PGP key that made the signature. | | `unknown_key` | The key that made the signature has not been registered with any user's account. | | `malformed_signature` | There was an error parsing the signature. | | `invalid` | The signature could not be cryptographically verified using the key whose key-id was found in the signature. | | `valid` | None of the above errors applied, so the signature is considered to be verified. | tags: - repos operationId: repos/compare-commits externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/repos#compare-two-commits parameters: - "$ref": "#/components/parameters/owner" - "$ref": "#/components/parameters/repo" - name: basehead description: The base branch and head branch to compare. This parameter expects the format `{base}...{head}`. in: path required: true schema: type: string responses: '200': description: Response content: application/json: schema: "$ref": "#/components/schemas/commit-comparison" examples: default: "$ref": "#/components/examples/commit-comparison" '500': "$ref": "#/components/responses/internal_error" '404': "$ref": "#/components/responses/not_found" x-github: githubCloudOnly: false enabledForGitHubApps: true category: repos subcategory: commits "/repos/{owner}/{repo}/content_references/{content_reference_id}/attachments": post: summary: Create a content attachment description: |- Creates an attachment under a content reference URL in the body or comment of an issue or pull request. Use the `id` and `repository` `full_name` of the content reference from the [`content_reference` event](https://docs.github.com/enterprise-server@3.0/webhooks/event-payloads/#content_reference) to create an attachment. The app must create a content attachment within six hours of the content reference URL being posted. See "[Using content attachments](https://docs.github.com/enterprise-server@3.0/apps/using-content-attachments/)" for details about content attachments. You must use an [installation access token](https://docs.github.com/enterprise-server@3.0/apps/building-github-apps/authenticating-with-github-apps/#authenticating-as-an-installation) to access this endpoint. tags: - apps operationId: apps/create-content-attachment externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/apps#create-a-content-attachment parameters: - name: owner description: The owner of the repository. Determined from the `repository` `full_name` of the `content_reference` event. in: path required: true schema: type: string - name: repo description: The name of the repository. Determined from the `repository` `full_name` of the `content_reference` event. in: path required: true schema: type: string - name: content_reference_id description: The `id` of the `content_reference` event. in: path required: true schema: type: integer requestBody: required: true content: application/json: schema: properties: title: description: The title of the attachment type: string maxLength: 1024 examples: - Title of the attachment body: description: The body of the attachment type: string maxLength: 262144 examples: - Body of the attachment required: - title - body type: object responses: '200': description: Response content: application/json: schema: "$ref": "#/components/schemas/content-reference-attachment" examples: default: "$ref": "#/components/examples/content-reference-attachment" '422': "$ref": "#/components/responses/validation_failed" '404': "$ref": "#/components/responses/not_found" '410': "$ref": "#/components/responses/gone" '415': "$ref": "#/components/responses/preview_header_missing" '304': "$ref": "#/components/responses/not_modified" '403': "$ref": "#/components/responses/forbidden" x-github: githubCloudOnly: false enabledForGitHubApps: true previews: - required: true name: corsair note: |- To access the Content Attachments API during the preview period, you must provide a custom [media type](https://docs.github.com/enterprise-server@3.0/rest/overview/media-types) in the `Accept` header: ```shell application/vnd.github.corsair-preview+json ``` category: apps subcategory: installations "/repos/{owner}/{repo}/contents/{path}": get: summary: Get repository content description: "Gets the contents of a file or directory in a repository. Specify the file path or directory in `:path`. If you omit\n`:path`, you will receive the contents of the repository's root directory. See the description below regarding what the API response includes for directories. \n\nFiles and symlinks support [a custom media type](https://docs.github.com/enterprise-server@3.0/rest/reference/repos#custom-media-types) for\nretrieving the raw content or rendered HTML (when supported). All content types support [a custom media\ntype](https://docs.github.com/enterprise-server@3.0/rest/reference/repos#custom-media-types) to ensure the content is returned in a consistent\nobject format.\n\n**Note**:\n* \ To get a repository's contents recursively, you can [recursively get the tree](https://docs.github.com/enterprise-server@3.0/rest/reference/git#trees).\n* \ This API has an upper limit of 1,000 files for a directory. If you need to retrieve more files, use the [Git Trees\nAPI](https://docs.github.com/enterprise-server@3.0/rest/reference/git#get-a-tree).\n* \ This API supports files up to 1 megabyte in size.\n\n#### If the content is a directory\nThe response will be an array of objects, one object for each item in the directory.\nWhen listing the contents of a directory, submodules have their \"type\" specified as \"file\". Logically, the value\n_should_ be \"submodule\". This behavior exists in API v3 [for backwards compatibility purposes](https://git.io/v1YCW).\nIn the next major version of the API, the type will be returned as \"submodule\".\n\n#### If the content is a symlink \nIf the requested `:path` points to a symlink, and the symlink's target is a normal file in the repository, then the\nAPI responds with the content of the file (in the format shown in the example. Otherwise, the API responds with an object \ndescribing the symlink itself.\n\n#### If the content is a submodule\nThe `submodule_git_url` identifies the location of the submodule repository, and the `sha` identifies a specific\ncommit within the submodule repository. Git uses the given URL when cloning the submodule repository, and checks out\nthe submodule at that specific commit.\n\nIf the submodule repository is not hosted on github.com, the Git URLs (`git_url` and `_links[\"git\"]`) and the\ngithub.com URLs (`html_url` and `_links[\"html\"]`) will have null values." tags: - repos operationId: repos/get-content externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/repos#get-repository-content parameters: - "$ref": "#/components/parameters/owner" - "$ref": "#/components/parameters/repo" - name: path description: path parameter in: path required: true schema: type: string x-multi-segment: true - name: ref description: 'The name of the commit/branch/tag. Default: the repository’s default branch (usually `master`)' in: query required: false schema: type: string responses: '200': description: Response content: application/vnd.github.v3.object: schema: "$ref": "#/components/schemas/content-tree" application/json: schema: oneOf: - "$ref": "#/components/schemas/content-directory" - "$ref": "#/components/schemas/content-file" - "$ref": "#/components/schemas/content-symlink" - "$ref": "#/components/schemas/content-submodule" examples: response-if-content-is-a-file: "$ref": "#/components/examples/content-file-response-if-content-is-a-file" response-if-content-is-a-directory: "$ref": "#/components/examples/content-file-response-if-content-is-a-directory" response-if-content-is-a-symlink: "$ref": "#/components/examples/content-file-response-if-content-is-a-symlink" response-if-content-is-a-submodule: "$ref": "#/components/examples/content-file-response-if-content-is-a-submodule" '404': "$ref": "#/components/responses/not_found" '403': "$ref": "#/components/responses/forbidden" '302': "$ref": "#/components/responses/found" x-github: githubCloudOnly: false enabledForGitHubApps: true category: repos subcategory: contents put: summary: Create or update file contents description: Creates a new file or replaces an existing file in a repository. tags: - repos operationId: repos/create-or-update-file-contents externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/repos#create-or-update-file-contents parameters: - "$ref": "#/components/parameters/owner" - "$ref": "#/components/parameters/repo" - name: path description: path parameter in: path required: true schema: type: string x-multi-segment: true requestBody: required: true content: application/json: schema: type: object properties: message: type: string description: The commit message. content: type: string description: The new file content, using Base64 encoding. sha: type: string description: "**Required if you are updating a file**. The blob SHA of the file being replaced." branch: type: string description: 'The branch name. Default: the repository’s default branch (usually `master`)' committer: type: object description: 'The person that committed the file. Default: the authenticated user.' properties: name: type: string description: The name of the author or committer of the commit. You'll receive a `422` status code if `name` is omitted. email: type: string description: The email of the author or committer of the commit. You'll receive a `422` status code if `email` is omitted. date: type: string examples: - '"2013-01-05T13:13:22+05:00"' required: - name - email author: type: object description: 'The author of the file. Default: The `committer` or the authenticated user if you omit `committer`.' properties: name: type: string description: The name of the author or committer of the commit. You'll receive a `422` status code if `name` is omitted. email: type: string description: The email of the author or committer of the commit. You'll receive a `422` status code if `email` is omitted. date: type: string examples: - '"2013-01-15T17:13:22+05:00"' required: - name - email required: - message - content examples: example-for-creating-a-file: summary: Example for creating a file value: message: my commit message committer: name: Monalisa Octocat email: octocat@github.com content: bXkgbmV3IGZpbGUgY29udGVudHM= example-for-updating-a-file: summary: Example for updating a file value: message: a new commit message committer: name: Monalisa Octocat email: octocat@github.com content: bXkgdXBkYXRlZCBmaWxlIGNvbnRlbnRz sha: 95b966ae1c166bd92f8ae7d1c313e738c731dfc3 responses: '200': description: Response content: application/json: schema: "$ref": "#/components/schemas/file-commit" examples: example-for-updating-a-file: "$ref": "#/components/examples/file-commit-example-for-updating-a-file" '201': description: Response content: application/json: schema: "$ref": "#/components/schemas/file-commit" examples: example-for-creating-a-file: "$ref": "#/components/examples/file-commit-example-for-creating-a-file" '404': "$ref": "#/components/responses/not_found" '422': "$ref": "#/components/responses/validation_failed" '409': "$ref": "#/components/responses/conflict" x-github: githubCloudOnly: false enabledForGitHubApps: true category: repos subcategory: contents delete: summary: Delete a file description: |- Deletes a file in a repository. You can provide an additional `committer` parameter, which is an object containing information about the committer. Or, you can provide an `author` parameter, which is an object containing information about the author. The `author` section is optional and is filled in with the `committer` information if omitted. If the `committer` information is omitted, the authenticated user's information is used. You must provide values for both `name` and `email`, whether you choose to use `author` or `committer`. Otherwise, you'll receive a `422` status code. tags: - repos operationId: repos/delete-file externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/repos#delete-a-file parameters: - "$ref": "#/components/parameters/owner" - "$ref": "#/components/parameters/repo" - name: path description: path parameter in: path required: true schema: type: string x-multi-segment: true requestBody: required: true content: application/json: schema: type: object properties: message: type: string description: The commit message. sha: type: string description: The blob SHA of the file being replaced. branch: type: string description: 'The branch name. Default: the repository’s default branch (usually `master`)' committer: type: object description: object containing information about the committer. properties: name: type: string description: The name of the author (or committer) of the commit email: type: string description: The email of the author (or committer) of the commit author: type: object description: object containing information about the author. properties: name: type: string description: The name of the author (or committer) of the commit email: type: string description: The email of the author (or committer) of the commit required: - message - sha example: message: my commit message committer: name: Monalisa Octocat email: octocat@github.com sha: 329688480d39049927147c162b9d2deaf885005f responses: '200': description: Response content: application/json: schema: "$ref": "#/components/schemas/file-commit" examples: default: "$ref": "#/components/examples/file-commit" '422': "$ref": "#/components/responses/validation_failed" '404': "$ref": "#/components/responses/not_found" '409': "$ref": "#/components/responses/conflict" '503': "$ref": "#/components/responses/service_unavailable" x-github: githubCloudOnly: false enabledForGitHubApps: true category: repos subcategory: contents "/repos/{owner}/{repo}/contributors": get: summary: List repository contributors description: |- Lists contributors to the specified repository and sorts them by the number of commits per contributor in descending order. This endpoint may return information that is a few hours old because the GitHub REST API v3 caches contributor data to improve performance. GitHub identifies contributors by author email address. This endpoint groups contribution counts by GitHub user, which includes all associated email addresses. To improve performance, only the first 500 author email addresses in the repository link to GitHub users. The rest will appear as anonymous contributors without associated GitHub user information. tags: - repos operationId: repos/list-contributors externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/repos#list-repository-contributors parameters: - "$ref": "#/components/parameters/owner" - "$ref": "#/components/parameters/repo" - name: anon description: Set to `1` or `true` to include anonymous contributors in results. in: query required: false schema: type: string - "$ref": "#/components/parameters/per-page" - "$ref": "#/components/parameters/page" responses: '200': description: if repository contains content content: application/json: schema: type: array items: "$ref": "#/components/schemas/contributor" examples: response-if-repository-contains-content: "$ref": "#/components/examples/contributor-items-response-if-repository-contains-content" headers: Link: "$ref": "#/components/headers/link" '204': description: Response if repository is empty '403': "$ref": "#/components/responses/forbidden" '404': "$ref": "#/components/responses/not_found" x-github: githubCloudOnly: false enabledForGitHubApps: true category: repos subcategory: "/repos/{owner}/{repo}/deployments": get: summary: List deployments description: 'Simple filtering of deployments is available via query parameters:' tags: - repos operationId: repos/list-deployments externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/repos#list-deployments parameters: - "$ref": "#/components/parameters/owner" - "$ref": "#/components/parameters/repo" - name: sha description: The SHA recorded at creation time. in: query required: false schema: type: string default: none - name: ref description: The name of the ref. This can be a branch, tag, or SHA. in: query required: false schema: type: string default: none - name: task description: The name of the task for the deployment (e.g., `deploy` or `deploy:migrations`). in: query required: false schema: type: string default: none - name: environment description: The name of the environment that was deployed to (e.g., `staging` or `production`). in: query required: false schema: type: - string - 'null' default: none - "$ref": "#/components/parameters/per-page" - "$ref": "#/components/parameters/page" responses: '200': description: Response content: application/json: schema: type: array items: "$ref": "#/components/schemas/deployment" examples: default: "$ref": "#/components/examples/deployment-items" headers: Link: "$ref": "#/components/headers/link" x-github: githubCloudOnly: false enabledForGitHubApps: true category: repos subcategory: deployments previews: - required: false name: ant-man note: |- The `inactive` state and the `log_url`, `environment_url`, and `auto_inactive` parameters are currently available for developers to preview. Please see the [blog post](https://developer.github.com/changes/2016-04-06-deployment-and-deployment-status-enhancements) for full details. To access the API during the preview period, you must provide a custom [media type](https://docs.github.com/enterprise-server@3.0/rest/overview/media-types) in the `Accept` header: ```shell application/vnd.github.ant-man-preview+json ``` post: summary: Create a deployment description: |- Deployments offer a few configurable parameters with certain defaults. The `ref` parameter can be any named branch, tag, or SHA. At GitHub Enterprise Server we often deploy branches and verify them before we merge a pull request. The `environment` parameter allows deployments to be issued to different runtime environments. Teams often have multiple environments for verifying their applications, such as `production`, `staging`, and `qa`. This parameter makes it easier to track which environments have requested deployments. The default environment is `production`. The `auto_merge` parameter is used to ensure that the requested ref is not behind the repository's default branch. If the ref _is_ behind the default branch for the repository, we will attempt to merge it for you. If the merge succeeds, the API will return a successful merge commit. If merge conflicts prevent the merge from succeeding, the API will return a failure response. By default, [commit statuses](https://docs.github.com/enterprise-server@3.0/rest/reference/commits#commit-statuses) for every submitted context must be in a `success` state. The `required_contexts` parameter allows you to specify a subset of contexts that must be `success`, or to specify contexts that have not yet been submitted. You are not required to use commit statuses to deploy. If you do not require any contexts or create any commit statuses, the deployment will always succeed. The `payload` parameter is available for any extra information that a deployment system might need. It is a JSON text field that will be passed on when a deployment event is dispatched. The `task` parameter is used by the deployment system to allow different execution paths. In the web world this might be `deploy:migrations` to run schema changes on the system. In the compiled world this could be a flag to compile an application with debugging enabled. Users with `repo` or `repo_deployment` scopes can create a deployment for a given ref. #### Merged branch response You will see this response when GitHub automatically merges the base branch into the topic branch instead of creating a deployment. This auto-merge happens when: * Auto-merge option is enabled in the repository * Topic branch does not include the latest changes on the base branch, which is `master` in the response example * There are no merge conflicts If there are no new commits in the base branch, a new request to create a deployment should give a successful response. #### Merge conflict response This error happens when the `auto_merge` option is enabled and when the default branch (in this case `master`), can't be merged into the branch that's being deployed (in this case `topic-branch`), due to merge conflicts. #### Failed commit status checks This error happens when the `required_contexts` parameter indicates that one or more contexts need to have a `success` status for the commit to be deployed, but one or more of the required contexts do not have a state of `success`. tags: - repos operationId: repos/create-deployment externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/repos#create-a-deployment parameters: - "$ref": "#/components/parameters/owner" - "$ref": "#/components/parameters/repo" requestBody: required: true content: application/json: schema: type: object properties: ref: type: string description: The ref to deploy. This can be a branch, tag, or SHA. task: type: string description: Specifies a task to execute (e.g., `deploy` or `deploy:migrations`). default: deploy auto_merge: type: boolean description: Attempts to automatically merge the default branch into the requested ref, if it's behind the default branch. default: true required_contexts: type: array description: The [status](https://docs.github.com/enterprise-server@3.0/rest/reference/commits#commit-statuses) contexts to verify against commit status checks. If you omit this parameter, GitHub verifies all unique contexts before creating a deployment. To bypass checking entirely, pass an empty array. Defaults to all unique contexts. items: type: string payload: oneOf: - type: object additionalProperties: true - type: string description: JSON payload with extra information about the deployment. default: '' environment: type: string description: Name for the target deployment environment (e.g., `production`, `staging`, `qa`). default: production description: type: - string - 'null' description: Short description of the deployment. default: '' transient_environment: type: boolean description: "Specifies if the given environment is specific to the deployment and will no longer exist at some point in the future. Default: `false` \n**Note:** This parameter requires you to use the [`application/vnd.github.ant-man-preview+json`](https://docs.github.com/enterprise-server@3.0/rest/overview/api-previews#enhanced-deployments) custom media type." default: false production_environment: type: boolean description: "Specifies if the given environment is one that end-users directly interact with. Default: `true` when `environment` is `production` and `false` otherwise. \n**Note:** This parameter requires you to use the [`application/vnd.github.ant-man-preview+json`](https://docs.github.com/enterprise-server@3.0/rest/overview/api-previews#enhanced-deployments) custom media type." required: - ref examples: simple-example: summary: Simple example value: ref: topic-branch payload: '{ "deploy": "migrate" }' description: Deploy request from hubot advanced-example: summary: Advanced example value: ref: topic-branch auto_merge: false payload: '{ "deploy": "migrate" }' description: Deploy request from hubot required_contexts: - ci/janky - security/brakeman responses: '201': description: Response content: application/json: schema: "$ref": "#/components/schemas/deployment" examples: simple-example: "$ref": "#/components/examples/deployment-simple-example" '202': description: Merged branch response content: application/json: schema: type: object properties: message: type: string examples: merged-branch-response: value: message: Auto-merged master into topic-branch on deployment. '409': description: Conflict when there is a merge conflict or the commit's status checks failed '422': "$ref": "#/components/responses/validation_failed" x-github: githubCloudOnly: false enabledForGitHubApps: true category: repos subcategory: deployments previews: - required: false name: ant-man note: |- The `inactive` state and the `log_url`, `environment_url`, and `auto_inactive` parameters are currently available for developers to preview. Please see the [blog post](https://developer.github.com/changes/2016-04-06-deployment-and-deployment-status-enhancements) for full details. To access the API during the preview period, you must provide a custom [media type](https://docs.github.com/enterprise-server@3.0/rest/overview/media-types) in the `Accept` header: ```shell application/vnd.github.ant-man-preview+json ``` "/repos/{owner}/{repo}/deployments/{deployment_id}": get: summary: Get a deployment description: '' tags: - repos operationId: repos/get-deployment externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/repos#get-a-deployment parameters: - "$ref": "#/components/parameters/owner" - "$ref": "#/components/parameters/repo" - "$ref": "#/components/parameters/deployment-id" responses: '200': description: Response content: application/json: schema: "$ref": "#/components/schemas/deployment" examples: default: "$ref": "#/components/examples/deployment" '404': "$ref": "#/components/responses/not_found" x-github: githubCloudOnly: false enabledForGitHubApps: true category: repos subcategory: deployments previews: - required: false name: flash note: |- New features in the Deployments API on GitHub are currently available during a public beta. Please see the [blog post](https://developer.github.com/changes/2018-10-16-deployments-environments-states-and-auto-inactive-updates/) for full details. To access the new `environment` parameter, the two new values for the `state` parameter (`in_progress` and `queued`), and use `auto_inactive` on production deployments during the public beta period, you must provide the following custom [media type](https://docs.github.com/enterprise-server@3.0/rest/overview/media-types) in the `Accept` header: ```shell application/vnd.github.flash-preview+json ``` - required: false name: ant-man note: |- The `inactive` state and the `log_url`, `environment_url`, and `auto_inactive` parameters are currently available for developers to preview. Please see the [blog post](https://developer.github.com/changes/2016-04-06-deployment-and-deployment-status-enhancements) for full details. To access the API during the preview period, you must provide a custom [media type](https://docs.github.com/enterprise-server@3.0/rest/overview/media-types) in the `Accept` header: ```shell application/vnd.github.ant-man-preview+json ``` delete: summary: Delete a deployment description: |- If the repository only has one deployment, you can delete the deployment regardless of its status. If the repository has more than one deployment, you can only delete inactive deployments. This ensures that repositories with multiple deployments will always have an active deployment. Anyone with `repo` or `repo_deployment` scopes can delete a deployment. To set a deployment as inactive, you must: * Create a new deployment that is active so that the system has a record of the current state, then delete the previously active deployment. * Mark the active deployment as inactive by adding any non-successful deployment status. For more information, see "[Create a deployment](https://docs.github.com/enterprise-server@3.0/rest/reference/repos/#create-a-deployment)" and "[Create a deployment status](https://docs.github.com/enterprise-server@3.0/rest/reference/repos#create-a-deployment-status)." tags: - repos operationId: repos/delete-deployment externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/repos#delete-a-deployment parameters: - "$ref": "#/components/parameters/owner" - "$ref": "#/components/parameters/repo" - "$ref": "#/components/parameters/deployment-id" responses: '204': description: Response '404': "$ref": "#/components/responses/not_found" '422': "$ref": "#/components/responses/validation_failed_simple" x-github: githubCloudOnly: false enabledForGitHubApps: true category: repos subcategory: deployments "/repos/{owner}/{repo}/deployments/{deployment_id}/statuses": get: summary: List deployment statuses description: 'Users with pull access can view deployment statuses for a deployment:' tags: - repos operationId: repos/list-deployment-statuses externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/repos#list-deployment-statuses parameters: - "$ref": "#/components/parameters/owner" - "$ref": "#/components/parameters/repo" - "$ref": "#/components/parameters/deployment-id" - "$ref": "#/components/parameters/per-page" - "$ref": "#/components/parameters/page" responses: '200': description: Response content: application/json: schema: type: array items: "$ref": "#/components/schemas/deployment-status" examples: default: "$ref": "#/components/examples/deployment-status-items" headers: Link: "$ref": "#/components/headers/link" '404': "$ref": "#/components/responses/not_found" x-github: githubCloudOnly: false enabledForGitHubApps: true category: repos subcategory: deployments previews: - required: false name: flash note: |- New features in the Deployments API on GitHub are currently available during a public beta. Please see the [blog post](https://developer.github.com/changes/2018-10-16-deployments-environments-states-and-auto-inactive-updates/) for full details. To access the new `environment` parameter, the two new values for the `state` parameter (`in_progress` and `queued`), and use `auto_inactive` on production deployments during the public beta period, you must provide the following custom [media type](https://docs.github.com/enterprise-server@3.0/rest/overview/media-types) in the `Accept` header: ```shell application/vnd.github.flash-preview+json ``` - required: false name: ant-man note: |- The `inactive` state and the `log_url`, `environment_url`, and `auto_inactive` parameters are currently available for developers to preview. Please see the [blog post](https://developer.github.com/changes/2016-04-06-deployment-and-deployment-status-enhancements) for full details. To access the API during the preview period, you must provide a custom [media type](https://docs.github.com/enterprise-server@3.0/rest/overview/media-types) in the `Accept` header: ```shell application/vnd.github.ant-man-preview+json ``` post: summary: Create a deployment status description: |- Users with `push` access can create deployment statuses for a given deployment. GitHub Apps require `read & write` access to "Deployments" and `read-only` access to "Repo contents" (for private repos). OAuth Apps require the `repo_deployment` scope. tags: - repos operationId: repos/create-deployment-status externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/repos#create-a-deployment-status parameters: - "$ref": "#/components/parameters/owner" - "$ref": "#/components/parameters/repo" - "$ref": "#/components/parameters/deployment-id" requestBody: required: true content: application/json: schema: type: object properties: state: type: string description: The state of the status. Can be one of `error`, `failure`, `inactive`, `in_progress`, `queued`, `pending`, or `success`. **Note:** To use the `inactive` state, you must provide the [`application/vnd.github.ant-man-preview+json`](https://docs.github.com/enterprise-server@3.0/rest/overview/api-previews#enhanced-deployments) custom media type. When you set a transient deployment to `inactive`, the deployment will be shown as `destroyed` in GitHub. enum: - error - failure - inactive - in_progress - queued - pending - success target_url: type: string description: The target URL to associate with this status. This URL should contain output to keep the user updated while the task is running or serve as historical information for what happened in the deployment. **Note:** It's recommended to use the `log_url` parameter, which replaces `target_url`. default: '' log_url: type: string description: "The full URL of the deployment's output. This parameter replaces `target_url`. We will continue to accept `target_url` to support legacy uses, but we recommend replacing `target_url` with `log_url`. Setting `log_url` will automatically set `target_url` to the same value. Default: `\"\"` \n**Note:** This parameter requires you to use the [`application/vnd.github.ant-man-preview+json`](https://docs.github.com/enterprise-server@3.0/rest/overview/api-previews#enhanced-deployments) custom media type." default: '' description: type: string description: A short description of the status. The maximum description length is 140 characters. default: '' environment: type: string description: Name for the target deployment environment, which can be changed when setting a deploy status. For example, `production`, `staging`, or `qa`. enum: - production - staging - qa environment_url: type: string description: "Sets the URL for accessing your environment. Default: `\"\"` \n**Note:** This parameter requires you to use the [`application/vnd.github.ant-man-preview+json`](https://docs.github.com/enterprise-server@3.0/rest/overview/api-previews#enhanced-deployments) custom media type." default: '' auto_inactive: type: boolean description: "Adds a new `inactive` status to all prior non-transient, non-production environment deployments with the same repository and `environment` name as the created status's deployment. An `inactive` status is only added to deployments that had a `success` state. Default: `true` \n**Note:** This parameter requires you to use the [`application/vnd.github.ant-man-preview+json`](https://docs.github.com/enterprise-server@3.0/rest/overview/api-previews#enhanced-deployments) custom media type." required: - state example: environment: production state: success log_url: https://example.com/deployment/42/output description: Deployment finished successfully. responses: '201': description: Response content: application/json: schema: "$ref": "#/components/schemas/deployment-status" examples: default: "$ref": "#/components/examples/deployment-status" headers: Location: example: https://api.github.com/repos/octocat/example/deployments/42/statuses/1 schema: type: string '422': "$ref": "#/components/responses/validation_failed" x-github: githubCloudOnly: false enabledForGitHubApps: true category: repos subcategory: deployments previews: - required: false name: flash note: |- New features in the Deployments API on GitHub are currently available during a public beta. Please see the [blog post](https://developer.github.com/changes/2018-10-16-deployments-environments-states-and-auto-inactive-updates/) for full details. To access the new `environment` parameter, the two new values for the `state` parameter (`in_progress` and `queued`), and use `auto_inactive` on production deployments during the public beta period, you must provide the following custom [media type](https://docs.github.com/enterprise-server@3.0/rest/overview/media-types) in the `Accept` header: ```shell application/vnd.github.flash-preview+json ``` - required: false name: ant-man note: |- The `inactive` state and the `log_url`, `environment_url`, and `auto_inactive` parameters are currently available for developers to preview. Please see the [blog post](https://developer.github.com/changes/2016-04-06-deployment-and-deployment-status-enhancements) for full details. To access the API during the preview period, you must provide a custom [media type](https://docs.github.com/enterprise-server@3.0/rest/overview/media-types) in the `Accept` header: ```shell application/vnd.github.ant-man-preview+json ``` "/repos/{owner}/{repo}/deployments/{deployment_id}/statuses/{status_id}": get: summary: Get a deployment status description: 'Users with pull access can view a deployment status for a deployment:' tags: - repos operationId: repos/get-deployment-status externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/repos#get-a-deployment-status parameters: - "$ref": "#/components/parameters/owner" - "$ref": "#/components/parameters/repo" - "$ref": "#/components/parameters/deployment-id" - name: status_id in: path required: true schema: type: integer responses: '200': description: Response content: application/json: schema: "$ref": "#/components/schemas/deployment-status" examples: default: "$ref": "#/components/examples/deployment-status" '404': "$ref": "#/components/responses/not_found" x-github: githubCloudOnly: false enabledForGitHubApps: true category: repos subcategory: deployments previews: - required: false name: flash note: |- New features in the Deployments API on GitHub are currently available during a public beta. Please see the [blog post](https://developer.github.com/changes/2018-10-16-deployments-environments-states-and-auto-inactive-updates/) for full details. To access the new `environment` parameter, the two new values for the `state` parameter (`in_progress` and `queued`), and use `auto_inactive` on production deployments during the public beta period, you must provide the following custom [media type](https://docs.github.com/enterprise-server@3.0/rest/overview/media-types) in the `Accept` header: ```shell application/vnd.github.flash-preview+json ``` - required: false name: ant-man note: |- The `inactive` state and the `log_url`, `environment_url`, and `auto_inactive` parameters are currently available for developers to preview. Please see the [blog post](https://developer.github.com/changes/2016-04-06-deployment-and-deployment-status-enhancements) for full details. To access the API during the preview period, you must provide a custom [media type](https://docs.github.com/enterprise-server@3.0/rest/overview/media-types) in the `Accept` header: ```shell application/vnd.github.ant-man-preview+json ``` "/repos/{owner}/{repo}/dispatches": post: summary: Create a repository dispatch event description: |- You can use this endpoint to trigger a webhook event called `repository_dispatch` when you want activity that happens outside of GitHub Enterprise Server to trigger a GitHub Actions workflow or GitHub App webhook. You must configure your GitHub Actions workflow or GitHub App to run when the `repository_dispatch` event occurs. For an example `repository_dispatch` webhook payload, see "[RepositoryDispatchEvent](https://docs.github.com/enterprise-server@3.0/webhooks/event-payloads/#repository_dispatch)." The `client_payload` parameter is available for any extra information that your workflow might need. This parameter is a JSON payload that will be passed on when the webhook event is dispatched. For example, the `client_payload` can include a message that a user would like to send using a GitHub Actions workflow. Or the `client_payload` can be used as a test to debug your workflow. This endpoint requires write access to the repository by providing either: - Personal access tokens with `repo` scope. For more information, see "[Creating a personal access token for the command line](https://docs.github.com/articles/creating-a-personal-access-token-for-the-command-line)" in the GitHub Help documentation. - GitHub Apps with both `metadata:read` and `contents:read&write` permissions. This input example shows how you can use the `client_payload` as a test to debug your workflow. tags: - repos operationId: repos/create-dispatch-event externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/repos#create-a-repository-dispatch-event parameters: - "$ref": "#/components/parameters/owner" - "$ref": "#/components/parameters/repo" requestBody: required: true content: application/json: schema: type: object required: - event_type properties: event_type: type: string description: A custom webhook event name. minLength: 1 maxLength: 100 client_payload: type: object description: JSON payload with extra information about the webhook event that your action or worklow may use. additionalProperties: true maxProperties: 10 example: event_type: on-demand-test client_payload: unit: false integration: true responses: '204': description: Response '422': "$ref": "#/components/responses/validation_failed" x-github: githubCloudOnly: false enabledForGitHubApps: true category: repos subcategory: "/repos/{owner}/{repo}/events": get: summary: List repository events description: '' tags: - activity operationId: activity/list-repo-events externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/activity#list-repository-events parameters: - "$ref": "#/components/parameters/owner" - "$ref": "#/components/parameters/repo" - "$ref": "#/components/parameters/per-page" - "$ref": "#/components/parameters/page" responses: '200': description: Response content: application/json: schema: type: array items: "$ref": "#/components/schemas/event" x-github: githubCloudOnly: false enabledForGitHubApps: true category: activity subcategory: events "/repos/{owner}/{repo}/forks": get: summary: List forks description: '' tags: - repos operationId: repos/list-forks externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/repos#list-forks parameters: - "$ref": "#/components/parameters/owner" - "$ref": "#/components/parameters/repo" - name: sort description: The sort order. Can be either `newest`, `oldest`, or `stargazers`. in: query required: false schema: type: string enum: - newest - oldest - stargazers - watchers default: newest - "$ref": "#/components/parameters/per-page" - "$ref": "#/components/parameters/page" responses: '200': description: Response content: application/json: schema: type: array items: "$ref": "#/components/schemas/minimal-repository" examples: default: "$ref": "#/components/examples/minimal-repository-items-2" headers: Link: "$ref": "#/components/headers/link" '400': "$ref": "#/components/responses/bad_request" x-github: githubCloudOnly: false enabledForGitHubApps: true category: repos subcategory: forks post: summary: Create a fork description: |- Create a fork for the authenticated user. **Note**: Forking a Repository happens asynchronously. You may have to wait a short period of time before you can access the git objects. If this takes longer than 5 minutes, be sure to contact [GitHub Enterprise Server Support](https://support.github.com/contact?tags=dotcom-rest-api). tags: - repos operationId: repos/create-fork externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/repos#create-a-fork parameters: - "$ref": "#/components/parameters/owner" - "$ref": "#/components/parameters/repo" requestBody: required: false content: application/json: schema: type: - object - 'null' properties: organization: type: string description: Optional parameter to specify the organization name if forking into an organization. responses: '202': description: Response content: application/json: schema: "$ref": "#/components/schemas/full-repository" examples: default: "$ref": "#/components/examples/full-repository" '400': "$ref": "#/components/responses/bad_request" '422': "$ref": "#/components/responses/validation_failed" '403': "$ref": "#/components/responses/forbidden" '404': "$ref": "#/components/responses/not_found" x-github: githubCloudOnly: false enabledForGitHubApps: true category: repos subcategory: forks "/repos/{owner}/{repo}/git/blobs": post: summary: Create a blob description: '' tags: - git operationId: git/create-blob externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/git#create-a-blob parameters: - "$ref": "#/components/parameters/owner" - "$ref": "#/components/parameters/repo" requestBody: required: true content: application/json: schema: type: object properties: content: type: string description: The new blob's content. encoding: type: string description: The encoding used for `content`. Currently, `"utf-8"` and `"base64"` are supported. default: utf-8 required: - content example: content: Content of the blob encoding: utf-8 responses: '201': description: Response content: application/json: schema: "$ref": "#/components/schemas/short-blob" examples: default: "$ref": "#/components/examples/short-blob" headers: Location: example: https://api.github.com/repos/octocat/example/git/blobs/3a0f86fb8db8eea7ccbb9a95f325ddbedfb25e15 schema: type: string '404': "$ref": "#/components/responses/not_found" '409': "$ref": "#/components/responses/conflict" '403': "$ref": "#/components/responses/forbidden" '422': "$ref": "#/components/responses/validation_failed" x-github: githubCloudOnly: false enabledForGitHubApps: true category: git subcategory: blobs "/repos/{owner}/{repo}/git/blobs/{file_sha}": get: summary: Get a blob description: |- The `content` in the response will always be Base64 encoded. _Note_: This API supports blobs up to 100 megabytes in size. tags: - git operationId: git/get-blob externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/git#get-a-blob parameters: - "$ref": "#/components/parameters/owner" - "$ref": "#/components/parameters/repo" - name: file_sha in: path required: true schema: type: string responses: '200': description: Response content: application/json: schema: "$ref": "#/components/schemas/blob" examples: default: "$ref": "#/components/examples/blob" '404': "$ref": "#/components/responses/not_found" '422': "$ref": "#/components/responses/validation_failed" '403': "$ref": "#/components/responses/forbidden" x-github: githubCloudOnly: false enabledForGitHubApps: true category: git subcategory: blobs "/repos/{owner}/{repo}/git/commits": post: summary: Create a commit description: |- Creates a new Git [commit object](https://git-scm.com/book/en/v1/Git-Internals-Git-Objects#Commit-Objects). **Signature verification object** The response will include a `verification` object that describes the result of verifying the commit's signature. The following fields are included in the `verification` object: | Name | Type | Description | | ---- | ---- | ----------- | | `verified` | `boolean` | Indicates whether GitHub considers the signature in this commit to be verified. | | `reason` | `string` | The reason for verified value. Possible values and their meanings are enumerated in table below. | | `signature` | `string` | The signature that was extracted from the commit. | | `payload` | `string` | The value that was signed. | These are the possible values for `reason` in the `verification` object: | Value | Description | | ----- | ----------- | | `expired_key` | The key that made the signature is expired. | | `not_signing_key` | The "signing" flag is not among the usage flags in the GPG key that made the signature. | | `gpgverify_error` | There was an error communicating with the signature verification service. | | `gpgverify_unavailable` | The signature verification service is currently unavailable. | | `unsigned` | The object does not include a signature. | | `unknown_signature_type` | A non-PGP signature was found in the commit. | | `no_user` | No user was associated with the `committer` email address in the commit. | | `unverified_email` | The `committer` email address in the commit was associated with a user, but the email address is not verified on her/his account. | | `bad_email` | The `committer` email address in the commit is not included in the identities of the PGP key that made the signature. | | `unknown_key` | The key that made the signature has not been registered with any user's account. | | `malformed_signature` | There was an error parsing the signature. | | `invalid` | The signature could not be cryptographically verified using the key whose key-id was found in the signature. | | `valid` | None of the above errors applied, so the signature is considered to be verified. | tags: - git operationId: git/create-commit externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/git#create-a-commit parameters: - "$ref": "#/components/parameters/owner" - "$ref": "#/components/parameters/repo" requestBody: required: true content: application/json: schema: type: object properties: message: type: string description: The commit message tree: type: string description: The SHA of the tree object this commit points to parents: type: array description: The SHAs of the commits that were the parents of this commit. If omitted or empty, the commit will be written as a root commit. For a single parent, an array of one SHA should be provided; for a merge commit, an array of more than one should be provided. items: type: string author: type: object description: Information about the author of the commit. By default, the `author` will be the authenticated user and the current date. See the `author` and `committer` object below for details. properties: name: type: string description: The name of the author (or committer) of the commit email: type: string description: The email of the author (or committer) of the commit date: type: string format: date-time description: 'Indicates when this commit was authored (or committed). This is a timestamp in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format: `YYYY-MM-DDTHH:MM:SSZ`.' required: - name - email committer: type: object description: Information about the person who is making the commit. By default, `committer` will use the information set in `author`. See the `author` and `committer` object below for details. properties: name: type: string description: The name of the author (or committer) of the commit email: type: string description: The email of the author (or committer) of the commit date: type: string format: date-time description: 'Indicates when this commit was authored (or committed). This is a timestamp in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format: `YYYY-MM-DDTHH:MM:SSZ`.' signature: type: string description: The [PGP signature](https://en.wikipedia.org/wiki/Pretty_Good_Privacy) of the commit. GitHub adds the signature to the `gpgsig` header of the created commit. For a commit signature to be verifiable by Git or GitHub, it must be an ASCII-armored detached PGP signature over the string commit as it would be written to the object database. To pass a `signature` parameter, you need to first manually create a valid PGP signature, which can be complicated. You may find it easier to [use the command line](https://git-scm.com/book/id/v2/Git-Tools-Signing-Your-Work) to create signed commits. required: - message - tree example: message: my commit message author: name: Mona Octocat email: octocat@github.com date: '2008-07-09T16:13:30+12:00' parents: - 7d1b31e74ee336d15cbd21741bc88a537ed063a0 tree: 827efc6d56897b048c772eb4087f854f46256132 signature: | -----BEGIN PGP SIGNATURE----- iQIzBAABAQAdFiEESn/54jMNIrGSE6Tp6cQjvhfv7nAFAlnT71cACgkQ6cQjvhfv 7nCWwA//XVqBKWO0zF+bZl6pggvky3Oc2j1pNFuRWZ29LXpNuD5WUGXGG209B0hI DkmcGk19ZKUTnEUJV2Xd0R7AW01S/YSub7OYcgBkI7qUE13FVHN5ln1KvH2all2n 2+JCV1HcJLEoTjqIFZSSu/sMdhkLQ9/NsmMAzpf/iIM0nQOyU4YRex9eD1bYj6nA OQPIDdAuaTQj1gFPHYLzM4zJnCqGdRlg0sOM/zC5apBNzIwlgREatOYQSCfCKV7k nrU34X8b9BzQaUx48Qa+Dmfn5KQ8dl27RNeWAqlkuWyv3pUauH9UeYW+KyuJeMkU +NyHgAsWFaCFl23kCHThbLStMZOYEnGagrd0hnm1TPS4GJkV4wfYMwnI4KuSlHKB jHl3Js9vNzEUQipQJbgCgTiWvRJoK3ENwBTMVkKHaqT4x9U4Jk/XZB6Q8MA09ezJ 3QgiTjTAGcum9E9QiJqMYdWQPWkaBIRRz5cET6HPB48YNXAAUsfmuYsGrnVLYbG+ UpC6I97VybYHTy2O9XSGoaLeMI9CsFn38ycAxxbWagk5mhclNTP5mezIq6wKSwmr X11FW3n1J23fWZn5HJMBsRnUCgzqzX3871IqLYHqRJ/bpZ4h20RhTyPj5c/z7QXp eSakNQMfbbMcljkha+ZMuVQX1K9aRlVqbmv3ZMWh+OijLYVU2bc= =5Io4 -----END PGP SIGNATURE----- responses: '201': description: Response content: application/json: schema: "$ref": "#/components/schemas/git-commit" examples: default: "$ref": "#/components/examples/git-commit" headers: Location: example: https://api.github.com/repos/octocat/Hello-World/git/commits/7638417db6d59f3c431d3e1f261cc637155684cd schema: type: string '422': "$ref": "#/components/responses/validation_failed" '404': "$ref": "#/components/responses/not_found" x-github: githubCloudOnly: false enabledForGitHubApps: true category: git subcategory: commits "/repos/{owner}/{repo}/git/commits/{commit_sha}": get: summary: Get a commit description: |- Gets a Git [commit object](https://git-scm.com/book/en/v1/Git-Internals-Git-Objects#Commit-Objects). **Signature verification object** The response will include a `verification` object that describes the result of verifying the commit's signature. The following fields are included in the `verification` object: | Name | Type | Description | | ---- | ---- | ----------- | | `verified` | `boolean` | Indicates whether GitHub considers the signature in this commit to be verified. | | `reason` | `string` | The reason for verified value. Possible values and their meanings are enumerated in table below. | | `signature` | `string` | The signature that was extracted from the commit. | | `payload` | `string` | The value that was signed. | These are the possible values for `reason` in the `verification` object: | Value | Description | | ----- | ----------- | | `expired_key` | The key that made the signature is expired. | | `not_signing_key` | The "signing" flag is not among the usage flags in the GPG key that made the signature. | | `gpgverify_error` | There was an error communicating with the signature verification service. | | `gpgverify_unavailable` | The signature verification service is currently unavailable. | | `unsigned` | The object does not include a signature. | | `unknown_signature_type` | A non-PGP signature was found in the commit. | | `no_user` | No user was associated with the `committer` email address in the commit. | | `unverified_email` | The `committer` email address in the commit was associated with a user, but the email address is not verified on her/his account. | | `bad_email` | The `committer` email address in the commit is not included in the identities of the PGP key that made the signature. | | `unknown_key` | The key that made the signature has not been registered with any user's account. | | `malformed_signature` | There was an error parsing the signature. | | `invalid` | The signature could not be cryptographically verified using the key whose key-id was found in the signature. | | `valid` | None of the above errors applied, so the signature is considered to be verified. | tags: - git operationId: git/get-commit externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/git#get-a-commit parameters: - "$ref": "#/components/parameters/owner" - "$ref": "#/components/parameters/repo" - "$ref": "#/components/parameters/commit-sha" responses: '200': description: Response content: application/json: schema: "$ref": "#/components/schemas/git-commit" examples: default: "$ref": "#/components/examples/git-commit-2" '404': "$ref": "#/components/responses/not_found" x-github: githubCloudOnly: false enabledForGitHubApps: true category: git subcategory: commits "/repos/{owner}/{repo}/git/matching-refs/{ref}": get: summary: List matching references description: |- Returns an array of references from your Git database that match the supplied name. The `:ref` in the URL must be formatted as `heads/` for branches and `tags/` for tags. If the `:ref` doesn't exist in the repository, but existing refs start with `:ref`, they will be returned as an array. When you use this endpoint without providing a `:ref`, it will return an array of all the references from your Git database, including notes and stashes if they exist on the server. Anything in the namespace is returned, not just `heads` and `tags`. **Note:** You need to explicitly [request a pull request](https://docs.github.com/enterprise-server@3.0/rest/reference/pulls#get-a-pull-request) to trigger a test merge commit, which checks the mergeability of pull requests. For more information, see "[Checking mergeability of pull requests](https://docs.github.com/enterprise-server@3.0/rest/guides/getting-started-with-the-git-database-api#checking-mergeability-of-pull-requests)". If you request matching references for a branch named `feature` but the branch `feature` doesn't exist, the response can still include other matching head refs that start with the word `feature`, such as `featureA` and `featureB`. tags: - git operationId: git/list-matching-refs externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/git#list-matching-references parameters: - "$ref": "#/components/parameters/owner" - "$ref": "#/components/parameters/repo" - name: ref description: ref parameter in: path required: true schema: type: string x-multi-segment: true - "$ref": "#/components/parameters/per-page" - "$ref": "#/components/parameters/page" responses: '200': description: Response content: application/json: schema: type: array items: "$ref": "#/components/schemas/git-ref" examples: default: "$ref": "#/components/examples/git-ref-items" headers: Link: "$ref": "#/components/headers/link" x-github: githubCloudOnly: false enabledForGitHubApps: true category: git subcategory: refs "/repos/{owner}/{repo}/git/ref/{ref}": get: summary: Get a reference description: |- Returns a single reference from your Git database. The `:ref` in the URL must be formatted as `heads/` for branches and `tags/` for tags. If the `:ref` doesn't match an existing ref, a `404` is returned. **Note:** You need to explicitly [request a pull request](https://docs.github.com/enterprise-server@3.0/rest/reference/pulls#get-a-pull-request) to trigger a test merge commit, which checks the mergeability of pull requests. For more information, see "[Checking mergeability of pull requests](https://docs.github.com/enterprise-server@3.0/rest/guides/getting-started-with-the-git-database-api#checking-mergeability-of-pull-requests)". tags: - git operationId: git/get-ref externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/git#get-a-reference parameters: - "$ref": "#/components/parameters/owner" - "$ref": "#/components/parameters/repo" - name: ref description: ref parameter in: path required: true schema: type: string x-multi-segment: true responses: '200': description: Response content: application/json: schema: "$ref": "#/components/schemas/git-ref" examples: default: "$ref": "#/components/examples/git-ref" '404': "$ref": "#/components/responses/not_found" x-github: githubCloudOnly: false enabledForGitHubApps: true category: git subcategory: refs "/repos/{owner}/{repo}/git/refs": post: summary: Create a reference description: Creates a reference for your repository. You are unable to create new references for empty repositories, even if the commit SHA-1 hash used exists. Empty repositories are repositories without branches. tags: - git operationId: git/create-ref externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/git#create-a-reference parameters: - "$ref": "#/components/parameters/owner" - "$ref": "#/components/parameters/repo" requestBody: required: true content: application/json: schema: type: object properties: ref: type: string description: 'The name of the fully qualified reference (ie: `refs/heads/master`). If it doesn''t start with ''refs'' and have at least two slashes, it will be rejected.' sha: type: string description: The SHA1 value for this reference. key: type: string examples: - '"refs/heads/newbranch"' required: - ref - sha example: ref: refs/heads/featureA sha: aa218f56b14c9653891f9e74264a383fa43fefbd responses: '201': description: Response content: application/json: schema: "$ref": "#/components/schemas/git-ref" examples: default: "$ref": "#/components/examples/git-ref" headers: Location: example: https://api.github.com/repos/octocat/Hello-World/git/refs/heads/featureA schema: type: string '422': "$ref": "#/components/responses/validation_failed" x-github: githubCloudOnly: false enabledForGitHubApps: true category: git subcategory: refs "/repos/{owner}/{repo}/git/refs/{ref}": patch: summary: Update a reference description: '' tags: - git operationId: git/update-ref externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/git#update-a-reference parameters: - "$ref": "#/components/parameters/owner" - "$ref": "#/components/parameters/repo" - name: ref description: ref parameter in: path required: true schema: type: string x-multi-segment: true requestBody: required: true content: application/json: schema: type: object properties: sha: type: string description: The SHA1 value to set this reference to force: type: boolean description: Indicates whether to force the update or to make sure the update is a fast-forward update. Leaving this out or setting it to `false` will make sure you're not overwriting work. default: false required: - sha example: sha: aa218f56b14c9653891f9e74264a383fa43fefbd force: true responses: '200': description: Response content: application/json: schema: "$ref": "#/components/schemas/git-ref" examples: default: "$ref": "#/components/examples/git-ref" '422': "$ref": "#/components/responses/validation_failed" x-github: githubCloudOnly: false enabledForGitHubApps: true category: git subcategory: refs delete: summary: Delete a reference description: '' tags: - git operationId: git/delete-ref externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/git#delete-a-reference parameters: - "$ref": "#/components/parameters/owner" - "$ref": "#/components/parameters/repo" - name: ref description: ref parameter in: path required: true schema: type: string x-multi-segment: true responses: '204': description: Response '422': "$ref": "#/components/responses/validation_failed" x-github: githubCloudOnly: false enabledForGitHubApps: true category: git subcategory: refs "/repos/{owner}/{repo}/git/tags": post: summary: Create a tag object description: |- Note that creating a tag object does not create the reference that makes a tag in Git. If you want to create an annotated tag in Git, you have to do this call to create the tag object, and then [create](https://docs.github.com/enterprise-server@3.0/rest/reference/git#create-a-reference) the `refs/tags/[tag]` reference. If you want to create a lightweight tag, you only have to [create](https://docs.github.com/enterprise-server@3.0/rest/reference/git#create-a-reference) the tag reference - this call would be unnecessary. **Signature verification object** The response will include a `verification` object that describes the result of verifying the commit's signature. The following fields are included in the `verification` object: | Name | Type | Description | | ---- | ---- | ----------- | | `verified` | `boolean` | Indicates whether GitHub considers the signature in this commit to be verified. | | `reason` | `string` | The reason for verified value. Possible values and their meanings are enumerated in table below. | | `signature` | `string` | The signature that was extracted from the commit. | | `payload` | `string` | The value that was signed. | These are the possible values for `reason` in the `verification` object: | Value | Description | | ----- | ----------- | | `expired_key` | The key that made the signature is expired. | | `not_signing_key` | The "signing" flag is not among the usage flags in the GPG key that made the signature. | | `gpgverify_error` | There was an error communicating with the signature verification service. | | `gpgverify_unavailable` | The signature verification service is currently unavailable. | | `unsigned` | The object does not include a signature. | | `unknown_signature_type` | A non-PGP signature was found in the commit. | | `no_user` | No user was associated with the `committer` email address in the commit. | | `unverified_email` | The `committer` email address in the commit was associated with a user, but the email address is not verified on her/his account. | | `bad_email` | The `committer` email address in the commit is not included in the identities of the PGP key that made the signature. | | `unknown_key` | The key that made the signature has not been registered with any user's account. | | `malformed_signature` | There was an error parsing the signature. | | `invalid` | The signature could not be cryptographically verified using the key whose key-id was found in the signature. | | `valid` | None of the above errors applied, so the signature is considered to be verified. | tags: - git operationId: git/create-tag externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/git#create-a-tag-object parameters: - "$ref": "#/components/parameters/owner" - "$ref": "#/components/parameters/repo" requestBody: required: true content: application/json: schema: type: object properties: tag: type: string description: The tag's name. This is typically a version (e.g., "v0.0.1"). message: type: string description: The tag message. object: type: string description: The SHA of the git object this is tagging. type: type: string description: The type of the object we're tagging. Normally this is a `commit` but it can also be a `tree` or a `blob`. enum: - commit - tree - blob tagger: type: object description: An object with information about the individual creating the tag. properties: name: type: string description: The name of the author of the tag email: type: string description: The email of the author of the tag date: type: string format: date-time description: 'When this object was tagged. This is a timestamp in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format: `YYYY-MM-DDTHH:MM:SSZ`.' required: - name - email required: - tag - message - object - type example: tag: v0.0.1 message: initial version object: c3d0be41ecbe669545ee3e94d31ed9a4bc91ee3c type: commit tagger: name: Monalisa Octocat email: octocat@github.com date: '2011-06-17T14:53:35-07:00' responses: '201': description: Response content: application/json: schema: "$ref": "#/components/schemas/git-tag" examples: default: "$ref": "#/components/examples/git-tag" headers: Location: example: https://api.github.com/repos/octocat/Hello-World/git/tags/940bd336248efae0f9ee5bc7b2d5c985887b16ac schema: type: string '422': "$ref": "#/components/responses/validation_failed" x-github: githubCloudOnly: false enabledForGitHubApps: true category: git subcategory: tags "/repos/{owner}/{repo}/git/tags/{tag_sha}": get: summary: Get a tag description: |- **Signature verification object** The response will include a `verification` object that describes the result of verifying the commit's signature. The following fields are included in the `verification` object: | Name | Type | Description | | ---- | ---- | ----------- | | `verified` | `boolean` | Indicates whether GitHub considers the signature in this commit to be verified. | | `reason` | `string` | The reason for verified value. Possible values and their meanings are enumerated in table below. | | `signature` | `string` | The signature that was extracted from the commit. | | `payload` | `string` | The value that was signed. | These are the possible values for `reason` in the `verification` object: | Value | Description | | ----- | ----------- | | `expired_key` | The key that made the signature is expired. | | `not_signing_key` | The "signing" flag is not among the usage flags in the GPG key that made the signature. | | `gpgverify_error` | There was an error communicating with the signature verification service. | | `gpgverify_unavailable` | The signature verification service is currently unavailable. | | `unsigned` | The object does not include a signature. | | `unknown_signature_type` | A non-PGP signature was found in the commit. | | `no_user` | No user was associated with the `committer` email address in the commit. | | `unverified_email` | The `committer` email address in the commit was associated with a user, but the email address is not verified on her/his account. | | `bad_email` | The `committer` email address in the commit is not included in the identities of the PGP key that made the signature. | | `unknown_key` | The key that made the signature has not been registered with any user's account. | | `malformed_signature` | There was an error parsing the signature. | | `invalid` | The signature could not be cryptographically verified using the key whose key-id was found in the signature. | | `valid` | None of the above errors applied, so the signature is considered to be verified. | tags: - git operationId: git/get-tag externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/git#get-a-tag parameters: - "$ref": "#/components/parameters/owner" - "$ref": "#/components/parameters/repo" - name: tag_sha in: path required: true schema: type: string responses: '200': description: Response content: application/json: schema: "$ref": "#/components/schemas/git-tag" examples: default: "$ref": "#/components/examples/git-tag" '404': "$ref": "#/components/responses/not_found" x-github: githubCloudOnly: false enabledForGitHubApps: true category: git subcategory: tags "/repos/{owner}/{repo}/git/trees": post: summary: Create a tree description: |- The tree creation API accepts nested entries. If you specify both a tree and a nested path modifying that tree, this endpoint will overwrite the contents of the tree with the new path contents, and create a new tree structure. If you use this endpoint to add, delete, or modify the file contents in a tree, you will need to commit the tree and then update a branch to point to the commit. For more information see "[Create a commit](https://docs.github.com/enterprise-server@3.0/rest/reference/git#create-a-commit)" and "[Update a reference](https://docs.github.com/enterprise-server@3.0/rest/reference/git#update-a-reference)." tags: - git operationId: git/create-tree externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/git#create-a-tree parameters: - "$ref": "#/components/parameters/owner" - "$ref": "#/components/parameters/repo" requestBody: required: true content: application/json: schema: type: object properties: tree: type: array description: Objects (of `path`, `mode`, `type`, and `sha`) specifying a tree structure. items: type: object properties: path: type: string description: The file referenced in the tree. mode: type: string description: The file mode; one of `100644` for file (blob), `100755` for executable (blob), `040000` for subdirectory (tree), `160000` for submodule (commit), or `120000` for a blob that specifies the path of a symlink. enum: - '100644' - '100755' - '040000' - '160000' - '120000' type: type: string description: Either `blob`, `tree`, or `commit`. enum: - blob - tree - commit sha: type: - string - 'null' description: "The SHA1 checksum ID of the object in the tree. Also called `tree.sha`. If the value is `null` then the file will be deleted. \n \n**Note:** Use either `tree.sha` or `content` to specify the contents of the entry. Using both `tree.sha` and `content` will return an error." content: type: string description: "The content you want this file to have. GitHub will write this blob out and use that SHA for this entry. Use either this, or `tree.sha`. \n \n**Note:** Use either `tree.sha` or `content` to specify the contents of the entry. Using both `tree.sha` and `content` will return an error." base_tree: type: string description: | The SHA1 of an existing Git tree object which will be used as the base for the new tree. If provided, a new Git tree object will be created from entries in the Git tree object pointed to by `base_tree` and entries defined in the `tree` parameter. Entries defined in the `tree` parameter will overwrite items from `base_tree` with the same `path`. If you're creating new changes on a branch, then normally you'd set `base_tree` to the SHA1 of the Git tree object of the current latest commit on the branch you're working on. If not provided, GitHub will create a new Git tree object from only the entries defined in the `tree` parameter. If you create a new commit pointing to such a tree, then all files which were a part of the parent commit's tree and were not defined in the `tree` parameter will be listed as deleted by the new commit. required: - tree example: base_tree: 9fb037999f264ba9a7fc6274d15fa3ae2ab98312 tree: - path: file.rb mode: '100644' type: blob sha: 44b4fc6d56897b048c772eb4087f854f46256132 responses: '201': description: Response content: application/json: schema: "$ref": "#/components/schemas/git-tree" examples: default: "$ref": "#/components/examples/git-tree" headers: Location: example: https://api.github.com/repos/octocat/Hello-World/trees/cd8274d15fa3ae2ab983129fb037999f264ba9a7 schema: type: string '422': "$ref": "#/components/responses/validation_failed" '404': "$ref": "#/components/responses/not_found" '403': "$ref": "#/components/responses/forbidden" x-github: githubCloudOnly: false enabledForGitHubApps: true category: git subcategory: trees "/repos/{owner}/{repo}/git/trees/{tree_sha}": get: summary: Get a tree description: |- Returns a single tree using the SHA1 value for that tree. If `truncated` is `true` in the response then the number of items in the `tree` array exceeded our maximum limit. If you need to fetch more items, use the non-recursive method of fetching trees, and fetch one sub-tree at a time. tags: - git operationId: git/get-tree externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/git#get-a-tree parameters: - "$ref": "#/components/parameters/owner" - "$ref": "#/components/parameters/repo" - name: tree_sha in: path required: true schema: type: string x-multi-segment: true - name: recursive description: 'Setting this parameter to any value returns the objects or subtrees referenced by the tree specified in `:tree_sha`. For example, setting `recursive` to any of the following will enable returning objects or subtrees: `0`, `1`, `"true"`, and `"false"`. Omit this parameter to prevent recursively returning objects or subtrees.' in: query required: false schema: type: string responses: '200': description: Response content: application/json: schema: "$ref": "#/components/schemas/git-tree" examples: default-response: "$ref": "#/components/examples/git-tree-default-response" response-recursively-retrieving-a-tree: "$ref": "#/components/examples/git-tree-response-recursively-retrieving-a-tree" '422': "$ref": "#/components/responses/validation_failed" '404': "$ref": "#/components/responses/not_found" x-github: githubCloudOnly: false enabledForGitHubApps: true category: git subcategory: trees "/repos/{owner}/{repo}/hooks": get: summary: List repository webhooks description: '' tags: - repos operationId: repos/list-webhooks externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/repos#list-repository-webhooks parameters: - "$ref": "#/components/parameters/owner" - "$ref": "#/components/parameters/repo" - "$ref": "#/components/parameters/per-page" - "$ref": "#/components/parameters/page" responses: '200': description: Response content: application/json: schema: type: array items: "$ref": "#/components/schemas/hook" examples: default: "$ref": "#/components/examples/hook-items" headers: Link: "$ref": "#/components/headers/link" '404': "$ref": "#/components/responses/not_found" x-github: githubCloudOnly: false enabledForGitHubApps: true category: repos subcategory: webhooks post: summary: Create a repository webhook description: |- Repositories can have multiple webhooks installed. Each webhook should have a unique `config`. Multiple webhooks can share the same `config` as long as those webhooks do not have any `events` that overlap. tags: - repos operationId: repos/create-webhook externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/repos#create-a-repository-webhook parameters: - "$ref": "#/components/parameters/owner" - "$ref": "#/components/parameters/repo" requestBody: required: false content: application/json: schema: type: - object - 'null' properties: name: type: string description: 'Use `web` to create a webhook. Default: `web`. This parameter only accepts the value `web`.' config: type: object description: Key/value pairs to provide settings for this webhook. [These are defined below](https://docs.github.com/enterprise-server@3.0/rest/reference/repos#create-hook-config-params). properties: url: "$ref": "#/components/schemas/webhook-config-url" content_type: "$ref": "#/components/schemas/webhook-config-content-type" secret: "$ref": "#/components/schemas/webhook-config-secret" insecure_ssl: "$ref": "#/components/schemas/webhook-config-insecure-ssl" token: type: string examples: - '"abc"' digest: type: string examples: - '"sha256"' events: type: array description: Determines what [events](https://docs.github.com/enterprise-server@3.0/webhooks/event-payloads) the hook is triggered for. default: - push items: type: string active: type: boolean description: Determines if notifications are sent when the webhook is triggered. Set to `true` to send notifications. default: true additionalProperties: false example: name: web active: true events: - push - pull_request config: url: https://example.com/webhook content_type: json insecure_ssl: '0' responses: '201': description: Response content: application/json: schema: "$ref": "#/components/schemas/hook" examples: default: "$ref": "#/components/examples/hook" headers: Location: example: https://api.github.com/repos/octocat/Hello-World/hooks/12345678 schema: type: string '404': "$ref": "#/components/responses/not_found" '422': "$ref": "#/components/responses/validation_failed" '403': "$ref": "#/components/responses/forbidden" x-github: githubCloudOnly: false enabledForGitHubApps: true category: repos subcategory: webhooks "/repos/{owner}/{repo}/hooks/{hook_id}": get: summary: Get a repository webhook description: Returns a webhook configured in a repository. To get only the webhook `config` properties, see "[Get a webhook configuration for a repository](/rest/reference/repos#get-a-webhook-configuration-for-a-repository)." tags: - repos operationId: repos/get-webhook externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/repos#get-a-repository-webhook parameters: - "$ref": "#/components/parameters/owner" - "$ref": "#/components/parameters/repo" - "$ref": "#/components/parameters/hook-id" responses: '200': description: Response content: application/json: schema: "$ref": "#/components/schemas/hook" examples: default: "$ref": "#/components/examples/hook" '404': "$ref": "#/components/responses/not_found" x-github: githubCloudOnly: false enabledForGitHubApps: true category: repos subcategory: webhooks patch: summary: Update a repository webhook description: Updates a webhook configured in a repository. If you previously had a `secret` set, you must provide the same `secret` or set a new `secret` or the secret will be removed. If you are only updating individual webhook `config` properties, use "[Update a webhook configuration for a repository](/rest/reference/repos#update-a-webhook-configuration-for-a-repository)." tags: - repos operationId: repos/update-webhook externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/repos#update-a-repository-webhook parameters: - "$ref": "#/components/parameters/owner" - "$ref": "#/components/parameters/repo" - "$ref": "#/components/parameters/hook-id" requestBody: required: true content: application/json: schema: type: object properties: config: type: object description: Key/value pairs to provide settings for this webhook. [These are defined below](https://docs.github.com/enterprise-server@3.0/rest/reference/repos#create-hook-config-params). properties: url: "$ref": "#/components/schemas/webhook-config-url" content_type: "$ref": "#/components/schemas/webhook-config-content-type" secret: "$ref": "#/components/schemas/webhook-config-secret" insecure_ssl: "$ref": "#/components/schemas/webhook-config-insecure-ssl" address: type: string examples: - '"bar@example.com"' room: type: string examples: - '"The Serious Room"' required: - url events: type: array description: Determines what [events](https://docs.github.com/enterprise-server@3.0/webhooks/event-payloads) the hook is triggered for. This replaces the entire array of events. default: - push items: type: string add_events: type: array description: Determines a list of events to be added to the list of events that the Hook triggers for. items: type: string remove_events: type: array description: Determines a list of events to be removed from the list of events that the Hook triggers for. items: type: string active: type: boolean description: Determines if notifications are sent when the webhook is triggered. Set to `true` to send notifications. default: true example: active: true add_events: - pull_request responses: '200': description: Response content: application/json: schema: "$ref": "#/components/schemas/hook" examples: default: "$ref": "#/components/examples/hook" '422': "$ref": "#/components/responses/validation_failed" '404': "$ref": "#/components/responses/not_found" x-github: githubCloudOnly: false enabledForGitHubApps: true category: repos subcategory: webhooks delete: summary: Delete a repository webhook description: '' tags: - repos operationId: repos/delete-webhook externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/repos#delete-a-repository-webhook parameters: - "$ref": "#/components/parameters/owner" - "$ref": "#/components/parameters/repo" - "$ref": "#/components/parameters/hook-id" responses: '204': description: Response '404': "$ref": "#/components/responses/not_found" x-github: githubCloudOnly: false enabledForGitHubApps: true category: repos subcategory: webhooks "/repos/{owner}/{repo}/hooks/{hook_id}/config": get: summary: Get a webhook configuration for a repository description: |- Returns the webhook configuration for a repository. To get more information about the webhook, including the `active` state and `events`, use "[Get a repository webhook](/rest/reference/orgs#get-a-repository-webhook)." Access tokens must have the `read:repo_hook` or `repo` scope, and GitHub Apps must have the `repository_hooks:read` permission. tags: - repos operationId: repos/get-webhook-config-for-repo externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/repos#get-a-webhook-configuration-for-a-repository parameters: - "$ref": "#/components/parameters/owner" - "$ref": "#/components/parameters/repo" - "$ref": "#/components/parameters/hook-id" responses: '200': description: Response content: application/json: schema: "$ref": "#/components/schemas/webhook-config" examples: default: "$ref": "#/components/examples/webhook-config" x-github: githubCloudOnly: false enabledForGitHubApps: true category: repos subcategory: webhooks patch: summary: Update a webhook configuration for a repository description: |- Updates the webhook configuration for a repository. To update more information about the webhook, including the `active` state and `events`, use "[Update a repository webhook](/rest/reference/orgs#update-a-repository-webhook)." Access tokens must have the `write:repo_hook` or `repo` scope, and GitHub Apps must have the `repository_hooks:write` permission. tags: - repos operationId: repos/update-webhook-config-for-repo externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/repos#update-a-webhook-configuration-for-a-repository parameters: - "$ref": "#/components/parameters/owner" - "$ref": "#/components/parameters/repo" - "$ref": "#/components/parameters/hook-id" requestBody: required: false content: application/json: schema: type: object additionalProperties: false properties: url: "$ref": "#/components/schemas/webhook-config-url" content_type: "$ref": "#/components/schemas/webhook-config-content-type" secret: "$ref": "#/components/schemas/webhook-config-secret" insecure_ssl: "$ref": "#/components/schemas/webhook-config-insecure-ssl" example: content_type: json insecure_ssl: '0' secret: "********" url: https://example.com/webhook responses: '200': description: Response content: application/json: schema: "$ref": "#/components/schemas/webhook-config" examples: default: "$ref": "#/components/examples/webhook-config" x-github: githubCloudOnly: false enabledForGitHubApps: true category: repos subcategory: webhooks "/repos/{owner}/{repo}/hooks/{hook_id}/pings": post: summary: Ping a repository webhook description: This will trigger a [ping event](https://docs.github.com/enterprise-server@3.0/webhooks/#ping-event) to be sent to the hook. tags: - repos operationId: repos/ping-webhook externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/repos#ping-a-repository-webhook parameters: - "$ref": "#/components/parameters/owner" - "$ref": "#/components/parameters/repo" - "$ref": "#/components/parameters/hook-id" responses: '204': description: Response '404': "$ref": "#/components/responses/not_found" x-github: githubCloudOnly: false enabledForGitHubApps: true category: repos subcategory: webhooks "/repos/{owner}/{repo}/hooks/{hook_id}/tests": post: summary: Test the push repository webhook description: |- This will trigger the hook with the latest push to the current repository if the hook is subscribed to `push` events. If the hook is not subscribed to `push` events, the server will respond with 204 but no test POST will be generated. **Note**: Previously `/repos/:owner/:repo/hooks/:hook_id/test` tags: - repos operationId: repos/test-push-webhook externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/repos#test-the-push-repository-webhook parameters: - "$ref": "#/components/parameters/owner" - "$ref": "#/components/parameters/repo" - "$ref": "#/components/parameters/hook-id" responses: '204': description: Response '404': "$ref": "#/components/responses/not_found" x-github: githubCloudOnly: false enabledForGitHubApps: true category: repos subcategory: webhooks "/repos/{owner}/{repo}/installation": get: summary: Get a repository installation for the authenticated app description: |- Enables an authenticated GitHub App to find the repository's installation information. The installation's account type will be either an organization or a user account, depending which account the repository belongs to. You must use a [JWT](https://docs.github.com/enterprise-server@3.0/apps/building-github-apps/authenticating-with-github-apps/#authenticating-as-a-github-app) to access this endpoint. tags: - apps operationId: apps/get-repo-installation externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/apps#get-a-repository-installation-for-the-authenticated-app parameters: - "$ref": "#/components/parameters/owner" - "$ref": "#/components/parameters/repo" responses: '200': description: Response content: application/json: schema: "$ref": "#/components/schemas/installation" examples: default: "$ref": "#/components/examples/installation" '301': "$ref": "#/components/responses/moved_permanently" '404': "$ref": "#/components/responses/not_found" x-github: githubCloudOnly: false enabledForGitHubApps: false category: apps subcategory: "/repos/{owner}/{repo}/invitations": get: summary: List repository invitations description: When authenticating as a user with admin rights to a repository, this endpoint will list all currently open repository invitations. tags: - repos operationId: repos/list-invitations externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/repos#list-repository-invitations parameters: - "$ref": "#/components/parameters/owner" - "$ref": "#/components/parameters/repo" - "$ref": "#/components/parameters/per-page" - "$ref": "#/components/parameters/page" responses: '200': description: Response content: application/json: schema: type: array items: "$ref": "#/components/schemas/repository-invitation" examples: default: "$ref": "#/components/examples/repository-invitation-items" headers: Link: "$ref": "#/components/headers/link" x-github: githubCloudOnly: false enabledForGitHubApps: true category: repos subcategory: invitations "/repos/{owner}/{repo}/invitations/{invitation_id}": patch: summary: Update a repository invitation description: '' tags: - repos operationId: repos/update-invitation externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/repos#update-a-repository-invitation parameters: - "$ref": "#/components/parameters/owner" - "$ref": "#/components/parameters/repo" - "$ref": "#/components/parameters/invitation-id" requestBody: required: false content: application/json: schema: type: object properties: permissions: type: string description: The permissions that the associated user will have on the repository. Valid values are `read`, `write`, `maintain`, `triage`, and `admin`. enum: - read - write - maintain - triage - admin responses: '200': description: Response content: application/json: schema: "$ref": "#/components/schemas/repository-invitation" examples: default: "$ref": "#/components/examples/repository-invitation" x-github: githubCloudOnly: false enabledForGitHubApps: true category: repos subcategory: invitations delete: summary: Delete a repository invitation description: '' tags: - repos operationId: repos/delete-invitation externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/repos#delete-a-repository-invitation parameters: - "$ref": "#/components/parameters/owner" - "$ref": "#/components/parameters/repo" - "$ref": "#/components/parameters/invitation-id" responses: '204': description: Response x-github: githubCloudOnly: false enabledForGitHubApps: true category: repos subcategory: invitations "/repos/{owner}/{repo}/issues": get: summary: List repository issues description: |- List issues in a repository. **Note**: GitHub's REST API v3 considers every pull request an issue, but not every issue is a pull request. For this reason, "Issues" endpoints may return both issues and pull requests in the response. You can identify pull requests by the `pull_request` key. Be aware that the `id` of a pull request returned from "Issues" endpoints will be an _issue id_. To find out the pull request id, use the "[List pull requests](https://docs.github.com/enterprise-server@3.0/rest/reference/pulls#list-pull-requests)" endpoint. tags: - issues operationId: issues/list-for-repo externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/issues#list-repository-issues parameters: - "$ref": "#/components/parameters/owner" - "$ref": "#/components/parameters/repo" - name: milestone description: If an `integer` is passed, it should refer to a milestone by its `number` field. If the string `*` is passed, issues with any milestone are accepted. If the string `none` is passed, issues without milestones are returned. in: query required: false schema: type: string - name: state description: Indicates the state of the issues to return. Can be either `open`, `closed`, or `all`. in: query required: false schema: type: string enum: - open - closed - all default: open - name: assignee description: Can be the name of a user. Pass in `none` for issues with no assigned user, and `*` for issues assigned to any user. in: query required: false schema: type: string - name: creator description: The user that created the issue. in: query required: false schema: type: string - name: mentioned description: A user that's mentioned in the issue. in: query required: false schema: type: string - "$ref": "#/components/parameters/labels" - name: sort description: What to sort results by. Can be either `created`, `updated`, `comments`. in: query required: false schema: type: string enum: - created - updated - comments default: created - "$ref": "#/components/parameters/direction" - "$ref": "#/components/parameters/since" - "$ref": "#/components/parameters/per-page" - "$ref": "#/components/parameters/page" responses: '200': description: Response content: application/json: schema: type: array items: "$ref": "#/components/schemas/issue" examples: default: "$ref": "#/components/examples/issue-items" headers: Link: "$ref": "#/components/headers/link" '301': "$ref": "#/components/responses/moved_permanently" '422': "$ref": "#/components/responses/validation_failed" '404': "$ref": "#/components/responses/not_found" x-github: githubCloudOnly: false enabledForGitHubApps: true category: issues previews: - required: false name: machine-man note: "If an issue event is created via a GitHub App, the response will include the `performed_via_github_app` object with\tinformation about the GitHub App. For more information, see the [related blog\tpost](https://developer.github.com/changes/2016-09-14-Integrations-Early-Access).\nTo receive the `performed_via_github_app` object in the response, you must provide a custom [media type](https://docs.github.com/enterprise-server@3.0/rest/overview/media-types) in the `Accept` header:\n```shell\napplication/vnd.github.machine-man-preview\n```" - required: false name: squirrel-girl note: |- An additional `reactions` object in the issue comment payload is currently available for developers to preview. During the preview period, the APIs may change without advance notice. Please see the [blog post](https://developer.github.com/changes/2016-05-12-reactions-api-preview) for full details. To access the API you must provide a custom [media type](https://docs.github.com/enterprise-server@3.0/rest/overview/media-types) in the `Accept` header: ```shell application/vnd.github.squirrel-girl-preview ``` The `reactions` key will have the following payload where `url` can be used to construct the API location for [listing and creating](https://docs.github.com/enterprise-server@3.0/rest/reference/reactions) reactions. post: summary: Create an issue description: |- Any user with pull access to a repository can create an issue. If [issues are disabled in the repository](https://docs.github.com/articles/disabling-issues/), the API returns a `410 Gone` status. This endpoint triggers [notifications](https://docs.github.com/enterprise-server@3.0/github/managing-subscriptions-and-notifications-on-github/about-notifications). Creating content too quickly using this endpoint may result in secondary rate limiting. See "[Secondary rate limits](https://docs.github.com/enterprise-server@3.0/rest/overview/resources-in-the-rest-api#secondary-rate-limits)" and "[Dealing with secondary rate limits](https://docs.github.com/enterprise-server@3.0/rest/guides/best-practices-for-integrators#dealing-with-secondary-rate-limits)" for details. tags: - issues operationId: issues/create externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/issues#create-an-issue parameters: - "$ref": "#/components/parameters/owner" - "$ref": "#/components/parameters/repo" requestBody: required: true content: application/json: schema: type: object properties: title: oneOf: - type: string - type: integer description: The title of the issue. body: type: string description: The contents of the issue. assignee: type: - string - 'null' description: 'Login for the user that this issue should be assigned to. _NOTE: Only users with push access can set the assignee for new issues. The assignee is silently dropped otherwise. **This field is deprecated.**_' milestone: oneOf: - type: string - type: integer description: 'The `number` of the milestone to associate this issue with. _NOTE: Only users with push access can set the milestone for new issues. The milestone is silently dropped otherwise._' type: - 'null' - string - integer labels: type: array description: 'Labels to associate with this issue. _NOTE: Only users with push access can set labels for new issues. Labels are silently dropped otherwise._' items: oneOf: - type: string - type: object properties: id: type: integer name: type: string description: type: - string - 'null' color: type: - string - 'null' assignees: type: array description: 'Logins for Users to assign to this issue. _NOTE: Only users with push access can set assignees for new issues. Assignees are silently dropped otherwise._' items: type: string required: - title example: title: Found a bug body: I'm having a problem with this. assignees: - octocat milestone: 1 labels: - bug responses: '201': description: Response content: application/json: schema: "$ref": "#/components/schemas/issue" examples: default: "$ref": "#/components/examples/issue" headers: Location: example: https://api.github.com/repos/octocat/Hello-World/issues/1347 schema: type: string '403': "$ref": "#/components/responses/forbidden" '422': "$ref": "#/components/responses/validation_failed" '503': "$ref": "#/components/responses/service_unavailable" '404': "$ref": "#/components/responses/not_found" '410': "$ref": "#/components/responses/gone" x-github: triggersNotification: true githubCloudOnly: false enabledForGitHubApps: true category: issues subcategory: "/repos/{owner}/{repo}/issues/comments": get: summary: List issue comments for a repository description: By default, Issue Comments are ordered by ascending ID. tags: - issues operationId: issues/list-comments-for-repo externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/issues#list-issue-comments-for-a-repository parameters: - "$ref": "#/components/parameters/owner" - "$ref": "#/components/parameters/repo" - "$ref": "#/components/parameters/sort" - name: direction description: Either `asc` or `desc`. Ignored without the `sort` parameter. in: query required: false schema: type: string enum: - asc - desc - "$ref": "#/components/parameters/since" - "$ref": "#/components/parameters/per-page" - "$ref": "#/components/parameters/page" responses: '200': description: Response content: application/json: schema: type: array items: "$ref": "#/components/schemas/issue-comment" examples: default: "$ref": "#/components/examples/issue-comment-items" headers: Link: "$ref": "#/components/headers/link" '422': "$ref": "#/components/responses/validation_failed" '404': "$ref": "#/components/responses/not_found" x-github: githubCloudOnly: false enabledForGitHubApps: true category: issues subcategory: comments previews: - required: false name: squirrel-girl note: |- An additional `reactions` object in the issue comment payload is currently available for developers to preview. During the preview period, the APIs may change without advance notice. Please see the [blog post](https://developer.github.com/changes/2016-05-12-reactions-api-preview) for full details. To access the API you must provide a custom [media type](https://docs.github.com/enterprise-server@3.0/rest/overview/media-types) in the `Accept` header: ```shell application/vnd.github.squirrel-girl-preview ``` The `reactions` key will have the following payload where `url` can be used to construct the API location for [listing and creating](https://docs.github.com/enterprise-server@3.0/rest/reference/reactions) reactions. "/repos/{owner}/{repo}/issues/comments/{comment_id}": get: summary: Get an issue comment description: '' tags: - issues operationId: issues/get-comment externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/issues#get-an-issue-comment parameters: - "$ref": "#/components/parameters/owner" - "$ref": "#/components/parameters/repo" - "$ref": "#/components/parameters/comment-id" responses: '200': description: Response content: application/json: schema: "$ref": "#/components/schemas/issue-comment" examples: default: "$ref": "#/components/examples/issue-comment" '404': "$ref": "#/components/responses/not_found" x-github: githubCloudOnly: false enabledForGitHubApps: true category: issues subcategory: comments previews: - required: false name: machine-man note: "If an issue event is created via a GitHub App, the response will include the `performed_via_github_app` object with\tinformation about the GitHub App. For more information, see the [related blog\tpost](https://developer.github.com/changes/2016-09-14-Integrations-Early-Access).\nTo receive the `performed_via_github_app` object in the response, you must provide a custom [media type](https://docs.github.com/enterprise-server@3.0/rest/overview/media-types) in the `Accept` header:\n```shell\napplication/vnd.github.machine-man-preview\n```" - required: false name: squirrel-girl note: |- An additional `reactions` object in the issue comment payload is currently available for developers to preview. During the preview period, the APIs may change without advance notice. Please see the [blog post](https://developer.github.com/changes/2016-05-12-reactions-api-preview) for full details. To access the API you must provide a custom [media type](https://docs.github.com/enterprise-server@3.0/rest/overview/media-types) in the `Accept` header: ```shell application/vnd.github.squirrel-girl-preview ``` The `reactions` key will have the following payload where `url` can be used to construct the API location for [listing and creating](https://docs.github.com/enterprise-server@3.0/rest/reference/reactions) reactions. patch: summary: Update an issue comment description: '' tags: - issues operationId: issues/update-comment externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/issues#update-an-issue-comment parameters: - "$ref": "#/components/parameters/owner" - "$ref": "#/components/parameters/repo" - "$ref": "#/components/parameters/comment-id" requestBody: required: true content: application/json: schema: type: object properties: body: type: string description: The contents of the comment. required: - body example: body: Me too responses: '200': description: Response content: application/json: schema: "$ref": "#/components/schemas/issue-comment" examples: default: "$ref": "#/components/examples/issue-comment" '422': "$ref": "#/components/responses/validation_failed" x-github: githubCloudOnly: false enabledForGitHubApps: true category: issues subcategory: comments delete: summary: Delete an issue comment description: '' tags: - issues operationId: issues/delete-comment externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/issues#delete-an-issue-comment parameters: - "$ref": "#/components/parameters/owner" - "$ref": "#/components/parameters/repo" - "$ref": "#/components/parameters/comment-id" responses: '204': description: Response x-github: githubCloudOnly: false enabledForGitHubApps: true category: issues subcategory: comments "/repos/{owner}/{repo}/issues/comments/{comment_id}/reactions": get: summary: List reactions for an issue comment description: List the reactions to an [issue comment](https://docs.github.com/enterprise-server@3.0/rest/reference/issues#comments). tags: - reactions operationId: reactions/list-for-issue-comment externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/reactions#list-reactions-for-an-issue-comment parameters: - "$ref": "#/components/parameters/owner" - "$ref": "#/components/parameters/repo" - "$ref": "#/components/parameters/comment-id" - name: content description: Returns a single [reaction type](https://docs.github.com/enterprise-server@3.0/rest/reference/reactions#reaction-types). Omit this parameter to list all reactions to an issue comment. in: query required: false schema: type: string enum: - "+1" - "-1" - laugh - confused - heart - hooray - rocket - eyes - "$ref": "#/components/parameters/per-page" - "$ref": "#/components/parameters/page" responses: '200': description: Response content: application/json: schema: type: array items: "$ref": "#/components/schemas/reaction" examples: default: "$ref": "#/components/examples/reaction-items" headers: Link: "$ref": "#/components/headers/link" '404': "$ref": "#/components/responses/not_found" x-github: githubCloudOnly: false enabledForGitHubApps: true category: reactions previews: - required: true name: squirrel-girl note: |- An additional `reactions` object in the issue comment payload is currently available for developers to preview. During the preview period, the APIs may change without advance notice. Please see the [blog post](https://developer.github.com/changes/2016-05-12-reactions-api-preview) for full details. To access the API you must provide a custom [media type](https://docs.github.com/enterprise-server@3.0/rest/overview/media-types) in the `Accept` header: ```shell application/vnd.github.squirrel-girl-preview ``` The `reactions` key will have the following payload where `url` can be used to construct the API location for [listing and creating](https://docs.github.com/enterprise-server@3.0/rest/reference/reactions) reactions. post: summary: Create reaction for an issue comment description: Create a reaction to an [issue comment](https://docs.github.com/enterprise-server@3.0/rest/reference/issues#comments). A response with an HTTP `200` status means that you already added the reaction type to this issue comment. tags: - reactions operationId: reactions/create-for-issue-comment externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/reactions#create-reaction-for-an-issue-comment parameters: - "$ref": "#/components/parameters/owner" - "$ref": "#/components/parameters/repo" - "$ref": "#/components/parameters/comment-id" requestBody: required: true content: application/json: schema: type: object properties: content: type: string description: The [reaction type](https://docs.github.com/enterprise-server@3.0/rest/reference/reactions#reaction-types) to add to the issue comment. enum: - "+1" - "-1" - laugh - confused - heart - hooray - rocket - eyes required: - content example: content: heart responses: '200': description: Reaction exists content: application/json: schema: "$ref": "#/components/schemas/reaction" examples: default: "$ref": "#/components/examples/reaction" '201': description: Reaction created content: application/json: schema: "$ref": "#/components/schemas/reaction" examples: default: "$ref": "#/components/examples/reaction" '422': "$ref": "#/components/responses/validation_failed" x-github: githubCloudOnly: false enabledForGitHubApps: true category: reactions previews: - required: true name: squirrel-girl note: |- An additional `reactions` object in the issue comment payload is currently available for developers to preview. During the preview period, the APIs may change without advance notice. Please see the [blog post](https://developer.github.com/changes/2016-05-12-reactions-api-preview) for full details. To access the API you must provide a custom [media type](https://docs.github.com/enterprise-server@3.0/rest/overview/media-types) in the `Accept` header: ```shell application/vnd.github.squirrel-girl-preview ``` The `reactions` key will have the following payload where `url` can be used to construct the API location for [listing and creating](https://docs.github.com/enterprise-server@3.0/rest/reference/reactions) reactions. "/repos/{owner}/{repo}/issues/comments/{comment_id}/reactions/{reaction_id}": delete: summary: Delete an issue comment reaction description: |- **Note:** You can also specify a repository by `repository_id` using the route `DELETE delete /repositories/:repository_id/issues/comments/:comment_id/reactions/:reaction_id`. Delete a reaction to an [issue comment](https://docs.github.com/enterprise-server@3.0/rest/reference/issues#comments). tags: - reactions operationId: reactions/delete-for-issue-comment externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/reactions#delete-an-issue-comment-reaction parameters: - "$ref": "#/components/parameters/owner" - "$ref": "#/components/parameters/repo" - "$ref": "#/components/parameters/comment-id" - "$ref": "#/components/parameters/reaction-id" responses: '204': description: Response x-github: githubCloudOnly: false enabledForGitHubApps: true category: reactions previews: - required: true name: squirrel-girl note: |- An additional `reactions` object in the issue comment payload is currently available for developers to preview. During the preview period, the APIs may change without advance notice. Please see the [blog post](https://developer.github.com/changes/2016-05-12-reactions-api-preview) for full details. To access the API you must provide a custom [media type](https://docs.github.com/enterprise-server@3.0/rest/overview/media-types) in the `Accept` header: ```shell application/vnd.github.squirrel-girl-preview ``` The `reactions` key will have the following payload where `url` can be used to construct the API location for [listing and creating](https://docs.github.com/enterprise-server@3.0/rest/reference/reactions) reactions. "/repos/{owner}/{repo}/issues/events": get: summary: List issue events for a repository description: '' tags: - issues operationId: issues/list-events-for-repo externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/issues#list-issue-events-for-a-repository parameters: - "$ref": "#/components/parameters/owner" - "$ref": "#/components/parameters/repo" - "$ref": "#/components/parameters/per-page" - "$ref": "#/components/parameters/page" responses: '200': description: Response content: application/json: schema: type: array items: "$ref": "#/components/schemas/issue-event" examples: default: "$ref": "#/components/examples/issue-event-items" headers: Link: "$ref": "#/components/headers/link" '422': "$ref": "#/components/responses/validation_failed" x-github: githubCloudOnly: false enabledForGitHubApps: true category: issues subcategory: events previews: - required: false name: starfox note: |- Project card details are now shown in REST API v3 responses for project-related issue and timeline events. This feature is now available for developers to preview. For details, see the [blog post](https://developer.github.com/changes/2018-09-05-project-card-events). To receive the `project_card` attribute, project boards must be [enabled](https://docs.github.com/articles/disabling-project-boards-in-a-repository) for a repository, and you must provide a custom [media type](https://docs.github.com/enterprise-server@3.0/rest/overview/media-types) in the `Accept` header: ```shell application/vnd.github.starfox-preview+json ``` "/repos/{owner}/{repo}/issues/events/{event_id}": get: summary: Get an issue event description: '' tags: - issues operationId: issues/get-event externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/issues#get-an-issue-event parameters: - "$ref": "#/components/parameters/owner" - "$ref": "#/components/parameters/repo" - name: event_id in: path required: true schema: type: integer responses: '200': description: Response content: application/json: schema: "$ref": "#/components/schemas/issue-event" examples: default: "$ref": "#/components/examples/issue-event" '404': "$ref": "#/components/responses/not_found" '410': "$ref": "#/components/responses/gone" '403': "$ref": "#/components/responses/forbidden" x-github: githubCloudOnly: false enabledForGitHubApps: true category: issues subcategory: events previews: - required: false name: starfox note: |- Project card details are now shown in REST API v3 responses for project-related issue and timeline events. This feature is now available for developers to preview. For details, see the [blog post](https://developer.github.com/changes/2018-09-05-project-card-events). To receive the `project_card` attribute, project boards must be [enabled](https://docs.github.com/articles/disabling-project-boards-in-a-repository) for a repository, and you must provide a custom [media type](https://docs.github.com/enterprise-server@3.0/rest/overview/media-types) in the `Accept` header: ```shell application/vnd.github.starfox-preview+json ``` "/repos/{owner}/{repo}/issues/{issue_number}": get: summary: Get an issue description: |- The API returns a [`301 Moved Permanently` status](https://docs.github.com/enterprise-server@3.0/rest/overview/resources-in-the-rest-api#http-redirects-redirects) if the issue was [transferred](https://docs.github.com/articles/transferring-an-issue-to-another-repository/) to another repository. If the issue was transferred to or deleted from a repository where the authenticated user lacks read access, the API returns a `404 Not Found` status. If the issue was deleted from a repository where the authenticated user has read access, the API returns a `410 Gone` status. To receive webhook events for transferred and deleted issues, subscribe to the [`issues`](https://docs.github.com/enterprise-server@3.0/webhooks/event-payloads/#issues) webhook. **Note**: GitHub's REST API v3 considers every pull request an issue, but not every issue is a pull request. For this reason, "Issues" endpoints may return both issues and pull requests in the response. You can identify pull requests by the `pull_request` key. Be aware that the `id` of a pull request returned from "Issues" endpoints will be an _issue id_. To find out the pull request id, use the "[List pull requests](https://docs.github.com/enterprise-server@3.0/rest/reference/pulls#list-pull-requests)" endpoint. tags: - issues operationId: issues/get externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/issues#get-an-issue parameters: - "$ref": "#/components/parameters/owner" - "$ref": "#/components/parameters/repo" - "$ref": "#/components/parameters/issue-number" responses: '200': description: Response content: application/json: schema: "$ref": "#/components/schemas/issue" examples: default: "$ref": "#/components/examples/issue" '301': "$ref": "#/components/responses/moved_permanently" '404': "$ref": "#/components/responses/not_found" '410': "$ref": "#/components/responses/gone" '304': "$ref": "#/components/responses/not_modified" x-github: githubCloudOnly: false enabledForGitHubApps: true category: issues previews: - required: false name: squirrel-girl note: |- An additional `reactions` object in the issue comment payload is currently available for developers to preview. During the preview period, the APIs may change without advance notice. Please see the [blog post](https://developer.github.com/changes/2016-05-12-reactions-api-preview) for full details. To access the API you must provide a custom [media type](https://docs.github.com/enterprise-server@3.0/rest/overview/media-types) in the `Accept` header: ```shell application/vnd.github.squirrel-girl-preview ``` The `reactions` key will have the following payload where `url` can be used to construct the API location for [listing and creating](https://docs.github.com/enterprise-server@3.0/rest/reference/reactions) reactions. patch: summary: Update an issue description: Issue owners and users with push access can edit an issue. tags: - issues operationId: issues/update externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/issues/#update-an-issue parameters: - "$ref": "#/components/parameters/owner" - "$ref": "#/components/parameters/repo" - "$ref": "#/components/parameters/issue-number" requestBody: required: false content: application/json: schema: type: object properties: title: oneOf: - type: string - type: integer description: The title of the issue. type: - 'null' - string - integer body: type: - string - 'null' description: The contents of the issue. assignee: type: - string - 'null' description: Login for the user that this issue should be assigned to. **This field is deprecated.** state: type: string description: State of the issue. Either `open` or `closed`. enum: - open - closed milestone: oneOf: - type: string - type: integer description: 'The `number` of the milestone to associate this issue with or `null` to remove current. _NOTE: Only users with push access can set the milestone for issues. The milestone is silently dropped otherwise._' type: - 'null' - string - integer labels: type: array description: 'Labels to associate with this issue. Pass one or more Labels to _replace_ the set of Labels on this Issue. Send an empty array (`[]`) to clear all Labels from the Issue. _NOTE: Only users with push access can set labels for issues. Labels are silently dropped otherwise._' items: oneOf: - type: string - type: object properties: id: type: integer name: type: string description: type: - string - 'null' color: type: - string - 'null' assignees: type: array description: 'Logins for Users to assign to this issue. Pass one or more user logins to _replace_ the set of assignees on this Issue. Send an empty array (`[]`) to clear all assignees from the Issue. _NOTE: Only users with push access can set assignees for new issues. Assignees are silently dropped otherwise._' items: type: string example: title: Found a bug body: I'm having a problem with this. assignees: - octocat milestone: 1 state: open labels: - bug responses: '200': description: Response content: application/json: schema: "$ref": "#/components/schemas/issue" examples: default: "$ref": "#/components/examples/issue" '422': "$ref": "#/components/responses/validation_failed" '503': "$ref": "#/components/responses/service_unavailable" '403': "$ref": "#/components/responses/forbidden" '301': "$ref": "#/components/responses/moved_permanently" '404': "$ref": "#/components/responses/not_found" '410': "$ref": "#/components/responses/gone" x-github: githubCloudOnly: false enabledForGitHubApps: true category: issues subcategory: "/repos/{owner}/{repo}/issues/{issue_number}/assignees": post: summary: Add assignees to an issue description: Adds up to 10 assignees to an issue. Users already assigned to an issue are not replaced. tags: - issues operationId: issues/add-assignees externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/issues#add-assignees-to-an-issue parameters: - "$ref": "#/components/parameters/owner" - "$ref": "#/components/parameters/repo" - "$ref": "#/components/parameters/issue-number" requestBody: required: false content: application/json: schema: type: object properties: assignees: type: array description: 'Usernames of people to assign this issue to. _NOTE: Only users with push access can add assignees to an issue. Assignees are silently ignored otherwise._' items: type: string example: assignees: - hubot - other_user responses: '201': description: Response content: application/json: schema: "$ref": "#/components/schemas/issue" examples: default: "$ref": "#/components/examples/issue" x-github: githubCloudOnly: false enabledForGitHubApps: true category: issues subcategory: assignees delete: summary: Remove assignees from an issue description: Removes one or more assignees from an issue. tags: - issues operationId: issues/remove-assignees externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/issues#remove-assignees-from-an-issue parameters: - "$ref": "#/components/parameters/owner" - "$ref": "#/components/parameters/repo" - "$ref": "#/components/parameters/issue-number" requestBody: content: application/json: schema: type: object properties: assignees: type: array description: 'Usernames of assignees to remove from an issue. _NOTE: Only users with push access can remove assignees from an issue. Assignees are silently ignored otherwise._' items: type: string example: assignees: - hubot - other_user responses: '200': description: Response content: application/json: schema: "$ref": "#/components/schemas/issue" examples: default: "$ref": "#/components/examples/issue" x-github: githubCloudOnly: false enabledForGitHubApps: true category: issues subcategory: assignees "/repos/{owner}/{repo}/issues/{issue_number}/comments": get: summary: List issue comments description: Issue Comments are ordered by ascending ID. tags: - issues operationId: issues/list-comments externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/issues#list-issue-comments parameters: - "$ref": "#/components/parameters/owner" - "$ref": "#/components/parameters/repo" - "$ref": "#/components/parameters/issue-number" - "$ref": "#/components/parameters/since" - "$ref": "#/components/parameters/per-page" - "$ref": "#/components/parameters/page" responses: '200': description: Response content: application/json: schema: type: array items: "$ref": "#/components/schemas/issue-comment" examples: default: "$ref": "#/components/examples/issue-comment-items" headers: Link: "$ref": "#/components/headers/link" '404': "$ref": "#/components/responses/not_found" '410': "$ref": "#/components/responses/gone" x-github: githubCloudOnly: false enabledForGitHubApps: true category: issues subcategory: comments previews: - required: false name: squirrel-girl note: |- An additional `reactions` object in the issue comment payload is currently available for developers to preview. During the preview period, the APIs may change without advance notice. Please see the [blog post](https://developer.github.com/changes/2016-05-12-reactions-api-preview) for full details. To access the API you must provide a custom [media type](https://docs.github.com/enterprise-server@3.0/rest/overview/media-types) in the `Accept` header: ```shell application/vnd.github.squirrel-girl-preview ``` The `reactions` key will have the following payload where `url` can be used to construct the API location for [listing and creating](https://docs.github.com/enterprise-server@3.0/rest/reference/reactions) reactions. post: summary: Create an issue comment description: This endpoint triggers [notifications](https://docs.github.com/enterprise-server@3.0/github/managing-subscriptions-and-notifications-on-github/about-notifications). Creating content too quickly using this endpoint may result in secondary rate limiting. See "[Secondary rate limits](https://docs.github.com/enterprise-server@3.0/rest/overview/resources-in-the-rest-api#secondary-rate-limits)" and "[Dealing with secondary rate limits](https://docs.github.com/enterprise-server@3.0/rest/guides/best-practices-for-integrators#dealing-with-secondary-rate-limits)" for details. tags: - issues operationId: issues/create-comment externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/issues#create-an-issue-comment parameters: - "$ref": "#/components/parameters/owner" - "$ref": "#/components/parameters/repo" - "$ref": "#/components/parameters/issue-number" requestBody: required: true content: application/json: schema: type: object properties: body: type: string description: The contents of the comment. required: - body example: body: Me too responses: '201': description: Response content: application/json: schema: "$ref": "#/components/schemas/issue-comment" examples: default: "$ref": "#/components/examples/issue-comment" headers: Location: example: https://api.github.com/repos/octocat/Hello-World/issues/comments/1 schema: type: string '403': "$ref": "#/components/responses/forbidden" '410': "$ref": "#/components/responses/gone" '422': "$ref": "#/components/responses/validation_failed" '404': "$ref": "#/components/responses/not_found" x-github: triggersNotification: true githubCloudOnly: false enabledForGitHubApps: true category: issues subcategory: comments "/repos/{owner}/{repo}/issues/{issue_number}/events": get: summary: List issue events description: '' tags: - issues operationId: issues/list-events externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/issues#list-issue-events parameters: - "$ref": "#/components/parameters/owner" - "$ref": "#/components/parameters/repo" - "$ref": "#/components/parameters/issue-number" - "$ref": "#/components/parameters/per-page" - "$ref": "#/components/parameters/page" responses: '200': description: Response content: application/json: schema: type: array items: "$ref": "#/components/schemas/issue-event-for-issue" examples: default: "$ref": "#/components/examples/issue-event-for-issue-items" headers: Link: "$ref": "#/components/headers/link" '410': "$ref": "#/components/responses/gone" x-github: githubCloudOnly: false enabledForGitHubApps: true category: issues subcategory: events previews: - required: false name: starfox note: |- Project card details are now shown in REST API v3 responses for project-related issue and timeline events. This feature is now available for developers to preview. For details, see the [blog post](https://developer.github.com/changes/2018-09-05-project-card-events). To receive the `project_card` attribute, project boards must be [enabled](https://docs.github.com/articles/disabling-project-boards-in-a-repository) for a repository, and you must provide a custom [media type](https://docs.github.com/enterprise-server@3.0/rest/overview/media-types) in the `Accept` header: ```shell application/vnd.github.starfox-preview+json ``` "/repos/{owner}/{repo}/issues/{issue_number}/labels": get: summary: List labels for an issue description: '' tags: - issues operationId: issues/list-labels-on-issue externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/issues#list-labels-for-an-issue parameters: - "$ref": "#/components/parameters/owner" - "$ref": "#/components/parameters/repo" - "$ref": "#/components/parameters/issue-number" - "$ref": "#/components/parameters/per-page" - "$ref": "#/components/parameters/page" responses: '200': description: Response content: application/json: schema: type: array items: "$ref": "#/components/schemas/label" examples: default: "$ref": "#/components/examples/label-items" headers: Link: "$ref": "#/components/headers/link" '410': "$ref": "#/components/responses/gone" x-github: githubCloudOnly: false enabledForGitHubApps: true category: issues subcategory: labels post: summary: Add labels to an issue description: '' tags: - issues operationId: issues/add-labels externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/issues#add-labels-to-an-issue parameters: - "$ref": "#/components/parameters/owner" - "$ref": "#/components/parameters/repo" - "$ref": "#/components/parameters/issue-number" requestBody: required: false content: application/json: schema: oneOf: - type: object properties: labels: type: array minItems: 1 description: The names of the labels to add to the issue's existing labels. You can pass an empty array to remove all labels. Alternatively, you can pass a single label as a `string` or an `array` of labels directly, but GitHub recommends passing an object with the `labels` key. You can also replace all of the labels for an issue. For more information, see "[Set labels for an issue](https://docs.github.com/enterprise-server@3.0/rest/reference/issues#set-labels-for-an-issue)." items: type: string - type: array minItems: 1 items: type: string - type: object properties: labels: type: array minItems: 1 items: type: object properties: name: type: string required: - name - type: array minItems: 1 items: type: object properties: name: type: string required: - name - type: string example: labels: - bug - enhancement responses: '200': description: Response content: application/json: schema: type: array items: "$ref": "#/components/schemas/label" examples: default: "$ref": "#/components/examples/label-items" '410': "$ref": "#/components/responses/gone" '422': "$ref": "#/components/responses/validation_failed" x-github: githubCloudOnly: false enabledForGitHubApps: true category: issues subcategory: labels put: summary: Set labels for an issue description: Removes any previous labels and sets the new labels for an issue. tags: - issues operationId: issues/set-labels externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/issues#set-labels-for-an-issue parameters: - "$ref": "#/components/parameters/owner" - "$ref": "#/components/parameters/repo" - "$ref": "#/components/parameters/issue-number" requestBody: required: false content: application/json: schema: oneOf: - type: object properties: labels: type: array minItems: 1 description: The names of the labels to set for the issue. The labels you set replace any existing labels. You can pass an empty array to remove all labels. Alternatively, you can pass a single label as a `string` or an `array` of labels directly, but GitHub recommends passing an object with the `labels` key. You can also add labels to the existing labels for an issue. For more information, see "[Add labels to an issue](https://docs.github.com/enterprise-server@3.0/rest/reference/issues#add-labels-to-an-issue)." items: type: string - type: array minItems: 1 items: type: string - type: object properties: labels: type: array minItems: 1 items: type: object properties: name: type: string required: - name - type: array minItems: 1 items: type: object properties: name: type: string required: - name - type: string example: labels: - bug - enhancement responses: '200': description: Response content: application/json: schema: type: array items: "$ref": "#/components/schemas/label" examples: default: "$ref": "#/components/examples/label-items" '410': "$ref": "#/components/responses/gone" '422': "$ref": "#/components/responses/validation_failed" x-github: githubCloudOnly: false enabledForGitHubApps: true category: issues subcategory: labels delete: summary: Remove all labels from an issue description: '' tags: - issues operationId: issues/remove-all-labels externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/issues#remove-all-labels-from-an-issue parameters: - "$ref": "#/components/parameters/owner" - "$ref": "#/components/parameters/repo" - "$ref": "#/components/parameters/issue-number" responses: '204': description: Response '410': "$ref": "#/components/responses/gone" x-github: githubCloudOnly: false enabledForGitHubApps: true category: issues subcategory: labels "/repos/{owner}/{repo}/issues/{issue_number}/labels/{name}": delete: summary: Remove a label from an issue description: Removes the specified label from the issue, and returns the remaining labels on the issue. This endpoint returns a `404 Not Found` status if the label does not exist. tags: - issues operationId: issues/remove-label externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/issues#remove-a-label-from-an-issue parameters: - "$ref": "#/components/parameters/owner" - "$ref": "#/components/parameters/repo" - "$ref": "#/components/parameters/issue-number" - name: name in: path required: true schema: type: string responses: '200': description: Response content: application/json: schema: type: array items: "$ref": "#/components/schemas/label" examples: default: "$ref": "#/components/examples/label-items-2" '404': "$ref": "#/components/responses/not_found" '410': "$ref": "#/components/responses/gone" x-github: githubCloudOnly: false enabledForGitHubApps: true category: issues subcategory: labels "/repos/{owner}/{repo}/issues/{issue_number}/lock": put: summary: Lock an issue description: |- Users with push access can lock an issue or pull request's conversation. Note that, if you choose not to pass any parameters, you'll need to set `Content-Length` to zero when calling out to this endpoint. For more information, see "[HTTP verbs](https://docs.github.com/enterprise-server@3.0/rest/overview/resources-in-the-rest-api#http-verbs)." tags: - issues operationId: issues/lock externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/issues#lock-an-issue parameters: - "$ref": "#/components/parameters/owner" - "$ref": "#/components/parameters/repo" - "$ref": "#/components/parameters/issue-number" requestBody: required: false content: application/json: schema: type: - object - 'null' properties: lock_reason: type: string description: "The reason for locking the issue or pull request conversation. Lock will fail if you don't use one of these reasons: \n\\* `off-topic` \ \n\\* `too heated` \n\\* `resolved` \n\\* `spam`" enum: - off-topic - too heated - resolved - spam responses: '204': description: Response '403': "$ref": "#/components/responses/forbidden" '410': "$ref": "#/components/responses/gone" '404': "$ref": "#/components/responses/not_found" '422': "$ref": "#/components/responses/validation_failed" x-github: githubCloudOnly: false enabledForGitHubApps: true category: issues subcategory: delete: summary: Unlock an issue description: Users with push access can unlock an issue's conversation. tags: - issues operationId: issues/unlock externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/issues#unlock-an-issue parameters: - "$ref": "#/components/parameters/owner" - "$ref": "#/components/parameters/repo" - "$ref": "#/components/parameters/issue-number" responses: '204': description: Response '403': "$ref": "#/components/responses/forbidden" '404': "$ref": "#/components/responses/not_found" x-github: githubCloudOnly: false enabledForGitHubApps: true category: issues subcategory: "/repos/{owner}/{repo}/issues/{issue_number}/reactions": get: summary: List reactions for an issue description: List the reactions to an [issue](https://docs.github.com/enterprise-server@3.0/rest/reference/issues). tags: - reactions operationId: reactions/list-for-issue externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/reactions#list-reactions-for-an-issue parameters: - "$ref": "#/components/parameters/owner" - "$ref": "#/components/parameters/repo" - "$ref": "#/components/parameters/issue-number" - name: content description: Returns a single [reaction type](https://docs.github.com/enterprise-server@3.0/rest/reference/reactions#reaction-types). Omit this parameter to list all reactions to an issue. in: query required: false schema: type: string enum: - "+1" - "-1" - laugh - confused - heart - hooray - rocket - eyes - "$ref": "#/components/parameters/per-page" - "$ref": "#/components/parameters/page" responses: '200': description: Response content: application/json: schema: type: array items: "$ref": "#/components/schemas/reaction" examples: default: "$ref": "#/components/examples/reaction-items" headers: Link: "$ref": "#/components/headers/link" '404': "$ref": "#/components/responses/not_found" '410': "$ref": "#/components/responses/gone" x-github: githubCloudOnly: false enabledForGitHubApps: true category: reactions previews: - required: true name: squirrel-girl note: |- An additional `reactions` object in the issue comment payload is currently available for developers to preview. During the preview period, the APIs may change without advance notice. Please see the [blog post](https://developer.github.com/changes/2016-05-12-reactions-api-preview) for full details. To access the API you must provide a custom [media type](https://docs.github.com/enterprise-server@3.0/rest/overview/media-types) in the `Accept` header: ```shell application/vnd.github.squirrel-girl-preview ``` The `reactions` key will have the following payload where `url` can be used to construct the API location for [listing and creating](https://docs.github.com/enterprise-server@3.0/rest/reference/reactions) reactions. post: summary: Create reaction for an issue description: Create a reaction to an [issue](https://docs.github.com/enterprise-server@3.0/rest/reference/issues/). A response with an HTTP `200` status means that you already added the reaction type to this issue. tags: - reactions operationId: reactions/create-for-issue externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/reactions#create-reaction-for-an-issue parameters: - "$ref": "#/components/parameters/owner" - "$ref": "#/components/parameters/repo" - "$ref": "#/components/parameters/issue-number" requestBody: required: true content: application/json: schema: type: object properties: content: type: string description: The [reaction type](https://docs.github.com/enterprise-server@3.0/rest/reference/reactions#reaction-types) to add to the issue. enum: - "+1" - "-1" - laugh - confused - heart - hooray - rocket - eyes required: - content example: content: heart responses: '200': description: Response content: application/json: schema: "$ref": "#/components/schemas/reaction" examples: default: "$ref": "#/components/examples/reaction" '201': description: Response content: application/json: schema: "$ref": "#/components/schemas/reaction" examples: default: "$ref": "#/components/examples/reaction" '422': "$ref": "#/components/responses/validation_failed" x-github: githubCloudOnly: false enabledForGitHubApps: false category: reactions previews: - required: true name: squirrel-girl note: |- An additional `reactions` object in the issue comment payload is currently available for developers to preview. During the preview period, the APIs may change without advance notice. Please see the [blog post](https://developer.github.com/changes/2016-05-12-reactions-api-preview) for full details. To access the API you must provide a custom [media type](https://docs.github.com/enterprise-server@3.0/rest/overview/media-types) in the `Accept` header: ```shell application/vnd.github.squirrel-girl-preview ``` The `reactions` key will have the following payload where `url` can be used to construct the API location for [listing and creating](https://docs.github.com/enterprise-server@3.0/rest/reference/reactions) reactions. "/repos/{owner}/{repo}/issues/{issue_number}/reactions/{reaction_id}": delete: summary: Delete an issue reaction description: |- **Note:** You can also specify a repository by `repository_id` using the route `DELETE /repositories/:repository_id/issues/:issue_number/reactions/:reaction_id`. Delete a reaction to an [issue](https://docs.github.com/enterprise-server@3.0/rest/reference/issues/). tags: - reactions operationId: reactions/delete-for-issue externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/reactions#delete-an-issue-reaction parameters: - "$ref": "#/components/parameters/owner" - "$ref": "#/components/parameters/repo" - "$ref": "#/components/parameters/issue-number" - "$ref": "#/components/parameters/reaction-id" responses: '204': description: Response x-github: githubCloudOnly: false enabledForGitHubApps: true category: reactions previews: - required: true name: squirrel-girl note: |- An additional `reactions` object in the issue comment payload is currently available for developers to preview. During the preview period, the APIs may change without advance notice. Please see the [blog post](https://developer.github.com/changes/2016-05-12-reactions-api-preview) for full details. To access the API you must provide a custom [media type](https://docs.github.com/enterprise-server@3.0/rest/overview/media-types) in the `Accept` header: ```shell application/vnd.github.squirrel-girl-preview ``` The `reactions` key will have the following payload where `url` can be used to construct the API location for [listing and creating](https://docs.github.com/enterprise-server@3.0/rest/reference/reactions) reactions. "/repos/{owner}/{repo}/issues/{issue_number}/timeline": get: summary: List timeline events for an issue description: '' tags: - issues operationId: issues/list-events-for-timeline externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/issues#list-timeline-events-for-an-issue parameters: - "$ref": "#/components/parameters/owner" - "$ref": "#/components/parameters/repo" - "$ref": "#/components/parameters/issue-number" - "$ref": "#/components/parameters/per-page" - "$ref": "#/components/parameters/page" responses: '200': description: Response content: application/json: schema: type: array items: "$ref": "#/components/schemas/timeline-issue-events" headers: Link: "$ref": "#/components/headers/link" '404': "$ref": "#/components/responses/not_found" '410': "$ref": "#/components/responses/gone" x-github: githubCloudOnly: false enabledForGitHubApps: true category: issues subcategory: timeline previews: - required: true name: mockingbird note: |- The API to get issue timeline events is currently available for developers to preview. During the preview period, the APIs may change without advance notice. Please see the [blog post](https://developer.github.com/changes/2016-05-23-timeline-preview-api/) for full details. To access the API you must provide a custom [media type](https://docs.github.com/enterprise-server@3.0/rest/overview/media-types) in the `Accept` header: ```shell application/vnd.github.mockingbird-preview ``` - required: false name: starfox note: |- Project card details are now shown in REST API v3 responses for project-related issue and timeline events. This feature is now available for developers to preview. For details, see the [blog post](https://developer.github.com/changes/2018-09-05-project-card-events). To receive the `project_card` attribute, project boards must be [enabled](https://docs.github.com/articles/disabling-project-boards-in-a-repository) for a repository, and you must provide a custom [media type](https://docs.github.com/enterprise-server@3.0/rest/overview/media-types) in the `Accept` header: ```shell application/vnd.github.starfox-preview+json ``` "/repos/{owner}/{repo}/keys": get: summary: List deploy keys description: '' tags: - repos operationId: repos/list-deploy-keys externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/repos#list-deploy-keys parameters: - "$ref": "#/components/parameters/owner" - "$ref": "#/components/parameters/repo" - "$ref": "#/components/parameters/per-page" - "$ref": "#/components/parameters/page" responses: '200': description: Response content: application/json: schema: type: array items: "$ref": "#/components/schemas/deploy-key" examples: default: "$ref": "#/components/examples/deploy-key-items" headers: Link: "$ref": "#/components/headers/link" x-github: githubCloudOnly: false enabledForGitHubApps: true category: repos subcategory: keys post: summary: Create a deploy key description: You can create a read-only deploy key. tags: - repos operationId: repos/create-deploy-key externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/repos#create-a-deploy-key parameters: - "$ref": "#/components/parameters/owner" - "$ref": "#/components/parameters/repo" requestBody: required: true content: application/json: schema: type: object properties: title: type: string description: A name for the key. key: type: string description: The contents of the key. read_only: type: boolean description: "If `true`, the key will only be able to read repository contents. Otherwise, the key will be able to read and write. \n \ \nDeploy keys with write access can perform the same actions as an organization member with admin access, or a collaborator on a personal repository. For more information, see \"[Repository permission levels for an organization](https://docs.github.com/articles/repository-permission-levels-for-an-organization/)\" and \"[Permission levels for a user account repository](https://docs.github.com/articles/permission-levels-for-a-user-account-repository/).\"" required: - key example: title: octocat@octomac key: ssh-rsa AAA... read_only: true responses: '201': description: Response content: application/json: schema: "$ref": "#/components/schemas/deploy-key" examples: default: "$ref": "#/components/examples/deploy-key" headers: Location: example: https://api.github.com/repos/octocat/Hello-World/keys/1 schema: type: string '422': "$ref": "#/components/responses/validation_failed" x-github: githubCloudOnly: false enabledForGitHubApps: true category: repos subcategory: keys "/repos/{owner}/{repo}/keys/{key_id}": get: summary: Get a deploy key description: '' tags: - repos operationId: repos/get-deploy-key externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/repos#get-a-deploy-key parameters: - "$ref": "#/components/parameters/owner" - "$ref": "#/components/parameters/repo" - "$ref": "#/components/parameters/key-id" responses: '200': description: Response content: application/json: schema: "$ref": "#/components/schemas/deploy-key" examples: default: "$ref": "#/components/examples/deploy-key" '404': "$ref": "#/components/responses/not_found" x-github: githubCloudOnly: false enabledForGitHubApps: true category: repos subcategory: keys delete: summary: Delete a deploy key description: Deploy keys are immutable. If you need to update a key, remove the key and create a new one instead. tags: - repos operationId: repos/delete-deploy-key externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/repos#delete-a-deploy-key parameters: - "$ref": "#/components/parameters/owner" - "$ref": "#/components/parameters/repo" - "$ref": "#/components/parameters/key-id" responses: '204': description: Response x-github: githubCloudOnly: false enabledForGitHubApps: true category: repos subcategory: keys "/repos/{owner}/{repo}/labels": get: summary: List labels for a repository description: '' tags: - issues operationId: issues/list-labels-for-repo externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/issues#list-labels-for-a-repository parameters: - "$ref": "#/components/parameters/owner" - "$ref": "#/components/parameters/repo" - "$ref": "#/components/parameters/per-page" - "$ref": "#/components/parameters/page" responses: '200': description: Response content: application/json: schema: type: array items: "$ref": "#/components/schemas/label" examples: default: "$ref": "#/components/examples/label-items" headers: Link: "$ref": "#/components/headers/link" '404': "$ref": "#/components/responses/not_found" x-github: githubCloudOnly: false enabledForGitHubApps: true category: issues subcategory: labels post: summary: Create a label description: '' tags: - issues operationId: issues/create-label externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/issues#create-a-label parameters: - "$ref": "#/components/parameters/owner" - "$ref": "#/components/parameters/repo" requestBody: required: true content: application/json: schema: type: object properties: name: type: string description: The name of the label. Emoji can be added to label names, using either native emoji or colon-style markup. For example, typing `:strawberry:` will render the emoji ![:strawberry:](https://github.githubassets.com/images/icons/emoji/unicode/1f353.png ":strawberry:"). For a full list of available emoji and codes, see "[Emoji cheat sheet](https://github.com/ikatyang/emoji-cheat-sheet)." color: type: string description: The [hexadecimal color code](http://www.color-hex.com/) for the label, without the leading `#`. description: type: string description: A short description of the label. Must be 100 characters or fewer. required: - name example: name: bug description: Something isn't working color: f29513 responses: '201': description: Response content: application/json: schema: "$ref": "#/components/schemas/label" examples: default: "$ref": "#/components/examples/label" headers: Location: example: https://api.github.com/repos/octocat/Hello-World/labels/bug schema: type: string '422': "$ref": "#/components/responses/validation_failed" '404': "$ref": "#/components/responses/not_found" x-github: githubCloudOnly: false enabledForGitHubApps: true category: issues subcategory: labels "/repos/{owner}/{repo}/labels/{name}": get: summary: Get a label description: '' tags: - issues operationId: issues/get-label externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/issues#get-a-label parameters: - "$ref": "#/components/parameters/owner" - "$ref": "#/components/parameters/repo" - name: name in: path required: true schema: type: string responses: '200': description: Response content: application/json: schema: "$ref": "#/components/schemas/label" examples: default: "$ref": "#/components/examples/label" '404': "$ref": "#/components/responses/not_found" x-github: githubCloudOnly: false enabledForGitHubApps: true category: issues subcategory: labels patch: summary: Update a label description: '' tags: - issues operationId: issues/update-label externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/issues#update-a-label parameters: - "$ref": "#/components/parameters/owner" - "$ref": "#/components/parameters/repo" - name: name in: path required: true schema: type: string requestBody: required: false content: application/json: schema: type: object properties: new_name: type: string description: The new name of the label. Emoji can be added to label names, using either native emoji or colon-style markup. For example, typing `:strawberry:` will render the emoji ![:strawberry:](https://github.githubassets.com/images/icons/emoji/unicode/1f353.png ":strawberry:"). For a full list of available emoji and codes, see "[Emoji cheat sheet](https://github.com/ikatyang/emoji-cheat-sheet)." color: type: string description: The [hexadecimal color code](http://www.color-hex.com/) for the label, without the leading `#`. description: type: string description: A short description of the label. Must be 100 characters or fewer. example: new_name: 'bug :bug:' description: Small bug fix required color: b01f26 responses: '200': description: Response content: application/json: schema: "$ref": "#/components/schemas/label" examples: default: "$ref": "#/components/examples/label-2" x-github: githubCloudOnly: false enabledForGitHubApps: true category: issues subcategory: labels delete: summary: Delete a label description: '' tags: - issues operationId: issues/delete-label externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/issues#delete-a-label parameters: - "$ref": "#/components/parameters/owner" - "$ref": "#/components/parameters/repo" - name: name in: path required: true schema: type: string responses: '204': description: Response x-github: githubCloudOnly: false enabledForGitHubApps: true category: issues subcategory: labels "/repos/{owner}/{repo}/languages": get: summary: List repository languages description: Lists languages for the specified repository. The value shown for each language is the number of bytes of code written in that language. tags: - repos operationId: repos/list-languages externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/repos#list-repository-languages parameters: - "$ref": "#/components/parameters/owner" - "$ref": "#/components/parameters/repo" responses: '200': description: Response content: application/json: schema: "$ref": "#/components/schemas/language" examples: default: "$ref": "#/components/examples/language" x-github: githubCloudOnly: false enabledForGitHubApps: true category: repos subcategory: "/repos/{owner}/{repo}/license": get: summary: Get the license for a repository description: |- This method returns the contents of the repository's license file, if one is detected. Similar to [Get repository content](https://docs.github.com/enterprise-server@3.0/rest/reference/repos#get-repository-content), this method also supports [custom media types](https://docs.github.com/enterprise-server@3.0/rest/overview/media-types) for retrieving the raw license content or rendered license HTML. tags: - licenses operationId: licenses/get-for-repo externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/licenses/#get-the-license-for-a-repository parameters: - "$ref": "#/components/parameters/owner" - "$ref": "#/components/parameters/repo" responses: '200': description: Response content: application/json: schema: "$ref": "#/components/schemas/license-content" examples: default: "$ref": "#/components/examples/license-content" x-github: githubCloudOnly: false enabledForGitHubApps: true category: licenses subcategory: "/repos/{owner}/{repo}/merges": post: summary: Merge a branch description: '' tags: - repos operationId: repos/merge externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/repos#merge-a-branch parameters: - "$ref": "#/components/parameters/owner" - "$ref": "#/components/parameters/repo" requestBody: required: true content: application/json: schema: type: object properties: base: type: string description: The name of the base branch that the head will be merged into. head: type: string description: The head to merge. This can be a branch name or a commit SHA1. commit_message: type: string description: Commit message to use for the merge commit. If omitted, a default message will be used. required: - base - head example: base: master head: cool_feature commit_message: Shipped cool_feature! responses: '201': description: Successful Response (The resulting merge commit) content: application/json: schema: "$ref": "#/components/schemas/commit" examples: default: "$ref": "#/components/examples/commit" '204': description: Response when already merged '404': description: Not Found when the base or head does not exist '409': description: Conflict when there is a merge conflict '403': "$ref": "#/components/responses/forbidden" '422': "$ref": "#/components/responses/validation_failed" x-github: githubCloudOnly: false enabledForGitHubApps: true category: repos subcategory: merging "/repos/{owner}/{repo}/milestones": get: summary: List milestones description: '' tags: - issues operationId: issues/list-milestones externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/issues#list-milestones parameters: - "$ref": "#/components/parameters/owner" - "$ref": "#/components/parameters/repo" - name: state description: The state of the milestone. Either `open`, `closed`, or `all`. in: query required: false schema: type: string enum: - open - closed - all default: open - name: sort description: What to sort results by. Either `due_on` or `completeness`. in: query required: false schema: type: string enum: - due_on - completeness default: due_on - name: direction description: The direction of the sort. Either `asc` or `desc`. in: query required: false schema: type: string enum: - asc - desc default: asc - "$ref": "#/components/parameters/per-page" - "$ref": "#/components/parameters/page" responses: '200': description: Response content: application/json: schema: type: array items: "$ref": "#/components/schemas/milestone" examples: default: "$ref": "#/components/examples/milestone-items" headers: Link: "$ref": "#/components/headers/link" '404': "$ref": "#/components/responses/not_found" x-github: githubCloudOnly: false enabledForGitHubApps: true category: issues subcategory: milestones post: summary: Create a milestone description: '' tags: - issues operationId: issues/create-milestone externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/issues#create-a-milestone parameters: - "$ref": "#/components/parameters/owner" - "$ref": "#/components/parameters/repo" requestBody: required: true content: application/json: schema: type: object properties: title: type: string description: The title of the milestone. state: type: string description: The state of the milestone. Either `open` or `closed`. enum: - open - closed default: open description: type: string description: A description of the milestone. due_on: type: string format: date-time description: 'The milestone due date. This is a timestamp in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format: `YYYY-MM-DDTHH:MM:SSZ`.' required: - title example: title: v1.0 state: open description: Tracking milestone for version 1.0 due_on: '2012-10-09T23:39:01Z' responses: '201': description: Response content: application/json: schema: "$ref": "#/components/schemas/milestone" examples: default: "$ref": "#/components/examples/milestone" headers: Location: example: https://api.github.com/repos/octocat/Hello-World/milestones/1 schema: type: string '404': "$ref": "#/components/responses/not_found" '422': "$ref": "#/components/responses/validation_failed" x-github: githubCloudOnly: false enabledForGitHubApps: true category: issues subcategory: milestones "/repos/{owner}/{repo}/milestones/{milestone_number}": get: summary: Get a milestone description: '' tags: - issues operationId: issues/get-milestone externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/issues#get-a-milestone parameters: - "$ref": "#/components/parameters/owner" - "$ref": "#/components/parameters/repo" - "$ref": "#/components/parameters/milestone-number" responses: '200': description: Response content: application/json: schema: "$ref": "#/components/schemas/milestone" examples: default: "$ref": "#/components/examples/milestone" '404': "$ref": "#/components/responses/not_found" x-github: githubCloudOnly: false enabledForGitHubApps: true category: issues subcategory: milestones patch: summary: Update a milestone description: '' tags: - issues operationId: issues/update-milestone externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/issues#update-a-milestone parameters: - "$ref": "#/components/parameters/owner" - "$ref": "#/components/parameters/repo" - "$ref": "#/components/parameters/milestone-number" requestBody: required: false content: application/json: schema: type: object properties: title: type: string description: The title of the milestone. state: type: string description: The state of the milestone. Either `open` or `closed`. enum: - open - closed default: open description: type: string description: A description of the milestone. due_on: type: string format: date-time description: 'The milestone due date. This is a timestamp in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format: `YYYY-MM-DDTHH:MM:SSZ`.' example: title: v1.0 state: open description: Tracking milestone for version 1.0 due_on: '2012-10-09T23:39:01Z' responses: '200': description: Response content: application/json: schema: "$ref": "#/components/schemas/milestone" examples: default: "$ref": "#/components/examples/milestone" x-github: githubCloudOnly: false enabledForGitHubApps: true category: issues subcategory: milestones delete: summary: Delete a milestone description: '' tags: - issues operationId: issues/delete-milestone externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/issues#delete-a-milestone parameters: - "$ref": "#/components/parameters/owner" - "$ref": "#/components/parameters/repo" - "$ref": "#/components/parameters/milestone-number" responses: '204': description: Response '404': "$ref": "#/components/responses/not_found" x-github: githubCloudOnly: false enabledForGitHubApps: true category: issues subcategory: milestones "/repos/{owner}/{repo}/milestones/{milestone_number}/labels": get: summary: List labels for issues in a milestone description: '' tags: - issues operationId: issues/list-labels-for-milestone externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/issues#list-labels-for-issues-in-a-milestone parameters: - "$ref": "#/components/parameters/owner" - "$ref": "#/components/parameters/repo" - "$ref": "#/components/parameters/milestone-number" - "$ref": "#/components/parameters/per-page" - "$ref": "#/components/parameters/page" responses: '200': description: Response content: application/json: schema: type: array items: "$ref": "#/components/schemas/label" examples: default: "$ref": "#/components/examples/label-items" headers: Link: "$ref": "#/components/headers/link" x-github: githubCloudOnly: false enabledForGitHubApps: true category: issues subcategory: labels "/repos/{owner}/{repo}/notifications": get: summary: List repository notifications for the authenticated user description: List all notifications for the current user. tags: - activity operationId: activity/list-repo-notifications-for-authenticated-user externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/activity#list-repository-notifications-for-the-authenticated-user parameters: - "$ref": "#/components/parameters/owner" - "$ref": "#/components/parameters/repo" - "$ref": "#/components/parameters/all" - "$ref": "#/components/parameters/participating" - "$ref": "#/components/parameters/since" - "$ref": "#/components/parameters/before" - "$ref": "#/components/parameters/per-page" - "$ref": "#/components/parameters/page" responses: '200': description: Response content: application/json: schema: type: array items: "$ref": "#/components/schemas/thread" examples: default: "$ref": "#/components/examples/thread-items" headers: Link: "$ref": "#/components/headers/link" x-github: githubCloudOnly: false enabledForGitHubApps: false category: activity subcategory: notifications put: summary: Mark repository notifications as read description: Marks all notifications in a repository as "read" removes them from the [default view on GitHub Enterprise Server](https://github.com/notifications). If the number of notifications is too large to complete in one request, you will receive a `202 Accepted` status and GitHub Enterprise Server will run an asynchronous process to mark notifications as "read." To check whether any "unread" notifications remain, you can use the [List repository notifications for the authenticated user](https://docs.github.com/enterprise-server@3.0/rest/reference/activity#list-repository-notifications-for-the-authenticated-user) endpoint and pass the query parameter `all=false`. tags: - activity operationId: activity/mark-repo-notifications-as-read externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/activity#mark-repository-notifications-as-read parameters: - "$ref": "#/components/parameters/owner" - "$ref": "#/components/parameters/repo" requestBody: required: false content: application/json: schema: type: object properties: last_read_at: type: string format: date-time description: 'Describes the last point that notifications were checked. Anything updated since this time will not be marked as read. If you omit this parameter, all notifications are marked as read. This is a timestamp in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format: `YYYY-MM-DDTHH:MM:SSZ`. Default: The current timestamp.' responses: '202': description: Response content: application/json: schema: type: object properties: message: type: string url: type: string '205': description: Reset Content x-github: githubCloudOnly: false enabledForGitHubApps: false category: activity subcategory: notifications "/repos/{owner}/{repo}/pages": get: summary: Get a GitHub Enterprise Server Pages site description: '' tags: - repos operationId: repos/get-pages externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/repos#get-a-github-pages-site parameters: - "$ref": "#/components/parameters/owner" - "$ref": "#/components/parameters/repo" responses: '200': description: Response content: application/json: schema: "$ref": "#/components/schemas/page" examples: default: "$ref": "#/components/examples/page" '404': "$ref": "#/components/responses/not_found" x-github: githubCloudOnly: false enabledForGitHubApps: true category: repos subcategory: pages post: summary: Create a GitHub Enterprise Server Pages site description: Configures a GitHub Enterprise Server Pages site. For more information, see "[About GitHub Pages](/github/working-with-github-pages/about-github-pages)." tags: - repos operationId: repos/create-pages-site externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/repos#create-a-github-pages-site parameters: - "$ref": "#/components/parameters/owner" - "$ref": "#/components/parameters/repo" requestBody: required: true content: application/json: schema: type: - object - 'null' description: The source branch and directory used to publish your Pages site. properties: source: type: object description: The source branch and directory used to publish your Pages site. properties: branch: type: string description: The repository branch used to publish your site's source files. path: type: string description: 'The repository directory that includes the source files for the Pages site. Allowed paths are `/` or `/docs`. Default: `/`' enum: - "/" - "/docs" default: "/" required: - branch required: - source example: source: branch: main path: "/docs" responses: '201': description: Response content: application/json: schema: "$ref": "#/components/schemas/page" examples: default: "$ref": "#/components/examples/page" '422': "$ref": "#/components/responses/validation_failed" '409': "$ref": "#/components/responses/conflict" x-github: githubCloudOnly: false enabledForGitHubApps: true category: repos subcategory: pages previews: - required: true name: switcheroo note: |- Enabling and disabling Pages in the Pages API is currently available for developers to preview. See the [blog post](https://developer.github.com/changes/2019-03-14-enabling-disabling-pages/) preview for more details. To access the new endpoints during the preview period, you must provide a custom [media type](https://docs.github.com/enterprise-server@3.0/rest/overview/media-types) in the `Accept` header: ```shell application/vnd.github.switcheroo-preview+json ``` put: summary: Update information about a GitHub Enterprise Server Pages site description: Updates information for a GitHub Enterprise Server Pages site. For more information, see "[About GitHub Pages](/github/working-with-github-pages/about-github-pages). tags: - repos operationId: repos/update-information-about-pages-site externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/repos#update-information-about-a-github-pages-site parameters: - "$ref": "#/components/parameters/owner" - "$ref": "#/components/parameters/repo" requestBody: required: true content: application/json: schema: type: object properties: cname: type: - string - 'null' description: Specify a custom domain for the repository. Sending a `null` value will remove the custom domain. For more about custom domains, see "[Using a custom domain with GitHub Pages](https://docs.github.com/articles/using-a-custom-domain-with-github-pages/)." https_enforced: type: boolean description: Specify whether HTTPS should be enforced for the repository. public: type: boolean description: Configures access controls for the GitHub Pages site. If public is set to `true`, the site is accessible to anyone on the internet. If set to `false`, the site will only be accessible to users who have at least `read` access to the repository that published the site. This includes anyone in your Enterprise if the repository is set to `internal` visibility. This feature is only available to repositories in an organization on an Enterprise plan. source: anyOf: - type: string description: Update the source for the repository. Must include the branch name, and may optionally specify the subdirectory `/docs`. Possible values are `"gh-pages"`, `"master"`, and `"master /docs"`. enum: - gh-pages - master - master /docs - type: object description: Update the source for the repository. Must include the branch name and path. properties: branch: type: string description: The repository branch used to publish your site's source files. path: type: string description: The repository directory that includes the source files for the Pages site. Allowed paths are `/` or `/docs`. enum: - "/" - "/docs" required: - branch - path anyOf: - required: - source - required: - cname - required: - public - required: - https_enforced example: cname: octocatblog.com source: branch: main path: "/" responses: '204': description: Response '422': "$ref": "#/components/responses/validation_failed" '400': "$ref": "#/components/responses/bad_request" x-github: githubCloudOnly: false enabledForGitHubApps: true category: repos subcategory: pages delete: summary: Delete a GitHub Enterprise Server Pages site description: '' tags: - repos operationId: repos/delete-pages-site externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/repos#delete-a-github-pages-site parameters: - "$ref": "#/components/parameters/owner" - "$ref": "#/components/parameters/repo" responses: '204': description: Response '422': "$ref": "#/components/responses/validation_failed" '404': "$ref": "#/components/responses/not_found" x-github: githubCloudOnly: false enabledForGitHubApps: true category: repos subcategory: pages previews: - required: true name: switcheroo note: |- Enabling and disabling Pages in the Pages API is currently available for developers to preview. See the [blog post](https://developer.github.com/changes/2019-03-14-enabling-disabling-pages/) preview for more details. To access the new endpoints during the preview period, you must provide a custom [media type](https://docs.github.com/enterprise-server@3.0/rest/overview/media-types) in the `Accept` header: ```shell application/vnd.github.switcheroo-preview+json ``` "/repos/{owner}/{repo}/pages/builds": get: summary: List GitHub Enterprise Server Pages builds description: '' tags: - repos operationId: repos/list-pages-builds externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/repos#list-github-pages-builds parameters: - "$ref": "#/components/parameters/owner" - "$ref": "#/components/parameters/repo" - "$ref": "#/components/parameters/per-page" - "$ref": "#/components/parameters/page" responses: '200': description: Response content: application/json: schema: type: array items: "$ref": "#/components/schemas/page-build" examples: default: "$ref": "#/components/examples/page-build-items" headers: Link: "$ref": "#/components/headers/link" x-github: githubCloudOnly: false enabledForGitHubApps: true category: repos subcategory: pages post: summary: Request a GitHub Enterprise Server Pages build description: |- You can request that your site be built from the latest revision on the default branch. This has the same effect as pushing a commit to your default branch, but does not require an additional commit. Manually triggering page builds can be helpful when diagnosing build warnings and failures. Build requests are limited to one concurrent build per repository and one concurrent build per requester. If you request a build while another is still in progress, the second request will be queued until the first completes. tags: - repos operationId: repos/request-pages-build externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/repos#request-a-github-pages-build parameters: - "$ref": "#/components/parameters/owner" - "$ref": "#/components/parameters/repo" responses: '201': description: Response content: application/json: schema: "$ref": "#/components/schemas/page-build-status" examples: default: "$ref": "#/components/examples/page-build-status" x-github: githubCloudOnly: false enabledForGitHubApps: true category: repos subcategory: pages "/repos/{owner}/{repo}/pages/builds/latest": get: summary: Get latest Pages build description: '' tags: - repos operationId: repos/get-latest-pages-build externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/repos#get-latest-pages-build parameters: - "$ref": "#/components/parameters/owner" - "$ref": "#/components/parameters/repo" responses: '200': description: Response content: application/json: schema: "$ref": "#/components/schemas/page-build" examples: default: "$ref": "#/components/examples/page-build" x-github: githubCloudOnly: false enabledForGitHubApps: true category: repos subcategory: pages "/repos/{owner}/{repo}/pages/builds/{build_id}": get: summary: Get GitHub Enterprise Server Pages build description: '' tags: - repos operationId: repos/get-pages-build externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/repos#get-github-pages-build parameters: - "$ref": "#/components/parameters/owner" - "$ref": "#/components/parameters/repo" - name: build_id in: path required: true schema: type: integer responses: '200': description: Response content: application/json: schema: "$ref": "#/components/schemas/page-build" examples: default: "$ref": "#/components/examples/page-build" x-github: githubCloudOnly: false enabledForGitHubApps: true category: repos subcategory: pages "/repos/{owner}/{repo}/pre-receive-hooks": get: summary: List pre-receive hooks for a repository description: List all pre-receive hooks that are enabled or testing for this repository as well as any disabled hooks that are allowed to be enabled at the repository level. Pre-receive hooks that are disabled at a higher level and are not configurable will not be listed. operationId: enterprise-admin/list-pre-receive-hooks-for-repo tags: - enterprise-admin externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/enterprise-admin#list-pre-receive-hooks-for-a-repository parameters: - "$ref": "#/components/parameters/owner" - "$ref": "#/components/parameters/repo" - "$ref": "#/components/parameters/per-page" - "$ref": "#/components/parameters/page" - "$ref": "#/components/parameters/direction" - name: sort in: query required: false schema: type: string enum: - created - updated - name default: created responses: '200': description: Response content: application/json: schema: type: array items: "$ref": "#/components/schemas/repository-pre-receive-hook" examples: default: "$ref": "#/components/examples/repository-pre-receive-hook-items" x-github: githubCloudOnly: false enabledForGitHubApps: true category: enterprise-admin subcategory: repo-pre-receive-hooks previews: - required: true name: eye-scream note: |- APIs for managing pre-receive hooks are currently available for developers to preview. During the preview period, the APIs may change without advance notice. To access the API you must provide a custom [media type](/rest/overview/media-types) in the `Accept` header: ```shell application/vnd.github.eye-scream-preview ``` "/repos/{owner}/{repo}/pre-receive-hooks/{pre_receive_hook_id}": get: summary: Get a pre-receive hook for a repository description: '' operationId: enterprise-admin/get-pre-receive-hook-for-repo tags: - enterprise-admin externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/enterprise-admin#get-a-pre-receive-hook-for-a-repository parameters: - "$ref": "#/components/parameters/owner" - "$ref": "#/components/parameters/repo" - "$ref": "#/components/parameters/pre-receive-hook-id" responses: '200': description: Response content: application/json: schema: "$ref": "#/components/schemas/repository-pre-receive-hook" examples: default: "$ref": "#/components/examples/repository-pre-receive-hook" x-github: githubCloudOnly: false enabledForGitHubApps: true category: enterprise-admin subcategory: repo-pre-receive-hooks previews: - required: true name: eye-scream note: |- APIs for managing pre-receive hooks are currently available for developers to preview. During the preview period, the APIs may change without advance notice. To access the API you must provide a custom [media type](/rest/overview/media-types) in the `Accept` header: ```shell application/vnd.github.eye-scream-preview ``` patch: summary: Update pre-receive hook enforcement for a repository description: For pre-receive hooks which are allowed to be configured at the repo level, you can set `enforcement` operationId: enterprise-admin/update-pre-receive-hook-enforcement-for-repo tags: - enterprise-admin externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/enterprise-admin#update-pre-receive-hook-enforcement-for-a-repository parameters: - "$ref": "#/components/parameters/owner" - "$ref": "#/components/parameters/repo" - "$ref": "#/components/parameters/pre-receive-hook-id" responses: '200': description: Response content: application/json: schema: "$ref": "#/components/schemas/repository-pre-receive-hook" examples: default: "$ref": "#/components/examples/repository-pre-receive-hook-2" requestBody: content: application/json: schema: type: object properties: enforcement: description: The state of enforcement for the hook on this repository. type: string enum: - enabled - disabled - testing example: enforcement: enabled x-github: githubCloudOnly: false enabledForGitHubApps: true category: enterprise-admin subcategory: repo-pre-receive-hooks previews: - required: true name: eye-scream note: |- APIs for managing pre-receive hooks are currently available for developers to preview. During the preview period, the APIs may change without advance notice. To access the API you must provide a custom [media type](/rest/overview/media-types) in the `Accept` header: ```shell application/vnd.github.eye-scream-preview ``` delete: summary: Remove pre-receive hook enforcement for a repository description: |- Deletes any overridden enforcement on this repository for the specified hook. Responds with effective values inherited from owner and/or global level. operationId: enterprise-admin/remove-pre-receive-hook-enforcement-for-repo tags: - enterprise-admin externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/enterprise-admin#remove-pre-receive-hook-enforcement-for-a-repository parameters: - "$ref": "#/components/parameters/owner" - "$ref": "#/components/parameters/repo" - "$ref": "#/components/parameters/pre-receive-hook-id" responses: '200': description: Responds with effective values inherited from owner and/or global level. content: application/json: schema: "$ref": "#/components/schemas/repository-pre-receive-hook" examples: default: "$ref": "#/components/examples/repository-pre-receive-hook" x-github: githubCloudOnly: false enabledForGitHubApps: true category: enterprise-admin subcategory: repo-pre-receive-hooks previews: - required: true name: eye-scream note: |- APIs for managing pre-receive hooks are currently available for developers to preview. During the preview period, the APIs may change without advance notice. To access the API you must provide a custom [media type](/rest/overview/media-types) in the `Accept` header: ```shell application/vnd.github.eye-scream-preview ``` "/repos/{owner}/{repo}/projects": get: summary: List repository projects description: Lists the projects in a repository. Returns a `404 Not Found` status if projects are disabled in the repository. If you do not have sufficient privileges to perform this action, a `401 Unauthorized` or `410 Gone` status is returned. tags: - projects operationId: projects/list-for-repo externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/projects#list-repository-projects parameters: - "$ref": "#/components/parameters/owner" - "$ref": "#/components/parameters/repo" - name: state description: Indicates the state of the projects to return. Can be either `open`, `closed`, or `all`. in: query required: false schema: type: string enum: - open - closed - all default: open - "$ref": "#/components/parameters/per-page" - "$ref": "#/components/parameters/page" responses: '200': description: Response content: application/json: schema: type: array items: "$ref": "#/components/schemas/project" examples: default: "$ref": "#/components/examples/project-items-2" headers: Link: "$ref": "#/components/headers/link" '401': "$ref": "#/components/responses/requires_authentication" '403': "$ref": "#/components/responses/forbidden" '404': "$ref": "#/components/responses/not_found" '410': "$ref": "#/components/responses/gone" '422': "$ref": "#/components/responses/validation_failed_simple" x-github: githubCloudOnly: false enabledForGitHubApps: true category: projects previews: - required: true name: inertia note: |- The Projects API is currently available for developers to preview. During the preview period, the API may change without advance notice. Please see the [blog post](https://developer.github.com/changes/2016-10-27-changes-to-projects-api) for full details. To access the API during the preview period, you must provide a custom [media type](https://docs.github.com/enterprise-server@3.0/rest/overview/media-types) in the `Accept` header: ```shell application/vnd.github.inertia-preview+json ``` post: summary: Create a repository project description: Creates a repository project board. Returns a `404 Not Found` status if projects are disabled in the repository. If you do not have sufficient privileges to perform this action, a `401 Unauthorized` or `410 Gone` status is returned. tags: - projects operationId: projects/create-for-repo externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/projects#create-a-repository-project parameters: - "$ref": "#/components/parameters/owner" - "$ref": "#/components/parameters/repo" requestBody: required: true content: application/json: schema: type: object properties: name: type: string description: The name of the project. body: type: string description: The description of the project. required: - name example: name: Projects Documentation body: Developer documentation project for the developer site. responses: '201': description: Response content: application/json: schema: "$ref": "#/components/schemas/project" examples: default: "$ref": "#/components/examples/project-3" '401': "$ref": "#/components/responses/requires_authentication" '403': "$ref": "#/components/responses/forbidden" '404': "$ref": "#/components/responses/not_found" '410': "$ref": "#/components/responses/gone" '422': "$ref": "#/components/responses/validation_failed_simple" x-github: githubCloudOnly: false enabledForGitHubApps: true category: projects previews: - required: true name: inertia note: |- The Projects API is currently available for developers to preview. During the preview period, the API may change without advance notice. Please see the [blog post](https://developer.github.com/changes/2016-10-27-changes-to-projects-api) for full details. To access the API during the preview period, you must provide a custom [media type](https://docs.github.com/enterprise-server@3.0/rest/overview/media-types) in the `Accept` header: ```shell application/vnd.github.inertia-preview+json ``` "/repos/{owner}/{repo}/pulls": get: summary: List pull requests description: Draft pull requests are available in public repositories with GitHub Free and GitHub Free for organizations, GitHub Pro, and legacy per-repository billing plans, and in public and private repositories with GitHub Team and GitHub Enterprise Cloud. For more information, see [GitHub's products](https://docs.github.com/github/getting-started-with-github/githubs-products) in the GitHub Help documentation. tags: - pulls operationId: pulls/list externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/pulls#list-pull-requests parameters: - "$ref": "#/components/parameters/owner" - "$ref": "#/components/parameters/repo" - name: state description: Either `open`, `closed`, or `all` to filter by state. in: query required: false schema: type: string enum: - open - closed - all default: open - name: head description: 'Filter pulls by head user or head organization and branch name in the format of `user:ref-name` or `organization:ref-name`. For example: `github:new-script-format` or `octocat:test-branch`.' in: query required: false schema: type: string - name: base description: 'Filter pulls by base branch name. Example: `gh-pages`.' in: query required: false schema: type: string - name: sort description: What to sort results by. Can be either `created`, `updated`, `popularity` (comment count) or `long-running` (age, filtering by pulls updated in the last month). in: query required: false schema: type: string enum: - created - updated - popularity - long-running default: created - name: direction description: 'The direction of the sort. Can be either `asc` or `desc`. Default: `desc` when sort is `created` or sort is not specified, otherwise `asc`.' in: query required: false schema: type: string enum: - asc - desc - "$ref": "#/components/parameters/per-page" - "$ref": "#/components/parameters/page" responses: '200': description: Response content: application/json: schema: type: array items: "$ref": "#/components/schemas/pull-request-simple" examples: default: "$ref": "#/components/examples/pull-request-simple-items" headers: Link: "$ref": "#/components/headers/link" '304': "$ref": "#/components/responses/not_modified" '422': "$ref": "#/components/responses/validation_failed" x-github: githubCloudOnly: false enabledForGitHubApps: true category: pulls subcategory: post: summary: Create a pull request description: |- Draft pull requests are available in public repositories with GitHub Free and GitHub Free for organizations, GitHub Pro, and legacy per-repository billing plans, and in public and private repositories with GitHub Team and GitHub Enterprise Cloud. For more information, see [GitHub's products](https://docs.github.com/github/getting-started-with-github/githubs-products) in the GitHub Help documentation. To open or update a pull request in a public repository, you must have write access to the head or the source branch. For organization-owned repositories, you must be a member of the organization that owns the repository to open or update a pull request. You can create a new pull request. This endpoint triggers [notifications](https://docs.github.com/en/github/managing-subscriptions-and-notifications-on-github/about-notifications). Creating content too quickly using this endpoint may result in secondary rate limiting. See "[Secondary rate limits](https://docs.github.com/enterprise-server@3.0/rest/overview/resources-in-the-rest-api#secondary-rate-limits)" and "[Dealing with secondary rate limits](https://docs.github.com/enterprise-server@3.0/rest/guides/best-practices-for-integrators#dealing-with-rate-limits)" for details. tags: - pulls operationId: pulls/create externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/pulls#create-a-pull-request parameters: - "$ref": "#/components/parameters/owner" - "$ref": "#/components/parameters/repo" requestBody: required: true content: application/json: schema: type: object properties: title: type: string description: The title of the new pull request. head: type: string description: 'The name of the branch where your changes are implemented. For cross-repository pull requests in the same network, namespace `head` with a user like this: `username:branch`.' base: type: string description: The name of the branch you want the changes pulled into. This should be an existing branch on the current repository. You cannot submit a pull request to one repository that requests a merge to a base of another repository. body: type: string description: The contents of the pull request. maintainer_can_modify: type: boolean description: Indicates whether [maintainers can modify](https://docs.github.com/articles/allowing-changes-to-a-pull-request-branch-created-from-a-fork/) the pull request. draft: type: boolean description: Indicates whether the pull request is a draft. See "[Draft Pull Requests](https://docs.github.com/en/articles/about-pull-requests#draft-pull-requests)" in the GitHub Help documentation to learn more. issue: type: integer examples: - 1 required: - head - base example: title: Amazing new feature body: Please pull these awesome changes in! head: octocat:new-feature base: master responses: '201': description: Response content: application/json: schema: "$ref": "#/components/schemas/pull-request" examples: default: "$ref": "#/components/examples/pull-request" headers: Location: example: https://api.github.com/repos/octocat/Hello-World/pulls/1347 schema: type: string '403': "$ref": "#/components/responses/forbidden" '422': "$ref": "#/components/responses/validation_failed" x-github: triggersNotification: true githubCloudOnly: false enabledForGitHubApps: true category: pulls subcategory: "/repos/{owner}/{repo}/pulls/comments": get: summary: List review comments in a repository description: Lists review comments for all pull requests in a repository. By default, review comments are in ascending order by ID. tags: - pulls operationId: pulls/list-review-comments-for-repo externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/pulls#list-review-comments-in-a-repository parameters: - "$ref": "#/components/parameters/owner" - "$ref": "#/components/parameters/repo" - name: sort in: query required: false schema: type: string enum: - created - updated - created_at - name: direction description: Can be either `asc` or `desc`. Ignored without `sort` parameter. in: query required: false schema: type: string enum: - asc - desc - "$ref": "#/components/parameters/since" - "$ref": "#/components/parameters/per-page" - "$ref": "#/components/parameters/page" responses: '200': description: Response content: application/json: schema: type: array items: "$ref": "#/components/schemas/pull-request-review-comment" examples: default: "$ref": "#/components/examples/pull-request-review-comment-items" headers: Link: "$ref": "#/components/headers/link" x-github: githubCloudOnly: false enabledForGitHubApps: true category: pulls subcategory: comments previews: - required: false name: squirrel-girl note: |- An additional `reactions` object in the issue comment payload is currently available for developers to preview. During the preview period, the APIs may change without advance notice. Please see the [blog post](https://developer.github.com/changes/2016-05-12-reactions-api-preview) for full details. To access the API you must provide a custom [media type](https://docs.github.com/enterprise-server@3.0/rest/overview/media-types) in the `Accept` header: ```shell application/vnd.github.squirrel-girl-preview ``` The `reactions` key will have the following payload where `url` can be used to construct the API location for [listing and creating](https://docs.github.com/enterprise-server@3.0/rest/reference/reactions) reactions. - required: false name: comfort-fade note: |- Multi-line comments in a pull request diff is currently available for developers to preview. During the preview period, these response fields may change without advance notice. See the [blog post](https://developer.github.com/changes/2019-10-03-multi-line-comments) for more information. To create multi-line comments or see multi-line comments with the new supported fields during the preview period, you must provide a custom [media type](https://docs.github.com/enterprise-server@3.0/rest/overview/media-types) in the `Accept` header: ```shell application/vnd.github.comfort-fade-preview+json ``` To show multi-line comment-supported fields in the response, use the `comfort-fade` preview header and the `line` parameter. If you use the `comfort-fade` preview header, your response will show: * For multi-line comments, values for `start_line`, `original_start_line`, `start_side`, `line`, `original_line`, and `side`. * For single-line comments, values for `line`, `original_line`, and `side` and a `null` value for `start_line`, `original_start_line`, and `start_side`. If you don't use the `comfort-fade` preview header, multi-line and single-line comments will appear the same way in the response with a single `position` attribute. Your response will show: * For multi-line comments, the last line of the comment range for the `position` attribute. * For single-line comments, the diff-positioned way of referencing comments for the `position` attribute. "/repos/{owner}/{repo}/pulls/comments/{comment_id}": get: summary: Get a review comment for a pull request description: Provides details for a review comment. tags: - pulls operationId: pulls/get-review-comment externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/pulls#get-a-review-comment-for-a-pull-request parameters: - "$ref": "#/components/parameters/owner" - "$ref": "#/components/parameters/repo" - "$ref": "#/components/parameters/comment-id" responses: '200': description: Response content: application/json: schema: "$ref": "#/components/schemas/pull-request-review-comment" examples: default: "$ref": "#/components/examples/pull-request-review-comment-2" '404': "$ref": "#/components/responses/not_found" x-github: githubCloudOnly: false enabledForGitHubApps: true category: pulls subcategory: comments previews: - required: false name: squirrel-girl note: |- An additional `reactions` object in the issue comment payload is currently available for developers to preview. During the preview period, the APIs may change without advance notice. Please see the [blog post](https://developer.github.com/changes/2016-05-12-reactions-api-preview) for full details. To access the API you must provide a custom [media type](https://docs.github.com/enterprise-server@3.0/rest/overview/media-types) in the `Accept` header: ```shell application/vnd.github.squirrel-girl-preview ``` The `reactions` key will have the following payload where `url` can be used to construct the API location for [listing and creating](https://docs.github.com/enterprise-server@3.0/rest/reference/reactions) reactions. - required: false name: comfort-fade note: |- Multi-line comments in a pull request diff is currently available for developers to preview. During the preview period, these response fields may change without advance notice. See the [blog post](https://developer.github.com/changes/2019-10-03-multi-line-comments) for more information. To create multi-line comments or see multi-line comments with the new supported fields during the preview period, you must provide a custom [media type](https://docs.github.com/enterprise-server@3.0/rest/overview/media-types) in the `Accept` header: ```shell application/vnd.github.comfort-fade-preview+json ``` To show multi-line comment-supported fields in the response, use the `comfort-fade` preview header and the `line` parameter. If you use the `comfort-fade` preview header, your response will show: * For multi-line comments, values for `start_line`, `original_start_line`, `start_side`, `line`, `original_line`, and `side`. * For single-line comments, values for `line`, `original_line`, and `side` and a `null` value for `start_line`, `original_start_line`, and `start_side`. If you don't use the `comfort-fade` preview header, multi-line and single-line comments will appear the same way in the response with a single `position` attribute. Your response will show: * For multi-line comments, the last line of the comment range for the `position` attribute. * For single-line comments, the diff-positioned way of referencing comments for the `position` attribute. patch: summary: Update a review comment for a pull request description: Enables you to edit a review comment. tags: - pulls operationId: pulls/update-review-comment externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/pulls#update-a-review-comment-for-a-pull-request parameters: - "$ref": "#/components/parameters/owner" - "$ref": "#/components/parameters/repo" - "$ref": "#/components/parameters/comment-id" requestBody: required: true content: application/json: schema: type: object properties: body: type: string description: The text of the reply to the review comment. required: - body example: body: I like this too! responses: '200': description: Response content: application/json: schema: "$ref": "#/components/schemas/pull-request-review-comment" examples: default: "$ref": "#/components/examples/pull-request-review-comment-2" x-github: githubCloudOnly: false enabledForGitHubApps: true category: pulls subcategory: comments previews: - required: false name: comfort-fade note: |- Multi-line comments in a pull request diff is currently available for developers to preview. During the preview period, these response fields may change without advance notice. See the [blog post](https://developer.github.com/changes/2019-10-03-multi-line-comments) for more information. To create multi-line comments or see multi-line comments with the new supported fields during the preview period, you must provide a custom [media type](https://docs.github.com/enterprise-server@3.0/rest/overview/media-types) in the `Accept` header: ```shell application/vnd.github.comfort-fade-preview+json ``` To show multi-line comment-supported fields in the response, use the `comfort-fade` preview header and the `line` parameter. If you use the `comfort-fade` preview header, your response will show: * For multi-line comments, values for `start_line`, `original_start_line`, `start_side`, `line`, `original_line`, and `side`. * For single-line comments, values for `line`, `original_line`, and `side` and a `null` value for `start_line`, `original_start_line`, and `start_side`. If you don't use the `comfort-fade` preview header, multi-line and single-line comments will appear the same way in the response with a single `position` attribute. Your response will show: * For multi-line comments, the last line of the comment range for the `position` attribute. * For single-line comments, the diff-positioned way of referencing comments for the `position` attribute. delete: summary: Delete a review comment for a pull request description: Deletes a review comment. tags: - pulls operationId: pulls/delete-review-comment externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/pulls#delete-a-review-comment-for-a-pull-request parameters: - "$ref": "#/components/parameters/owner" - "$ref": "#/components/parameters/repo" - "$ref": "#/components/parameters/comment-id" responses: '204': description: Response '404': "$ref": "#/components/responses/not_found" x-github: githubCloudOnly: false enabledForGitHubApps: true category: pulls subcategory: comments "/repos/{owner}/{repo}/pulls/comments/{comment_id}/reactions": get: summary: List reactions for a pull request review comment description: List the reactions to a [pull request review comment](https://docs.github.com/enterprise-server@3.0/rest/reference/pulls#review-comments). tags: - reactions operationId: reactions/list-for-pull-request-review-comment externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/reactions#list-reactions-for-a-pull-request-review-comment parameters: - "$ref": "#/components/parameters/owner" - "$ref": "#/components/parameters/repo" - "$ref": "#/components/parameters/comment-id" - name: content description: Returns a single [reaction type](https://docs.github.com/enterprise-server@3.0/rest/reference/reactions#reaction-types). Omit this parameter to list all reactions to a pull request review comment. in: query required: false schema: type: string enum: - "+1" - "-1" - laugh - confused - heart - hooray - rocket - eyes - "$ref": "#/components/parameters/per-page" - "$ref": "#/components/parameters/page" responses: '200': description: Response content: application/json: schema: type: array items: "$ref": "#/components/schemas/reaction" examples: default: "$ref": "#/components/examples/reaction-items" headers: Link: "$ref": "#/components/headers/link" '404': "$ref": "#/components/responses/not_found" x-github: githubCloudOnly: false enabledForGitHubApps: true category: reactions previews: - required: true name: squirrel-girl note: |- An additional `reactions` object in the issue comment payload is currently available for developers to preview. During the preview period, the APIs may change without advance notice. Please see the [blog post](https://developer.github.com/changes/2016-05-12-reactions-api-preview) for full details. To access the API you must provide a custom [media type](https://docs.github.com/enterprise-server@3.0/rest/overview/media-types) in the `Accept` header: ```shell application/vnd.github.squirrel-girl-preview ``` The `reactions` key will have the following payload where `url` can be used to construct the API location for [listing and creating](https://docs.github.com/enterprise-server@3.0/rest/reference/reactions) reactions. post: summary: Create reaction for a pull request review comment description: Create a reaction to a [pull request review comment](https://docs.github.com/enterprise-server@3.0/rest/reference/pulls#comments). A response with an HTTP `200` status means that you already added the reaction type to this pull request review comment. tags: - reactions operationId: reactions/create-for-pull-request-review-comment externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/reactions#create-reaction-for-a-pull-request-review-comment parameters: - "$ref": "#/components/parameters/owner" - "$ref": "#/components/parameters/repo" - "$ref": "#/components/parameters/comment-id" requestBody: required: true content: application/json: schema: type: object properties: content: type: string description: The [reaction type](https://docs.github.com/enterprise-server@3.0/rest/reference/reactions#reaction-types) to add to the pull request review comment. enum: - "+1" - "-1" - laugh - confused - heart - hooray - rocket - eyes required: - content example: content: heart responses: '200': description: Reaction exists content: application/json: schema: "$ref": "#/components/schemas/reaction" examples: default: "$ref": "#/components/examples/reaction" '201': description: Reaction created content: application/json: schema: "$ref": "#/components/schemas/reaction" examples: default: "$ref": "#/components/examples/reaction" '422': "$ref": "#/components/responses/validation_failed" x-github: githubCloudOnly: false enabledForGitHubApps: true category: reactions previews: - required: true name: squirrel-girl note: |- An additional `reactions` object in the issue comment payload is currently available for developers to preview. During the preview period, the APIs may change without advance notice. Please see the [blog post](https://developer.github.com/changes/2016-05-12-reactions-api-preview) for full details. To access the API you must provide a custom [media type](https://docs.github.com/enterprise-server@3.0/rest/overview/media-types) in the `Accept` header: ```shell application/vnd.github.squirrel-girl-preview ``` The `reactions` key will have the following payload where `url` can be used to construct the API location for [listing and creating](https://docs.github.com/enterprise-server@3.0/rest/reference/reactions) reactions. "/repos/{owner}/{repo}/pulls/comments/{comment_id}/reactions/{reaction_id}": delete: summary: Delete a pull request comment reaction description: |- **Note:** You can also specify a repository by `repository_id` using the route `DELETE /repositories/:repository_id/pulls/comments/:comment_id/reactions/:reaction_id.` Delete a reaction to a [pull request review comment](https://docs.github.com/enterprise-server@3.0/rest/reference/pulls#review-comments). tags: - reactions operationId: reactions/delete-for-pull-request-comment externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/reactions#delete-a-pull-request-comment-reaction parameters: - "$ref": "#/components/parameters/owner" - "$ref": "#/components/parameters/repo" - "$ref": "#/components/parameters/comment-id" - "$ref": "#/components/parameters/reaction-id" responses: '204': description: Response x-github: githubCloudOnly: false enabledForGitHubApps: true category: reactions previews: - required: true name: squirrel-girl note: |- An additional `reactions` object in the issue comment payload is currently available for developers to preview. During the preview period, the APIs may change without advance notice. Please see the [blog post](https://developer.github.com/changes/2016-05-12-reactions-api-preview) for full details. To access the API you must provide a custom [media type](https://docs.github.com/enterprise-server@3.0/rest/overview/media-types) in the `Accept` header: ```shell application/vnd.github.squirrel-girl-preview ``` The `reactions` key will have the following payload where `url` can be used to construct the API location for [listing and creating](https://docs.github.com/enterprise-server@3.0/rest/reference/reactions) reactions. "/repos/{owner}/{repo}/pulls/{pull_number}": get: summary: Get a pull request description: |- Draft pull requests are available in public repositories with GitHub Free and GitHub Free for organizations, GitHub Pro, and legacy per-repository billing plans, and in public and private repositories with GitHub Team and GitHub Enterprise Cloud. For more information, see [GitHub's products](https://docs.github.com/github/getting-started-with-github/githubs-products) in the GitHub Help documentation. Lists details of a pull request by providing its number. When you get, [create](https://docs.github.com/enterprise-server@3.0/rest/reference/pulls/#create-a-pull-request), or [edit](https://docs.github.com/enterprise-server@3.0/rest/reference/pulls#update-a-pull-request) a pull request, GitHub Enterprise Server creates a merge commit to test whether the pull request can be automatically merged into the base branch. This test commit is not added to the base branch or the head branch. You can review the status of the test commit using the `mergeable` key. For more information, see "[Checking mergeability of pull requests](https://docs.github.com/enterprise-server@3.0/rest/guides/getting-started-with-the-git-database-api#checking-mergeability-of-pull-requests)". The value of the `mergeable` attribute can be `true`, `false`, or `null`. If the value is `null`, then GitHub Enterprise Server has started a background job to compute the mergeability. After giving the job time to complete, resubmit the request. When the job finishes, you will see a non-`null` value for the `mergeable` attribute in the response. If `mergeable` is `true`, then `merge_commit_sha` will be the SHA of the _test_ merge commit. The value of the `merge_commit_sha` attribute changes depending on the state of the pull request. Before merging a pull request, the `merge_commit_sha` attribute holds the SHA of the _test_ merge commit. After merging a pull request, the `merge_commit_sha` attribute changes depending on how you merged the pull request: * If merged as a [merge commit](https://docs.github.com/articles/about-merge-methods-on-github/), `merge_commit_sha` represents the SHA of the merge commit. * If merged via a [squash](https://docs.github.com/articles/about-merge-methods-on-github/#squashing-your-merge-commits), `merge_commit_sha` represents the SHA of the squashed commit on the base branch. * If [rebased](https://docs.github.com/articles/about-merge-methods-on-github/#rebasing-and-merging-your-commits), `merge_commit_sha` represents the commit that the base branch was updated to. Pass the appropriate [media type](https://docs.github.com/enterprise-server@3.0/rest/overview/media-types/#commits-commit-comparison-and-pull-requests) to fetch diff and patch formats. tags: - pulls operationId: pulls/get externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/pulls#get-a-pull-request parameters: - "$ref": "#/components/parameters/owner" - "$ref": "#/components/parameters/repo" - "$ref": "#/components/parameters/pull-number" responses: '200': description: Pass the appropriate [media type](https://docs.github.com/enterprise-server@3.0/rest/overview/media-types/#commits-commit-comparison-and-pull-requests) to fetch diff and patch formats. content: application/json: schema: "$ref": "#/components/schemas/pull-request" examples: default: "$ref": "#/components/examples/pull-request" '304': "$ref": "#/components/responses/not_modified" '500': "$ref": "#/components/responses/internal_error" '404': "$ref": "#/components/responses/not_found" x-github: githubCloudOnly: false enabledForGitHubApps: true category: pulls subcategory: patch: summary: Update a pull request description: |- Draft pull requests are available in public repositories with GitHub Free and GitHub Free for organizations, GitHub Pro, and legacy per-repository billing plans, and in public and private repositories with GitHub Team and GitHub Enterprise Cloud. For more information, see [GitHub's products](https://docs.github.com/github/getting-started-with-github/githubs-products) in the GitHub Help documentation. To open or update a pull request in a public repository, you must have write access to the head or the source branch. For organization-owned repositories, you must be a member of the organization that owns the repository to open or update a pull request. tags: - pulls operationId: pulls/update externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/pulls/#update-a-pull-request parameters: - "$ref": "#/components/parameters/owner" - "$ref": "#/components/parameters/repo" - "$ref": "#/components/parameters/pull-number" requestBody: required: false content: application/json: schema: type: object properties: title: type: string description: The title of the pull request. body: type: string description: The contents of the pull request. state: type: string description: State of this Pull Request. Either `open` or `closed`. enum: - open - closed base: type: string description: The name of the branch you want your changes pulled into. This should be an existing branch on the current repository. You cannot update the base branch on a pull request to point to another repository. maintainer_can_modify: type: boolean description: Indicates whether [maintainers can modify](https://docs.github.com/articles/allowing-changes-to-a-pull-request-branch-created-from-a-fork/) the pull request. example: title: new title body: updated body state: open base: master responses: '200': description: Response content: application/json: schema: "$ref": "#/components/schemas/pull-request" examples: default: "$ref": "#/components/examples/pull-request" '422': "$ref": "#/components/responses/validation_failed" '403': "$ref": "#/components/responses/forbidden" x-github: githubCloudOnly: false enabledForGitHubApps: true category: pulls subcategory: "/repos/{owner}/{repo}/pulls/{pull_number}/comments": get: summary: List review comments on a pull request description: Lists all review comments for a pull request. By default, review comments are in ascending order by ID. tags: - pulls operationId: pulls/list-review-comments externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/pulls#list-review-comments-on-a-pull-request parameters: - "$ref": "#/components/parameters/owner" - "$ref": "#/components/parameters/repo" - "$ref": "#/components/parameters/pull-number" - "$ref": "#/components/parameters/sort" - name: direction description: Can be either `asc` or `desc`. Ignored without `sort` parameter. in: query required: false schema: type: string enum: - asc - desc - "$ref": "#/components/parameters/since" - "$ref": "#/components/parameters/per-page" - "$ref": "#/components/parameters/page" responses: '200': description: Response content: application/json: schema: type: array items: "$ref": "#/components/schemas/pull-request-review-comment" examples: default: "$ref": "#/components/examples/pull-request-review-comment-items" headers: Link: "$ref": "#/components/headers/link" x-github: githubCloudOnly: false enabledForGitHubApps: true category: pulls subcategory: comments previews: - required: false name: squirrel-girl note: |- An additional `reactions` object in the issue comment payload is currently available for developers to preview. During the preview period, the APIs may change without advance notice. Please see the [blog post](https://developer.github.com/changes/2016-05-12-reactions-api-preview) for full details. To access the API you must provide a custom [media type](https://docs.github.com/enterprise-server@3.0/rest/overview/media-types) in the `Accept` header: ```shell application/vnd.github.squirrel-girl-preview ``` The `reactions` key will have the following payload where `url` can be used to construct the API location for [listing and creating](https://docs.github.com/enterprise-server@3.0/rest/reference/reactions) reactions. - required: false name: comfort-fade note: |- Multi-line comments in a pull request diff is currently available for developers to preview. During the preview period, these response fields may change without advance notice. See the [blog post](https://developer.github.com/changes/2019-10-03-multi-line-comments) for more information. To create multi-line comments or see multi-line comments with the new supported fields during the preview period, you must provide a custom [media type](https://docs.github.com/enterprise-server@3.0/rest/overview/media-types) in the `Accept` header: ```shell application/vnd.github.comfort-fade-preview+json ``` To show multi-line comment-supported fields in the response, use the `comfort-fade` preview header and the `line` parameter. If you use the `comfort-fade` preview header, your response will show: * For multi-line comments, values for `start_line`, `original_start_line`, `start_side`, `line`, `original_line`, and `side`. * For single-line comments, values for `line`, `original_line`, and `side` and a `null` value for `start_line`, `original_start_line`, and `start_side`. If you don't use the `comfort-fade` preview header, multi-line and single-line comments will appear the same way in the response with a single `position` attribute. Your response will show: * For multi-line comments, the last line of the comment range for the `position` attribute. * For single-line comments, the diff-positioned way of referencing comments for the `position` attribute. post: summary: Create a review comment for a pull request description: |2- Creates a review comment in the pull request diff. To add a regular comment to a pull request timeline, see "[Create an issue comment](https://docs.github.com/enterprise-server@3.0/rest/reference/issues#create-an-issue-comment)." We recommend creating a review comment using `line`, `side`, and optionally `start_line` and `start_side` if your comment applies to more than one line in the pull request diff. You can still create a review comment using the `position` parameter. When you use `position`, the `line`, `side`, `start_line`, and `start_side` parameters are not required. For more information, see the [`comfort-fade` preview notice](https://docs.github.com/enterprise-server@3.0/rest/reference/pulls#create-a-review-comment-for-a-pull-request-preview-notices). **Note:** The position value equals the number of lines down from the first "@@" hunk header in the file you want to add a comment. The line just below the "@@" line is position 1, the next line is position 2, and so on. The position in the diff continues to increase through lines of whitespace and additional hunks until the beginning of a new file. This endpoint triggers [notifications](https://docs.github.com/en/github/managing-subscriptions-and-notifications-on-github/about-notifications). Creating content too quickly using this endpoint may result in secondary rate limiting. See "[Secondary rate limits](https://docs.github.com/enterprise-server@3.0/rest/overview/resources-in-the-rest-api#secondary-rate-limits)" and "[Dealing with secondary rate limits](https://docs.github.com/enterprise-server@3.0/rest/guides/best-practices-for-integrators#dealing-with-secondary-rate-limits)" for details. tags: - pulls operationId: pulls/create-review-comment externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/pulls#create-a-review-comment-for-a-pull-request parameters: - "$ref": "#/components/parameters/owner" - "$ref": "#/components/parameters/repo" - "$ref": "#/components/parameters/pull-number" requestBody: required: true content: application/json: schema: type: object properties: body: type: string description: The text of the review comment. commit_id: type: string description: The SHA of the commit needing a comment. Not using the latest commit SHA may render your comment outdated if a subsequent commit modifies the line you specify as the `position`. path: type: string description: The relative path to the file that necessitates a comment. position: type: integer description: "**Required without `comfort-fade` preview**. The position in the diff where you want to add a review comment. Note this value is not the same as the line number in the file. For help finding the position value, read the note above." side: type: string description: '**Required with `comfort-fade` preview**. In a split diff view, the side of the diff that the pull request''s changes appear on. Can be `LEFT` or `RIGHT`. Use `LEFT` for deletions that appear in red. Use `RIGHT` for additions that appear in green or unchanged lines that appear in white and are shown for context. For a multi-line comment, side represents whether the last line of the comment range is a deletion or addition. For more information, see "[Diff view options](https://docs.github.com/en/articles/about-comparing-branches-in-pull-requests#diff-view-options)" in the GitHub Help documentation.' enum: - LEFT - RIGHT line: type: integer description: "**Required with `comfort-fade` preview**. The line of the blob in the pull request diff that the comment applies to. For a multi-line comment, the last line of the range that your comment applies to." start_line: type: integer description: '**Required when using multi-line comments**. To create multi-line comments, you must use the `comfort-fade` preview header. The `start_line` is the first line in the pull request diff that your multi-line comment applies to. To learn more about multi-line comments, see "[Commenting on a pull request](https://docs.github.com/en/articles/commenting-on-a-pull-request#adding-line-comments-to-a-pull-request)" in the GitHub Help documentation.' start_side: type: string description: '**Required when using multi-line comments**. To create multi-line comments, you must use the `comfort-fade` preview header. The `start_side` is the starting side of the diff that the comment applies to. Can be `LEFT` or `RIGHT`. To learn more about multi-line comments, see "[Commenting on a pull request](https://docs.github.com/en/articles/commenting-on-a-pull-request#adding-line-comments-to-a-pull-request)" in the GitHub Help documentation. See `side` in this table for additional context.' enum: - LEFT - RIGHT - side in_reply_to: type: integer description: The ID of the review comment to reply to. To find the ID of a review comment with ["List review comments on a pull request"](#list-review-comments-on-a-pull-request). When specified, all parameters other than `body` in the request body are ignored. examples: - 2 required: - body examples: example-for-a-single-line-comment: summary: Example for a single-line comment value: body: Let's add this deleted line back. commit_id: 6dcb09b5b57875f334f61aebed695e2e4193db5e path: file1.txt line: 5 side: LEFT example-for-a-multi-line-comment: summary: Example for a multi-line comment value: body: Great stuff! commit_id: 6dcb09b5b57875f334f61aebed695e2e4193db5e path: file1.txt start_line: 1 start_side: RIGHT line: 2 side: RIGHT responses: '201': description: Response content: application/json: schema: "$ref": "#/components/schemas/pull-request-review-comment" examples: example-for-a-multi-line-comment: "$ref": "#/components/examples/pull-request-review-comment-example-for-a-multi-line-comment" headers: Location: example: https://api.github.com/repos/octocat/Hello-World/pulls/comments/1 schema: type: string '422': "$ref": "#/components/responses/validation_failed" '403': "$ref": "#/components/responses/forbidden" x-github: triggersNotification: true githubCloudOnly: false enabledForGitHubApps: true category: pulls subcategory: comments previews: - required: false name: comfort-fade note: |- Multi-line comments in a pull request diff is currently available for developers to preview. During the preview period, these response fields may change without advance notice. See the [blog post](https://developer.github.com/changes/2019-10-03-multi-line-comments) for more information. To create multi-line comments or see multi-line comments with the new supported fields during the preview period, you must provide a custom [media type](https://docs.github.com/enterprise-server@3.0/rest/overview/media-types) in the `Accept` header: ```shell application/vnd.github.comfort-fade-preview+json ``` To show multi-line comment-supported fields in the response, use the `comfort-fade` preview header and the `line` parameter. If you use the `comfort-fade` preview header, your response will show: * For multi-line comments, values for `start_line`, `original_start_line`, `start_side`, `line`, `original_line`, and `side`. * For single-line comments, values for `line`, `original_line`, and `side` and a `null` value for `start_line`, `original_start_line`, and `start_side`. If you don't use the `comfort-fade` preview header, multi-line and single-line comments will appear the same way in the response with a single `position` attribute. Your response will show: * For multi-line comments, the last line of the comment range for the `position` attribute. * For single-line comments, the diff-positioned way of referencing comments for the `position` attribute. "/repos/{owner}/{repo}/pulls/{pull_number}/comments/{comment_id}/replies": post: summary: Create a reply for a review comment description: |- Creates a reply to a review comment for a pull request. For the `comment_id`, provide the ID of the review comment you are replying to. This must be the ID of a _top-level review comment_, not a reply to that comment. Replies to replies are not supported. This endpoint triggers [notifications](https://docs.github.com/en/github/managing-subscriptions-and-notifications-on-github/about-notifications). Creating content too quickly using this endpoint may result in secondary rate limiting. See "[Secondary rate limits](https://docs.github.com/enterprise-server@3.0/rest/overview/resources-in-the-rest-api#secondary-rate-limits)" and "[Dealing with secondary rate limits](https://docs.github.com/enterprise-server@3.0/rest/guides/best-practices-for-integrators#dealing-with-secondary-rate-limits)" for details. tags: - pulls operationId: pulls/create-reply-for-review-comment externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/pulls#create-a-reply-for-a-review-comment parameters: - "$ref": "#/components/parameters/owner" - "$ref": "#/components/parameters/repo" - "$ref": "#/components/parameters/pull-number" - "$ref": "#/components/parameters/comment-id" requestBody: required: true content: application/json: schema: type: object properties: body: type: string description: The text of the review comment. required: - body example: body: Great stuff! responses: '201': description: Response content: application/json: schema: "$ref": "#/components/schemas/pull-request-review-comment" examples: default: "$ref": "#/components/examples/pull-request-review-comment" headers: Location: example: https://api.github.com/repos/octocat/Hello-World/pulls/comments/1 schema: type: string '404': "$ref": "#/components/responses/not_found" x-github: triggersNotification: true githubCloudOnly: false enabledForGitHubApps: false category: pulls subcategory: comments "/repos/{owner}/{repo}/pulls/{pull_number}/commits": get: summary: List commits on a pull request description: Lists a maximum of 250 commits for a pull request. To receive a complete commit list for pull requests with more than 250 commits, use the [List commits](https://docs.github.com/enterprise-server@3.0/rest/reference/repos#list-commits) endpoint. tags: - pulls operationId: pulls/list-commits externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/pulls#list-commits-on-a-pull-request parameters: - "$ref": "#/components/parameters/owner" - "$ref": "#/components/parameters/repo" - "$ref": "#/components/parameters/pull-number" - "$ref": "#/components/parameters/per-page" - "$ref": "#/components/parameters/page" responses: '200': description: Response content: application/json: schema: type: array items: "$ref": "#/components/schemas/commit" examples: default: "$ref": "#/components/examples/commit-items" headers: Link: "$ref": "#/components/headers/link" x-github: githubCloudOnly: false enabledForGitHubApps: true category: pulls subcategory: "/repos/{owner}/{repo}/pulls/{pull_number}/files": get: summary: List pull requests files description: "**Note:** Responses include a maximum of 3000 files. The paginated response returns 30 files per page by default." tags: - pulls operationId: pulls/list-files externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/pulls#list-pull-requests-files parameters: - "$ref": "#/components/parameters/owner" - "$ref": "#/components/parameters/repo" - "$ref": "#/components/parameters/pull-number" - "$ref": "#/components/parameters/per-page" - "$ref": "#/components/parameters/page" responses: '200': description: Response content: application/json: schema: type: array items: "$ref": "#/components/schemas/diff-entry" examples: default: "$ref": "#/components/examples/diff-entry-items" headers: Link: "$ref": "#/components/headers/link" '422': "$ref": "#/components/responses/validation_failed" '500': "$ref": "#/components/responses/internal_error" x-github: githubCloudOnly: false enabledForGitHubApps: true category: pulls subcategory: "/repos/{owner}/{repo}/pulls/{pull_number}/merge": get: summary: Check if a pull request has been merged description: '' tags: - pulls operationId: pulls/check-if-merged externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/pulls#check-if-a-pull-request-has-been-merged parameters: - "$ref": "#/components/parameters/owner" - "$ref": "#/components/parameters/repo" - "$ref": "#/components/parameters/pull-number" responses: '204': description: Response if pull request has been merged '404': description: Not Found if pull request has not been merged x-github: githubCloudOnly: false enabledForGitHubApps: true category: pulls subcategory: put: summary: Merge a pull request description: This endpoint triggers [notifications](https://docs.github.com/enterprise-server@3.0/github/managing-subscriptions-and-notifications-on-github/about-notifications). Creating content too quickly using this endpoint may result in secondary rate limiting. See "[Secondary rate limits](https://docs.github.com/enterprise-server@3.0/rest/overview/resources-in-the-rest-api#secondary-rate-limits)" and "[Dealing with secondary rate limits](https://docs.github.com/enterprise-server@3.0/rest/guides/best-practices-for-integrators#dealing-with-secondary-rate-limits)" for details. tags: - pulls operationId: pulls/merge externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/pulls#merge-a-pull-request parameters: - "$ref": "#/components/parameters/owner" - "$ref": "#/components/parameters/repo" - "$ref": "#/components/parameters/pull-number" requestBody: required: false content: application/json: schema: type: - object - 'null' properties: commit_title: type: string description: Title for the automatic commit message. commit_message: type: string description: Extra detail to append to automatic commit message. sha: type: string description: SHA that pull request head must match to allow merge. merge_method: type: string description: Merge method to use. Possible values are `merge`, `squash` or `rebase`. Default is `merge`. enum: - merge - squash - rebase responses: '200': description: if merge was successful content: application/json: schema: "$ref": "#/components/schemas/pull-request-merge-result" examples: response-if-merge-was-successful: "$ref": "#/components/examples/pull-request-merge-result-response-if-merge-was-successful" '405': description: Method Not Allowed if merge cannot be performed content: application/json: schema: type: object properties: message: type: string documentation_url: type: string examples: response-if-merge-cannot-be-performed: value: message: Pull Request is not mergeable '409': description: Conflict if sha was provided and pull request head did not match content: application/json: schema: type: object properties: message: type: string documentation_url: type: string examples: response-if-sha-was-provided-and-pull-request-head-did-not-match: value: message: Head branch was modified. Review and try the merge again. '422': "$ref": "#/components/responses/validation_failed" '403': "$ref": "#/components/responses/forbidden" '404': "$ref": "#/components/responses/not_found" x-github: triggersNotification: true githubCloudOnly: false enabledForGitHubApps: true category: pulls subcategory: "/repos/{owner}/{repo}/pulls/{pull_number}/requested_reviewers": get: summary: List requested reviewers for a pull request description: '' tags: - pulls operationId: pulls/list-requested-reviewers externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/pulls#list-requested-reviewers-for-a-pull-request parameters: - "$ref": "#/components/parameters/owner" - "$ref": "#/components/parameters/repo" - "$ref": "#/components/parameters/pull-number" - "$ref": "#/components/parameters/per-page" - "$ref": "#/components/parameters/page" responses: '200': description: Response content: application/json: schema: "$ref": "#/components/schemas/pull-request-review-request" examples: default: "$ref": "#/components/examples/simple-pull-request-review-request" headers: Link: "$ref": "#/components/headers/link" x-github: githubCloudOnly: false enabledForGitHubApps: true category: pulls subcategory: review-requests post: summary: Request reviewers for a pull request description: This endpoint triggers [notifications](https://docs.github.com/enterprise-server@3.0/github/managing-subscriptions-and-notifications-on-github/about-notifications). Creating content too quickly using this endpoint may result in secondary rate limiting. See "[Secondary rate limits](https://docs.github.com/enterprise-server@3.0/rest/overview/resources-in-the-rest-api#secondary-rate-limits)" and "[Dealing with secondary rate limits](https://docs.github.com/enterprise-server@3.0/rest/guides/best-practices-for-integrators#dealing-with-secondary-rate-limits)" for details. tags: - pulls operationId: pulls/request-reviewers externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/pulls#request-reviewers-for-a-pull-request parameters: - "$ref": "#/components/parameters/owner" - "$ref": "#/components/parameters/repo" - "$ref": "#/components/parameters/pull-number" requestBody: required: false content: application/json: schema: type: object properties: reviewers: type: array description: An array of user `login`s that will be requested. items: type: string team_reviewers: type: array description: An array of team `slug`s that will be requested. items: type: string anyOf: - required: - reviewers - required: - team_reviewers example: reviewers: - octocat - hubot - other_user team_reviewers: - justice-league responses: '201': description: Response content: application/json: schema: "$ref": "#/components/schemas/pull-request-simple" examples: default: "$ref": "#/components/examples/pull-request-review-request" '422': description: Unprocessable Entity if user is not a collaborator '403': "$ref": "#/components/responses/forbidden" x-github: triggersNotification: true githubCloudOnly: false enabledForGitHubApps: true category: pulls subcategory: review-requests delete: summary: Remove requested reviewers from a pull request description: '' tags: - pulls operationId: pulls/remove-requested-reviewers externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/pulls#remove-requested-reviewers-from-a-pull-request parameters: - "$ref": "#/components/parameters/owner" - "$ref": "#/components/parameters/repo" - "$ref": "#/components/parameters/pull-number" requestBody: required: true content: application/json: schema: type: object properties: reviewers: type: array description: An array of user `login`s that will be removed. items: type: string team_reviewers: type: array description: An array of team `slug`s that will be removed. items: type: string required: - reviewers example: reviewers: - octocat - hubot - other_user team_reviewers: - justice-league responses: '200': description: Response content: application/json: schema: "$ref": "#/components/schemas/pull-request-simple" '422': "$ref": "#/components/responses/validation_failed" x-github: githubCloudOnly: false enabledForGitHubApps: true category: pulls subcategory: review-requests "/repos/{owner}/{repo}/pulls/{pull_number}/reviews": get: summary: List reviews for a pull request description: The list of reviews returns in chronological order. tags: - pulls operationId: pulls/list-reviews externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/pulls#list-reviews-for-a-pull-request parameters: - "$ref": "#/components/parameters/owner" - "$ref": "#/components/parameters/repo" - "$ref": "#/components/parameters/pull-number" - "$ref": "#/components/parameters/per-page" - "$ref": "#/components/parameters/page" responses: '200': description: The list of reviews returns in chronological order. content: application/json: schema: type: array items: "$ref": "#/components/schemas/pull-request-review" examples: default: "$ref": "#/components/examples/pull-request-review-items" headers: Link: "$ref": "#/components/headers/link" x-github: githubCloudOnly: false enabledForGitHubApps: true category: pulls subcategory: reviews post: summary: Create a review for a pull request description: |- This endpoint triggers [notifications](https://docs.github.com/en/github/managing-subscriptions-and-notifications-on-github/about-notifications). Creating content too quickly using this endpoint may result in secondary rate limiting. See "[Secondary rate limits](https://docs.github.com/enterprise-server@3.0/rest/overview/resources-in-the-rest-api#secondary-rate-limits)" and "[Dealing with secondary rate limits](https://docs.github.com/enterprise-server@3.0/rest/guides/best-practices-for-integrators#dealing-with-secondary-rate-limits)" for details. Pull request reviews created in the `PENDING` state do not include the `submitted_at` property in the response. **Note:** To comment on a specific line in a file, you need to first determine the _position_ of that line in the diff. The GitHub REST API v3 offers the `application/vnd.github.v3.diff` [media type](https://docs.github.com/enterprise-server@3.0/rest/overview/media-types#commits-commit-comparison-and-pull-requests). To see a pull request diff, add this media type to the `Accept` header of a call to the [single pull request](https://docs.github.com/enterprise-server@3.0/rest/reference/pulls#get-a-pull-request) endpoint. The `position` value equals the number of lines down from the first "@@" hunk header in the file you want to add a comment. The line just below the "@@" line is position 1, the next line is position 2, and so on. The position in the diff continues to increase through lines of whitespace and additional hunks until the beginning of a new file. tags: - pulls operationId: pulls/create-review externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/pulls#create-a-review-for-a-pull-request parameters: - "$ref": "#/components/parameters/owner" - "$ref": "#/components/parameters/repo" - "$ref": "#/components/parameters/pull-number" requestBody: required: false content: application/json: schema: type: object properties: commit_id: type: string description: The SHA of the commit that needs a review. Not using the latest commit SHA may render your review comment outdated if a subsequent commit modifies the line you specify as the `position`. Defaults to the most recent commit in the pull request when you do not specify a value. body: type: string description: "**Required** when using `REQUEST_CHANGES` or `COMMENT` for the `event` parameter. The body text of the pull request review." event: type: string description: 'The review action you want to perform. The review actions include: `APPROVE`, `REQUEST_CHANGES`, or `COMMENT`. By leaving this blank, you set the review action state to `PENDING`, which means you will need to [submit the pull request review](https://docs.github.com/enterprise-server@3.0/rest/reference/pulls#submit-a-review-for-a-pull-request) when you are ready.' enum: - APPROVE - REQUEST_CHANGES - COMMENT comments: type: array description: Use the following table to specify the location, destination, and contents of the draft review comment. items: type: object properties: path: type: string description: The relative path to the file that necessitates a review comment. position: type: integer description: The position in the diff where you want to add a review comment. Note this value is not the same as the line number in the file. For help finding the position value, read the note below. body: type: string description: Text of the review comment. line: type: integer examples: - 28 side: type: string examples: - RIGHT start_line: type: integer examples: - 26 start_side: type: string examples: - LEFT required: - path - body example: commit_id: ecdd80bb57125d7ba9641ffaa4d7d2c19d3f3091 body: This is close to perfect! Please address the suggested inline change. event: REQUEST_CHANGES comments: - path: file.md position: 6 body: Please add more information here, and fix this typo. responses: '200': description: Response content: application/json: schema: "$ref": "#/components/schemas/pull-request-review" examples: default: "$ref": "#/components/examples/pull-request-review" '422': "$ref": "#/components/responses/validation_failed_simple" '403': "$ref": "#/components/responses/forbidden" x-github: triggersNotification: true githubCloudOnly: false enabledForGitHubApps: true category: pulls subcategory: reviews "/repos/{owner}/{repo}/pulls/{pull_number}/reviews/{review_id}": get: summary: Get a review for a pull request description: '' tags: - pulls operationId: pulls/get-review externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/pulls#get-a-review-for-a-pull-request parameters: - "$ref": "#/components/parameters/owner" - "$ref": "#/components/parameters/repo" - "$ref": "#/components/parameters/pull-number" - "$ref": "#/components/parameters/review-id" responses: '200': description: Response content: application/json: schema: "$ref": "#/components/schemas/pull-request-review" examples: default: "$ref": "#/components/examples/pull-request-review-4" '404': "$ref": "#/components/responses/not_found" x-github: githubCloudOnly: false enabledForGitHubApps: true category: pulls subcategory: reviews put: summary: Update a review for a pull request description: Update the review summary comment with new text. tags: - pulls operationId: pulls/update-review externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/pulls#update-a-review-for-a-pull-request parameters: - "$ref": "#/components/parameters/owner" - "$ref": "#/components/parameters/repo" - "$ref": "#/components/parameters/pull-number" - "$ref": "#/components/parameters/review-id" requestBody: required: true content: application/json: schema: type: object properties: body: type: string description: The body text of the pull request review. required: - body example: body: This is close to perfect! Please address the suggested inline change. And add more about this. responses: '200': description: Response content: application/json: schema: "$ref": "#/components/schemas/pull-request-review" examples: default: "$ref": "#/components/examples/pull-request-review-5" '422': "$ref": "#/components/responses/validation_failed_simple" x-github: githubCloudOnly: false enabledForGitHubApps: true category: pulls subcategory: reviews delete: summary: Delete a pending review for a pull request description: '' tags: - pulls operationId: pulls/delete-pending-review externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/pulls#delete-a-pending-review-for-a-pull-request parameters: - "$ref": "#/components/parameters/owner" - "$ref": "#/components/parameters/repo" - "$ref": "#/components/parameters/pull-number" - "$ref": "#/components/parameters/review-id" responses: '200': description: Response content: application/json: schema: "$ref": "#/components/schemas/pull-request-review" examples: default: "$ref": "#/components/examples/pull-request-review" '422': "$ref": "#/components/responses/validation_failed_simple" '404': "$ref": "#/components/responses/not_found" x-github: githubCloudOnly: false enabledForGitHubApps: true category: pulls subcategory: reviews "/repos/{owner}/{repo}/pulls/{pull_number}/reviews/{review_id}/comments": get: summary: List comments for a pull request review description: List comments for a specific pull request review. tags: - pulls operationId: pulls/list-comments-for-review externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/pulls#list-comments-for-a-pull-request-review parameters: - "$ref": "#/components/parameters/owner" - "$ref": "#/components/parameters/repo" - "$ref": "#/components/parameters/pull-number" - "$ref": "#/components/parameters/review-id" - "$ref": "#/components/parameters/per-page" - "$ref": "#/components/parameters/page" responses: '200': description: Response content: application/json: schema: type: array items: "$ref": "#/components/schemas/review-comment" examples: default: "$ref": "#/components/examples/review-comment-items" headers: Link: "$ref": "#/components/headers/link" '404': "$ref": "#/components/responses/not_found" x-github: githubCloudOnly: false enabledForGitHubApps: true category: pulls subcategory: reviews "/repos/{owner}/{repo}/pulls/{pull_number}/reviews/{review_id}/dismissals": put: summary: Dismiss a review for a pull request description: "**Note:** To dismiss a pull request review on a [protected branch](https://docs.github.com/enterprise-server@3.0/rest/reference/repos#branches), you must be a repository administrator or be included in the list of people or teams who can dismiss pull request reviews." tags: - pulls operationId: pulls/dismiss-review externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/pulls#dismiss-a-review-for-a-pull-request parameters: - "$ref": "#/components/parameters/owner" - "$ref": "#/components/parameters/repo" - "$ref": "#/components/parameters/pull-number" - "$ref": "#/components/parameters/review-id" requestBody: required: true content: application/json: schema: type: object properties: message: type: string description: The message for the pull request review dismissal event: type: string examples: - '"APPROVE"' required: - message responses: '200': description: Response content: application/json: schema: "$ref": "#/components/schemas/pull-request-review" examples: default: "$ref": "#/components/examples/pull-request-review-3" '404': "$ref": "#/components/responses/not_found" '422': "$ref": "#/components/responses/validation_failed_simple" x-github: githubCloudOnly: false enabledForGitHubApps: true category: pulls subcategory: reviews "/repos/{owner}/{repo}/pulls/{pull_number}/reviews/{review_id}/events": post: summary: Submit a review for a pull request description: '' tags: - pulls operationId: pulls/submit-review externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/pulls#submit-a-review-for-a-pull-request parameters: - "$ref": "#/components/parameters/owner" - "$ref": "#/components/parameters/repo" - "$ref": "#/components/parameters/pull-number" - "$ref": "#/components/parameters/review-id" requestBody: required: true content: application/json: schema: type: object properties: body: type: string description: The body text of the pull request review event: type: string description: 'The review action you want to perform. The review actions include: `APPROVE`, `REQUEST_CHANGES`, or `COMMENT`. When you leave this blank, the API returns _HTTP 422 (Unrecognizable entity)_ and sets the review action state to `PENDING`, which means you will need to re-submit the pull request review using a review action.' enum: - APPROVE - REQUEST_CHANGES - COMMENT required: - event responses: '200': description: Response content: application/json: schema: "$ref": "#/components/schemas/pull-request-review" examples: default: "$ref": "#/components/examples/pull-request-review-4" '404': "$ref": "#/components/responses/not_found" '422': "$ref": "#/components/responses/validation_failed_simple" '403': "$ref": "#/components/responses/forbidden" x-github: githubCloudOnly: false enabledForGitHubApps: true category: pulls subcategory: reviews "/repos/{owner}/{repo}/pulls/{pull_number}/update-branch": put: summary: Update a pull request branch description: Updates the pull request branch with the latest upstream changes by merging HEAD from the base branch into the pull request branch. tags: - pulls operationId: pulls/update-branch externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/pulls#update-a-pull-request-branch parameters: - "$ref": "#/components/parameters/owner" - "$ref": "#/components/parameters/repo" - "$ref": "#/components/parameters/pull-number" requestBody: required: false content: application/json: schema: type: - object - 'null' properties: expected_head_sha: type: string description: 'The expected SHA of the pull request''s HEAD ref. This is the most recent commit on the pull request''s branch. If the expected SHA does not match the pull request''s HEAD, you will receive a `422 Unprocessable Entity` status. You can use the "[List commits](https://docs.github.com/enterprise-server@3.0/rest/reference/repos#list-commits)" endpoint to find the most recent commit SHA. Default: SHA of the pull request''s current HEAD ref.' example: expected_head_sha: 6dcb09b5b57875f334f61aebed695e2e4193db5e responses: '202': description: Response content: application/json: schema: type: object properties: message: type: string url: type: string example: message: Updating pull request branch. url: https://github.com/repos/octocat/Hello-World/pulls/53 '422': "$ref": "#/components/responses/validation_failed" '403': "$ref": "#/components/responses/forbidden" x-github: githubCloudOnly: false enabledForGitHubApps: false category: pulls previews: - required: true name: lydian note: |- Updating the pull request branch with latest upstream changes is currently available for developers to preview. To access this new endpoint during the preview period, you must provide a custom [media type](https://docs.github.com/enterprise-server@3.0/rest/overview/media-types) in the `Accept` header: ```shell application/vnd.github.lydian-preview+json ``` "/repos/{owner}/{repo}/readme": get: summary: Get a repository README description: |- Gets the preferred README for a repository. READMEs support [custom media types](https://docs.github.com/enterprise-server@3.0/rest/reference/repos#custom-media-types) for retrieving the raw content or rendered HTML. tags: - repos operationId: repos/get-readme externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/repos#get-a-repository-readme parameters: - "$ref": "#/components/parameters/owner" - "$ref": "#/components/parameters/repo" - name: ref description: 'The name of the commit/branch/tag. Default: the repository’s default branch (usually `master`)' in: query required: false schema: type: string responses: '200': description: Response content: application/json: schema: "$ref": "#/components/schemas/content-file" examples: default: "$ref": "#/components/examples/content-file" '404': "$ref": "#/components/responses/not_found" '422': "$ref": "#/components/responses/validation_failed" x-github: githubCloudOnly: false enabledForGitHubApps: true category: repos subcategory: contents "/repos/{owner}/{repo}/readme/{dir}": get: summary: Get a repository README for a directory description: |- Gets the README from a repository directory. READMEs support [custom media types](https://docs.github.com/enterprise-server@3.0/rest/reference/repos#custom-media-types) for retrieving the raw content or rendered HTML. tags: - repos operationId: repos/get-readme-in-directory externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/repos#get-a-repository-directory-readme parameters: - "$ref": "#/components/parameters/owner" - "$ref": "#/components/parameters/repo" - name: dir description: The alternate path to look for a README file in: path required: true schema: type: string x-multi-segment: true - name: ref description: 'The name of the commit/branch/tag. Default: the repository’s default branch (usually `master`)' in: query required: false schema: type: string responses: '200': description: Response content: application/json: schema: "$ref": "#/components/schemas/content-file" examples: default: "$ref": "#/components/examples/content-file" '404': "$ref": "#/components/responses/not_found" '422': "$ref": "#/components/responses/validation_failed" x-github: githubCloudOnly: false enabledForGitHubApps: true category: repos subcategory: contents "/repos/{owner}/{repo}/releases": get: summary: List releases description: |- This returns a list of releases, which does not include regular Git tags that have not been associated with a release. To get a list of Git tags, use the [Repository Tags API](https://docs.github.com/enterprise-server@3.0/rest/reference/repos#list-repository-tags). Information about published releases are available to everyone. Only users with push access will receive listings for draft releases. tags: - repos operationId: repos/list-releases externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/repos#list-releases parameters: - "$ref": "#/components/parameters/owner" - "$ref": "#/components/parameters/repo" - "$ref": "#/components/parameters/per-page" - "$ref": "#/components/parameters/page" responses: '200': description: Response content: application/json: schema: type: array items: "$ref": "#/components/schemas/release" examples: default: "$ref": "#/components/examples/release-items" headers: Link: "$ref": "#/components/headers/link" '404': "$ref": "#/components/responses/not_found" x-github: githubCloudOnly: false enabledForGitHubApps: true category: repos subcategory: releases post: summary: Create a release description: |- Users with push access to the repository can create a release. This endpoint triggers [notifications](https://docs.github.com/en/github/managing-subscriptions-and-notifications-on-github/about-notifications). Creating content too quickly using this endpoint may result in secondary rate limiting. See "[Secondary rate limits](https://docs.github.com/enterprise-server@3.0/rest/overview/resources-in-the-rest-api#secondary-rate-limits)" and "[Dealing with secondary rate limits](https://docs.github.com/enterprise-server@3.0/rest/guides/best-practices-for-integrators#dealing-with-secondary-rate-limits)" for details. tags: - repos operationId: repos/create-release externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/repos#create-a-release parameters: - "$ref": "#/components/parameters/owner" - "$ref": "#/components/parameters/repo" requestBody: required: true content: application/json: schema: type: object properties: tag_name: type: string description: The name of the tag. target_commitish: type: string description: 'Specifies the commitish value that determines where the Git tag is created from. Can be any branch or commit SHA. Unused if the Git tag already exists. Default: the repository''s default branch (usually `master`).' name: type: string description: The name of the release. body: type: string description: Text describing the contents of the tag. draft: type: boolean description: "`true` to create a draft (unpublished) release, `false` to create a published one." default: false prerelease: type: boolean description: "`true` to identify the release as a prerelease. `false` to identify the release as a full release." default: false required: - tag_name example: tag_name: v1.0.0 target_commitish: master name: v1.0.0 body: Description of the release draft: false prerelease: false responses: '201': description: Response content: application/json: schema: "$ref": "#/components/schemas/release" examples: default: "$ref": "#/components/examples/release" headers: Location: example: https://api.github.com/repos/octocat/Hello-World/releases/1 schema: type: string '422': "$ref": "#/components/responses/validation_failed" x-github: triggersNotification: true githubCloudOnly: false enabledForGitHubApps: true category: repos subcategory: releases "/repos/{owner}/{repo}/releases/assets/{asset_id}": get: summary: Get a release asset description: To download the asset's binary content, set the `Accept` header of the request to [`application/octet-stream`](https://docs.github.com/enterprise-server@3.0/rest/overview/media-types). The API will either redirect the client to the location, or stream it directly if possible. API clients should handle both a `200` or `302` response. tags: - repos operationId: repos/get-release-asset externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/repos#get-a-release-asset parameters: - "$ref": "#/components/parameters/owner" - "$ref": "#/components/parameters/repo" - "$ref": "#/components/parameters/asset-id" responses: '200': description: To download the asset's binary content, set the `Accept` header of the request to [`application/octet-stream`](https://docs.github.com/enterprise-server@3.0/rest/overview/media-types). The API will either redirect the client to the location, or stream it directly if possible. API clients should handle both a `200` or `302` response. content: application/json: schema: "$ref": "#/components/schemas/release-asset" examples: default: "$ref": "#/components/examples/release-asset" '404': "$ref": "#/components/responses/not_found" '415': "$ref": "#/components/responses/preview_header_missing" '302': "$ref": "#/components/responses/found" x-github: githubCloudOnly: false enabledForGitHubApps: true category: repos subcategory: releases patch: summary: Update a release asset description: Users with push access to the repository can edit a release asset. tags: - repos operationId: repos/update-release-asset externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/repos#update-a-release-asset parameters: - "$ref": "#/components/parameters/owner" - "$ref": "#/components/parameters/repo" - "$ref": "#/components/parameters/asset-id" requestBody: required: false content: application/json: schema: type: object properties: name: type: string description: The file name of the asset. label: type: string description: An alternate short description of the asset. Used in place of the filename. state: type: string examples: - '"uploaded"' example: name: foo-1.0.0-osx.zip label: Mac binary responses: '200': description: Response content: application/json: schema: "$ref": "#/components/schemas/release-asset" examples: default: "$ref": "#/components/examples/release-asset" x-github: githubCloudOnly: false enabledForGitHubApps: true category: repos subcategory: releases delete: summary: Delete a release asset description: '' tags: - repos operationId: repos/delete-release-asset externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/repos#delete-a-release-asset parameters: - "$ref": "#/components/parameters/owner" - "$ref": "#/components/parameters/repo" - "$ref": "#/components/parameters/asset-id" responses: '204': description: Response x-github: githubCloudOnly: false enabledForGitHubApps: true category: repos subcategory: releases "/repos/{owner}/{repo}/releases/latest": get: summary: Get the latest release description: |- View the latest published full release for the repository. The latest release is the most recent non-prerelease, non-draft release, sorted by the `created_at` attribute. The `created_at` attribute is the date of the commit used for the release, and not the date when the release was drafted or published. tags: - repos operationId: repos/get-latest-release externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/repos#get-the-latest-release parameters: - "$ref": "#/components/parameters/owner" - "$ref": "#/components/parameters/repo" responses: '200': description: Response content: application/json: schema: "$ref": "#/components/schemas/release" examples: default: "$ref": "#/components/examples/release" x-github: githubCloudOnly: false enabledForGitHubApps: true category: repos subcategory: releases "/repos/{owner}/{repo}/releases/tags/{tag}": get: summary: Get a release by tag name description: Get a published release with the specified tag. tags: - repos operationId: repos/get-release-by-tag externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/repos#get-a-release-by-tag-name parameters: - "$ref": "#/components/parameters/owner" - "$ref": "#/components/parameters/repo" - name: tag description: tag parameter in: path required: true schema: type: string x-multi-segment: true responses: '200': description: Response content: application/json: schema: "$ref": "#/components/schemas/release" examples: default: "$ref": "#/components/examples/release" '404': "$ref": "#/components/responses/not_found" x-github: githubCloudOnly: false enabledForGitHubApps: true category: repos subcategory: releases "/repos/{owner}/{repo}/releases/{release_id}": get: summary: Get a release description: "**Note:** This returns an `upload_url` key corresponding to the endpoint for uploading release assets. This key is a [hypermedia resource](https://docs.github.com/enterprise-server@3.0/rest/overview/resources-in-the-rest-api#hypermedia)." tags: - repos operationId: repos/get-release externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/repos#get-a-release parameters: - "$ref": "#/components/parameters/owner" - "$ref": "#/components/parameters/repo" - "$ref": "#/components/parameters/release-id" responses: '200': description: "**Note:** This returns an `upload_url` key corresponding to the endpoint for uploading release assets. This key is a [hypermedia resource](https://docs.github.com/enterprise-server@3.0/rest/overview/resources-in-the-rest-api#hypermedia)." content: application/json: schema: "$ref": "#/components/schemas/release" examples: default: "$ref": "#/components/examples/release" '404': "$ref": "#/components/responses/not_found" x-github: githubCloudOnly: false enabledForGitHubApps: true category: repos subcategory: releases patch: summary: Update a release description: Users with push access to the repository can edit a release. tags: - repos operationId: repos/update-release externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/repos#update-a-release parameters: - "$ref": "#/components/parameters/owner" - "$ref": "#/components/parameters/repo" - "$ref": "#/components/parameters/release-id" requestBody: required: false content: application/json: schema: type: object properties: tag_name: type: string description: The name of the tag. target_commitish: type: string description: 'Specifies the commitish value that determines where the Git tag is created from. Can be any branch or commit SHA. Unused if the Git tag already exists. Default: the repository''s default branch (usually `master`).' name: type: string description: The name of the release. body: type: string description: Text describing the contents of the tag. draft: type: boolean description: "`true` makes the release a draft, and `false` publishes the release." prerelease: type: boolean description: "`true` to identify the release as a prerelease, `false` to identify the release as a full release." example: tag_name: v1.0.0 target_commitish: master name: v1.0.0 body: Description of the release draft: false prerelease: false responses: '200': description: Response content: application/json: schema: "$ref": "#/components/schemas/release" examples: default: "$ref": "#/components/examples/release" x-github: githubCloudOnly: false enabledForGitHubApps: true category: repos subcategory: releases delete: summary: Delete a release description: Users with push access to the repository can delete a release. tags: - repos operationId: repos/delete-release externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/repos#delete-a-release parameters: - "$ref": "#/components/parameters/owner" - "$ref": "#/components/parameters/repo" - "$ref": "#/components/parameters/release-id" responses: '204': description: Response x-github: githubCloudOnly: false enabledForGitHubApps: true category: repos subcategory: releases "/repos/{owner}/{repo}/releases/{release_id}/assets": get: summary: List release assets description: '' tags: - repos operationId: repos/list-release-assets externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/repos#list-release-assets parameters: - "$ref": "#/components/parameters/owner" - "$ref": "#/components/parameters/repo" - "$ref": "#/components/parameters/release-id" - "$ref": "#/components/parameters/per-page" - "$ref": "#/components/parameters/page" responses: '200': description: Response content: application/json: schema: type: array items: "$ref": "#/components/schemas/release-asset" examples: default: "$ref": "#/components/examples/release-asset-items" headers: Link: "$ref": "#/components/headers/link" x-github: githubCloudOnly: false enabledForGitHubApps: true category: repos subcategory: releases post: summary: Upload a release asset description: "This endpoint makes use of [a Hypermedia relation](https://docs.github.com/enterprise-server@3.0/rest/overview/resources-in-the-rest-api#hypermedia) to determine which URL to access. The endpoint you call to upload release assets is specific to your release. Use the `upload_url` returned in\nthe response of the [Create a release endpoint](https://docs.github.com/enterprise-server@3.0/rest/reference/repos#create-a-release) to upload a release asset.\n\nYou need to use an HTTP client which supports [SNI](http://en.wikipedia.org/wiki/Server_Name_Indication) to make calls to this endpoint.\n\nMost libraries will set the required `Content-Length` header automatically. Use the required `Content-Type` header to provide the media type of the asset. For a list of media types, see [Media Types](https://www.iana.org/assignments/media-types/media-types.xhtml). For example: \n\n`application/zip`\n\nGitHub Enterprise Server expects the asset data in its raw binary form, rather than JSON. You will send the raw binary content of the asset as the request body. Everything else about the endpoint is the same as the rest of the API. For example,\nyou'll still need to pass your authentication to be able to upload an asset.\n\nWhen an upstream failure occurs, you will receive a `502 Bad Gateway` status. This may leave an empty asset with a state of `starter`. It can be safely deleted.\n\n**Notes:**\n* \ GitHub Enterprise Server renames asset filenames that have special characters, non-alphanumeric characters, and leading or trailing periods. The \"[List assets for a release](https://docs.github.com/enterprise-server@3.0/rest/reference/repos#list-assets-for-a-release)\"\nendpoint lists the renamed filenames. For more information and help, contact [GitHub Enterprise Server Support](https://support.github.com/contact?tags=dotcom-rest-api).\n* \ If you upload an asset with the same filename as another uploaded asset, you'll receive an error and must delete the old file before you can re-upload the new asset." tags: - repos operationId: repos/upload-release-asset externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/repos#upload-a-release-asset servers: - url: "{origin}" variables: origin: default: https://uploads.github.com description: The URL origin (protocol + host name + port) is included in `upload_url` returned in the response of the "Create a release" endpoint parameters: - "$ref": "#/components/parameters/owner" - "$ref": "#/components/parameters/repo" - "$ref": "#/components/parameters/release-id" - name: name in: query required: true schema: type: string - name: label in: query schema: type: string requestBody: required: false content: "*/*": schema: type: string description: The raw file data responses: '201': description: Response for successful upload content: application/json: schema: "$ref": "#/components/schemas/release-asset" examples: response-for-successful-upload: "$ref": "#/components/examples/release-asset-response-for-successful-upload" '422': description: Response if you upload an asset with the same filename as another uploaded asset x-github: githubCloudOnly: false enabledForGitHubApps: true category: repos subcategory: releases "/repos/{owner}/{repo}/stargazers": get: summary: List stargazers description: |- Lists the people that have starred the repository. You can also find out _when_ stars were created by passing the following custom [media type](https://docs.github.com/enterprise-server@3.0/rest/overview/media-types/) via the `Accept` header: tags: - activity operationId: activity/list-stargazers-for-repo externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/activity#list-stargazers parameters: - "$ref": "#/components/parameters/owner" - "$ref": "#/components/parameters/repo" - "$ref": "#/components/parameters/per-page" - "$ref": "#/components/parameters/page" responses: '200': description: Response content: application/json: schema: anyOf: - type: array items: "$ref": "#/components/schemas/simple-user" - type: array items: "$ref": "#/components/schemas/stargazer" examples: default-response: "$ref": "#/components/examples/simple-user-items-default-response" alternative-response-with-star-creation-timestamps: "$ref": "#/components/examples/stargazer-items-alternative-response-with-star-creation-timestamps" headers: Link: "$ref": "#/components/headers/link" '422': "$ref": "#/components/responses/validation_failed" x-github: githubCloudOnly: false enabledForGitHubApps: true category: activity subcategory: starring "/repos/{owner}/{repo}/stats/code_frequency": get: summary: Get the weekly commit activity description: Returns a weekly aggregate of the number of additions and deletions pushed to a repository. tags: - repos operationId: repos/get-code-frequency-stats externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/repos#get-the-weekly-commit-activity parameters: - "$ref": "#/components/parameters/owner" - "$ref": "#/components/parameters/repo" responses: '200': description: Returns a weekly aggregate of the number of additions and deletions pushed to a repository. content: application/json: schema: type: array items: "$ref": "#/components/schemas/code-frequency-stat" examples: default: "$ref": "#/components/examples/code-frequency-stat-items" '202': "$ref": "#/components/responses/accepted" '204': "$ref": "#/components/responses/no_content" x-github: githubCloudOnly: false enabledForGitHubApps: true category: repos subcategory: statistics "/repos/{owner}/{repo}/stats/commit_activity": get: summary: Get the last year of commit activity description: Returns the last year of commit activity grouped by week. The `days` array is a group of commits per day, starting on `Sunday`. tags: - repos operationId: repos/get-commit-activity-stats externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/repos#get-the-last-year-of-commit-activity parameters: - "$ref": "#/components/parameters/owner" - "$ref": "#/components/parameters/repo" responses: '200': description: Response content: application/json: schema: type: array items: "$ref": "#/components/schemas/commit-activity" examples: default: "$ref": "#/components/examples/commit-activity-items" '202': "$ref": "#/components/responses/accepted" '204': "$ref": "#/components/responses/no_content" x-github: githubCloudOnly: false enabledForGitHubApps: true category: repos subcategory: statistics "/repos/{owner}/{repo}/stats/contributors": get: summary: Get all contributor commit activity description: |2- Returns the `total` number of commits authored by the contributor. In addition, the response includes a Weekly Hash (`weeks` array) with the following information: * `w` - Start of the week, given as a [Unix timestamp](http://en.wikipedia.org/wiki/Unix_time). * `a` - Number of additions * `d` - Number of deletions * `c` - Number of commits tags: - repos operationId: repos/get-contributors-stats externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/repos#get-all-contributor-commit-activity parameters: - "$ref": "#/components/parameters/owner" - "$ref": "#/components/parameters/repo" responses: '200': description: |- * `w` - Start of the week, given as a [Unix timestamp](http://en.wikipedia.org/wiki/Unix_time). * `a` - Number of additions * `d` - Number of deletions * `c` - Number of commits content: application/json: schema: type: array items: "$ref": "#/components/schemas/contributor-activity" examples: default: "$ref": "#/components/examples/contributor-activity-items" '202': "$ref": "#/components/responses/accepted" '204': "$ref": "#/components/responses/no_content" x-github: githubCloudOnly: false enabledForGitHubApps: true category: repos subcategory: statistics "/repos/{owner}/{repo}/stats/participation": get: summary: Get the weekly commit count description: |- Returns the total commit counts for the `owner` and total commit counts in `all`. `all` is everyone combined, including the `owner` in the last 52 weeks. If you'd like to get the commit counts for non-owners, you can subtract `owner` from `all`. The array order is oldest week (index 0) to most recent week. tags: - repos operationId: repos/get-participation-stats externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/repos#get-the-weekly-commit-count parameters: - "$ref": "#/components/parameters/owner" - "$ref": "#/components/parameters/repo" responses: '200': description: The array order is oldest week (index 0) to most recent week. content: application/json: schema: "$ref": "#/components/schemas/participation-stats" examples: default: "$ref": "#/components/examples/participation-stats" '404': "$ref": "#/components/responses/not_found" x-github: githubCloudOnly: false enabledForGitHubApps: true category: repos subcategory: statistics "/repos/{owner}/{repo}/stats/punch_card": get: summary: Get the hourly commit count for each day description: |- Each array contains the day number, hour number, and number of commits: * `0-6`: Sunday - Saturday * `0-23`: Hour of day * Number of commits For example, `[2, 14, 25]` indicates that there were 25 total commits, during the 2:00pm hour on Tuesdays. All times are based on the time zone of individual commits. tags: - repos operationId: repos/get-punch-card-stats externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/repos#get-the-hourly-commit-count-for-each-day parameters: - "$ref": "#/components/parameters/owner" - "$ref": "#/components/parameters/repo" responses: '200': description: For example, `[2, 14, 25]` indicates that there were 25 total commits, during the 2:00pm hour on Tuesdays. All times are based on the time zone of individual commits. content: application/json: schema: type: array items: "$ref": "#/components/schemas/code-frequency-stat" examples: default: "$ref": "#/components/examples/code-frequency-stat-items-2" '204': "$ref": "#/components/responses/no_content" x-github: githubCloudOnly: false enabledForGitHubApps: true category: repos subcategory: statistics "/repos/{owner}/{repo}/statuses/{sha}": post: summary: Create a commit status description: |- Users with push access in a repository can create commit statuses for a given SHA. Note: there is a limit of 1000 statuses per `sha` and `context` within a repository. Attempts to create more than 1000 statuses will result in a validation error. tags: - repos operationId: repos/create-commit-status externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/repos#create-a-commit-status parameters: - "$ref": "#/components/parameters/owner" - "$ref": "#/components/parameters/repo" - name: sha in: path required: true schema: type: string x-multi-segment: true requestBody: required: true content: application/json: schema: type: object properties: state: type: string description: The state of the status. Can be one of `error`, `failure`, `pending`, or `success`. enum: - error - failure - pending - success target_url: type: string description: "The target URL to associate with this status. This URL will be linked from the GitHub UI to allow users to easily see the source of the status. \nFor example, if your continuous integration system is posting build status, you would want to provide the deep link for the build output for this specific SHA: \ \n`http://ci.example.com/user/repo/build/sha`" description: type: string description: A short description of the status. context: type: string description: A string label to differentiate this status from the status of other systems. This field is case-insensitive. default: default required: - state example: state: success target_url: https://example.com/build/status description: The build succeeded! context: continuous-integration/jenkins responses: '201': description: Response content: application/json: schema: "$ref": "#/components/schemas/status" examples: default: "$ref": "#/components/examples/status" headers: Location: example: https://api.github.com/repos/octocat/Hello-World/statuses/6dcb09b5b57875f334f61aebed695e2e4193db5e schema: type: string x-github: githubCloudOnly: false enabledForGitHubApps: true category: repos subcategory: statuses "/repos/{owner}/{repo}/subscribers": get: summary: List watchers description: Lists the people watching the specified repository. tags: - activity operationId: activity/list-watchers-for-repo externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/activity#list-watchers parameters: - "$ref": "#/components/parameters/owner" - "$ref": "#/components/parameters/repo" - "$ref": "#/components/parameters/per-page" - "$ref": "#/components/parameters/page" responses: '200': description: Response content: application/json: schema: type: array items: "$ref": "#/components/schemas/simple-user" examples: default: "$ref": "#/components/examples/simple-user-items" headers: Link: "$ref": "#/components/headers/link" x-github: githubCloudOnly: false enabledForGitHubApps: true category: activity subcategory: watching "/repos/{owner}/{repo}/subscription": get: summary: Get a repository subscription description: '' tags: - activity operationId: activity/get-repo-subscription externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/activity#get-a-repository-subscription parameters: - "$ref": "#/components/parameters/owner" - "$ref": "#/components/parameters/repo" responses: '200': description: if you subscribe to the repository content: application/json: schema: "$ref": "#/components/schemas/repository-subscription" examples: response-if-you-subscribe-to-the-repository: "$ref": "#/components/examples/repository-subscription-response-if-you-subscribe-to-the-repository" '404': description: Not Found if you don't subscribe to the repository '403': "$ref": "#/components/responses/forbidden" x-github: githubCloudOnly: false enabledForGitHubApps: false category: activity subcategory: watching put: summary: Set a repository subscription description: If you would like to watch a repository, set `subscribed` to `true`. If you would like to ignore notifications made within a repository, set `ignored` to `true`. If you would like to stop watching a repository, [delete the repository's subscription](https://docs.github.com/enterprise-server@3.0/rest/reference/activity#delete-a-repository-subscription) completely. tags: - activity operationId: activity/set-repo-subscription externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/activity#set-a-repository-subscription parameters: - "$ref": "#/components/parameters/owner" - "$ref": "#/components/parameters/repo" requestBody: required: false content: application/json: schema: type: object properties: subscribed: type: boolean description: Determines if notifications should be received from this repository. ignored: type: boolean description: Determines if all notifications should be blocked from this repository. responses: '200': description: Response content: application/json: schema: "$ref": "#/components/schemas/repository-subscription" examples: default: "$ref": "#/components/examples/repository-subscription" x-github: githubCloudOnly: false enabledForGitHubApps: false category: activity subcategory: watching delete: summary: Delete a repository subscription description: This endpoint should only be used to stop watching a repository. To control whether or not you wish to receive notifications from a repository, [set the repository's subscription manually](https://docs.github.com/enterprise-server@3.0/rest/reference/activity#set-a-repository-subscription). tags: - activity operationId: activity/delete-repo-subscription externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/activity#delete-a-repository-subscription parameters: - "$ref": "#/components/parameters/owner" - "$ref": "#/components/parameters/repo" responses: '204': description: Response x-github: githubCloudOnly: false enabledForGitHubApps: false category: activity subcategory: watching "/repos/{owner}/{repo}/tags": get: summary: List repository tags description: '' tags: - repos operationId: repos/list-tags externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/repos#list-repository-tags parameters: - "$ref": "#/components/parameters/owner" - "$ref": "#/components/parameters/repo" - "$ref": "#/components/parameters/per-page" - "$ref": "#/components/parameters/page" responses: '200': description: Response content: application/json: schema: type: array items: "$ref": "#/components/schemas/tag" examples: default: "$ref": "#/components/examples/tag-items" headers: Link: "$ref": "#/components/headers/link" x-github: githubCloudOnly: false enabledForGitHubApps: true category: repos subcategory: "/repos/{owner}/{repo}/tarball/{ref}": get: summary: Download a repository archive (tar) description: |- Gets a redirect URL to download a tar archive for a repository. If you omit `:ref`, the repository’s default branch (usually `master`) will be used. Please make sure your HTTP framework is configured to follow redirects or you will need to use the `Location` header to make a second `GET` request. **Note**: For private repositories, these links are temporary and expire after five minutes. tags: - repos externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/repos#download-a-repository-archive operationId: repos/download-tarball-archive parameters: - "$ref": "#/components/parameters/owner" - "$ref": "#/components/parameters/repo" - name: ref in: path required: true schema: type: string responses: '302': description: Response headers: Location: example: https://codeload.github.com/me/myprivate/legacy.zip/master?login=me&token=thistokenexpires schema: type: string x-github: githubCloudOnly: false enabledForGitHubApps: true category: repos subcategory: contents "/repos/{owner}/{repo}/teams": get: summary: List repository teams description: '' tags: - repos operationId: repos/list-teams externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/repos#list-repository-teams parameters: - "$ref": "#/components/parameters/owner" - "$ref": "#/components/parameters/repo" - "$ref": "#/components/parameters/per-page" - "$ref": "#/components/parameters/page" responses: '200': description: Response content: application/json: schema: type: array items: "$ref": "#/components/schemas/team" examples: default: "$ref": "#/components/examples/team-items" headers: Link: "$ref": "#/components/headers/link" x-github: githubCloudOnly: false enabledForGitHubApps: true category: repos subcategory: "/repos/{owner}/{repo}/topics": get: summary: Get all repository topics description: '' tags: - repos operationId: repos/get-all-topics externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/repos#get-all-repository-topics parameters: - "$ref": "#/components/parameters/owner" - "$ref": "#/components/parameters/repo" - "$ref": "#/components/parameters/page" - "$ref": "#/components/parameters/per-page" responses: '200': description: Response content: application/json: schema: "$ref": "#/components/schemas/topic" examples: default: "$ref": "#/components/examples/topic" '404': "$ref": "#/components/responses/not_found" '415': "$ref": "#/components/responses/preview_header_missing" x-github: githubCloudOnly: false enabledForGitHubApps: true category: repos previews: - required: true name: mercy note: |- The `topics` property for repositories on GitHub is currently available for developers to preview. To view the `topics` property in calls that return repository results, you must provide a custom [media type](https://docs.github.com/enterprise-server@3.0/rest/overview/media-types) in the `Accept` header: ```shell application/vnd.github.mercy-preview+json ``` put: summary: Replace all repository topics description: '' tags: - repos operationId: repos/replace-all-topics externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/repos#replace-all-repository-topics parameters: - "$ref": "#/components/parameters/owner" - "$ref": "#/components/parameters/repo" requestBody: required: true content: application/json: schema: type: object properties: names: type: array description: An array of topics to add to the repository. Pass one or more topics to _replace_ the set of existing topics. Send an empty array (`[]`) to clear all topics from the repository. **Note:** Topic `names` cannot contain uppercase letters. items: type: string required: - names example: names: - octocat - atom - electron - api responses: '200': description: Response content: application/json: schema: "$ref": "#/components/schemas/topic" examples: default: "$ref": "#/components/examples/topic" '404': "$ref": "#/components/responses/not_found" '422': "$ref": "#/components/responses/validation_failed_simple" '415': "$ref": "#/components/responses/preview_header_missing" x-github: githubCloudOnly: false enabledForGitHubApps: true category: repos previews: - required: true name: mercy note: |- The `topics` property for repositories on GitHub is currently available for developers to preview. To view the `topics` property in calls that return repository results, you must provide a custom [media type](https://docs.github.com/enterprise-server@3.0/rest/overview/media-types) in the `Accept` header: ```shell application/vnd.github.mercy-preview+json ``` "/repos/{owner}/{repo}/transfer": post: summary: Transfer a repository description: A transfer request will need to be accepted by the new owner when transferring a personal repository to another user. The response will contain the original `owner`, and the transfer will continue asynchronously. For more details on the requirements to transfer personal and organization-owned repositories, see [about repository transfers](https://docs.github.com/articles/about-repository-transfers/). tags: - repos operationId: repos/transfer externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/repos#transfer-a-repository parameters: - "$ref": "#/components/parameters/owner" - "$ref": "#/components/parameters/repo" requestBody: required: true content: application/json: schema: type: object properties: new_owner: type: string description: The username or organization name the repository will be transferred to. team_ids: type: array description: ID of the team or teams to add to the repository. Teams can only be added to organization-owned repositories. items: type: integer required: - new_owner example: new_owner: github team_ids: - 12 - 345 responses: '202': description: Response content: application/json: schema: "$ref": "#/components/schemas/minimal-repository" examples: default: "$ref": "#/components/examples/minimal-repository" x-github: githubCloudOnly: false enabledForGitHubApps: true category: repos subcategory: "/repos/{owner}/{repo}/zipball/{ref}": get: summary: Download a repository archive (zip) description: |- Gets a redirect URL to download a zip archive for a repository. If you omit `:ref`, the repository’s default branch (usually `master`) will be used. Please make sure your HTTP framework is configured to follow redirects or you will need to use the `Location` header to make a second `GET` request. **Note**: For private repositories, these links are temporary and expire after five minutes. tags: - repos externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/repos#download-a-repository-archive operationId: repos/download-zipball-archive parameters: - "$ref": "#/components/parameters/owner" - "$ref": "#/components/parameters/repo" - name: ref in: path required: true schema: type: string responses: '302': description: Response headers: Location: example: https://codeload.github.com/me/myprivate/legacy.zip/master?login=me&token=thistokenexpires schema: type: string x-github: githubCloudOnly: false enabledForGitHubApps: true category: repos subcategory: contents "/repos/{template_owner}/{template_repo}/generate": post: summary: Create a repository using a template description: |- Creates a new repository using a repository template. Use the `template_owner` and `template_repo` route parameters to specify the repository to use as the template. The authenticated user must own or be a member of an organization that owns the repository. To check if a repository is available to use as a template, get the repository's information using the [Get a repository](https://docs.github.com/enterprise-server@3.0/rest/reference/repos#get-a-repository) endpoint and check that the `is_template` key is `true`. **OAuth scope requirements** When using [OAuth](https://docs.github.com/enterprise-server@3.0/apps/building-oauth-apps/understanding-scopes-for-oauth-apps/), authorizations must include: * `public_repo` scope or `repo` scope to create a public repository. Note: For GitHub AE, use `repo` scope to create an internal repository. * `repo` scope to create a private repository tags: - repos operationId: repos/create-using-template externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/repos#create-a-repository-using-a-template parameters: - name: template_owner in: path required: true schema: type: string - name: template_repo in: path required: true schema: type: string requestBody: required: true content: application/json: schema: type: object properties: owner: type: string description: The organization or person who will own the new repository. To create a new repository in an organization, the authenticated user must be a member of the specified organization. name: type: string description: The name of the new repository. description: type: string description: A short description of the new repository. include_all_branches: type: boolean description: 'Set to `true` to include the directory structure and files from all branches in the template repository, and not just the default branch. Default: `false`.' default: false private: type: boolean description: Either `true` to create a new private repository or `false` to create a new public one. default: false required: - name example: owner: octocat name: Hello-World description: This is your first repository include_all_branches: false private: false responses: '201': description: Response content: application/json: schema: "$ref": "#/components/schemas/repository" examples: default: "$ref": "#/components/examples/repository-3" headers: Location: example: https://api.github.com/repos/octocat/Hello-World schema: type: string x-github: githubCloudOnly: false enabledForGitHubApps: false category: repos previews: - required: true name: baptiste note: |- Creating and using repository templates is currently available for developers to preview. To access this new endpoint during the preview period, you must provide a custom [media type](https://docs.github.com/enterprise-server@3.0/rest/overview/media-types) in the `Accept` header: ```shell application/vnd.github.baptiste-preview+json ``` "/repositories": get: summary: List public repositories description: |- Lists all public repositories in the order that they were created. Note: - For GitHub Enterprise Server, this endpoint will only list repositories available to all users on the enterprise. - Pagination is powered exclusively by the `since` parameter. Use the [Link header](https://docs.github.com/enterprise-server@3.0/rest/overview/resources-in-the-rest-api#link-header) to get the URL for the next page of repositories. tags: - repos operationId: repos/list-public externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/repos#list-public-repositories parameters: - "$ref": "#/components/parameters/since-repo" - name: visibility description: 'Specifies the types of repositories to return. Can be one of `all` or `public`. Default: `public`. Note: For GitHub Enterprise Server and GitHub AE, this endpoint will only list repositories available to all users on the enterprise.' in: query required: false schema: type: string default: public enum: - all - public examples: - all responses: '200': description: Response content: application/json: schema: type: array items: "$ref": "#/components/schemas/minimal-repository" examples: default: "$ref": "#/components/examples/public-repository-items" headers: Link: example: ; rel="next" schema: type: string '422': "$ref": "#/components/responses/validation_failed" '304': "$ref": "#/components/responses/not_modified" x-github: githubCloudOnly: false enabledForGitHubApps: true category: repos subcategory: "/search/code": get: summary: Search code description: |- Searches for query terms inside of a file. This method returns up to 100 results [per page](https://docs.github.com/enterprise-server@3.0/rest/overview/resources-in-the-rest-api#pagination). When searching for code, you can get text match metadata for the file **content** and file **path** fields when you pass the `text-match` media type. For more details about how to receive highlighted search results, see [Text match metadata](https://docs.github.com/enterprise-server@3.0/rest/reference/search#text-match-metadata). For example, if you want to find the definition of the `addClass` function inside [jQuery](https://github.com/jquery/jquery) repository, your query would look something like this: `q=addClass+in:file+language:js+repo:jquery/jquery` This query searches for the keyword `addClass` within a file's contents. The query limits the search to files where the language is JavaScript in the `jquery/jquery` repository. #### Considerations for code search Due to the complexity of searching code, there are a few restrictions on how searches are performed: * Only the _default branch_ is considered. In most cases, this will be the `master` branch. * Only files smaller than 384 KB are searchable. * You must always include at least one search term when searching source code. For example, searching for [`language:go`](https://github.com/search?utf8=%E2%9C%93&q=language%3Ago&type=Code) is not valid, while [`amazing language:go`](https://github.com/search?utf8=%E2%9C%93&q=amazing+language%3Ago&type=Code) is. tags: - search operationId: search/code externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/search#search-code parameters: - name: q description: The query contains one or more search keywords and qualifiers. Qualifiers allow you to limit your search to specific areas of GitHub. The REST API supports the same qualifiers as GitHub.com. To learn more about the format of the query, see [Constructing a search query](https://docs.github.com/enterprise-server@3.0/rest/reference/search#constructing-a-search-query). See "[Searching code](https://docs.github.com/articles/searching-code/)" for a detailed list of qualifiers. in: query required: true schema: type: string - name: sort description: 'Sorts the results of your query. Can only be `indexed`, which indicates how recently a file has been indexed by the GitHub Enterprise Server search infrastructure. Default: [best match](https://docs.github.com/enterprise-server@3.0/rest/reference/search#ranking-search-results)' in: query required: false schema: type: string enum: - indexed - "$ref": "#/components/parameters/order" - "$ref": "#/components/parameters/per-page" - "$ref": "#/components/parameters/page" responses: '200': description: Response content: application/json: schema: type: object required: - total_count - incomplete_results - items properties: total_count: type: integer incomplete_results: type: boolean items: type: array items: "$ref": "#/components/schemas/code-search-result-item" examples: default: "$ref": "#/components/examples/code-search-result-item-paginated" '304': "$ref": "#/components/responses/not_modified" '503': "$ref": "#/components/responses/service_unavailable" '422': "$ref": "#/components/responses/validation_failed" '403': "$ref": "#/components/responses/forbidden" x-github: githubCloudOnly: false enabledForGitHubApps: true category: search subcategory: "/search/commits": get: summary: Search commits description: |- Find commits via various criteria on the default branch (usually `master`). This method returns up to 100 results [per page](https://docs.github.com/enterprise-server@3.0/rest/overview/resources-in-the-rest-api#pagination). When searching for commits, you can get text match metadata for the **message** field when you provide the `text-match` media type. For more details about how to receive highlighted search results, see [Text match metadata](https://docs.github.com/enterprise-server@3.0/rest/reference/search#text-match-metadata). For example, if you want to find commits related to CSS in the [octocat/Spoon-Knife](https://github.com/octocat/Spoon-Knife) repository. Your query would look something like this: `q=repo:octocat/Spoon-Knife+css` tags: - search operationId: search/commits externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/search#search-commits parameters: - name: q description: The query contains one or more search keywords and qualifiers. Qualifiers allow you to limit your search to specific areas of GitHub. The REST API supports the same qualifiers as GitHub.com. To learn more about the format of the query, see [Constructing a search query](https://docs.github.com/enterprise-server@3.0/rest/reference/search#constructing-a-search-query). See "[Searching commits](https://docs.github.com/articles/searching-commits/)" for a detailed list of qualifiers. in: query required: true schema: type: string - name: sort description: 'Sorts the results of your query by `author-date` or `committer-date`. Default: [best match](https://docs.github.com/enterprise-server@3.0/rest/reference/search#ranking-search-results)' in: query required: false schema: type: string enum: - author-date - committer-date - "$ref": "#/components/parameters/order" - "$ref": "#/components/parameters/per-page" - "$ref": "#/components/parameters/page" responses: '200': description: Response content: application/json: schema: type: object required: - total_count - incomplete_results - items properties: total_count: type: integer incomplete_results: type: boolean items: type: array items: "$ref": "#/components/schemas/commit-search-result-item" examples: default: "$ref": "#/components/examples/commit-search-result-item-paginated" '304': "$ref": "#/components/responses/not_modified" x-github: githubCloudOnly: false enabledForGitHubApps: true category: search previews: - required: true name: cloak note: |- The Commit Search API is currently available for developers to preview. During the preview period, the APIs may change without advance notice. Please see the [blog post](https://developer.github.com/changes/2017-01-05-commit-search-api/) for full details. To access the API you must provide a custom [media type](https://docs.github.com/enterprise-server@3.0/rest/overview/media-types) in the `Accept` header: ```shell application/vnd.github.cloak-preview ``` "/search/issues": get: summary: Search issues and pull requests description: |- Find issues by state and keyword. This method returns up to 100 results [per page](https://docs.github.com/enterprise-server@3.0/rest/overview/resources-in-the-rest-api#pagination). When searching for issues, you can get text match metadata for the issue **title**, issue **body**, and issue **comment body** fields when you pass the `text-match` media type. For more details about how to receive highlighted search results, see [Text match metadata](https://docs.github.com/enterprise-server@3.0/rest/reference/search#text-match-metadata). For example, if you want to find the oldest unresolved Python bugs on Windows. Your query might look something like this. `q=windows+label:bug+language:python+state:open&sort=created&order=asc` This query searches for the keyword `windows`, within any open issue that is labeled as `bug`. The search runs across repositories whose primary language is Python. The results are sorted by creation date in ascending order, which means the oldest issues appear first in the search results. **Note:** For [user-to-server](https://docs.github.com/developers/apps/identifying-and-authorizing-users-for-github-apps#user-to-server-requests) GitHub App requests, you can't retrieve a combination of issues and pull requests in a single query. Requests that don't include the `is:issue` or `is:pull-request` qualifier will receive an HTTP `422 Unprocessable Entity` response. To get results for both issues and pull requests, you must send separate queries for issues and pull requests. For more information about the `is` qualifier, see "[Searching only issues or pull requests](https://docs.github.com/github/searching-for-information-on-github/searching-issues-and-pull-requests#search-only-issues-or-pull-requests)." tags: - search operationId: search/issues-and-pull-requests externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/search#search-issues-and-pull-requests parameters: - name: q description: The query contains one or more search keywords and qualifiers. Qualifiers allow you to limit your search to specific areas of GitHub. The REST API supports the same qualifiers as GitHub.com. To learn more about the format of the query, see [Constructing a search query](https://docs.github.com/enterprise-server@3.0/rest/reference/search#constructing-a-search-query). See "[Searching issues and pull requests](https://docs.github.com/articles/searching-issues-and-pull-requests/)" for a detailed list of qualifiers. in: query required: true schema: type: string - name: sort description: 'Sorts the results of your query by the number of `comments`, `reactions`, `reactions-+1`, `reactions--1`, `reactions-smile`, `reactions-thinking_face`, `reactions-heart`, `reactions-tada`, or `interactions`. You can also sort results by how recently the items were `created` or `updated`, Default: [best match](https://docs.github.com/enterprise-server@3.0/rest/reference/search#ranking-search-results)' in: query required: false schema: type: string enum: - comments - reactions - reactions-+1 - reactions--1 - reactions-smile - reactions-thinking_face - reactions-heart - reactions-tada - interactions - created - updated - "$ref": "#/components/parameters/order" - "$ref": "#/components/parameters/per-page" - "$ref": "#/components/parameters/page" responses: '200': description: Response content: application/json: schema: type: object required: - total_count - incomplete_results - items properties: total_count: type: integer incomplete_results: type: boolean items: type: array items: "$ref": "#/components/schemas/issue-search-result-item" examples: default: "$ref": "#/components/examples/issue-search-result-item-paginated" '503': "$ref": "#/components/responses/service_unavailable" '422': "$ref": "#/components/responses/validation_failed" '304': "$ref": "#/components/responses/not_modified" '403': "$ref": "#/components/responses/forbidden" x-github: githubCloudOnly: false enabledForGitHubApps: true category: search subcategory: "/search/labels": get: summary: Search labels description: |- Find labels in a repository with names or descriptions that match search keywords. Returns up to 100 results [per page](https://docs.github.com/enterprise-server@3.0/rest/overview/resources-in-the-rest-api#pagination). When searching for labels, you can get text match metadata for the label **name** and **description** fields when you pass the `text-match` media type. For more details about how to receive highlighted search results, see [Text match metadata](https://docs.github.com/enterprise-server@3.0/rest/reference/search#text-match-metadata). For example, if you want to find labels in the `linguist` repository that match `bug`, `defect`, or `enhancement`. Your query might look like this: `q=bug+defect+enhancement&repository_id=64778136` The labels that best match the query appear first in the search results. tags: - search operationId: search/labels externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/search#search-labels parameters: - name: repository_id description: The id of the repository. in: query required: true schema: type: integer - name: q description: The search keywords. This endpoint does not accept qualifiers in the query. To learn more about the format of the query, see [Constructing a search query](https://docs.github.com/enterprise-server@3.0/rest/reference/search#constructing-a-search-query). in: query required: true schema: type: string - name: sort description: 'Sorts the results of your query by when the label was `created` or `updated`. Default: [best match](https://docs.github.com/enterprise-server@3.0/rest/reference/search#ranking-search-results)' in: query required: false schema: type: string enum: - created - updated - "$ref": "#/components/parameters/order" - "$ref": "#/components/parameters/per-page" - "$ref": "#/components/parameters/page" responses: '200': description: Response content: application/json: schema: type: object required: - total_count - incomplete_results - items properties: total_count: type: integer incomplete_results: type: boolean items: type: array items: "$ref": "#/components/schemas/label-search-result-item" examples: default: "$ref": "#/components/examples/label-search-result-item-paginated" '304': "$ref": "#/components/responses/not_modified" '404': "$ref": "#/components/responses/not_found" '403': "$ref": "#/components/responses/forbidden" '422': "$ref": "#/components/responses/validation_failed" x-github: githubCloudOnly: false enabledForGitHubApps: true category: search subcategory: "/search/repositories": get: summary: Search repositories description: |- Find repositories via various criteria. This method returns up to 100 results [per page](https://docs.github.com/enterprise-server@3.0/rest/overview/resources-in-the-rest-api#pagination). When searching for repositories, you can get text match metadata for the **name** and **description** fields when you pass the `text-match` media type. For more details about how to receive highlighted search results, see [Text match metadata](https://docs.github.com/enterprise-server@3.0/rest/reference/search#text-match-metadata). For example, if you want to search for popular Tetris repositories written in assembly code, your query might look like this: `q=tetris+language:assembly&sort=stars&order=desc` This query searches for repositories with the word `tetris` in the name, the description, or the README. The results are limited to repositories where the primary language is assembly. The results are sorted by stars in descending order, so that the most popular repositories appear first in the search results. When you include the `mercy` preview header, you can also search for multiple topics by adding more `topic:` instances. For example, your query might look like this: `q=topic:ruby+topic:rails` tags: - search operationId: search/repos externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/search#search-repositories parameters: - name: q description: The query contains one or more search keywords and qualifiers. Qualifiers allow you to limit your search to specific areas of GitHub. The REST API supports the same qualifiers as GitHub.com. To learn more about the format of the query, see [Constructing a search query](https://docs.github.com/enterprise-server@3.0/rest/reference/search#constructing-a-search-query). See "[Searching for repositories](https://docs.github.com/articles/searching-for-repositories/)" for a detailed list of qualifiers. in: query required: true schema: type: string - name: sort description: 'Sorts the results of your query by number of `stars`, `forks`, or `help-wanted-issues` or how recently the items were `updated`. Default: [best match](https://docs.github.com/enterprise-server@3.0/rest/reference/search#ranking-search-results)' in: query required: false schema: type: string enum: - stars - forks - help-wanted-issues - updated - "$ref": "#/components/parameters/order" - "$ref": "#/components/parameters/per-page" - "$ref": "#/components/parameters/page" responses: '200': description: Response content: application/json: schema: type: object required: - total_count - incomplete_results - items properties: total_count: type: integer incomplete_results: type: boolean items: type: array items: "$ref": "#/components/schemas/repo-search-result-item" examples: default: "$ref": "#/components/examples/repo-search-result-item-paginated" '503': "$ref": "#/components/responses/service_unavailable" '422': "$ref": "#/components/responses/validation_failed" '304': "$ref": "#/components/responses/not_modified" x-github: githubCloudOnly: false enabledForGitHubApps: true category: search previews: - required: false name: mercy note: |- The `topics` property for repositories on GitHub is currently available for developers to preview. To view the `topics` property in calls that return repository results, you must provide a custom [media type](https://docs.github.com/enterprise-server@3.0/rest/overview/media-types) in the `Accept` header: ```shell application/vnd.github.mercy-preview+json ``` "/search/topics": get: summary: Search topics description: |- Find topics via various criteria. Results are sorted by best match. This method returns up to 100 results [per page](https://docs.github.com/enterprise-server@3.0/rest/overview/resources-in-the-rest-api#pagination). See "[Searching topics](https://docs.github.com/articles/searching-topics/)" for a detailed list of qualifiers. When searching for topics, you can get text match metadata for the topic's **short\_description**, **description**, **name**, or **display\_name** field when you pass the `text-match` media type. For more details about how to receive highlighted search results, see [Text match metadata](https://docs.github.com/enterprise-server@3.0/rest/reference/search#text-match-metadata). For example, if you want to search for topics related to Ruby that are featured on https://github.com/topics. Your query might look like this: `q=ruby+is:featured` This query searches for topics with the keyword `ruby` and limits the results to find only topics that are featured. The topics that are the best match for the query appear first in the search results. tags: - search operationId: search/topics externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/search#search-topics parameters: - name: q description: The query contains one or more search keywords and qualifiers. Qualifiers allow you to limit your search to specific areas of GitHub. The REST API supports the same qualifiers as GitHub.com. To learn more about the format of the query, see [Constructing a search query](https://docs.github.com/enterprise-server@3.0/rest/reference/search#constructing-a-search-query). in: query required: true schema: type: string - "$ref": "#/components/parameters/per-page" - "$ref": "#/components/parameters/page" responses: '200': description: Response content: application/json: schema: type: object required: - total_count - incomplete_results - items properties: total_count: type: integer incomplete_results: type: boolean items: type: array items: "$ref": "#/components/schemas/topic-search-result-item" examples: default: "$ref": "#/components/examples/topic-search-result-item-paginated" '304': "$ref": "#/components/responses/not_modified" '415': "$ref": "#/components/responses/preview_header_missing" x-github: githubCloudOnly: false enabledForGitHubApps: true category: search previews: - required: true name: mercy note: |- The `topics` property for repositories on GitHub is currently available for developers to preview. To view the `topics` property in calls that return repository results, you must provide a custom [media type](https://docs.github.com/enterprise-server@3.0/rest/overview/media-types) in the `Accept` header: ```shell application/vnd.github.mercy-preview+json ``` "/search/users": get: summary: Search users description: |- Find users via various criteria. This method returns up to 100 results [per page](https://docs.github.com/enterprise-server@3.0/rest/overview/resources-in-the-rest-api#pagination). When searching for users, you can get text match metadata for the issue **login**, **email**, and **name** fields when you pass the `text-match` media type. For more details about highlighting search results, see [Text match metadata](https://docs.github.com/enterprise-server@3.0/rest/reference/search#text-match-metadata). For more details about how to receive highlighted search results, see [Text match metadata](https://docs.github.com/enterprise-server@3.0/rest/reference/search#text-match-metadata). For example, if you're looking for a list of popular users, you might try this query: `q=tom+repos:%3E42+followers:%3E1000` This query searches for users with the name `tom`. The results are restricted to users with more than 42 repositories and over 1,000 followers. tags: - search operationId: search/users externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/search#search-users parameters: - name: q description: The query contains one or more search keywords and qualifiers. Qualifiers allow you to limit your search to specific areas of GitHub. The REST API supports the same qualifiers as GitHub.com. To learn more about the format of the query, see [Constructing a search query](https://docs.github.com/enterprise-server@3.0/rest/reference/search#constructing-a-search-query). See "[Searching users](https://docs.github.com/articles/searching-users/)" for a detailed list of qualifiers. in: query required: true schema: type: string - name: sort description: 'Sorts the results of your query by number of `followers` or `repositories`, or when the person `joined` GitHub Enterprise Server. Default: [best match](https://docs.github.com/enterprise-server@3.0/rest/reference/search#ranking-search-results)' in: query required: false schema: type: string enum: - followers - repositories - joined - "$ref": "#/components/parameters/order" - "$ref": "#/components/parameters/per-page" - "$ref": "#/components/parameters/page" responses: '200': description: Response content: application/json: schema: type: object required: - total_count - incomplete_results - items properties: total_count: type: integer incomplete_results: type: boolean items: type: array items: "$ref": "#/components/schemas/user-search-result-item" examples: default: "$ref": "#/components/examples/user-search-result-item-paginated" '304': "$ref": "#/components/responses/not_modified" '503': "$ref": "#/components/responses/service_unavailable" '422': "$ref": "#/components/responses/validation_failed" x-github: githubCloudOnly: false enabledForGitHubApps: true category: search subcategory: "/setup/api/configcheck": get: summary: Get the configuration status description: |- This endpoint allows you to check the status of the most recent configuration process: Note that you may need to wait several seconds after you start a process before you can check its status. The different statuses are: | Status | Description | | ------------- | --------------------------------- | | `PENDING` | The job has not started yet | | `CONFIGURING` | The job is running | | `DONE` | The job has finished correctly | | `FAILED` | The job has finished unexpectedly | operationId: enterprise-admin/get-configuration-status tags: - enterprise-admin externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/enterprise-admin#get-the-configuration-status responses: '200': description: Response content: application/json: schema: "$ref": "#/components/schemas/configuration-status" examples: default: "$ref": "#/components/examples/configuration-status" x-github: githubCloudOnly: false enabledForGitHubApps: false category: enterprise-admin subcategory: management-console "/setup/api/configure": post: summary: Start a configuration process description: 'This endpoint allows you to start a configuration process at any time for your updated settings to take effect:' operationId: enterprise-admin/start-configuration-process tags: - enterprise-admin externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/enterprise-admin#start-a-configuration-process responses: '202': description: Response x-github: githubCloudOnly: false enabledForGitHubApps: false category: enterprise-admin subcategory: management-console "/setup/api/maintenance": get: summary: Get the maintenance status description: 'Check your installation''s maintenance status:' operationId: enterprise-admin/get-maintenance-status tags: - enterprise-admin externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/enterprise-admin#get-the-maintenance-status responses: '200': description: Response content: application/json: schema: "$ref": "#/components/schemas/maintenance-status" examples: default: "$ref": "#/components/examples/maintenance-status" x-github: githubCloudOnly: false enabledForGitHubApps: false category: enterprise-admin subcategory: management-console post: summary: Enable or disable maintenance mode description: "**Note:** The request body for this operation must be submitted as `application/x-www-form-urlencoded` data. You can submit a parameter value as a string, or you can use a tool such as `curl` to submit a parameter value as the contents of a text file. For more information, see the [`curl` documentation](https://curl.se/docs/manpage.html#--data-urlencode)." operationId: enterprise-admin/enable-or-disable-maintenance-mode tags: - enterprise-admin externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/enterprise-admin#enable-or-disable-maintenance-mode responses: '200': description: Response content: application/json: schema: "$ref": "#/components/schemas/maintenance-status" examples: default: "$ref": "#/components/examples/maintenance-status" requestBody: required: true content: application/x-www-form-urlencoded: schema: type: object properties: maintenance: type: string description: |- A JSON string with the attributes `enabled` and `when`. The possible values for `enabled` are `true` and `false`. When it's `false`, the attribute `when` is ignored and the maintenance mode is turned off. `when` defines the time period when the maintenance was enabled. The possible values for `when` are `now` or any date parseable by [mojombo/chronic](https://github.com/mojombo/chronic). required: - maintenance example: maintenance: '{"enabled":true, "when":"now"}' x-github: githubCloudOnly: false enabledForGitHubApps: false category: enterprise-admin subcategory: management-console "/setup/api/settings": get: summary: Get settings description: '' operationId: enterprise-admin/get-settings tags: - enterprise-admin externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/enterprise-admin#get-settings responses: '200': description: Response content: application/json: schema: "$ref": "#/components/schemas/enterprise-settings" examples: default: "$ref": "#/components/examples/enterprise-settings" x-github: githubCloudOnly: false enabledForGitHubApps: false category: enterprise-admin subcategory: management-console put: summary: Set settings description: |- For a list of the available settings, see the [Get settings endpoint](https://docs.github.com/enterprise-server@3.0/rest/reference/enterprise-admin#get-settings). **Note:** The request body for this operation must be submitted as `application/x-www-form-urlencoded` data. You can submit a parameter value as a string, or you can use a tool such as `curl` to submit a parameter value as the contents of a text file. For more information, see the [`curl` documentation](https://curl.se/docs/manpage.html#--data-urlencode). operationId: enterprise-admin/set-settings tags: - enterprise-admin externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/enterprise-admin#set-settings responses: '204': description: Response requestBody: required: true content: application/x-www-form-urlencoded: schema: type: object properties: settings: type: string description: A JSON string with the new settings. Note that you only need to pass the specific settings you want to modify. For a list of the available settings, see the [Get settings endpoint](https://docs.github.com/enterprise-server@3.0/rest/reference/enterprise-admin#get-settings). required: - settings example: settings: '{ "enterprise": { "public_pages": true }}' x-github: githubCloudOnly: false enabledForGitHubApps: false category: enterprise-admin subcategory: management-console "/setup/api/settings/authorized-keys": get: summary: Get all authorized SSH keys description: '' operationId: enterprise-admin/get-all-authorized-ssh-keys tags: - enterprise-admin externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/enterprise-admin#get-all-authorized-ssh-keys responses: '200': description: Response content: application/json: schema: type: array items: "$ref": "#/components/schemas/ssh-key" examples: default: "$ref": "#/components/examples/ssh-key-items" x-github: githubCloudOnly: false enabledForGitHubApps: false category: enterprise-admin subcategory: management-console post: summary: Add an authorized SSH key description: "**Note:** The request body for this operation must be submitted as `application/x-www-form-urlencoded` data. You can submit a parameter value as a string, or you can use a tool such as `curl` to submit a parameter value as the contents of a text file. For more information, see the [`curl` documentation](https://curl.se/docs/manpage.html#--data-urlencode)." operationId: enterprise-admin/add-authorized-ssh-key tags: - enterprise-admin externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/enterprise-admin#add-an-authorized-ssh-key responses: '201': description: Response content: application/json: schema: type: array items: "$ref": "#/components/schemas/ssh-key" examples: default: "$ref": "#/components/examples/ssh-key-items" requestBody: required: true content: application/x-www-form-urlencoded: schema: type: object properties: authorized_key: type: string description: The public SSH key. required: - authorized_key example: authorized_key: ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAAAgQCssTL/Vtu/ODLTj0VtZoRAbvf7uiv5997GyDq0MoAZUjb5jmA5wYe2/wF6sFuhiZTnZoF1ZtCHunPp0hM/GHrn6VySBhNncx14YO8FPt1CIhEeRMSEjUK9cY3xAbS365oXY8vnUHJsS9+1tr/2bx/+4NJfcUt/Ezf1OR/0LStQXw== x-github: githubCloudOnly: false enabledForGitHubApps: false category: enterprise-admin subcategory: management-console delete: summary: Remove an authorized SSH key description: "**Note:** The request body for this operation must be submitted as `application/x-www-form-urlencoded` data. You can submit a parameter value as a string, or you can use a tool such as `curl` to submit a parameter value as the contents of a text file. For more information, see the [`curl` documentation](https://curl.se/docs/manpage.html#--data-urlencode)." operationId: enterprise-admin/remove-authorized-ssh-key tags: - enterprise-admin externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/enterprise-admin#remove-an-authorized-ssh-key responses: '200': description: Response content: application/json: schema: type: array items: "$ref": "#/components/schemas/ssh-key" examples: default: "$ref": "#/components/examples/ssh-key-items" requestBody: required: true content: application/x-www-form-urlencoded: schema: type: object properties: authorized_key: type: string description: The public SSH key. required: - authorized_key example: authorized_key: ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAAAgQCssTL/Vtu/ODLTj0VtZoRAbvf7uiv5997GyDq0MoAZUjb5jmA5wYe2/wF6sFuhiZTnZoF1ZtCHunPp0hM/GHrn6VySBhNncx14YO8FPt1CIhEeRMSEjUK9cY3xAbS365oXY8vnUHJsS9+1tr/2bx/+4NJfcUt/Ezf1OR/0LStQXw== x-github: githubCloudOnly: false enabledForGitHubApps: false category: enterprise-admin subcategory: management-console "/setup/api/start": post: summary: Create a GitHub license description: |- When you boot a GitHub instance for the first time, you can use the following endpoint to upload a license. Note that you need to `POST` to [`/setup/api/configure`](https://docs.github.com/enterprise-server@3.0/rest/reference/enterprise-admin#start-a-configuration-process) to start the actual configuration process. When using this endpoint, your GitHub instance must have a password set. This can be accomplished two ways: 1. If you're working directly with the API before accessing the web interface, you must pass in the password parameter to set your password. 2. If you set up your instance via the web interface before accessing the API, your calls to this endpoint do not need the password parameter. **Note:** The request body for this operation must be submitted as `application/x-www-form-urlencoded` data. You can submit a parameter value as a string, or you can use a tool such as `curl` to submit a parameter value as the contents of a text file. For more information, see the [`curl` documentation](https://curl.se/docs/manpage.html#--data-urlencode). operationId: enterprise-admin/create-enterprise-server-license tags: - enterprise-admin externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/enterprise-admin#create-a-github-enterprise-server-license responses: '202': description: Response requestBody: required: true content: application/x-www-form-urlencoded: schema: type: object properties: license: type: string description: The content of your _.ghl_ license file. password: type: string description: You **must** provide a password _only if_ you are uploading your license for the first time. If you previously set a password through the web interface, you don't need this parameter. settings: type: string description: An optional JSON string containing the installation settings. For a list of the available settings, see the [Get settings endpoint](https://docs.github.com/enterprise-server@3.0/rest/reference/enterprise-admin#get-settings). required: - license x-github: githubCloudOnly: false enabledForGitHubApps: false category: enterprise-admin subcategory: management-console "/setup/api/upgrade": post: summary: Upgrade a license description: |- This API upgrades your license and also triggers the configuration process. **Note:** The request body for this operation must be submitted as `application/x-www-form-urlencoded` data. You can submit a parameter value as a string, or you can use a tool such as `curl` to submit a parameter value as the contents of a text file. For more information, see the [`curl` documentation](https://curl.se/docs/manpage.html#--data-urlencode). operationId: enterprise-admin/upgrade-license tags: - enterprise-admin externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/enterprise-admin#upgrade-a-license responses: '202': description: Response requestBody: content: application/x-www-form-urlencoded: schema: type: object properties: license: type: string description: The content of your new _.ghl_ license file. x-github: githubCloudOnly: false enabledForGitHubApps: false category: enterprise-admin subcategory: management-console "/teams/{team_id}": get: summary: Get a team (Legacy) description: "**Deprecation Notice:** This endpoint route is deprecated and will be removed from the Teams API. We recommend migrating your existing code to use the [Get a team by name](https://docs.github.com/enterprise-server@3.0/rest/reference/teams#get-a-team-by-name) endpoint." tags: - teams operationId: teams/get-legacy externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/teams/#get-a-team-legacy parameters: - "$ref": "#/components/parameters/team-id" responses: '200': description: Response content: application/json: schema: "$ref": "#/components/schemas/team-full" examples: default: "$ref": "#/components/examples/team-full" '404': "$ref": "#/components/responses/not_found" x-github: githubCloudOnly: false enabledForGitHubApps: true removalDate: '2021-02-01' deprecationDate: '2020-01-21' category: teams subcategory: deprecated: true patch: summary: Update a team (Legacy) description: |- **Deprecation Notice:** This endpoint route is deprecated and will be removed from the Teams API. We recommend migrating your existing code to use the new [Update a team](https://docs.github.com/enterprise-server@3.0/rest/reference/teams#update-a-team) endpoint. To edit a team, the authenticated user must either be an organization owner or a team maintainer. **Note:** With nested teams, the `privacy` for parent teams cannot be `secret`. tags: - teams operationId: teams/update-legacy externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/teams/#update-a-team-legacy parameters: - "$ref": "#/components/parameters/team-id" requestBody: required: true content: application/json: schema: type: object properties: name: type: string description: The name of the team. description: type: string description: The description of the team. privacy: type: string description: "The level of privacy this team should have. Editing teams without specifying this parameter leaves `privacy` intact. The options are: \n**For a non-nested team:** \n\\* `secret` - only visible to organization owners and members of this team. \ \n\\* `closed` - visible to all members of this organization. \ \n**For a parent or child team:** \n\\* `closed` - visible to all members of this organization." enum: - secret - closed permission: type: string description: "**Deprecated**. The permission that new repositories will be added to the team with when none is specified. Can be one of: \n\\* `pull` - team members can pull, but not push to or administer newly-added repositories. \n\\* `push` - team members can pull and push, but not administer newly-added repositories. \ \n\\* `admin` - team members can pull, push and administer newly-added repositories." enum: - pull - push - admin default: pull parent_team_id: type: - integer - 'null' description: The ID of a team to set as the parent team. required: - name example: name: new team name description: new team description privacy: closed responses: '200': description: Response content: application/json: schema: "$ref": "#/components/schemas/team-full" examples: default: "$ref": "#/components/examples/team-full" '201': description: Response content: application/json: schema: "$ref": "#/components/schemas/team-full" examples: default: "$ref": "#/components/examples/team-full" '404': "$ref": "#/components/responses/not_found" '422': "$ref": "#/components/responses/validation_failed" '403': "$ref": "#/components/responses/forbidden" x-github: githubCloudOnly: false enabledForGitHubApps: true removalDate: '2021-02-01' deprecationDate: '2020-01-21' category: teams subcategory: deprecated: true delete: summary: Delete a team (Legacy) description: |- **Deprecation Notice:** This endpoint route is deprecated and will be removed from the Teams API. We recommend migrating your existing code to use the new [Delete a team](https://docs.github.com/enterprise-server@3.0/rest/reference/teams#delete-a-team) endpoint. To delete a team, the authenticated user must be an organization owner or team maintainer. If you are an organization owner, deleting a parent team will delete all of its child teams as well. tags: - teams operationId: teams/delete-legacy externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/teams/#delete-a-team-legacy parameters: - "$ref": "#/components/parameters/team-id" responses: '204': description: Response '404': "$ref": "#/components/responses/not_found" '422': "$ref": "#/components/responses/validation_failed" x-github: githubCloudOnly: false enabledForGitHubApps: true removalDate: '2021-02-01' deprecationDate: '2020-01-21' category: teams subcategory: deprecated: true "/teams/{team_id}/discussions": get: summary: List discussions (Legacy) description: |- **Deprecation Notice:** This endpoint route is deprecated and will be removed from the Teams API. We recommend migrating your existing code to use the new [`List discussions`](https://docs.github.com/enterprise-server@3.0/rest/reference/teams#list-discussions) endpoint. List all discussions on a team's page. OAuth access tokens require the `read:discussion` [scope](https://docs.github.com/enterprise-server@3.0/apps/building-oauth-apps/understanding-scopes-for-oauth-apps/). tags: - teams operationId: teams/list-discussions-legacy externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/teams#list-discussions-legacy parameters: - "$ref": "#/components/parameters/team-id" - "$ref": "#/components/parameters/direction" - "$ref": "#/components/parameters/per-page" - "$ref": "#/components/parameters/page" responses: '200': description: Response content: application/json: schema: type: array items: "$ref": "#/components/schemas/team-discussion" examples: default: "$ref": "#/components/examples/team-discussion-items" headers: Link: "$ref": "#/components/headers/link" x-github: githubCloudOnly: false enabledForGitHubApps: true removalDate: '2021-02-01' deprecationDate: '2020-01-21' category: teams subcategory: discussions previews: - required: false name: squirrel-girl note: |- An additional `reactions` object in the issue comment payload is currently available for developers to preview. During the preview period, the APIs may change without advance notice. Please see the [blog post](https://developer.github.com/changes/2016-05-12-reactions-api-preview) for full details. To access the API you must provide a custom [media type](https://docs.github.com/enterprise-server@3.0/rest/overview/media-types) in the `Accept` header: ```shell application/vnd.github.squirrel-girl-preview ``` The `reactions` key will have the following payload where `url` can be used to construct the API location for [listing and creating](https://docs.github.com/enterprise-server@3.0/rest/reference/reactions) reactions. deprecated: true post: summary: Create a discussion (Legacy) description: |- **Deprecation Notice:** This endpoint route is deprecated and will be removed from the Teams API. We recommend migrating your existing code to use the new [`Create a discussion`](https://docs.github.com/enterprise-server@3.0/rest/reference/teams#create-a-discussion) endpoint. Creates a new discussion post on a team's page. OAuth access tokens require the `write:discussion` [scope](https://docs.github.com/enterprise-server@3.0/apps/building-oauth-apps/understanding-scopes-for-oauth-apps/). This endpoint triggers [notifications](https://docs.github.com/en/github/managing-subscriptions-and-notifications-on-github/about-notifications). Creating content too quickly using this endpoint may result in secondary rate limiting. See "[Secondary rate limits](https://docs.github.com/enterprise-server@3.0/rest/overview/resources-in-the-rest-api#secondary-rate-limits)" and "[Dealing with secondary rate limits](https://docs.github.com/enterprise-server@3.0/rest/guides/best-practices-for-integrators#dealing-with-secondary-rate-limits)" for details. tags: - teams operationId: teams/create-discussion-legacy externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/teams#create-a-discussion-legacy parameters: - "$ref": "#/components/parameters/team-id" requestBody: required: true content: application/json: schema: type: object properties: title: type: string description: The discussion post's title. body: type: string description: The discussion post's body text. private: type: boolean description: Private posts are only visible to team members, organization owners, and team maintainers. Public posts are visible to all members of the organization. Set to `true` to create a private post. default: false required: - title - body example: title: Our first team post body: Hi! This is an area for us to collaborate as a team. responses: '201': description: Response content: application/json: schema: "$ref": "#/components/schemas/team-discussion" examples: default: "$ref": "#/components/examples/team-discussion" x-github: triggersNotification: true githubCloudOnly: false enabledForGitHubApps: true removalDate: '2021-02-01' deprecationDate: '2020-01-21' category: teams subcategory: discussions previews: - required: false name: squirrel-girl note: |- An additional `reactions` object in the issue comment payload is currently available for developers to preview. During the preview period, the APIs may change without advance notice. Please see the [blog post](https://developer.github.com/changes/2016-05-12-reactions-api-preview) for full details. To access the API you must provide a custom [media type](https://docs.github.com/enterprise-server@3.0/rest/overview/media-types) in the `Accept` header: ```shell application/vnd.github.squirrel-girl-preview ``` The `reactions` key will have the following payload where `url` can be used to construct the API location for [listing and creating](https://docs.github.com/enterprise-server@3.0/rest/reference/reactions) reactions. deprecated: true "/teams/{team_id}/discussions/{discussion_number}": get: summary: Get a discussion (Legacy) description: |- **Deprecation Notice:** This endpoint route is deprecated and will be removed from the Teams API. We recommend migrating your existing code to use the new [Get a discussion](https://docs.github.com/enterprise-server@3.0/rest/reference/teams#get-a-discussion) endpoint. Get a specific discussion on a team's page. OAuth access tokens require the `read:discussion` [scope](https://docs.github.com/enterprise-server@3.0/apps/building-oauth-apps/understanding-scopes-for-oauth-apps/). tags: - teams operationId: teams/get-discussion-legacy externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/teams#get-a-discussion-legacy parameters: - "$ref": "#/components/parameters/team-id" - "$ref": "#/components/parameters/discussion-number" responses: '200': description: Response content: application/json: schema: "$ref": "#/components/schemas/team-discussion" examples: default: "$ref": "#/components/examples/team-discussion" x-github: githubCloudOnly: false enabledForGitHubApps: true removalDate: '2021-02-01' deprecationDate: '2020-01-21' category: teams subcategory: discussions previews: - required: false name: squirrel-girl note: |- An additional `reactions` object in the issue comment payload is currently available for developers to preview. During the preview period, the APIs may change without advance notice. Please see the [blog post](https://developer.github.com/changes/2016-05-12-reactions-api-preview) for full details. To access the API you must provide a custom [media type](https://docs.github.com/enterprise-server@3.0/rest/overview/media-types) in the `Accept` header: ```shell application/vnd.github.squirrel-girl-preview ``` The `reactions` key will have the following payload where `url` can be used to construct the API location for [listing and creating](https://docs.github.com/enterprise-server@3.0/rest/reference/reactions) reactions. deprecated: true patch: summary: Update a discussion (Legacy) description: |- **Deprecation Notice:** This endpoint route is deprecated and will be removed from the Teams API. We recommend migrating your existing code to use the new [Update a discussion](https://docs.github.com/enterprise-server@3.0/rest/reference/teams#update-a-discussion) endpoint. Edits the title and body text of a discussion post. Only the parameters you provide are updated. OAuth access tokens require the `write:discussion` [scope](https://docs.github.com/enterprise-server@3.0/apps/building-oauth-apps/understanding-scopes-for-oauth-apps/). tags: - teams operationId: teams/update-discussion-legacy externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/teams#update-a-discussion-legacy parameters: - "$ref": "#/components/parameters/team-id" - "$ref": "#/components/parameters/discussion-number" requestBody: required: false content: application/json: schema: type: object properties: title: type: string description: The discussion post's title. body: type: string description: The discussion post's body text. example: title: Welcome to our first team post responses: '200': description: Response content: application/json: schema: "$ref": "#/components/schemas/team-discussion" examples: default: "$ref": "#/components/examples/team-discussion-2" x-github: githubCloudOnly: false enabledForGitHubApps: true removalDate: '2021-02-01' deprecationDate: '2020-01-21' category: teams subcategory: discussions previews: - required: false name: squirrel-girl note: |- An additional `reactions` object in the issue comment payload is currently available for developers to preview. During the preview period, the APIs may change without advance notice. Please see the [blog post](https://developer.github.com/changes/2016-05-12-reactions-api-preview) for full details. To access the API you must provide a custom [media type](https://docs.github.com/enterprise-server@3.0/rest/overview/media-types) in the `Accept` header: ```shell application/vnd.github.squirrel-girl-preview ``` The `reactions` key will have the following payload where `url` can be used to construct the API location for [listing and creating](https://docs.github.com/enterprise-server@3.0/rest/reference/reactions) reactions. deprecated: true delete: summary: Delete a discussion (Legacy) description: |- **Deprecation Notice:** This endpoint route is deprecated and will be removed from the Teams API. We recommend migrating your existing code to use the new [`Delete a discussion`](https://docs.github.com/enterprise-server@3.0/rest/reference/teams#delete-a-discussion) endpoint. Delete a discussion from a team's page. OAuth access tokens require the `write:discussion` [scope](https://docs.github.com/enterprise-server@3.0/apps/building-oauth-apps/understanding-scopes-for-oauth-apps/). tags: - teams operationId: teams/delete-discussion-legacy externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/teams#delete-a-discussion-legacy parameters: - "$ref": "#/components/parameters/team-id" - "$ref": "#/components/parameters/discussion-number" responses: '204': description: Response x-github: githubCloudOnly: false enabledForGitHubApps: true removalDate: '2021-02-01' deprecationDate: '2020-01-21' category: teams subcategory: discussions deprecated: true "/teams/{team_id}/discussions/{discussion_number}/comments": get: summary: List discussion comments (Legacy) description: |- **Deprecation Notice:** This endpoint route is deprecated and will be removed from the Teams API. We recommend migrating your existing code to use the new [List discussion comments](https://docs.github.com/enterprise-server@3.0/rest/reference/teams#list-discussion-comments) endpoint. List all comments on a team discussion. OAuth access tokens require the `read:discussion` [scope](https://docs.github.com/enterprise-server@3.0/apps/building-oauth-apps/understanding-scopes-for-oauth-apps/). tags: - teams operationId: teams/list-discussion-comments-legacy externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/teams#list-discussion-comments-legacy parameters: - "$ref": "#/components/parameters/team-id" - "$ref": "#/components/parameters/discussion-number" - "$ref": "#/components/parameters/direction" - "$ref": "#/components/parameters/per-page" - "$ref": "#/components/parameters/page" responses: '200': description: Response content: application/json: schema: type: array items: "$ref": "#/components/schemas/team-discussion-comment" examples: default: "$ref": "#/components/examples/team-discussion-comment-items" headers: Link: "$ref": "#/components/headers/link" x-github: githubCloudOnly: false enabledForGitHubApps: true removalDate: '2021-02-01' deprecationDate: '2020-01-21' category: teams subcategory: discussion-comments previews: - required: false name: squirrel-girl note: |- An additional `reactions` object in the issue comment payload is currently available for developers to preview. During the preview period, the APIs may change without advance notice. Please see the [blog post](https://developer.github.com/changes/2016-05-12-reactions-api-preview) for full details. To access the API you must provide a custom [media type](https://docs.github.com/enterprise-server@3.0/rest/overview/media-types) in the `Accept` header: ```shell application/vnd.github.squirrel-girl-preview ``` The `reactions` key will have the following payload where `url` can be used to construct the API location for [listing and creating](https://docs.github.com/enterprise-server@3.0/rest/reference/reactions) reactions. deprecated: true post: summary: Create a discussion comment (Legacy) description: |- **Deprecation Notice:** This endpoint route is deprecated and will be removed from the Teams API. We recommend migrating your existing code to use the new [Create a discussion comment](https://docs.github.com/enterprise-server@3.0/rest/reference/teams#create-a-discussion-comment) endpoint. Creates a new comment on a team discussion. OAuth access tokens require the `write:discussion` [scope](https://docs.github.com/enterprise-server@3.0/apps/building-oauth-apps/understanding-scopes-for-oauth-apps/). This endpoint triggers [notifications](https://docs.github.com/en/github/managing-subscriptions-and-notifications-on-github/about-notifications). Creating content too quickly using this endpoint may result in secondary rate limiting. See "[Secondary rate limits](https://docs.github.com/enterprise-server@3.0/rest/overview/resources-in-the-rest-api#secondary-rate-limits)" and "[Dealing with secondary rate limits](https://docs.github.com/enterprise-server@3.0/rest/guides/best-practices-for-integrators#dealing-with-secondary-rate-limits)" for details. tags: - teams operationId: teams/create-discussion-comment-legacy externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/teams#create-a-discussion-comment-legacy parameters: - "$ref": "#/components/parameters/team-id" - "$ref": "#/components/parameters/discussion-number" requestBody: required: true content: application/json: schema: type: object properties: body: type: string description: The discussion comment's body text. required: - body example: body: Do you like apples? responses: '201': description: Response content: application/json: schema: "$ref": "#/components/schemas/team-discussion-comment" examples: default: "$ref": "#/components/examples/team-discussion-comment" x-github: triggersNotification: true githubCloudOnly: false enabledForGitHubApps: true removalDate: '2021-02-01' deprecationDate: '2020-01-21' category: teams subcategory: discussion-comments previews: - required: false name: squirrel-girl note: |- An additional `reactions` object in the issue comment payload is currently available for developers to preview. During the preview period, the APIs may change without advance notice. Please see the [blog post](https://developer.github.com/changes/2016-05-12-reactions-api-preview) for full details. To access the API you must provide a custom [media type](https://docs.github.com/enterprise-server@3.0/rest/overview/media-types) in the `Accept` header: ```shell application/vnd.github.squirrel-girl-preview ``` The `reactions` key will have the following payload where `url` can be used to construct the API location for [listing and creating](https://docs.github.com/enterprise-server@3.0/rest/reference/reactions) reactions. deprecated: true "/teams/{team_id}/discussions/{discussion_number}/comments/{comment_number}": get: summary: Get a discussion comment (Legacy) description: |- **Deprecation Notice:** This endpoint route is deprecated and will be removed from the Teams API. We recommend migrating your existing code to use the new [Get a discussion comment](https://docs.github.com/enterprise-server@3.0/rest/reference/teams#get-a-discussion-comment) endpoint. Get a specific comment on a team discussion. OAuth access tokens require the `read:discussion` [scope](https://docs.github.com/enterprise-server@3.0/apps/building-oauth-apps/understanding-scopes-for-oauth-apps/). tags: - teams operationId: teams/get-discussion-comment-legacy externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/teams#get-a-discussion-comment-legacy parameters: - "$ref": "#/components/parameters/team-id" - "$ref": "#/components/parameters/discussion-number" - "$ref": "#/components/parameters/comment-number" responses: '200': description: Response content: application/json: schema: "$ref": "#/components/schemas/team-discussion-comment" examples: default: "$ref": "#/components/examples/team-discussion-comment" x-github: githubCloudOnly: false enabledForGitHubApps: true removalDate: '2021-02-01' deprecationDate: '2020-01-21' category: teams subcategory: discussion-comments previews: - required: false name: squirrel-girl note: |- An additional `reactions` object in the issue comment payload is currently available for developers to preview. During the preview period, the APIs may change without advance notice. Please see the [blog post](https://developer.github.com/changes/2016-05-12-reactions-api-preview) for full details. To access the API you must provide a custom [media type](https://docs.github.com/enterprise-server@3.0/rest/overview/media-types) in the `Accept` header: ```shell application/vnd.github.squirrel-girl-preview ``` The `reactions` key will have the following payload where `url` can be used to construct the API location for [listing and creating](https://docs.github.com/enterprise-server@3.0/rest/reference/reactions) reactions. deprecated: true patch: summary: Update a discussion comment (Legacy) description: |- **Deprecation Notice:** This endpoint route is deprecated and will be removed from the Teams API. We recommend migrating your existing code to use the new [Update a discussion comment](https://docs.github.com/enterprise-server@3.0/rest/reference/teams#update-a-discussion-comment) endpoint. Edits the body text of a discussion comment. OAuth access tokens require the `write:discussion` [scope](https://docs.github.com/enterprise-server@3.0/apps/building-oauth-apps/understanding-scopes-for-oauth-apps/). tags: - teams operationId: teams/update-discussion-comment-legacy externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/teams#update-a-discussion-comment-legacy parameters: - "$ref": "#/components/parameters/team-id" - "$ref": "#/components/parameters/discussion-number" - "$ref": "#/components/parameters/comment-number" requestBody: required: true content: application/json: schema: type: object properties: body: type: string description: The discussion comment's body text. required: - body example: body: Do you like pineapples? responses: '200': description: Response content: application/json: schema: "$ref": "#/components/schemas/team-discussion-comment" examples: default: "$ref": "#/components/examples/team-discussion-comment-2" x-github: githubCloudOnly: false enabledForGitHubApps: true removalDate: '2021-02-01' deprecationDate: '2020-01-21' category: teams subcategory: discussion-comments previews: - required: false name: squirrel-girl note: |- An additional `reactions` object in the issue comment payload is currently available for developers to preview. During the preview period, the APIs may change without advance notice. Please see the [blog post](https://developer.github.com/changes/2016-05-12-reactions-api-preview) for full details. To access the API you must provide a custom [media type](https://docs.github.com/enterprise-server@3.0/rest/overview/media-types) in the `Accept` header: ```shell application/vnd.github.squirrel-girl-preview ``` The `reactions` key will have the following payload where `url` can be used to construct the API location for [listing and creating](https://docs.github.com/enterprise-server@3.0/rest/reference/reactions) reactions. deprecated: true delete: summary: Delete a discussion comment (Legacy) description: |- **Deprecation Notice:** This endpoint route is deprecated and will be removed from the Teams API. We recommend migrating your existing code to use the new [Delete a discussion comment](https://docs.github.com/enterprise-server@3.0/rest/reference/teams#delete-a-discussion-comment) endpoint. Deletes a comment on a team discussion. OAuth access tokens require the `write:discussion` [scope](https://docs.github.com/enterprise-server@3.0/apps/building-oauth-apps/understanding-scopes-for-oauth-apps/). tags: - teams operationId: teams/delete-discussion-comment-legacy externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/teams#delete-a-discussion-comment-legacy parameters: - "$ref": "#/components/parameters/team-id" - "$ref": "#/components/parameters/discussion-number" - "$ref": "#/components/parameters/comment-number" responses: '204': description: Response x-github: githubCloudOnly: false enabledForGitHubApps: true removalDate: '2021-02-01' deprecationDate: '2020-01-21' category: teams subcategory: discussion-comments deprecated: true "/teams/{team_id}/discussions/{discussion_number}/comments/{comment_number}/reactions": get: summary: List reactions for a team discussion comment (Legacy) description: |- **Deprecation Notice:** This endpoint route is deprecated and will be removed from the Teams API. We recommend migrating your existing code to use the new [`List reactions for a team discussion comment`](https://docs.github.com/enterprise-server@3.0/rest/reference/reactions#list-reactions-for-a-team-discussion-comment) endpoint. List the reactions to a [team discussion comment](https://docs.github.com/enterprise-server@3.0/rest/reference/teams#discussion-comments). OAuth access tokens require the `read:discussion` [scope](https://docs.github.com/enterprise-server@3.0/apps/building-oauth-apps/understanding-scopes-for-oauth-apps/). tags: - reactions operationId: reactions/list-for-team-discussion-comment-legacy externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/reactions/#list-reactions-for-a-team-discussion-comment-legacy parameters: - "$ref": "#/components/parameters/team-id" - "$ref": "#/components/parameters/discussion-number" - "$ref": "#/components/parameters/comment-number" - name: content description: Returns a single [reaction type](https://docs.github.com/enterprise-server@3.0/rest/reference/reactions#reaction-types). Omit this parameter to list all reactions to a team discussion comment. in: query required: false schema: type: string enum: - "+1" - "-1" - laugh - confused - heart - hooray - rocket - eyes - "$ref": "#/components/parameters/per-page" - "$ref": "#/components/parameters/page" responses: '200': description: Response content: application/json: schema: type: array items: "$ref": "#/components/schemas/reaction" examples: default: "$ref": "#/components/examples/reaction-items" headers: Link: "$ref": "#/components/headers/link" x-github: githubCloudOnly: false enabledForGitHubApps: true removalDate: '2021-02-21' deprecationDate: '2020-02-26' category: reactions previews: - required: true name: squirrel-girl note: |- An additional `reactions` object in the issue comment payload is currently available for developers to preview. During the preview period, the APIs may change without advance notice. Please see the [blog post](https://developer.github.com/changes/2016-05-12-reactions-api-preview) for full details. To access the API you must provide a custom [media type](https://docs.github.com/enterprise-server@3.0/rest/overview/media-types) in the `Accept` header: ```shell application/vnd.github.squirrel-girl-preview ``` The `reactions` key will have the following payload where `url` can be used to construct the API location for [listing and creating](https://docs.github.com/enterprise-server@3.0/rest/reference/reactions) reactions. deprecated: true post: summary: Create reaction for a team discussion comment (Legacy) description: |- **Deprecation Notice:** This endpoint route is deprecated and will be removed from the Teams API. We recommend migrating your existing code to use the new "[Create reaction for a team discussion comment](https://docs.github.com/enterprise-server@3.0/rest/reference/reactions#create-reaction-for-a-team-discussion-comment)" endpoint. Create a reaction to a [team discussion comment](https://docs.github.com/enterprise-server@3.0/rest/reference/teams#discussion-comments). OAuth access tokens require the `write:discussion` [scope](https://docs.github.com/enterprise-server@3.0/apps/building-oauth-apps/understanding-scopes-for-oauth-apps/). A response with an HTTP `200` status means that you already added the reaction type to this team discussion comment. tags: - reactions operationId: reactions/create-for-team-discussion-comment-legacy externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/reactions/#create-reaction-for-a-team-discussion-comment-legacy parameters: - "$ref": "#/components/parameters/team-id" - "$ref": "#/components/parameters/discussion-number" - "$ref": "#/components/parameters/comment-number" requestBody: required: true content: application/json: schema: type: object properties: content: type: string description: The [reaction type](https://docs.github.com/enterprise-server@3.0/rest/reference/reactions#reaction-types) to add to the team discussion comment. enum: - "+1" - "-1" - laugh - confused - heart - hooray - rocket - eyes required: - content example: content: heart responses: '201': description: Response content: application/json: schema: "$ref": "#/components/schemas/reaction" examples: default: "$ref": "#/components/examples/reaction" x-github: githubCloudOnly: false enabledForGitHubApps: true removalDate: '2021-02-21' deprecationDate: '2020-02-26' category: reactions previews: - required: true name: squirrel-girl note: |- An additional `reactions` object in the issue comment payload is currently available for developers to preview. During the preview period, the APIs may change without advance notice. Please see the [blog post](https://developer.github.com/changes/2016-05-12-reactions-api-preview) for full details. To access the API you must provide a custom [media type](https://docs.github.com/enterprise-server@3.0/rest/overview/media-types) in the `Accept` header: ```shell application/vnd.github.squirrel-girl-preview ``` The `reactions` key will have the following payload where `url` can be used to construct the API location for [listing and creating](https://docs.github.com/enterprise-server@3.0/rest/reference/reactions) reactions. deprecated: true "/teams/{team_id}/discussions/{discussion_number}/reactions": get: summary: List reactions for a team discussion (Legacy) description: |- **Deprecation Notice:** This endpoint route is deprecated and will be removed from the Teams API. We recommend migrating your existing code to use the new [`List reactions for a team discussion`](https://docs.github.com/enterprise-server@3.0/rest/reference/reactions#list-reactions-for-a-team-discussion) endpoint. List the reactions to a [team discussion](https://docs.github.com/enterprise-server@3.0/rest/reference/teams#discussions). OAuth access tokens require the `read:discussion` [scope](https://docs.github.com/enterprise-server@3.0/apps/building-oauth-apps/understanding-scopes-for-oauth-apps/). tags: - reactions operationId: reactions/list-for-team-discussion-legacy externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/reactions/#list-reactions-for-a-team-discussion-legacy parameters: - "$ref": "#/components/parameters/team-id" - "$ref": "#/components/parameters/discussion-number" - name: content description: Returns a single [reaction type](https://docs.github.com/enterprise-server@3.0/rest/reference/reactions#reaction-types). Omit this parameter to list all reactions to a team discussion. in: query required: false schema: type: string enum: - "+1" - "-1" - laugh - confused - heart - hooray - rocket - eyes - "$ref": "#/components/parameters/per-page" - "$ref": "#/components/parameters/page" responses: '200': description: Response content: application/json: schema: type: array items: "$ref": "#/components/schemas/reaction" examples: default: "$ref": "#/components/examples/reaction-items" headers: Link: "$ref": "#/components/headers/link" x-github: githubCloudOnly: false enabledForGitHubApps: true removalDate: '2021-02-21' deprecationDate: '2020-02-26' category: reactions previews: - required: true name: squirrel-girl note: |- An additional `reactions` object in the issue comment payload is currently available for developers to preview. During the preview period, the APIs may change without advance notice. Please see the [blog post](https://developer.github.com/changes/2016-05-12-reactions-api-preview) for full details. To access the API you must provide a custom [media type](https://docs.github.com/enterprise-server@3.0/rest/overview/media-types) in the `Accept` header: ```shell application/vnd.github.squirrel-girl-preview ``` The `reactions` key will have the following payload where `url` can be used to construct the API location for [listing and creating](https://docs.github.com/enterprise-server@3.0/rest/reference/reactions) reactions. deprecated: true post: summary: Create reaction for a team discussion (Legacy) description: |- **Deprecation Notice:** This endpoint route is deprecated and will be removed from the Teams API. We recommend migrating your existing code to use the new [`Create reaction for a team discussion`](https://docs.github.com/enterprise-server@3.0/rest/reference/reactions#create-reaction-for-a-team-discussion) endpoint. Create a reaction to a [team discussion](https://docs.github.com/enterprise-server@3.0/rest/reference/teams#discussions). OAuth access tokens require the `write:discussion` [scope](https://docs.github.com/enterprise-server@3.0/apps/building-oauth-apps/understanding-scopes-for-oauth-apps/). A response with an HTTP `200` status means that you already added the reaction type to this team discussion. tags: - reactions operationId: reactions/create-for-team-discussion-legacy externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/reactions/#create-reaction-for-a-team-discussion-legacy parameters: - "$ref": "#/components/parameters/team-id" - "$ref": "#/components/parameters/discussion-number" requestBody: required: true content: application/json: schema: type: object properties: content: type: string description: The [reaction type](https://docs.github.com/enterprise-server@3.0/rest/reference/reactions#reaction-types) to add to the team discussion. enum: - "+1" - "-1" - laugh - confused - heart - hooray - rocket - eyes required: - content example: content: heart responses: '201': description: Response content: application/json: schema: "$ref": "#/components/schemas/reaction" examples: default: "$ref": "#/components/examples/reaction" x-github: githubCloudOnly: false enabledForGitHubApps: false removalDate: '2021-02-21' deprecationDate: '2020-02-26' category: reactions previews: - required: true name: squirrel-girl note: |- An additional `reactions` object in the issue comment payload is currently available for developers to preview. During the preview period, the APIs may change without advance notice. Please see the [blog post](https://developer.github.com/changes/2016-05-12-reactions-api-preview) for full details. To access the API you must provide a custom [media type](https://docs.github.com/enterprise-server@3.0/rest/overview/media-types) in the `Accept` header: ```shell application/vnd.github.squirrel-girl-preview ``` The `reactions` key will have the following payload where `url` can be used to construct the API location for [listing and creating](https://docs.github.com/enterprise-server@3.0/rest/reference/reactions) reactions. deprecated: true "/teams/{team_id}/members": get: summary: List team members (Legacy) description: |- **Deprecation Notice:** This endpoint route is deprecated and will be removed from the Teams API. We recommend migrating your existing code to use the new [`List team members`](https://docs.github.com/enterprise-server@3.0/rest/reference/teams#list-team-members) endpoint. Team members will include the members of child teams. tags: - teams operationId: teams/list-members-legacy externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/teams#list-team-members-legacy parameters: - "$ref": "#/components/parameters/team-id" - name: role description: "Filters members returned by their role in the team. Can be one of: \n\\* `member` - normal members of the team. \n\\* `maintainer` - team maintainers. \n\\* `all` - all members of the team." in: query required: false schema: type: string enum: - member - maintainer - all default: all - "$ref": "#/components/parameters/per-page" - "$ref": "#/components/parameters/page" responses: '200': description: Response content: application/json: schema: type: array items: "$ref": "#/components/schemas/simple-user" examples: default: "$ref": "#/components/examples/simple-user-items" headers: Link: "$ref": "#/components/headers/link" '404': "$ref": "#/components/responses/not_found" x-github: githubCloudOnly: false enabledForGitHubApps: true removalDate: '2021-02-01' deprecationDate: '2020-01-21' category: teams subcategory: members deprecated: true "/teams/{team_id}/members/{username}": get: summary: Get team member (Legacy) description: |- The "Get team member" endpoint (described below) is deprecated. We recommend using the [Get team membership for a user](https://docs.github.com/enterprise-server@3.0/rest/reference/teams#get-team-membership-for-a-user) endpoint instead. It allows you to get both active and pending memberships. To list members in a team, the team must be visible to the authenticated user. tags: - teams operationId: teams/get-member-legacy externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/teams#get-team-member-legacy parameters: - "$ref": "#/components/parameters/team-id" - "$ref": "#/components/parameters/username" responses: '204': description: if user is a member '404': description: if user is not a member x-github: githubCloudOnly: false enabledForGitHubApps: true removalDate: '2021-02-01' deprecationDate: '2020-01-21' category: teams subcategory: members deprecated: true put: summary: Add team member (Legacy) description: |- The "Add team member" endpoint (described below) is deprecated. We recommend using the [Add or update team membership for a user](https://docs.github.com/enterprise-server@3.0/rest/reference/teams#add-or-update-team-membership-for-a-user) endpoint instead. It allows you to invite new organization members to your teams. Team synchronization is available for organizations using GitHub Enterprise Cloud. For more information, see [GitHub's products](https://docs.github.com/github/getting-started-with-github/githubs-products) in the GitHub Help documentation. To add someone to a team, the authenticated user must be an organization owner or a team maintainer in the team they're changing. The person being added to the team must be a member of the team's organization. **Note:** When you have team synchronization set up for a team with your organization's identity provider (IdP), you will see an error if you attempt to use the API for making changes to the team's membership. If you have access to manage group membership in your IdP, you can manage GitHub Enterprise Server team membership through your identity provider, which automatically adds and removes team members in an organization. For more information, see "[Synchronizing teams between your identity provider and GitHub Enterprise Server](https://docs.github.com/articles/synchronizing-teams-between-your-identity-provider-and-github/)." Note that you'll need to set `Content-Length` to zero when calling out to this endpoint. For more information, see "[HTTP verbs](https://docs.github.com/enterprise-server@3.0/rest/overview/resources-in-the-rest-api#http-verbs)." tags: - teams operationId: teams/add-member-legacy externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/teams#add-team-member-legacy parameters: - "$ref": "#/components/parameters/team-id" - "$ref": "#/components/parameters/username" responses: '204': description: Response '404': description: Not Found if team synchronization is set up '422': description: Unprocessable Entity if you attempt to add an organization to a team or you attempt to add a user to a team when they are not a member of at least one other team in the same organization '403': "$ref": "#/components/responses/forbidden" x-github: githubCloudOnly: false enabledForGitHubApps: true removalDate: '2021-02-01' deprecationDate: '2020-01-21' category: teams subcategory: members deprecated: true delete: summary: Remove team member (Legacy) description: |- The "Remove team member" endpoint (described below) is deprecated. We recommend using the [Remove team membership for a user](https://docs.github.com/enterprise-server@3.0/rest/reference/teams#remove-team-membership-for-a-user) endpoint instead. It allows you to remove both active and pending memberships. Team synchronization is available for organizations using GitHub Enterprise Cloud. For more information, see [GitHub's products](https://docs.github.com/github/getting-started-with-github/githubs-products) in the GitHub Help documentation. To remove a team member, the authenticated user must have 'admin' permissions to the team or be an owner of the org that the team is associated with. Removing a team member does not delete the user, it just removes them from the team. **Note:** When you have team synchronization set up for a team with your organization's identity provider (IdP), you will see an error if you attempt to use the API for making changes to the team's membership. If you have access to manage group membership in your IdP, you can manage GitHub Enterprise Server team membership through your identity provider, which automatically adds and removes team members in an organization. For more information, see "[Synchronizing teams between your identity provider and GitHub Enterprise Server](https://docs.github.com/articles/synchronizing-teams-between-your-identity-provider-and-github/)." tags: - teams operationId: teams/remove-member-legacy externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/teams#remove-team-member-legacy parameters: - "$ref": "#/components/parameters/team-id" - "$ref": "#/components/parameters/username" responses: '204': description: Response '404': description: Not Found if team synchronization is setup x-github: githubCloudOnly: false enabledForGitHubApps: true removalDate: '2021-02-01' deprecationDate: '2020-01-21' category: teams subcategory: members deprecated: true "/teams/{team_id}/memberships/{username}": get: summary: Get team membership for a user (Legacy) description: |- **Deprecation Notice:** This endpoint route is deprecated and will be removed from the Teams API. We recommend migrating your existing code to use the new [Get team membership for a user](https://docs.github.com/enterprise-server@3.0/rest/reference/teams#get-team-membership-for-a-user) endpoint. Team members will include the members of child teams. To get a user's membership with a team, the team must be visible to the authenticated user. **Note:** The response contains the `state` of the membership and the member's `role`. The `role` for organization owners is set to `maintainer`. For more information about `maintainer` roles, see [Create a team](https://docs.github.com/enterprise-server@3.0/rest/reference/teams#create-a-team). tags: - teams operationId: teams/get-membership-for-user-legacy externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/teams#get-team-membership-for-a-user-legacy parameters: - "$ref": "#/components/parameters/team-id" - "$ref": "#/components/parameters/username" responses: '200': description: Response content: application/json: schema: "$ref": "#/components/schemas/team-membership" examples: response-if-user-is-a-team-maintainer: "$ref": "#/components/examples/team-membership-response-if-user-is-a-team-maintainer" '404': "$ref": "#/components/responses/not_found" x-github: githubCloudOnly: false enabledForGitHubApps: true removalDate: '2021-02-01' deprecationDate: '2020-01-21' category: teams subcategory: members deprecated: true put: summary: Add or update team membership for a user (Legacy) description: |- **Deprecation Notice:** This endpoint route is deprecated and will be removed from the Teams API. We recommend migrating your existing code to use the new [Add or update team membership for a user](https://docs.github.com/enterprise-server@3.0/rest/reference/teams#add-or-update-team-membership-for-a-user) endpoint. Team synchronization is available for organizations using GitHub Enterprise Cloud. For more information, see [GitHub's products](https://docs.github.com/github/getting-started-with-github/githubs-products) in the GitHub Help documentation. If the user is already a member of the team's organization, this endpoint will add the user to the team. To add a membership between an organization member and a team, the authenticated user must be an organization owner or a team maintainer. **Note:** When you have team synchronization set up for a team with your organization's identity provider (IdP), you will see an error if you attempt to use the API for making changes to the team's membership. If you have access to manage group membership in your IdP, you can manage GitHub Enterprise Server team membership through your identity provider, which automatically adds and removes team members in an organization. For more information, see "[Synchronizing teams between your identity provider and GitHub Enterprise Server](https://docs.github.com/articles/synchronizing-teams-between-your-identity-provider-and-github/)." If the user is unaffiliated with the team's organization, this endpoint will send an invitation to the user via email. This newly-created membership will be in the "pending" state until the user accepts the invitation, at which point the membership will transition to the "active" state and the user will be added as a member of the team. To add a membership between an unaffiliated user and a team, the authenticated user must be an organization owner. If the user is already a member of the team, this endpoint will update the role of the team member's role. To update the membership of a team member, the authenticated user must be an organization owner or a team maintainer. tags: - teams operationId: teams/add-or-update-membership-for-user-legacy externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/teams#add-or-update-team-membership-for-a-user-legacy parameters: - "$ref": "#/components/parameters/team-id" - "$ref": "#/components/parameters/username" requestBody: required: false content: application/json: schema: type: object properties: role: type: string description: "The role that this user should have in the team. Can be one of: \n\\* `member` - a normal member of the team. \n\\* `maintainer` - a team maintainer. Able to add/remove other team members, promote other team members to team maintainer, and edit the team's name and description." enum: - member - maintainer default: member responses: '200': description: Response content: application/json: schema: "$ref": "#/components/schemas/team-membership" examples: response-if-users-membership-with-team-is-now-pending: "$ref": "#/components/examples/team-membership-response-if-users-membership-with-team-is-now-pending" '403': description: Forbidden if team synchronization is set up '422': description: Unprocessable Entity if you attempt to add an organization to a team '404': "$ref": "#/components/responses/not_found" x-github: githubCloudOnly: false enabledForGitHubApps: true removalDate: '2021-02-01' deprecationDate: '2020-01-21' category: teams subcategory: members deprecated: true delete: summary: Remove team membership for a user (Legacy) description: |- **Deprecation Notice:** This endpoint route is deprecated and will be removed from the Teams API. We recommend migrating your existing code to use the new [Remove team membership for a user](https://docs.github.com/enterprise-server@3.0/rest/reference/teams#remove-team-membership-for-a-user) endpoint. Team synchronization is available for organizations using GitHub Enterprise Cloud. For more information, see [GitHub's products](https://docs.github.com/github/getting-started-with-github/githubs-products) in the GitHub Help documentation. To remove a membership between a user and a team, the authenticated user must have 'admin' permissions to the team or be an owner of the organization that the team is associated with. Removing team membership does not delete the user, it just removes their membership from the team. **Note:** When you have team synchronization set up for a team with your organization's identity provider (IdP), you will see an error if you attempt to use the API for making changes to the team's membership. If you have access to manage group membership in your IdP, you can manage GitHub Enterprise Server team membership through your identity provider, which automatically adds and removes team members in an organization. For more information, see "[Synchronizing teams between your identity provider and GitHub Enterprise Server](https://docs.github.com/articles/synchronizing-teams-between-your-identity-provider-and-github/)." tags: - teams operationId: teams/remove-membership-for-user-legacy externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/teams#remove-team-membership-for-a-user-legacy parameters: - "$ref": "#/components/parameters/team-id" - "$ref": "#/components/parameters/username" responses: '204': description: Response '403': description: if team synchronization is set up x-github: githubCloudOnly: false enabledForGitHubApps: true removalDate: '2021-02-01' deprecationDate: '2020-01-21' category: teams subcategory: members deprecated: true "/teams/{team_id}/projects": get: summary: List team projects (Legacy) description: |- **Deprecation Notice:** This endpoint route is deprecated and will be removed from the Teams API. We recommend migrating your existing code to use the new [`List team projects`](https://docs.github.com/enterprise-server@3.0/rest/reference/teams#list-team-projects) endpoint. Lists the organization projects for a team. tags: - teams operationId: teams/list-projects-legacy externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/teams/#list-team-projects-legacy parameters: - "$ref": "#/components/parameters/team-id" - "$ref": "#/components/parameters/per-page" - "$ref": "#/components/parameters/page" responses: '200': description: Response content: application/json: schema: type: array items: "$ref": "#/components/schemas/team-project" examples: default: "$ref": "#/components/examples/team-project-items" headers: Link: "$ref": "#/components/headers/link" '404': "$ref": "#/components/responses/not_found" x-github: githubCloudOnly: false enabledForGitHubApps: true removalDate: '2021-02-01' deprecationDate: '2020-01-21' category: teams previews: - required: true name: inertia note: |- The Projects API is currently available for developers to preview. During the preview period, the API may change without advance notice. Please see the [blog post](https://developer.github.com/changes/2016-10-27-changes-to-projects-api) for full details. To access the API during the preview period, you must provide a custom [media type](https://docs.github.com/enterprise-server@3.0/rest/overview/media-types) in the `Accept` header: ```shell application/vnd.github.inertia-preview+json ``` deprecated: true "/teams/{team_id}/projects/{project_id}": get: summary: Check team permissions for a project (Legacy) description: |- **Deprecation Notice:** This endpoint route is deprecated and will be removed from the Teams API. We recommend migrating your existing code to use the new [Check team permissions for a project](https://docs.github.com/enterprise-server@3.0/rest/reference/teams#check-team-permissions-for-a-project) endpoint. Checks whether a team has `read`, `write`, or `admin` permissions for an organization project. The response includes projects inherited from a parent team. tags: - teams operationId: teams/check-permissions-for-project-legacy externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/teams/#check-team-permissions-for-a-project-legacy parameters: - "$ref": "#/components/parameters/team-id" - "$ref": "#/components/parameters/project-id" responses: '200': description: Response content: application/json: schema: "$ref": "#/components/schemas/team-project" examples: default: "$ref": "#/components/examples/team-project" '404': description: Not Found if project is not managed by this team x-github: githubCloudOnly: false enabledForGitHubApps: true removalDate: '2021-02-01' deprecationDate: '2020-01-21' category: teams previews: - required: true name: inertia note: |- The Projects API is currently available for developers to preview. During the preview period, the API may change without advance notice. Please see the [blog post](https://developer.github.com/changes/2016-10-27-changes-to-projects-api) for full details. To access the API during the preview period, you must provide a custom [media type](https://docs.github.com/enterprise-server@3.0/rest/overview/media-types) in the `Accept` header: ```shell application/vnd.github.inertia-preview+json ``` deprecated: true put: summary: Add or update team project permissions (Legacy) description: |- **Deprecation Notice:** This endpoint route is deprecated and will be removed from the Teams API. We recommend migrating your existing code to use the new [Add or update team project permissions](https://docs.github.com/enterprise-server@3.0/rest/reference/teams#add-or-update-team-project-permissions) endpoint. Adds an organization project to a team. To add a project to a team or update the team's permission on a project, the authenticated user must have `admin` permissions for the project. The project and team must be part of the same organization. tags: - teams operationId: teams/add-or-update-project-permissions-legacy externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/teams/#add-or-update-team-project-permissions-legacy parameters: - "$ref": "#/components/parameters/team-id" - "$ref": "#/components/parameters/project-id" requestBody: required: false content: application/json: schema: type: object properties: permission: type: string description: "The permission to grant to the team for this project. Can be one of: \n\\* `read` - team members can read, but not write to or administer this project. \n\\* `write` - team members can read and write, but not administer this project. \n\\* `admin` - team members can read, write and administer this project. \nDefault: the team's `permission` attribute will be used to determine what permission to grant the team on this project. Note that, if you choose not to pass any parameters, you'll need to set `Content-Length` to zero when calling out to this endpoint. For more information, see \"[HTTP verbs](https://docs.github.com/enterprise-server@3.0/rest/overview/resources-in-the-rest-api#http-verbs).\"" enum: - read - write - admin responses: '204': description: Response '403': description: Forbidden if the project is not owned by the organization content: application/json: schema: type: object properties: message: type: string documentation_url: type: string examples: response-if-the-project-is-not-owned-by-the-organization: value: message: Must have admin rights to Repository. documentation_url: https://docs.github.com/enterprise-server@3.0/rest/reference/teams#add-or-update-team-project-permissions '404': "$ref": "#/components/responses/not_found" '422': "$ref": "#/components/responses/validation_failed" x-github: githubCloudOnly: false enabledForGitHubApps: true removalDate: '2021-02-01' deprecationDate: '2020-01-21' category: teams previews: - required: true name: inertia note: |- The Projects API is currently available for developers to preview. During the preview period, the API may change without advance notice. Please see the [blog post](https://developer.github.com/changes/2016-10-27-changes-to-projects-api) for full details. To access the API during the preview period, you must provide a custom [media type](https://docs.github.com/enterprise-server@3.0/rest/overview/media-types) in the `Accept` header: ```shell application/vnd.github.inertia-preview+json ``` deprecated: true delete: summary: Remove a project from a team (Legacy) description: |- **Deprecation Notice:** This endpoint route is deprecated and will be removed from the Teams API. We recommend migrating your existing code to use the new [Remove a project from a team](https://docs.github.com/enterprise-server@3.0/rest/reference/teams#remove-a-project-from-a-team) endpoint. Removes an organization project from a team. An organization owner or a team maintainer can remove any project from the team. To remove a project from a team as an organization member, the authenticated user must have `read` access to both the team and project, or `admin` access to the team or project. **Note:** This endpoint removes the project from the team, but does not delete it. tags: - teams operationId: teams/remove-project-legacy externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/teams/#remove-a-project-from-a-team-legacy parameters: - "$ref": "#/components/parameters/team-id" - "$ref": "#/components/parameters/project-id" responses: '204': description: Response '404': "$ref": "#/components/responses/not_found" '415': "$ref": "#/components/responses/preview_header_missing" '422': "$ref": "#/components/responses/validation_failed" x-github: githubCloudOnly: false enabledForGitHubApps: true removalDate: '2021-02-01' deprecationDate: '2020-01-21' category: teams subcategory: deprecated: true "/teams/{team_id}/repos": get: summary: List team repositories (Legacy) description: "**Deprecation Notice:** This endpoint route is deprecated and will be removed from the Teams API. We recommend migrating your existing code to use the new [List team repositories](https://docs.github.com/enterprise-server@3.0/rest/reference/teams#list-team-repositories) endpoint." tags: - teams operationId: teams/list-repos-legacy externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/teams/#list-team-repositories-legacy parameters: - "$ref": "#/components/parameters/team-id" - "$ref": "#/components/parameters/per-page" - "$ref": "#/components/parameters/page" responses: '200': description: Response content: application/json: schema: type: array items: "$ref": "#/components/schemas/minimal-repository" examples: default: "$ref": "#/components/examples/minimal-repository-items" headers: Link: "$ref": "#/components/headers/link" '404': "$ref": "#/components/responses/not_found" x-github: githubCloudOnly: false enabledForGitHubApps: true removalDate: '2021-02-01' deprecationDate: '2020-01-21' category: teams subcategory: deprecated: true "/teams/{team_id}/repos/{owner}/{repo}": get: summary: Check team permissions for a repository (Legacy) description: |- **Note**: Repositories inherited through a parent team will also be checked. **Deprecation Notice:** This endpoint route is deprecated and will be removed from the Teams API. We recommend migrating your existing code to use the new [Check team permissions for a repository](https://docs.github.com/enterprise-server@3.0/rest/reference/teams#check-team-permissions-for-a-repository) endpoint. You can also get information about the specified repository, including what permissions the team grants on it, by passing the following custom [media type](https://docs.github.com/enterprise-server@3.0/rest/overview/media-types/) via the `Accept` header: tags: - teams operationId: teams/check-permissions-for-repo-legacy externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/teams/#check-team-permissions-for-a-repository-legacy parameters: - "$ref": "#/components/parameters/team-id" - "$ref": "#/components/parameters/owner" - "$ref": "#/components/parameters/repo" responses: '200': description: Alternative response with extra repository information content: application/json: schema: "$ref": "#/components/schemas/team-repository" examples: alternative-response-with-extra-repository-information: "$ref": "#/components/examples/team-repository-alternative-response-with-extra-repository-information" '204': description: Response if repository is managed by this team '404': description: Not Found if repository is not managed by this team x-github: githubCloudOnly: false enabledForGitHubApps: true removalDate: '2021-02-01' deprecationDate: '2020-01-21' category: teams subcategory: deprecated: true put: summary: Add or update team repository permissions (Legacy) description: |- **Deprecation Notice:** This endpoint route is deprecated and will be removed from the Teams API. We recommend migrating your existing code to use the new "[Add or update team repository permissions](https://docs.github.com/enterprise-server@3.0/rest/reference/teams#add-or-update-team-repository-permissions)" endpoint. To add a repository to a team or update the team's permission on a repository, the authenticated user must have admin access to the repository, and must be able to see the team. The repository must be owned by the organization, or a direct fork of a repository owned by the organization. You will get a `422 Unprocessable Entity` status if you attempt to add a repository to a team that is not owned by the organization. Note that, if you choose not to pass any parameters, you'll need to set `Content-Length` to zero when calling out to this endpoint. For more information, see "[HTTP verbs](https://docs.github.com/enterprise-server@3.0/rest/overview/resources-in-the-rest-api#http-verbs)." tags: - teams operationId: teams/add-or-update-repo-permissions-legacy externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/teams/#add-or-update-team-repository-permissions-legacy parameters: - "$ref": "#/components/parameters/team-id" - "$ref": "#/components/parameters/owner" - "$ref": "#/components/parameters/repo" requestBody: required: false content: application/json: schema: type: object properties: permission: type: string description: "The permission to grant the team on this repository. Can be one of: \n\\* `pull` - team members can pull, but not push to or administer this repository. \n\\* `push` - team members can pull and push, but not administer this repository. \n\\* `admin` - team members can pull, push and administer this repository. \ \n \nIf no permission is specified, the team's `permission` attribute will be used to determine what permission to grant the team on this repository." enum: - pull - push - admin responses: '204': description: Response '403': "$ref": "#/components/responses/forbidden" '422': "$ref": "#/components/responses/validation_failed" x-github: githubCloudOnly: false enabledForGitHubApps: true removalDate: '2021-02-01' deprecationDate: '2020-01-21' category: teams subcategory: deprecated: true delete: summary: Remove a repository from a team (Legacy) description: |- **Deprecation Notice:** This endpoint route is deprecated and will be removed from the Teams API. We recommend migrating your existing code to use the new [Remove a repository from a team](https://docs.github.com/enterprise-server@3.0/rest/reference/teams#remove-a-repository-from-a-team) endpoint. If the authenticated user is an organization owner or a team maintainer, they can remove any repositories from the team. To remove a repository from a team as an organization member, the authenticated user must have admin access to the repository and must be able to see the team. NOTE: This does not delete the repository, it just removes it from the team. tags: - teams operationId: teams/remove-repo-legacy externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/teams/#remove-a-repository-from-a-team-legacy parameters: - "$ref": "#/components/parameters/team-id" - "$ref": "#/components/parameters/owner" - "$ref": "#/components/parameters/repo" responses: '204': description: Response x-github: githubCloudOnly: false enabledForGitHubApps: true removalDate: '2021-02-01' deprecationDate: '2020-01-21' category: teams subcategory: deprecated: true "/teams/{team_id}/teams": get: summary: List child teams (Legacy) description: "**Deprecation Notice:** This endpoint route is deprecated and will be removed from the Teams API. We recommend migrating your existing code to use the new [`List child teams`](https://docs.github.com/enterprise-server@3.0/rest/reference/teams#list-child-teams) endpoint." tags: - teams operationId: teams/list-child-legacy externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/teams/#list-child-teams-legacy parameters: - "$ref": "#/components/parameters/team-id" - "$ref": "#/components/parameters/per-page" - "$ref": "#/components/parameters/page" responses: '200': description: if child teams exist content: application/json: schema: type: array items: "$ref": "#/components/schemas/team" examples: response-if-child-teams-exist: "$ref": "#/components/examples/team-items-response-if-child-teams-exist" headers: Link: "$ref": "#/components/headers/link" '404': "$ref": "#/components/responses/not_found" '403': "$ref": "#/components/responses/forbidden" '422': "$ref": "#/components/responses/validation_failed" x-github: githubCloudOnly: false enabledForGitHubApps: true removalDate: '2021-02-01' deprecationDate: '2020-01-21' category: teams subcategory: deprecated: true "/user": get: summary: Get the authenticated user description: |- If the authenticated user is authenticated through basic authentication or OAuth with the `user` scope, then the response lists public and private profile information. If the authenticated user is authenticated through OAuth without the `user` scope, then the response lists only public profile information. tags: - users operationId: users/get-authenticated externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/users#get-the-authenticated-user parameters: [] responses: '200': description: Response content: application/json: schema: oneOf: - "$ref": "#/components/schemas/private-user" - "$ref": "#/components/schemas/public-user" examples: response-with-public-and-private-profile-information: "$ref": "#/components/examples/private-user-response-with-public-and-private-profile-information" response-with-public-profile-information: "$ref": "#/components/examples/private-user-response-with-public-profile-information" '304': "$ref": "#/components/responses/not_modified" '403': "$ref": "#/components/responses/forbidden" '401': "$ref": "#/components/responses/requires_authentication" x-github: githubCloudOnly: false enabledForGitHubApps: false category: users subcategory: patch: summary: Update the authenticated user description: "**Note:** If your email is set to private and you send an `email` parameter as part of this request to update your profile, your privacy settings are still enforced: the email address will not be displayed on your public profile or via the API." tags: - users operationId: users/update-authenticated externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/users/#update-the-authenticated-user parameters: [] requestBody: required: false content: application/json: schema: type: object properties: name: description: The new name of the user. type: string examples: - Omar Jahandar email: description: The publicly visible email address of the user. type: string examples: - omar@example.com blog: description: The new blog URL of the user. type: string examples: - blog.example.com twitter_username: description: The new Twitter username of the user. type: - string - 'null' examples: - therealomarj company: description: The new company of the user. type: string examples: - Acme corporation location: description: The new location of the user. type: string examples: - Berlin, Germany hireable: description: The new hiring availability of the user. type: boolean bio: description: The new short biography of the user. type: string responses: '200': description: Response content: application/json: schema: "$ref": "#/components/schemas/private-user" examples: default: "$ref": "#/components/examples/private-user" '304': "$ref": "#/components/responses/not_modified" '404': "$ref": "#/components/responses/not_found" '403': "$ref": "#/components/responses/forbidden" '401': "$ref": "#/components/responses/requires_authentication" '422': "$ref": "#/components/responses/validation_failed" x-github: githubCloudOnly: false enabledForGitHubApps: false category: users subcategory: "/user/emails": get: summary: List email addresses for the authenticated user description: Lists all of your email addresses, and specifies which one is visible to the public. This endpoint is accessible with the `user:email` scope. tags: - users operationId: users/list-emails-for-authenticated-user externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/users#list-email-addresses-for-the-authenticated-user parameters: - "$ref": "#/components/parameters/per-page" - "$ref": "#/components/parameters/page" responses: '200': description: Response content: application/json: schema: type: array items: "$ref": "#/components/schemas/email" examples: default: "$ref": "#/components/examples/email-items-2" headers: Link: "$ref": "#/components/headers/link" '304': "$ref": "#/components/responses/not_modified" '404': "$ref": "#/components/responses/not_found" '403': "$ref": "#/components/responses/forbidden" '401': "$ref": "#/components/responses/requires_authentication" x-github: githubCloudOnly: false enabledForGitHubApps: false category: users subcategory: emails post: summary: Add an email address for the authenticated user description: This endpoint is accessible with the `user` scope. tags: - users operationId: users/add-email-for-authenticated-user externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/users#add-an-email-address-for-the-authenticated-user parameters: [] requestBody: required: false content: application/json: schema: oneOf: - type: object properties: emails: description: Adds one or more email addresses to your GitHub account. Must contain at least one email address. **Note:** Alternatively, you can pass a single email address or an `array` of emails addresses directly, but we recommend that you pass an object using the `emails` key. type: array items: type: string minItems: 1 examples: - username@example.com examples: [] required: - emails example: emails: - octocat@github.com - mona@github.com - type: array items: type: string minItems: 1 examples: - username@example.com - type: string responses: '201': description: Response content: application/json: schema: type: array items: "$ref": "#/components/schemas/email" examples: default: "$ref": "#/components/examples/email-items" '422': "$ref": "#/components/responses/validation_failed" '304': "$ref": "#/components/responses/not_modified" '404': "$ref": "#/components/responses/not_found" '403': "$ref": "#/components/responses/forbidden" '401': "$ref": "#/components/responses/requires_authentication" x-github: githubCloudOnly: false enabledForGitHubApps: false category: users subcategory: emails delete: summary: Delete an email address for the authenticated user description: This endpoint is accessible with the `user` scope. tags: - users operationId: users/delete-email-for-authenticated-user externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/users#delete-an-email-address-for-the-authenticated-user parameters: [] requestBody: content: application/json: schema: oneOf: - type: object description: Deletes one or more email addresses from your GitHub account. Must contain at least one email address. **Note:** Alternatively, you can pass a single email address or an `array` of emails addresses directly, but we recommend that you pass an object using the `emails` key. properties: emails: description: Email addresses associated with the GitHub user account. type: array items: type: string minItems: 1 examples: - username@example.com example: emails: - octocat@github.com - mona@github.com required: - emails - type: array items: type: string minItems: 1 examples: - username@example.com - type: string responses: '204': description: Response '304': "$ref": "#/components/responses/not_modified" '404': "$ref": "#/components/responses/not_found" '403': "$ref": "#/components/responses/forbidden" '401': "$ref": "#/components/responses/requires_authentication" '422': "$ref": "#/components/responses/validation_failed" x-github: githubCloudOnly: false enabledForGitHubApps: false category: users subcategory: emails "/user/followers": get: summary: List followers of the authenticated user description: Lists the people following the authenticated user. tags: - users operationId: users/list-followers-for-authenticated-user externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/users#list-followers-of-the-authenticated-user parameters: - "$ref": "#/components/parameters/per-page" - "$ref": "#/components/parameters/page" responses: '200': description: Response content: application/json: schema: type: array items: "$ref": "#/components/schemas/simple-user" examples: default: "$ref": "#/components/examples/simple-user-items" headers: Link: "$ref": "#/components/headers/link" '304': "$ref": "#/components/responses/not_modified" '403': "$ref": "#/components/responses/forbidden" '401': "$ref": "#/components/responses/requires_authentication" x-github: githubCloudOnly: false enabledForGitHubApps: false category: users subcategory: followers "/user/following": get: summary: List the people the authenticated user follows description: Lists the people who the authenticated user follows. tags: - users operationId: users/list-followed-by-authenticated-user externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/users#list-the-people-the-authenticated-user-follows parameters: - "$ref": "#/components/parameters/per-page" - "$ref": "#/components/parameters/page" responses: '200': description: Response content: application/json: schema: type: array items: "$ref": "#/components/schemas/simple-user" examples: default: "$ref": "#/components/examples/simple-user-items" headers: Link: "$ref": "#/components/headers/link" '304': "$ref": "#/components/responses/not_modified" '403': "$ref": "#/components/responses/forbidden" '401': "$ref": "#/components/responses/requires_authentication" x-github: githubCloudOnly: false enabledForGitHubApps: false category: users subcategory: followers "/user/following/{username}": get: summary: Check if a person is followed by the authenticated user description: '' tags: - users operationId: users/check-person-is-followed-by-authenticated externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/users#check-if-a-person-is-followed-by-the-authenticated-user parameters: - "$ref": "#/components/parameters/username" responses: '204': description: if the person is followed by the authenticated user '404': description: if the person is not followed by the authenticated user content: application/json: schema: "$ref": "#/components/schemas/basic-error" '304': "$ref": "#/components/responses/not_modified" '403': "$ref": "#/components/responses/forbidden" '401': "$ref": "#/components/responses/requires_authentication" x-github: githubCloudOnly: false enabledForGitHubApps: false category: users subcategory: followers put: summary: Follow a user description: |- Note that you'll need to set `Content-Length` to zero when calling out to this endpoint. For more information, see "[HTTP verbs](https://docs.github.com/enterprise-server@3.0/rest/overview/resources-in-the-rest-api#http-verbs)." Following a user requires the user to be logged in and authenticated with basic auth or OAuth with the `user:follow` scope. tags: - users operationId: users/follow externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/users#follow-a-user parameters: - "$ref": "#/components/parameters/username" responses: '204': description: Response '304': "$ref": "#/components/responses/not_modified" '404': "$ref": "#/components/responses/not_found" '403': "$ref": "#/components/responses/forbidden" '401': "$ref": "#/components/responses/requires_authentication" x-github: githubCloudOnly: false enabledForGitHubApps: false category: users subcategory: followers delete: summary: Unfollow a user description: Unfollowing a user requires the user to be logged in and authenticated with basic auth or OAuth with the `user:follow` scope. tags: - users operationId: users/unfollow externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/users#unfollow-a-user parameters: - "$ref": "#/components/parameters/username" responses: '204': description: Response '304': "$ref": "#/components/responses/not_modified" '404': "$ref": "#/components/responses/not_found" '403': "$ref": "#/components/responses/forbidden" '401': "$ref": "#/components/responses/requires_authentication" x-github: githubCloudOnly: false enabledForGitHubApps: false category: users subcategory: followers "/user/gpg_keys": get: summary: List GPG keys for the authenticated user description: Lists the current user's GPG keys. Requires that you are authenticated via Basic Auth or via OAuth with at least `read:gpg_key` [scope](https://docs.github.com/enterprise-server@3.0/apps/building-oauth-apps/understanding-scopes-for-oauth-apps/). tags: - users operationId: users/list-gpg-keys-for-authenticated-user externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/users#list-gpg-keys-for-the-authenticated-user parameters: - "$ref": "#/components/parameters/per-page" - "$ref": "#/components/parameters/page" responses: '200': description: Response content: application/json: schema: type: array items: "$ref": "#/components/schemas/gpg-key" examples: default: "$ref": "#/components/examples/gpg-key-items" headers: Link: "$ref": "#/components/headers/link" '304': "$ref": "#/components/responses/not_modified" '404': "$ref": "#/components/responses/not_found" '403': "$ref": "#/components/responses/forbidden" '401': "$ref": "#/components/responses/requires_authentication" x-github: githubCloudOnly: false enabledForGitHubApps: false category: users subcategory: gpg-keys post: summary: Create a GPG key for the authenticated user description: Adds a GPG key to the authenticated user's GitHub account. Requires that you are authenticated via Basic Auth, or OAuth with at least `write:gpg_key` [scope](https://docs.github.com/enterprise-server@3.0/apps/building-oauth-apps/understanding-scopes-for-oauth-apps/). operationId: users/create-gpg-key-for-authenticated-user tags: - users externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/users#create-a-gpg-key-for-the-authenticated-user parameters: [] requestBody: required: true content: application/json: schema: properties: armored_public_key: description: A GPG key in ASCII-armored format. type: string type: object required: - armored_public_key responses: '201': description: Response content: application/json: schema: "$ref": "#/components/schemas/gpg-key" examples: default: "$ref": "#/components/examples/gpg-key" '422': "$ref": "#/components/responses/validation_failed" '304': "$ref": "#/components/responses/not_modified" '404': "$ref": "#/components/responses/not_found" '403': "$ref": "#/components/responses/forbidden" '401': "$ref": "#/components/responses/requires_authentication" x-github: githubCloudOnly: false enabledForGitHubApps: false category: users subcategory: gpg-keys "/user/gpg_keys/{gpg_key_id}": get: summary: Get a GPG key for the authenticated user description: View extended details for a single GPG key. Requires that you are authenticated via Basic Auth or via OAuth with at least `read:gpg_key` [scope](https://docs.github.com/enterprise-server@3.0/apps/building-oauth-apps/understanding-scopes-for-oauth-apps/). tags: - users operationId: users/get-gpg-key-for-authenticated-user externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/users#get-a-gpg-key-for-the-authenticated-user parameters: - "$ref": "#/components/parameters/gpg-key-id" responses: '200': description: Response content: application/json: schema: "$ref": "#/components/schemas/gpg-key" examples: default: "$ref": "#/components/examples/gpg-key" '404': "$ref": "#/components/responses/not_found" '304': "$ref": "#/components/responses/not_modified" '403': "$ref": "#/components/responses/forbidden" '401': "$ref": "#/components/responses/requires_authentication" x-github: githubCloudOnly: false enabledForGitHubApps: false category: users subcategory: gpg-keys delete: summary: Delete a GPG key for the authenticated user description: Removes a GPG key from the authenticated user's GitHub account. Requires that you are authenticated via Basic Auth or via OAuth with at least `admin:gpg_key` [scope](https://docs.github.com/enterprise-server@3.0/apps/building-oauth-apps/understanding-scopes-for-oauth-apps/). tags: - users operationId: users/delete-gpg-key-for-authenticated-user externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/users#delete-a-gpg-key-for-the-authenticated-user parameters: - "$ref": "#/components/parameters/gpg-key-id" responses: '204': description: Response '404': "$ref": "#/components/responses/not_found" '422': "$ref": "#/components/responses/validation_failed" '304': "$ref": "#/components/responses/not_modified" '403': "$ref": "#/components/responses/forbidden" '401': "$ref": "#/components/responses/requires_authentication" x-github: githubCloudOnly: false enabledForGitHubApps: false category: users subcategory: gpg-keys "/user/installations": get: summary: List app installations accessible to the user access token description: |- Lists installations of your GitHub App that the authenticated user has explicit permission (`:read`, `:write`, or `:admin`) to access. You must use a [user-to-server OAuth access token](https://docs.github.com/enterprise-server@3.0/apps/building-github-apps/identifying-and-authorizing-users-for-github-apps/#identifying-users-on-your-site), created for a user who has authorized your GitHub App, to access this endpoint. The authenticated user has explicit permission to access repositories they own, repositories where they are a collaborator, and repositories that they can access through an organization membership. You can find the permissions for the installation under the `permissions` key. tags: - apps operationId: apps/list-installations-for-authenticated-user externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/apps#list-app-installations-accessible-to-the-user-access-token parameters: - "$ref": "#/components/parameters/per-page" - "$ref": "#/components/parameters/page" responses: '200': description: You can find the permissions for the installation under the `permissions` key. content: application/json: schema: type: object required: - total_count - installations properties: total_count: type: integer installations: type: array items: "$ref": "#/components/schemas/installation" examples: default: "$ref": "#/components/examples/base-installation-for-auth-user-paginated" headers: Link: "$ref": "#/components/headers/link" '304': "$ref": "#/components/responses/not_modified" '403': "$ref": "#/components/responses/forbidden" '401': "$ref": "#/components/responses/requires_authentication" '415': "$ref": "#/components/responses/preview_header_missing" x-github: githubCloudOnly: false enabledForGitHubApps: false category: apps subcategory: installations "/user/installations/{installation_id}/repositories": get: summary: List repositories accessible to the user access token description: |- List repositories that the authenticated user has explicit permission (`:read`, `:write`, or `:admin`) to access for an installation. The authenticated user has explicit permission to access repositories they own, repositories where they are a collaborator, and repositories that they can access through an organization membership. You must use a [user-to-server OAuth access token](https://docs.github.com/enterprise-server@3.0/apps/building-github-apps/identifying-and-authorizing-users-for-github-apps/#identifying-users-on-your-site), created for a user who has authorized your GitHub App, to access this endpoint. The access the user has to each repository is included in the hash under the `permissions` key. tags: - apps operationId: apps/list-installation-repos-for-authenticated-user externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/apps#list-repositories-accessible-to-the-user-access-token parameters: - "$ref": "#/components/parameters/installation-id" - "$ref": "#/components/parameters/per-page" - "$ref": "#/components/parameters/page" responses: '200': description: The access the user has to each repository is included in the hash under the `permissions` key. content: application/json: schema: type: object required: - total_count - repositories properties: total_count: type: integer repository_selection: type: string repositories: type: array items: "$ref": "#/components/schemas/repository" examples: default: "$ref": "#/components/examples/repository-paginated" headers: Link: "$ref": "#/components/headers/link" '404': "$ref": "#/components/responses/not_found" '403': "$ref": "#/components/responses/forbidden" '304': "$ref": "#/components/responses/not_modified" x-github: githubCloudOnly: false enabledForGitHubApps: false category: apps subcategory: installations previews: - required: false name: mercy note: |- The `topics` property for repositories on GitHub is currently available for developers to preview. To view the `topics` property in calls that return repository results, you must provide a custom [media type](https://docs.github.com/enterprise-server@3.0/rest/overview/media-types) in the `Accept` header: ```shell application/vnd.github.mercy-preview+json ``` "/user/installations/{installation_id}/repositories/{repository_id}": put: summary: Add a repository to an app installation description: |- Add a single repository to an installation. The authenticated user must have admin access to the repository. You must use a personal access token (which you can create via the [command line](https://docs.github.com/enterprise-server@3.0/github/authenticating-to-github/creating-a-personal-access-token) or [Basic Authentication](https://docs.github.com/enterprise-server@3.0/rest/overview/other-authentication-methods#basic-authentication)) to access this endpoint. tags: - apps operationId: apps/add-repo-to-installation-for-authenticated-user externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/apps#add-a-repository-to-an-app-installation parameters: - "$ref": "#/components/parameters/installation-id" - "$ref": "#/components/parameters/repository-id" responses: '204': description: Response '403': "$ref": "#/components/responses/forbidden" '304': "$ref": "#/components/responses/not_modified" '404': "$ref": "#/components/responses/not_found" x-github: githubCloudOnly: false enabledForGitHubApps: false category: apps subcategory: installations delete: summary: Remove a repository from an app installation description: |- Remove a single repository from an installation. The authenticated user must have admin access to the repository. You must use a personal access token (which you can create via the [command line](https://docs.github.com/enterprise-server@3.0/github/authenticating-to-github/creating-a-personal-access-token) or [Basic Authentication](https://docs.github.com/enterprise-server@3.0/rest/overview/other-authentication-methods#basic-authentication)) to access this endpoint. tags: - apps operationId: apps/remove-repo-from-installation-for-authenticated-user externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/apps#remove-a-repository-from-an-app-installation parameters: - "$ref": "#/components/parameters/installation-id" - "$ref": "#/components/parameters/repository-id" responses: '204': description: Response '403': "$ref": "#/components/responses/forbidden" '304': "$ref": "#/components/responses/not_modified" '404': "$ref": "#/components/responses/not_found" x-github: githubCloudOnly: false enabledForGitHubApps: false category: apps subcategory: installations "/user/issues": get: summary: List user account issues assigned to the authenticated user description: |- List issues across owned and member repositories assigned to the authenticated user. **Note**: GitHub's REST API v3 considers every pull request an issue, but not every issue is a pull request. For this reason, "Issues" endpoints may return both issues and pull requests in the response. You can identify pull requests by the `pull_request` key. Be aware that the `id` of a pull request returned from "Issues" endpoints will be an _issue id_. To find out the pull request id, use the "[List pull requests](https://docs.github.com/enterprise-server@3.0/rest/reference/pulls#list-pull-requests)" endpoint. tags: - issues operationId: issues/list-for-authenticated-user externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/issues#list-user-account-issues-assigned-to-the-authenticated-user parameters: - name: filter description: "Indicates which sorts of issues to return. Can be one of: \n\\* `assigned`: Issues assigned to you \n\\* `created`: Issues created by you \ \n\\* `mentioned`: Issues mentioning you \n\\* `subscribed`: Issues you're subscribed to updates for \n\\* `all` or `repos`: All issues the authenticated user can see, regardless of participation or creation" in: query required: false schema: type: string enum: - assigned - created - mentioned - subscribed - repos - all default: assigned - name: state description: Indicates the state of the issues to return. Can be either `open`, `closed`, or `all`. in: query required: false schema: type: string enum: - open - closed - all default: open - "$ref": "#/components/parameters/labels" - name: sort description: What to sort results by. Can be either `created`, `updated`, `comments`. in: query required: false schema: type: string enum: - created - updated - comments default: created - "$ref": "#/components/parameters/direction" - "$ref": "#/components/parameters/since" - "$ref": "#/components/parameters/per-page" - "$ref": "#/components/parameters/page" responses: '200': description: Response content: application/json: schema: type: array items: "$ref": "#/components/schemas/issue" examples: default: "$ref": "#/components/examples/issue-with-repo-items" headers: Link: "$ref": "#/components/headers/link" '404': "$ref": "#/components/responses/not_found" '304': "$ref": "#/components/responses/not_modified" x-github: githubCloudOnly: false enabledForGitHubApps: false category: issues previews: - required: false name: machine-man note: "If an issue event is created via a GitHub App, the response will include the `performed_via_github_app` object with\tinformation about the GitHub App. For more information, see the [related blog\tpost](https://developer.github.com/changes/2016-09-14-Integrations-Early-Access).\nTo receive the `performed_via_github_app` object in the response, you must provide a custom [media type](https://docs.github.com/enterprise-server@3.0/rest/overview/media-types) in the `Accept` header:\n```shell\napplication/vnd.github.machine-man-preview\n```" - required: false name: squirrel-girl note: |- An additional `reactions` object in the issue comment payload is currently available for developers to preview. During the preview period, the APIs may change without advance notice. Please see the [blog post](https://developer.github.com/changes/2016-05-12-reactions-api-preview) for full details. To access the API you must provide a custom [media type](https://docs.github.com/enterprise-server@3.0/rest/overview/media-types) in the `Accept` header: ```shell application/vnd.github.squirrel-girl-preview ``` The `reactions` key will have the following payload where `url` can be used to construct the API location for [listing and creating](https://docs.github.com/enterprise-server@3.0/rest/reference/reactions) reactions. "/user/keys": get: summary: List public SSH keys for the authenticated user description: Lists the public SSH keys for the authenticated user's GitHub account. Requires that you are authenticated via Basic Auth or via OAuth with at least `read:public_key` [scope](https://docs.github.com/enterprise-server@3.0/apps/building-oauth-apps/understanding-scopes-for-oauth-apps/). tags: - users operationId: users/list-public-ssh-keys-for-authenticated-user externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/users#list-public-ssh-keys-for-the-authenticated-user parameters: - "$ref": "#/components/parameters/per-page" - "$ref": "#/components/parameters/page" responses: '200': description: Response content: application/json: schema: type: array items: "$ref": "#/components/schemas/key" examples: default: "$ref": "#/components/examples/key-items" headers: Link: "$ref": "#/components/headers/link" '304': "$ref": "#/components/responses/not_modified" '404': "$ref": "#/components/responses/not_found" '403': "$ref": "#/components/responses/forbidden" '401': "$ref": "#/components/responses/requires_authentication" x-github: githubCloudOnly: false enabledForGitHubApps: false category: users subcategory: keys post: summary: Create a public SSH key for the authenticated user description: Adds a public SSH key to the authenticated user's GitHub account. Requires that you are authenticated via Basic Auth, or OAuth with at least `write:public_key` [scope](https://docs.github.com/enterprise-server@3.0/apps/building-oauth-apps/understanding-scopes-for-oauth-apps/). operationId: users/create-public-ssh-key-for-authenticated-user tags: - users externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/users#create-a-public-ssh-key-for-the-authenticated-user parameters: [] requestBody: required: true content: application/json: schema: properties: title: description: A descriptive name for the new key. type: string examples: - Personal MacBook Air key: description: The public SSH key to add to your GitHub account. type: string pattern: "^ssh-(rsa|dss|ed25519) |^ecdsa-sha2-nistp(256|384|521) " required: - key type: object responses: '201': description: Response content: application/json: schema: "$ref": "#/components/schemas/key" examples: default: "$ref": "#/components/examples/key" '422': "$ref": "#/components/responses/validation_failed" '304': "$ref": "#/components/responses/not_modified" '404': "$ref": "#/components/responses/not_found" '403': "$ref": "#/components/responses/forbidden" '401': "$ref": "#/components/responses/requires_authentication" x-github: githubCloudOnly: false enabledForGitHubApps: false category: users subcategory: keys "/user/keys/{key_id}": get: summary: Get a public SSH key for the authenticated user description: View extended details for a single public SSH key. Requires that you are authenticated via Basic Auth or via OAuth with at least `read:public_key` [scope](https://docs.github.com/enterprise-server@3.0/apps/building-oauth-apps/understanding-scopes-for-oauth-apps/). tags: - users operationId: users/get-public-ssh-key-for-authenticated-user externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/users#get-a-public-ssh-key-for-the-authenticated-user parameters: - "$ref": "#/components/parameters/key-id" responses: '200': description: Response content: application/json: schema: "$ref": "#/components/schemas/key" examples: default: "$ref": "#/components/examples/key" '404': "$ref": "#/components/responses/not_found" '304': "$ref": "#/components/responses/not_modified" '403': "$ref": "#/components/responses/forbidden" '401': "$ref": "#/components/responses/requires_authentication" x-github: githubCloudOnly: false enabledForGitHubApps: false category: users subcategory: keys delete: summary: Delete a public SSH key for the authenticated user description: Removes a public SSH key from the authenticated user's GitHub account. Requires that you are authenticated via Basic Auth or via OAuth with at least `admin:public_key` [scope](https://docs.github.com/enterprise-server@3.0/apps/building-oauth-apps/understanding-scopes-for-oauth-apps/). tags: - users operationId: users/delete-public-ssh-key-for-authenticated-user externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/users#delete-a-public-ssh-key-for-the-authenticated-user parameters: - "$ref": "#/components/parameters/key-id" responses: '204': description: Response '304': "$ref": "#/components/responses/not_modified" '404': "$ref": "#/components/responses/not_found" '403': "$ref": "#/components/responses/forbidden" '401': "$ref": "#/components/responses/requires_authentication" x-github: githubCloudOnly: false enabledForGitHubApps: false category: users subcategory: keys "/user/memberships/orgs": get: summary: List organization memberships for the authenticated user description: '' tags: - orgs operationId: orgs/list-memberships-for-authenticated-user externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/orgs#list-organization-memberships-for-the-authenticated-user parameters: - name: state description: Indicates the state of the memberships to return. Can be either `active` or `pending`. If not specified, the API returns both active and pending memberships. in: query required: false schema: type: string enum: - active - pending - "$ref": "#/components/parameters/per-page" - "$ref": "#/components/parameters/page" responses: '200': description: Response content: application/json: schema: type: array items: "$ref": "#/components/schemas/org-membership" examples: default: "$ref": "#/components/examples/org-membership-items" headers: Link: "$ref": "#/components/headers/link" '304': "$ref": "#/components/responses/not_modified" '403': "$ref": "#/components/responses/forbidden" '401': "$ref": "#/components/responses/requires_authentication" '422': "$ref": "#/components/responses/validation_failed" x-github: githubCloudOnly: false enabledForGitHubApps: false category: orgs subcategory: members "/user/memberships/orgs/{org}": get: summary: Get an organization membership for the authenticated user description: '' tags: - orgs operationId: orgs/get-membership-for-authenticated-user externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/orgs#get-an-organization-membership-for-the-authenticated-user parameters: - "$ref": "#/components/parameters/org" responses: '200': description: Response content: application/json: schema: "$ref": "#/components/schemas/org-membership" examples: default: "$ref": "#/components/examples/org-membership" '403': "$ref": "#/components/responses/forbidden" '404': "$ref": "#/components/responses/not_found" x-github: githubCloudOnly: false enabledForGitHubApps: false category: orgs subcategory: members patch: summary: Update an organization membership for the authenticated user description: '' tags: - orgs operationId: orgs/update-membership-for-authenticated-user externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/orgs#update-an-organization-membership-for-the-authenticated-user parameters: - "$ref": "#/components/parameters/org" requestBody: required: true content: application/json: schema: type: object properties: state: type: string description: The state that the membership should be in. Only `"active"` will be accepted. enum: - active required: - state example: state: active responses: '200': description: Response content: application/json: schema: "$ref": "#/components/schemas/org-membership" examples: default: "$ref": "#/components/examples/org-membership-2" '403': "$ref": "#/components/responses/forbidden" '404': "$ref": "#/components/responses/not_found" '422': "$ref": "#/components/responses/validation_failed" x-github: githubCloudOnly: false enabledForGitHubApps: false category: orgs subcategory: members "/user/orgs": get: summary: List organizations for the authenticated user description: |- List organizations for the authenticated user. **OAuth scope requirements** This only lists organizations that your authorization allows you to operate on in some way (e.g., you can list teams with `read:org` scope, you can publicize your organization membership with `user` scope, etc.). Therefore, this API requires at least `user` or `read:org` scope. OAuth requests with insufficient scope receive a `403 Forbidden` response. tags: - orgs operationId: orgs/list-for-authenticated-user externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/orgs#list-organizations-for-the-authenticated-user parameters: - "$ref": "#/components/parameters/per-page" - "$ref": "#/components/parameters/page" responses: '200': description: Response content: application/json: schema: type: array items: "$ref": "#/components/schemas/organization-simple" examples: default: "$ref": "#/components/examples/organization-simple-items" headers: Link: "$ref": "#/components/headers/link" '304': "$ref": "#/components/responses/not_modified" '403': "$ref": "#/components/responses/forbidden" '401': "$ref": "#/components/responses/requires_authentication" x-github: githubCloudOnly: false enabledForGitHubApps: false category: orgs subcategory: "/user/projects": post: summary: Create a user project description: '' tags: - projects operationId: projects/create-for-authenticated-user externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/projects#create-a-user-project parameters: [] requestBody: required: true content: application/json: schema: properties: name: description: Name of the project type: string examples: - Week One Sprint body: description: Body of the project type: - string - 'null' examples: - This project represents the sprint of the first week in January required: - name type: object responses: '201': description: Response content: application/json: schema: "$ref": "#/components/schemas/project" examples: default: "$ref": "#/components/examples/project" '304': "$ref": "#/components/responses/not_modified" '403': "$ref": "#/components/responses/forbidden" '401': "$ref": "#/components/responses/requires_authentication" '415': "$ref": "#/components/responses/preview_header_missing" '422': "$ref": "#/components/responses/validation_failed_simple" x-github: githubCloudOnly: false enabledForGitHubApps: true category: projects previews: - required: true name: inertia note: |- The Projects API is currently available for developers to preview. During the preview period, the API may change without advance notice. Please see the [blog post](https://developer.github.com/changes/2016-10-27-changes-to-projects-api) for full details. To access the API during the preview period, you must provide a custom [media type](https://docs.github.com/enterprise-server@3.0/rest/overview/media-types) in the `Accept` header: ```shell application/vnd.github.inertia-preview+json ``` "/user/public_emails": get: summary: List public email addresses for the authenticated user description: Lists your publicly visible email address, which you can set with the [Set primary email visibility for the authenticated user](https://docs.github.com/enterprise-server@3.0/rest/reference/users#set-primary-email-visibility-for-the-authenticated-user) endpoint. This endpoint is accessible with the `user:email` scope. tags: - users operationId: users/list-public-emails-for-authenticated-user externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/users#list-public-email-addresses-for-the-authenticated-user parameters: - "$ref": "#/components/parameters/per-page" - "$ref": "#/components/parameters/page" responses: '200': description: Response content: application/json: schema: type: array items: "$ref": "#/components/schemas/email" examples: default: "$ref": "#/components/examples/email-items-2" headers: Link: "$ref": "#/components/headers/link" '304': "$ref": "#/components/responses/not_modified" '404': "$ref": "#/components/responses/not_found" '403': "$ref": "#/components/responses/forbidden" '401': "$ref": "#/components/responses/requires_authentication" x-github: githubCloudOnly: false enabledForGitHubApps: false category: users subcategory: emails "/user/repos": get: summary: List repositories for the authenticated user description: |- Lists repositories that the authenticated user has explicit permission (`:read`, `:write`, or `:admin`) to access. The authenticated user has explicit permission to access repositories they own, repositories where they are a collaborator, and repositories that they can access through an organization membership. tags: - repos operationId: repos/list-for-authenticated-user externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/repos#list-repositories-for-the-authenticated-user parameters: - name: visibility description: 'Can be one of `all`, `public`, or `private`. Note: For GitHub AE, can be one of `all`, `internal`, or `private`.' in: query required: false schema: type: string enum: - all - public - private default: all - name: affiliation description: "Comma-separated list of values. Can include: \n\\* `owner`: Repositories that are owned by the authenticated user. \n\\* `collaborator`: Repositories that the user has been added to as a collaborator. \n\\* `organization_member`: Repositories that the user has access to through being a member of an organization. This includes every repository on every team that the user is on." in: query required: false schema: type: string default: owner,collaborator,organization_member - name: type description: "Can be one of `all`, `owner`, `public`, `private`, `member`. Note: For GitHub AE, can be one of `all`, `owner`, `internal`, `private`, `member`. Default: `all` \n \nWill cause a `422` error if used in the same request as **visibility** or **affiliation**. Will cause a `422` error if used in the same request as **visibility** or **affiliation**." in: query required: false schema: type: string enum: - all - owner - public - private - member default: all - name: sort description: Can be one of `created`, `updated`, `pushed`, `full_name`. in: query required: false schema: type: string enum: - created - updated - pushed - full_name default: full_name - name: direction description: 'Can be one of `asc` or `desc`. Default: `asc` when using `full_name`, otherwise `desc`' in: query required: false schema: type: string enum: - asc - desc - "$ref": "#/components/parameters/per-page" - "$ref": "#/components/parameters/page" - "$ref": "#/components/parameters/since" - "$ref": "#/components/parameters/before" responses: '200': description: Response content: application/json: schema: type: array items: "$ref": "#/components/schemas/repository" examples: default: "$ref": "#/components/examples/repository-items-default-response" '422': "$ref": "#/components/responses/validation_failed" '304': "$ref": "#/components/responses/not_modified" '403': "$ref": "#/components/responses/forbidden" '401': "$ref": "#/components/responses/requires_authentication" x-github: githubCloudOnly: false enabledForGitHubApps: false category: repos subcategory: post: summary: Create a repository for the authenticated user description: |- Creates a new repository for the authenticated user. **OAuth scope requirements** When using [OAuth](https://docs.github.com/enterprise-server@3.0/apps/building-oauth-apps/understanding-scopes-for-oauth-apps/), authorizations must include: * `public_repo` scope or `repo` scope to create a public repository. Note: For GitHub AE, use `repo` scope to create an internal repository. * `repo` scope to create a private repository. tags: - repos operationId: repos/create-for-authenticated-user externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/repos#create-a-repository-for-the-authenticated-user parameters: [] requestBody: required: true content: application/json: schema: properties: name: description: The name of the repository. type: string examples: - Team Environment description: description: A short description of the repository. type: string homepage: description: A URL with more information about the repository. type: string private: description: Whether the repository is private. default: false type: boolean has_issues: description: Whether issues are enabled. default: true type: boolean examples: - true has_projects: description: Whether projects are enabled. default: true type: boolean examples: - true has_wiki: description: Whether the wiki is enabled. default: true type: boolean examples: - true team_id: description: The id of the team that will be granted access to this repository. This is only valid when creating a repository in an organization. type: integer auto_init: description: Whether the repository is initialized with a minimal README. default: false type: boolean gitignore_template: description: The desired language or platform to apply to the .gitignore. type: string examples: - Haskell license_template: description: The license keyword of the open source license for this repository. type: string examples: - mit allow_squash_merge: description: Whether to allow squash merges for pull requests. default: true type: boolean examples: - true allow_merge_commit: description: Whether to allow merge commits for pull requests. default: true type: boolean examples: - true allow_rebase_merge: description: Whether to allow rebase merges for pull requests. default: true type: boolean examples: - true delete_branch_on_merge: description: Whether to delete head branches when pull requests are merged default: false type: boolean examples: - false has_downloads: description: Whether downloads are enabled. default: true type: boolean examples: - true is_template: description: Whether this repository acts as a template that can be used to generate new repositories. default: false type: boolean examples: - true required: - name type: object responses: '201': description: Response content: application/json: schema: "$ref": "#/components/schemas/repository" examples: default: "$ref": "#/components/examples/repository" headers: Location: example: https://api.github.com/repos/octocat/Hello-World schema: type: string '401': "$ref": "#/components/responses/requires_authentication" '304': "$ref": "#/components/responses/not_modified" '404': "$ref": "#/components/responses/not_found" '403': "$ref": "#/components/responses/forbidden" '422': "$ref": "#/components/responses/validation_failed" '400': "$ref": "#/components/responses/bad_request" x-github: githubCloudOnly: false enabledForGitHubApps: false category: repos previews: - required: false name: nebula note: |- You can set the visibility of a repository using the new `visibility` parameter in the [Repositories API](https://docs.github.com/enterprise-server@3.0/rest/reference/repos/), and get a repository's visibility with a new response key. For more information, see the [blog post](https://developer.github.com/changes/2019-12-03-internal-visibility-changes/). To access repository visibility during the preview period, you must provide a custom [media type](https://docs.github.com/enterprise-server@3.0/rest/overview/media-types) in the `Accept` header: ```shell application/vnd.github.nebula-preview+json ``` - required: false name: baptiste note: |- The `is_template` and `template_repository` keys are currently available for developer to preview. See [Create a repository using a template](https://docs.github.com/enterprise-server@3.0/rest/reference/repos#create-a-repository-using-a-template) to learn how to create template repositories. To access these new response keys during the preview period, you must provide a custom [media type](https://docs.github.com/enterprise-server@3.0/rest/overview/media-types) in the `Accept` header: ```shell application/vnd.github.baptiste-preview+json ``` "/user/repository_invitations": get: summary: List repository invitations for the authenticated user description: When authenticating as a user, this endpoint will list all currently open repository invitations for that user. tags: - repos operationId: repos/list-invitations-for-authenticated-user externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/repos#list-repository-invitations-for-the-authenticated-user parameters: - "$ref": "#/components/parameters/per-page" - "$ref": "#/components/parameters/page" responses: '200': description: Response content: application/json: schema: type: array items: "$ref": "#/components/schemas/repository-invitation" examples: default: "$ref": "#/components/examples/repository-invitation-items" headers: Link: "$ref": "#/components/headers/link" '304': "$ref": "#/components/responses/not_modified" '404': "$ref": "#/components/responses/not_found" '403': "$ref": "#/components/responses/forbidden" '401': "$ref": "#/components/responses/requires_authentication" x-github: githubCloudOnly: false enabledForGitHubApps: false category: repos subcategory: invitations "/user/repository_invitations/{invitation_id}": patch: summary: Accept a repository invitation description: '' tags: - repos operationId: repos/accept-invitation-for-authenticated-user externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/repos#accept-a-repository-invitation parameters: - "$ref": "#/components/parameters/invitation-id" responses: '204': description: Response '403': "$ref": "#/components/responses/forbidden" '409': "$ref": "#/components/responses/conflict" '404': "$ref": "#/components/responses/not_found" '304': "$ref": "#/components/responses/not_modified" x-github: githubCloudOnly: false enabledForGitHubApps: false category: repos subcategory: invitations delete: summary: Decline a repository invitation description: '' tags: - repos operationId: repos/decline-invitation-for-authenticated-user externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/repos#decline-a-repository-invitation parameters: - "$ref": "#/components/parameters/invitation-id" responses: '204': description: Response '409': "$ref": "#/components/responses/conflict" '304': "$ref": "#/components/responses/not_modified" '404': "$ref": "#/components/responses/not_found" '403': "$ref": "#/components/responses/forbidden" x-github: githubCloudOnly: false enabledForGitHubApps: false category: repos subcategory: invitations "/user/starred": get: summary: List repositories starred by the authenticated user description: |- Lists repositories the authenticated user has starred. You can also find out _when_ stars were created by passing the following custom [media type](https://docs.github.com/enterprise-server@3.0/rest/overview/media-types/) via the `Accept` header: tags: - activity operationId: activity/list-repos-starred-by-authenticated-user externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/activity#list-repositories-starred-by-the-authenticated-user parameters: - "$ref": "#/components/parameters/sort" - "$ref": "#/components/parameters/direction" - "$ref": "#/components/parameters/per-page" - "$ref": "#/components/parameters/page" responses: '200': description: Response content: application/json: schema: type: array items: "$ref": "#/components/schemas/repository" examples: default-response: "$ref": "#/components/examples/repository-items-default-response" application/vnd.github.v3.star+json: schema: type: array items: "$ref": "#/components/schemas/starred-repository" examples: alternative-response-with-star-creation-timestamps: "$ref": "#/components/examples/starred-repository-items-alternative-response-with-star-creation-timestamps" headers: Link: "$ref": "#/components/headers/link" '304': "$ref": "#/components/responses/not_modified" '403': "$ref": "#/components/responses/forbidden" '401': "$ref": "#/components/responses/requires_authentication" x-github: githubCloudOnly: false enabledForGitHubApps: false category: activity subcategory: starring "/user/starred/{owner}/{repo}": get: summary: Check if a repository is starred by the authenticated user description: '' tags: - activity operationId: activity/check-repo-is-starred-by-authenticated-user externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/activity#check-if-a-repository-is-starred-by-the-authenticated-user parameters: - "$ref": "#/components/parameters/owner" - "$ref": "#/components/parameters/repo" responses: '204': description: Response if this repository is starred by you '404': description: Not Found if this repository is not starred by you content: application/json: schema: "$ref": "#/components/schemas/basic-error" '401': "$ref": "#/components/responses/requires_authentication" '304': "$ref": "#/components/responses/not_modified" '403': "$ref": "#/components/responses/forbidden" x-github: githubCloudOnly: false enabledForGitHubApps: false category: activity subcategory: starring put: summary: Star a repository for the authenticated user description: Note that you'll need to set `Content-Length` to zero when calling out to this endpoint. For more information, see "[HTTP verbs](https://docs.github.com/enterprise-server@3.0/rest/overview/resources-in-the-rest-api#http-verbs)." tags: - activity operationId: activity/star-repo-for-authenticated-user externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/activity#star-a-repository-for-the-authenticated-user parameters: - "$ref": "#/components/parameters/owner" - "$ref": "#/components/parameters/repo" responses: '204': description: Response '403': "$ref": "#/components/responses/forbidden" '404': "$ref": "#/components/responses/not_found" '401': "$ref": "#/components/responses/requires_authentication" '304': "$ref": "#/components/responses/not_modified" x-github: githubCloudOnly: false enabledForGitHubApps: false category: activity subcategory: starring delete: summary: Unstar a repository for the authenticated user description: '' tags: - activity operationId: activity/unstar-repo-for-authenticated-user externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/activity#unstar-a-repository-for-the-authenticated-user parameters: - "$ref": "#/components/parameters/owner" - "$ref": "#/components/parameters/repo" responses: '204': description: Response '404': "$ref": "#/components/responses/not_found" '401': "$ref": "#/components/responses/requires_authentication" '304': "$ref": "#/components/responses/not_modified" '403': "$ref": "#/components/responses/forbidden" x-github: githubCloudOnly: false enabledForGitHubApps: false category: activity subcategory: starring "/user/subscriptions": get: summary: List repositories watched by the authenticated user description: Lists repositories the authenticated user is watching. tags: - activity operationId: activity/list-watched-repos-for-authenticated-user externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/activity#list-repositories-watched-by-the-authenticated-user parameters: - "$ref": "#/components/parameters/per-page" - "$ref": "#/components/parameters/page" responses: '200': description: Response content: application/json: schema: type: array items: "$ref": "#/components/schemas/minimal-repository" examples: default: "$ref": "#/components/examples/minimal-repository-items" headers: Link: "$ref": "#/components/headers/link" '304': "$ref": "#/components/responses/not_modified" '403': "$ref": "#/components/responses/forbidden" '401': "$ref": "#/components/responses/requires_authentication" x-github: githubCloudOnly: false enabledForGitHubApps: false category: activity subcategory: watching "/user/teams": get: summary: List teams for the authenticated user description: List all of the teams across all of the organizations to which the authenticated user belongs. This method requires `user`, `repo`, or `read:org` [scope](https://docs.github.com/enterprise-server@3.0/apps/building-oauth-apps/understanding-scopes-for-oauth-apps/) when authenticating via [OAuth](https://docs.github.com/enterprise-server@3.0/apps/building-oauth-apps/). tags: - teams operationId: teams/list-for-authenticated-user externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/teams#list-teams-for-the-authenticated-user parameters: - "$ref": "#/components/parameters/per-page" - "$ref": "#/components/parameters/page" responses: '200': description: Response content: application/json: schema: type: array items: "$ref": "#/components/schemas/team-full" examples: default: "$ref": "#/components/examples/team-full-items" headers: Link: "$ref": "#/components/headers/link" '304': "$ref": "#/components/responses/not_modified" '404': "$ref": "#/components/responses/not_found" '403': "$ref": "#/components/responses/forbidden" x-github: githubCloudOnly: false enabledForGitHubApps: false category: teams subcategory: "/users": get: summary: List users description: |- Lists all users, in the order that they signed up on GitHub Enterprise Server. This list includes personal user accounts and organization accounts. Note: Pagination is powered exclusively by the `since` parameter. Use the [Link header](https://docs.github.com/enterprise-server@3.0/rest/overview/resources-in-the-rest-api#link-header) to get the URL for the next page of users. tags: - users operationId: users/list externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/users#list-users parameters: - "$ref": "#/components/parameters/since-user" - "$ref": "#/components/parameters/per-page" responses: '200': description: Response content: application/json: schema: type: array items: "$ref": "#/components/schemas/simple-user" examples: default: "$ref": "#/components/examples/simple-user-items" headers: Link: example: ; rel="next" schema: type: string '304': "$ref": "#/components/responses/not_modified" x-github: githubCloudOnly: false enabledForGitHubApps: true category: users subcategory: "/users/{username}": get: summary: Get a user description: |- Provides publicly available information about someone with a GitHub account. GitHub Apps with the `Plan` user permission can use this endpoint to retrieve information about a user's GitHub Enterprise Server plan. The GitHub App must be authenticated as a user. See "[Identifying and authorizing users for GitHub Apps](https://docs.github.com/enterprise-server@3.0/apps/building-github-apps/identifying-and-authorizing-users-for-github-apps/)" for details about authentication. For an example response, see 'Response with GitHub Enterprise Server plan information' below" The `email` key in the following response is the publicly visible email address from your GitHub Enterprise Server [profile page](https://github.com/settings/profile). When setting up your profile, you can select a primary email address to be “public” which provides an email entry for this endpoint. If you do not set a public email address for `email`, then it will have a value of `null`. You only see publicly visible email addresses when authenticated with GitHub Enterprise Server. For more information, see [Authentication](https://docs.github.com/enterprise-server@3.0/rest/overview/resources-in-the-rest-api#authentication). The Emails API enables you to list all of your email addresses, and toggle a primary email to be visible publicly. For more information, see "[Emails API](https://docs.github.com/enterprise-server@3.0/rest/reference/users#emails)". tags: - users operationId: users/get-by-username externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/users#get-a-user parameters: - "$ref": "#/components/parameters/username" responses: '200': description: Response content: application/json: schema: oneOf: - "$ref": "#/components/schemas/private-user" - "$ref": "#/components/schemas/public-user" examples: default-response: "$ref": "#/components/examples/public-user-default-response" response-with-git-hub-plan-information: "$ref": "#/components/examples/public-user-response-with-git-hub-plan-information" '404': "$ref": "#/components/responses/not_found" x-github: githubCloudOnly: false enabledForGitHubApps: true category: users subcategory: "/users/{username}/events": get: summary: List events for the authenticated user description: If you are authenticated as the given user, you will see your private events. Otherwise, you'll only see public events. tags: - activity operationId: activity/list-events-for-authenticated-user externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/activity#list-events-for-the-authenticated-user parameters: - "$ref": "#/components/parameters/username" - "$ref": "#/components/parameters/per-page" - "$ref": "#/components/parameters/page" responses: '200': description: Response content: application/json: schema: type: array items: "$ref": "#/components/schemas/event" x-github: githubCloudOnly: false enabledForGitHubApps: true category: activity subcategory: events "/users/{username}/events/orgs/{org}": get: summary: List organization events for the authenticated user description: This is the user's organization dashboard. You must be authenticated as the user to view this. tags: - activity operationId: activity/list-org-events-for-authenticated-user externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/activity#list-organization-events-for-the-authenticated-user parameters: - "$ref": "#/components/parameters/username" - "$ref": "#/components/parameters/org" - "$ref": "#/components/parameters/per-page" - "$ref": "#/components/parameters/page" responses: '200': description: Response content: application/json: schema: type: array items: "$ref": "#/components/schemas/event" x-github: githubCloudOnly: false enabledForGitHubApps: false category: activity subcategory: events "/users/{username}/events/public": get: summary: List public events for a user description: '' tags: - activity operationId: activity/list-public-events-for-user externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/activity#list-public-events-for-a-user parameters: - "$ref": "#/components/parameters/username" - "$ref": "#/components/parameters/per-page" - "$ref": "#/components/parameters/page" responses: '200': description: Response content: application/json: schema: type: array items: "$ref": "#/components/schemas/event" x-github: githubCloudOnly: false enabledForGitHubApps: true category: activity subcategory: events "/users/{username}/followers": get: summary: List followers of a user description: Lists the people following the specified user. tags: - users operationId: users/list-followers-for-user externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/users#list-followers-of-a-user parameters: - "$ref": "#/components/parameters/username" - "$ref": "#/components/parameters/per-page" - "$ref": "#/components/parameters/page" responses: '200': description: Response content: application/json: schema: type: array items: "$ref": "#/components/schemas/simple-user" examples: default: "$ref": "#/components/examples/simple-user-items" headers: Link: "$ref": "#/components/headers/link" x-github: githubCloudOnly: false enabledForGitHubApps: true category: users subcategory: followers "/users/{username}/following": get: summary: List the people a user follows description: Lists the people who the specified user follows. tags: - users operationId: users/list-following-for-user externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/users#list-the-people-a-user-follows parameters: - "$ref": "#/components/parameters/username" - "$ref": "#/components/parameters/per-page" - "$ref": "#/components/parameters/page" responses: '200': description: Response content: application/json: schema: type: array items: "$ref": "#/components/schemas/simple-user" examples: default: "$ref": "#/components/examples/simple-user-items" headers: Link: "$ref": "#/components/headers/link" x-github: githubCloudOnly: false enabledForGitHubApps: true category: users subcategory: followers "/users/{username}/following/{target_user}": get: summary: Check if a user follows another user description: '' tags: - users operationId: users/check-following-for-user externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/users#check-if-a-user-follows-another-user parameters: - "$ref": "#/components/parameters/username" - name: target_user in: path required: true schema: type: string responses: '204': description: if the user follows the target user '404': description: if the user does not follow the target user x-github: githubCloudOnly: false enabledForGitHubApps: true category: users subcategory: followers "/users/{username}/gists": get: summary: List gists for a user description: 'Lists public gists for the specified user:' tags: - gists operationId: gists/list-for-user externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/gists#list-gists-for-a-user parameters: - "$ref": "#/components/parameters/username" - "$ref": "#/components/parameters/since" - "$ref": "#/components/parameters/per-page" - "$ref": "#/components/parameters/page" responses: '200': description: Response content: application/json: schema: type: array items: "$ref": "#/components/schemas/base-gist" examples: default: "$ref": "#/components/examples/base-gist-items" headers: Link: "$ref": "#/components/headers/link" '422': "$ref": "#/components/responses/validation_failed" x-github: githubCloudOnly: false enabledForGitHubApps: false category: gists subcategory: "/users/{username}/gpg_keys": get: summary: List GPG keys for a user description: Lists the GPG keys for a user. This information is accessible by anyone. tags: - users operationId: users/list-gpg-keys-for-user externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/users#list-gpg-keys-for-a-user parameters: - "$ref": "#/components/parameters/username" - "$ref": "#/components/parameters/per-page" - "$ref": "#/components/parameters/page" responses: '200': description: Response content: application/json: schema: type: array items: "$ref": "#/components/schemas/gpg-key" examples: default: "$ref": "#/components/examples/gpg-key-items" headers: Link: "$ref": "#/components/headers/link" x-github: githubCloudOnly: false enabledForGitHubApps: true category: users subcategory: gpg-keys "/users/{username}/hovercard": get: summary: Get contextual information for a user description: |- Provides hovercard information when authenticated through basic auth or OAuth with the `repo` scope. You can find out more about someone in relation to their pull requests, issues, repositories, and organizations. The `subject_type` and `subject_id` parameters provide context for the person's hovercard, which returns more information than without the parameters. For example, if you wanted to find out more about `octocat` who owns the `Spoon-Knife` repository via cURL, it would look like this: ```shell curl -u username:token https://api.github.com/users/octocat/hovercard?subject_type=repository&subject_id=1300192 ``` tags: - users operationId: users/get-context-for-user externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/users#get-contextual-information-for-a-user parameters: - "$ref": "#/components/parameters/username" - name: subject_type description: Identifies which additional information you'd like to receive about the person's hovercard. Can be `organization`, `repository`, `issue`, `pull_request`. **Required** when using `subject_id`. in: query required: false schema: type: string enum: - organization - repository - issue - pull_request - name: subject_id description: Uses the ID for the `subject_type` you specified. **Required** when using `subject_type`. in: query required: false schema: type: string responses: '200': description: Response content: application/json: schema: "$ref": "#/components/schemas/hovercard" examples: default: "$ref": "#/components/examples/hovercard" '404': "$ref": "#/components/responses/not_found" '422': "$ref": "#/components/responses/validation_failed" x-github: githubCloudOnly: false enabledForGitHubApps: false category: users subcategory: "/users/{username}/installation": get: summary: Get a user installation for the authenticated app description: |- Enables an authenticated GitHub App to find the user’s installation information. You must use a [JWT](https://docs.github.com/enterprise-server@3.0/apps/building-github-apps/authenticating-with-github-apps/#authenticating-as-a-github-app) to access this endpoint. tags: - apps operationId: apps/get-user-installation externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/apps#get-a-user-installation-for-the-authenticated-app parameters: - "$ref": "#/components/parameters/username" responses: '200': description: Response content: application/json: schema: "$ref": "#/components/schemas/installation" examples: default: "$ref": "#/components/examples/installation" x-github: githubCloudOnly: false enabledForGitHubApps: false category: apps subcategory: "/users/{username}/keys": get: summary: List public keys for a user description: Lists the _verified_ public SSH keys for a user. This is accessible by anyone. tags: - users operationId: users/list-public-keys-for-user externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/users#list-public-keys-for-a-user parameters: - "$ref": "#/components/parameters/username" - "$ref": "#/components/parameters/per-page" - "$ref": "#/components/parameters/page" responses: '200': description: Response content: application/json: schema: type: array items: "$ref": "#/components/schemas/key-simple" examples: default: "$ref": "#/components/examples/key-simple-items" headers: Link: "$ref": "#/components/headers/link" x-github: githubCloudOnly: false enabledForGitHubApps: true category: users subcategory: keys "/users/{username}/orgs": get: summary: List organizations for a user description: |- List [public organization memberships](https://docs.github.com/articles/publicizing-or-concealing-organization-membership) for the specified user. This method only lists _public_ memberships, regardless of authentication. If you need to fetch all of the organization memberships (public and private) for the authenticated user, use the [List organizations for the authenticated user](https://docs.github.com/enterprise-server@3.0/rest/reference/orgs#list-organizations-for-the-authenticated-user) API instead. tags: - orgs operationId: orgs/list-for-user externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/orgs#list-organizations-for-a-user parameters: - "$ref": "#/components/parameters/username" - "$ref": "#/components/parameters/per-page" - "$ref": "#/components/parameters/page" responses: '200': description: Response content: application/json: schema: type: array items: "$ref": "#/components/schemas/organization-simple" examples: default: "$ref": "#/components/examples/organization-simple-items" headers: Link: "$ref": "#/components/headers/link" x-github: githubCloudOnly: false enabledForGitHubApps: true category: orgs subcategory: "/users/{username}/projects": get: summary: List user projects description: '' tags: - projects operationId: projects/list-for-user externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/projects#list-user-projects parameters: - "$ref": "#/components/parameters/username" - name: state description: Indicates the state of the projects to return. Can be either `open`, `closed`, or `all`. in: query required: false schema: type: string enum: - open - closed - all default: open - "$ref": "#/components/parameters/per-page" - "$ref": "#/components/parameters/page" responses: '200': description: Response content: application/json: schema: type: array items: "$ref": "#/components/schemas/project" examples: default: "$ref": "#/components/examples/project-items-3" headers: Link: "$ref": "#/components/headers/link" '422': "$ref": "#/components/responses/validation_failed" x-github: githubCloudOnly: false enabledForGitHubApps: false category: projects previews: - required: true name: inertia note: |- The Projects API is currently available for developers to preview. During the preview period, the API may change without advance notice. Please see the [blog post](https://developer.github.com/changes/2016-10-27-changes-to-projects-api) for full details. To access the API during the preview period, you must provide a custom [media type](https://docs.github.com/enterprise-server@3.0/rest/overview/media-types) in the `Accept` header: ```shell application/vnd.github.inertia-preview+json ``` "/users/{username}/received_events": get: summary: List events received by the authenticated user description: These are events that you've received by watching repos and following users. If you are authenticated as the given user, you will see private events. Otherwise, you'll only see public events. tags: - activity operationId: activity/list-received-events-for-user externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/activity#list-events-received-by-the-authenticated-user parameters: - "$ref": "#/components/parameters/username" - "$ref": "#/components/parameters/per-page" - "$ref": "#/components/parameters/page" responses: '200': description: Response content: application/json: schema: type: array items: "$ref": "#/components/schemas/event" x-github: githubCloudOnly: false enabledForGitHubApps: true category: activity subcategory: events "/users/{username}/received_events/public": get: summary: List public events received by a user description: '' tags: - activity operationId: activity/list-received-public-events-for-user externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/activity#list-public-events-received-by-a-user parameters: - "$ref": "#/components/parameters/username" - "$ref": "#/components/parameters/per-page" - "$ref": "#/components/parameters/page" responses: '200': description: Response content: application/json: schema: type: array items: "$ref": "#/components/schemas/event" x-github: githubCloudOnly: false enabledForGitHubApps: true category: activity subcategory: events "/users/{username}/repos": get: summary: List repositories for a user description: 'Lists public repositories for the specified user. Note: For GitHub AE, this endpoint will list internal repositories for the specified user.' tags: - repos operationId: repos/list-for-user externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/repos#list-repositories-for-a-user parameters: - "$ref": "#/components/parameters/username" - name: type description: Can be one of `all`, `owner`, `member`. in: query required: false schema: type: string enum: - all - owner - member default: owner - name: sort description: Can be one of `created`, `updated`, `pushed`, `full_name`. in: query required: false schema: type: string enum: - created - updated - pushed - full_name default: full_name - name: direction description: 'Can be one of `asc` or `desc`. Default: `asc` when using `full_name`, otherwise `desc`' in: query required: false schema: type: string enum: - asc - desc - "$ref": "#/components/parameters/per-page" - "$ref": "#/components/parameters/page" responses: '200': description: Response content: application/json: schema: type: array items: "$ref": "#/components/schemas/minimal-repository" examples: default: "$ref": "#/components/examples/minimal-repository-items" headers: Link: "$ref": "#/components/headers/link" x-github: githubCloudOnly: false enabledForGitHubApps: true category: repos previews: - required: false name: nebula note: |- You can set the visibility of a repository using the new `visibility` parameter in the [Repositories API](https://docs.github.com/enterprise-server@3.0/rest/reference/repos/), and get a repository's visibility with a new response key. For more information, see the [blog post](https://developer.github.com/changes/2019-12-03-internal-visibility-changes/). To access repository visibility during the preview period, you must provide a custom [media type](https://docs.github.com/enterprise-server@3.0/rest/overview/media-types) in the `Accept` header: ```shell application/vnd.github.nebula-preview+json ``` "/users/{username}/site_admin": put: summary: Promote a user to be a site administrator description: Note that you'll need to set `Content-Length` to zero when calling out to this endpoint. For more information, see "[HTTP verbs](https://docs.github.com/enterprise-server@3.0/rest/overview/resources-in-the-rest-api#http-verbs)." operationId: enterprise-admin/promote-user-to-be-site-administrator tags: - enterprise-admin externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/enterprise-admin#promote-a-user-to-be-a-site-administrator parameters: - "$ref": "#/components/parameters/username" responses: '204': description: Response x-github: githubCloudOnly: false enabledForGitHubApps: false category: enterprise-admin subcategory: users delete: summary: Demote a site administrator description: You can demote any user account except your own. operationId: enterprise-admin/demote-site-administrator tags: - enterprise-admin externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/enterprise-admin#demote-a-site-administrator parameters: - "$ref": "#/components/parameters/username" responses: '204': description: Response x-github: githubCloudOnly: false enabledForGitHubApps: false category: enterprise-admin subcategory: users "/users/{username}/starred": get: summary: List repositories starred by a user description: |- Lists repositories a user has starred. You can also find out _when_ stars were created by passing the following custom [media type](https://docs.github.com/enterprise-server@3.0/rest/overview/media-types/) via the `Accept` header: tags: - activity operationId: activity/list-repos-starred-by-user externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/activity#list-repositories-starred-by-a-user parameters: - "$ref": "#/components/parameters/username" - "$ref": "#/components/parameters/sort" - "$ref": "#/components/parameters/direction" - "$ref": "#/components/parameters/per-page" - "$ref": "#/components/parameters/page" responses: '200': description: Response content: application/json: schema: anyOf: - type: array items: "$ref": "#/components/schemas/starred-repository" - type: array items: "$ref": "#/components/schemas/repository" examples: default-response: "$ref": "#/components/examples/repository-items-default-response" headers: Link: "$ref": "#/components/headers/link" x-github: githubCloudOnly: false enabledForGitHubApps: true category: activity subcategory: starring "/users/{username}/subscriptions": get: summary: List repositories watched by a user description: Lists repositories a user is watching. tags: - activity operationId: activity/list-repos-watched-by-user externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/activity#list-repositories-watched-by-a-user parameters: - "$ref": "#/components/parameters/username" - "$ref": "#/components/parameters/per-page" - "$ref": "#/components/parameters/page" responses: '200': description: Response content: application/json: schema: type: array items: "$ref": "#/components/schemas/minimal-repository" examples: default: "$ref": "#/components/examples/minimal-repository-items" headers: Link: "$ref": "#/components/headers/link" x-github: githubCloudOnly: false enabledForGitHubApps: true category: activity subcategory: watching "/users/{username}/suspended": put: summary: Suspend a user description: |- If your GitHub instance uses [LDAP Sync with Active Directory LDAP servers](https://docs.github.com/enterprise/admin/guides/user-management/using-ldap), Active Directory LDAP-authenticated users cannot be suspended through this API. If you attempt to suspend an Active Directory LDAP-authenticated user through this API, it will return a `403` response. You can suspend any user account except your own. Note that, if you choose not to pass any parameters, you'll need to set `Content-Length` to zero when calling out to this endpoint. For more information, see "[HTTP verbs](https://docs.github.com/enterprise-server@3.0/rest/overview/resources-in-the-rest-api#http-verbs)." operationId: enterprise-admin/suspend-user tags: - enterprise-admin externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/enterprise-admin#suspend-a-user parameters: - "$ref": "#/components/parameters/username" responses: '204': description: Response requestBody: content: application/json: schema: type: - object - 'null' properties: reason: type: string description: The reason the user is being suspended. This message will be logged in the [audit log](https://docs.github.com/enterprise/admin/articles/audit-logging/). If you don't provide a `reason`, it will default to "Suspended via API by _SITE\_ADMINISTRATOR_", where _SITE\_ADMINISTRATOR_ is the person who performed the action. x-github: githubCloudOnly: false enabledForGitHubApps: false category: enterprise-admin subcategory: users delete: summary: Unsuspend a user description: If your GitHub instance uses [LDAP Sync with Active Directory LDAP servers](https://docs.github.com/enterprise/admin/guides/user-management/using-ldap), this API is disabled and will return a `403` response. Active Directory LDAP-authenticated users cannot be unsuspended using the API. operationId: enterprise-admin/unsuspend-user tags: - enterprise-admin externalDocs: description: API method documentation url: https://docs.github.com/enterprise-server@3.0/rest/reference/enterprise-admin#unsuspend-a-user parameters: - "$ref": "#/components/parameters/username" responses: '204': description: Response requestBody: content: application/json: schema: type: - object - 'null' properties: reason: type: string description: The reason the user is being unsuspended. This message will be logged in the [audit log](https://docs.github.com/enterprise/admin/articles/audit-logging/). If you don't provide a `reason`, it will default to "Unsuspended via API by _SITE\_ADMINISTRATOR_", where _SITE\_ADMINISTRATOR_ is the person who performed the action. x-github: githubCloudOnly: false enabledForGitHubApps: false category: enterprise-admin subcategory: users "/zen": get: summary: Get the Zen of GitHub description: Get a random sentence from the Zen of GitHub tags: - meta operationId: meta/get-zen responses: '200': description: Response content: text/plain: schema: type: string x-github: githubCloudOnly: false enabledForGitHubApps: true category: meta components: parameters: per-page: name: per_page description: Results per page (max 100) in: query schema: type: integer default: 30 page: name: page description: Page number of the results to fetch. in: query schema: type: integer default: 1 hook-id: name: hook_id in: path required: true schema: type: integer direction: name: direction description: One of `asc` (ascending) or `desc` (descending). in: query required: false schema: type: string enum: - asc - desc default: desc key-ids: name: key_ids in: path required: true schema: type: string team-id: name: team_id in: path required: true schema: type: integer username: name: username in: path required: true schema: type: string org: name: org in: path required: true schema: type: string pre-receive-environment-id: name: pre_receive_environment_id in: path required: true schema: type: integer pre-receive-hook-id: name: pre_receive_hook_id description: pre_receive_hook_id parameter in: path required: true schema: type: integer token-id: name: token_id in: path required: true schema: type: integer since: name: since description: 'Only show notifications updated after the given time. This is a timestamp in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format: `YYYY-MM-DDTHH:MM:SSZ`.' in: query required: false schema: type: string format: date-time installation-id: name: installation_id description: installation_id parameter in: path required: true schema: type: integer grant-id: name: grant_id description: grant_id parameter in: path required: true schema: type: integer client-id: name: client_id in: path required: true description: The client ID of your GitHub app. schema: type: string access-token: name: access_token in: path required: true schema: type: string app-slug: name: app_slug in: path required: true schema: type: string authorization-id: name: authorization_id description: authorization_id parameter in: path required: true schema: type: integer enterprise: name: enterprise description: The slug version of the enterprise name. You can also substitute this value with the enterprise id. in: path required: true schema: type: string org-id: name: org_id description: Unique identifier of an organization. in: path required: true schema: type: integer runner-group-id: name: runner_group_id description: Unique identifier of the self-hosted runner group. in: path required: true schema: type: integer runner-id: name: runner_id description: Unique identifier of the self-hosted runner. in: path required: true schema: type: integer gist-id: name: gist_id description: gist_id parameter in: path required: true schema: type: string comment-id: name: comment_id description: comment_id parameter in: path required: true schema: type: integer labels: name: labels description: 'A list of comma separated label names. Example: `bug,ui,@high`' in: query required: false schema: type: string owner: name: owner in: path required: true schema: type: string repo: name: repo in: path required: true schema: type: string all: name: all description: If `true`, show notifications marked as read. in: query required: false schema: type: boolean default: false participating: name: participating description: If `true`, only shows notifications in which the user is directly participating or mentioned. in: query required: false schema: type: boolean default: false before: name: before description: 'Only show notifications updated before the given time. This is a timestamp in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format: `YYYY-MM-DDTHH:MM:SSZ`.' in: query required: false schema: type: string format: date-time thread-id: name: thread_id description: thread_id parameter in: path required: true schema: type: integer since-org: name: since description: An organization ID. Only return organizations with an ID greater than this ID. in: query required: false schema: type: integer repository-id: name: repository_id in: path required: true schema: type: integer secret-name: name: secret_name description: secret_name parameter in: path required: true schema: type: string team-slug: name: team_slug description: team_slug parameter in: path required: true schema: type: string discussion-number: name: discussion_number in: path required: true schema: type: integer comment-number: name: comment_number in: path required: true schema: type: integer reaction-id: name: reaction_id in: path required: true schema: type: integer project-id: name: project_id in: path required: true schema: type: integer card-id: name: card_id description: card_id parameter in: path required: true schema: type: integer column-id: name: column_id description: column_id parameter in: path required: true schema: type: integer artifact-id: name: artifact_id description: artifact_id parameter in: path required: true schema: type: integer job-id: name: job_id description: job_id parameter in: path required: true schema: type: integer actor: name: actor description: Returns someone's workflow runs. Use the login for the user who created the `push` associated with the check suite or workflow run. in: query required: false schema: type: string workflow-run-branch: name: branch description: Returns workflow runs associated with a branch. Use the name of the branch of the `push`. in: query required: false schema: type: string event: name: event description: Returns workflow run triggered by the event you specify. For example, `push`, `pull_request` or `issue`. For more information, see "[Events that trigger workflows](https://docs.github.com/en/actions/automating-your-workflow-with-github-actions/events-that-trigger-workflows)." in: query required: false schema: type: string workflow-run-status: name: status description: Returns workflow runs with the check run `status` or `conclusion` that you specify. For example, a conclusion can be `success` or a status can be `in_progress`. Only GitHub can set a status of `waiting` or `requested`. For a list of the possible `status` and `conclusion` options, see "[Create a check run](https://docs.github.com/enterprise-server@3.0/rest/reference/checks#create-a-check-run)." in: query required: false schema: type: string enum: - completed - action_required - cancelled - failure - neutral - skipped - stale - success - timed_out - in_progress - queued - requested - waiting created: name: created description: Returns workflow runs created within the given date-time range. For more information on the syntax, see "[Understanding the search syntax](https://docs.github.com/enterprise-server@3.0/search-github/getting-started-with-searching-on-github/understanding-the-search-syntax#query-for-dates)." in: query required: false schema: type: string format: date-time exclude-pull-requests: name: exclude_pull_requests description: If `true` pull requests are omitted from the response (empty array). in: query required: false schema: type: boolean default: false run-id: name: run_id description: The id of the workflow run. in: path required: true schema: type: integer workflow-id: name: workflow_id in: path description: The ID of the workflow. You can also pass the workflow file name as a string. required: true schema: oneOf: - type: integer - type: string branch: name: branch description: The name of the branch. in: path required: true schema: type: string x-multi-segment: true check-run-id: name: check_run_id description: check_run_id parameter in: path required: true schema: type: integer check-suite-id: name: check_suite_id description: check_suite_id parameter in: path required: true schema: type: integer check-name: name: check_name description: Returns check runs with the specified `name`. in: query required: false schema: type: string status: name: status description: Returns check runs with the specified `status`. Can be one of `queued`, `in_progress`, or `completed`. in: query required: false schema: type: string enum: - queued - in_progress - completed tool-name: name: tool_name description: The name of a code scanning tool. Only results by this tool will be listed. You can specify the tool by using either `tool_name` or `tool_guid`, but not both. in: query required: false schema: "$ref": "#/components/schemas/code-scanning-analysis-tool-name" tool-guid: name: tool_guid description: The GUID of a code scanning tool. Only results by this tool will be listed. Note that some code scanning tools may not include a GUID in their analysis data. You can specify the tool by using either `tool_guid` or `tool_name`, but not both. in: query required: false schema: "$ref": "#/components/schemas/code-scanning-analysis-tool-guid" git-ref: name: ref description: The Git reference for the results you want to list. The `ref` for a branch can be formatted either as `refs/heads/` or simply ``. To reference a pull request use `refs/pull//merge`. in: query required: false schema: "$ref": "#/components/schemas/code-scanning-ref" alert-number: name: alert_number in: path description: The number that identifies an alert. You can find this at the end of the URL for a code scanning alert within GitHub, and in the `number` field in the response from the `GET /repos/{owner}/{repo}/code-scanning/alerts` operation. required: true schema: "$ref": "#/components/schemas/alert-number" commit-sha: name: commit_sha description: commit_sha parameter in: path required: true schema: type: string x-multi-segment: true deployment-id: name: deployment_id description: deployment_id parameter in: path required: true schema: type: integer invitation-id: name: invitation_id description: invitation_id parameter in: path required: true schema: type: integer sort: name: sort description: One of `created` (when the repository was starred) or `updated` (when it was last pushed to). in: query required: false schema: type: string enum: - created - updated default: created issue-number: name: issue_number description: issue_number parameter in: path required: true schema: type: integer key-id: name: key_id description: key_id parameter in: path required: true schema: type: integer milestone-number: name: milestone_number description: milestone_number parameter in: path required: true schema: type: integer pull-number: name: pull_number in: path required: true schema: type: integer review-id: name: review_id description: review_id parameter in: path required: true schema: type: integer asset-id: name: asset_id description: asset_id parameter in: path required: true schema: type: integer release-id: name: release_id description: release_id parameter in: path required: true schema: type: integer since-repo: name: since description: A repository ID. Only return repositories with an ID greater than this ID. in: query required: false schema: type: integer order: name: order description: Determines whether the first search result returned is the highest number of matches (`desc`) or lowest number of matches (`asc`). This parameter is ignored unless you provide `sort`. in: query required: false schema: type: string enum: - desc - asc default: desc gpg-key-id: name: gpg_key_id description: gpg_key_id parameter in: path required: true schema: type: integer since-user: name: since description: A user ID. Only return users with an ID greater than this ID. in: query required: false schema: type: integer schemas: global-hook: type: object properties: type: type: string id: type: integer name: type: string active: type: boolean events: type: array items: type: string config: type: object properties: url: type: string content_type: type: string insecure_ssl: type: string secret: type: string updated_at: type: string created_at: type: string url: type: string ping_url: type: string global-hook-2: type: object properties: type: type: string id: type: integer name: type: string active: type: boolean events: type: array items: type: string config: type: object properties: url: type: string content_type: type: string insecure_ssl: type: string updated_at: type: string created_at: type: string url: type: string ping_url: type: string public-key-full: type: object properties: id: type: integer key: type: string user_id: type: - integer - 'null' repository_id: type: - integer - 'null' url: type: string title: type: string read_only: type: boolean verified: type: boolean created_at: type: string format: date-time last_used: type: - string - 'null' format: date-time required: - id - key - url - title - verified - created_at - read_only - last_used - user_id - repository_id ldap-mapping-team: type: object properties: ldap_dn: type: string id: type: integer node_id: type: string url: type: string html_url: type: string name: type: string slug: type: string description: type: - string - 'null' privacy: type: string permission: type: string members_url: type: string repositories_url: type: string parent: type: - 'null' ldap-mapping-user: title: Ldap Private User description: Ldap Private User type: object properties: ldap_dn: type: string login: type: string examples: - octocat id: type: integer examples: - 1 node_id: type: string examples: - MDQ6VXNlcjE= avatar_url: type: string format: uri examples: - https://github.com/images/error/octocat_happy.gif gravatar_id: type: - string - 'null' examples: - 41d064eb2195891e12d0413f63227ea7 url: type: string format: uri examples: - https://api.github.com/users/octocat html_url: type: string format: uri examples: - https://github.com/octocat followers_url: type: string format: uri examples: - https://api.github.com/users/octocat/followers following_url: type: string examples: - https://api.github.com/users/octocat/following{/other_user} gists_url: type: string examples: - https://api.github.com/users/octocat/gists{/gist_id} starred_url: type: string examples: - https://api.github.com/users/octocat/starred{/owner}{/repo} subscriptions_url: type: string format: uri examples: - https://api.github.com/users/octocat/subscriptions organizations_url: type: string format: uri examples: - https://api.github.com/users/octocat/orgs repos_url: type: string format: uri examples: - https://api.github.com/users/octocat/repos events_url: type: string examples: - https://api.github.com/users/octocat/events{/privacy} received_events_url: type: string format: uri examples: - https://api.github.com/users/octocat/received_events type: type: string examples: - User site_admin: type: boolean name: type: - string - 'null' examples: - monalisa octocat company: type: - string - 'null' examples: - GitHub blog: type: - string - 'null' examples: - https://github.com/blog location: type: - string - 'null' examples: - San Francisco email: type: - string - 'null' format: email examples: - octocat@github.com hireable: type: - boolean - 'null' bio: type: - string - 'null' examples: - There once was... twitter_username: type: - string - 'null' examples: - monalisa public_repos: type: integer examples: - 2 public_gists: type: integer examples: - 1 followers: type: integer examples: - 20 following: type: integer examples: - 0 created_at: type: string format: date-time examples: - '2008-01-14T04:33:35Z' updated_at: type: string format: date-time examples: - '2008-01-14T04:33:35Z' private_gists: type: integer examples: - 81 total_private_repos: type: integer examples: - 100 owned_private_repos: type: integer examples: - 100 disk_usage: type: integer examples: - 10000 collaborators: type: integer examples: - 8 two_factor_authentication: type: boolean examples: - true plan: type: object properties: collaborators: type: integer name: type: string space: type: integer private_repos: type: integer required: - collaborators - name - space - private_repos suspended_at: type: string format: date-time business_plus: type: boolean required: - avatar_url - events_url - followers_url - following_url - gists_url - gravatar_id - html_url - id - node_id - login - organizations_url - received_events_url - repos_url - site_admin - starred_url - subscriptions_url - type - url - bio - blog - company - email - followers - following - hireable - location - name - public_gists - public_repos - created_at - updated_at - collaborators - disk_usage - owned_private_repos - private_gists - total_private_repos - two_factor_authentication organization-simple: title: Organization Simple description: Organization Simple type: object properties: login: type: string examples: - github id: type: integer examples: - 1 node_id: type: string examples: - MDEyOk9yZ2FuaXphdGlvbjE= url: type: string format: uri examples: - https://api.github.com/orgs/github repos_url: type: string format: uri examples: - https://api.github.com/orgs/github/repos events_url: type: string format: uri examples: - https://api.github.com/orgs/github/events hooks_url: type: string examples: - https://api.github.com/orgs/github/hooks issues_url: type: string examples: - https://api.github.com/orgs/github/issues members_url: type: string examples: - https://api.github.com/orgs/github/members{/member} public_members_url: type: string examples: - https://api.github.com/orgs/github/public_members{/member} avatar_url: type: string examples: - https://github.com/images/error/octocat_happy.gif description: type: - string - 'null' examples: - A great organization required: - login - url - id - node_id - repos_url - events_url - hooks_url - issues_url - members_url - public_members_url - avatar_url - description pre-receive-environment: type: object properties: id: type: integer name: type: string image_url: type: string url: type: string html_url: type: string default_environment: type: boolean created_at: type: string hooks_count: type: integer download: type: object properties: url: type: string state: type: string downloaded_at: type: - string - 'null' message: type: - string - 'null' pre-receive-environment-download-status: type: object properties: url: type: string state: type: string downloaded_at: type: - string - 'null' message: type: - string - 'null' pre-receive-hook: type: object properties: id: type: integer name: type: string enforcement: type: string script: type: string script_repository: type: object properties: id: type: integer full_name: type: string url: type: string html_url: type: string environment: type: object properties: id: type: integer name: type: string image_url: type: string url: type: string html_url: type: string default_environment: type: boolean created_at: type: string hooks_count: type: integer download: type: object properties: url: type: string state: type: string downloaded_at: type: - string - 'null' message: type: - string - 'null' allow_downstream_configuration: type: boolean simple-user: title: Simple User description: Simple User type: object properties: name: type: - string - 'null' email: type: - string - 'null' login: type: string examples: - octocat id: type: integer examples: - 1 node_id: type: string examples: - MDQ6VXNlcjE= avatar_url: type: string format: uri examples: - https://github.com/images/error/octocat_happy.gif gravatar_id: type: - string - 'null' examples: - 41d064eb2195891e12d0413f63227ea7 url: type: string format: uri examples: - https://api.github.com/users/octocat html_url: type: string format: uri examples: - https://github.com/octocat followers_url: type: string format: uri examples: - https://api.github.com/users/octocat/followers following_url: type: string examples: - https://api.github.com/users/octocat/following{/other_user} gists_url: type: string examples: - https://api.github.com/users/octocat/gists{/gist_id} starred_url: type: string examples: - https://api.github.com/users/octocat/starred{/owner}{/repo} subscriptions_url: type: string format: uri examples: - https://api.github.com/users/octocat/subscriptions organizations_url: type: string format: uri examples: - https://api.github.com/users/octocat/orgs repos_url: type: string format: uri examples: - https://api.github.com/users/octocat/repos events_url: type: string examples: - https://api.github.com/users/octocat/events{/privacy} received_events_url: type: string format: uri examples: - https://api.github.com/users/octocat/received_events type: type: string examples: - User site_admin: type: boolean starred_at: type: string examples: - '"2020-07-09T00:17:55Z"' required: - avatar_url - events_url - followers_url - following_url - gists_url - gravatar_id - html_url - id - node_id - login - organizations_url - received_events_url - repos_url - site_admin - starred_url - subscriptions_url - type - url app-permissions: title: App Permissions type: object description: The permissions granted to the user-to-server access token. properties: actions: type: string description: 'The level of permission to grant the access token for GitHub Actions workflows, workflow runs, and artifacts. Can be one of: `read` or `write`.' enum: - read - write administration: type: string description: 'The level of permission to grant the access token for repository creation, deletion, settings, teams, and collaborators creation. Can be one of: `read` or `write`.' enum: - read - write checks: type: string description: 'The level of permission to grant the access token for checks on code. Can be one of: `read` or `write`.' enum: - read - write contents: type: string description: 'The level of permission to grant the access token for repository contents, commits, branches, downloads, releases, and merges. Can be one of: `read` or `write`.' enum: - read - write deployments: type: string description: 'The level of permission to grant the access token for deployments and deployment statuses. Can be one of: `read` or `write`.' enum: - read - write environments: type: string description: 'The level of permission to grant the access token for managing repository environments. Can be one of: `read` or `write`.' enum: - read - write issues: type: string description: 'The level of permission to grant the access token for issues and related comments, assignees, labels, and milestones. Can be one of: `read` or `write`.' enum: - read - write metadata: type: string description: 'The level of permission to grant the access token to search repositories, list collaborators, and access repository metadata. Can be one of: `read` or `write`.' enum: - read - write packages: type: string description: 'The level of permission to grant the access token for packages published to GitHub Packages. Can be one of: `read` or `write`.' enum: - read - write pages: type: string description: 'The level of permission to grant the access token to retrieve Pages statuses, configuration, and builds, as well as create new builds. Can be one of: `read` or `write`.' enum: - read - write pull_requests: type: string description: 'The level of permission to grant the access token for pull requests and related comments, assignees, labels, milestones, and merges. Can be one of: `read` or `write`.' enum: - read - write repository_hooks: type: string description: 'The level of permission to grant the access token to manage the post-receive hooks for a repository. Can be one of: `read` or `write`.' enum: - read - write repository_projects: type: string description: 'The level of permission to grant the access token to manage repository projects, columns, and cards. Can be one of: `read`, `write`, or `admin`.' enum: - read - write - admin secret_scanning_alerts: type: string description: 'The level of permission to grant the access token to view and manage secret scanning alerts. Can be one of: `read` or `write`.' enum: - read - write secrets: type: string description: 'The level of permission to grant the access token to manage repository secrets. Can be one of: `read` or `write`.' enum: - read - write security_events: type: string description: 'The level of permission to grant the access token to view and manage security events like code scanning alerts. Can be one of: `read` or `write`.' enum: - read - write single_file: type: string description: 'The level of permission to grant the access token to manage just a single file. Can be one of: `read` or `write`.' enum: - read - write statuses: type: string description: 'The level of permission to grant the access token for commit statuses. Can be one of: `read` or `write`.' enum: - read - write vulnerability_alerts: type: string description: 'The level of permission to grant the access token to manage Dependabot alerts. Can be one of: `read` or `write`.' enum: - read - write workflows: type: string description: 'The level of permission to grant the access token to update GitHub Actions workflow files. Can be one of: `write`.' enum: - write members: type: string description: 'The level of permission to grant the access token for organization teams and members. Can be one of: `read` or `write`.' enum: - read - write organization_administration: type: string description: 'The level of permission to grant the access token to manage access to an organization. Can be one of: `read` or `write`.' enum: - read - write organization_hooks: type: string description: 'The level of permission to grant the access token to manage the post-receive hooks for an organization. Can be one of: `read` or `write`.' enum: - read - write organization_plan: type: string description: 'The level of permission to grant the access token for viewing an organization''s plan. Can be one of: `read`.' enum: - read organization_projects: type: string description: 'The level of permission to grant the access token to manage organization projects and projects beta (where available). Can be one of: `read`, `write`, or `admin`.' enum: - read - write - admin organization_packages: type: string description: 'The level of permission to grant the access token for organization packages published to GitHub Packages. Can be one of: `read` or `write`.' enum: - read - write organization_secrets: type: string description: 'The level of permission to grant the access token to manage organization secrets. Can be one of: `read` or `write`.' enum: - read - write organization_self_hosted_runners: type: string description: 'The level of permission to grant the access token to view and manage GitHub Actions self-hosted runners available to an organization. Can be one of: `read` or `write`.' enum: - read - write organization_user_blocking: type: string description: 'The level of permission to grant the access token to view and manage users blocked by the organization. Can be one of: `read` or `write`.' enum: - read - write team_discussions: type: string description: 'The level of permission to grant the access token to manage team discussions and related comments. Can be one of: `read` or `write`.' enum: - read - write content_references: type: string description: 'The level of permission to grant the access token for notification of content references and creation content attachments. Can be one of: `read` or `write`.' enum: - read - write example: contents: read issues: read deployments: write single_file: read scoped-installation: title: Scoped Installation type: object properties: permissions: "$ref": "#/components/schemas/app-permissions" repository_selection: description: Describe whether all repositories have been selected or there's a selection involved type: string enum: - all - selected single_file_name: type: - string - 'null' examples: - config.yaml has_multiple_single_files: type: boolean examples: - true single_file_paths: type: array items: type: string examples: - config.yml - ".github/issue_TEMPLATE.md" repositories_url: type: string format: uri examples: - https://api.github.com/users/octocat/repos account: "$ref": "#/components/schemas/simple-user" required: - permissions - repository_selection - single_file_name - repositories_url - account authorization: title: Authorization description: The authorization for an OAuth app, GitHub App, or a Personal Access Token. type: object properties: id: type: integer url: type: string format: uri scopes: description: A list of scopes that this authorization is in. type: - array - 'null' items: type: string token: type: string token_last_eight: type: - string - 'null' hashed_token: type: - string - 'null' app: type: object properties: client_id: type: string name: type: string url: type: string format: uri required: - client_id - name - url note: type: - string - 'null' note_url: type: - string - 'null' format: uri updated_at: type: string format: date-time created_at: type: string format: date-time fingerprint: type: - string - 'null' user: anyOf: - type: 'null' - "$ref": "#/components/schemas/simple-user" installation: anyOf: - type: 'null' - "$ref": "#/components/schemas/scoped-installation" required: - app - id - note - note_url - scopes - token - hashed_token - token_last_eight - fingerprint - url - created_at - updated_at - expires_at integration: title: GitHub app description: GitHub apps are a new way to extend GitHub. They can be installed directly on organizations and user accounts and granted access to specific repositories. They come with granular permissions and built-in webhooks. GitHub apps are first class actors within GitHub. type: object properties: id: description: Unique identifier of the GitHub app type: integer examples: - 37 slug: description: The slug name of the GitHub app type: string examples: - probot-owners node_id: type: string examples: - MDExOkludGVncmF0aW9uMQ== owner: anyOf: - type: 'null' - "$ref": "#/components/schemas/simple-user" name: description: The name of the GitHub app type: string examples: - Probot Owners description: type: - string - 'null' examples: - The description of the app. external_url: type: string format: uri examples: - https://example.com html_url: type: string format: uri examples: - https://github.com/apps/super-ci created_at: type: string format: date-time examples: - '2017-07-08T16:18:44-04:00' updated_at: type: string format: date-time examples: - '2017-07-08T16:18:44-04:00' permissions: description: The set of permissions for the GitHub app type: object properties: issues: type: string checks: type: string metadata: type: string contents: type: string deployments: type: string additionalProperties: type: string example: issues: read deployments: write events: description: The list of events for the GitHub app type: array items: type: string examples: - label - deployment installations_count: description: The number of installations associated with the GitHub app type: integer examples: - 5 client_id: type: string examples: - '"Iv1.25b5d1e65ffc4022"' client_secret: type: string examples: - '"1d4b2097ac622ba702d19de498f005747a8b21d3"' webhook_secret: type: - string - 'null' examples: - '"6fba8f2fc8a7e8f2cca5577eddd82ca7586b3b6b"' pem: type: string examples: - '"-----BEGIN RSA PRIVATE KEY-----\nMIIEogIBAAKCAQEArYxrNYD/iT5CZVpRJu4rBKmmze3PVmT/gCo2ATUvDvZTPTey\nxcGJ3vvrJXazKk06pN05TN29o98jrYz4cengG3YGsXPNEpKsIrEl8NhbnxapEnM9\nJCMRe0P5JcPsfZlX6hmiT7136GRWiGOUba2X9+HKh8QJVLG5rM007TBER9/z9mWm\nrJuNh+m5l320oBQY/Qq3A7wzdEfZw8qm/mIN0FCeoXH1L6B8xXWaAYBwhTEh6SSn\nZHlO1Xu1JWDmAvBCi0RO5aRSKM8q9QEkvvHP4yweAtK3N8+aAbZ7ovaDhyGz8r6r\nzhU1b8Uo0Z2ysf503WqzQgIajr7Fry7/kUwpgQIDAQABAoIBADwJp80Ko1xHPZDy\nfcCKBDfIuPvkmSW6KumbsLMaQv1aGdHDwwTGv3t0ixSay8CGlxMRtRDyZPib6SvQ\n6OH/lpfpbMdW2ErkksgtoIKBVrDilfrcAvrNZu7NxRNbhCSvN8q0s4ICecjbbVQh\nnueSdlA6vGXbW58BHMq68uRbHkP+k+mM9U0mDJ1HMch67wlg5GbayVRt63H7R2+r\nVxcna7B80J/lCEjIYZznawgiTvp3MSanTglqAYi+m1EcSsP14bJIB9vgaxS79kTu\noiSo93leJbBvuGo8QEiUqTwMw4tDksmkLsoqNKQ1q9P7LZ9DGcujtPy4EZsamSJT\ny8OJt0ECgYEA2lxOxJsQk2kI325JgKFjo92mQeUObIvPfSNWUIZQDTjniOI6Gv63\nGLWVFrZcvQBWjMEQraJA9xjPbblV8PtfO87MiJGLWCHFxmPz2dzoedN+2Coxom8m\nV95CLz8QUShuao6u/RYcvUaZEoYs5bHcTmy5sBK80JyEmafJPtCQVxMCgYEAy3ar\nZr3yv4xRPEPMat4rseswmuMooSaK3SKub19WFI5IAtB/e7qR1Rj9JhOGcZz+OQrl\nT78O2OFYlgOIkJPvRMrPpK5V9lslc7tz1FSh3BZMRGq5jSyD7ETSOQ0c8T2O/s7v\nbeEPbVbDe4mwvM24XByH0GnWveVxaDl51ABD65sCgYB3ZAspUkOA5egVCh8kNpnd\nSd6SnuQBE3ySRlT2WEnCwP9Ph6oPgn+oAfiPX4xbRqkL8q/k0BdHQ4h+zNwhk7+h\nWtPYRAP1Xxnc/F+jGjb+DVaIaKGU18MWPg7f+FI6nampl3Q0KvfxwX0GdNhtio8T\nTj1E+SnFwh56SRQuxSh2gwKBgHKjlIO5NtNSflsUYFM+hyQiPiqnHzddfhSG+/3o\nm5nNaSmczJesUYreH5San7/YEy2UxAugvP7aSY2MxB+iGsiJ9WD2kZzTUlDZJ7RV\nUzWsoqBR+eZfVJ2FUWWvy8TpSG6trh4dFxImNtKejCR1TREpSiTV3Zb1dmahK9GV\nrK9NAoGAbBxRLoC01xfxCTgt5BDiBcFVh4fp5yYKwavJPLzHSpuDOrrI9jDn1oKN\nonq5sDU1i391zfQvdrbX4Ova48BN+B7p63FocP/MK5tyyBoT8zQEk2+vWDOw7H/Z\nu5dTCPxTIsoIwUw1I+7yIxqJzLPFgR2gVBwY1ra/8iAqCj+zeBw=\n-----END RSA PRIVATE KEY-----\n"' required: - id - node_id - owner - name - description - external_url - html_url - created_at - updated_at - permissions - events basic-error: title: Basic Error description: Basic Error type: object properties: message: type: string documentation_url: type: string url: type: string status: type: string validation-error-simple: title: Validation Error Simple description: Validation Error Simple type: object required: - message - documentation_url properties: message: type: string documentation_url: type: string errors: type: array items: type: string webhook-config-url: type: string description: The URL to which the payloads will be delivered. format: uri examples: - https://example.com/webhook webhook-config-content-type: type: string description: The media type used to serialize the payloads. Supported values include `json` and `form`. The default is `form`. examples: - '"json"' webhook-config-secret: type: string description: If provided, the `secret` will be used as the `key` to generate the HMAC hex digest value for [delivery signature headers](https://docs.github.com/enterprise-server@3.0/webhooks/event-payloads/#delivery-headers). examples: - '"********"' webhook-config-insecure-ssl: oneOf: - type: string description: Determines whether the SSL certificate of the host for `url` will be verified when delivering payloads. Supported values include `0` (verification is performed) and `1` (verification is not performed). The default is `0`. **We strongly recommend not setting this to `1` as you are subject to man-in-the-middle and other attacks.** examples: - '"0"' - type: number webhook-config: title: Webhook Configuration description: Configuration object of the webhook type: object properties: url: "$ref": "#/components/schemas/webhook-config-url" content_type: "$ref": "#/components/schemas/webhook-config-content-type" secret: "$ref": "#/components/schemas/webhook-config-secret" insecure_ssl: "$ref": "#/components/schemas/webhook-config-insecure-ssl" enterprise: title: Enterprise description: An enterprise account type: object properties: description: description: A short description of the enterprise. type: - string - 'null' html_url: type: string format: uri examples: - https://github.com/enterprises/octo-business website_url: description: The enterprise's website URL. type: - string - 'null' format: uri id: description: Unique identifier of the enterprise type: integer examples: - 42 node_id: type: string examples: - MDEwOlJlcG9zaXRvcnkxMjk2MjY5 name: description: The name of the enterprise. type: string examples: - Octo Business slug: description: The slug url identifier for the enterprise. type: string examples: - octo-business created_at: type: - string - 'null' format: date-time examples: - '2019-01-26T19:01:12Z' updated_at: type: - string - 'null' format: date-time examples: - '2019-01-26T19:14:43Z' avatar_url: type: string format: uri required: - id - node_id - name - slug - html_url - created_at - updated_at - avatar_url installation: title: Installation description: Installation type: object properties: id: description: The ID of the installation. type: integer examples: - 1 account: anyOf: - "$ref": "#/components/schemas/simple-user" - "$ref": "#/components/schemas/enterprise" type: - 'null' - object repository_selection: description: Describe whether all repositories have been selected or there's a selection involved type: string enum: - all - selected access_tokens_url: type: string format: uri examples: - https://api.github.com/installations/1/access_tokens repositories_url: type: string format: uri examples: - https://api.github.com/installation/repositories html_url: type: string format: uri examples: - https://github.com/organizations/github/settings/installations/1 app_id: type: integer examples: - 1 target_id: description: The ID of the user or organization this token is being scoped to. type: integer target_type: type: string examples: - Organization permissions: "$ref": "#/components/schemas/app-permissions" events: type: array items: type: string created_at: type: string format: date-time updated_at: type: string format: date-time single_file_name: type: - string - 'null' examples: - config.yaml has_multiple_single_files: type: boolean examples: - true single_file_paths: type: array items: type: string examples: - config.yml - ".github/issue_TEMPLATE.md" app_slug: type: string examples: - github-actions suspended_by: anyOf: - type: 'null' - "$ref": "#/components/schemas/simple-user" suspended_at: type: - string - 'null' format: date-time contact_email: type: - string - 'null' examples: - '"test_13f1e99741e3e004@d7e1eb0bc0a1ba12.com"' required: - id - app_id - app_slug - target_id - target_type - single_file_name - repository_selection - access_tokens_url - html_url - repositories_url - events - account - permissions - created_at - updated_at - suspended_by - suspended_at license-simple: title: License Simple description: License Simple type: object properties: key: type: string examples: - mit name: type: string examples: - MIT License url: type: - string - 'null' format: uri examples: - https://api.github.com/licenses/mit spdx_id: type: - string - 'null' examples: - MIT node_id: type: string examples: - MDc6TGljZW5zZW1pdA== html_url: type: string format: uri required: - key - name - url - spdx_id - node_id repository: title: Repository description: A git repository type: object properties: id: description: Unique identifier of the repository type: integer examples: - 42 node_id: type: string examples: - MDEwOlJlcG9zaXRvcnkxMjk2MjY5 name: description: The name of the repository. type: string examples: - Team Environment full_name: type: string examples: - octocat/Hello-World license: anyOf: - type: 'null' - "$ref": "#/components/schemas/license-simple" organization: anyOf: - type: 'null' - "$ref": "#/components/schemas/simple-user" forks: type: integer permissions: type: object properties: admin: type: boolean pull: type: boolean triage: type: boolean push: type: boolean maintain: type: boolean required: - admin - pull - push owner: "$ref": "#/components/schemas/simple-user" private: description: Whether the repository is private or public. default: false type: boolean html_url: type: string format: uri examples: - https://github.com/octocat/Hello-World description: type: - string - 'null' examples: - This your first repo! fork: type: boolean url: type: string format: uri examples: - https://api.github.com/repos/octocat/Hello-World archive_url: type: string examples: - http://api.github.com/repos/octocat/Hello-World/{archive_format}{/ref} assignees_url: type: string examples: - http://api.github.com/repos/octocat/Hello-World/assignees{/user} blobs_url: type: string examples: - http://api.github.com/repos/octocat/Hello-World/git/blobs{/sha} branches_url: type: string examples: - http://api.github.com/repos/octocat/Hello-World/branches{/branch} collaborators_url: type: string examples: - http://api.github.com/repos/octocat/Hello-World/collaborators{/collaborator} comments_url: type: string examples: - http://api.github.com/repos/octocat/Hello-World/comments{/number} commits_url: type: string examples: - http://api.github.com/repos/octocat/Hello-World/commits{/sha} compare_url: type: string examples: - http://api.github.com/repos/octocat/Hello-World/compare/{base}...{head} contents_url: type: string examples: - http://api.github.com/repos/octocat/Hello-World/contents/{+path} contributors_url: type: string format: uri examples: - http://api.github.com/repos/octocat/Hello-World/contributors deployments_url: type: string format: uri examples: - http://api.github.com/repos/octocat/Hello-World/deployments downloads_url: type: string format: uri examples: - http://api.github.com/repos/octocat/Hello-World/downloads events_url: type: string format: uri examples: - http://api.github.com/repos/octocat/Hello-World/events forks_url: type: string format: uri examples: - http://api.github.com/repos/octocat/Hello-World/forks git_commits_url: type: string examples: - http://api.github.com/repos/octocat/Hello-World/git/commits{/sha} git_refs_url: type: string examples: - http://api.github.com/repos/octocat/Hello-World/git/refs{/sha} git_tags_url: type: string examples: - http://api.github.com/repos/octocat/Hello-World/git/tags{/sha} git_url: type: string examples: - git:github.com/octocat/Hello-World.git issue_comment_url: type: string examples: - http://api.github.com/repos/octocat/Hello-World/issues/comments{/number} issue_events_url: type: string examples: - http://api.github.com/repos/octocat/Hello-World/issues/events{/number} issues_url: type: string examples: - http://api.github.com/repos/octocat/Hello-World/issues{/number} keys_url: type: string examples: - http://api.github.com/repos/octocat/Hello-World/keys{/key_id} labels_url: type: string examples: - http://api.github.com/repos/octocat/Hello-World/labels{/name} languages_url: type: string format: uri examples: - http://api.github.com/repos/octocat/Hello-World/languages merges_url: type: string format: uri examples: - http://api.github.com/repos/octocat/Hello-World/merges milestones_url: type: string examples: - http://api.github.com/repos/octocat/Hello-World/milestones{/number} notifications_url: type: string examples: - http://api.github.com/repos/octocat/Hello-World/notifications{?since,all,participating} pulls_url: type: string examples: - http://api.github.com/repos/octocat/Hello-World/pulls{/number} releases_url: type: string examples: - http://api.github.com/repos/octocat/Hello-World/releases{/id} ssh_url: type: string examples: - git@github.com:octocat/Hello-World.git stargazers_url: type: string format: uri examples: - http://api.github.com/repos/octocat/Hello-World/stargazers statuses_url: type: string examples: - http://api.github.com/repos/octocat/Hello-World/statuses/{sha} subscribers_url: type: string format: uri examples: - http://api.github.com/repos/octocat/Hello-World/subscribers subscription_url: type: string format: uri examples: - http://api.github.com/repos/octocat/Hello-World/subscription tags_url: type: string format: uri examples: - http://api.github.com/repos/octocat/Hello-World/tags teams_url: type: string format: uri examples: - http://api.github.com/repos/octocat/Hello-World/teams trees_url: type: string examples: - http://api.github.com/repos/octocat/Hello-World/git/trees{/sha} clone_url: type: string examples: - https://github.com/octocat/Hello-World.git mirror_url: type: - string - 'null' format: uri examples: - git:git.example.com/octocat/Hello-World hooks_url: type: string format: uri examples: - http://api.github.com/repos/octocat/Hello-World/hooks svn_url: type: string format: uri examples: - https://svn.github.com/octocat/Hello-World homepage: type: - string - 'null' format: uri examples: - https://github.com language: type: - string - 'null' forks_count: type: integer examples: - 9 stargazers_count: type: integer examples: - 80 watchers_count: type: integer examples: - 80 size: type: integer examples: - 108 default_branch: description: The default branch of the repository. type: string examples: - master open_issues_count: type: integer examples: - 0 is_template: description: Whether this repository acts as a template that can be used to generate new repositories. default: false type: boolean examples: - true topics: type: array items: type: string has_issues: description: Whether issues are enabled. default: true type: boolean examples: - true has_projects: description: Whether projects are enabled. default: true type: boolean examples: - true has_wiki: description: Whether the wiki is enabled. default: true type: boolean examples: - true has_pages: type: boolean has_downloads: description: Whether downloads are enabled. default: true type: boolean examples: - true archived: description: Whether the repository is archived. default: false type: boolean disabled: type: boolean description: Returns whether or not this repository disabled. visibility: description: 'The repository visibility: public, private, or internal.' default: public type: string pushed_at: type: - string - 'null' format: date-time examples: - '2011-01-26T19:06:43Z' created_at: type: - string - 'null' format: date-time examples: - '2011-01-26T19:01:12Z' updated_at: type: - string - 'null' format: date-time examples: - '2011-01-26T19:14:43Z' allow_rebase_merge: description: Whether to allow rebase merges for pull requests. default: true type: boolean examples: - true template_repository: type: - object - 'null' properties: id: type: integer node_id: type: string name: type: string full_name: type: string owner: type: object properties: login: type: string id: type: integer node_id: type: string avatar_url: type: string gravatar_id: type: string url: type: string html_url: type: string followers_url: type: string following_url: type: string gists_url: type: string starred_url: type: string subscriptions_url: type: string organizations_url: type: string repos_url: type: string events_url: type: string received_events_url: type: string type: type: string site_admin: type: boolean private: type: boolean html_url: type: string description: type: string fork: type: boolean url: type: string archive_url: type: string assignees_url: type: string blobs_url: type: string branches_url: type: string collaborators_url: type: string comments_url: type: string commits_url: type: string compare_url: type: string contents_url: type: string contributors_url: type: string deployments_url: type: string downloads_url: type: string events_url: type: string forks_url: type: string git_commits_url: type: string git_refs_url: type: string git_tags_url: type: string git_url: type: string issue_comment_url: type: string issue_events_url: type: string issues_url: type: string keys_url: type: string labels_url: type: string languages_url: type: string merges_url: type: string milestones_url: type: string notifications_url: type: string pulls_url: type: string releases_url: type: string ssh_url: type: string stargazers_url: type: string statuses_url: type: string subscribers_url: type: string subscription_url: type: string tags_url: type: string teams_url: type: string trees_url: type: string clone_url: type: string mirror_url: type: string hooks_url: type: string svn_url: type: string homepage: type: string language: type: string forks_count: type: integer stargazers_count: type: integer watchers_count: type: integer size: type: integer default_branch: type: string open_issues_count: type: integer is_template: type: boolean topics: type: array items: type: string has_issues: type: boolean has_projects: type: boolean has_wiki: type: boolean has_pages: type: boolean has_downloads: type: boolean archived: type: boolean disabled: type: boolean visibility: type: string pushed_at: type: string created_at: type: string updated_at: type: string permissions: type: object properties: admin: type: boolean maintain: type: boolean push: type: boolean triage: type: boolean pull: type: boolean allow_rebase_merge: type: boolean temp_clone_token: type: string allow_squash_merge: type: boolean delete_branch_on_merge: type: boolean allow_update_branch: type: boolean allow_merge_commit: type: boolean subscribers_count: type: integer network_count: type: integer temp_clone_token: type: string allow_squash_merge: description: Whether to allow squash merges for pull requests. default: true type: boolean examples: - true delete_branch_on_merge: description: Whether to delete head branches when pull requests are merged default: false type: boolean examples: - false allow_merge_commit: description: Whether to allow merge commits for pull requests. default: true type: boolean examples: - true allow_forking: description: Whether to allow forking this repo type: boolean subscribers_count: type: integer network_count: type: integer open_issues: type: integer watchers: type: integer master_branch: type: string starred_at: type: string examples: - '"2020-07-09T00:17:42Z"' required: - archive_url - assignees_url - blobs_url - branches_url - collaborators_url - comments_url - commits_url - compare_url - contents_url - contributors_url - deployments_url - description - downloads_url - events_url - fork - forks_url - full_name - git_commits_url - git_refs_url - git_tags_url - hooks_url - html_url - id - node_id - issue_comment_url - issue_events_url - issues_url - keys_url - labels_url - languages_url - merges_url - milestones_url - name - notifications_url - owner - private - pulls_url - releases_url - stargazers_url - statuses_url - subscribers_url - subscription_url - tags_url - teams_url - trees_url - url - clone_url - default_branch - forks - forks_count - git_url - has_downloads - has_issues - has_projects - has_wiki - has_pages - homepage - language - archived - disabled - mirror_url - open_issues - open_issues_count - license - pushed_at - size - ssh_url - stargazers_count - svn_url - watchers - watchers_count - created_at - updated_at installation-token: title: Installation Token description: Authentication token for a GitHub App installed on a user or org. type: object properties: token: type: string expires_at: type: string permissions: "$ref": "#/components/schemas/app-permissions" repository_selection: type: string enum: - all - selected repositories: type: array items: "$ref": "#/components/schemas/repository" single_file: type: string examples: - README.md has_multiple_single_files: type: boolean examples: - true single_file_paths: type: array items: type: string examples: - config.yml - ".github/issue_TEMPLATE.md" required: - token - expires_at validation-error: title: Validation Error description: Validation Error type: object required: - message - documentation_url properties: message: type: string documentation_url: type: string errors: type: array items: type: object required: - code properties: resource: type: string field: type: string message: type: string code: type: string index: type: integer value: oneOf: - type: - string - 'null' - type: - integer - 'null' - type: - array - 'null' items: type: string application-grant: title: Application Grant description: The authorization associated with an OAuth Access. type: object properties: id: type: integer examples: - 1 url: type: string format: uri examples: - https://api.github.com/applications/grants/1 app: type: object properties: client_id: type: string name: type: string url: type: string format: uri required: - client_id - name - url created_at: type: string format: date-time examples: - '2011-09-06T17:26:27Z' updated_at: type: string format: date-time examples: - '2011-09-06T20:39:23Z' scopes: type: array items: type: string examples: - public_repo user: anyOf: - type: 'null' - "$ref": "#/components/schemas/simple-user" required: - app - id - scopes - url - created_at - updated_at code-of-conduct: title: Code Of Conduct description: Code Of Conduct type: object properties: key: type: string examples: - contributor_covenant name: type: string examples: - Contributor Covenant url: type: string format: uri examples: - https://api.github.com/codes_of_conduct/contributor_covenant body: type: string examples: - | # Contributor Covenant Code of Conduct ## Our Pledge In the interest of fostering an open and welcoming environment, we as contributors and maintainers pledge to making participation in our project and our community a harassment-free experience for everyone, regardless of age, body size, disability, ethnicity, gender identity and expression, level of experience, nationality, personal appearance, race, religion, or sexual identity and orientation. ## Our Standards Examples of behavior that contributes to creating a positive environment include: * Using welcoming and inclusive language * Being respectful of differing viewpoints and experiences * Gracefully accepting constructive criticism * Focusing on what is best for the community * Showing empathy towards other community members Examples of unacceptable behavior by participants include: * The use of sexualized language or imagery and unwelcome sexual attention or advances * Trolling, insulting/derogatory comments, and personal or political attacks * Public or private harassment * Publishing others' private information, such as a physical or electronic address, without explicit permission * Other conduct which could reasonably be considered inappropriate in a professional setting ## Our Responsibilities Project maintainers are responsible for clarifying the standards of acceptable behavior and are expected to take appropriate and fair corrective action in response to any instances of unacceptable behavior. Project maintainers have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, or to ban temporarily or permanently any contributor for other behaviors that they deem inappropriate, threatening, offensive, or harmful. ## Scope This Code of Conduct applies both within project spaces and in public spaces when an individual is representing the project or its community. Examples of representing a project or community include using an official project e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event. Representation of a project may be further defined and clarified by project maintainers. ## Enforcement Instances of abusive, harassing, or otherwise unacceptable behavior may be reported by contacting the project team at [EMAIL]. The project team will review and investigate all complaints, and will respond in a way that it deems appropriate to the circumstances. The project team is obligated to maintain confidentiality with regard to the reporter of an incident. Further details of specific enforcement policies may be posted separately. Project maintainers who do not follow or enforce the Code of Conduct in good faith may face temporary or permanent repercussions as determined by other members of the project's leadership. ## Attribution This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, available at [http://contributor-covenant.org/version/1/4][version] [homepage]: http://contributor-covenant.org [version]: http://contributor-covenant.org/version/1/4/ html_url: type: - string - 'null' format: uri required: - url - html_url - key - name announcement-message: type: string description: The announcement text in GitHub Flavored Markdown. For more information about GitHub Flavored Markdown, see "[Basic writing and formatting syntax](https://docs.github.com/enterprise-server@3.0/github/writing-on-github/getting-started-with-writing-and-formatting-on-github/basic-writing-and-formatting-syntax)." examples: - Very **important** announcement about _nothing_. announcement-expiration: type: - string - 'null' format: date-time description: 'The time at which the announcement expires. This is a timestamp in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format: `YYYY-MM-DDTHH:MM:SSZ`. To set an announcement that never expires, omit this parameter, set it to `null`, or set it to an empty string.' examples: - '"2021-01-01T00:00:00.000-07:00"' announcement: title: Enterprise Announcement description: Enterprise global announcement type: object properties: announcement: "$ref": "#/components/schemas/announcement-message" expires_at: "$ref": "#/components/schemas/announcement-expiration" required: - announcement license-info: type: object properties: seats: oneOf: - type: string - type: integer seats_used: type: integer seats_available: oneOf: - type: string - type: integer kind: type: string days_until_expiration: type: integer expire_at: type: string enterprise-repository-overview: title: Repository Enterprise Stats type: object properties: total_repos: type: integer root_repos: type: integer fork_repos: type: integer org_repos: type: integer total_pushes: type: integer total_wikis: type: integer required: - total_repos - root_repos - fork_repos - org_repos - total_pushes - total_wikis enterprise-hook-overview: title: Hooks Enterprise Stats type: object properties: total_hooks: type: integer active_hooks: type: integer inactive_hooks: type: integer required: - total_hooks - active_hooks - inactive_hooks enterprise-page-overview: title: Enterprise Pages Stats type: object properties: total_pages: type: integer required: - total_pages enterprise-organization-overview: title: Enterprise Organization Stats type: object properties: total_orgs: type: integer disabled_orgs: type: integer total_teams: type: integer total_team_members: type: integer required: - total_orgs - disabled_orgs - total_teams - total_team_members enterprise-user-overview: title: Enterprise User Stats type: object properties: total_users: type: integer admin_users: type: integer suspended_users: type: integer required: - total_users - admin_users - suspended_users enterprise-pull-request-overview: title: Enterprise Pull Request Stats type: object properties: total_pulls: type: integer merged_pulls: type: integer mergeable_pulls: type: integer unmergeable_pulls: type: integer required: - total_pulls - merged_pulls - mergeable_pulls - unmergeable_pulls enterprise-issue-overview: title: Enterprise Issue Stats type: object properties: total_issues: type: integer open_issues: type: integer closed_issues: type: integer required: - total_issues - open_issues - closed_issues enterprise-milestone-overview: title: Enterprise Milestone Stats type: object properties: total_milestones: type: integer open_milestones: type: integer closed_milestones: type: integer required: - total_milestones - open_milestones - closed_milestones enterprise-gist-overview: title: Enterprise Gist Stats type: object properties: total_gists: type: integer private_gists: type: integer public_gists: type: integer required: - total_gists - private_gists - public_gists enterprise-comment-overview: title: Enterprise Comment Stats type: object properties: total_commit_comments: type: integer total_gist_comments: type: integer total_issue_comments: type: integer total_pull_request_comments: type: integer required: - total_commit_comments - total_gist_comments - total_issue_comments - total_pull_request_comments enterprise-overview: type: object properties: repos: "$ref": "#/components/schemas/enterprise-repository-overview" hooks: "$ref": "#/components/schemas/enterprise-hook-overview" pages: "$ref": "#/components/schemas/enterprise-page-overview" orgs: "$ref": "#/components/schemas/enterprise-organization-overview" users: "$ref": "#/components/schemas/enterprise-user-overview" pulls: "$ref": "#/components/schemas/enterprise-pull-request-overview" issues: "$ref": "#/components/schemas/enterprise-issue-overview" milestones: "$ref": "#/components/schemas/enterprise-milestone-overview" gists: "$ref": "#/components/schemas/enterprise-gist-overview" comments: "$ref": "#/components/schemas/enterprise-comment-overview" enabled-organizations: type: string description: 'The policy that controls the organizations in the enterprise that are allowed to run GitHub Actions. Can be one of: `all`, `none`, or `selected`.' enum: - all - none - selected allowed-actions: type: string description: 'The permissions policy that controls the actions that are allowed to run. Can be one of: `all`, `local_only`, or `selected`.' enum: - all - local_only - selected selected-actions-url: type: string description: The API URL to use to get or set the actions that are allowed to run, when `allowed_actions` is set to `selected`. actions-enterprise-permissions: type: object properties: enabled_organizations: "$ref": "#/components/schemas/enabled-organizations" selected_organizations_url: type: string description: The API URL to use to get or set the selected organizations that are allowed to run GitHub Actions, when `enabled_organizations` is set to `selected`. allowed_actions: "$ref": "#/components/schemas/allowed-actions" selected_actions_url: "$ref": "#/components/schemas/selected-actions-url" required: - enabled_organizations selected-actions: type: object properties: github_owned_allowed: type: boolean description: Whether GitHub-owned actions are allowed. For example, this includes the actions in the `actions` organization. patterns_allowed: type: array description: Specifies a list of string-matching patterns to allow specific action(s). Wildcards, tags, and SHAs are allowed. For example, `monalisa/octocat@*`, `monalisa/octocat@v2`, `monalisa/*`." items: type: string required: - github_owned_allowed - patterns_allowed runner-groups-enterprise: type: object properties: id: type: number name: type: string visibility: type: string default: type: boolean selected_organizations_url: type: string runners_url: type: string allows_public_repositories: type: boolean required: - id - name - visibility - allows_public_repositories - default - runners_url runner-label: title: Self hosted runner label description: A label for a self hosted runner type: object properties: id: type: integer description: Unique identifier of the label. name: type: string description: Name of the label. type: type: string description: The type of label. Read-only labels are applied automatically when the runner is configured. enum: - read-only - custom required: - name runner: title: Self hosted runners description: A self hosted runner type: object properties: id: description: The id of the runner. type: integer examples: - 5 name: description: The name of the runner. type: string examples: - iMac os: description: The Operating System of the runner. type: string examples: - macos status: description: The status of the runner. type: string examples: - online busy: type: boolean labels: type: array items: "$ref": "#/components/schemas/runner-label" required: - id - name - os - status - busy - labels runner-application: title: Runner Application description: Runner Application type: object properties: os: type: string architecture: type: string download_url: type: string filename: type: string temp_download_token: description: A short lived bearer token used to download the runner, if needed. type: string sha256_checksum: type: string required: - os - architecture - download_url - filename authentication-token: title: Authentication Token description: Authentication Token type: object properties: token: description: The token used for authentication type: string examples: - v1.1f699f1069f60xxx expires_at: description: The time this token expires type: string format: date-time examples: - '2016-07-11T22:14:10Z' permissions: type: object examples: - issues: read deployments: write repositories: description: The repositories this token has access to type: array items: "$ref": "#/components/schemas/repository" single_file: type: - string - 'null' examples: - config.yaml repository_selection: description: Describe whether all repositories have been selected or there's a selection involved type: string enum: - all - selected required: - token - expires_at actor: title: Actor description: Actor type: object properties: id: type: integer login: type: string display_login: type: string gravatar_id: type: - string - 'null' url: type: string format: uri avatar_url: type: string format: uri required: - id - login - gravatar_id - url - avatar_url milestone: title: Milestone description: A collection of related issues and pull requests. type: object properties: url: type: string format: uri examples: - https://api.github.com/repos/octocat/Hello-World/milestones/1 html_url: type: string format: uri examples: - https://github.com/octocat/Hello-World/milestones/v1.0 labels_url: type: string format: uri examples: - https://api.github.com/repos/octocat/Hello-World/milestones/1/labels id: type: integer examples: - 1002604 node_id: type: string examples: - MDk6TWlsZXN0b25lMTAwMjYwNA== number: description: The number of the milestone. type: integer examples: - 42 state: description: The state of the milestone. type: string enum: - open - closed default: open examples: - open title: description: The title of the milestone. type: string examples: - v1.0 description: type: - string - 'null' examples: - Tracking milestone for version 1.0 creator: anyOf: - type: 'null' - "$ref": "#/components/schemas/simple-user" open_issues: type: integer examples: - 4 closed_issues: type: integer examples: - 8 created_at: type: string format: date-time examples: - '2011-04-10T20:09:31Z' updated_at: type: string format: date-time examples: - '2014-03-03T18:58:10Z' closed_at: type: - string - 'null' format: date-time examples: - '2013-02-12T13:22:01Z' due_on: type: - string - 'null' format: date-time examples: - '2012-10-09T23:39:01Z' required: - closed_issues - creator - description - due_on - closed_at - id - node_id - labels_url - html_url - number - open_issues - state - title - url - created_at - updated_at author_association: title: author_association type: string description: How the author is associated with the repository. enum: - COLLABORATOR - CONTRIBUTOR - FIRST_TIMER - FIRST_TIME_CONTRIBUTOR - MANNEQUIN - MEMBER - NONE - OWNER examples: - OWNER reaction-rollup: title: Reaction Rollup type: object properties: url: type: string format: uri total_count: type: integer "+1": type: integer "-1": type: integer laugh: type: integer confused: type: integer heart: type: integer hooray: type: integer eyes: type: integer rocket: type: integer required: - url - total_count - "+1" - "-1" - laugh - confused - heart - hooray - eyes - rocket issue: title: Issue description: Issues are a great way to keep track of tasks, enhancements, and bugs for your projects. type: object properties: id: type: integer node_id: type: string url: description: URL for the issue type: string format: uri examples: - https://api.github.com/repositories/42/issues/1 repository_url: type: string format: uri labels_url: type: string comments_url: type: string format: uri events_url: type: string format: uri html_url: type: string format: uri number: description: Number uniquely identifying the issue within its repository type: integer examples: - 42 state: description: State of the issue; either 'open' or 'closed' type: string examples: - open title: description: Title of the issue type: string examples: - Widget creation fails in Safari on OS X 10.8 body: description: Contents of the issue type: - string - 'null' examples: - It looks like the new widget form is broken on Safari. When I try and create the widget, Safari crashes. This is reproducible on 10.8, but not 10.9. Maybe a browser bug? user: anyOf: - type: 'null' - "$ref": "#/components/schemas/simple-user" labels: description: Labels to associate with this issue; pass one or more label names to replace the set of labels on this issue; send an empty array to clear all labels from the issue; note that the labels are silently dropped for users without push access to the repository type: array items: oneOf: - type: string - type: object properties: id: type: integer format: int64 node_id: type: string url: type: string format: uri name: type: string description: type: - string - 'null' color: type: - string - 'null' default: type: boolean examples: - bug - registration assignee: anyOf: - type: 'null' - "$ref": "#/components/schemas/simple-user" assignees: type: - array - 'null' items: "$ref": "#/components/schemas/simple-user" milestone: anyOf: - type: 'null' - "$ref": "#/components/schemas/milestone" locked: type: boolean active_lock_reason: type: - string - 'null' comments: type: integer pull_request: type: object properties: merged_at: type: - string - 'null' format: date-time diff_url: type: - string - 'null' format: uri html_url: type: - string - 'null' format: uri patch_url: type: - string - 'null' format: uri url: type: - string - 'null' format: uri required: - diff_url - html_url - patch_url - url closed_at: type: - string - 'null' format: date-time created_at: type: string format: date-time updated_at: type: string format: date-time draft: type: boolean closed_by: anyOf: - type: 'null' - "$ref": "#/components/schemas/simple-user" body_html: type: string body_text: type: string timeline_url: type: string format: uri repository: "$ref": "#/components/schemas/repository" performed_via_github_app: anyOf: - type: 'null' - "$ref": "#/components/schemas/integration" author_association: "$ref": "#/components/schemas/author_association" reactions: "$ref": "#/components/schemas/reaction-rollup" required: - assignee - closed_at - comments - comments_url - events_url - html_url - id - node_id - labels - labels_url - milestone - number - repository_url - state - locked - title - url - user - author_association - created_at - updated_at issue-comment: title: Issue Comment description: Comments provide a way for people to collaborate on an issue. type: object properties: id: description: Unique identifier of the issue comment type: integer examples: - 42 node_id: type: string url: description: URL for the issue comment type: string format: uri examples: - https://api.github.com/repositories/42/issues/comments/1 body: description: Contents of the issue comment type: string examples: - What version of Safari were you using when you observed this bug? body_text: type: string body_html: type: string html_url: type: string format: uri user: anyOf: - type: 'null' - "$ref": "#/components/schemas/simple-user" created_at: type: string format: date-time examples: - '2011-04-14T16:00:49Z' updated_at: type: string format: date-time examples: - '2011-04-14T16:00:49Z' issue_url: type: string format: uri author_association: "$ref": "#/components/schemas/author_association" performed_via_github_app: anyOf: - type: 'null' - "$ref": "#/components/schemas/integration" reactions: "$ref": "#/components/schemas/reaction-rollup" required: - id - node_id - html_url - issue_url - author_association - user - url - created_at - updated_at event: title: Event description: Event type: object properties: id: type: string type: type: - string - 'null' actor: "$ref": "#/components/schemas/actor" repo: type: object properties: id: type: integer name: type: string url: type: string format: uri required: - id - name - url org: "$ref": "#/components/schemas/actor" payload: type: object properties: action: type: string issue: "$ref": "#/components/schemas/issue" comment: "$ref": "#/components/schemas/issue-comment" pages: type: array items: type: object properties: page_name: type: string title: type: string summary: type: - string - 'null' action: type: string sha: type: string html_url: type: string public: type: boolean created_at: type: - string - 'null' format: date-time required: - id - type - actor - repo - payload - public - created_at link-with-type: title: Link With Type description: Hypermedia Link with Type type: object properties: href: type: string type: type: string required: - href - type feed: title: Feed description: Feed type: object properties: timeline_url: type: string examples: - https://github.com/timeline user_url: type: string examples: - https://github.com/{user} current_user_public_url: type: string examples: - https://github.com/octocat current_user_url: type: string examples: - https://github.com/octocat.private?token=abc123 current_user_actor_url: type: string examples: - https://github.com/octocat.private.actor?token=abc123 current_user_organization_url: type: string examples: - https://github.com/octocat-org current_user_organization_urls: type: array items: type: string format: uri examples: - https://github.com/organizations/github/octocat.private.atom?token=abc123 _links: type: object properties: timeline: "$ref": "#/components/schemas/link-with-type" user: "$ref": "#/components/schemas/link-with-type" security_advisories: "$ref": "#/components/schemas/link-with-type" current_user: "$ref": "#/components/schemas/link-with-type" current_user_public: "$ref": "#/components/schemas/link-with-type" current_user_actor: "$ref": "#/components/schemas/link-with-type" current_user_organization: "$ref": "#/components/schemas/link-with-type" current_user_organizations: type: array items: "$ref": "#/components/schemas/link-with-type" required: - timeline - user required: - _links - timeline_url - user_url base-gist: title: Base Gist description: Base Gist type: object properties: url: type: string format: uri forks_url: type: string format: uri commits_url: type: string format: uri id: type: string node_id: type: string git_pull_url: type: string format: uri git_push_url: type: string format: uri html_url: type: string format: uri files: type: object additionalProperties: type: object properties: filename: type: string type: type: string language: type: string raw_url: type: string size: type: integer public: type: boolean created_at: type: string format: date-time updated_at: type: string format: date-time description: type: - string - 'null' comments: type: integer user: anyOf: - type: 'null' - "$ref": "#/components/schemas/simple-user" comments_url: type: string format: uri owner: "$ref": "#/components/schemas/simple-user" truncated: type: boolean forks: type: array items: {} history: type: array items: {} required: - id - node_id - url - forks_url - commits_url - git_pull_url - git_push_url - html_url - comments_url - public - description - comments - user - files - created_at - updated_at public-user: title: Public User description: Public User type: object properties: login: type: string id: type: integer node_id: type: string avatar_url: type: string format: uri gravatar_id: type: - string - 'null' url: type: string format: uri html_url: type: string format: uri followers_url: type: string format: uri following_url: type: string gists_url: type: string starred_url: type: string subscriptions_url: type: string format: uri organizations_url: type: string format: uri repos_url: type: string format: uri events_url: type: string received_events_url: type: string format: uri type: type: string site_admin: type: boolean name: type: - string - 'null' company: type: - string - 'null' blog: type: - string - 'null' location: type: - string - 'null' email: type: - string - 'null' format: email hireable: type: - boolean - 'null' bio: type: - string - 'null' public_repos: type: integer public_gists: type: integer followers: type: integer following: type: integer created_at: type: string format: date-time updated_at: type: string format: date-time plan: type: object properties: collaborators: type: integer name: type: string space: type: integer private_repos: type: integer required: - collaborators - name - space - private_repos suspended_at: type: - string - 'null' format: date-time private_gists: type: integer examples: - 1 total_private_repos: type: integer examples: - 2 owned_private_repos: type: integer examples: - 2 disk_usage: type: integer examples: - 1 collaborators: type: integer examples: - 3 required: - avatar_url - events_url - followers_url - following_url - gists_url - gravatar_id - html_url - id - node_id - login - organizations_url - received_events_url - repos_url - site_admin - starred_url - subscriptions_url - type - url - bio - blog - company - email - followers - following - hireable - location - name - public_gists - public_repos - created_at - updated_at additionalProperties: false gist-history: title: Gist History description: Gist History type: object properties: user: anyOf: - type: 'null' - "$ref": "#/components/schemas/simple-user" version: type: string committed_at: type: string format: date-time change_status: type: object properties: total: type: integer additions: type: integer deletions: type: integer url: type: string format: uri gist-simple: title: Gist Simple description: Gist Simple type: object properties: forks: deprecated: true type: - array - 'null' items: type: object properties: id: type: string url: type: string format: uri user: "$ref": "#/components/schemas/public-user" created_at: type: string format: date-time updated_at: type: string format: date-time history: deprecated: true type: - array - 'null' items: "$ref": "#/components/schemas/gist-history" fork_of: title: Gist description: Gist type: - object - 'null' properties: url: type: string format: uri forks_url: type: string format: uri commits_url: type: string format: uri id: type: string node_id: type: string git_pull_url: type: string format: uri git_push_url: type: string format: uri html_url: type: string format: uri files: type: object additionalProperties: type: object properties: filename: type: string type: type: string language: type: string raw_url: type: string size: type: integer public: type: boolean created_at: type: string format: date-time updated_at: type: string format: date-time description: type: - string - 'null' comments: type: integer user: anyOf: - type: 'null' - "$ref": "#/components/schemas/simple-user" comments_url: type: string format: uri owner: anyOf: - type: 'null' - "$ref": "#/components/schemas/simple-user" truncated: type: boolean forks: type: array items: {} history: type: array items: {} required: - id - node_id - url - forks_url - commits_url - git_pull_url - git_push_url - html_url - comments_url - public - description - comments - user - files - created_at - updated_at url: type: string forks_url: type: string commits_url: type: string id: type: string node_id: type: string git_pull_url: type: string git_push_url: type: string html_url: type: string files: type: object additionalProperties: type: - object - 'null' properties: filename: type: string type: type: string language: type: string raw_url: type: string size: type: integer truncated: type: boolean content: type: string public: type: boolean created_at: type: string updated_at: type: string description: type: - string - 'null' comments: type: integer user: type: - string - 'null' comments_url: type: string owner: "$ref": "#/components/schemas/simple-user" truncated: type: boolean gist-comment: title: Gist Comment description: A comment made to a gist. type: object properties: id: type: integer examples: - 1 node_id: type: string examples: - MDExOkdpc3RDb21tZW50MQ== url: type: string format: uri examples: - https://api.github.com/gists/a6db0bec360bb87e9418/comments/1 body: description: The comment text. type: string maxLength: 65535 examples: - Body of the attachment user: anyOf: - type: 'null' - "$ref": "#/components/schemas/simple-user" created_at: type: string format: date-time examples: - '2011-04-18T23:23:56Z' updated_at: type: string format: date-time examples: - '2011-04-18T23:23:56Z' author_association: "$ref": "#/components/schemas/author_association" required: - url - id - node_id - user - body - author_association - created_at - updated_at gist-commit: title: Gist Commit description: Gist Commit type: object properties: url: type: string format: uri examples: - https://api.github.com/gists/aa5a315d61ae9438b18d/57a7f021a713b1c5a6a199b54cc514735d2d462f version: type: string examples: - 57a7f021a713b1c5a6a199b54cc514735d2d462f user: anyOf: - type: 'null' - "$ref": "#/components/schemas/simple-user" change_status: type: object properties: total: type: integer additions: type: integer deletions: type: integer committed_at: type: string format: date-time examples: - '2010-04-14T02:15:15Z' required: - url - user - version - committed_at - change_status gitignore-template: title: Gitignore Template description: Gitignore Template type: object properties: name: type: string examples: - C source: type: string examples: - | # Object files *.o # Libraries *.lib *.a # Shared objects (inc. Windows DLLs) *.dll *.so *.so.* *.dylib # Executables *.exe *.out *.app required: - name - source license: title: License description: License type: object properties: key: type: string examples: - mit name: type: string examples: - MIT License spdx_id: type: - string - 'null' examples: - MIT url: type: - string - 'null' format: uri examples: - https://api.github.com/licenses/mit node_id: type: string examples: - MDc6TGljZW5zZW1pdA== html_url: type: string format: uri examples: - http://choosealicense.com/licenses/mit/ description: type: string examples: - A permissive license that is short and to the point. It lets people do anything with your code with proper attribution and without warranty. implementation: type: string examples: - Create a text file (typically named LICENSE or LICENSE.txt) in the root of your source code and copy the text of the license into the file. Replace [year] with the current year and [fullname] with the name (or names) of the copyright holders. permissions: type: array items: type: string examples: - commercial-use - modifications - distribution - sublicense - private-use conditions: type: array items: type: string examples: - include-copyright limitations: type: array items: type: string examples: - no-liability body: type: string examples: - |2 The MIT License (MIT) Copyright (c) [year] [fullname] Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. featured: type: boolean examples: - true required: - key - name - url - spdx_id - node_id - html_url - description - implementation - permissions - conditions - limitations - body - featured api-overview: title: Api Overview description: Api Overview type: object properties: verifiable_password_authentication: type: boolean examples: - true packages: type: array items: type: string examples: - 13.65.0.0/16 - 157.55.204.33/32 - 2a01:111:f403:f90c::/62 dependabot: type: array items: type: string examples: - 192.168.7.15/32 - 192.168.7.16/32 installed_version: type: string examples: - 3.0.0 required: - verifiable_password_authentication minimal-repository: title: Minimal Repository description: Minimal Repository type: object properties: id: type: integer examples: - 1296269 node_id: type: string examples: - MDEwOlJlcG9zaXRvcnkxMjk2MjY5 name: type: string examples: - Hello-World full_name: type: string examples: - octocat/Hello-World owner: "$ref": "#/components/schemas/simple-user" private: type: boolean html_url: type: string format: uri examples: - https://github.com/octocat/Hello-World description: type: - string - 'null' examples: - This your first repo! fork: type: boolean url: type: string format: uri examples: - https://api.github.com/repos/octocat/Hello-World archive_url: type: string examples: - http://api.github.com/repos/octocat/Hello-World/{archive_format}{/ref} assignees_url: type: string examples: - http://api.github.com/repos/octocat/Hello-World/assignees{/user} blobs_url: type: string examples: - http://api.github.com/repos/octocat/Hello-World/git/blobs{/sha} branches_url: type: string examples: - http://api.github.com/repos/octocat/Hello-World/branches{/branch} collaborators_url: type: string examples: - http://api.github.com/repos/octocat/Hello-World/collaborators{/collaborator} comments_url: type: string examples: - http://api.github.com/repos/octocat/Hello-World/comments{/number} commits_url: type: string examples: - http://api.github.com/repos/octocat/Hello-World/commits{/sha} compare_url: type: string examples: - http://api.github.com/repos/octocat/Hello-World/compare/{base}...{head} contents_url: type: string examples: - http://api.github.com/repos/octocat/Hello-World/contents/{+path} contributors_url: type: string format: uri examples: - http://api.github.com/repos/octocat/Hello-World/contributors deployments_url: type: string format: uri examples: - http://api.github.com/repos/octocat/Hello-World/deployments downloads_url: type: string format: uri examples: - http://api.github.com/repos/octocat/Hello-World/downloads events_url: type: string format: uri examples: - http://api.github.com/repos/octocat/Hello-World/events forks_url: type: string format: uri examples: - http://api.github.com/repos/octocat/Hello-World/forks git_commits_url: type: string examples: - http://api.github.com/repos/octocat/Hello-World/git/commits{/sha} git_refs_url: type: string examples: - http://api.github.com/repos/octocat/Hello-World/git/refs{/sha} git_tags_url: type: string examples: - http://api.github.com/repos/octocat/Hello-World/git/tags{/sha} git_url: type: string issue_comment_url: type: string examples: - http://api.github.com/repos/octocat/Hello-World/issues/comments{/number} issue_events_url: type: string examples: - http://api.github.com/repos/octocat/Hello-World/issues/events{/number} issues_url: type: string examples: - http://api.github.com/repos/octocat/Hello-World/issues{/number} keys_url: type: string examples: - http://api.github.com/repos/octocat/Hello-World/keys{/key_id} labels_url: type: string examples: - http://api.github.com/repos/octocat/Hello-World/labels{/name} languages_url: type: string format: uri examples: - http://api.github.com/repos/octocat/Hello-World/languages merges_url: type: string format: uri examples: - http://api.github.com/repos/octocat/Hello-World/merges milestones_url: type: string examples: - http://api.github.com/repos/octocat/Hello-World/milestones{/number} notifications_url: type: string examples: - http://api.github.com/repos/octocat/Hello-World/notifications{?since,all,participating} pulls_url: type: string examples: - http://api.github.com/repos/octocat/Hello-World/pulls{/number} releases_url: type: string examples: - http://api.github.com/repos/octocat/Hello-World/releases{/id} ssh_url: type: string stargazers_url: type: string format: uri examples: - http://api.github.com/repos/octocat/Hello-World/stargazers statuses_url: type: string examples: - http://api.github.com/repos/octocat/Hello-World/statuses/{sha} subscribers_url: type: string format: uri examples: - http://api.github.com/repos/octocat/Hello-World/subscribers subscription_url: type: string format: uri examples: - http://api.github.com/repos/octocat/Hello-World/subscription tags_url: type: string format: uri examples: - http://api.github.com/repos/octocat/Hello-World/tags teams_url: type: string format: uri examples: - http://api.github.com/repos/octocat/Hello-World/teams trees_url: type: string examples: - http://api.github.com/repos/octocat/Hello-World/git/trees{/sha} clone_url: type: string mirror_url: type: - string - 'null' hooks_url: type: string format: uri examples: - http://api.github.com/repos/octocat/Hello-World/hooks svn_url: type: string homepage: type: - string - 'null' language: type: - string - 'null' forks_count: type: integer stargazers_count: type: integer watchers_count: type: integer size: type: integer default_branch: type: string open_issues_count: type: integer is_template: type: boolean topics: type: array items: type: string has_issues: type: boolean has_projects: type: boolean has_wiki: type: boolean has_pages: type: boolean has_downloads: type: boolean archived: type: boolean disabled: type: boolean visibility: type: string pushed_at: type: - string - 'null' format: date-time examples: - '2011-01-26T19:06:43Z' created_at: type: - string - 'null' format: date-time examples: - '2011-01-26T19:01:12Z' updated_at: type: - string - 'null' format: date-time examples: - '2011-01-26T19:14:43Z' permissions: type: object properties: admin: type: boolean maintain: type: boolean push: type: boolean triage: type: boolean pull: type: boolean template_repository: anyOf: - type: 'null' - "$ref": "#/components/schemas/repository" temp_clone_token: type: string delete_branch_on_merge: type: boolean subscribers_count: type: integer network_count: type: integer code_of_conduct: "$ref": "#/components/schemas/code-of-conduct" license: type: - object - 'null' properties: key: type: string name: type: string spdx_id: type: string url: type: string node_id: type: string forks: type: integer examples: - 0 open_issues: type: integer examples: - 0 watchers: type: integer examples: - 0 allow_forking: type: boolean required: - archive_url - assignees_url - blobs_url - branches_url - collaborators_url - comments_url - commits_url - compare_url - contents_url - contributors_url - deployments_url - description - downloads_url - events_url - fork - forks_url - full_name - git_commits_url - git_refs_url - git_tags_url - hooks_url - html_url - id - node_id - issue_comment_url - issue_events_url - issues_url - keys_url - labels_url - languages_url - merges_url - milestones_url - name - notifications_url - owner - private - pulls_url - releases_url - stargazers_url - statuses_url - subscribers_url - subscription_url - tags_url - teams_url - trees_url - url thread: title: Thread description: Thread type: object properties: id: type: string repository: "$ref": "#/components/schemas/minimal-repository" subject: type: object properties: title: type: string url: type: string latest_comment_url: type: string type: type: string required: - title - url - latest_comment_url - type reason: type: string unread: type: boolean updated_at: type: string last_read_at: type: - string - 'null' url: type: string subscription_url: type: string examples: - https://api.github.com/notifications/threads/2/subscription required: - id - unread - reason - updated_at - last_read_at - subject - repository - url - subscription_url thread-subscription: title: Thread Subscription description: Thread Subscription type: object properties: subscribed: type: boolean examples: - true ignored: type: boolean reason: type: - string - 'null' created_at: type: - string - 'null' format: date-time examples: - '2012-10-06T21:34:12Z' url: type: string format: uri examples: - https://api.github.com/notifications/threads/1/subscription thread_url: type: string format: uri examples: - https://api.github.com/notifications/threads/1 repository_url: type: string format: uri examples: - https://api.github.com/repos/1 required: - created_at - ignored - reason - url - subscribed organization-full: title: Organization Full description: Organization Full type: object properties: login: type: string examples: - github id: type: integer examples: - 1 node_id: type: string examples: - MDEyOk9yZ2FuaXphdGlvbjE= url: type: string format: uri examples: - https://api.github.com/orgs/github repos_url: type: string format: uri examples: - https://api.github.com/orgs/github/repos events_url: type: string format: uri examples: - https://api.github.com/orgs/github/events hooks_url: type: string examples: - https://api.github.com/orgs/github/hooks issues_url: type: string examples: - https://api.github.com/orgs/github/issues members_url: type: string examples: - https://api.github.com/orgs/github/members{/member} public_members_url: type: string examples: - https://api.github.com/orgs/github/public_members{/member} avatar_url: type: string examples: - https://github.com/images/error/octocat_happy.gif description: type: - string - 'null' examples: - A great organization name: type: string examples: - github company: type: string examples: - GitHub blog: type: string format: uri examples: - https://github.com/blog location: type: string examples: - San Francisco email: type: string format: email examples: - octocat@github.com twitter_username: type: - string - 'null' examples: - github is_verified: type: boolean examples: - true has_organization_projects: type: boolean examples: - true has_repository_projects: type: boolean examples: - true public_repos: type: integer examples: - 2 public_gists: type: integer examples: - 1 followers: type: integer examples: - 20 following: type: integer examples: - 0 html_url: type: string format: uri examples: - https://github.com/octocat created_at: type: string format: date-time examples: - '2008-01-14T04:33:35Z' type: type: string examples: - Organization total_private_repos: type: integer examples: - 100 owned_private_repos: type: integer examples: - 100 private_gists: type: - integer - 'null' examples: - 81 disk_usage: type: - integer - 'null' examples: - 10000 collaborators: type: - integer - 'null' examples: - 8 billing_email: type: - string - 'null' format: email examples: - org@example.com plan: type: object properties: name: type: string space: type: integer private_repos: type: integer filled_seats: type: integer seats: type: integer required: - name - space - private_repos default_repository_permission: type: - string - 'null' members_can_create_repositories: type: - boolean - 'null' examples: - true two_factor_requirement_enabled: type: - boolean - 'null' examples: - true members_allowed_repository_creation_type: type: string examples: - all members_can_create_public_repositories: type: boolean examples: - true members_can_create_private_repositories: type: boolean examples: - true members_can_create_internal_repositories: type: boolean examples: - true members_can_create_pages: type: boolean examples: - true members_can_create_public_pages: type: boolean examples: - true members_can_create_private_pages: type: boolean examples: - true members_can_fork_private_repositories: type: - boolean - 'null' examples: - false updated_at: type: string format: date-time required: - login - url - id - node_id - repos_url - events_url - hooks_url - issues_url - members_url - public_members_url - avatar_url - description - html_url - has_organization_projects - has_repository_projects - public_repos - public_gists - followers - following - type - created_at - updated_at enabled-repositories: type: string description: 'The policy that controls the repositories in the organization that are allowed to run GitHub Actions. Can be one of: `all`, `none`, or `selected`.' enum: - all - none - selected actions-organization-permissions: type: object properties: enabled_repositories: "$ref": "#/components/schemas/enabled-repositories" selected_repositories_url: type: string description: The API URL to use to get or set the selected repositories that are allowed to run GitHub Actions, when `enabled_repositories` is set to `selected`. allowed_actions: "$ref": "#/components/schemas/allowed-actions" selected_actions_url: "$ref": "#/components/schemas/selected-actions-url" required: - enabled_repositories runner-groups-org: type: object properties: id: type: number name: type: string visibility: type: string default: type: boolean selected_repositories_url: description: Link to the selected repositories resource for this runner group. Not present unless visibility was set to `selected` type: string runners_url: type: string inherited: type: boolean inherited_allows_public_repositories: type: boolean allows_public_repositories: type: boolean required: - id - name - visibility - default - runners_url - inherited - allows_public_repositories organization-actions-secret: title: Actions Secret for an Organization description: Secrets for GitHub Actions for an organization. type: object properties: name: description: The name of the secret. type: string examples: - SECRET_TOKEN created_at: type: string format: date-time updated_at: type: string format: date-time visibility: description: Visibility of a secret enum: - all - private - selected type: string selected_repositories_url: type: string format: uri examples: - https://api.github.com/organizations/org/secrets/my_secret/repositories required: - name - created_at - updated_at - visibility actions-public-key: title: ActionsPublicKey description: The public key used for setting Actions Secrets. type: object properties: key_id: description: The identifier for the key. type: string examples: - '1234567' key: description: The Base64 encoded public key. type: string examples: - hBT5WZEj8ZoOv6TYJsfWq7MxTEQopZO5/IT3ZCVQPzs= id: type: integer examples: - 2 url: type: string examples: - https://api.github.com/user/keys/2 title: type: string examples: - ssh-rsa AAAAB3NzaC1yc2EAAA created_at: type: string examples: - '2011-01-26T19:01:12Z' required: - key_id - key empty-object: title: Empty Object description: An object without any properties. type: object properties: {} additionalProperties: false org-hook: title: Org Hook description: Org Hook type: object properties: id: type: integer examples: - 1 url: type: string format: uri examples: - https://api.github.com/orgs/octocat/hooks/1 ping_url: type: string format: uri examples: - https://api.github.com/orgs/octocat/hooks/1/pings name: type: string examples: - web events: type: array items: type: string examples: - push - pull_request active: type: boolean examples: - true config: type: object properties: url: type: string examples: - '"http://example.com/2"' insecure_ssl: type: string examples: - '"0"' content_type: type: string examples: - '"form"' secret: type: string examples: - '"********"' updated_at: type: string format: date-time examples: - '2011-09-06T20:39:23Z' created_at: type: string format: date-time examples: - '2011-09-06T17:26:27Z' type: type: string required: - id - url - type - name - active - events - config - ping_url - created_at - updated_at org-membership: title: Org Membership description: Org Membership type: object properties: url: type: string format: uri examples: - https://api.github.com/orgs/octocat/memberships/defunkt state: type: string description: The state of the member in the organization. The `pending` state indicates the user has not yet accepted an invitation. enum: - active - pending examples: - active role: type: string description: The user's membership type in the organization. enum: - admin - member - billing_manager examples: - admin organization_url: type: string format: uri examples: - https://api.github.com/orgs/octocat organization: "$ref": "#/components/schemas/organization-simple" user: anyOf: - type: 'null' - "$ref": "#/components/schemas/simple-user" permissions: type: object properties: can_create_repository: type: boolean required: - can_create_repository required: - state - role - organization_url - url - organization - user org-pre-receive-hook: type: object properties: id: type: integer name: type: string enforcement: type: string configuration_url: type: string allow_downstream_configuration: type: boolean project: title: Project description: Projects are a way to organize columns and cards of work. type: object properties: owner_url: type: string format: uri examples: - https://api.github.com/repos/api-playground/projects-test url: type: string format: uri examples: - https://api.github.com/projects/1002604 html_url: type: string format: uri examples: - https://github.com/api-playground/projects-test/projects/12 columns_url: type: string format: uri examples: - https://api.github.com/projects/1002604/columns id: type: integer examples: - 1002604 node_id: type: string examples: - MDc6UHJvamVjdDEwMDI2MDQ= name: description: Name of the project type: string examples: - Week One Sprint body: description: Body of the project type: - string - 'null' examples: - This project represents the sprint of the first week in January number: type: integer examples: - 1 state: description: State of the project; either 'open' or 'closed' type: string examples: - open creator: anyOf: - type: 'null' - "$ref": "#/components/schemas/simple-user" created_at: type: string format: date-time examples: - '2011-04-10T20:09:31Z' updated_at: type: string format: date-time examples: - '2014-03-03T18:58:10Z' organization_permission: description: The baseline permission that all organization members have on this project. Only present if owner is an organization. type: string enum: - read - write - admin - none private: description: Whether or not this project can be seen by everyone. Only present if owner is an organization. type: boolean required: - id - node_id - number - name - body - state - url - html_url - owner_url - creator - columns_url - created_at - updated_at team-simple: title: Team Simple description: Groups of organization members that gives permissions on specified repositories. type: object properties: id: description: Unique identifier of the team type: integer examples: - 1 node_id: type: string examples: - MDQ6VGVhbTE= url: description: URL for the team type: string format: uri examples: - https://api.github.com/organizations/1/team/1 members_url: type: string examples: - https://api.github.com/organizations/1/team/1/members{/member} name: description: Name of the team type: string examples: - Justice League description: description: Description of the team type: - string - 'null' examples: - A great team. permission: description: Permission that the team will have for its repositories type: string examples: - admin privacy: description: The level of privacy this team should have type: string examples: - closed html_url: type: string format: uri examples: - https://github.com/orgs/rails/teams/core repositories_url: type: string format: uri examples: - https://api.github.com/organizations/1/team/1/repos slug: type: string examples: - justice-league ldap_dn: description: Distinguished Name (DN) that team maps to within LDAP environment type: string examples: - uid=example,ou=users,dc=github,dc=com required: - id - node_id - url - members_url - name - description - permission - html_url - repositories_url - slug team: title: Team description: Groups of organization members that gives permissions on specified repositories. type: object properties: id: type: integer node_id: type: string name: type: string slug: type: string description: type: - string - 'null' privacy: type: string permission: type: string permissions: type: object properties: pull: type: boolean triage: type: boolean push: type: boolean maintain: type: boolean admin: type: boolean required: - pull - triage - push - maintain - admin url: type: string format: uri html_url: type: string format: uri examples: - https://github.com/orgs/rails/teams/core members_url: type: string repositories_url: type: string format: uri parent: anyOf: - type: 'null' - "$ref": "#/components/schemas/team-simple" required: - id - node_id - url - members_url - name - description - permission - html_url - repositories_url - slug - parent team-full: title: Full Team description: Groups of organization members that gives permissions on specified repositories. type: object properties: id: description: Unique identifier of the team type: integer examples: - 42 node_id: type: string examples: - MDQ6VGVhbTE= url: description: URL for the team type: string format: uri examples: - https://api.github.com/organizations/1/team/1 html_url: type: string format: uri examples: - https://github.com/orgs/rails/teams/core name: description: Name of the team type: string examples: - Developers slug: type: string examples: - justice-league description: type: - string - 'null' examples: - A great team. privacy: description: The level of privacy this team should have type: string enum: - closed - secret examples: - closed permission: description: Permission that the team will have for its repositories type: string examples: - push members_url: type: string examples: - https://api.github.com/organizations/1/team/1/members{/member} repositories_url: type: string format: uri examples: - https://api.github.com/organizations/1/team/1/repos parent: anyOf: - type: 'null' - "$ref": "#/components/schemas/team-simple" members_count: type: integer examples: - 3 repos_count: type: integer examples: - 10 created_at: type: string format: date-time examples: - '2017-07-14T16:53:42Z' updated_at: type: string format: date-time examples: - '2017-08-17T12:37:15Z' organization: "$ref": "#/components/schemas/organization-full" ldap_dn: description: Distinguished Name (DN) that team maps to within LDAP environment type: string examples: - uid=example,ou=users,dc=github,dc=com required: - id - node_id - url - members_url - name - description - permission - html_url - repositories_url - slug - created_at - updated_at - members_count - repos_count - organization team-discussion: title: Team Discussion description: A team discussion is a persistent record of a free-form conversation within a team. type: object properties: author: anyOf: - type: 'null' - "$ref": "#/components/schemas/simple-user" body: description: The main text of the discussion. type: string examples: - Please suggest improvements to our workflow in comments. body_html: type: string examples: - "

      Hi! This is an area for us to collaborate as a team

      " body_version: description: The current version of the body content. If provided, this update operation will be rejected if the given version does not match the latest version on the server. type: string examples: - 0307116bbf7ced493b8d8a346c650b71 comments_count: type: integer examples: - 0 comments_url: type: string format: uri examples: - https://api.github.com/organizations/1/team/2343027/discussions/1/comments created_at: type: string format: date-time examples: - '2018-01-25T18:56:31Z' last_edited_at: type: - string - 'null' format: date-time html_url: type: string format: uri examples: - https://github.com/orgs/github/teams/justice-league/discussions/1 node_id: type: string examples: - MDE0OlRlYW1EaXNjdXNzaW9uMQ== number: description: The unique sequence number of a team discussion. type: integer examples: - 42 pinned: description: Whether or not this discussion should be pinned for easy retrieval. type: boolean examples: - true private: description: Whether or not this discussion should be restricted to team members and organization administrators. type: boolean examples: - true team_url: type: string format: uri examples: - https://api.github.com/organizations/1/team/2343027 title: description: The title of the discussion. type: string examples: - How can we improve our workflow? updated_at: type: string format: date-time examples: - '2018-01-25T18:56:31Z' url: type: string format: uri examples: - https://api.github.com/organizations/1/team/2343027/discussions/1 reactions: "$ref": "#/components/schemas/reaction-rollup" required: - author - body - body_html - body_version - comments_count - comments_url - created_at - last_edited_at - html_url - pinned - private - node_id - number - team_url - title - updated_at - url team-discussion-comment: title: Team Discussion Comment description: A reply to a discussion within a team. type: object properties: author: anyOf: - type: 'null' - "$ref": "#/components/schemas/simple-user" body: description: The main text of the comment. type: string examples: - I agree with this suggestion. body_html: type: string examples: - "

      Do you like apples?

      " body_version: description: The current version of the body content. If provided, this update operation will be rejected if the given version does not match the latest version on the server. type: string examples: - 0307116bbf7ced493b8d8a346c650b71 created_at: type: string format: date-time examples: - '2018-01-15T23:53:58Z' last_edited_at: type: - string - 'null' format: date-time discussion_url: type: string format: uri examples: - https://api.github.com/organizations/1/team/2403582/discussions/1 html_url: type: string format: uri examples: - https://github.com/orgs/github/teams/justice-league/discussions/1/comments/1 node_id: type: string examples: - MDIxOlRlYW1EaXNjdXNzaW9uQ29tbWVudDE= number: description: The unique sequence number of a team discussion comment. type: integer examples: - 42 updated_at: type: string format: date-time examples: - '2018-01-15T23:53:58Z' url: type: string format: uri examples: - https://api.github.com/organizations/1/team/2403582/discussions/1/comments/1 reactions: "$ref": "#/components/schemas/reaction-rollup" required: - author - body - body_html - body_version - created_at - last_edited_at - discussion_url - html_url - node_id - number - updated_at - url reaction: title: Reaction description: Reactions to conversations provide a way to help people express their feelings more simply and effectively. type: object properties: id: type: integer examples: - 1 node_id: type: string examples: - MDg6UmVhY3Rpb24x user: anyOf: - type: 'null' - "$ref": "#/components/schemas/simple-user" content: description: The reaction to use type: string enum: - "+1" - "-1" - laugh - confused - heart - hooray - rocket - eyes examples: - heart created_at: type: string format: date-time examples: - '2016-05-20T20:09:31Z' required: - id - node_id - user - content - created_at team-membership: title: Team Membership description: Team Membership type: object properties: url: type: string format: uri role: description: The role of the user in the team. enum: - member - maintainer default: member type: string examples: - member state: description: The state of the user's membership in the team. type: string enum: - active - pending required: - role - state - url team-project: title: Team Project description: A team's access to a project. type: object properties: owner_url: type: string url: type: string html_url: type: string columns_url: type: string id: type: integer node_id: type: string name: type: string body: type: - string - 'null' number: type: integer state: type: string creator: "$ref": "#/components/schemas/simple-user" created_at: type: string updated_at: type: string organization_permission: description: The organization permission for this project. Only present when owner is an organization. type: string private: description: Whether the project is private or not. Only present when owner is an organization. type: boolean permissions: type: object properties: read: type: boolean write: type: boolean admin: type: boolean required: - read - write - admin required: - owner_url - url - html_url - columns_url - id - node_id - name - body - number - state - creator - created_at - updated_at - permissions team-repository: title: Team Repository description: A team's access to a repository. type: object properties: id: description: Unique identifier of the repository type: integer examples: - 42 node_id: type: string examples: - MDEwOlJlcG9zaXRvcnkxMjk2MjY5 name: description: The name of the repository. type: string examples: - Team Environment full_name: type: string examples: - octocat/Hello-World license: anyOf: - type: 'null' - "$ref": "#/components/schemas/license-simple" forks: type: integer permissions: type: object properties: admin: type: boolean pull: type: boolean triage: type: boolean push: type: boolean maintain: type: boolean required: - admin - pull - push owner: anyOf: - type: 'null' - "$ref": "#/components/schemas/simple-user" private: description: Whether the repository is private or public. default: false type: boolean html_url: type: string format: uri examples: - https://github.com/octocat/Hello-World description: type: - string - 'null' examples: - This your first repo! fork: type: boolean url: type: string format: uri examples: - https://api.github.com/repos/octocat/Hello-World archive_url: type: string examples: - http://api.github.com/repos/octocat/Hello-World/{archive_format}{/ref} assignees_url: type: string examples: - http://api.github.com/repos/octocat/Hello-World/assignees{/user} blobs_url: type: string examples: - http://api.github.com/repos/octocat/Hello-World/git/blobs{/sha} branches_url: type: string examples: - http://api.github.com/repos/octocat/Hello-World/branches{/branch} collaborators_url: type: string examples: - http://api.github.com/repos/octocat/Hello-World/collaborators{/collaborator} comments_url: type: string examples: - http://api.github.com/repos/octocat/Hello-World/comments{/number} commits_url: type: string examples: - http://api.github.com/repos/octocat/Hello-World/commits{/sha} compare_url: type: string examples: - http://api.github.com/repos/octocat/Hello-World/compare/{base}...{head} contents_url: type: string examples: - http://api.github.com/repos/octocat/Hello-World/contents/{+path} contributors_url: type: string format: uri examples: - http://api.github.com/repos/octocat/Hello-World/contributors deployments_url: type: string format: uri examples: - http://api.github.com/repos/octocat/Hello-World/deployments downloads_url: type: string format: uri examples: - http://api.github.com/repos/octocat/Hello-World/downloads events_url: type: string format: uri examples: - http://api.github.com/repos/octocat/Hello-World/events forks_url: type: string format: uri examples: - http://api.github.com/repos/octocat/Hello-World/forks git_commits_url: type: string examples: - http://api.github.com/repos/octocat/Hello-World/git/commits{/sha} git_refs_url: type: string examples: - http://api.github.com/repos/octocat/Hello-World/git/refs{/sha} git_tags_url: type: string examples: - http://api.github.com/repos/octocat/Hello-World/git/tags{/sha} git_url: type: string examples: - git:github.com/octocat/Hello-World.git issue_comment_url: type: string examples: - http://api.github.com/repos/octocat/Hello-World/issues/comments{/number} issue_events_url: type: string examples: - http://api.github.com/repos/octocat/Hello-World/issues/events{/number} issues_url: type: string examples: - http://api.github.com/repos/octocat/Hello-World/issues{/number} keys_url: type: string examples: - http://api.github.com/repos/octocat/Hello-World/keys{/key_id} labels_url: type: string examples: - http://api.github.com/repos/octocat/Hello-World/labels{/name} languages_url: type: string format: uri examples: - http://api.github.com/repos/octocat/Hello-World/languages merges_url: type: string format: uri examples: - http://api.github.com/repos/octocat/Hello-World/merges milestones_url: type: string examples: - http://api.github.com/repos/octocat/Hello-World/milestones{/number} notifications_url: type: string examples: - http://api.github.com/repos/octocat/Hello-World/notifications{?since,all,participating} pulls_url: type: string examples: - http://api.github.com/repos/octocat/Hello-World/pulls{/number} releases_url: type: string examples: - http://api.github.com/repos/octocat/Hello-World/releases{/id} ssh_url: type: string examples: - git@github.com:octocat/Hello-World.git stargazers_url: type: string format: uri examples: - http://api.github.com/repos/octocat/Hello-World/stargazers statuses_url: type: string examples: - http://api.github.com/repos/octocat/Hello-World/statuses/{sha} subscribers_url: type: string format: uri examples: - http://api.github.com/repos/octocat/Hello-World/subscribers subscription_url: type: string format: uri examples: - http://api.github.com/repos/octocat/Hello-World/subscription tags_url: type: string format: uri examples: - http://api.github.com/repos/octocat/Hello-World/tags teams_url: type: string format: uri examples: - http://api.github.com/repos/octocat/Hello-World/teams trees_url: type: string examples: - http://api.github.com/repos/octocat/Hello-World/git/trees{/sha} clone_url: type: string examples: - https://github.com/octocat/Hello-World.git mirror_url: type: - string - 'null' format: uri examples: - git:git.example.com/octocat/Hello-World hooks_url: type: string format: uri examples: - http://api.github.com/repos/octocat/Hello-World/hooks svn_url: type: string format: uri examples: - https://svn.github.com/octocat/Hello-World homepage: type: - string - 'null' format: uri examples: - https://github.com language: type: - string - 'null' forks_count: type: integer examples: - 9 stargazers_count: type: integer examples: - 80 watchers_count: type: integer examples: - 80 size: type: integer examples: - 108 default_branch: description: The default branch of the repository. type: string examples: - master open_issues_count: type: integer examples: - 0 is_template: description: Whether this repository acts as a template that can be used to generate new repositories. default: false type: boolean examples: - true topics: type: array items: type: string has_issues: description: Whether issues are enabled. default: true type: boolean examples: - true has_projects: description: Whether projects are enabled. default: true type: boolean examples: - true has_wiki: description: Whether the wiki is enabled. default: true type: boolean examples: - true has_pages: type: boolean has_downloads: description: Whether downloads are enabled. default: true type: boolean examples: - true archived: description: Whether the repository is archived. default: false type: boolean disabled: type: boolean description: Returns whether or not this repository disabled. visibility: description: 'The repository visibility: public, private, or internal.' default: public type: string pushed_at: type: - string - 'null' format: date-time examples: - '2011-01-26T19:06:43Z' created_at: type: - string - 'null' format: date-time examples: - '2011-01-26T19:01:12Z' updated_at: type: - string - 'null' format: date-time examples: - '2011-01-26T19:14:43Z' allow_rebase_merge: description: Whether to allow rebase merges for pull requests. default: true type: boolean examples: - true template_repository: anyOf: - type: 'null' - "$ref": "#/components/schemas/repository" temp_clone_token: type: string allow_squash_merge: description: Whether to allow squash merges for pull requests. default: true type: boolean examples: - true delete_branch_on_merge: description: Whether to delete head branches when pull requests are merged default: false type: boolean examples: - false allow_merge_commit: description: Whether to allow merge commits for pull requests. default: true type: boolean examples: - true allow_forking: description: Whether to allow forking this repo default: false type: boolean examples: - false subscribers_count: type: integer network_count: type: integer open_issues: type: integer watchers: type: integer master_branch: type: string required: - archive_url - assignees_url - blobs_url - branches_url - collaborators_url - comments_url - commits_url - compare_url - contents_url - contributors_url - deployments_url - description - downloads_url - events_url - fork - forks_url - full_name - git_commits_url - git_refs_url - git_tags_url - hooks_url - html_url - id - node_id - issue_comment_url - issue_events_url - issues_url - keys_url - labels_url - languages_url - merges_url - milestones_url - name - notifications_url - owner - private - pulls_url - releases_url - stargazers_url - statuses_url - subscribers_url - subscription_url - tags_url - teams_url - trees_url - url - clone_url - default_branch - forks - forks_count - git_url - has_downloads - has_issues - has_projects - has_wiki - has_pages - homepage - language - archived - disabled - mirror_url - open_issues - open_issues_count - license - pushed_at - size - ssh_url - stargazers_count - svn_url - watchers - watchers_count - created_at - updated_at project-card: title: Project Card description: Project cards represent a scope of work. type: object properties: url: type: string format: uri examples: - https://api.github.com/projects/columns/cards/1478 id: description: The project card's ID type: integer examples: - 42 node_id: type: string examples: - MDExOlByb2plY3RDYXJkMTQ3OA== note: type: - string - 'null' examples: - Add payload for delete Project column creator: anyOf: - type: 'null' - "$ref": "#/components/schemas/simple-user" created_at: type: string format: date-time examples: - '2016-09-05T14:21:06Z' updated_at: type: string format: date-time examples: - '2016-09-05T14:20:22Z' archived: description: Whether or not the card is archived type: boolean examples: - false column_name: type: string project_id: type: string column_url: type: string format: uri examples: - https://api.github.com/projects/columns/367 content_url: type: string format: uri examples: - https://api.github.com/repos/api-playground/projects-test/issues/3 project_url: type: string format: uri examples: - https://api.github.com/projects/120 required: - id - node_id - note - url - column_url - project_url - creator - created_at - updated_at project-column: title: Project Column description: Project columns contain cards of work. type: object properties: url: type: string format: uri examples: - https://api.github.com/projects/columns/367 project_url: type: string format: uri examples: - https://api.github.com/projects/120 cards_url: type: string format: uri examples: - https://api.github.com/projects/columns/367/cards id: description: The unique identifier of the project column type: integer examples: - 42 node_id: type: string examples: - MDEzOlByb2plY3RDb2x1bW4zNjc= name: description: Name of the project column type: string examples: - Remaining tasks created_at: type: string format: date-time examples: - '2016-09-05T14:18:44Z' updated_at: type: string format: date-time examples: - '2016-09-05T14:22:28Z' required: - id - node_id - url - project_url - cards_url - name - created_at - updated_at project-collaborator-permission: title: Project Collaborator Permission description: Project Collaborator Permission type: object properties: permission: type: string user: anyOf: - type: 'null' - "$ref": "#/components/schemas/simple-user" required: - permission - user rate-limit: title: Rate Limit type: object properties: limit: type: integer remaining: type: integer reset: type: integer used: type: integer required: - limit - remaining - reset - used rate-limit-overview: title: Rate Limit Overview description: Rate Limit Overview type: object properties: resources: type: object properties: core: "$ref": "#/components/schemas/rate-limit" graphql: "$ref": "#/components/schemas/rate-limit" search: "$ref": "#/components/schemas/rate-limit" source_import: "$ref": "#/components/schemas/rate-limit" integration_manifest: "$ref": "#/components/schemas/rate-limit" code_scanning_upload: "$ref": "#/components/schemas/rate-limit" actions_runner_registration: "$ref": "#/components/schemas/rate-limit" scim: "$ref": "#/components/schemas/rate-limit" required: - core - search rate: "$ref": "#/components/schemas/rate-limit" required: - rate - resources code-of-conduct-simple: title: Code Of Conduct Simple description: Code of Conduct Simple type: object properties: url: type: string format: uri examples: - https://api.github.com/repos/github/docs/community/code_of_conduct key: type: string examples: - citizen_code_of_conduct name: type: string examples: - Citizen Code of Conduct html_url: type: - string - 'null' format: uri examples: - https://github.com/github/docs/blob/main/CODE_OF_CONDUCT.md required: - url - key - name - html_url full-repository: title: Full Repository description: Full Repository type: object properties: id: type: integer examples: - 1296269 node_id: type: string examples: - MDEwOlJlcG9zaXRvcnkxMjk2MjY5 name: type: string examples: - Hello-World full_name: type: string examples: - octocat/Hello-World owner: "$ref": "#/components/schemas/simple-user" private: type: boolean html_url: type: string format: uri examples: - https://github.com/octocat/Hello-World description: type: - string - 'null' examples: - This your first repo! fork: type: boolean url: type: string format: uri examples: - https://api.github.com/repos/octocat/Hello-World archive_url: type: string examples: - http://api.github.com/repos/octocat/Hello-World/{archive_format}{/ref} assignees_url: type: string examples: - http://api.github.com/repos/octocat/Hello-World/assignees{/user} blobs_url: type: string examples: - http://api.github.com/repos/octocat/Hello-World/git/blobs{/sha} branches_url: type: string examples: - http://api.github.com/repos/octocat/Hello-World/branches{/branch} collaborators_url: type: string examples: - http://api.github.com/repos/octocat/Hello-World/collaborators{/collaborator} comments_url: type: string examples: - http://api.github.com/repos/octocat/Hello-World/comments{/number} commits_url: type: string examples: - http://api.github.com/repos/octocat/Hello-World/commits{/sha} compare_url: type: string examples: - http://api.github.com/repos/octocat/Hello-World/compare/{base}...{head} contents_url: type: string examples: - http://api.github.com/repos/octocat/Hello-World/contents/{+path} contributors_url: type: string format: uri examples: - http://api.github.com/repos/octocat/Hello-World/contributors deployments_url: type: string format: uri examples: - http://api.github.com/repos/octocat/Hello-World/deployments downloads_url: type: string format: uri examples: - http://api.github.com/repos/octocat/Hello-World/downloads events_url: type: string format: uri examples: - http://api.github.com/repos/octocat/Hello-World/events forks_url: type: string format: uri examples: - http://api.github.com/repos/octocat/Hello-World/forks git_commits_url: type: string examples: - http://api.github.com/repos/octocat/Hello-World/git/commits{/sha} git_refs_url: type: string examples: - http://api.github.com/repos/octocat/Hello-World/git/refs{/sha} git_tags_url: type: string examples: - http://api.github.com/repos/octocat/Hello-World/git/tags{/sha} git_url: type: string examples: - git:github.com/octocat/Hello-World.git issue_comment_url: type: string examples: - http://api.github.com/repos/octocat/Hello-World/issues/comments{/number} issue_events_url: type: string examples: - http://api.github.com/repos/octocat/Hello-World/issues/events{/number} issues_url: type: string examples: - http://api.github.com/repos/octocat/Hello-World/issues{/number} keys_url: type: string examples: - http://api.github.com/repos/octocat/Hello-World/keys{/key_id} labels_url: type: string examples: - http://api.github.com/repos/octocat/Hello-World/labels{/name} languages_url: type: string format: uri examples: - http://api.github.com/repos/octocat/Hello-World/languages merges_url: type: string format: uri examples: - http://api.github.com/repos/octocat/Hello-World/merges milestones_url: type: string examples: - http://api.github.com/repos/octocat/Hello-World/milestones{/number} notifications_url: type: string examples: - http://api.github.com/repos/octocat/Hello-World/notifications{?since,all,participating} pulls_url: type: string examples: - http://api.github.com/repos/octocat/Hello-World/pulls{/number} releases_url: type: string examples: - http://api.github.com/repos/octocat/Hello-World/releases{/id} ssh_url: type: string examples: - git@github.com:octocat/Hello-World.git stargazers_url: type: string format: uri examples: - http://api.github.com/repos/octocat/Hello-World/stargazers statuses_url: type: string examples: - http://api.github.com/repos/octocat/Hello-World/statuses/{sha} subscribers_url: type: string format: uri examples: - http://api.github.com/repos/octocat/Hello-World/subscribers subscription_url: type: string format: uri examples: - http://api.github.com/repos/octocat/Hello-World/subscription tags_url: type: string format: uri examples: - http://api.github.com/repos/octocat/Hello-World/tags teams_url: type: string format: uri examples: - http://api.github.com/repos/octocat/Hello-World/teams trees_url: type: string examples: - http://api.github.com/repos/octocat/Hello-World/git/trees{/sha} clone_url: type: string examples: - https://github.com/octocat/Hello-World.git mirror_url: type: - string - 'null' format: uri examples: - git:git.example.com/octocat/Hello-World hooks_url: type: string format: uri examples: - http://api.github.com/repos/octocat/Hello-World/hooks svn_url: type: string format: uri examples: - https://svn.github.com/octocat/Hello-World homepage: type: - string - 'null' format: uri examples: - https://github.com language: type: - string - 'null' forks_count: type: integer examples: - 9 stargazers_count: type: integer examples: - 80 watchers_count: type: integer examples: - 80 size: type: integer examples: - 108 default_branch: type: string examples: - master open_issues_count: type: integer examples: - 0 is_template: type: boolean examples: - true topics: type: array items: type: string examples: - octocat - atom - electron - API has_issues: type: boolean examples: - true has_projects: type: boolean examples: - true has_wiki: type: boolean examples: - true has_pages: type: boolean has_downloads: type: boolean examples: - true archived: type: boolean disabled: type: boolean description: Returns whether or not this repository disabled. visibility: description: 'The repository visibility: public, private, or internal.' type: string examples: - public pushed_at: type: string format: date-time examples: - '2011-01-26T19:06:43Z' created_at: type: string format: date-time examples: - '2011-01-26T19:01:12Z' updated_at: type: string format: date-time examples: - '2011-01-26T19:14:43Z' permissions: type: object properties: admin: type: boolean maintain: type: boolean push: type: boolean triage: type: boolean pull: type: boolean required: - admin - pull - push allow_rebase_merge: type: boolean examples: - true template_repository: anyOf: - type: 'null' - "$ref": "#/components/schemas/repository" temp_clone_token: type: - string - 'null' allow_squash_merge: type: boolean examples: - true delete_branch_on_merge: type: boolean examples: - false allow_merge_commit: type: boolean examples: - true allow_forking: type: boolean examples: - true subscribers_count: type: integer examples: - 42 network_count: type: integer examples: - 0 license: anyOf: - type: 'null' - "$ref": "#/components/schemas/license-simple" organization: anyOf: - type: 'null' - "$ref": "#/components/schemas/simple-user" parent: "$ref": "#/components/schemas/repository" source: "$ref": "#/components/schemas/repository" forks: type: integer master_branch: type: string open_issues: type: integer watchers: type: integer anonymous_access_enabled: description: Whether anonymous git access is allowed. default: true type: boolean code_of_conduct: "$ref": "#/components/schemas/code-of-conduct-simple" required: - archive_url - assignees_url - blobs_url - branches_url - collaborators_url - comments_url - commits_url - compare_url - contents_url - contributors_url - deployments_url - description - downloads_url - events_url - fork - forks_url - full_name - git_commits_url - git_refs_url - git_tags_url - hooks_url - html_url - id - node_id - issue_comment_url - issue_events_url - issues_url - keys_url - labels_url - languages_url - merges_url - milestones_url - name - notifications_url - owner - private - pulls_url - releases_url - stargazers_url - statuses_url - subscribers_url - subscription_url - tags_url - teams_url - trees_url - url - clone_url - default_branch - forks - forks_count - git_url - has_downloads - has_issues - has_projects - has_wiki - has_pages - homepage - language - archived - disabled - mirror_url - open_issues - open_issues_count - license - pushed_at - size - ssh_url - stargazers_count - svn_url - watchers - watchers_count - created_at - updated_at - network_count - subscribers_count artifact: title: Artifact description: An artifact type: object properties: id: type: integer examples: - 5 node_id: type: string examples: - MDEwOkNoZWNrU3VpdGU1 name: description: The name of the artifact. type: string examples: - AdventureWorks.Framework size_in_bytes: description: The size in bytes of the artifact. type: integer examples: - 12345 url: type: string examples: - https://api.github.com/repos/github/hello-world/actions/artifacts/5 archive_download_url: type: string examples: - https://api.github.com/repos/github/hello-world/actions/artifacts/5/zip expired: description: Whether or not the artifact has expired. type: boolean created_at: type: - string - 'null' format: date-time expires_at: type: - string - 'null' format: date-time updated_at: type: - string - 'null' format: date-time required: - id - node_id - name - size_in_bytes - url - archive_download_url - expired - created_at - expires_at - updated_at job: title: Job description: Information of a job execution in a workflow run type: object properties: id: description: The id of the job. type: integer examples: - 21 run_id: description: The id of the associated workflow run. type: integer examples: - 5 run_url: type: string examples: - https://api.github.com/repos/github/hello-world/actions/runs/5 run_attempt: type: integer description: Attempt number of the associated workflow run, 1 for first attempt and higher if the workflow was re-run. examples: - 1 node_id: type: string examples: - MDg6Q2hlY2tSdW40 head_sha: description: The SHA of the commit that is being run. type: string examples: - '009b8a3a9ccbb128af87f9b1c0f4c62e8a304f6d' url: type: string examples: - https://api.github.com/repos/github/hello-world/actions/jobs/21 html_url: type: - string - 'null' examples: - https://github.com/github/hello-world/runs/4 status: description: The phase of the lifecycle that the job is currently in. type: string enum: - queued - in_progress - completed examples: - queued conclusion: description: The outcome of the job. type: - string - 'null' examples: - success started_at: description: The time that the job started, in ISO 8601 format. format: date-time type: string examples: - '2019-08-08T08:00:00-07:00' completed_at: description: The time that the job finished, in ISO 8601 format. format: date-time type: - string - 'null' examples: - '2019-08-08T08:00:00-07:00' name: description: The name of the job. type: string examples: - test-coverage steps: description: Steps in this job. type: array items: type: object required: - name - status - conclusion - number properties: status: description: The phase of the lifecycle that the job is currently in. type: string enum: - queued - in_progress - completed examples: - queued conclusion: description: The outcome of the job. type: - string - 'null' examples: - success name: description: The name of the job. type: string examples: - test-coverage number: type: integer examples: - 1 started_at: description: The time that the step started, in ISO 8601 format. format: date-time type: - string - 'null' examples: - '2019-08-08T08:00:00-07:00' completed_at: description: The time that the job finished, in ISO 8601 format. format: date-time type: - string - 'null' examples: - '2019-08-08T08:00:00-07:00' check_run_url: type: string examples: - https://api.github.com/repos/github/hello-world/check-runs/4 required: - id - node_id - run_id - run_url - head_sha - name - url - html_url - status - conclusion - started_at - completed_at - check_run_url actions-enabled: type: boolean description: Whether GitHub Actions is enabled on the repository. actions-repository-permissions: type: object properties: enabled: "$ref": "#/components/schemas/actions-enabled" allowed_actions: "$ref": "#/components/schemas/allowed-actions" selected_actions_url: "$ref": "#/components/schemas/selected-actions-url" required: - enabled pull-request-minimal: title: Pull Request Minimal type: object properties: id: type: integer number: type: integer url: type: string head: type: object properties: ref: type: string sha: type: string repo: type: object properties: id: type: integer url: type: string name: type: string required: - id - url - name required: - ref - sha - repo base: type: object properties: ref: type: string sha: type: string repo: type: object properties: id: type: integer url: type: string name: type: string required: - id - url - name required: - ref - sha - repo required: - id - number - url - head - base simple-commit: title: Simple Commit description: Simple Commit type: object properties: id: type: string tree_id: type: string message: type: string timestamp: type: string format: date-time author: type: - object - 'null' properties: name: type: string email: type: string required: - name - email committer: type: - object - 'null' properties: name: type: string email: type: string required: - name - email required: - id - tree_id - message - timestamp - author - committer workflow-run: title: Workflow Run description: An invocation of a workflow type: object properties: id: type: integer description: The ID of the workflow run. examples: - 5 name: type: - string - 'null' description: The name of the workflow run. examples: - Build node_id: type: string examples: - MDEwOkNoZWNrU3VpdGU1 check_suite_id: type: integer description: The ID of the associated check suite. examples: - 42 check_suite_node_id: type: string description: The node ID of the associated check suite. examples: - MDEwOkNoZWNrU3VpdGU0Mg== head_branch: type: - string - 'null' examples: - master head_sha: description: The SHA of the head commit that points to the version of the workflow being run. type: string examples: - '009b8a3a9ccbb128af87f9b1c0f4c62e8a304f6d' run_number: type: integer description: The auto incrementing run number for the workflow run. examples: - 106 run_attempt: type: integer description: Attempt number of the run, 1 for first attempt and higher if the workflow was re-run. examples: - 1 event: type: string examples: - push status: type: - string - 'null' examples: - completed conclusion: type: - string - 'null' examples: - neutral workflow_id: type: integer description: The ID of the parent workflow. examples: - 5 url: type: string description: The URL to the workflow run. examples: - https://api.github.com/repos/github/hello-world/actions/runs/5 html_url: type: string examples: - https://github.com/github/hello-world/suites/4 pull_requests: type: - array - 'null' items: "$ref": "#/components/schemas/pull-request-minimal" created_at: type: string format: date-time updated_at: type: string format: date-time run_started_at: type: string format: date-time description: The start time of the latest run. Resets on re-run. jobs_url: description: The URL to the jobs for the workflow run. type: string examples: - https://api.github.com/repos/github/hello-world/actions/runs/5/jobs logs_url: description: The URL to download the logs for the workflow run. type: string examples: - https://api.github.com/repos/github/hello-world/actions/runs/5/logs check_suite_url: description: The URL to the associated check suite. type: string examples: - https://api.github.com/repos/github/hello-world/check-suites/12 artifacts_url: description: The URL to the artifacts for the workflow run. type: string examples: - https://api.github.com/repos/github/hello-world/actions/runs/5/rerun/artifacts cancel_url: description: The URL to cancel the workflow run. type: string examples: - https://api.github.com/repos/github/hello-world/actions/runs/5/cancel rerun_url: description: The URL to rerun the workflow run. type: string examples: - https://api.github.com/repos/github/hello-world/actions/runs/5/rerun previous_attempt_url: description: The URL to the previous attempted run of this workflow, if one exists. type: - string - 'null' examples: - https://api.github.com/repos/github/hello-world/actions/runs/5/attempts/3 workflow_url: description: The URL to the workflow. type: string examples: - https://api.github.com/repos/github/hello-world/actions/workflows/main.yaml head_commit: anyOf: - type: 'null' - "$ref": "#/components/schemas/simple-commit" repository: "$ref": "#/components/schemas/minimal-repository" head_repository: "$ref": "#/components/schemas/minimal-repository" head_repository_id: type: integer examples: - 5 required: - id - node_id - head_branch - run_number - event - status - conclusion - head_sha - workflow_id - url - html_url - created_at - updated_at - head_commit - head_repository - repository - jobs_url - logs_url - check_suite_url - cancel_url - rerun_url - artifacts_url - workflow_url - pull_requests actions-secret: title: Actions Secret description: Set secrets for GitHub Actions. type: object properties: name: description: The name of the secret. type: string examples: - SECRET_TOKEN created_at: type: string format: date-time updated_at: type: string format: date-time required: - name - created_at - updated_at workflow: title: Workflow description: A GitHub Actions workflow type: object properties: id: type: integer examples: - 5 node_id: type: string examples: - MDg6V29ya2Zsb3cxMg== name: type: string examples: - CI path: type: string examples: - ruby.yaml state: type: string enum: - active - deleted - disabled_fork - disabled_inactivity - disabled_manually examples: - active created_at: type: string format: date-time examples: - '2019-12-06T14:20:20.000Z' updated_at: type: string format: date-time examples: - '2019-12-06T14:20:20.000Z' url: type: string examples: - https://api.github.com/repos/actions/setup-ruby/workflows/5 html_url: type: string examples: - https://github.com/actions/setup-ruby/blob/master/.github/workflows/ruby.yaml badge_url: type: string examples: - https://github.com/actions/setup-ruby/workflows/CI/badge.svg deleted_at: type: string format: date-time examples: - '2019-12-06T14:20:20.000Z' required: - id - node_id - name - path - state - url - html_url - badge_url - created_at - updated_at protected-branch-required-status-check: title: Protected Branch Required Status Check description: Protected Branch Required Status Check type: object properties: url: type: string enforcement_level: type: string contexts: type: array items: type: string contexts_url: type: string strict: type: boolean required: - contexts protected-branch-admin-enforced: title: Protected Branch Admin Enforced description: Protected Branch Admin Enforced type: object properties: url: type: string format: uri examples: - https://api.github.com/repos/octocat/Hello-World/branches/master/protection/enforce_admins enabled: type: boolean examples: - true required: - url - enabled protected-branch-pull-request-review: title: Protected Branch Pull Request Review description: Protected Branch Pull Request Review type: object properties: url: type: string format: uri examples: - https://api.github.com/repos/octocat/Hello-World/branches/master/protection/dismissal_restrictions dismissal_restrictions: type: object properties: users: description: The list of users with review dismissal access. type: array items: "$ref": "#/components/schemas/simple-user" teams: description: The list of teams with review dismissal access. type: array items: "$ref": "#/components/schemas/team" url: type: string examples: - '"https://api.github.com/repos/the-org/an-org-repo/branches/master/protection/dismissal_restrictions"' users_url: type: string examples: - '"https://api.github.com/repos/the-org/an-org-repo/branches/master/protection/dismissal_restrictions/users"' teams_url: type: string examples: - '"https://api.github.com/repos/the-org/an-org-repo/branches/master/protection/dismissal_restrictions/teams"' dismiss_stale_reviews: type: boolean examples: - true require_code_owner_reviews: type: boolean examples: - true required_approving_review_count: type: integer minimum: 1 maximum: 6 examples: - 2 required: - dismiss_stale_reviews - require_code_owner_reviews branch-restriction-policy: title: Branch Restriction Policy description: Branch Restriction Policy type: object properties: url: type: string format: uri users_url: type: string format: uri teams_url: type: string format: uri apps_url: type: string format: uri users: type: array items: type: object properties: login: type: string id: type: integer node_id: type: string avatar_url: type: string gravatar_id: type: string url: type: string html_url: type: string followers_url: type: string following_url: type: string gists_url: type: string starred_url: type: string subscriptions_url: type: string organizations_url: type: string repos_url: type: string events_url: type: string received_events_url: type: string type: type: string site_admin: type: boolean teams: type: array items: type: object properties: id: type: integer node_id: type: string url: type: string html_url: type: string name: type: string slug: type: string description: type: - string - 'null' privacy: type: string permission: type: string members_url: type: string repositories_url: type: string parent: type: - string - 'null' apps: type: array items: type: object properties: id: type: integer slug: type: string node_id: type: string owner: type: object properties: login: type: string id: type: integer node_id: type: string url: type: string repos_url: type: string events_url: type: string hooks_url: type: string issues_url: type: string members_url: type: string public_members_url: type: string avatar_url: type: string description: type: string gravatar_id: type: string examples: - '""' html_url: type: string examples: - '"https://github.com/testorg-ea8ec76d71c3af4b"' followers_url: type: string examples: - '"https://api.github.com/users/testorg-ea8ec76d71c3af4b/followers"' following_url: type: string examples: - '"https://api.github.com/users/testorg-ea8ec76d71c3af4b/following{/other_user}"' gists_url: type: string examples: - '"https://api.github.com/users/testorg-ea8ec76d71c3af4b/gists{/gist_id}"' starred_url: type: string examples: - '"https://api.github.com/users/testorg-ea8ec76d71c3af4b/starred{/owner}{/repo}"' subscriptions_url: type: string examples: - '"https://api.github.com/users/testorg-ea8ec76d71c3af4b/subscriptions"' organizations_url: type: string examples: - '"https://api.github.com/users/testorg-ea8ec76d71c3af4b/orgs"' received_events_url: type: string examples: - '"https://api.github.com/users/testorg-ea8ec76d71c3af4b/received_events"' type: type: string examples: - '"Organization"' site_admin: type: boolean examples: - false name: type: string description: type: string external_url: type: string html_url: type: string created_at: type: string updated_at: type: string permissions: type: object properties: metadata: type: string contents: type: string issues: type: string single_file: type: string events: type: array items: type: string required: - url - users_url - teams_url - apps_url - users - teams - apps branch-protection: title: Branch Protection description: Branch Protection type: object properties: url: type: string enabled: type: boolean required_status_checks: "$ref": "#/components/schemas/protected-branch-required-status-check" enforce_admins: "$ref": "#/components/schemas/protected-branch-admin-enforced" required_pull_request_reviews: "$ref": "#/components/schemas/protected-branch-pull-request-review" restrictions: "$ref": "#/components/schemas/branch-restriction-policy" required_linear_history: type: object properties: enabled: type: boolean allow_force_pushes: type: object properties: enabled: type: boolean allow_deletions: type: object properties: enabled: type: boolean required_conversation_resolution: type: object properties: enabled: type: boolean name: type: string examples: - '"branch/with/protection"' protection_url: type: string examples: - '"https://api.github.com/repos/owner-79e94e2d36b3fd06a32bb213/AAA_Public_Repo/branches/branch/with/protection/protection"' required_signatures: type: object properties: url: type: string format: uri examples: - https://api.github.com/repos/octocat/Hello-World/branches/master/protection/required_signatures enabled: type: boolean examples: - true required: - url - enabled short-branch: title: Short Branch description: Short Branch type: object properties: name: type: string commit: type: object properties: sha: type: string url: type: string format: uri required: - sha - url protected: type: boolean protection: "$ref": "#/components/schemas/branch-protection" protection_url: type: string format: uri required: - name - commit - protected git-user: title: Git User description: Metaproperties for Git author/committer information. type: object properties: name: type: string examples: - '"Chris Wanstrath"' email: type: string examples: - '"chris@ozmm.org"' date: type: string examples: - '"2007-10-29T02:42:39.000-07:00"' verification: title: Verification type: object properties: verified: type: boolean reason: type: string payload: type: - string - 'null' signature: type: - string - 'null' required: - verified - reason - payload - signature diff-entry: title: Diff Entry description: Diff Entry type: object properties: sha: type: string examples: - bbcd538c8e72b8c175046e27cc8f907076331401 filename: type: string examples: - file1.txt status: type: string enum: - added - removed - modified - renamed - copied - changed - unchanged examples: - added additions: type: integer examples: - 103 deletions: type: integer examples: - 21 changes: type: integer examples: - 124 blob_url: type: string format: uri examples: - https://github.com/octocat/Hello-World/blob/6dcb09b5b57875f334f61aebed695e2e4193db5e/file1.txt raw_url: type: string format: uri examples: - https://github.com/octocat/Hello-World/raw/6dcb09b5b57875f334f61aebed695e2e4193db5e/file1.txt contents_url: type: string format: uri examples: - https://api.github.com/repos/octocat/Hello-World/contents/file1.txt?ref=6dcb09b5b57875f334f61aebed695e2e4193db5e patch: type: string examples: - "@@ -132,7 +132,7 @@ module Test @@ -1000,7 +1000,7 @@ module Test" previous_filename: type: string examples: - file.txt required: - additions - blob_url - changes - contents_url - deletions - filename - raw_url - sha - status commit: title: Commit description: Commit type: object properties: url: type: string format: uri examples: - https://api.github.com/repos/octocat/Hello-World/commits/6dcb09b5b57875f334f61aebed695e2e4193db5e sha: type: string examples: - 6dcb09b5b57875f334f61aebed695e2e4193db5e node_id: type: string examples: - MDY6Q29tbWl0NmRjYjA5YjViNTc4NzVmMzM0ZjYxYWViZWQ2OTVlMmU0MTkzZGI1ZQ== html_url: type: string format: uri examples: - https://github.com/octocat/Hello-World/commit/6dcb09b5b57875f334f61aebed695e2e4193db5e comments_url: type: string format: uri examples: - https://api.github.com/repos/octocat/Hello-World/commits/6dcb09b5b57875f334f61aebed695e2e4193db5e/comments commit: type: object properties: url: type: string format: uri examples: - https://api.github.com/repos/octocat/Hello-World/commits/6dcb09b5b57875f334f61aebed695e2e4193db5e author: anyOf: - type: 'null' - "$ref": "#/components/schemas/git-user" committer: anyOf: - type: 'null' - "$ref": "#/components/schemas/git-user" message: type: string examples: - Fix all the bugs comment_count: type: integer examples: - 0 tree: type: object properties: sha: type: string examples: - 827efc6d56897b048c772eb4087f854f46256132 url: type: string format: uri examples: - https://api.github.com/repos/octocat/Hello-World/tree/827efc6d56897b048c772eb4087f854f46256132 required: - sha - url verification: "$ref": "#/components/schemas/verification" required: - author - committer - comment_count - message - tree - url author: anyOf: - type: 'null' - "$ref": "#/components/schemas/simple-user" committer: anyOf: - type: 'null' - "$ref": "#/components/schemas/simple-user" parents: type: array items: type: object properties: sha: type: string examples: - 7638417db6d59f3c431d3e1f261cc637155684cd url: type: string format: uri examples: - https://api.github.com/repos/octocat/Hello-World/commits/7638417db6d59f3c431d3e1f261cc637155684cd html_url: type: string format: uri examples: - https://github.com/octocat/Hello-World/commit/7638417db6d59f3c431d3e1f261cc637155684cd required: - sha - url stats: type: object properties: additions: type: integer deletions: type: integer total: type: integer files: type: array items: "$ref": "#/components/schemas/diff-entry" required: - url - sha - node_id - html_url - comments_url - commit - author - committer - parents branch-with-protection: title: Branch With Protection description: Branch With Protection type: object properties: name: type: string commit: "$ref": "#/components/schemas/commit" _links: type: object properties: html: type: string self: type: string format: uri required: - html - self protected: type: boolean protection: "$ref": "#/components/schemas/branch-protection" protection_url: type: string format: uri pattern: type: string examples: - '"mas*"' required_approving_review_count: type: integer examples: - 1 required: - name - commit - _links - protection - protected - protection_url status-check-policy: title: Status Check Policy description: Status Check Policy type: object properties: url: type: string format: uri examples: - https://api.github.com/repos/octocat/Hello-World/branches/master/protection/required_status_checks strict: type: boolean examples: - true contexts: type: array items: type: string examples: - continuous-integration/travis-ci contexts_url: type: string format: uri examples: - https://api.github.com/repos/octocat/Hello-World/branches/master/protection/required_status_checks/contexts required: - url - contexts_url - strict - contexts protected-branch: title: Protected Branch description: Branch protections protect branches type: object properties: url: type: string format: uri required_status_checks: "$ref": "#/components/schemas/status-check-policy" required_pull_request_reviews: type: object properties: url: type: string format: uri dismiss_stale_reviews: type: boolean require_code_owner_reviews: type: boolean required_approving_review_count: type: integer dismissal_restrictions: type: object properties: url: type: string format: uri users_url: type: string format: uri teams_url: type: string format: uri users: type: array items: "$ref": "#/components/schemas/simple-user" teams: type: array items: "$ref": "#/components/schemas/team" required: - url - users_url - teams_url - users - teams required: - url required_signatures: type: object properties: url: type: string format: uri examples: - https://api.github.com/repos/octocat/Hello-World/branches/master/protection/required_signatures enabled: type: boolean examples: - true required: - url - enabled enforce_admins: type: object properties: url: type: string format: uri enabled: type: boolean additionalProperties: false required: - url - enabled required_linear_history: type: object properties: enabled: type: boolean additionalProperties: false required: - enabled allow_force_pushes: type: object properties: enabled: type: boolean additionalProperties: false required: - enabled allow_deletions: type: object properties: enabled: type: boolean additionalProperties: false required: - enabled restrictions: "$ref": "#/components/schemas/branch-restriction-policy" required_conversation_resolution: type: object properties: enabled: type: boolean additionalProperties: false required: - url deployment-simple: title: Deployment description: A deployment created as the result of an Actions check run from a workflow that references an environment type: object properties: url: type: string format: uri examples: - https://api.github.com/repos/octocat/example/deployments/1 id: description: Unique identifier of the deployment type: integer examples: - 42 node_id: type: string examples: - MDEwOkRlcGxveW1lbnQx task: description: Parameter to specify a task to execute type: string examples: - deploy original_environment: type: string examples: - staging environment: description: Name for the target deployment environment. type: string examples: - production description: type: - string - 'null' examples: - Deploy request from hubot created_at: type: string format: date-time examples: - '2012-07-20T01:19:13Z' updated_at: type: string format: date-time examples: - '2012-07-20T01:19:13Z' statuses_url: type: string format: uri examples: - https://api.github.com/repos/octocat/example/deployments/1/statuses repository_url: type: string format: uri examples: - https://api.github.com/repos/octocat/example transient_environment: description: 'Specifies if the given environment is will no longer exist at some point in the future. Default: false.' type: boolean examples: - true production_environment: description: 'Specifies if the given environment is one that end-users directly interact with. Default: false.' type: boolean examples: - true performed_via_github_app: anyOf: - type: 'null' - "$ref": "#/components/schemas/integration" required: - id - node_id - task - environment - description - statuses_url - repository_url - url - created_at - updated_at check-run: title: CheckRun description: A check performed on the code of a given code change type: object properties: id: description: The id of the check. type: integer examples: - 21 head_sha: description: The SHA of the commit that is being checked. type: string examples: - '009b8a3a9ccbb128af87f9b1c0f4c62e8a304f6d' node_id: type: string examples: - MDg6Q2hlY2tSdW40 external_id: type: - string - 'null' examples: - '42' url: type: string examples: - https://api.github.com/repos/github/hello-world/check-runs/4 html_url: type: - string - 'null' examples: - https://github.com/github/hello-world/runs/4 details_url: type: - string - 'null' examples: - https://example.com status: description: The phase of the lifecycle that the check is currently in. type: string enum: - queued - in_progress - completed examples: - queued conclusion: type: - string - 'null' enum: - success - failure - neutral - cancelled - skipped - timed_out - action_required - examples: - neutral started_at: type: - string - 'null' format: date-time examples: - '2018-05-04T01:14:52Z' completed_at: type: - string - 'null' format: date-time examples: - '2018-05-04T01:14:52Z' output: type: object properties: title: type: - string - 'null' summary: type: - string - 'null' text: type: - string - 'null' annotations_count: type: integer annotations_url: type: string format: uri required: - title - summary - text - annotations_count - annotations_url name: description: The name of the check. type: string examples: - test-coverage check_suite: type: - object - 'null' properties: id: type: integer required: - id app: anyOf: - type: 'null' - "$ref": "#/components/schemas/integration" pull_requests: type: array items: "$ref": "#/components/schemas/pull-request-minimal" deployment: "$ref": "#/components/schemas/deployment-simple" required: - id - node_id - head_sha - name - url - html_url - details_url - status - conclusion - started_at - completed_at - external_id - check_suite - output - app - pull_requests check-annotation: title: Check Annotation description: Check Annotation type: object properties: path: type: string examples: - README.md start_line: type: integer examples: - 2 end_line: type: integer examples: - 2 start_column: type: - integer - 'null' examples: - 5 end_column: type: - integer - 'null' examples: - 10 annotation_level: type: - string - 'null' examples: - warning title: type: - string - 'null' examples: - Spell Checker message: type: - string - 'null' examples: - Check your spelling for 'banaas'. raw_details: type: - string - 'null' examples: - Do you mean 'bananas' or 'banana'? blob_href: type: string required: - path - blob_href - start_line - end_line - start_column - end_column - annotation_level - title - message - raw_details check-suite: title: CheckSuite description: A suite of checks performed on the code of a given code change type: object properties: id: type: integer examples: - 5 node_id: type: string examples: - MDEwOkNoZWNrU3VpdGU1 head_branch: type: - string - 'null' examples: - master head_sha: description: The SHA of the head commit that is being checked. type: string examples: - '009b8a3a9ccbb128af87f9b1c0f4c62e8a304f6d' status: type: - string - 'null' enum: - queued - in_progress - completed - examples: - completed conclusion: type: - string - 'null' enum: - success - failure - neutral - cancelled - skipped - timed_out - action_required - examples: - neutral url: type: - string - 'null' examples: - https://api.github.com/repos/github/hello-world/check-suites/5 before: type: - string - 'null' examples: - 146e867f55c26428e5f9fade55a9bbf5e95a7912 after: type: - string - 'null' examples: - d6fde92930d4715a2b49857d24b940956b26d2d3 pull_requests: type: - array - 'null' items: "$ref": "#/components/schemas/pull-request-minimal" app: anyOf: - type: 'null' - "$ref": "#/components/schemas/integration" repository: "$ref": "#/components/schemas/minimal-repository" created_at: type: - string - 'null' format: date-time updated_at: type: - string - 'null' format: date-time head_commit: "$ref": "#/components/schemas/simple-commit" latest_check_runs_count: type: integer check_runs_url: type: string rerequestable: type: boolean runs_rerequestable: type: boolean required: - id - node_id - head_branch - status - conclusion - head_sha - url - before - after - created_at - updated_at - app - head_commit - repository - latest_check_runs_count - check_runs_url - pull_requests check-suite-preference: title: Check Suite Preference description: Check suite configuration preferences for a repository. type: object required: - preferences - repository properties: preferences: type: object properties: auto_trigger_checks: type: array items: type: object properties: app_id: type: integer setting: type: boolean required: - app_id - setting repository: "$ref": "#/components/schemas/minimal-repository" code-scanning-analysis-tool-name: type: string description: The name of the tool used to generate the code scanning analysis. code-scanning-analysis-tool-guid: type: - string - 'null' description: The GUID of the tool used to generate the code scanning analysis, if provided in the uploaded SARIF data. code-scanning-ref: type: string description: |- The full Git reference, formatted as `refs/heads/`, `refs/pull//merge`, or `refs/pull//head`. code-scanning-alert-state: type: string description: State of a code scanning alert. enum: - open - closed - dismissed - fixed alert-number: type: integer description: The security alert number. readOnly: true alert-created-at: type: string description: 'The time that the alert was created in ISO 8601 format: `YYYY-MM-DDTHH:MM:SSZ`.' format: date-time readOnly: true alert-url: type: string description: The REST API URL of the alert resource. format: uri readOnly: true alert-html-url: type: string description: The GitHub URL of the alert resource. format: uri readOnly: true alert-instances-url: type: string description: The REST API URL for fetching the list of instances for an alert. format: uri readOnly: true code-scanning-alert-dismissed-at: type: - string - 'null' description: 'The time that the alert was dismissed in ISO 8601 format: `YYYY-MM-DDTHH:MM:SSZ`.' format: date-time readOnly: true code-scanning-alert-dismissed-reason: type: - string - 'null' description: "**Required when the state is dismissed.** The reason for dismissing or closing the alert. Can be one of: `false positive`, `won't fix`, and `used in tests`." enum: - - false positive - won't fix - used in tests code-scanning-alert-rule-summary: type: object properties: id: type: - string - 'null' description: A unique identifier for the rule used to detect the alert. name: type: string description: The name of the rule used to detect the alert. severity: type: - string - 'null' description: The severity of the alert. enum: - none - note - warning - error - description: type: string description: A short description of the rule used to detect the alert. code-scanning-analysis-tool-version: type: - string - 'null' description: The version of the tool used to generate the code scanning analysis. code-scanning-analysis-tool: type: object properties: name: "$ref": "#/components/schemas/code-scanning-analysis-tool-name" version: "$ref": "#/components/schemas/code-scanning-analysis-tool-version" guid: "$ref": "#/components/schemas/code-scanning-analysis-tool-guid" code-scanning-analysis-analysis-key: type: string description: Identifies the configuration under which the analysis was executed. For example, in GitHub Actions this includes the workflow filename and job name. code-scanning-alert-environment: type: string description: Identifies the variable values associated with the environment in which the analysis that generated this alert instance was performed, such as the language that was analyzed. code-scanning-analysis-category: type: string description: Identifies the configuration under which the analysis was executed. Used to distinguish between multiple analyses for the same tool and commit, but performed on different languages or different parts of the code. code-scanning-alert-location: type: object description: Describe a region within a file for the alert. properties: path: type: string start_line: type: integer end_line: type: integer start_column: type: integer end_column: type: integer code-scanning-alert-classification: type: - string - 'null' description: A classification of the file. For example to identify it as generated. enum: - source - generated - test - library - code-scanning-alert-instance: type: object properties: ref: "$ref": "#/components/schemas/code-scanning-ref" analysis_key: "$ref": "#/components/schemas/code-scanning-analysis-analysis-key" environment: "$ref": "#/components/schemas/code-scanning-alert-environment" category: "$ref": "#/components/schemas/code-scanning-analysis-category" state: "$ref": "#/components/schemas/code-scanning-alert-state" commit_sha: type: string message: type: object properties: text: type: string location: "$ref": "#/components/schemas/code-scanning-alert-location" html_url: type: string classifications: type: array description: |- Classifications that have been applied to the file that triggered the alert. For example identifying it as documentation, or a generated file. items: "$ref": "#/components/schemas/code-scanning-alert-classification" code-scanning-alert-items: type: object properties: number: "$ref": "#/components/schemas/alert-number" created_at: "$ref": "#/components/schemas/alert-created-at" url: "$ref": "#/components/schemas/alert-url" html_url: "$ref": "#/components/schemas/alert-html-url" instances_url: "$ref": "#/components/schemas/alert-instances-url" state: "$ref": "#/components/schemas/code-scanning-alert-state" dismissed_by: anyOf: - type: 'null' - "$ref": "#/components/schemas/simple-user" dismissed_at: "$ref": "#/components/schemas/code-scanning-alert-dismissed-at" dismissed_reason: "$ref": "#/components/schemas/code-scanning-alert-dismissed-reason" rule: "$ref": "#/components/schemas/code-scanning-alert-rule-summary" tool: "$ref": "#/components/schemas/code-scanning-analysis-tool" most_recent_instance: "$ref": "#/components/schemas/code-scanning-alert-instance" required: - number - created_at - url - html_url - instances_url - state - dismissed_by - dismissed_at - dismissed_reason - rule - tool - most_recent_instance code-scanning-alert-rule: type: object properties: id: type: - string - 'null' description: A unique identifier for the rule used to detect the alert. name: type: string description: The name of the rule used to detect the alert. severity: type: - string - 'null' description: The severity of the alert. enum: - none - note - warning - error - description: type: string description: A short description of the rule used to detect the alert. full_description: type: string description: description of the rule used to detect the alert. tags: type: - array - 'null' description: A set of tags applicable for the rule. items: type: string help: type: - string - 'null' description: Detailed documentation for the rule as GitHub Flavored Markdown. code-scanning-alert: type: object properties: number: "$ref": "#/components/schemas/alert-number" created_at: "$ref": "#/components/schemas/alert-created-at" url: "$ref": "#/components/schemas/alert-url" html_url: "$ref": "#/components/schemas/alert-html-url" instances_url: "$ref": "#/components/schemas/alert-instances-url" state: "$ref": "#/components/schemas/code-scanning-alert-state" dismissed_by: anyOf: - type: 'null' - "$ref": "#/components/schemas/simple-user" dismissed_at: "$ref": "#/components/schemas/code-scanning-alert-dismissed-at" dismissed_reason: "$ref": "#/components/schemas/code-scanning-alert-dismissed-reason" rule: "$ref": "#/components/schemas/code-scanning-alert-rule" tool: "$ref": "#/components/schemas/code-scanning-analysis-tool" most_recent_instance: "$ref": "#/components/schemas/code-scanning-alert-instance" instances: deprecated: true required: - number - created_at - url - html_url - instances_url - state - dismissed_by - dismissed_at - dismissed_reason - rule - tool - most_recent_instance code-scanning-alert-set-state: description: Sets the state of the code scanning alert. Can be one of `open` or `dismissed`. You must provide `dismissed_reason` when you set the state to `dismissed`. type: string enum: - open - dismissed code-scanning-analysis-sarif-id: type: string description: An identifier for the upload. examples: - 6c81cd8e-b078-4ac3-a3be-1dad7dbd0b53 code-scanning-analysis-commit-sha: description: The SHA of the commit to which the analysis you are uploading relates. type: string minLength: 40 maxLength: 40 pattern: "^[0-9a-fA-F]+$" code-scanning-analysis-environment: type: string description: Identifies the variable values associated with the environment in which this analysis was performed. code-scanning-analysis-created-at: type: string description: 'The time that the analysis was created in ISO 8601 format: `YYYY-MM-DDTHH:MM:SSZ`.' format: date-time readOnly: true code-scanning-analysis-url: type: string description: The REST API URL of the analysis resource. format: uri readOnly: true code-scanning-analysis: type: object properties: ref: "$ref": "#/components/schemas/code-scanning-ref" commit_sha: "$ref": "#/components/schemas/code-scanning-analysis-commit-sha" analysis_key: "$ref": "#/components/schemas/code-scanning-analysis-analysis-key" environment: "$ref": "#/components/schemas/code-scanning-analysis-environment" category: "$ref": "#/components/schemas/code-scanning-analysis-category" error: type: string examples: - error reading field xyz created_at: "$ref": "#/components/schemas/code-scanning-analysis-created-at" results_count: type: integer description: The total number of results in the analysis. rules_count: type: integer description: The total number of rules used in the analysis. id: type: integer description: Unique identifier for this analysis. url: "$ref": "#/components/schemas/code-scanning-analysis-url" sarif_id: "$ref": "#/components/schemas/code-scanning-analysis-sarif-id" tool: "$ref": "#/components/schemas/code-scanning-analysis-tool" deletable: type: boolean warning: type: string description: Warning generated when processing the analysis examples: - 123 results were ignored tool_name: type: string required: - ref - commit_sha - analysis_key - environment - error - created_at - results_count - rules_count - id - url - sarif_id - tool - deletable - warning code-scanning-analysis-sarif-file: description: A Base64 string representing the SARIF file to upload. You must first compress your SARIF file using [`gzip`](http://www.gnu.org/software/gzip/manual/gzip.html) and then translate the contents of the file into a Base64 encoding string. For more information, see "[SARIF support for code scanning](https://docs.github.com/enterprise-server@3.0/code-security/secure-coding/sarif-support-for-code-scanning)." type: string code-scanning-sarifs-receipt: type: object properties: id: "$ref": "#/components/schemas/code-scanning-analysis-sarif-id" url: type: string description: The REST API URL for checking the status of the upload. format: uri readOnly: true collaborator: title: Collaborator description: Collaborator type: object properties: login: type: string examples: - octocat id: type: integer examples: - 1 email: type: - string - 'null' name: type: - string - 'null' node_id: type: string examples: - MDQ6VXNlcjE= avatar_url: type: string format: uri examples: - https://github.com/images/error/octocat_happy.gif gravatar_id: type: - string - 'null' examples: - 41d064eb2195891e12d0413f63227ea7 url: type: string format: uri examples: - https://api.github.com/users/octocat html_url: type: string format: uri examples: - https://github.com/octocat followers_url: type: string format: uri examples: - https://api.github.com/users/octocat/followers following_url: type: string examples: - https://api.github.com/users/octocat/following{/other_user} gists_url: type: string examples: - https://api.github.com/users/octocat/gists{/gist_id} starred_url: type: string examples: - https://api.github.com/users/octocat/starred{/owner}{/repo} subscriptions_url: type: string format: uri examples: - https://api.github.com/users/octocat/subscriptions organizations_url: type: string format: uri examples: - https://api.github.com/users/octocat/orgs repos_url: type: string format: uri examples: - https://api.github.com/users/octocat/repos events_url: type: string examples: - https://api.github.com/users/octocat/events{/privacy} received_events_url: type: string format: uri examples: - https://api.github.com/users/octocat/received_events type: type: string examples: - User site_admin: type: boolean permissions: type: object properties: pull: type: boolean triage: type: boolean push: type: boolean maintain: type: boolean admin: type: boolean required: - pull - push - admin required: - avatar_url - events_url - followers_url - following_url - gists_url - gravatar_id - html_url - id - node_id - login - organizations_url - received_events_url - repos_url - site_admin - starred_url - subscriptions_url - type - url repository-invitation: title: Repository Invitation description: Repository invitations let you manage who you collaborate with. type: object properties: id: description: Unique identifier of the repository invitation. type: integer examples: - 42 repository: "$ref": "#/components/schemas/minimal-repository" invitee: anyOf: - type: 'null' - "$ref": "#/components/schemas/simple-user" inviter: anyOf: - type: 'null' - "$ref": "#/components/schemas/simple-user" permissions: description: The permission associated with the invitation. type: string enum: - read - write - admin - triage - maintain examples: - read created_at: type: string format: date-time examples: - '2016-06-13T14:52:50-05:00' expired: description: Whether or not the invitation has expired type: boolean url: description: URL for the repository invitation type: string examples: - https://api.github.com/user/repository-invitations/1 html_url: type: string examples: - https://github.com/octocat/Hello-World/invitations node_id: type: string required: - id - node_id - permissions - inviter - invitee - repository - url - html_url - created_at repository-collaborator-permission: title: Repository Collaborator Permission description: Repository Collaborator Permission type: object properties: permission: type: string user: anyOf: - type: 'null' - "$ref": "#/components/schemas/collaborator" required: - permission - user commit-comment: title: Commit Comment description: Commit Comment type: object properties: html_url: type: string format: uri url: type: string format: uri id: type: integer node_id: type: string body: type: string path: type: - string - 'null' position: type: - integer - 'null' line: type: - integer - 'null' commit_id: type: string user: anyOf: - type: 'null' - "$ref": "#/components/schemas/simple-user" created_at: type: string format: date-time updated_at: type: string format: date-time author_association: "$ref": "#/components/schemas/author_association" reactions: "$ref": "#/components/schemas/reaction-rollup" required: - url - html_url - id - node_id - user - position - line - path - commit_id - body - author_association - created_at - updated_at scim-error: title: Scim Error description: Scim Error type: object properties: message: type: - string - 'null' documentation_url: type: - string - 'null' detail: type: - string - 'null' status: type: integer scimType: type: - string - 'null' schemas: type: array items: type: string branch-short: title: Branch Short description: Branch Short type: object properties: name: type: string commit: type: object properties: sha: type: string url: type: string required: - sha - url protected: type: boolean required: - name - commit - protected link: title: Link description: Hypermedia Link type: object properties: href: type: string required: - href pull-request-simple: title: Pull Request Simple description: Pull Request Simple type: object properties: url: type: string format: uri examples: - https://api.github.com/repos/octocat/Hello-World/pulls/1347 id: type: integer examples: - 1 node_id: type: string examples: - MDExOlB1bGxSZXF1ZXN0MQ== html_url: type: string format: uri examples: - https://github.com/octocat/Hello-World/pull/1347 diff_url: type: string format: uri examples: - https://github.com/octocat/Hello-World/pull/1347.diff patch_url: type: string format: uri examples: - https://github.com/octocat/Hello-World/pull/1347.patch issue_url: type: string format: uri examples: - https://api.github.com/repos/octocat/Hello-World/issues/1347 commits_url: type: string format: uri examples: - https://api.github.com/repos/octocat/Hello-World/pulls/1347/commits review_comments_url: type: string format: uri examples: - https://api.github.com/repos/octocat/Hello-World/pulls/1347/comments review_comment_url: type: string examples: - https://api.github.com/repos/octocat/Hello-World/pulls/comments{/number} comments_url: type: string format: uri examples: - https://api.github.com/repos/octocat/Hello-World/issues/1347/comments statuses_url: type: string format: uri examples: - https://api.github.com/repos/octocat/Hello-World/statuses/6dcb09b5b57875f334f61aebed695e2e4193db5e number: type: integer examples: - 1347 state: type: string examples: - open locked: type: boolean examples: - true title: type: string examples: - new-feature user: anyOf: - type: 'null' - "$ref": "#/components/schemas/simple-user" body: type: - string - 'null' examples: - Please pull these awesome changes labels: type: array items: type: object properties: id: type: integer format: int64 node_id: type: string url: type: string name: type: string description: type: string color: type: string default: type: boolean required: - id - node_id - url - name - description - color - default milestone: anyOf: - type: 'null' - "$ref": "#/components/schemas/milestone" active_lock_reason: type: - string - 'null' examples: - too heated created_at: type: string format: date-time examples: - '2011-01-26T19:01:12Z' updated_at: type: string format: date-time examples: - '2011-01-26T19:01:12Z' closed_at: type: - string - 'null' format: date-time examples: - '2011-01-26T19:01:12Z' merged_at: type: - string - 'null' format: date-time examples: - '2011-01-26T19:01:12Z' merge_commit_sha: type: - string - 'null' examples: - e5bd3914e2e596debea16f433f57875b5b90bcd6 assignee: anyOf: - type: 'null' - "$ref": "#/components/schemas/simple-user" assignees: type: - array - 'null' items: "$ref": "#/components/schemas/simple-user" requested_reviewers: type: - array - 'null' items: "$ref": "#/components/schemas/simple-user" requested_teams: type: - array - 'null' items: "$ref": "#/components/schemas/team" head: type: object properties: label: type: string ref: type: string repo: "$ref": "#/components/schemas/repository" sha: type: string user: anyOf: - type: 'null' - "$ref": "#/components/schemas/simple-user" required: - label - ref - repo - sha - user base: type: object properties: label: type: string ref: type: string repo: "$ref": "#/components/schemas/repository" sha: type: string user: anyOf: - type: 'null' - "$ref": "#/components/schemas/simple-user" required: - label - ref - repo - sha - user _links: type: object properties: comments: "$ref": "#/components/schemas/link" commits: "$ref": "#/components/schemas/link" statuses: "$ref": "#/components/schemas/link" html: "$ref": "#/components/schemas/link" issue: "$ref": "#/components/schemas/link" review_comments: "$ref": "#/components/schemas/link" review_comment: "$ref": "#/components/schemas/link" self: "$ref": "#/components/schemas/link" required: - comments - commits - statuses - html - issue - review_comments - review_comment - self author_association: "$ref": "#/components/schemas/author_association" draft: description: Indicates whether or not the pull request is a draft. type: boolean examples: - false required: - _links - assignee - labels - base - body - closed_at - comments_url - commits_url - created_at - diff_url - head - html_url - id - node_id - issue_url - merge_commit_sha - merged_at - milestone - number - patch_url - review_comment_url - review_comments_url - statuses_url - state - locked - title - updated_at - url - user - author_association simple-commit-status: title: Simple Commit Status type: object properties: description: type: - string - 'null' id: type: integer node_id: type: string state: type: string context: type: string target_url: type: string format: uri required: type: - boolean - 'null' avatar_url: type: - string - 'null' format: uri url: type: string format: uri created_at: type: string format: date-time updated_at: type: string format: date-time required: - description - id - node_id - state - context - target_url - avatar_url - url - created_at - updated_at combined-commit-status: title: Combined Commit Status description: Combined Commit Status type: object properties: state: type: string statuses: type: array items: "$ref": "#/components/schemas/simple-commit-status" sha: type: string total_count: type: integer repository: "$ref": "#/components/schemas/minimal-repository" commit_url: type: string format: uri url: type: string format: uri required: - state - sha - total_count - statuses - repository - commit_url - url status: title: Status description: The status of a commit. type: object properties: url: type: string avatar_url: type: - string - 'null' id: type: integer node_id: type: string state: type: string description: type: string target_url: type: string context: type: string created_at: type: string updated_at: type: string creator: anyOf: - type: 'null' - "$ref": "#/components/schemas/simple-user" required: - url - avatar_url - id - node_id - state - description - target_url - context - created_at - updated_at - creator commit-comparison: title: Commit Comparison description: Commit Comparison type: object properties: url: type: string format: uri examples: - https://api.github.com/repos/octocat/Hello-World/compare/master...topic html_url: type: string format: uri examples: - https://github.com/octocat/Hello-World/compare/master...topic permalink_url: type: string format: uri examples: - https://github.com/octocat/Hello-World/compare/octocat:bbcd538c8e72b8c175046e27cc8f907076331401...octocat:0328041d1152db8ae77652d1618a02e57f745f17 diff_url: type: string format: uri examples: - https://github.com/octocat/Hello-World/compare/master...topic.diff patch_url: type: string format: uri examples: - https://github.com/octocat/Hello-World/compare/master...topic.patch base_commit: "$ref": "#/components/schemas/commit" merge_base_commit: "$ref": "#/components/schemas/commit" status: type: string enum: - diverged - ahead - behind - identical examples: - ahead ahead_by: type: integer examples: - 4 behind_by: type: integer examples: - 5 total_commits: type: integer examples: - 6 commits: type: array items: "$ref": "#/components/schemas/commit" files: type: array items: "$ref": "#/components/schemas/diff-entry" required: - url - html_url - permalink_url - diff_url - patch_url - base_commit - merge_base_commit - status - ahead_by - behind_by - total_commits - commits content-reference-attachment: title: ContentReferenceAttachment description: Content Reference attachments allow you to provide context around URLs posted in comments type: object properties: id: description: The ID of the attachment type: integer examples: - 21 title: description: The title of the attachment type: string maxLength: 1024 examples: - Title of the attachment body: description: The body of the attachment type: string maxLength: 262144 examples: - Body of the attachment node_id: description: The node_id of the content attachment type: string examples: - MDE3OkNvbnRlbnRBdHRhY2htZW50MjE= required: - id - title - body content-tree: title: Content Tree description: Content Tree type: object properties: type: type: string size: type: integer name: type: string path: type: string sha: type: string url: type: string format: uri git_url: type: - string - 'null' format: uri html_url: type: - string - 'null' format: uri download_url: type: - string - 'null' format: uri entries: type: array items: type: object properties: type: type: string size: type: integer name: type: string path: type: string content: type: string sha: type: string url: type: string format: uri git_url: type: - string - 'null' format: uri html_url: type: - string - 'null' format: uri download_url: type: - string - 'null' format: uri _links: type: object properties: git: type: - string - 'null' format: uri html: type: - string - 'null' format: uri self: type: string format: uri required: - git - html - self required: - _links - git_url - html_url - download_url - name - path - sha - size - type - url _links: type: object properties: git: type: - string - 'null' format: uri html: type: - string - 'null' format: uri self: type: string format: uri required: - git - html - self required: - _links - git_url - html_url - download_url - name - path - sha - size - type - url - content - encoding content-directory: title: Content Directory description: A list of directory items type: array items: type: object properties: type: type: string size: type: integer name: type: string path: type: string content: type: string sha: type: string url: type: string format: uri git_url: type: - string - 'null' format: uri html_url: type: - string - 'null' format: uri download_url: type: - string - 'null' format: uri _links: type: object properties: git: type: - string - 'null' format: uri html: type: - string - 'null' format: uri self: type: string format: uri required: - git - html - self required: - _links - git_url - html_url - download_url - name - path - sha - size - type - url content-file: title: Content File description: Content File type: object properties: type: type: string encoding: type: string size: type: integer name: type: string path: type: string content: type: string sha: type: string url: type: string format: uri git_url: type: - string - 'null' format: uri html_url: type: - string - 'null' format: uri download_url: type: - string - 'null' format: uri _links: type: object properties: git: type: - string - 'null' format: uri html: type: - string - 'null' format: uri self: type: string format: uri required: - git - html - self target: type: string examples: - '"actual/actual.md"' submodule_git_url: type: string examples: - '"git://example.com/defunkt/dotjs.git"' required: - _links - git_url - html_url - download_url - name - path - sha - size - type - url - content - encoding content-symlink: title: Symlink Content description: An object describing a symlink type: object properties: type: type: string target: type: string size: type: integer name: type: string path: type: string sha: type: string url: type: string format: uri git_url: type: - string - 'null' format: uri html_url: type: - string - 'null' format: uri download_url: type: - string - 'null' format: uri _links: type: object properties: git: type: - string - 'null' format: uri html: type: - string - 'null' format: uri self: type: string format: uri required: - git - html - self required: - _links - git_url - html_url - download_url - name - path - sha - size - type - url - target content-submodule: title: Symlink Content description: An object describing a symlink type: object properties: type: type: string submodule_git_url: type: string format: uri size: type: integer name: type: string path: type: string sha: type: string url: type: string format: uri git_url: type: - string - 'null' format: uri html_url: type: - string - 'null' format: uri download_url: type: - string - 'null' format: uri _links: type: object properties: git: type: - string - 'null' format: uri html: type: - string - 'null' format: uri self: type: string format: uri required: - git - html - self required: - _links - git_url - html_url - download_url - name - path - sha - size - type - url - submodule_git_url file-commit: title: File Commit description: File Commit type: object required: - content - commit properties: content: type: - object - 'null' properties: name: type: string path: type: string sha: type: string size: type: integer url: type: string html_url: type: string git_url: type: string download_url: type: string type: type: string _links: type: object properties: self: type: string git: type: string html: type: string commit: type: object properties: sha: type: string node_id: type: string url: type: string html_url: type: string author: type: object properties: date: type: string name: type: string email: type: string committer: type: object properties: date: type: string name: type: string email: type: string message: type: string tree: type: object properties: url: type: string sha: type: string parents: type: array items: type: object properties: url: type: string html_url: type: string sha: type: string verification: type: object properties: verified: type: boolean reason: type: string signature: type: - string - 'null' payload: type: - string - 'null' contributor: title: Contributor description: Contributor type: object properties: login: type: string id: type: integer node_id: type: string avatar_url: type: string format: uri gravatar_id: type: - string - 'null' url: type: string format: uri html_url: type: string format: uri followers_url: type: string format: uri following_url: type: string gists_url: type: string starred_url: type: string subscriptions_url: type: string format: uri organizations_url: type: string format: uri repos_url: type: string format: uri events_url: type: string received_events_url: type: string format: uri type: type: string site_admin: type: boolean contributions: type: integer email: type: string name: type: string required: - contributions - type deployment: title: Deployment description: A request for a specific ref(branch,sha,tag) to be deployed type: object properties: url: type: string format: uri examples: - https://api.github.com/repos/octocat/example/deployments/1 id: description: Unique identifier of the deployment type: integer examples: - 42 node_id: type: string examples: - MDEwOkRlcGxveW1lbnQx sha: type: string examples: - a84d88e7554fc1fa21bcbc4efae3c782a70d2b9d ref: description: The ref to deploy. This can be a branch, tag, or sha. type: string examples: - topic-branch task: description: Parameter to specify a task to execute type: string examples: - deploy payload: oneOf: - type: object additionalProperties: true - type: string original_environment: type: string examples: - staging environment: description: Name for the target deployment environment. type: string examples: - production description: type: - string - 'null' examples: - Deploy request from hubot creator: anyOf: - type: 'null' - "$ref": "#/components/schemas/simple-user" created_at: type: string format: date-time examples: - '2012-07-20T01:19:13Z' updated_at: type: string format: date-time examples: - '2012-07-20T01:19:13Z' statuses_url: type: string format: uri examples: - https://api.github.com/repos/octocat/example/deployments/1/statuses repository_url: type: string format: uri examples: - https://api.github.com/repos/octocat/example transient_environment: description: 'Specifies if the given environment is will no longer exist at some point in the future. Default: false.' type: boolean examples: - true production_environment: description: 'Specifies if the given environment is one that end-users directly interact with. Default: false.' type: boolean examples: - true performed_via_github_app: anyOf: - type: 'null' - "$ref": "#/components/schemas/integration" required: - id - node_id - sha - ref - task - environment - creator - payload - description - statuses_url - repository_url - url - created_at - updated_at deployment-status: title: Deployment Status description: The status of a deployment. type: object properties: url: type: string format: uri examples: - https://api.github.com/repos/octocat/example/deployments/42/statuses/1 id: type: integer examples: - 1 node_id: type: string examples: - MDE2OkRlcGxveW1lbnRTdGF0dXMx state: description: The state of the status. enum: - error - failure - inactive - pending - success - queued - in_progress type: string examples: - success creator: anyOf: - type: 'null' - "$ref": "#/components/schemas/simple-user" description: description: A short description of the status. default: '' type: string maxLength: 140 examples: - Deployment finished successfully. environment: description: The environment of the deployment that the status is for. default: '' type: string examples: - production target_url: description: 'Deprecated: the URL to associate with this status.' default: '' type: string format: uri examples: - https://example.com/deployment/42/output created_at: type: string format: date-time examples: - '2012-07-20T01:19:13Z' updated_at: type: string format: date-time examples: - '2012-07-20T01:19:13Z' deployment_url: type: string format: uri examples: - https://api.github.com/repos/octocat/example/deployments/42 repository_url: type: string format: uri examples: - https://api.github.com/repos/octocat/example environment_url: description: The URL for accessing your environment. default: '' type: string format: uri examples: - https://staging.example.com/ log_url: description: The URL to associate with this status. default: '' type: string format: uri examples: - https://example.com/deployment/42/output performed_via_github_app: anyOf: - type: 'null' - "$ref": "#/components/schemas/integration" required: - id - node_id - state - creator - description - deployment_url - target_url - repository_url - url - created_at - updated_at short-blob: title: Short Blob description: Short Blob type: object properties: url: type: string sha: type: string required: - url - sha blob: title: Blob description: Blob type: object properties: content: type: string encoding: type: string url: type: string format: uri sha: type: string size: type: - integer - 'null' node_id: type: string highlighted_content: type: string required: - sha - url - node_id - size - content - encoding git-commit: title: Git Commit description: Low-level Git commit operations within a repository type: object properties: sha: description: SHA for the commit type: string examples: - 7638417db6d59f3c431d3e1f261cc637155684cd node_id: type: string url: type: string format: uri author: description: Identifying information for the git-user type: object properties: date: description: Timestamp of the commit format: date-time type: string examples: - '2014-08-09T08:02:04+12:00' email: type: string description: Git email address of the user examples: - monalisa.octocat@example.com name: description: Name of the git user type: string examples: - Monalisa Octocat required: - email - name - date committer: description: Identifying information for the git-user type: object properties: date: description: Timestamp of the commit format: date-time type: string examples: - '2014-08-09T08:02:04+12:00' email: type: string description: Git email address of the user examples: - monalisa.octocat@example.com name: description: Name of the git user type: string examples: - Monalisa Octocat required: - email - name - date message: description: Message describing the purpose of the commit type: string examples: - 'Fix #42' tree: type: object properties: sha: description: SHA for the commit type: string examples: - 7638417db6d59f3c431d3e1f261cc637155684cd url: type: string format: uri required: - sha - url parents: type: array items: type: object properties: sha: description: SHA for the commit type: string examples: - 7638417db6d59f3c431d3e1f261cc637155684cd url: type: string format: uri html_url: type: string format: uri required: - sha - url - html_url verification: type: object properties: verified: type: boolean reason: type: string signature: type: - string - 'null' payload: type: - string - 'null' required: - verified - reason - signature - payload html_url: type: string format: uri required: - sha - node_id - url - html_url - author - committer - tree - message - parents - verification git-ref: title: Git Reference description: Git references within a repository type: object properties: ref: type: string node_id: type: string url: type: string format: uri object: type: object properties: type: type: string sha: description: SHA for the reference type: string minLength: 40 maxLength: 40 examples: - 7638417db6d59f3c431d3e1f261cc637155684cd url: type: string format: uri required: - type - sha - url required: - ref - node_id - url - object git-tag: title: Git Tag description: Metadata for a Git tag type: object properties: node_id: type: string examples: - MDM6VGFnOTQwYmQzMzYyNDhlZmFlMGY5ZWU1YmM3YjJkNWM5ODU4ODdiMTZhYw== tag: description: Name of the tag type: string examples: - v0.0.1 sha: type: string examples: - 940bd336248efae0f9ee5bc7b2d5c985887b16ac url: description: URL for the tag type: string format: uri examples: - https://api.github.com/repositories/42/git/tags/940bd336248efae0f9ee5bc7b2d5c985887b16ac message: description: Message describing the purpose of the tag type: string examples: - Initial public release tagger: type: object properties: date: type: string email: type: string name: type: string required: - date - email - name object: type: object properties: sha: type: string type: type: string url: type: string format: uri required: - sha - type - url verification: "$ref": "#/components/schemas/verification" required: - sha - url - node_id - tagger - object - tag - message git-tree: title: Git Tree description: The hierarchy between files in a Git repository. type: object properties: sha: type: string url: type: string format: uri truncated: type: boolean tree: description: Objects specifying a tree structure type: array items: type: object properties: path: type: string examples: - test/file.rb mode: type: string examples: - '040000' type: type: string examples: - tree sha: type: string examples: - 23f6827669e43831def8a7ad935069c8bd418261 size: type: integer examples: - 12 url: type: string examples: - https://api.github.com/repos/owner-482f3203ecf01f67e9deb18e/BBB_Private_Repo/git/blobs/23f6827669e43831def8a7ad935069c8bd418261 examples: - path: file.rb mode: '100644' type: blob size: 30 sha: 44b4fc6d56897b048c772eb4087f854f46256132 url: https://api.github.com/repos/octocat/Hello-World/git/blobs/44b4fc6d56897b048c772eb4087f854f46256132 properties: path: type: string mode: type: string type: type: string size: type: integer sha: type: string url: type: string required: - path - mode - type - sha - url - size required: - sha - url - tree - truncated hook-response: title: Hook Response type: object properties: code: type: - integer - 'null' status: type: - string - 'null' message: type: - string - 'null' required: - code - status - message hook: title: Webhook description: Webhooks for repositories. type: object properties: type: type: string id: description: Unique identifier of the webhook. type: integer examples: - 42 name: description: The name of a valid service, use 'web' for a webhook. type: string examples: - web active: description: Determines whether the hook is actually triggered on pushes. type: boolean examples: - true events: description: 'Determines what events the hook is triggered for. Default: [''push''].' type: array items: type: string examples: - push - pull_request config: type: object properties: email: type: string examples: - '"foo@bar.com"' password: type: string examples: - '"foo"' room: type: string examples: - '"roomer"' subdomain: type: string examples: - '"foo"' url: "$ref": "#/components/schemas/webhook-config-url" insecure_ssl: "$ref": "#/components/schemas/webhook-config-insecure-ssl" content_type: "$ref": "#/components/schemas/webhook-config-content-type" digest: type: string examples: - '"sha256"' secret: "$ref": "#/components/schemas/webhook-config-secret" token: type: string examples: - '"abc"' updated_at: type: string format: date-time examples: - '2011-09-06T20:39:23Z' created_at: type: string format: date-time examples: - '2011-09-06T17:26:27Z' url: type: string format: uri examples: - https://api.github.com/repos/octocat/Hello-World/hooks/1 test_url: type: string format: uri examples: - https://api.github.com/repos/octocat/Hello-World/hooks/1/test ping_url: type: string format: uri examples: - https://api.github.com/repos/octocat/Hello-World/hooks/1/pings last_response: "$ref": "#/components/schemas/hook-response" required: - id - url - type - name - active - events - config - ping_url - created_at - updated_at - last_response - test_url issue-event-label: title: Issue Event Label description: Issue Event Label type: object properties: name: type: - string - 'null' color: type: - string - 'null' required: - name - color issue-event-dismissed-review: title: Issue Event Dismissed Review type: object properties: state: type: string review_id: type: integer dismissal_message: type: - string - 'null' dismissal_commit_id: type: - string - 'null' required: - state - review_id - dismissal_message issue-event-milestone: title: Issue Event Milestone description: Issue Event Milestone type: object properties: title: type: string required: - title issue-event-project-card: title: Issue Event Project Card description: Issue Event Project Card type: object properties: url: type: string format: uri id: type: integer project_url: type: string format: uri project_id: type: integer column_name: type: string previous_column_name: type: string required: - url - id - project_url - project_id - column_name issue-event-rename: title: Issue Event Rename description: Issue Event Rename type: object properties: from: type: string to: type: string required: - from - to issue-event: title: Issue Event description: Issue Event type: object properties: id: type: integer examples: - 1 node_id: type: string examples: - MDEwOklzc3VlRXZlbnQx url: type: string format: uri examples: - https://api.github.com/repos/octocat/Hello-World/issues/events/1 actor: anyOf: - type: 'null' - "$ref": "#/components/schemas/simple-user" event: type: string examples: - closed commit_id: type: - string - 'null' examples: - 6dcb09b5b57875f334f61aebed695e2e4193db5e commit_url: type: - string - 'null' examples: - https://api.github.com/repos/octocat/Hello-World/commits/6dcb09b5b57875f334f61aebed695e2e4193db5e created_at: type: string format: date-time examples: - '2011-04-14T16:00:49Z' issue: anyOf: - type: 'null' - "$ref": "#/components/schemas/issue" label: "$ref": "#/components/schemas/issue-event-label" assignee: anyOf: - type: 'null' - "$ref": "#/components/schemas/simple-user" assigner: anyOf: - type: 'null' - "$ref": "#/components/schemas/simple-user" review_requester: anyOf: - type: 'null' - "$ref": "#/components/schemas/simple-user" requested_reviewer: anyOf: - type: 'null' - "$ref": "#/components/schemas/simple-user" requested_team: "$ref": "#/components/schemas/team" dismissed_review: "$ref": "#/components/schemas/issue-event-dismissed-review" milestone: "$ref": "#/components/schemas/issue-event-milestone" project_card: "$ref": "#/components/schemas/issue-event-project-card" rename: "$ref": "#/components/schemas/issue-event-rename" author_association: "$ref": "#/components/schemas/author_association" lock_reason: type: - string - 'null' performed_via_github_app: anyOf: - type: 'null' - "$ref": "#/components/schemas/integration" required: - id - node_id - url - actor - event - commit_id - commit_url - created_at labeled-issue-event: title: Labeled Issue Event description: Labeled Issue Event type: object properties: id: type: integer node_id: type: string url: type: string actor: "$ref": "#/components/schemas/simple-user" event: type: string commit_id: type: - string - 'null' commit_url: type: - string - 'null' created_at: type: string performed_via_github_app: anyOf: - type: 'null' - "$ref": "#/components/schemas/integration" label: type: object properties: name: type: string color: type: string required: - name - color required: - label - id - node_id - url - actor - event - commit_id - commit_url - created_at - performed_via_github_app unlabeled-issue-event: title: Unlabeled Issue Event description: Unlabeled Issue Event type: object properties: id: type: integer node_id: type: string url: type: string actor: "$ref": "#/components/schemas/simple-user" event: type: string commit_id: type: - string - 'null' commit_url: type: - string - 'null' created_at: type: string performed_via_github_app: anyOf: - type: 'null' - "$ref": "#/components/schemas/integration" label: type: object properties: name: type: string color: type: string required: - name - color required: - label - id - node_id - url - actor - event - commit_id - commit_url - created_at - performed_via_github_app assigned-issue-event: title: Assigned Issue Event description: Assigned Issue Event type: object properties: id: type: integer node_id: type: string url: type: string actor: "$ref": "#/components/schemas/simple-user" event: type: string commit_id: type: - string - 'null' commit_url: type: - string - 'null' created_at: type: string performed_via_github_app: "$ref": "#/components/schemas/integration" assignee: "$ref": "#/components/schemas/simple-user" assigner: "$ref": "#/components/schemas/simple-user" required: - id - node_id - url - actor - event - commit_id - commit_url - created_at - performed_via_github_app - assignee - assigner unassigned-issue-event: title: Unassigned Issue Event description: Unassigned Issue Event type: object properties: id: type: integer node_id: type: string url: type: string actor: "$ref": "#/components/schemas/simple-user" event: type: string commit_id: type: - string - 'null' commit_url: type: - string - 'null' created_at: type: string performed_via_github_app: anyOf: - type: 'null' - "$ref": "#/components/schemas/integration" assignee: "$ref": "#/components/schemas/simple-user" assigner: "$ref": "#/components/schemas/simple-user" required: - id - node_id - url - actor - event - commit_id - commit_url - created_at - performed_via_github_app - assignee - assigner milestoned-issue-event: title: Milestoned Issue Event description: Milestoned Issue Event type: object properties: id: type: integer node_id: type: string url: type: string actor: "$ref": "#/components/schemas/simple-user" event: type: string commit_id: type: - string - 'null' commit_url: type: - string - 'null' created_at: type: string performed_via_github_app: anyOf: - type: 'null' - "$ref": "#/components/schemas/integration" milestone: type: object properties: title: type: string required: - title required: - milestone - id - node_id - url - actor - event - commit_id - commit_url - created_at - performed_via_github_app demilestoned-issue-event: title: Demilestoned Issue Event description: Demilestoned Issue Event type: object properties: id: type: integer node_id: type: string url: type: string actor: "$ref": "#/components/schemas/simple-user" event: type: string commit_id: type: - string - 'null' commit_url: type: - string - 'null' created_at: type: string performed_via_github_app: anyOf: - type: 'null' - "$ref": "#/components/schemas/integration" milestone: type: object properties: title: type: string required: - title required: - milestone - id - node_id - url - actor - event - commit_id - commit_url - created_at - performed_via_github_app renamed-issue-event: title: Renamed Issue Event description: Renamed Issue Event type: object properties: id: type: integer node_id: type: string url: type: string actor: "$ref": "#/components/schemas/simple-user" event: type: string commit_id: type: - string - 'null' commit_url: type: - string - 'null' created_at: type: string performed_via_github_app: anyOf: - type: 'null' - "$ref": "#/components/schemas/integration" rename: type: object properties: from: type: string to: type: string required: - from - to required: - rename - id - node_id - url - actor - event - commit_id - commit_url - created_at - performed_via_github_app review-requested-issue-event: title: Review Requested Issue Event description: Review Requested Issue Event type: object properties: id: type: integer node_id: type: string url: type: string actor: "$ref": "#/components/schemas/simple-user" event: type: string commit_id: type: - string - 'null' commit_url: type: - string - 'null' created_at: type: string performed_via_github_app: anyOf: - type: 'null' - "$ref": "#/components/schemas/integration" review_requester: "$ref": "#/components/schemas/simple-user" requested_team: "$ref": "#/components/schemas/team" requested_reviewer: "$ref": "#/components/schemas/simple-user" required: - review_requester - id - node_id - url - actor - event - commit_id - commit_url - created_at - performed_via_github_app review-request-removed-issue-event: title: Review Request Removed Issue Event description: Review Request Removed Issue Event type: object properties: id: type: integer node_id: type: string url: type: string actor: "$ref": "#/components/schemas/simple-user" event: type: string commit_id: type: - string - 'null' commit_url: type: - string - 'null' created_at: type: string performed_via_github_app: anyOf: - type: 'null' - "$ref": "#/components/schemas/integration" review_requester: "$ref": "#/components/schemas/simple-user" requested_team: "$ref": "#/components/schemas/team" requested_reviewer: "$ref": "#/components/schemas/simple-user" required: - review_requester - id - node_id - url - actor - event - commit_id - commit_url - created_at - performed_via_github_app review-dismissed-issue-event: title: Review Dismissed Issue Event description: Review Dismissed Issue Event type: object properties: id: type: integer node_id: type: string url: type: string actor: "$ref": "#/components/schemas/simple-user" event: type: string commit_id: type: - string - 'null' commit_url: type: - string - 'null' created_at: type: string performed_via_github_app: anyOf: - type: 'null' - "$ref": "#/components/schemas/integration" dismissed_review: type: object properties: state: type: string review_id: type: integer dismissal_message: type: - string - 'null' dismissal_commit_id: type: string required: - state - review_id - dismissal_message required: - dismissed_review - id - node_id - url - actor - event - commit_id - commit_url - created_at - performed_via_github_app locked-issue-event: title: Locked Issue Event description: Locked Issue Event type: object properties: id: type: integer node_id: type: string url: type: string actor: "$ref": "#/components/schemas/simple-user" event: type: string commit_id: type: - string - 'null' commit_url: type: - string - 'null' created_at: type: string performed_via_github_app: anyOf: - type: 'null' - "$ref": "#/components/schemas/integration" lock_reason: type: - string - 'null' examples: - '"off-topic"' required: - lock_reason - id - node_id - url - actor - event - commit_id - commit_url - created_at - performed_via_github_app added-to-project-issue-event: title: Added to Project Issue Event description: Added to Project Issue Event type: object properties: id: type: integer node_id: type: string url: type: string actor: "$ref": "#/components/schemas/simple-user" event: type: string commit_id: type: - string - 'null' commit_url: type: - string - 'null' created_at: type: string performed_via_github_app: anyOf: - type: 'null' - "$ref": "#/components/schemas/integration" project_card: type: object properties: id: type: integer url: type: string format: uri project_id: type: integer project_url: type: string format: uri column_name: type: string previous_column_name: type: string required: - id - url - project_id - project_url - column_name required: - id - node_id - url - actor - event - commit_id - commit_url - created_at - performed_via_github_app moved-column-in-project-issue-event: title: Moved Column in Project Issue Event description: Moved Column in Project Issue Event type: object properties: id: type: integer node_id: type: string url: type: string actor: "$ref": "#/components/schemas/simple-user" event: type: string commit_id: type: - string - 'null' commit_url: type: - string - 'null' created_at: type: string performed_via_github_app: anyOf: - type: 'null' - "$ref": "#/components/schemas/integration" project_card: type: object properties: id: type: integer url: type: string format: uri project_id: type: integer project_url: type: string format: uri column_name: type: string previous_column_name: type: string required: - id - url - project_id - project_url - column_name required: - id - node_id - url - actor - event - commit_id - commit_url - created_at - performed_via_github_app removed-from-project-issue-event: title: Removed from Project Issue Event description: Removed from Project Issue Event type: object properties: id: type: integer node_id: type: string url: type: string actor: "$ref": "#/components/schemas/simple-user" event: type: string commit_id: type: - string - 'null' commit_url: type: - string - 'null' created_at: type: string performed_via_github_app: anyOf: - type: 'null' - "$ref": "#/components/schemas/integration" project_card: type: object properties: id: type: integer url: type: string format: uri project_id: type: integer project_url: type: string format: uri column_name: type: string previous_column_name: type: string required: - id - url - project_id - project_url - column_name required: - id - node_id - url - actor - event - commit_id - commit_url - created_at - performed_via_github_app converted-note-to-issue-issue-event: title: Converted Note to Issue Issue Event description: Converted Note to Issue Issue Event type: object properties: id: type: integer node_id: type: string url: type: string actor: "$ref": "#/components/schemas/simple-user" event: type: string commit_id: type: - string - 'null' commit_url: type: - string - 'null' created_at: type: string performed_via_github_app: "$ref": "#/components/schemas/integration" project_card: type: object properties: id: type: integer url: type: string format: uri project_id: type: integer project_url: type: string format: uri column_name: type: string previous_column_name: type: string required: - id - url - project_id - project_url - column_name required: - id - node_id - url - actor - event - commit_id - commit_url - created_at - performed_via_github_app issue-event-for-issue: title: Issue Event for Issue description: Issue Event for Issue anyOf: - "$ref": "#/components/schemas/labeled-issue-event" - "$ref": "#/components/schemas/unlabeled-issue-event" - "$ref": "#/components/schemas/assigned-issue-event" - "$ref": "#/components/schemas/unassigned-issue-event" - "$ref": "#/components/schemas/milestoned-issue-event" - "$ref": "#/components/schemas/demilestoned-issue-event" - "$ref": "#/components/schemas/renamed-issue-event" - "$ref": "#/components/schemas/review-requested-issue-event" - "$ref": "#/components/schemas/review-request-removed-issue-event" - "$ref": "#/components/schemas/review-dismissed-issue-event" - "$ref": "#/components/schemas/locked-issue-event" - "$ref": "#/components/schemas/added-to-project-issue-event" - "$ref": "#/components/schemas/moved-column-in-project-issue-event" - "$ref": "#/components/schemas/removed-from-project-issue-event" - "$ref": "#/components/schemas/converted-note-to-issue-issue-event" label: title: Label description: Color-coded labels help you categorize and filter your issues (just like labels in Gmail). type: object properties: id: type: integer format: int64 examples: - 208045946 node_id: type: string examples: - MDU6TGFiZWwyMDgwNDU5NDY= url: description: URL for the label type: string format: uri examples: - https://api.github.com/repositories/42/labels/bug name: description: The name of the label. type: string examples: - bug description: type: - string - 'null' examples: - Something isn't working color: description: '6-character hex code, without the leading #, identifying the color' type: string examples: - FFFFFF default: type: boolean examples: - true required: - id - node_id - url - name - description - color - default timeline-comment-event: title: Timeline Comment Event description: Timeline Comment Event type: object properties: event: type: string actor: "$ref": "#/components/schemas/simple-user" id: description: Unique identifier of the issue comment type: integer examples: - 42 node_id: type: string url: description: URL for the issue comment type: string format: uri examples: - https://api.github.com/repositories/42/issues/comments/1 body: description: Contents of the issue comment type: string examples: - What version of Safari were you using when you observed this bug? body_text: type: string body_html: type: string html_url: type: string format: uri user: "$ref": "#/components/schemas/simple-user" created_at: type: string format: date-time examples: - '2011-04-14T16:00:49Z' updated_at: type: string format: date-time examples: - '2011-04-14T16:00:49Z' issue_url: type: string format: uri author_association: "$ref": "#/components/schemas/author_association" performed_via_github_app: anyOf: - type: 'null' - "$ref": "#/components/schemas/integration" reactions: "$ref": "#/components/schemas/reaction-rollup" required: - event - actor - id - node_id - html_url - issue_url - author_association - user - url - created_at - updated_at timeline-cross-referenced-event: title: Timeline Cross Referenced Event description: Timeline Cross Referenced Event type: object properties: event: type: string actor: "$ref": "#/components/schemas/simple-user" created_at: type: string format: date-time updated_at: type: string format: date-time source: type: object properties: type: type: string issue: "$ref": "#/components/schemas/issue" required: - event - created_at - updated_at - source timeline-committed-event: title: Timeline Committed Event description: Timeline Committed Event type: object properties: event: type: string sha: description: SHA for the commit type: string examples: - 7638417db6d59f3c431d3e1f261cc637155684cd node_id: type: string url: type: string format: uri author: description: Identifying information for the git-user type: object properties: date: description: Timestamp of the commit format: date-time type: string examples: - '2014-08-09T08:02:04+12:00' email: type: string description: Git email address of the user examples: - monalisa.octocat@example.com name: description: Name of the git user type: string examples: - Monalisa Octocat required: - email - name - date committer: description: Identifying information for the git-user type: object properties: date: description: Timestamp of the commit format: date-time type: string examples: - '2014-08-09T08:02:04+12:00' email: type: string description: Git email address of the user examples: - monalisa.octocat@example.com name: description: Name of the git user type: string examples: - Monalisa Octocat required: - email - name - date message: description: Message describing the purpose of the commit type: string examples: - 'Fix #42' tree: type: object properties: sha: description: SHA for the commit type: string examples: - 7638417db6d59f3c431d3e1f261cc637155684cd url: type: string format: uri required: - sha - url parents: type: array items: type: object properties: sha: description: SHA for the commit type: string examples: - 7638417db6d59f3c431d3e1f261cc637155684cd url: type: string format: uri html_url: type: string format: uri required: - sha - url - html_url verification: type: object properties: verified: type: boolean reason: type: string signature: type: - string - 'null' payload: type: - string - 'null' required: - verified - reason - signature - payload html_url: type: string format: uri required: - sha - node_id - url - html_url - author - committer - tree - message - parents - verification timeline-reviewed-event: title: Timeline Reviewed Event description: Timeline Reviewed Event type: object properties: event: type: string id: description: Unique identifier of the review type: integer examples: - 42 node_id: type: string examples: - MDE3OlB1bGxSZXF1ZXN0UmV2aWV3ODA= user: "$ref": "#/components/schemas/simple-user" body: description: The text of the review. type: - string - 'null' examples: - This looks great. state: type: string examples: - CHANGES_REQUESTED html_url: type: string format: uri examples: - https://github.com/octocat/Hello-World/pull/12#pullrequestreview-80 pull_request_url: type: string format: uri examples: - https://api.github.com/repos/octocat/Hello-World/pulls/12 _links: type: object properties: html: type: object properties: href: type: string required: - href pull_request: type: object properties: href: type: string required: - href required: - html - pull_request submitted_at: type: string format: date-time commit_id: description: A commit SHA for the review. type: string examples: - 54bb654c9e6025347f57900a4a5c2313a96b8035 body_html: type: string body_text: type: string author_association: "$ref": "#/components/schemas/author_association" required: - event - id - node_id - user - body - state - commit_id - html_url - pull_request_url - _links - author_association pull-request-review-comment: title: Pull Request Review Comment description: Pull Request Review Comments are comments on a portion of the Pull Request's diff. type: object properties: url: description: URL for the pull request review comment type: string examples: - https://api.github.com/repos/octocat/Hello-World/pulls/comments/1 pull_request_review_id: description: The ID of the pull request review to which the comment belongs. type: - integer - 'null' examples: - 42 id: description: The ID of the pull request review comment. type: integer examples: - 1 node_id: description: The node ID of the pull request review comment. type: string examples: - MDI0OlB1bGxSZXF1ZXN0UmV2aWV3Q29tbWVudDEw diff_hunk: description: The diff of the line that the comment refers to. type: string examples: - "@@ -16,33 +16,40 @@ public class Connection : IConnection..." path: description: The relative path of the file to which the comment applies. type: string examples: - config/database.yaml position: description: The line index in the diff to which the comment applies. type: integer examples: - 1 original_position: description: The index of the original line in the diff to which the comment applies. type: integer examples: - 4 commit_id: description: The SHA of the commit to which the comment applies. type: string examples: - 6dcb09b5b57875f334f61aebed695e2e4193db5e original_commit_id: description: The SHA of the original commit to which the comment applies. type: string examples: - 9c48853fa3dc5c1c3d6f1f1cd1f2743e72652840 in_reply_to_id: description: The comment ID to reply to. type: integer examples: - 8 user: "$ref": "#/components/schemas/simple-user" body: description: The text of the comment. type: string examples: - We should probably include a check for null values here. created_at: type: string format: date-time examples: - '2011-04-14T16:00:49Z' updated_at: type: string format: date-time examples: - '2011-04-14T16:00:49Z' html_url: description: HTML URL for the pull request review comment. type: string format: uri examples: - https://github.com/octocat/Hello-World/pull/1#discussion-diff-1 pull_request_url: description: URL for the pull request that the review comment belongs to. type: string format: uri examples: - https://api.github.com/repos/octocat/Hello-World/pulls/1 author_association: "$ref": "#/components/schemas/author_association" _links: type: object properties: self: type: object properties: href: type: string format: uri examples: - https://api.github.com/repos/octocat/Hello-World/pulls/comments/1 required: - href html: type: object properties: href: type: string format: uri examples: - https://github.com/octocat/Hello-World/pull/1#discussion-diff-1 required: - href pull_request: type: object properties: href: type: string format: uri examples: - https://api.github.com/repos/octocat/Hello-World/pulls/1 required: - href required: - self - html - pull_request start_line: type: - integer - 'null' description: The first line of the range for a multi-line comment. examples: - 2 original_start_line: type: - integer - 'null' description: The first line of the range for a multi-line comment. examples: - 2 start_side: type: - string - 'null' description: The side of the first line of the range for a multi-line comment. enum: - LEFT - RIGHT - default: RIGHT line: description: The line of the blob to which the comment applies. The last line of the range for a multi-line comment type: integer examples: - 2 original_line: description: The line of the blob to which the comment applies. The last line of the range for a multi-line comment type: integer examples: - 2 side: description: The side of the diff to which the comment applies. The side of the last line of the range for a multi-line comment enum: - LEFT - RIGHT default: RIGHT type: string reactions: "$ref": "#/components/schemas/reaction-rollup" body_html: type: string examples: - '"

      comment body

      "' body_text: type: string examples: - '"comment body"' required: - url - id - node_id - pull_request_review_id - diff_hunk - path - position - original_position - commit_id - original_commit_id - user - body - created_at - updated_at - html_url - pull_request_url - author_association - _links timeline-line-commented-event: title: Timeline Line Commented Event description: Timeline Line Commented Event type: object properties: event: type: string node_id: type: string comments: type: array items: "$ref": "#/components/schemas/pull-request-review-comment" timeline-commit-commented-event: title: Timeline Commit Commented Event description: Timeline Commit Commented Event type: object properties: event: type: string node_id: type: string commit_id: type: string comments: type: array items: "$ref": "#/components/schemas/commit-comment" timeline-assigned-issue-event: title: Timeline Assigned Issue Event description: Timeline Assigned Issue Event type: object properties: id: type: integer node_id: type: string url: type: string actor: "$ref": "#/components/schemas/simple-user" event: type: string commit_id: type: - string - 'null' commit_url: type: - string - 'null' created_at: type: string performed_via_github_app: anyOf: - type: 'null' - "$ref": "#/components/schemas/integration" assignee: "$ref": "#/components/schemas/simple-user" required: - id - node_id - url - actor - event - commit_id - commit_url - created_at - performed_via_github_app - assignee timeline-unassigned-issue-event: title: Timeline Unassigned Issue Event description: Timeline Unassigned Issue Event type: object properties: id: type: integer node_id: type: string url: type: string actor: "$ref": "#/components/schemas/simple-user" event: type: string commit_id: type: - string - 'null' commit_url: type: - string - 'null' created_at: type: string performed_via_github_app: anyOf: - type: 'null' - "$ref": "#/components/schemas/integration" assignee: "$ref": "#/components/schemas/simple-user" required: - id - node_id - url - actor - event - commit_id - commit_url - created_at - performed_via_github_app - assignee state-change-issue-event: title: State Change Issue Event description: State Change Issue Event type: object properties: id: type: integer node_id: type: string url: type: string actor: "$ref": "#/components/schemas/simple-user" event: type: string commit_id: type: - string - 'null' commit_url: type: - string - 'null' created_at: type: string performed_via_github_app: anyOf: - type: 'null' - "$ref": "#/components/schemas/integration" required: - id - node_id - url - actor - event - commit_id - commit_url - created_at - performed_via_github_app timeline-issue-events: title: Timeline Event description: Timeline Event type: object anyOf: - "$ref": "#/components/schemas/labeled-issue-event" - "$ref": "#/components/schemas/unlabeled-issue-event" - "$ref": "#/components/schemas/milestoned-issue-event" - "$ref": "#/components/schemas/demilestoned-issue-event" - "$ref": "#/components/schemas/renamed-issue-event" - "$ref": "#/components/schemas/review-requested-issue-event" - "$ref": "#/components/schemas/review-request-removed-issue-event" - "$ref": "#/components/schemas/review-dismissed-issue-event" - "$ref": "#/components/schemas/locked-issue-event" - "$ref": "#/components/schemas/added-to-project-issue-event" - "$ref": "#/components/schemas/moved-column-in-project-issue-event" - "$ref": "#/components/schemas/removed-from-project-issue-event" - "$ref": "#/components/schemas/converted-note-to-issue-issue-event" - "$ref": "#/components/schemas/timeline-comment-event" - "$ref": "#/components/schemas/timeline-cross-referenced-event" - "$ref": "#/components/schemas/timeline-committed-event" - "$ref": "#/components/schemas/timeline-reviewed-event" - "$ref": "#/components/schemas/timeline-line-commented-event" - "$ref": "#/components/schemas/timeline-commit-commented-event" - "$ref": "#/components/schemas/timeline-assigned-issue-event" - "$ref": "#/components/schemas/timeline-unassigned-issue-event" - "$ref": "#/components/schemas/state-change-issue-event" deploy-key: title: Deploy Key description: An SSH key granting access to a single repository. type: object properties: id: type: integer key: type: string url: type: string title: type: string verified: type: boolean created_at: type: string read_only: type: boolean required: - id - key - url - title - verified - created_at - read_only language: title: Language description: Language type: object additionalProperties: type: integer license-content: title: License Content description: License Content type: object properties: name: type: string path: type: string sha: type: string size: type: integer url: type: string format: uri html_url: type: - string - 'null' format: uri git_url: type: - string - 'null' format: uri download_url: type: - string - 'null' format: uri type: type: string content: type: string encoding: type: string _links: type: object properties: git: type: - string - 'null' format: uri html: type: - string - 'null' format: uri self: type: string format: uri required: - git - html - self license: anyOf: - type: 'null' - "$ref": "#/components/schemas/license-simple" required: - _links - git_url - html_url - download_url - name - path - sha - size - type - url - content - encoding - license pages-source-hash: title: Pages Source Hash type: object properties: branch: type: string path: type: string required: - branch - path pages-https-certificate: title: Pages Https Certificate type: object properties: state: type: string enum: - new - authorization_created - authorization_pending - authorized - authorization_revoked - issued - uploaded - approved - errored - bad_authz - destroy_pending - dns_changed examples: - approved description: type: string examples: - Certificate is approved domains: type: array items: type: string description: Array of the domain set and its alternate name (if it is configured) examples: - example.com - www.example.com expires_at: type: string format: date required: - state - description - domains page: title: GitHub Pages description: The configuration for GitHub Pages for a repository. type: object properties: url: type: string description: The API address for accessing this Page resource. format: uri examples: - https://api.github.com/repos/github/hello-world/pages status: type: - string - 'null' description: The status of the most recent build of the Page. enum: - built - building - errored - examples: - built cname: description: The Pages site's custom domain type: - string - 'null' examples: - example.com protected_domain_state: type: - string - 'null' description: The state if the domain is verified enum: - pending - verified - unverified - examples: - pending pending_domain_unverified_at: type: - string - 'null' description: The timestamp when a pending domain becomes unverified. format: date-time custom_404: type: boolean description: Whether the Page has a custom 404 page. default: false examples: - false html_url: type: string description: The web address the Page can be accessed from. format: uri examples: - https://example.com source: "$ref": "#/components/schemas/pages-source-hash" public: type: boolean description: Whether the GitHub Pages site is publicly visible. If set to `true`, the site is accessible to anyone on the internet. If set to `false`, the site will only be accessible to users who have at least `read` access to the repository that published the site. examples: - true https_certificate: "$ref": "#/components/schemas/pages-https-certificate" https_enforced: type: boolean description: Whether https is enabled on the domain examples: - true required: - url - status - cname - custom_404 - public page-build: title: Page Build description: Page Build type: object properties: url: type: string format: uri status: type: string error: type: object properties: message: type: - string - 'null' required: - message pusher: anyOf: - type: 'null' - "$ref": "#/components/schemas/simple-user" commit: type: string duration: type: integer created_at: type: string format: date-time updated_at: type: string format: date-time required: - url - status - error - pusher - commit - duration - created_at - updated_at page-build-status: title: Page Build Status description: Page Build Status type: object properties: url: type: string format: uri examples: - https://api.github.com/repos/github/hello-world/pages/builds/latest status: type: string examples: - queued required: - url - status repository-pre-receive-hook: type: object properties: id: type: integer name: type: string enforcement: type: string configuration_url: type: string pull-request: type: object title: Pull Request description: Pull requests let you tell others about changes you've pushed to a repository on GitHub. Once a pull request is sent, interested parties can review the set of changes, discuss potential modifications, and even push follow-up commits if necessary. properties: url: type: string format: uri examples: - https://api.github.com/repos/octocat/Hello-World/pulls/1347 id: type: integer examples: - 1 node_id: type: string examples: - MDExOlB1bGxSZXF1ZXN0MQ== html_url: type: string format: uri examples: - https://github.com/octocat/Hello-World/pull/1347 diff_url: type: string format: uri examples: - https://github.com/octocat/Hello-World/pull/1347.diff patch_url: type: string format: uri examples: - https://github.com/octocat/Hello-World/pull/1347.patch issue_url: type: string format: uri examples: - https://api.github.com/repos/octocat/Hello-World/issues/1347 commits_url: type: string format: uri examples: - https://api.github.com/repos/octocat/Hello-World/pulls/1347/commits review_comments_url: type: string format: uri examples: - https://api.github.com/repos/octocat/Hello-World/pulls/1347/comments review_comment_url: type: string examples: - https://api.github.com/repos/octocat/Hello-World/pulls/comments{/number} comments_url: type: string format: uri examples: - https://api.github.com/repos/octocat/Hello-World/issues/1347/comments statuses_url: type: string format: uri examples: - https://api.github.com/repos/octocat/Hello-World/statuses/6dcb09b5b57875f334f61aebed695e2e4193db5e number: description: Number uniquely identifying the pull request within its repository. type: integer examples: - 42 state: description: State of this Pull Request. Either `open` or `closed`. enum: - open - closed type: string examples: - open locked: type: boolean examples: - true title: description: The title of the pull request. type: string examples: - Amazing new feature user: anyOf: - type: 'null' - "$ref": "#/components/schemas/simple-user" body: type: - string - 'null' examples: - Please pull these awesome changes labels: type: array items: type: object properties: id: type: integer format: int64 node_id: type: string url: type: string name: type: string description: type: - string - 'null' color: type: string default: type: boolean required: - id - node_id - url - name - description - color - default milestone: anyOf: - type: 'null' - "$ref": "#/components/schemas/milestone" active_lock_reason: type: - string - 'null' examples: - too heated created_at: type: string format: date-time examples: - '2011-01-26T19:01:12Z' updated_at: type: string format: date-time examples: - '2011-01-26T19:01:12Z' closed_at: type: - string - 'null' format: date-time examples: - '2011-01-26T19:01:12Z' merged_at: type: - string - 'null' format: date-time examples: - '2011-01-26T19:01:12Z' merge_commit_sha: type: - string - 'null' examples: - e5bd3914e2e596debea16f433f57875b5b90bcd6 assignee: anyOf: - type: 'null' - "$ref": "#/components/schemas/simple-user" assignees: type: - array - 'null' items: "$ref": "#/components/schemas/simple-user" requested_reviewers: type: - array - 'null' items: "$ref": "#/components/schemas/simple-user" requested_teams: type: - array - 'null' items: "$ref": "#/components/schemas/team-simple" head: type: object properties: label: type: string ref: type: string repo: type: - object - 'null' properties: archive_url: type: string assignees_url: type: string blobs_url: type: string branches_url: type: string collaborators_url: type: string comments_url: type: string commits_url: type: string compare_url: type: string contents_url: type: string contributors_url: type: string format: uri deployments_url: type: string format: uri description: type: - string - 'null' downloads_url: type: string format: uri events_url: type: string format: uri fork: type: boolean forks_url: type: string format: uri full_name: type: string git_commits_url: type: string git_refs_url: type: string git_tags_url: type: string hooks_url: type: string format: uri html_url: type: string format: uri id: type: integer node_id: type: string issue_comment_url: type: string issue_events_url: type: string issues_url: type: string keys_url: type: string labels_url: type: string languages_url: type: string format: uri merges_url: type: string format: uri milestones_url: type: string name: type: string notifications_url: type: string owner: type: object properties: avatar_url: type: string format: uri events_url: type: string followers_url: type: string format: uri following_url: type: string gists_url: type: string gravatar_id: type: - string - 'null' html_url: type: string format: uri id: type: integer node_id: type: string login: type: string organizations_url: type: string format: uri received_events_url: type: string format: uri repos_url: type: string format: uri site_admin: type: boolean starred_url: type: string subscriptions_url: type: string format: uri type: type: string url: type: string format: uri required: - avatar_url - events_url - followers_url - following_url - gists_url - gravatar_id - html_url - id - node_id - login - organizations_url - received_events_url - repos_url - site_admin - starred_url - subscriptions_url - type - url private: type: boolean pulls_url: type: string releases_url: type: string stargazers_url: type: string format: uri statuses_url: type: string subscribers_url: type: string format: uri subscription_url: type: string format: uri tags_url: type: string format: uri teams_url: type: string format: uri trees_url: type: string url: type: string format: uri clone_url: type: string default_branch: type: string forks: type: integer forks_count: type: integer git_url: type: string has_downloads: type: boolean has_issues: type: boolean has_projects: type: boolean has_wiki: type: boolean has_pages: type: boolean homepage: type: - string - 'null' format: uri language: type: - string - 'null' master_branch: type: string archived: type: boolean disabled: type: boolean visibility: description: 'The repository visibility: public, private, or internal.' type: string mirror_url: type: - string - 'null' format: uri open_issues: type: integer open_issues_count: type: integer permissions: type: object properties: admin: type: boolean maintain: type: boolean push: type: boolean triage: type: boolean pull: type: boolean required: - admin - pull - push temp_clone_token: type: string allow_merge_commit: type: boolean allow_squash_merge: type: boolean allow_rebase_merge: type: boolean license: type: - object - 'null' properties: key: type: string name: type: string url: type: - string - 'null' format: uri spdx_id: type: - string - 'null' node_id: type: string required: - key - name - url - spdx_id - node_id pushed_at: type: string format: date-time size: type: integer ssh_url: type: string stargazers_count: type: integer svn_url: type: string format: uri topics: type: array items: type: string watchers: type: integer watchers_count: type: integer created_at: type: string format: date-time updated_at: type: string format: date-time allow_forking: type: boolean is_template: type: boolean required: - archive_url - assignees_url - blobs_url - branches_url - collaborators_url - comments_url - commits_url - compare_url - contents_url - contributors_url - deployments_url - description - downloads_url - events_url - fork - forks_url - full_name - git_commits_url - git_refs_url - git_tags_url - hooks_url - html_url - id - node_id - issue_comment_url - issue_events_url - issues_url - keys_url - labels_url - languages_url - merges_url - milestones_url - name - notifications_url - owner - private - pulls_url - releases_url - stargazers_url - statuses_url - subscribers_url - subscription_url - tags_url - teams_url - trees_url - url - clone_url - default_branch - forks - forks_count - git_url - has_downloads - has_issues - has_projects - has_wiki - has_pages - homepage - language - archived - disabled - mirror_url - open_issues - open_issues_count - license - pushed_at - size - ssh_url - stargazers_count - svn_url - watchers - watchers_count - created_at - updated_at sha: type: string user: type: object properties: avatar_url: type: string format: uri events_url: type: string followers_url: type: string format: uri following_url: type: string gists_url: type: string gravatar_id: type: - string - 'null' html_url: type: string format: uri id: type: integer node_id: type: string login: type: string organizations_url: type: string format: uri received_events_url: type: string format: uri repos_url: type: string format: uri site_admin: type: boolean starred_url: type: string subscriptions_url: type: string format: uri type: type: string url: type: string format: uri required: - avatar_url - events_url - followers_url - following_url - gists_url - gravatar_id - html_url - id - node_id - login - organizations_url - received_events_url - repos_url - site_admin - starred_url - subscriptions_url - type - url required: - label - ref - repo - sha - user base: type: object properties: label: type: string ref: type: string repo: type: object properties: archive_url: type: string assignees_url: type: string blobs_url: type: string branches_url: type: string collaborators_url: type: string comments_url: type: string commits_url: type: string compare_url: type: string contents_url: type: string contributors_url: type: string format: uri deployments_url: type: string format: uri description: type: - string - 'null' downloads_url: type: string format: uri events_url: type: string format: uri fork: type: boolean forks_url: type: string format: uri full_name: type: string git_commits_url: type: string git_refs_url: type: string git_tags_url: type: string hooks_url: type: string format: uri html_url: type: string format: uri id: type: integer is_template: type: boolean node_id: type: string issue_comment_url: type: string issue_events_url: type: string issues_url: type: string keys_url: type: string labels_url: type: string languages_url: type: string format: uri merges_url: type: string format: uri milestones_url: type: string name: type: string notifications_url: type: string owner: type: object properties: avatar_url: type: string format: uri events_url: type: string followers_url: type: string format: uri following_url: type: string gists_url: type: string gravatar_id: type: - string - 'null' html_url: type: string format: uri id: type: integer node_id: type: string login: type: string organizations_url: type: string format: uri received_events_url: type: string format: uri repos_url: type: string format: uri site_admin: type: boolean starred_url: type: string subscriptions_url: type: string format: uri type: type: string url: type: string format: uri required: - avatar_url - events_url - followers_url - following_url - gists_url - gravatar_id - html_url - id - node_id - login - organizations_url - received_events_url - repos_url - site_admin - starred_url - subscriptions_url - type - url private: type: boolean pulls_url: type: string releases_url: type: string stargazers_url: type: string format: uri statuses_url: type: string subscribers_url: type: string format: uri subscription_url: type: string format: uri tags_url: type: string format: uri teams_url: type: string format: uri trees_url: type: string url: type: string format: uri clone_url: type: string default_branch: type: string forks: type: integer forks_count: type: integer git_url: type: string has_downloads: type: boolean has_issues: type: boolean has_projects: type: boolean has_wiki: type: boolean has_pages: type: boolean homepage: type: - string - 'null' format: uri language: type: - string - 'null' master_branch: type: string archived: type: boolean disabled: type: boolean visibility: description: 'The repository visibility: public, private, or internal.' type: string mirror_url: type: - string - 'null' format: uri open_issues: type: integer open_issues_count: type: integer permissions: type: object properties: admin: type: boolean maintain: type: boolean push: type: boolean triage: type: boolean pull: type: boolean required: - admin - pull - push temp_clone_token: type: string allow_merge_commit: type: boolean allow_squash_merge: type: boolean allow_rebase_merge: type: boolean license: anyOf: - type: 'null' - "$ref": "#/components/schemas/license-simple" pushed_at: type: string format: date-time size: type: integer ssh_url: type: string stargazers_count: type: integer svn_url: type: string format: uri topics: type: array items: type: string watchers: type: integer watchers_count: type: integer created_at: type: string format: date-time updated_at: type: string format: date-time allow_forking: type: boolean required: - archive_url - assignees_url - blobs_url - branches_url - collaborators_url - comments_url - commits_url - compare_url - contents_url - contributors_url - deployments_url - description - downloads_url - events_url - fork - forks_url - full_name - git_commits_url - git_refs_url - git_tags_url - hooks_url - html_url - id - node_id - issue_comment_url - issue_events_url - issues_url - keys_url - labels_url - languages_url - merges_url - milestones_url - name - notifications_url - owner - private - pulls_url - releases_url - stargazers_url - statuses_url - subscribers_url - subscription_url - tags_url - teams_url - trees_url - url - clone_url - default_branch - forks - forks_count - git_url - has_downloads - has_issues - has_projects - has_wiki - has_pages - homepage - language - archived - disabled - mirror_url - open_issues - open_issues_count - license - pushed_at - size - ssh_url - stargazers_count - svn_url - watchers - watchers_count - created_at - updated_at sha: type: string user: type: object properties: avatar_url: type: string format: uri events_url: type: string followers_url: type: string format: uri following_url: type: string gists_url: type: string gravatar_id: type: - string - 'null' html_url: type: string format: uri id: type: integer node_id: type: string login: type: string organizations_url: type: string format: uri received_events_url: type: string format: uri repos_url: type: string format: uri site_admin: type: boolean starred_url: type: string subscriptions_url: type: string format: uri type: type: string url: type: string format: uri required: - avatar_url - events_url - followers_url - following_url - gists_url - gravatar_id - html_url - id - node_id - login - organizations_url - received_events_url - repos_url - site_admin - starred_url - subscriptions_url - type - url required: - label - ref - repo - sha - user _links: type: object properties: comments: "$ref": "#/components/schemas/link" commits: "$ref": "#/components/schemas/link" statuses: "$ref": "#/components/schemas/link" html: "$ref": "#/components/schemas/link" issue: "$ref": "#/components/schemas/link" review_comments: "$ref": "#/components/schemas/link" review_comment: "$ref": "#/components/schemas/link" self: "$ref": "#/components/schemas/link" required: - comments - commits - statuses - html - issue - review_comments - review_comment - self author_association: "$ref": "#/components/schemas/author_association" draft: description: Indicates whether or not the pull request is a draft. type: boolean examples: - false merged: type: boolean mergeable: type: - boolean - 'null' examples: - true rebaseable: type: - boolean - 'null' examples: - true mergeable_state: type: string examples: - clean merged_by: anyOf: - type: 'null' - "$ref": "#/components/schemas/simple-user" comments: type: integer examples: - 10 review_comments: type: integer examples: - 0 maintainer_can_modify: description: Indicates whether maintainers can modify the pull request. type: boolean examples: - true commits: type: integer examples: - 3 additions: type: integer examples: - 100 deletions: type: integer examples: - 3 changed_files: type: integer examples: - 5 required: - _links - assignee - labels - base - body - closed_at - comments_url - commits_url - created_at - diff_url - head - html_url - id - node_id - issue_url - merge_commit_sha - merged_at - milestone - number - patch_url - review_comment_url - review_comments_url - statuses_url - state - locked - title - updated_at - url - user - author_association - additions - changed_files - comments - commits - deletions - mergeable - mergeable_state - merged - maintainer_can_modify - merged_by - review_comments pull-request-merge-result: title: Pull Request Merge Result description: Pull Request Merge Result type: object properties: sha: type: string merged: type: boolean message: type: string required: - merged - message - sha pull-request-review-request: title: Pull Request Review Request description: Pull Request Review Request type: object properties: users: type: array items: "$ref": "#/components/schemas/simple-user" teams: type: array items: "$ref": "#/components/schemas/team" required: - users - teams pull-request-review: title: Pull Request Review description: Pull Request Reviews are reviews on pull requests. type: object properties: id: description: Unique identifier of the review type: integer examples: - 42 node_id: type: string examples: - MDE3OlB1bGxSZXF1ZXN0UmV2aWV3ODA= user: anyOf: - type: 'null' - "$ref": "#/components/schemas/simple-user" body: description: The text of the review. type: string examples: - This looks great. state: type: string examples: - CHANGES_REQUESTED html_url: type: string format: uri examples: - https://github.com/octocat/Hello-World/pull/12#pullrequestreview-80 pull_request_url: type: string format: uri examples: - https://api.github.com/repos/octocat/Hello-World/pulls/12 _links: type: object properties: html: type: object properties: href: type: string required: - href pull_request: type: object properties: href: type: string required: - href required: - html - pull_request submitted_at: type: string format: date-time commit_id: description: A commit SHA for the review. type: string examples: - 54bb654c9e6025347f57900a4a5c2313a96b8035 body_html: type: string body_text: type: string author_association: "$ref": "#/components/schemas/author_association" required: - id - node_id - user - body - state - commit_id - html_url - pull_request_url - _links - author_association review-comment: title: Legacy Review Comment description: Legacy Review Comment type: object properties: url: type: string format: uri examples: - https://api.github.com/repos/octocat/Hello-World/pulls/comments/1 pull_request_review_id: type: - integer - 'null' examples: - 42 id: type: integer examples: - 10 node_id: type: string examples: - MDI0OlB1bGxSZXF1ZXN0UmV2aWV3Q29tbWVudDEw diff_hunk: type: string examples: - "@@ -16,33 +16,40 @@ public class Connection : IConnection..." path: type: string examples: - file1.txt position: type: - integer - 'null' examples: - 1 original_position: type: integer examples: - 4 commit_id: type: string examples: - 6dcb09b5b57875f334f61aebed695e2e4193db5e original_commit_id: type: string examples: - 9c48853fa3dc5c1c3d6f1f1cd1f2743e72652840 in_reply_to_id: type: integer examples: - 8 user: anyOf: - type: 'null' - "$ref": "#/components/schemas/simple-user" body: type: string examples: - Great stuff created_at: type: string format: date-time examples: - '2011-04-14T16:00:49Z' updated_at: type: string format: date-time examples: - '2011-04-14T16:00:49Z' html_url: type: string format: uri examples: - https://github.com/octocat/Hello-World/pull/1#discussion-diff-1 pull_request_url: type: string format: uri examples: - https://api.github.com/repos/octocat/Hello-World/pulls/1 author_association: "$ref": "#/components/schemas/author_association" _links: type: object properties: self: "$ref": "#/components/schemas/link" html: "$ref": "#/components/schemas/link" pull_request: "$ref": "#/components/schemas/link" required: - self - html - pull_request body_text: type: string body_html: type: string reactions: "$ref": "#/components/schemas/reaction-rollup" side: description: The side of the first line of the range for a multi-line comment. enum: - LEFT - RIGHT default: RIGHT type: string start_side: type: - string - 'null' description: The side of the first line of the range for a multi-line comment. enum: - LEFT - RIGHT - default: RIGHT line: description: The line of the blob to which the comment applies. The last line of the range for a multi-line comment type: integer examples: - 2 original_line: description: The original line of the blob to which the comment applies. The last line of the range for a multi-line comment type: integer examples: - 2 start_line: description: The first line of the range for a multi-line comment. type: - integer - 'null' examples: - 2 original_start_line: description: The original first line of the range for a multi-line comment. type: - integer - 'null' examples: - 2 required: - id - node_id - url - body - diff_hunk - path - position - original_position - commit_id - original_commit_id - user - pull_request_review_id - html_url - pull_request_url - _links - author_association - created_at - updated_at release-asset: title: Release Asset description: Data related to a release. type: object properties: url: type: string format: uri browser_download_url: type: string format: uri id: type: integer node_id: type: string name: description: The file name of the asset. type: string examples: - Team Environment label: type: - string - 'null' state: description: State of the release asset. type: string enum: - uploaded - open content_type: type: string size: type: integer download_count: type: integer created_at: type: string format: date-time updated_at: type: string format: date-time uploader: anyOf: - type: 'null' - "$ref": "#/components/schemas/simple-user" required: - id - name - content_type - size - state - url - node_id - download_count - label - uploader - browser_download_url - created_at - updated_at release: title: Release description: A release. type: object properties: url: type: string format: uri html_url: type: string format: uri assets_url: type: string format: uri upload_url: type: string tarball_url: type: - string - 'null' format: uri zipball_url: type: - string - 'null' format: uri id: type: integer node_id: type: string tag_name: description: The name of the tag. type: string examples: - v1.0.0 target_commitish: description: Specifies the commitish value that determines where the Git tag is created from. type: string examples: - master name: type: - string - 'null' body: type: - string - 'null' draft: description: true to create a draft (unpublished) release, false to create a published one. type: boolean examples: - false prerelease: description: Whether to identify the release as a prerelease or a full release. type: boolean examples: - false created_at: type: string format: date-time published_at: type: - string - 'null' format: date-time author: "$ref": "#/components/schemas/simple-user" assets: type: array items: "$ref": "#/components/schemas/release-asset" body_html: type: string body_text: type: string reactions: "$ref": "#/components/schemas/reaction-rollup" required: - assets_url - upload_url - tarball_url - zipball_url - created_at - published_at - draft - id - node_id - author - html_url - name - prerelease - tag_name - target_commitish - assets - url stargazer: title: Stargazer description: Stargazer type: object properties: starred_at: type: string format: date-time user: anyOf: - type: 'null' - "$ref": "#/components/schemas/simple-user" required: - starred_at - user code-frequency-stat: title: Code Frequency Stat description: Code Frequency Stat type: array items: type: integer commit-activity: title: Commit Activity description: Commit Activity type: object properties: days: type: array items: type: integer examples: - 0 - 3 - 26 - 20 - 39 - 1 - 0 total: type: integer examples: - 89 week: type: integer examples: - 1336280400 required: - days - total - week contributor-activity: title: Contributor Activity description: Contributor Activity type: object properties: author: anyOf: - type: 'null' - "$ref": "#/components/schemas/simple-user" total: type: integer examples: - 135 weeks: type: array items: type: object properties: w: type: integer a: type: integer d: type: integer c: type: integer examples: - w: '1367712000' a: 6898 d: 77 c: 10 required: - author - total - weeks participation-stats: title: Participation Stats type: object properties: all: type: array items: type: integer owner: type: array items: type: integer required: - all - owner repository-subscription: title: Repository Invitation description: Repository invitations let you manage who you collaborate with. type: object properties: subscribed: description: Determines if notifications should be received from this repository. type: boolean examples: - true ignored: description: Determines if all notifications should be blocked from this repository. type: boolean reason: type: - string - 'null' created_at: type: string format: date-time examples: - '2012-10-06T21:34:12Z' url: type: string format: uri examples: - https://api.github.com/repos/octocat/example/subscription repository_url: type: string format: uri examples: - https://api.github.com/repos/octocat/example required: - created_at - ignored - reason - subscribed - url - repository_url tag: title: Tag description: Tag type: object properties: name: type: string examples: - v0.1 commit: type: object properties: sha: type: string url: type: string format: uri required: - sha - url zipball_url: type: string format: uri examples: - https://github.com/octocat/Hello-World/zipball/v0.1 tarball_url: type: string format: uri examples: - https://github.com/octocat/Hello-World/tarball/v0.1 node_id: type: string required: - name - node_id - commit - zipball_url - tarball_url topic: title: Topic description: A topic aggregates entities that are related to a subject. type: object properties: names: type: array items: type: string required: - names search-result-text-matches: title: Search Result Text Matches type: array items: type: object properties: object_url: type: string object_type: type: - string - 'null' property: type: string fragment: type: string matches: type: array items: type: object properties: text: type: string indices: type: array items: type: integer code-search-result-item: title: Code Search Result Item description: Code Search Result Item type: object properties: name: type: string path: type: string sha: type: string url: type: string format: uri git_url: type: string format: uri html_url: type: string format: uri repository: "$ref": "#/components/schemas/minimal-repository" score: type: number file_size: type: integer language: type: - string - 'null' last_modified_at: type: string format: date-time line_numbers: type: array items: type: string examples: - 73..77 - 77..78 text_matches: "$ref": "#/components/schemas/search-result-text-matches" required: - score - name - path - sha - git_url - html_url - url - repository commit-search-result-item: title: Commit Search Result Item description: Commit Search Result Item type: object properties: url: type: string format: uri sha: type: string html_url: type: string format: uri comments_url: type: string format: uri commit: type: object properties: author: type: object properties: name: type: string email: type: string date: type: string format: date-time required: - name - email - date committer: anyOf: - type: 'null' - "$ref": "#/components/schemas/git-user" comment_count: type: integer message: type: string tree: type: object properties: sha: type: string url: type: string format: uri required: - sha - url url: type: string format: uri verification: "$ref": "#/components/schemas/verification" required: - author - committer - comment_count - message - tree - url author: anyOf: - type: 'null' - "$ref": "#/components/schemas/simple-user" committer: anyOf: - type: 'null' - "$ref": "#/components/schemas/git-user" parents: type: array items: type: object properties: url: type: string html_url: type: string sha: type: string repository: "$ref": "#/components/schemas/minimal-repository" score: type: number node_id: type: string text_matches: "$ref": "#/components/schemas/search-result-text-matches" required: - sha - node_id - url - html_url - author - committer - parents - comments_url - commit - repository - score issue-search-result-item: title: Issue Search Result Item description: Issue Search Result Item type: object properties: url: type: string format: uri repository_url: type: string format: uri labels_url: type: string comments_url: type: string format: uri events_url: type: string format: uri html_url: type: string format: uri id: type: integer node_id: type: string number: type: integer title: type: string locked: type: boolean active_lock_reason: type: - string - 'null' assignees: type: - array - 'null' items: "$ref": "#/components/schemas/simple-user" user: anyOf: - type: 'null' - "$ref": "#/components/schemas/simple-user" labels: type: array items: type: object properties: id: type: integer format: int64 node_id: type: string url: type: string name: type: string color: type: string default: type: boolean description: type: - string - 'null' state: type: string assignee: anyOf: - type: 'null' - "$ref": "#/components/schemas/simple-user" milestone: anyOf: - type: 'null' - "$ref": "#/components/schemas/milestone" comments: type: integer created_at: type: string format: date-time updated_at: type: string format: date-time closed_at: type: - string - 'null' format: date-time text_matches: "$ref": "#/components/schemas/search-result-text-matches" pull_request: type: object properties: merged_at: type: - string - 'null' format: date-time diff_url: type: - string - 'null' format: uri html_url: type: - string - 'null' format: uri patch_url: type: - string - 'null' format: uri url: type: - string - 'null' format: uri required: - diff_url - html_url - patch_url - url body: type: string score: type: number author_association: "$ref": "#/components/schemas/author_association" draft: type: boolean repository: "$ref": "#/components/schemas/repository" body_html: type: string body_text: type: string timeline_url: type: string format: uri performed_via_github_app: anyOf: - type: 'null' - "$ref": "#/components/schemas/integration" reactions: "$ref": "#/components/schemas/reaction-rollup" required: - assignee - closed_at - comments - comments_url - events_url - html_url - id - node_id - labels - labels_url - milestone - number - repository_url - state - locked - title - url - user - author_association - created_at - updated_at - score label-search-result-item: title: Label Search Result Item description: Label Search Result Item type: object properties: id: type: integer node_id: type: string url: type: string format: uri name: type: string color: type: string default: type: boolean description: type: - string - 'null' score: type: number text_matches: "$ref": "#/components/schemas/search-result-text-matches" required: - id - node_id - url - name - color - default - description - score repo-search-result-item: title: Repo Search Result Item description: Repo Search Result Item type: object properties: id: type: integer node_id: type: string name: type: string full_name: type: string owner: anyOf: - type: 'null' - "$ref": "#/components/schemas/simple-user" private: type: boolean html_url: type: string format: uri description: type: - string - 'null' fork: type: boolean url: type: string format: uri created_at: type: string format: date-time updated_at: type: string format: date-time pushed_at: type: string format: date-time homepage: type: - string - 'null' format: uri size: type: integer stargazers_count: type: integer watchers_count: type: integer language: type: - string - 'null' forks_count: type: integer open_issues_count: type: integer master_branch: type: string default_branch: type: string score: type: number forks_url: type: string format: uri keys_url: type: string collaborators_url: type: string teams_url: type: string format: uri hooks_url: type: string format: uri issue_events_url: type: string events_url: type: string format: uri assignees_url: type: string branches_url: type: string tags_url: type: string format: uri blobs_url: type: string git_tags_url: type: string git_refs_url: type: string trees_url: type: string statuses_url: type: string languages_url: type: string format: uri stargazers_url: type: string format: uri contributors_url: type: string format: uri subscribers_url: type: string format: uri subscription_url: type: string format: uri commits_url: type: string git_commits_url: type: string comments_url: type: string issue_comment_url: type: string contents_url: type: string compare_url: type: string merges_url: type: string format: uri archive_url: type: string downloads_url: type: string format: uri issues_url: type: string pulls_url: type: string milestones_url: type: string notifications_url: type: string labels_url: type: string releases_url: type: string deployments_url: type: string format: uri git_url: type: string ssh_url: type: string clone_url: type: string svn_url: type: string format: uri forks: type: integer open_issues: type: integer watchers: type: integer topics: type: array items: type: string mirror_url: type: - string - 'null' format: uri has_issues: type: boolean has_projects: type: boolean has_pages: type: boolean has_wiki: type: boolean has_downloads: type: boolean archived: type: boolean disabled: type: boolean description: Returns whether or not this repository disabled. visibility: description: 'The repository visibility: public, private, or internal.' type: string license: anyOf: - type: 'null' - "$ref": "#/components/schemas/license-simple" permissions: type: object properties: admin: type: boolean maintain: type: boolean push: type: boolean triage: type: boolean pull: type: boolean required: - admin - pull - push text_matches: "$ref": "#/components/schemas/search-result-text-matches" temp_clone_token: type: string allow_merge_commit: type: boolean allow_squash_merge: type: boolean allow_rebase_merge: type: boolean delete_branch_on_merge: type: boolean allow_forking: type: boolean is_template: type: boolean required: - archive_url - assignees_url - blobs_url - branches_url - collaborators_url - comments_url - commits_url - compare_url - contents_url - contributors_url - deployments_url - description - downloads_url - events_url - fork - forks_url - full_name - git_commits_url - git_refs_url - git_tags_url - hooks_url - html_url - id - node_id - issue_comment_url - issue_events_url - issues_url - keys_url - labels_url - languages_url - merges_url - milestones_url - name - notifications_url - owner - private - pulls_url - releases_url - stargazers_url - statuses_url - subscribers_url - subscription_url - tags_url - teams_url - trees_url - url - clone_url - default_branch - forks - forks_count - git_url - has_downloads - has_issues - has_projects - has_wiki - has_pages - homepage - language - archived - disabled - mirror_url - open_issues - open_issues_count - license - pushed_at - size - ssh_url - stargazers_count - svn_url - watchers - watchers_count - created_at - updated_at - score topic-search-result-item: title: Topic Search Result Item description: Topic Search Result Item type: object properties: name: type: string display_name: type: - string - 'null' short_description: type: - string - 'null' description: type: - string - 'null' created_by: type: - string - 'null' released: type: - string - 'null' created_at: type: string format: date-time updated_at: type: string format: date-time featured: type: boolean curated: type: boolean score: type: number repository_count: type: - integer - 'null' logo_url: type: - string - 'null' format: uri text_matches: "$ref": "#/components/schemas/search-result-text-matches" related: type: - array - 'null' items: type: object properties: topic_relation: type: object properties: id: type: integer name: type: string topic_id: type: integer relation_type: type: string aliases: type: - array - 'null' items: type: object properties: topic_relation: type: object properties: id: type: integer name: type: string topic_id: type: integer relation_type: type: string required: - name - display_name - short_description - description - created_by - released - created_at - updated_at - featured - curated - score user-search-result-item: title: User Search Result Item description: User Search Result Item type: object properties: login: type: string id: type: integer node_id: type: string avatar_url: type: string format: uri gravatar_id: type: - string - 'null' url: type: string format: uri html_url: type: string format: uri followers_url: type: string format: uri subscriptions_url: type: string format: uri organizations_url: type: string format: uri repos_url: type: string format: uri received_events_url: type: string format: uri type: type: string score: type: number following_url: type: string gists_url: type: string starred_url: type: string events_url: type: string public_repos: type: integer public_gists: type: integer followers: type: integer following: type: integer created_at: type: string format: date-time updated_at: type: string format: date-time name: type: - string - 'null' bio: type: - string - 'null' email: type: - string - 'null' format: email location: type: - string - 'null' site_admin: type: boolean hireable: type: - boolean - 'null' text_matches: "$ref": "#/components/schemas/search-result-text-matches" blog: type: - string - 'null' company: type: - string - 'null' suspended_at: type: - string - 'null' format: date-time required: - avatar_url - events_url - followers_url - following_url - gists_url - gravatar_id - html_url - id - node_id - login - organizations_url - received_events_url - repos_url - site_admin - starred_url - subscriptions_url - type - url - score configuration-status: type: object properties: status: type: string progress: type: array items: type: object properties: status: type: string key: type: string required: - status - key maintenance-status: type: object properties: status: type: string scheduled_time: type: string connection_services: type: array items: type: object properties: name: type: string number: type: integer required: - name - number enterprise-settings: type: object properties: enterprise: type: object properties: private_mode: type: boolean public_pages: type: boolean subdomain_isolation: type: boolean signup_enabled: type: boolean github_hostname: type: string identicons_host: type: string http_proxy: type: - string - 'null' auth_mode: type: string expire_sessions: type: boolean admin_password: type: - string - 'null' configuration_id: type: integer configuration_run_count: type: integer avatar: type: object properties: enabled: type: boolean uri: type: string customer: type: object properties: name: type: string email: type: string uuid: type: string secret_key_data: type: string public_key_data: type: string license: type: object properties: seats: type: integer evaluation: type: boolean perpetual: type: boolean unlimited_seating: type: boolean support_key: type: string ssh_allowed: type: boolean cluster_support: type: boolean expire_at: type: string github_ssl: type: object properties: enabled: type: boolean cert: type: - string - 'null' key: type: - string - 'null' ldap: type: object properties: host: type: - string - 'null' port: type: integer base: type: array items: {} uid: type: - string - 'null' bind_dn: type: - string - 'null' password: type: - string - 'null' method: type: string search_strategy: type: string user_groups: type: array items: {} admin_group: type: - string - 'null' virtual_attribute_enabled: type: boolean recursive_group_search: type: boolean posix_support: type: boolean user_sync_emails: type: boolean user_sync_keys: type: boolean user_sync_interval: type: integer team_sync_interval: type: integer sync_enabled: type: boolean reconciliation: type: object properties: user: type: - string - 'null' org: type: - string - 'null' profile: type: object properties: uid: type: string name: type: - string - 'null' mail: type: - string - 'null' key: type: - string - 'null' cas: type: object properties: url: type: - string - 'null' saml: type: object properties: sso_url: type: - string - 'null' certificate: type: - string - 'null' certificate_path: type: - string - 'null' issuer: type: - string - 'null' idp_initiated_sso: type: boolean disable_admin_demote: type: boolean github_oauth: type: object properties: client_id: type: string client_secret: type: string organization_name: type: string organization_team: type: string smtp: type: object properties: enabled: type: boolean address: type: string authentication: type: string port: type: string domain: type: string username: type: string user_name: type: string enable_starttls_auto: type: boolean password: type: string discard-to-noreply-address: type: boolean support_address: type: string support_address_type: type: string noreply_address: type: string ntp: type: object properties: primary_server: type: string secondary_server: type: string timezone: type: - string - 'null' snmp: type: object properties: enabled: type: boolean community: type: string syslog: type: object properties: enabled: type: boolean server: type: - string - 'null' protocol_name: type: string assets: type: - string - 'null' pages: type: object properties: enabled: type: boolean collectd: type: object properties: enabled: type: boolean server: type: - string - 'null' port: type: integer encryption: type: - string - 'null' username: type: - string - 'null' password: type: - string - 'null' mapping: type: object properties: enabled: type: boolean tileserver: type: - string - 'null' basemap: type: string token: type: - string - 'null' load_balancer: type: - string - 'null' run_list: type: array items: type: string ssh-key: type: object properties: key: type: string pretty-print: type: string private-user: title: Private User description: Private User type: object properties: login: type: string examples: - octocat id: type: integer examples: - 1 node_id: type: string examples: - MDQ6VXNlcjE= avatar_url: type: string format: uri examples: - https://github.com/images/error/octocat_happy.gif gravatar_id: type: - string - 'null' examples: - 41d064eb2195891e12d0413f63227ea7 url: type: string format: uri examples: - https://api.github.com/users/octocat html_url: type: string format: uri examples: - https://github.com/octocat followers_url: type: string format: uri examples: - https://api.github.com/users/octocat/followers following_url: type: string examples: - https://api.github.com/users/octocat/following{/other_user} gists_url: type: string examples: - https://api.github.com/users/octocat/gists{/gist_id} starred_url: type: string examples: - https://api.github.com/users/octocat/starred{/owner}{/repo} subscriptions_url: type: string format: uri examples: - https://api.github.com/users/octocat/subscriptions organizations_url: type: string format: uri examples: - https://api.github.com/users/octocat/orgs repos_url: type: string format: uri examples: - https://api.github.com/users/octocat/repos events_url: type: string examples: - https://api.github.com/users/octocat/events{/privacy} received_events_url: type: string format: uri examples: - https://api.github.com/users/octocat/received_events type: type: string examples: - User site_admin: type: boolean name: type: - string - 'null' examples: - monalisa octocat company: type: - string - 'null' examples: - GitHub blog: type: - string - 'null' examples: - https://github.com/blog location: type: - string - 'null' examples: - San Francisco email: type: - string - 'null' format: email examples: - octocat@github.com hireable: type: - boolean - 'null' bio: type: - string - 'null' examples: - There once was... public_repos: type: integer examples: - 2 public_gists: type: integer examples: - 1 followers: type: integer examples: - 20 following: type: integer examples: - 0 created_at: type: string format: date-time examples: - '2008-01-14T04:33:35Z' updated_at: type: string format: date-time examples: - '2008-01-14T04:33:35Z' private_gists: type: integer examples: - 81 total_private_repos: type: integer examples: - 100 owned_private_repos: type: integer examples: - 100 disk_usage: type: integer examples: - 10000 collaborators: type: integer examples: - 8 two_factor_authentication: type: boolean examples: - true plan: type: object properties: collaborators: type: integer name: type: string space: type: integer private_repos: type: integer required: - collaborators - name - space - private_repos suspended_at: type: string format: date-time business_plus: type: boolean ldap_dn: type: string required: - avatar_url - events_url - followers_url - following_url - gists_url - gravatar_id - html_url - id - node_id - login - organizations_url - received_events_url - repos_url - site_admin - starred_url - subscriptions_url - type - url - bio - blog - company - email - followers - following - hireable - location - name - public_gists - public_repos - created_at - updated_at - collaborators - disk_usage - owned_private_repos - private_gists - total_private_repos - two_factor_authentication email: title: Email description: Email type: object properties: email: type: string format: email examples: - octocat@github.com primary: type: boolean examples: - true verified: type: boolean examples: - true visibility: type: - string - 'null' examples: - public required: - email - primary - verified - visibility gpg-key: title: GPG Key description: A unique encryption key type: object properties: id: type: integer examples: - 3 primary_key_id: type: - integer - 'null' key_id: type: string examples: - 3262EFF25BA0D270 public_key: type: string examples: - xsBNBFayYZ... emails: type: array items: type: object properties: email: type: string verified: type: boolean examples: - email: mastahyeti@users.noreply.github.com verified: true subkeys: type: array items: type: object properties: id: type: integer primary_key_id: type: integer key_id: type: string public_key: type: string emails: type: array items: {} subkeys: type: array items: {} can_sign: type: boolean can_encrypt_comms: type: boolean can_encrypt_storage: type: boolean can_certify: type: boolean created_at: type: string expires_at: type: - string - 'null' raw_key: type: - string - 'null' examples: - id: 4 primary_key_id: 3 key_id: 4A595D4C72EE49C7 public_key: zsBNBFayYZ... emails: [] subkeys: [] can_sign: false can_encrypt_comms: true can_encrypt_storage: true can_certify: false created_at: '2016-03-24T11:31:04-06:00' expires_at: can_sign: type: boolean examples: - true can_encrypt_comms: type: boolean can_encrypt_storage: type: boolean can_certify: type: boolean examples: - true created_at: type: string format: date-time examples: - '2016-03-24T11:31:04-06:00' expires_at: type: - string - 'null' format: date-time raw_key: type: - string - 'null' required: - id - primary_key_id - key_id - raw_key - public_key - created_at - expires_at - can_sign - can_encrypt_comms - can_encrypt_storage - can_certify - emails - subkeys key: title: Key description: Key type: object properties: key: type: string id: type: integer url: type: string title: type: string created_at: type: string format: date-time verified: type: boolean read_only: type: boolean required: - key - id - url - title - created_at - verified - read_only starred-repository: title: Starred Repository description: Starred Repository type: object properties: starred_at: type: string format: date-time repo: "$ref": "#/components/schemas/repository" required: - starred_at - repo hovercard: title: Hovercard description: Hovercard type: object properties: contexts: type: array items: type: object properties: message: type: string octicon: type: string required: - message - octicon required: - contexts key-simple: title: Key Simple description: Key Simple type: object properties: id: type: integer key: type: string required: - key - id examples: global-hook-items: value: - type: Global id: 1 name: web active: true events: - organization - user config: url: https://example.com content_type: json insecure_ssl: '0' secret: "********" updated_at: '2017-12-07T00:14:59Z' created_at: '2017-12-07T00:14:59Z' url: https://api.github.com/admin/hooks/1 ping_url: https://api.github.com/admin/hooks/1/pings global-hook: value: type: Global id: 1 name: web active: true events: - organization - user config: url: https://example.com content_type: json insecure_ssl: '0' secret: "********" updated_at: '2017-12-07T00:14:59Z' created_at: '2017-12-07T00:14:59Z' url: https://api.github.com/admin/hooks/1 ping_url: https://api.github.com/admin/hooks/1/pings global-hook-2: value: type: Global id: 1 name: web active: true events: - organization config: url: https://example.com content_type: form insecure_ssl: '0' updated_at: '2017-12-07T00:14:59Z' created_at: '2017-12-07T00:14:59Z' url: https://api.github.com/admin/hooks/1 ping_url: https://api.github.com/admin/hooks/1/pings enterprise-public-key-items: value: - key: 2Sg8iYjAxxmI2LvUXpJjkYrMxURPc8r+dB7TJyvv1234 id: 2 url: https://api.github.com/user/keys/2 title: ssh-rsa AAAAB3NzaC1yc2EAAA created_at: '2020-06-11T21:31:57Z' verified: false read_only: false last_used: '2020-06-11T22:31:57Z' user_id: 1 repository_id: 2 - key: 9Og8iYjAyymI9LvABpJerYrMxURPc8r+dB7TJyvv1234 id: 3 url: https://api.github.com/user/keys/2 title: ssh-rsa AAAAB3NzaC1yc2EAAA created_at: '2020-06-11T21:31:57Z' verified: false read_only: false last_used: '2020-06-11T22:31:57Z' user_id: 1 repository_id: 2 ldap-mapping-team: value: ldap_dn: cn=Enterprise Ops,ou=teams,dc=github,dc=com id: 1 node_id: MDQ6VGVhbTE= url: https://api.github.com/teams/1 html_url: https://github.com/orgs/github/teams/justice-league name: Justice League slug: justice-league description: A great team. privacy: closed permission: admin members_url: https://api.github.com/teams/1/members{/member} repositories_url: https://api.github.com/teams/1/repos parent: ldap-mapping-user: value: ldap_dn: uid=asdf,ou=users,dc=github,dc=com login: octocat id: 1 node_id: MDQ6VXNlcjE= avatar_url: https://github.com/images/error/octocat_happy.gif gravatar_id: '' url: https://api.github.com/users/octocat html_url: https://github.com/octocat followers_url: https://api.github.com/users/octocat/followers following_url: https://api.github.com/users/octocat/following{/other_user} gists_url: https://api.github.com/users/octocat/gists{/gist_id} starred_url: https://api.github.com/users/octocat/starred{/owner}{/repo} subscriptions_url: https://api.github.com/users/octocat/subscriptions organizations_url: https://api.github.com/users/octocat/orgs repos_url: https://api.github.com/users/octocat/repos events_url: https://api.github.com/users/octocat/events{/privacy} received_events_url: https://api.github.com/users/octocat/received_events type: User site_admin: false name: monalisa octocat company: GitHub blog: https://github.com/blog location: San Francisco email: octocat@github.com hireable: false bio: There once was... twitter_username: monatheoctocat public_repos: 2 public_gists: 1 followers: 20 following: 0 created_at: '2008-01-14T04:33:35Z' updated_at: '2008-01-14T04:33:35Z' private_gists: 81 total_private_repos: 100 owned_private_repos: 100 disk_usage: 10000 collaborators: 8 two_factor_authentication: true plan: name: Medium space: 400 private_repos: 20 collaborators: 0 organization-simple: value: login: github id: 1 node_id: MDEyOk9yZ2FuaXphdGlvbjE= url: https://api.github.com/orgs/github repos_url: https://api.github.com/orgs/github/repos events_url: https://api.github.com/orgs/github/events hooks_url: https://api.github.com/orgs/github/hooks issues_url: https://api.github.com/orgs/github/issues members_url: https://api.github.com/orgs/github/members{/member} public_members_url: https://api.github.com/orgs/github/public_members{/member} avatar_url: https://github.com/images/error/octocat_happy.gif description: A great organization pre-receive-environment-items: value: - id: 1 name: Default image_url: githubenterprise://internal url: https://github.example.com/api/v3/admin/pre-receive-environments/1 html_url: https://github.example.com/admin/pre-receive-environments/1 default_environment: true created_at: '2016-05-20T11:35:45-05:00' hooks_count: 14 download: url: https://github.example.com/api/v3/admin/pre-receive-environments/1/downloads/latest state: not_started downloaded_at: '2016-05-26T07:42:53-05:00' message: - id: 2 name: DevTools Hook Env image_url: https://my_file_server/path/to/devtools_env.tar.gz url: https://github.example.com/api/v3/admin/pre-receive-environments/2 html_url: https://github.example.com/admin/pre-receive-environments/2 default_environment: false created_at: '2016-05-20T11:35:45-05:00' hooks_count: 1 download: url: https://github.example.com/api/v3/admin/pre-receive-environments/2/downloads/latest state: success downloaded_at: '2016-05-26T07:42:53-05:00' message: pre-receive-environment: value: id: 2 name: DevTools Hook Env image_url: https://my_file_server/path/to/devtools_env.tar.gz url: https://github.example.com/api/v3/admin/pre-receive-environments/2 html_url: https://github.example.com/admin/pre-receive-environments/2 default_environment: false created_at: '2016-05-20T11:35:45-05:00' hooks_count: 1 download: url: https://github.example.com/api/v3/admin/pre-receive-environments/2/downloads/latest state: not_started downloaded_at: message: pre-receive-environment-default-response: value: id: 2 name: DevTools Hook Env image_url: https://my_file_server/path/to/devtools_env.tar.gz url: https://github.example.com/api/v3/admin/pre-receive-environments/2 html_url: https://github.example.com/admin/pre-receive-environments/2 default_environment: false created_at: '2016-05-20T11:35:45-05:00' hooks_count: 1 download: url: https://github.example.com/api/v3/admin/pre-receive-environments/2/downloads/latest state: success downloaded_at: '2016-05-26T07:42:53-05:00' message: pre-receive-environment-download-status-default-response: value: url: https://github.example.com/api/v3/admin/pre-receive-environments/3/downloads/latest state: not_started downloaded_at: message: pre-receive-environment-download-status: value: url: https://github.example.com/api/v3/admin/pre-receive-environments/3/downloads/latest state: success downloaded_at: '2016-05-26T07:42:53-05:00' message: pre-receive-hook-items: value: - id: 1 name: Check Commits enforcement: disabled script: scripts/commmit_check.sh script_repository: id: 595 full_name: DevIT/hooks url: https://github.example.com/api/v3/repos/DevIT/hooks html_url: https://github.example.com/DevIT/hooks environment: id: 2 name: DevTools Hook Env image_url: https://my_file_server/path/to/devtools_env.tar.gz url: https://github.example.com/api/v3/admin/pre-receive-environments/2 html_url: https://github.example.com/admin/pre-receive-environments/2 default_environment: false created_at: '2016-05-20T11:35:45-05:00' hooks_count: 1 download: url: https://github.example.com/api/v3/admin/pre-receive-environments/2/downloads/latest state: success downloaded_at: '2016-05-26T07:42:53-05:00' message: allow_downstream_configuration: false pre-receive-hook: value: id: 1 name: Check Commits enforcement: disabled script: scripts/commmit_check.sh script_repository: id: 595 full_name: DevIT/hooks url: https://github.example.com/api/v3/repos/DevIT/hooks html_url: https://github.example.com/DevIT/hooks environment: id: 2 name: DevTools Hook Env image_url: https://my_file_server/path/to/devtools_env.tar.gz url: https://github.example.com/api/v3/admin/pre-receive-environments/2 html_url: https://github.example.com/admin/pre-receive-environments/2 default_environment: false created_at: '2016-05-20T11:35:45-05:00' hooks_count: 1 download: url: https://github.example.com/api/v3/admin/pre-receive-environments/2/downloads/latest state: success downloaded_at: '2016-05-26T07:42:53-05:00' message: allow_downstream_configuration: false pre-receive-hook-2: value: id: 1 name: Check Commits enforcement: disabled script: scripts/commmit_check.sh script_repository: id: 595 full_name: DevIT/hooks url: https://github.example.com/api/v3/repos/DevIT/hooks html_url: https://github.example.com/DevIT/hooks environment: id: 1 name: Default image_url: githubenterprise://internal url: https://github.example.com/api/v3/admin/pre-receive-environments/1 html_url: https://github.example.com/admin/pre-receive-environments/1 default_environment: true created_at: '2016-05-20T11:35:45-05:00' hooks_count: 1 download: url: https://github.example.com/api/v3/admin/pre-receive-environments/1/downloads/latest state: success downloaded_at: '2016-05-26T07:42:53-05:00' message: allow_downstream_configuration: true authorization-items: value: - id: 2 url: https://enterprise.octocat.com/api/v3/authorizations/2 app: name: My personal access token url: https://docs.github.com/enterprise/rest/reference/enterprise-admin#list-personal-access-tokens client_id: '00000000000000000000' token: ghp_16C7e42F292c6912E7710c838347Ae178B4a hashed_token: 23cffb2fab1b0a62747863eba88cb9327e561f2f7a0c8661c0d9b83146cb8d45 token_last_eight: Ae178B4a note: My personal access token note_url: created_at: '2019-04-24T21:49:02Z' updated_at: '2019-04-24T21:49:02Z' scopes: - admin:business - admin:gpg_key - admin:org - admin:org_hook - admin:pre_receive_hook - admin:public_key - admin:repo_hook - delete_repo - gist - notifications - repo - user - write:discussion fingerprint: simple-user: value: login: octocat id: 1 node_id: MDQ6VXNlcjE= avatar_url: https://github.com/images/error/octocat_happy.gif gravatar_id: '' url: https://api.github.com/users/octocat html_url: https://github.com/octocat followers_url: https://api.github.com/users/octocat/followers following_url: https://api.github.com/users/octocat/following{/other_user} gists_url: https://api.github.com/users/octocat/gists{/gist_id} starred_url: https://api.github.com/users/octocat/starred{/owner}{/repo} subscriptions_url: https://api.github.com/users/octocat/subscriptions organizations_url: https://api.github.com/users/octocat/orgs repos_url: https://api.github.com/users/octocat/repos events_url: https://api.github.com/users/octocat/events{/privacy} received_events_url: https://api.github.com/users/octocat/received_events type: User site_admin: false authorization: value: id: 1 url: https://api.github.com/authorizations/1 scopes: - public_repo token: ghu_16C7e42F292c6912E7710c838347Ae178B4a token_last_eight: Ae178B4a hashed_token: 25f94a2a5c7fbaf499c665bc73d67c1c87e496da8985131633ee0a95819db2e8 app: url: http://my-github-app.com name: my github app client_id: abcde12345fghij67890 note: optional note note_url: http://optional/note/url updated_at: '2011-09-06T20:39:23Z' created_at: '2011-09-06T17:26:27Z' fingerprint: jklmnop12345678 integration: value: id: 1 slug: octoapp node_id: MDExOkludGVncmF0aW9uMQ== owner: login: github id: 1 node_id: MDEyOk9yZ2FuaXphdGlvbjE= url: https://api.github.com/orgs/github repos_url: https://api.github.com/orgs/github/repos events_url: https://api.github.com/orgs/github/events avatar_url: https://github.com/images/error/octocat_happy.gif gravatar_id: '' html_url: https://github.com/octocat followers_url: https://api.github.com/users/octocat/followers following_url: https://api.github.com/users/octocat/following{/other_user} gists_url: https://api.github.com/users/octocat/gists{/gist_id} starred_url: https://api.github.com/users/octocat/starred{/owner}{/repo} subscriptions_url: https://api.github.com/users/octocat/subscriptions organizations_url: https://api.github.com/users/octocat/orgs received_events_url: https://api.github.com/users/octocat/received_events type: User site_admin: true name: Octocat App description: '' external_url: https://example.com html_url: https://github.com/apps/octoapp created_at: '2017-07-08T16:18:44-04:00' updated_at: '2017-07-08T16:18:44-04:00' permissions: metadata: read contents: read issues: write single_file: write events: - push - pull_request integration-from-manifest: value: id: 1 slug: octoapp node_id: MDxOkludGVncmF0aW9uMQ== owner: login: github id: 1 node_id: MDEyOk9yZ2FuaXphdGlvbjE= url: https://api.github.com/orgs/github repos_url: https://api.github.com/orgs/github/repos events_url: https://api.github.com/orgs/github/events avatar_url: https://github.com/images/error/octocat_happy.gif gravatar_id: '' html_url: https://github.com/octocat followers_url: https://api.github.com/users/octocat/followers following_url: https://api.github.com/users/octocat/following{/other_user} gists_url: https://api.github.com/users/octocat/gists{/gist_id} starred_url: https://api.github.com/users/octocat/starred{/owner}{/repo} subscriptions_url: https://api.github.com/users/octocat/subscriptions organizations_url: https://api.github.com/users/octocat/orgs received_events_url: https://api.github.com/users/octocat/received_events type: User site_admin: true name: Octocat App description: '' external_url: https://example.com html_url: https://github.com/apps/octoapp created_at: '2017-07-08T16:18:44-04:00' updated_at: '2017-07-08T16:18:44-04:00' permissions: metadata: read contents: read issues: write single_file: write events: - push - pull_request client_id: Iv1.8a61f9b3a7aba766 client_secret: 1726be1638095a19edd134c77bde3aa2ece1e5d8 webhook_secret: e340154128314309424b7c8e90325147d99fdafa pem: | -----BEGIN RSA PRIVATE KEY----- MIIEowIBAAKCAQEAuEPzOUE+kiEH1WLiMeBytTEF856j0hOVcSUSUkZxKvqczkWM 9vo1gDyC7ZXhdH9fKh32aapba3RSsp4ke+giSmYTk2mGR538ShSDxh0OgpJmjiKP X0Bj4j5sFqfXuCtl9SkH4iueivv4R53ktqM+n6hk98l6hRwC39GVIblAh2lEM4L/ 6WvYwuQXPMM5OG2Ryh2tDZ1WS5RKfgq+9ksNJ5Q9UtqtqHkO+E63N5OK9sbzpUUm oNaOl3udTlZD3A8iqwMPVxH4SxgATBPAc+bmjk6BMJ0qIzDcVGTrqrzUiywCTLma szdk8GjzXtPDmuBgNn+o6s02qVGpyydgEuqmTQIDAQABAoIBACL6AvkjQVVLn8kJ dBYznJJ4M8ECo+YEgaFwgAHODT0zRQCCgzd+Vxl4YwHmKV2Lr+y2s0drZt8GvYva KOK8NYYZyi15IlwFyRXmvvykF1UBpSXluYFDH7KaVroWMgRreHcIys5LqVSIb6Bo gDmK0yBLPp8qR29s2b7ScZRtLaqGJiX+j55rNzrZwxHkxFHyG9OG+u9IsBElcKCP kYCVE8ZdYexfnKOZbgn2kZB9qu0T/Mdvki8yk3I2bI6xYO24oQmhnT36qnqWoCBX NuCNsBQgpYZeZET8mEAUmo9d+ABmIHIvSs005agK8xRaP4+6jYgy6WwoejJRF5yd NBuF7aECgYEA50nZ4FiZYV0vcJDxFYeY3kYOvVuKn8OyW+2rg7JIQTremIjv8FkE ZnwuF9ZRxgqLxUIfKKfzp/5l5LrycNoj2YKfHKnRejxRWXqG+ZETfxxlmlRns0QG J4+BYL0CoanDSeA4fuyn4Bv7cy/03TDhfg/Uq0Aeg+hhcPE/vx3ebPsCgYEAy/Pv eDLssOSdeyIxf0Brtocg6aPXIVaLdus+bXmLg77rJIFytAZmTTW8SkkSczWtucI3 FI1I6sei/8FdPzAl62/JDdlf7Wd9K7JIotY4TzT7Tm7QU7xpfLLYIP1bOFjN81rk 77oOD4LsXcosB/U6s1blPJMZ6AlO2EKs10UuR1cCgYBipzuJ2ADEaOz9RLWwi0AH Pza2Sj+c2epQD9ZivD7Zo/Sid3ZwvGeGF13JyR7kLEdmAkgsHUdu1rI7mAolXMaB 1pdrsHureeLxGbRM6za3tzMXWv1Il7FQWoPC8ZwXvMOR1VQDv4nzq7vbbA8z8c+c 57+8tALQHOTDOgQIzwK61QKBgERGVc0EJy4Uag+VY8J4m1ZQKBluqo7TfP6DQ7O8 M5MX73maB/7yAX8pVO39RjrhJlYACRZNMbK+v/ckEQYdJSSKmGCVe0JrGYDuPtic I9+IGfSorf7KHPoMmMN6bPYQ7Gjh7a++tgRFTMEc8956Hnt4xGahy9NcglNtBpVN 6G8jAoGBAMCh028pdzJa/xeBHLLaVB2sc0Fe7993WlsPmnVE779dAz7qMscOtXJK fgtriltLSSD6rTA9hUAsL/X62rY0wdXuNdijjBb/qvrx7CAV6i37NK1CjABNjsfG ZM372Ac6zc1EqSrid2IjET1YqyIW2KGLI1R2xbQc98UGlt48OdWu -----END RSA PRIVATE KEY----- webhook-config: value: content_type: json insecure_ssl: '0' secret: "********" url: https://example.com/webhook base-installation-items: value: - id: 1 account: login: octocat id: 1 node_id: MDQ6VXNlcjE= avatar_url: https://github.com/images/error/octocat_happy.gif gravatar_id: '' url: https://api.github.com/users/octocat html_url: https://github.com/octocat followers_url: https://api.github.com/users/octocat/followers following_url: https://api.github.com/users/octocat/following{/other_user} gists_url: https://api.github.com/users/octocat/gists{/gist_id} starred_url: https://api.github.com/users/octocat/starred{/owner}{/repo} subscriptions_url: https://api.github.com/users/octocat/subscriptions organizations_url: https://api.github.com/users/octocat/orgs repos_url: https://api.github.com/users/octocat/repos events_url: https://api.github.com/users/octocat/events{/privacy} received_events_url: https://api.github.com/users/octocat/received_events type: User site_admin: false access_tokens_url: https://api.github.com/installations/1/access_tokens repositories_url: https://api.github.com/installation/repositories html_url: https://github.com/organizations/github/settings/installations/1 app_id: 1 target_id: 1 target_type: Organization permissions: checks: write metadata: read contents: read events: - push - pull_request single_file_name: config.yaml has_multiple_single_files: true single_file_paths: - config.yml - ".github/issue_TEMPLATE.md" repository_selection: selected created_at: '2017-07-08T16:18:44-04:00' updated_at: '2017-07-08T16:18:44-04:00' app_slug: github-actions suspended_at: suspended_by: base-installation: value: id: 1 account: login: octocat id: 1 node_id: MDQ6VXNlcjE= avatar_url: https://github.com/images/error/octocat_happy.gif gravatar_id: '' url: https://api.github.com/users/octocat html_url: https://github.com/octocat followers_url: https://api.github.com/users/octocat/followers following_url: https://api.github.com/users/octocat/following{/other_user} gists_url: https://api.github.com/users/octocat/gists{/gist_id} starred_url: https://api.github.com/users/octocat/starred{/owner}{/repo} subscriptions_url: https://api.github.com/users/octocat/subscriptions organizations_url: https://api.github.com/users/octocat/orgs repos_url: https://api.github.com/users/octocat/repos events_url: https://api.github.com/users/octocat/events{/privacy} received_events_url: https://api.github.com/users/octocat/received_events type: User site_admin: false access_tokens_url: https://api.github.com/installations/1/access_tokens repositories_url: https://api.github.com/installation/repositories html_url: https://github.com/organizations/github/settings/installations/1 app_id: 1 target_id: 1 target_type: Organization permissions: checks: write metadata: read contents: read events: - push - pull_request single_file_name: config.yaml has_multiple_single_files: true single_file_paths: - config.yml - ".github/issue_TEMPLATE.md" repository_selection: selected created_at: '2017-07-08T16:18:44-04:00' updated_at: '2017-07-08T16:18:44-04:00' app_slug: github-actions suspended_at: suspended_by: installation-token: value: token: ghs_16C7e42F292c6912E7710c838347Ae178B4a expires_at: '2016-07-11T22:14:10Z' permissions: issues: write contents: read repository_selection: selected repositories: - id: 1296269 node_id: MDEwOlJlcG9zaXRvcnkxMjk2MjY5 name: Hello-World full_name: octocat/Hello-World owner: login: octocat id: 1 node_id: MDQ6VXNlcjE= avatar_url: https://github.com/images/error/octocat_happy.gif gravatar_id: '' url: https://api.github.com/users/octocat html_url: https://github.com/octocat followers_url: https://api.github.com/users/octocat/followers following_url: https://api.github.com/users/octocat/following{/other_user} gists_url: https://api.github.com/users/octocat/gists{/gist_id} starred_url: https://api.github.com/users/octocat/starred{/owner}{/repo} subscriptions_url: https://api.github.com/users/octocat/subscriptions organizations_url: https://api.github.com/users/octocat/orgs repos_url: https://api.github.com/users/octocat/repos events_url: https://api.github.com/users/octocat/events{/privacy} received_events_url: https://api.github.com/users/octocat/received_events type: User site_admin: false private: false html_url: https://github.com/octocat/Hello-World description: This your first repo! fork: false url: https://api.github.com/repos/octocat/Hello-World archive_url: https://api.github.com/repos/octocat/Hello-World/{archive_format}{/ref} assignees_url: https://api.github.com/repos/octocat/Hello-World/assignees{/user} blobs_url: https://api.github.com/repos/octocat/Hello-World/git/blobs{/sha} branches_url: https://api.github.com/repos/octocat/Hello-World/branches{/branch} collaborators_url: https://api.github.com/repos/octocat/Hello-World/collaborators{/collaborator} comments_url: https://api.github.com/repos/octocat/Hello-World/comments{/number} commits_url: https://api.github.com/repos/octocat/Hello-World/commits{/sha} compare_url: https://api.github.com/repos/octocat/Hello-World/compare/{base}...{head} contents_url: https://api.github.com/repos/octocat/Hello-World/contents/{+path} contributors_url: https://api.github.com/repos/octocat/Hello-World/contributors deployments_url: https://api.github.com/repos/octocat/Hello-World/deployments downloads_url: https://api.github.com/repos/octocat/Hello-World/downloads events_url: https://api.github.com/repos/octocat/Hello-World/events forks_url: https://api.github.com/repos/octocat/Hello-World/forks git_commits_url: https://api.github.com/repos/octocat/Hello-World/git/commits{/sha} git_refs_url: https://api.github.com/repos/octocat/Hello-World/git/refs{/sha} git_tags_url: https://api.github.com/repos/octocat/Hello-World/git/tags{/sha} git_url: git:github.com/octocat/Hello-World.git issue_comment_url: https://api.github.com/repos/octocat/Hello-World/issues/comments{/number} issue_events_url: https://api.github.com/repos/octocat/Hello-World/issues/events{/number} issues_url: https://api.github.com/repos/octocat/Hello-World/issues{/number} keys_url: https://api.github.com/repos/octocat/Hello-World/keys{/key_id} labels_url: https://api.github.com/repos/octocat/Hello-World/labels{/name} languages_url: https://api.github.com/repos/octocat/Hello-World/languages merges_url: https://api.github.com/repos/octocat/Hello-World/merges milestones_url: https://api.github.com/repos/octocat/Hello-World/milestones{/number} notifications_url: https://api.github.com/repos/octocat/Hello-World/notifications{?since,all,participating} pulls_url: https://api.github.com/repos/octocat/Hello-World/pulls{/number} releases_url: https://api.github.com/repos/octocat/Hello-World/releases{/id} ssh_url: git@github.com:octocat/Hello-World.git stargazers_url: https://api.github.com/repos/octocat/Hello-World/stargazers statuses_url: https://api.github.com/repos/octocat/Hello-World/statuses/{sha} subscribers_url: https://api.github.com/repos/octocat/Hello-World/subscribers subscription_url: https://api.github.com/repos/octocat/Hello-World/subscription tags_url: https://api.github.com/repos/octocat/Hello-World/tags teams_url: https://api.github.com/repos/octocat/Hello-World/teams trees_url: https://api.github.com/repos/octocat/Hello-World/git/trees{/sha} clone_url: https://github.com/octocat/Hello-World.git mirror_url: git:git.example.com/octocat/Hello-World hooks_url: https://api.github.com/repos/octocat/Hello-World/hooks svn_url: https://svn.github.com/octocat/Hello-World homepage: https://github.com language: forks_count: 9 stargazers_count: 80 watchers_count: 80 size: 108 default_branch: master open_issues_count: 0 is_template: true topics: - octocat - atom - electron - api has_issues: true has_projects: true has_wiki: true has_pages: false has_downloads: true archived: false disabled: false visibility: public pushed_at: '2011-01-26T19:06:43Z' created_at: '2011-01-26T19:01:12Z' updated_at: '2011-01-26T19:14:43Z' permissions: admin: false push: false pull: true allow_rebase_merge: true template_repository: temp_clone_token: ABTLWHOULUVAXGTRYU7OC2876QJ2O allow_squash_merge: true delete_branch_on_merge: true allow_merge_commit: true subscribers_count: 42 network_count: 0 license: key: mit name: MIT License url: https://api.github.com/licenses/mit spdx_id: MIT node_id: MDc6TGljZW5zZW1pdA== html_url: https://github.com/licenses/mit forks: 1 open_issues: 1 watchers: 1 application-grant-items: value: - id: 1 url: https://api.github.com/applications/grants/1 app: url: http://my-github-app.com name: my github app client_id: abcde12345fghij67890 created_at: '2011-09-06T17:26:27Z' updated_at: '2011-09-06T20:39:23Z' scopes: - public_repo application-grant: value: id: 1 url: https://api.github.com/applications/grants/1 app: url: http://my-github-app.com name: my github app client_id: abcde12345fghij67890 created_at: '2011-09-06T17:26:27Z' updated_at: '2011-09-06T20:39:23Z' scopes: - public_repo authorization-with-user: value: id: 1 url: https://api.github.com/authorizations/1 scopes: - public_repo - user token: ghu_16C7e42F292c6912E7710c838347Ae178B4a token_last_eight: Ae178B4a hashed_token: 25f94a2a5c7fbaf499c665bc73d67c1c87e496da8985131633ee0a95819db2e8 app: url: http://my-github-app.com name: my github app client_id: abcde12345fghij67890 note: optional note note_url: http://optional/note/url updated_at: '2011-09-06T20:39:23Z' created_at: '2011-09-06T17:26:27Z' fingerprint: jklmnop12345678 expires_at: '2011-09-08T17:26:27Z' user: login: octocat id: 1 node_id: MDQ6VXNlcjE= avatar_url: https://github.com/images/error/octocat_happy.gif gravatar_id: '' url: https://api.github.com/users/octocat html_url: https://github.com/octocat followers_url: https://api.github.com/users/octocat/followers following_url: https://api.github.com/users/octocat/following{/other_user} gists_url: https://api.github.com/users/octocat/gists{/gist_id} starred_url: https://api.github.com/users/octocat/starred{/owner}{/repo} subscriptions_url: https://api.github.com/users/octocat/subscriptions organizations_url: https://api.github.com/users/octocat/orgs repos_url: https://api.github.com/users/octocat/repos events_url: https://api.github.com/users/octocat/events{/privacy} received_events_url: https://api.github.com/users/octocat/received_events type: User site_admin: false scope-token: value: id: 1 url: https://api.github.com/authorizations/1 scopes: [] token: ghu_16C7e42F292c6912E7710c838347Ae178B4a token_last_eight: Ae178B4a hashed_token: 25f94a2a5c7fbaf499c665bc73d67c1c87e496da8985131633ee0a95819db2e8 app: url: http://my-github-app.com name: my github app client_id: abcde12345fghij67890 note: optional note note_url: http://optional/note/url updated_at: '2011-09-06T20:39:23Z' created_at: '2011-09-06T17:26:27Z' fingerprint: jklmnop12345678 expires_at: '2011-09-08T17:26:27Z' user: login: octocat id: 1 node_id: MDQ6VXNlcjE= avatar_url: https://github.com/images/error/octocat_happy.gif gravatar_id: '' url: https://api.github.com/users/octocat html_url: https://github.com/octocat followers_url: https://api.github.com/users/octocat/followers following_url: https://api.github.com/users/octocat/following{/other_user} gists_url: https://api.github.com/users/octocat/gists{/gist_id} starred_url: https://api.github.com/users/octocat/starred{/owner}{/repo} subscriptions_url: https://api.github.com/users/octocat/subscriptions organizations_url: https://api.github.com/users/octocat/orgs repos_url: https://api.github.com/users/octocat/repos events_url: https://api.github.com/users/octocat/events{/privacy} received_events_url: https://api.github.com/users/octocat/received_events type: User site_admin: false installation: permissions: metadata: read issues: write contents: read repository_selection: selected single_file_name: ".github/workflow.yml" repositories_url: https://api.github.com/user/repos account: login: octocat id: 1 node_id: MDQ6VXNlcjE= avatar_url: https://github.com/images/error/octocat_happy.gif gravatar_id: '' url: https://api.github.com/users/octocat html_url: https://github.com/octocat followers_url: https://api.github.com/users/octocat/followers following_url: https://api.github.com/users/octocat/following{/other_user} gists_url: https://api.github.com/users/octocat/gists{/gist_id} starred_url: https://api.github.com/users/octocat/starred{/owner}{/repo} subscriptions_url: https://api.github.com/users/octocat/subscriptions organizations_url: https://api.github.com/users/octocat/orgs repos_url: https://api.github.com/users/octocat/repos events_url: https://api.github.com/users/octocat/events{/privacy} received_events_url: https://api.github.com/users/octocat/received_events type: User site_admin: false has_multiple_single_files: false single_file_paths: [] authorization-response-if-returning-an-existing-token-2: value: id: 1 url: https://api.github.com/authorizations/1 scopes: - public_repo token: ghu_16C7e42F292c6912E7710c838347Ae178B4a token_last_eight: Ae178B4a hashed_token: 25f94a2a5c7fbaf499c665bc73d67c1c87e496da8985131633ee0a95819db2e8 app: url: http://my-github-app.com name: my github app client_id: abcde12345fghij67890 note: optional note note_url: http://optional/note/url updated_at: '2011-09-06T20:39:23Z' created_at: '2011-09-06T17:26:27Z' fingerprint: '' authorization-response-if-returning-an-existing-token: value: id: 1 url: https://api.github.com/authorizations/1 scopes: - public_repo token: ghu_16C7e42F292c6912E7710c838347Ae178B4a token_last_eight: Ae178B4a hashed_token: 25f94a2a5c7fbaf499c665bc73d67c1c87e496da8985131633ee0a95819db2e8 app: url: http://my-github-app.com name: my github app client_id: abcde12345fghij67890 note: optional note note_url: http://optional/note/url updated_at: '2011-09-06T20:39:23Z' created_at: '2011-09-06T17:26:27Z' fingerprint: jklmnop12345678 authorization-3: value: id: 1 url: https://api.github.com/authorizations/1 scopes: - public_repo token: ghu_16C7e42F292c6912E7710c838347Ae178B4a token_last_eight: Ae178B4a hashed_token: 25f94a2a5c7fbaf499c665bc73d67c1c87e496da8985131633ee0a95819db2e8 app: url: http://my-github-app.com name: my github app client_id: abcde12345fghij67890 note: optional note note_url: http://optional/note/url updated_at: '2011-09-06T20:39:23Z' created_at: '2011-09-06T17:26:27Z' fingerprint: jklmnop12345678 authorization-2: value: id: 1 url: https://api.github.com/authorizations/1 scopes: - public_repo token: ghu_16C7e42F292c6912E7710c838347Ae178B4a token_last_eight: Ae178B4a hashed_token: 25f94a2a5c7fbaf499c665bc73d67c1c87e496da8985131633ee0a95819db2e8 app: url: http://my-github-app.com name: my github app client_id: abcde12345fghij67890 note: optional note note_url: http://optional/note/url updated_at: '2011-09-06T20:39:23Z' created_at: '2011-09-06T17:26:27Z' fingerprint: jklmnop12345678 code-of-conduct-simple-items: value: - key: citizen_code_of_conduct name: Citizen Code of Conduct url: https://api.github.com/codes_of_conduct/citizen_code_of_conduct html_url: http://citizencodeofconduct.org/ - key: contributor_covenant name: Contributor Covenant url: https://api.github.com/codes_of_conduct/contributor_covenant html_url: https://www.contributor-covenant.org/version/2/0/code_of_conduct/ code-of-conduct: value: key: contributor_covenant name: Contributor Covenant url: https://api.github.com/codes_of_conduct/contributor_covenant body: | # Contributor Covenant Code of Conduct ## Our Pledge In the interest of fostering an open and welcoming environment, we as contributors and maintainers pledge to making participation in our project and our community a harassment-free experience for everyone, regardless of age, body size, disability, ethnicity, gender identity and expression, level of experience, nationality, personal appearance, race, religion, or sexual identity and orientation. ## Our Standards Examples of behavior that contributes to creating a positive environment include: * Using welcoming and inclusive language * Being respectful of differing viewpoints and experiences * Gracefully accepting constructive criticism * Focusing on what is best for the community * Showing empathy towards other community members Examples of unacceptable behavior by participants include: * The use of sexualized language or imagery and unwelcome sexual attention or advances * Trolling, insulting/derogatory comments, and personal or political attacks * Public or private harassment * Publishing others' private information, such as a physical or electronic address, without explicit permission * Other conduct which could reasonably be considered inappropriate in a professional setting ## Our Responsibilities Project maintainers are responsible for clarifying the standards of acceptable behavior and are expected to take appropriate and fair corrective action in response to any instances of unacceptable behavior. Project maintainers have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, or to ban temporarily or permanently any contributor for other behaviors that they deem inappropriate, threatening, offensive, or harmful. ## Scope This Code of Conduct applies both within project spaces and in public spaces when an individual is representing the project or its community. Examples of representing a project or community include using an official project e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event. Representation of a project may be further defined and clarified by project maintainers. ## Enforcement Instances of abusive, harassing, or otherwise unacceptable behavior may be reported by contacting the project team at [EMAIL]. The project team will review and investigate all complaints, and will respond in a way that it deems appropriate to the circumstances. The project team is obligated to maintain confidentiality with regard to the reporter of an incident. Further details of specific enforcement policies may be posted separately. Project maintainers who do not follow or enforce the Code of Conduct in good faith may face temporary or permanent repercussions as determined by other members of the project's leadership. ## Attribution This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, available at [http://contributor-covenant.org/version/1/4][version] [homepage]: http://contributor-covenant.org [version]: http://contributor-covenant.org/version/1/4/ html_url: http://contributor-covenant.org/version/1/4/ announcement: summary: Default response value: announcement: Very **important** announcement about _nothing_. expires_at: '2021-01-01T00:00:00.000+00:00' license-info: value: seats: 1400 seats_used: 1316 seats_available: 84 kind: standard days_until_expiration: 365 expire_at: 2016/02/06 12:41:52 -0600 enterprise-overview: value: repos: total_repos: 212 root_repos: 194 fork_repos: 18 org_repos: 51 total_pushes: 3082 total_wikis: 15 hooks: total_hooks: 27 active_hooks: 23 inactive_hooks: 4 pages: total_pages: 36 orgs: total_orgs: 33 disabled_orgs: 0 total_teams: 60 total_team_members: 314 users: total_users: 254 admin_users: 45 suspended_users: 21 pulls: total_pulls: 86 merged_pulls: 60 mergeable_pulls: 21 unmergeable_pulls: 3 issues: total_issues: 179 open_issues: 83 closed_issues: 96 milestones: total_milestones: 7 open_milestones: 6 closed_milestones: 1 gists: total_gists: 178 private_gists: 151 public_gists: 25 comments: total_commit_comments: 6 total_gist_comments: 28 total_issue_comments: 366 total_pull_request_comments: 30 actions-enterprise-permissions: value: enabled_organizations: all allowed_actions: selected selected_actions_url: https://api.github.com/enterprises/2/actions/permissions/selected-actions organization-targets: value: total_count: 1 organizations: - login: octocat id: 161335 node_id: MDEwOlJlcG9zaXRvcnkxMjk2MjY5 url: https://api.github.com/orgs/octo-org repos_url: https://api.github.com/orgs/octo-org/repos events_url: https://api.github.com/orgs/octo-org/events hooks_url: https://api.github.com/orgs/octo-org/hooks issues_url: https://api.github.com/orgs/octo-org/issues members_url: https://api.github.com/orgs/octo-org/members{/member} public_members_url: https://api.github.com/orgs/octo-org/public_members{/member} avatar_url: https://github.com/images/error/octocat_happy.gif description: A great organization selected-actions: value: github_owned_allowed: true verified_allowed: false patterns_allowed: - monalisa/octocat@* - docker/* runner-groups-enterprise: value: total_count: 3 runner_groups: - id: 1 name: Default visibility: all default: true runners_url: https://api.github.com/enterprises/octo-corp/actions/runner_groups/1/runners allows_public_repositories: false - id: 2 name: octo-runner-group visibility: selected default: false selected_organizations_url: https://api.github.com/enterprises/octo-corp/actions/runner_groups/2/organizations runners_url: https://api.github.com/enterprises/octo-corp/actions/runner_groups/2/runners allows_public_repositories: true - id: 3 name: expensive-hardware visibility: private default: false runners_url: https://api.github.com/enterprises/octo-corp/actions/runner_groups/3/runners allows_public_repositories: true runner-group-enterprise: value: id: 2 name: octo-runner-group visibility: selected default: false selected_organizations_url: https://api.github.com/enterprises/octo-corp/actions/runner-groups/2/organizations runners_url: https://api.github.com/enterprises/octo-corp/actions/runner-groups/2/runners allows_public_repositories: false runner-group-update-enterprise: value: id: 2 name: Expensive hardware runners visibility: selected default: false selected_organizations_url: https://api.github.com/enterprises/octo-corp/actions/runner-groups/2/organizations runners_url: https://api.github.com/enterprises/octo-corp/actions/runner-groups/2/runners allows_public_repositories: true runner-paginated: value: total_count: 2 runners: - id: 23 name: linux_runner os: linux status: online busy: true labels: - id: 5 name: self-hosted type: read-only - id: 7 name: X64 type: read-only - id: 11 name: Linux type: read-only - id: 24 name: mac_runner os: macos status: offline busy: false labels: - id: 5 name: self-hosted type: read-only - id: 7 name: X64 type: read-only - id: 20 name: macOS type: read-only - id: 21 name: no-gpu type: custom runner-application-items: value: - os: osx architecture: x64 download_url: https://github.com/actions/runner/releases/download/v2.164.0/actions-runner-osx-x64-2.164.0.tar.gz filename: actions-runner-osx-x64-2.164.0.tar.gz - os: linux architecture: x64 download_url: https://github.com/actions/runner/releases/download/v2.164.0/actions-runner-linux-x64-2.164.0.tar.gz filename: actions-runner-linux-x64-2.164.0.tar.gz - os: linux architecture: arm download_url: https://github.com/actions/runner/releases/download/v2.164.0/actions-runner-linux-arm-2.164.0.tar.gz filename: actions-runner-linux-arm-2.164.0.tar.gz - os: win architecture: x64 download_url: https://github.com/actions/runner/releases/download/v2.164.0/actions-runner-win-x64-2.164.0.zip filename: actions-runner-win-x64-2.164.0.zip - os: linux architecture: arm64 download_url: https://github.com/actions/runner/releases/download/v2.164.0/actions-runner-linux-arm64-2.164.0.tar.gz filename: actions-runner-linux-arm64-2.164.0.tar.gz authentication-token: value: token: LLBF3JGZDX3P5PMEXLND6TS6FCWO6 expires_at: '2020-01-22T12:13:35.123-08:00' authentication-token-2: value: token: AABF3JGZDX3P5PMEXLND6TS6FCWO6 expires_at: '2020-01-29T12:13:35.123-08:00' runner: value: id: 23 name: MBP os: macos status: online busy: true labels: - id: 5 name: self-hosted type: read-only - id: 7 name: X64 type: read-only - id: 20 name: macOS type: read-only - id: 21 name: no-gpu type: custom feed: value: timeline_url: https://github.com/timeline user_url: https://github.com/{user} current_user_public_url: https://github.com/octocat current_user_url: https://github.com/octocat.private?token=abc123 current_user_actor_url: https://github.com/octocat.private.actor?token=abc123 current_user_organization_url: '' current_user_organization_urls: - https://github.com/organizations/github/octocat.private.atom?token=abc123 _links: timeline: href: https://github.com/timeline type: application/atom+xml user: href: https://github.com/{user} type: application/atom+xml current_user_public: href: https://github.com/octocat type: application/atom+xml current_user: href: https://github.com/octocat.private?token=abc123 type: application/atom+xml current_user_actor: href: https://github.com/octocat.private.actor?token=abc123 type: application/atom+xml current_user_organization: href: '' type: '' current_user_organizations: - href: https://github.com/organizations/github/octocat.private.atom?token=abc123 type: application/atom+xml base-gist-items: value: - url: https://api.github.com/gists/aa5a315d61ae9438b18d forks_url: https://api.github.com/gists/aa5a315d61ae9438b18d/forks commits_url: https://api.github.com/gists/aa5a315d61ae9438b18d/commits id: aa5a315d61ae9438b18d node_id: MDQ6R2lzdGFhNWEzMTVkNjFhZTk0MzhiMThk git_pull_url: https://gist.github.com/aa5a315d61ae9438b18d.git git_push_url: https://gist.github.com/aa5a315d61ae9438b18d.git html_url: https://gist.github.com/aa5a315d61ae9438b18d files: hello_world.rb: filename: hello_world.rb type: application/x-ruby language: Ruby raw_url: https://gist.githubusercontent.com/octocat/6cad326836d38bd3a7ae/raw/db9c55113504e46fa076e7df3a04ce592e2e86d8/hello_world.rb size: 167 public: true created_at: '2010-04-14T02:15:15Z' updated_at: '2011-06-20T11:34:15Z' description: Hello World Examples comments: 0 user: comments_url: https://api.github.com/gists/aa5a315d61ae9438b18d/comments/ owner: login: octocat id: 1 node_id: MDQ6VXNlcjE= avatar_url: https://github.com/images/error/octocat_happy.gif gravatar_id: '' url: https://api.github.com/users/octocat html_url: https://github.com/octocat followers_url: https://api.github.com/users/octocat/followers following_url: https://api.github.com/users/octocat/following{/other_user} gists_url: https://api.github.com/users/octocat/gists{/gist_id} starred_url: https://api.github.com/users/octocat/starred{/owner}{/repo} subscriptions_url: https://api.github.com/users/octocat/subscriptions organizations_url: https://api.github.com/users/octocat/orgs repos_url: https://api.github.com/users/octocat/repos events_url: https://api.github.com/users/octocat/events{/privacy} received_events_url: https://api.github.com/users/octocat/received_events type: User site_admin: false truncated: false gist: value: url: https://api.github.com/gists/aa5a315d61ae9438b18d forks_url: https://api.github.com/gists/aa5a315d61ae9438b18d/forks commits_url: https://api.github.com/gists/aa5a315d61ae9438b18d/commits id: aa5a315d61ae9438b18d node_id: MDQ6R2lzdGFhNWEzMTVkNjFhZTk0MzhiMThk git_pull_url: https://gist.github.com/aa5a315d61ae9438b18d.git git_push_url: https://gist.github.com/aa5a315d61ae9438b18d.git html_url: https://gist.github.com/aa5a315d61ae9438b18d created_at: '2010-04-14T02:15:15Z' updated_at: '2011-06-20T11:34:15Z' description: Hello World Examples comments: 0 comments_url: https://api.github.com/gists/aa5a315d61ae9438b18d/comments/ gist-comment-items: value: - id: 1 node_id: MDExOkdpc3RDb21tZW50MQ== url: https://api.github.com/gists/a6db0bec360bb87e9418/comments/1 body: Just commenting for the sake of commenting user: login: octocat id: 1 node_id: MDQ6VXNlcjE= avatar_url: https://github.com/images/error/octocat_happy.gif gravatar_id: '' url: https://api.github.com/users/octocat html_url: https://github.com/octocat followers_url: https://api.github.com/users/octocat/followers following_url: https://api.github.com/users/octocat/following{/other_user} gists_url: https://api.github.com/users/octocat/gists{/gist_id} starred_url: https://api.github.com/users/octocat/starred{/owner}{/repo} subscriptions_url: https://api.github.com/users/octocat/subscriptions organizations_url: https://api.github.com/users/octocat/orgs repos_url: https://api.github.com/users/octocat/repos events_url: https://api.github.com/users/octocat/events{/privacy} received_events_url: https://api.github.com/users/octocat/received_events type: User site_admin: false created_at: '2011-04-18T23:23:56Z' updated_at: '2011-04-18T23:23:56Z' author_association: COLLABORATOR gist-comment: value: id: 1 node_id: MDExOkdpc3RDb21tZW50MQ== url: https://api.github.com/gists/a6db0bec360bb87e9418/comments/1 body: Just commenting for the sake of commenting user: login: octocat id: 1 node_id: MDQ6VXNlcjE= avatar_url: https://github.com/images/error/octocat_happy.gif gravatar_id: '' url: https://api.github.com/users/octocat html_url: https://github.com/octocat followers_url: https://api.github.com/users/octocat/followers following_url: https://api.github.com/users/octocat/following{/other_user} gists_url: https://api.github.com/users/octocat/gists{/gist_id} starred_url: https://api.github.com/users/octocat/starred{/owner}{/repo} subscriptions_url: https://api.github.com/users/octocat/subscriptions organizations_url: https://api.github.com/users/octocat/orgs repos_url: https://api.github.com/users/octocat/repos events_url: https://api.github.com/users/octocat/events{/privacy} received_events_url: https://api.github.com/users/octocat/received_events type: User site_admin: false created_at: '2011-04-18T23:23:56Z' updated_at: '2011-04-18T23:23:56Z' author_association: COLLABORATOR gist-commit-items: value: - url: https://api.github.com/gists/aa5a315d61ae9438b18d/57a7f021a713b1c5a6a199b54cc514735d2d462f version: 57a7f021a713b1c5a6a199b54cc514735d2d462f user: login: octocat id: 1 node_id: MDQ6VXNlcjE= avatar_url: https://github.com/images/error/octocat_happy.gif gravatar_id: '' url: https://api.github.com/users/octocat html_url: https://github.com/octocat followers_url: https://api.github.com/users/octocat/followers following_url: https://api.github.com/users/octocat/following{/other_user} gists_url: https://api.github.com/users/octocat/gists{/gist_id} starred_url: https://api.github.com/users/octocat/starred{/owner}{/repo} subscriptions_url: https://api.github.com/users/octocat/subscriptions organizations_url: https://api.github.com/users/octocat/orgs repos_url: https://api.github.com/users/octocat/repos events_url: https://api.github.com/users/octocat/events{/privacy} received_events_url: https://api.github.com/users/octocat/received_events type: User site_admin: false change_status: deletions: 0 additions: 180 total: 180 committed_at: '2010-04-14T02:15:15Z' gist-fork-items: value: - url: https://api.github.com/gists/aa5a315d61ae9438b18d forks_url: https://api.github.com/gists/aa5a315d61ae9438b18d/forks commits_url: https://api.github.com/gists/aa5a315d61ae9438b18d/commits id: aa5a315d61ae9438b18d node_id: MDQ6R2lzdGFhNWEzMTVkNjFhZTk0MzhiMThk git_pull_url: https://gist.github.com/aa5a315d61ae9438b18d.git git_push_url: https://gist.github.com/aa5a315d61ae9438b18d.git html_url: https://gist.github.com/aa5a315d61ae9438b18d files: hello_world.rb: filename: hello_world.rb type: application/x-ruby language: Ruby raw_url: https://gist.githubusercontent.com/octocat/6cad326836d38bd3a7ae/raw/db9c55113504e46fa076e7df3a04ce592e2e86d8/hello_world.rb size: 167 public: true created_at: '2010-04-14T02:15:15Z' updated_at: '2011-06-20T11:34:15Z' description: Hello World Examples comments: 1 user: comments_url: https://api.github.com/gists/aa5a315d61ae9438b18d/comments/ owner: login: octocat id: 1 node_id: MDQ6VXNlcjE= avatar_url: https://github.com/images/error/octocat_happy.gif gravatar_id: '' url: https://api.github.com/users/octocat html_url: https://github.com/octocat followers_url: https://api.github.com/users/octocat/followers following_url: https://api.github.com/users/octocat/following{/other_user} gists_url: https://api.github.com/users/octocat/gists{/gist_id} starred_url: https://api.github.com/users/octocat/starred{/owner}{/repo} subscriptions_url: https://api.github.com/users/octocat/subscriptions organizations_url: https://api.github.com/users/octocat/orgs repos_url: https://api.github.com/users/octocat/repos events_url: https://api.github.com/users/octocat/events{/privacy} received_events_url: https://api.github.com/users/octocat/received_events type: User site_admin: false base-gist: value: url: https://api.github.com/gists/aa5a315d61ae9438b18d forks_url: https://api.github.com/gists/aa5a315d61ae9438b18d/forks commits_url: https://api.github.com/gists/aa5a315d61ae9438b18d/commits id: aa5a315d61ae9438b18d node_id: MDQ6R2lzdGFhNWEzMTVkNjFhZTk0MzhiMThk git_pull_url: https://gist.github.com/aa5a315d61ae9438b18d.git git_push_url: https://gist.github.com/aa5a315d61ae9438b18d.git html_url: https://gist.github.com/aa5a315d61ae9438b18d files: hello_world.rb: filename: hello_world.rb type: application/x-ruby language: Ruby raw_url: https://gist.githubusercontent.com/octocat/6cad326836d38bd3a7ae/raw/db9c55113504e46fa076e7df3a04ce592e2e86d8/hello_world.rb size: 167 public: true created_at: '2010-04-14T02:15:15Z' updated_at: '2011-06-20T11:34:15Z' description: Hello World Examples comments: 0 user: comments_url: https://api.github.com/gists/aa5a315d61ae9438b18d/comments/ owner: login: octocat id: 1 node_id: MDQ6VXNlcjE= avatar_url: https://github.com/images/error/octocat_happy.gif gravatar_id: '' url: https://api.github.com/users/octocat html_url: https://github.com/octocat followers_url: https://api.github.com/users/octocat/followers following_url: https://api.github.com/users/octocat/following{/other_user} gists_url: https://api.github.com/users/octocat/gists{/gist_id} starred_url: https://api.github.com/users/octocat/starred{/owner}{/repo} subscriptions_url: https://api.github.com/users/octocat/subscriptions organizations_url: https://api.github.com/users/octocat/orgs repos_url: https://api.github.com/users/octocat/repos events_url: https://api.github.com/users/octocat/events{/privacy} received_events_url: https://api.github.com/users/octocat/received_events type: User site_admin: false truncated: false gitignore-template: value: name: C source: | # Object files *.o # Libraries *.lib *.a # Shared objects (inc. Windows DLLs) *.dll *.so *.so.* *.dylib # Executables *.exe *.out *.app repository-paginated-2: value: total_count: 1 repositories: - id: 1296269 node_id: MDEwOlJlcG9zaXRvcnkxMjk2MjY5 name: Hello-World full_name: octocat/Hello-World owner: login: octocat id: 1 node_id: MDQ6VXNlcjE= avatar_url: https://github.com/images/error/octocat_happy.gif gravatar_id: '' url: https://api.github.com/users/octocat html_url: https://github.com/octocat followers_url: https://api.github.com/users/octocat/followers following_url: https://api.github.com/users/octocat/following{/other_user} gists_url: https://api.github.com/users/octocat/gists{/gist_id} starred_url: https://api.github.com/users/octocat/starred{/owner}{/repo} subscriptions_url: https://api.github.com/users/octocat/subscriptions organizations_url: https://api.github.com/users/octocat/orgs repos_url: https://api.github.com/users/octocat/repos events_url: https://api.github.com/users/octocat/events{/privacy} received_events_url: https://api.github.com/users/octocat/received_events type: User site_admin: false private: false html_url: https://github.com/octocat/Hello-World description: This your first repo! fork: false url: https://api.github.com/repos/octocat/Hello-World archive_url: https://api.github.com/repos/octocat/Hello-World/{archive_format}{/ref} assignees_url: https://api.github.com/repos/octocat/Hello-World/assignees{/user} blobs_url: https://api.github.com/repos/octocat/Hello-World/git/blobs{/sha} branches_url: https://api.github.com/repos/octocat/Hello-World/branches{/branch} collaborators_url: https://api.github.com/repos/octocat/Hello-World/collaborators{/collaborator} comments_url: https://api.github.com/repos/octocat/Hello-World/comments{/number} commits_url: https://api.github.com/repos/octocat/Hello-World/commits{/sha} compare_url: https://api.github.com/repos/octocat/Hello-World/compare/{base}...{head} contents_url: https://api.github.com/repos/octocat/Hello-World/contents/{+path} contributors_url: https://api.github.com/repos/octocat/Hello-World/contributors deployments_url: https://api.github.com/repos/octocat/Hello-World/deployments downloads_url: https://api.github.com/repos/octocat/Hello-World/downloads events_url: https://api.github.com/repos/octocat/Hello-World/events forks_url: https://api.github.com/repos/octocat/Hello-World/forks git_commits_url: https://api.github.com/repos/octocat/Hello-World/git/commits{/sha} git_refs_url: https://api.github.com/repos/octocat/Hello-World/git/refs{/sha} git_tags_url: https://api.github.com/repos/octocat/Hello-World/git/tags{/sha} git_url: git:github.com/octocat/Hello-World.git issue_comment_url: https://api.github.com/repos/octocat/Hello-World/issues/comments{/number} issue_events_url: https://api.github.com/repos/octocat/Hello-World/issues/events{/number} issues_url: https://api.github.com/repos/octocat/Hello-World/issues{/number} keys_url: https://api.github.com/repos/octocat/Hello-World/keys{/key_id} labels_url: https://api.github.com/repos/octocat/Hello-World/labels{/name} languages_url: https://api.github.com/repos/octocat/Hello-World/languages merges_url: https://api.github.com/repos/octocat/Hello-World/merges milestones_url: https://api.github.com/repos/octocat/Hello-World/milestones{/number} notifications_url: https://api.github.com/repos/octocat/Hello-World/notifications{?since,all,participating} pulls_url: https://api.github.com/repos/octocat/Hello-World/pulls{/number} releases_url: https://api.github.com/repos/octocat/Hello-World/releases{/id} ssh_url: git@github.com:octocat/Hello-World.git stargazers_url: https://api.github.com/repos/octocat/Hello-World/stargazers statuses_url: https://api.github.com/repos/octocat/Hello-World/statuses/{sha} subscribers_url: https://api.github.com/repos/octocat/Hello-World/subscribers subscription_url: https://api.github.com/repos/octocat/Hello-World/subscription tags_url: https://api.github.com/repos/octocat/Hello-World/tags teams_url: https://api.github.com/repos/octocat/Hello-World/teams trees_url: https://api.github.com/repos/octocat/Hello-World/git/trees{/sha} clone_url: https://github.com/octocat/Hello-World.git mirror_url: git:git.example.com/octocat/Hello-World hooks_url: https://api.github.com/repos/octocat/Hello-World/hooks svn_url: https://svn.github.com/octocat/Hello-World homepage: https://github.com language: forks_count: 9 stargazers_count: 80 watchers_count: 80 size: 108 default_branch: master open_issues_count: 0 is_template: true topics: - octocat - atom - electron - api has_issues: true has_projects: true has_wiki: true has_pages: false has_downloads: true archived: false disabled: false visibility: public pushed_at: '2011-01-26T19:06:43Z' created_at: '2011-01-26T19:01:12Z' updated_at: '2011-01-26T19:14:43Z' allow_rebase_merge: true template_repository: temp_clone_token: ABTLWHOULUVAXGTRYU7OC2876QJ2O allow_squash_merge: true delete_branch_on_merge: true allow_merge_commit: true subscribers_count: 42 network_count: 0 license: key: mit name: MIT License url: https://api.github.com/licenses/mit spdx_id: MIT node_id: MDc6TGljZW5zZW1pdA== html_url: https://github.com/licenses/mit forks: 1 open_issues: 1 watchers: 1 issue-with-repo-items: value: - id: 1 node_id: MDU6SXNzdWUx url: https://api.github.com/repos/octocat/Hello-World/issues/1347 repository_url: https://api.github.com/repos/octocat/Hello-World labels_url: https://api.github.com/repos/octocat/Hello-World/issues/1347/labels{/name} comments_url: https://api.github.com/repos/octocat/Hello-World/issues/1347/comments events_url: https://api.github.com/repos/octocat/Hello-World/issues/1347/events html_url: https://github.com/octocat/Hello-World/issues/1347 number: 1347 state: open title: Found a bug body: I'm having a problem with this. user: login: octocat id: 1 node_id: MDQ6VXNlcjE= avatar_url: https://github.com/images/error/octocat_happy.gif gravatar_id: '' url: https://api.github.com/users/octocat html_url: https://github.com/octocat followers_url: https://api.github.com/users/octocat/followers following_url: https://api.github.com/users/octocat/following{/other_user} gists_url: https://api.github.com/users/octocat/gists{/gist_id} starred_url: https://api.github.com/users/octocat/starred{/owner}{/repo} subscriptions_url: https://api.github.com/users/octocat/subscriptions organizations_url: https://api.github.com/users/octocat/orgs repos_url: https://api.github.com/users/octocat/repos events_url: https://api.github.com/users/octocat/events{/privacy} received_events_url: https://api.github.com/users/octocat/received_events type: User site_admin: false labels: - id: 208045946 node_id: MDU6TGFiZWwyMDgwNDU5NDY= url: https://api.github.com/repos/octocat/Hello-World/labels/bug name: bug description: Something isn't working color: f29513 default: true assignee: login: octocat id: 1 node_id: MDQ6VXNlcjE= avatar_url: https://github.com/images/error/octocat_happy.gif gravatar_id: '' url: https://api.github.com/users/octocat html_url: https://github.com/octocat followers_url: https://api.github.com/users/octocat/followers following_url: https://api.github.com/users/octocat/following{/other_user} gists_url: https://api.github.com/users/octocat/gists{/gist_id} starred_url: https://api.github.com/users/octocat/starred{/owner}{/repo} subscriptions_url: https://api.github.com/users/octocat/subscriptions organizations_url: https://api.github.com/users/octocat/orgs repos_url: https://api.github.com/users/octocat/repos events_url: https://api.github.com/users/octocat/events{/privacy} received_events_url: https://api.github.com/users/octocat/received_events type: User site_admin: false assignees: - login: octocat id: 1 node_id: MDQ6VXNlcjE= avatar_url: https://github.com/images/error/octocat_happy.gif gravatar_id: '' url: https://api.github.com/users/octocat html_url: https://github.com/octocat followers_url: https://api.github.com/users/octocat/followers following_url: https://api.github.com/users/octocat/following{/other_user} gists_url: https://api.github.com/users/octocat/gists{/gist_id} starred_url: https://api.github.com/users/octocat/starred{/owner}{/repo} subscriptions_url: https://api.github.com/users/octocat/subscriptions organizations_url: https://api.github.com/users/octocat/orgs repos_url: https://api.github.com/users/octocat/repos events_url: https://api.github.com/users/octocat/events{/privacy} received_events_url: https://api.github.com/users/octocat/received_events type: User site_admin: false milestone: url: https://api.github.com/repos/octocat/Hello-World/milestones/1 html_url: https://github.com/octocat/Hello-World/milestones/v1.0 labels_url: https://api.github.com/repos/octocat/Hello-World/milestones/1/labels id: 1002604 node_id: MDk6TWlsZXN0b25lMTAwMjYwNA== number: 1 state: open title: v1.0 description: Tracking milestone for version 1.0 creator: login: octocat id: 1 node_id: MDQ6VXNlcjE= avatar_url: https://github.com/images/error/octocat_happy.gif gravatar_id: '' url: https://api.github.com/users/octocat html_url: https://github.com/octocat followers_url: https://api.github.com/users/octocat/followers following_url: https://api.github.com/users/octocat/following{/other_user} gists_url: https://api.github.com/users/octocat/gists{/gist_id} starred_url: https://api.github.com/users/octocat/starred{/owner}{/repo} subscriptions_url: https://api.github.com/users/octocat/subscriptions organizations_url: https://api.github.com/users/octocat/orgs repos_url: https://api.github.com/users/octocat/repos events_url: https://api.github.com/users/octocat/events{/privacy} received_events_url: https://api.github.com/users/octocat/received_events type: User site_admin: false open_issues: 4 closed_issues: 8 created_at: '2011-04-10T20:09:31Z' updated_at: '2014-03-03T18:58:10Z' closed_at: '2013-02-12T13:22:01Z' due_on: '2012-10-09T23:39:01Z' locked: true active_lock_reason: too heated comments: 0 pull_request: url: https://api.github.com/repos/octocat/Hello-World/pulls/1347 html_url: https://github.com/octocat/Hello-World/pull/1347 diff_url: https://github.com/octocat/Hello-World/pull/1347.diff patch_url: https://github.com/octocat/Hello-World/pull/1347.patch closed_at: created_at: '2011-04-22T13:33:48Z' updated_at: '2011-04-22T13:33:48Z' repository: id: 1296269 node_id: MDEwOlJlcG9zaXRvcnkxMjk2MjY5 name: Hello-World full_name: octocat/Hello-World owner: login: octocat id: 1 node_id: MDQ6VXNlcjE= avatar_url: https://github.com/images/error/octocat_happy.gif gravatar_id: '' url: https://api.github.com/users/octocat html_url: https://github.com/octocat followers_url: https://api.github.com/users/octocat/followers following_url: https://api.github.com/users/octocat/following{/other_user} gists_url: https://api.github.com/users/octocat/gists{/gist_id} starred_url: https://api.github.com/users/octocat/starred{/owner}{/repo} subscriptions_url: https://api.github.com/users/octocat/subscriptions organizations_url: https://api.github.com/users/octocat/orgs repos_url: https://api.github.com/users/octocat/repos events_url: https://api.github.com/users/octocat/events{/privacy} received_events_url: https://api.github.com/users/octocat/received_events type: User site_admin: false private: false html_url: https://github.com/octocat/Hello-World description: This your first repo! fork: false url: https://api.github.com/repos/octocat/Hello-World archive_url: https://api.github.com/repos/octocat/Hello-World/{archive_format}{/ref} assignees_url: https://api.github.com/repos/octocat/Hello-World/assignees{/user} blobs_url: https://api.github.com/repos/octocat/Hello-World/git/blobs{/sha} branches_url: https://api.github.com/repos/octocat/Hello-World/branches{/branch} collaborators_url: https://api.github.com/repos/octocat/Hello-World/collaborators{/collaborator} comments_url: https://api.github.com/repos/octocat/Hello-World/comments{/number} commits_url: https://api.github.com/repos/octocat/Hello-World/commits{/sha} compare_url: https://api.github.com/repos/octocat/Hello-World/compare/{base}...{head} contents_url: https://api.github.com/repos/octocat/Hello-World/contents/{+path} contributors_url: https://api.github.com/repos/octocat/Hello-World/contributors deployments_url: https://api.github.com/repos/octocat/Hello-World/deployments downloads_url: https://api.github.com/repos/octocat/Hello-World/downloads events_url: https://api.github.com/repos/octocat/Hello-World/events forks_url: https://api.github.com/repos/octocat/Hello-World/forks git_commits_url: https://api.github.com/repos/octocat/Hello-World/git/commits{/sha} git_refs_url: https://api.github.com/repos/octocat/Hello-World/git/refs{/sha} git_tags_url: https://api.github.com/repos/octocat/Hello-World/git/tags{/sha} git_url: git:github.com/octocat/Hello-World.git issue_comment_url: https://api.github.com/repos/octocat/Hello-World/issues/comments{/number} issue_events_url: https://api.github.com/repos/octocat/Hello-World/issues/events{/number} issues_url: https://api.github.com/repos/octocat/Hello-World/issues{/number} keys_url: https://api.github.com/repos/octocat/Hello-World/keys{/key_id} labels_url: https://api.github.com/repos/octocat/Hello-World/labels{/name} languages_url: https://api.github.com/repos/octocat/Hello-World/languages merges_url: https://api.github.com/repos/octocat/Hello-World/merges milestones_url: https://api.github.com/repos/octocat/Hello-World/milestones{/number} notifications_url: https://api.github.com/repos/octocat/Hello-World/notifications{?since,all,participating} pulls_url: https://api.github.com/repos/octocat/Hello-World/pulls{/number} releases_url: https://api.github.com/repos/octocat/Hello-World/releases{/id} ssh_url: git@github.com:octocat/Hello-World.git stargazers_url: https://api.github.com/repos/octocat/Hello-World/stargazers statuses_url: https://api.github.com/repos/octocat/Hello-World/statuses/{sha} subscribers_url: https://api.github.com/repos/octocat/Hello-World/subscribers subscription_url: https://api.github.com/repos/octocat/Hello-World/subscription tags_url: https://api.github.com/repos/octocat/Hello-World/tags teams_url: https://api.github.com/repos/octocat/Hello-World/teams trees_url: https://api.github.com/repos/octocat/Hello-World/git/trees{/sha} clone_url: https://github.com/octocat/Hello-World.git mirror_url: git:git.example.com/octocat/Hello-World hooks_url: https://api.github.com/repos/octocat/Hello-World/hooks svn_url: https://svn.github.com/octocat/Hello-World homepage: https://github.com language: forks_count: 9 stargazers_count: 80 watchers_count: 80 size: 108 default_branch: master open_issues_count: 0 is_template: true topics: - octocat - atom - electron - api has_issues: true has_projects: true has_wiki: true has_pages: false has_downloads: true archived: false disabled: false visibility: public pushed_at: '2011-01-26T19:06:43Z' created_at: '2011-01-26T19:01:12Z' updated_at: '2011-01-26T19:14:43Z' permissions: admin: false push: false pull: true allow_rebase_merge: true template_repository: temp_clone_token: ABTLWHOULUVAXGTRYU7OC2876QJ2O allow_squash_merge: true delete_branch_on_merge: true allow_merge_commit: true subscribers_count: 42 network_count: 0 license: key: mit name: MIT License url: https://api.github.com/licenses/mit spdx_id: MIT node_id: MDc6TGljZW5zZW1pdA== html_url: https://github.com/licenses/mit forks: 1 open_issues: 1 watchers: 1 author_association: COLLABORATOR license-simple-items: value: - key: mit name: MIT License spdx_id: MIT url: https://api.github.com/licenses/mit node_id: MDc6TGljZW5zZW1pdA== - key: lgpl-3.0 name: GNU Lesser General Public License v3.0 spdx_id: LGPL-3.0 url: https://api.github.com/licenses/lgpl-3.0 node_id: MDc6TGljZW5zZW1pdA== - key: mpl-2.0 name: Mozilla Public License 2.0 spdx_id: MPL-2.0 url: https://api.github.com/licenses/mpl-2.0 node_id: MDc6TGljZW5zZW1pdA== - key: agpl-3.0 name: GNU Affero General Public License v3.0 spdx_id: AGPL-3.0 url: https://api.github.com/licenses/agpl-3.0 node_id: MDc6TGljZW5zZW1pdA== - key: unlicense name: The Unlicense spdx_id: Unlicense url: https://api.github.com/licenses/unlicense node_id: MDc6TGljZW5zZW1pdA== - key: apache-2.0 name: Apache License 2.0 spdx_id: Apache-2.0 url: https://api.github.com/licenses/apache-2.0 node_id: MDc6TGljZW5zZW1pdA== - key: gpl-3.0 name: GNU General Public License v3.0 spdx_id: GPL-3.0 url: https://api.github.com/licenses/gpl-3.0 node_id: MDc6TGljZW5zZW1pdA== license: value: key: mit name: MIT License spdx_id: MIT url: https://api.github.com/licenses/mit node_id: MDc6TGljZW5zZW1pdA== html_url: http://choosealicense.com/licenses/mit/ description: A permissive license that is short and to the point. It lets people do anything with your code with proper attribution and without warranty. implementation: Create a text file (typically named LICENSE or LICENSE.txt) in the root of your source code and copy the text of the license into the file. Replace [year] with the current year and [fullname] with the name (or names) of the copyright holders. permissions: - commercial-use - modifications - distribution - sublicense - private-use conditions: - include-copyright limitations: - no-liability body: |2 The MIT License (MIT) Copyright (c) [year] [fullname] Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. featured: true api-overview: value: verifiable_password_authentication: true packages: - 192.30.252.0/22 dependabot: - 54.158.161.132 installed_version: 3.0.0 thread-items: value: - id: '1' repository: id: 1296269 node_id: MDEwOlJlcG9zaXRvcnkxMjk2MjY5 name: Hello-World full_name: octocat/Hello-World owner: login: octocat id: 1 node_id: MDQ6VXNlcjE= avatar_url: https://github.com/images/error/octocat_happy.gif gravatar_id: '' url: https://api.github.com/users/octocat html_url: https://github.com/octocat followers_url: https://api.github.com/users/octocat/followers following_url: https://api.github.com/users/octocat/following{/other_user} gists_url: https://api.github.com/users/octocat/gists{/gist_id} starred_url: https://api.github.com/users/octocat/starred{/owner}{/repo} subscriptions_url: https://api.github.com/users/octocat/subscriptions organizations_url: https://api.github.com/users/octocat/orgs repos_url: https://api.github.com/users/octocat/repos events_url: https://api.github.com/users/octocat/events{/privacy} received_events_url: https://api.github.com/users/octocat/received_events type: User site_admin: false private: false html_url: https://github.com/octocat/Hello-World description: This your first repo! fork: false url: https://api.github.com/repos/octocat/Hello-World archive_url: https://api.github.com/repos/octocat/Hello-World/{archive_format}{/ref} assignees_url: https://api.github.com/repos/octocat/Hello-World/assignees{/user} blobs_url: https://api.github.com/repos/octocat/Hello-World/git/blobs{/sha} branches_url: https://api.github.com/repos/octocat/Hello-World/branches{/branch} collaborators_url: https://api.github.com/repos/octocat/Hello-World/collaborators{/collaborator} comments_url: https://api.github.com/repos/octocat/Hello-World/comments{/number} commits_url: https://api.github.com/repos/octocat/Hello-World/commits{/sha} compare_url: https://api.github.com/repos/octocat/Hello-World/compare/{base}...{head} contents_url: https://api.github.com/repos/octocat/Hello-World/contents/{+path} contributors_url: https://api.github.com/repos/octocat/Hello-World/contributors deployments_url: https://api.github.com/repos/octocat/Hello-World/deployments downloads_url: https://api.github.com/repos/octocat/Hello-World/downloads events_url: https://api.github.com/repos/octocat/Hello-World/events forks_url: https://api.github.com/repos/octocat/Hello-World/forks git_commits_url: https://api.github.com/repos/octocat/Hello-World/git/commits{/sha} git_refs_url: https://api.github.com/repos/octocat/Hello-World/git/refs{/sha} git_tags_url: https://api.github.com/repos/octocat/Hello-World/git/tags{/sha} git_url: git:github.com/octocat/Hello-World.git issue_comment_url: https://api.github.com/repos/octocat/Hello-World/issues/comments{/number} issue_events_url: https://api.github.com/repos/octocat/Hello-World/issues/events{/number} issues_url: https://api.github.com/repos/octocat/Hello-World/issues{/number} keys_url: https://api.github.com/repos/octocat/Hello-World/keys{/key_id} labels_url: https://api.github.com/repos/octocat/Hello-World/labels{/name} languages_url: https://api.github.com/repos/octocat/Hello-World/languages merges_url: https://api.github.com/repos/octocat/Hello-World/merges milestones_url: https://api.github.com/repos/octocat/Hello-World/milestones{/number} notifications_url: https://api.github.com/repos/octocat/Hello-World/notifications{?since,all,participating} pulls_url: https://api.github.com/repos/octocat/Hello-World/pulls{/number} releases_url: https://api.github.com/repos/octocat/Hello-World/releases{/id} ssh_url: git@github.com:octocat/Hello-World.git stargazers_url: https://api.github.com/repos/octocat/Hello-World/stargazers statuses_url: https://api.github.com/repos/octocat/Hello-World/statuses/{sha} subscribers_url: https://api.github.com/repos/octocat/Hello-World/subscribers subscription_url: https://api.github.com/repos/octocat/Hello-World/subscription tags_url: https://api.github.com/repos/octocat/Hello-World/tags teams_url: https://api.github.com/repos/octocat/Hello-World/teams trees_url: https://api.github.com/repos/octocat/Hello-World/git/trees{/sha} hooks_url: http://api.github.com/repos/octocat/Hello-World/hooks subject: title: Greetings url: https://api.github.com/repos/octokit/octokit.rb/issues/123 latest_comment_url: https://api.github.com/repos/octokit/octokit.rb/issues/comments/123 type: Issue reason: subscribed unread: true updated_at: '2014-11-07T22:01:45Z' last_read_at: '2014-11-07T22:01:45Z' url: https://api.github.com/notifications/threads/1 subscription_url: https://api.github.com/notifications/threads/1/subscription thread: value: id: '1' repository: id: 1296269 node_id: MDEwOlJlcG9zaXRvcnkxMjk2MjY5 name: Hello-World full_name: octocat/Hello-World owner: login: octocat id: 1 node_id: MDQ6VXNlcjE= avatar_url: https://github.com/images/error/octocat_happy.gif gravatar_id: '' url: https://api.github.com/users/octocat html_url: https://github.com/octocat followers_url: https://api.github.com/users/octocat/followers following_url: https://api.github.com/users/octocat/following{/other_user} gists_url: https://api.github.com/users/octocat/gists{/gist_id} starred_url: https://api.github.com/users/octocat/starred{/owner}{/repo} subscriptions_url: https://api.github.com/users/octocat/subscriptions organizations_url: https://api.github.com/users/octocat/orgs repos_url: https://api.github.com/users/octocat/repos events_url: https://api.github.com/users/octocat/events{/privacy} received_events_url: https://api.github.com/users/octocat/received_events type: User site_admin: false private: false html_url: https://github.com/octocat/Hello-World description: This your first repo! fork: false url: https://api.github.com/repos/octocat/Hello-World archive_url: https://api.github.com/repos/octocat/Hello-World/{archive_format}{/ref} assignees_url: https://api.github.com/repos/octocat/Hello-World/assignees{/user} blobs_url: https://api.github.com/repos/octocat/Hello-World/git/blobs{/sha} branches_url: https://api.github.com/repos/octocat/Hello-World/branches{/branch} collaborators_url: https://api.github.com/repos/octocat/Hello-World/collaborators{/collaborator} comments_url: https://api.github.com/repos/octocat/Hello-World/comments{/number} commits_url: https://api.github.com/repos/octocat/Hello-World/commits{/sha} compare_url: https://api.github.com/repos/octocat/Hello-World/compare/{base}...{head} contents_url: https://api.github.com/repos/octocat/Hello-World/contents/{+path} contributors_url: https://api.github.com/repos/octocat/Hello-World/contributors deployments_url: https://api.github.com/repos/octocat/Hello-World/deployments downloads_url: https://api.github.com/repos/octocat/Hello-World/downloads events_url: https://api.github.com/repos/octocat/Hello-World/events forks_url: https://api.github.com/repos/octocat/Hello-World/forks git_commits_url: https://api.github.com/repos/octocat/Hello-World/git/commits{/sha} git_refs_url: https://api.github.com/repos/octocat/Hello-World/git/refs{/sha} git_tags_url: https://api.github.com/repos/octocat/Hello-World/git/tags{/sha} git_url: git:github.com/octocat/Hello-World.git issue_comment_url: https://api.github.com/repos/octocat/Hello-World/issues/comments{/number} issue_events_url: https://api.github.com/repos/octocat/Hello-World/issues/events{/number} issues_url: https://api.github.com/repos/octocat/Hello-World/issues{/number} keys_url: https://api.github.com/repos/octocat/Hello-World/keys{/key_id} labels_url: https://api.github.com/repos/octocat/Hello-World/labels{/name} languages_url: https://api.github.com/repos/octocat/Hello-World/languages merges_url: https://api.github.com/repos/octocat/Hello-World/merges milestones_url: https://api.github.com/repos/octocat/Hello-World/milestones{/number} notifications_url: https://api.github.com/repos/octocat/Hello-World/notifications{?since,all,participating} pulls_url: https://api.github.com/repos/octocat/Hello-World/pulls{/number} releases_url: https://api.github.com/repos/octocat/Hello-World/releases{/id} ssh_url: git@github.com:octocat/Hello-World.git stargazers_url: https://api.github.com/repos/octocat/Hello-World/stargazers statuses_url: https://api.github.com/repos/octocat/Hello-World/statuses/{sha} subscribers_url: https://api.github.com/repos/octocat/Hello-World/subscribers subscription_url: https://api.github.com/repos/octocat/Hello-World/subscription tags_url: https://api.github.com/repos/octocat/Hello-World/tags teams_url: https://api.github.com/repos/octocat/Hello-World/teams trees_url: https://api.github.com/repos/octocat/Hello-World/git/trees{/sha} hooks_url: http://api.github.com/repos/octocat/Hello-World/hooks subject: title: Greetings url: https://api.github.com/repos/octokit/octokit.rb/issues/123 latest_comment_url: https://api.github.com/repos/octokit/octokit.rb/issues/comments/123 type: Issue reason: subscribed unread: true updated_at: '2014-11-07T22:01:45Z' last_read_at: '2014-11-07T22:01:45Z' url: https://api.github.com/notifications/threads/1 subscription_url: https://api.github.com/notifications/threads/1/subscription thread-subscription: value: subscribed: true ignored: false reason: created_at: '2012-10-06T21:34:12Z' url: https://api.github.com/notifications/threads/1/subscription thread_url: https://api.github.com/notifications/threads/1 organization-simple-items: value: - login: github id: 1 node_id: MDEyOk9yZ2FuaXphdGlvbjE= url: https://api.github.com/orgs/github repos_url: https://api.github.com/orgs/github/repos events_url: https://api.github.com/orgs/github/events hooks_url: https://api.github.com/orgs/github/hooks issues_url: https://api.github.com/orgs/github/issues members_url: https://api.github.com/orgs/github/members{/member} public_members_url: https://api.github.com/orgs/github/public_members{/member} avatar_url: https://github.com/images/error/octocat_happy.gif description: A great organization organization-full-default-response: summary: Default response value: login: github id: 1 node_id: MDEyOk9yZ2FuaXphdGlvbjE= url: https://api.github.com/orgs/github repos_url: https://api.github.com/orgs/github/repos events_url: https://api.github.com/orgs/github/events hooks_url: https://api.github.com/orgs/github/hooks issues_url: https://api.github.com/orgs/github/issues members_url: https://api.github.com/orgs/github/members{/member} public_members_url: https://api.github.com/orgs/github/public_members{/member} avatar_url: https://github.com/images/error/octocat_happy.gif description: A great organization name: github company: GitHub blog: https://github.com/blog location: San Francisco email: octocat@github.com twitter_username: github is_verified: true has_organization_projects: true has_repository_projects: true public_repos: 2 public_gists: 1 followers: 20 following: 0 html_url: https://github.com/octocat created_at: '2008-01-14T04:33:35Z' updated_at: '2014-03-03T18:58:10Z' type: Organization total_private_repos: 100 owned_private_repos: 100 private_gists: 81 disk_usage: 10000 collaborators: 8 billing_email: mona@github.com plan: name: Medium space: 400 private_repos: 20 filled_seats: 4 seats: 5 default_repository_permission: read members_can_create_repositories: true two_factor_requirement_enabled: true members_allowed_repository_creation_type: all members_can_create_public_repositories: false members_can_create_private_repositories: false members_can_create_internal_repositories: false members_can_create_pages: true members_can_fork_private_repositories: false organization-full: value: login: github id: 1 node_id: MDEyOk9yZ2FuaXphdGlvbjE= url: https://api.github.com/orgs/github repos_url: https://api.github.com/orgs/github/repos events_url: https://api.github.com/orgs/github/events hooks_url: https://api.github.com/orgs/github/hooks issues_url: https://api.github.com/orgs/github/issues members_url: https://api.github.com/orgs/github/members{/member} public_members_url: https://api.github.com/orgs/github/public_members{/member} avatar_url: https://github.com/images/error/octocat_happy.gif description: A great organization name: github company: GitHub blog: https://github.com/blog location: San Francisco email: octocat@github.com twitter_username: github is_verified: true has_organization_projects: true has_repository_projects: true public_repos: 2 public_gists: 1 followers: 20 following: 0 html_url: https://github.com/octocat created_at: '2008-01-14T04:33:35Z' type: Organization total_private_repos: 100 owned_private_repos: 100 private_gists: 81 disk_usage: 10000 collaborators: 8 billing_email: mona@github.com plan: name: Medium space: 400 private_repos: 20 default_repository_permission: read members_can_create_repositories: true two_factor_requirement_enabled: true members_allowed_repository_creation_type: all members_can_create_public_repositories: false members_can_create_private_repositories: false members_can_create_internal_repositories: false members_can_create_pages: true members_can_create_public_pages: true members_can_create_private_pages: true members_can_fork_private_repositories: false updated_at: '2014-03-03T18:58:10Z' actions-organization-permissions: value: enabled_repositories: all allowed_actions: selected selected_actions_url: https://api.github.com/organizations/42/actions/permissions/selected-actions repository-paginated: value: total_count: 1 repositories: - id: 1296269 node_id: MDEwOlJlcG9zaXRvcnkxMjk2MjY5 name: Hello-World full_name: octocat/Hello-World owner: login: octocat id: 1 node_id: MDQ6VXNlcjE= avatar_url: https://github.com/images/error/octocat_happy.gif gravatar_id: '' url: https://api.github.com/users/octocat html_url: https://github.com/octocat followers_url: https://api.github.com/users/octocat/followers following_url: https://api.github.com/users/octocat/following{/other_user} gists_url: https://api.github.com/users/octocat/gists{/gist_id} starred_url: https://api.github.com/users/octocat/starred{/owner}{/repo} subscriptions_url: https://api.github.com/users/octocat/subscriptions organizations_url: https://api.github.com/users/octocat/orgs repos_url: https://api.github.com/users/octocat/repos events_url: https://api.github.com/users/octocat/events{/privacy} received_events_url: https://api.github.com/users/octocat/received_events type: User site_admin: false private: false html_url: https://github.com/octocat/Hello-World description: This your first repo! fork: false url: https://api.github.com/repos/octocat/Hello-World archive_url: https://api.github.com/repos/octocat/Hello-World/{archive_format}{/ref} assignees_url: https://api.github.com/repos/octocat/Hello-World/assignees{/user} blobs_url: https://api.github.com/repos/octocat/Hello-World/git/blobs{/sha} branches_url: https://api.github.com/repos/octocat/Hello-World/branches{/branch} collaborators_url: https://api.github.com/repos/octocat/Hello-World/collaborators{/collaborator} comments_url: https://api.github.com/repos/octocat/Hello-World/comments{/number} commits_url: https://api.github.com/repos/octocat/Hello-World/commits{/sha} compare_url: https://api.github.com/repos/octocat/Hello-World/compare/{base}...{head} contents_url: https://api.github.com/repos/octocat/Hello-World/contents/{+path} contributors_url: https://api.github.com/repos/octocat/Hello-World/contributors deployments_url: https://api.github.com/repos/octocat/Hello-World/deployments downloads_url: https://api.github.com/repos/octocat/Hello-World/downloads events_url: https://api.github.com/repos/octocat/Hello-World/events forks_url: https://api.github.com/repos/octocat/Hello-World/forks git_commits_url: https://api.github.com/repos/octocat/Hello-World/git/commits{/sha} git_refs_url: https://api.github.com/repos/octocat/Hello-World/git/refs{/sha} git_tags_url: https://api.github.com/repos/octocat/Hello-World/git/tags{/sha} git_url: git:github.com/octocat/Hello-World.git issue_comment_url: https://api.github.com/repos/octocat/Hello-World/issues/comments{/number} issue_events_url: https://api.github.com/repos/octocat/Hello-World/issues/events{/number} issues_url: https://api.github.com/repos/octocat/Hello-World/issues{/number} keys_url: https://api.github.com/repos/octocat/Hello-World/keys{/key_id} labels_url: https://api.github.com/repos/octocat/Hello-World/labels{/name} languages_url: https://api.github.com/repos/octocat/Hello-World/languages merges_url: https://api.github.com/repos/octocat/Hello-World/merges milestones_url: https://api.github.com/repos/octocat/Hello-World/milestones{/number} notifications_url: https://api.github.com/repos/octocat/Hello-World/notifications{?since,all,participating} pulls_url: https://api.github.com/repos/octocat/Hello-World/pulls{/number} releases_url: https://api.github.com/repos/octocat/Hello-World/releases{/id} ssh_url: git@github.com:octocat/Hello-World.git stargazers_url: https://api.github.com/repos/octocat/Hello-World/stargazers statuses_url: https://api.github.com/repos/octocat/Hello-World/statuses/{sha} subscribers_url: https://api.github.com/repos/octocat/Hello-World/subscribers subscription_url: https://api.github.com/repos/octocat/Hello-World/subscription tags_url: https://api.github.com/repos/octocat/Hello-World/tags teams_url: https://api.github.com/repos/octocat/Hello-World/teams trees_url: https://api.github.com/repos/octocat/Hello-World/git/trees{/sha} clone_url: https://github.com/octocat/Hello-World.git mirror_url: git:git.example.com/octocat/Hello-World hooks_url: https://api.github.com/repos/octocat/Hello-World/hooks svn_url: https://svn.github.com/octocat/Hello-World homepage: https://github.com language: forks_count: 9 stargazers_count: 80 watchers_count: 80 size: 108 default_branch: master open_issues_count: 0 is_template: true topics: - octocat - atom - electron - api has_issues: true has_projects: true has_wiki: true has_pages: false has_downloads: true archived: false disabled: false visibility: public pushed_at: '2011-01-26T19:06:43Z' created_at: '2011-01-26T19:01:12Z' updated_at: '2011-01-26T19:14:43Z' permissions: admin: false push: false pull: true allow_rebase_merge: true template_repository: temp_clone_token: ABTLWHOULUVAXGTRYU7OC2876QJ2O allow_squash_merge: true delete_branch_on_merge: true allow_merge_commit: true subscribers_count: 42 network_count: 0 license: key: mit name: MIT License url: https://api.github.com/licenses/mit spdx_id: MIT node_id: MDc6TGljZW5zZW1pdA== html_url: https://github.com/licenses/mit forks: 1 open_issues: 1 watchers: 1 runner-groups-org: value: total_count: 3 runner_groups: - id: 1 name: Default visibility: all default: true runners_url: https://api.github.com/orgs/octo-org/actions/runner_groups/1/runners inherited: false allows_public_repositories: true - id: 2 name: octo-runner-group visibility: selected default: false selected_repositories_url: https://api.github.com/orgs/octo-org/actions/runner_groups/2/repositories runners_url: https://api.github.com/orgs/octo-org/actions/runner_groups/2/runners inherited: true allows_public_repositories: true - id: 3 name: expensive-hardware visibility: private default: false runners_url: https://api.github.com/orgs/octo-org/actions/runner_groups/3/runners inherited: false allows_public_repositories: true runner-group: value: id: 2 name: octo-runner-group visibility: selected default: false selected_repositories_url: https://api.github.com/orgs/octo-org/actions/runner-groups/2/repositories runners_url: https://api.github.com/orgs/octo-org/actions/runner_groups/2/runners inherited: false allows_public_repositories: true runner-group-item: value: id: 2 name: octo-runner-group visibility: selected default: false selected_repositories_url: https://api.github.com/orgs/octo-org/actions/runner_groups/2/repositories runners_url: https://api.github.com/orgs/octo-org/actions/runner_groups/2/runners inherited: false allows_public_repositories: true minimal-repository-paginated: value: total_count: 1 repositories: - id: 1296269 node_id: MDEwOlJlcG9zaXRvcnkxMjk2MjY5 name: Hello-World full_name: octocat/Hello-World owner: login: octocat id: 1 node_id: MDQ6VXNlcjE= avatar_url: https://github.com/images/error/octocat_happy.gif gravatar_id: '' url: https://api.github.com/users/octocat html_url: https://github.com/octocat followers_url: https://api.github.com/users/octocat/followers following_url: https://api.github.com/users/octocat/following{/other_user} gists_url: https://api.github.com/users/octocat/gists{/gist_id} starred_url: https://api.github.com/users/octocat/starred{/owner}{/repo} subscriptions_url: https://api.github.com/users/octocat/subscriptions organizations_url: https://api.github.com/users/octocat/orgs repos_url: https://api.github.com/users/octocat/repos events_url: https://api.github.com/users/octocat/events{/privacy} received_events_url: https://api.github.com/users/octocat/received_events type: User site_admin: false private: false html_url: https://github.com/octocat/Hello-World description: This your first repo! fork: false url: https://api.github.com/repos/octocat/Hello-World archive_url: https://api.github.com/repos/octocat/Hello-World/{archive_format}{/ref} assignees_url: https://api.github.com/repos/octocat/Hello-World/assignees{/user} blobs_url: https://api.github.com/repos/octocat/Hello-World/git/blobs{/sha} branches_url: https://api.github.com/repos/octocat/Hello-World/branches{/branch} collaborators_url: https://api.github.com/repos/octocat/Hello-World/collaborators{/collaborator} comments_url: https://api.github.com/repos/octocat/Hello-World/comments{/number} commits_url: https://api.github.com/repos/octocat/Hello-World/commits{/sha} compare_url: https://api.github.com/repos/octocat/Hello-World/compare/{base}...{head} contents_url: https://api.github.com/repos/octocat/Hello-World/contents/{+path} contributors_url: https://api.github.com/repos/octocat/Hello-World/contributors deployments_url: https://api.github.com/repos/octocat/Hello-World/deployments downloads_url: https://api.github.com/repos/octocat/Hello-World/downloads events_url: https://api.github.com/repos/octocat/Hello-World/events forks_url: https://api.github.com/repos/octocat/Hello-World/forks git_commits_url: https://api.github.com/repos/octocat/Hello-World/git/commits{/sha} git_refs_url: https://api.github.com/repos/octocat/Hello-World/git/refs{/sha} git_tags_url: https://api.github.com/repos/octocat/Hello-World/git/tags{/sha} git_url: git:github.com/octocat/Hello-World.git issue_comment_url: https://api.github.com/repos/octocat/Hello-World/issues/comments{/number} issue_events_url: https://api.github.com/repos/octocat/Hello-World/issues/events{/number} issues_url: https://api.github.com/repos/octocat/Hello-World/issues{/number} keys_url: https://api.github.com/repos/octocat/Hello-World/keys{/key_id} labels_url: https://api.github.com/repos/octocat/Hello-World/labels{/name} languages_url: https://api.github.com/repos/octocat/Hello-World/languages merges_url: https://api.github.com/repos/octocat/Hello-World/merges milestones_url: https://api.github.com/repos/octocat/Hello-World/milestones{/number} notifications_url: https://api.github.com/repos/octocat/Hello-World/notifications{?since,all,participating} pulls_url: https://api.github.com/repos/octocat/Hello-World/pulls{/number} releases_url: https://api.github.com/repos/octocat/Hello-World/releases{/id} ssh_url: git@github.com:octocat/Hello-World.git stargazers_url: https://api.github.com/repos/octocat/Hello-World/stargazers statuses_url: https://api.github.com/repos/octocat/Hello-World/statuses/{sha} subscribers_url: https://api.github.com/repos/octocat/Hello-World/subscribers subscription_url: https://api.github.com/repos/octocat/Hello-World/subscription tags_url: https://api.github.com/repos/octocat/Hello-World/tags teams_url: https://api.github.com/repos/octocat/Hello-World/teams trees_url: https://api.github.com/repos/octocat/Hello-World/git/trees{/sha} clone_url: https://github.com/octocat/Hello-World.git mirror_url: git:git.example.com/octocat/Hello-World hooks_url: https://api.github.com/repos/octocat/Hello-World/hooks svn_url: https://svn.github.com/octocat/Hello-World homepage: https://github.com language: forks_count: 9 stargazers_count: 80 watchers_count: 80 size: 108 default_branch: master open_issues_count: 0 is_template: true topics: - octocat - atom - electron - api has_issues: true has_projects: true has_wiki: true has_pages: false has_downloads: true archived: false disabled: false visibility: public pushed_at: '2011-01-26T19:06:43Z' created_at: '2011-01-26T19:01:12Z' updated_at: '2011-01-26T19:14:43Z' permissions: admin: false push: false pull: true template_repository: id: 1296269 node_id: MDEwOlJlcG9zaXRvcnkxMjk2MjY5 name: Hello-World full_name: octocat/Hello-World owner: login: octocat id: 1 node_id: MDQ6VXNlcjE= avatar_url: https://github.com/images/error/octocat_happy.gif gravatar_id: '' url: https://api.github.com/users/octocat html_url: https://github.com/octocat followers_url: https://api.github.com/users/octocat/followers following_url: https://api.github.com/users/octocat/following{/other_user} gists_url: https://api.github.com/users/octocat/gists{/gist_id} starred_url: https://api.github.com/users/octocat/starred{/owner}{/repo} subscriptions_url: https://api.github.com/users/octocat/subscriptions organizations_url: https://api.github.com/users/octocat/orgs repos_url: https://api.github.com/users/octocat/repos events_url: https://api.github.com/users/octocat/events{/privacy} received_events_url: https://api.github.com/users/octocat/received_events type: User site_admin: false private: false html_url: https://github.com/octocat/Hello-World description: This your first repo! fork: false url: https://api.github.com/repos/octocat/Hello-World archive_url: https://api.github.com/repos/octocat/Hello-World/{archive_format}{/ref} assignees_url: https://api.github.com/repos/octocat/Hello-World/assignees{/user} blobs_url: https://api.github.com/repos/octocat/Hello-World/git/blobs{/sha} branches_url: https://api.github.com/repos/octocat/Hello-World/branches{/branch} collaborators_url: https://api.github.com/repos/octocat/Hello-World/collaborators{/collaborator} comments_url: https://api.github.com/repos/octocat/Hello-World/comments{/number} commits_url: https://api.github.com/repos/octocat/Hello-World/commits{/sha} compare_url: https://api.github.com/repos/octocat/Hello-World/compare/{base}...{head} contents_url: https://api.github.com/repos/octocat/Hello-World/contents/{+path} contributors_url: https://api.github.com/repos/octocat/Hello-World/contributors deployments_url: https://api.github.com/repos/octocat/Hello-World/deployments downloads_url: https://api.github.com/repos/octocat/Hello-World/downloads events_url: https://api.github.com/repos/octocat/Hello-World/events forks_url: https://api.github.com/repos/octocat/Hello-World/forks git_commits_url: https://api.github.com/repos/octocat/Hello-World/git/commits{/sha} git_refs_url: https://api.github.com/repos/octocat/Hello-World/git/refs{/sha} git_tags_url: https://api.github.com/repos/octocat/Hello-World/git/tags{/sha} git_url: git:github.com/octocat/Hello-World.git issue_comment_url: https://api.github.com/repos/octocat/Hello-World/issues/comments{/number} issue_events_url: https://api.github.com/repos/octocat/Hello-World/issues/events{/number} issues_url: https://api.github.com/repos/octocat/Hello-World/issues{/number} keys_url: https://api.github.com/repos/octocat/Hello-World/keys{/key_id} labels_url: https://api.github.com/repos/octocat/Hello-World/labels{/name} languages_url: https://api.github.com/repos/octocat/Hello-World/languages merges_url: https://api.github.com/repos/octocat/Hello-World/merges milestones_url: https://api.github.com/repos/octocat/Hello-World/milestones{/number} notifications_url: https://api.github.com/repos/octocat/Hello-World/notifications{?since,all,participating} pulls_url: https://api.github.com/repos/octocat/Hello-World/pulls{/number} releases_url: https://api.github.com/repos/octocat/Hello-World/releases{/id} ssh_url: git@github.com:octocat/Hello-World.git stargazers_url: https://api.github.com/repos/octocat/Hello-World/stargazers statuses_url: https://api.github.com/repos/octocat/Hello-World/statuses/{sha} subscribers_url: https://api.github.com/repos/octocat/Hello-World/subscribers subscription_url: https://api.github.com/repos/octocat/Hello-World/subscription tags_url: https://api.github.com/repos/octocat/Hello-World/tags teams_url: https://api.github.com/repos/octocat/Hello-World/teams trees_url: https://api.github.com/repos/octocat/Hello-World/git/trees{/sha} clone_url: https://github.com/octocat/Hello-World.git mirror_url: git:git.example.com/octocat/Hello-World hooks_url: https://api.github.com/repos/octocat/Hello-World/hooks svn_url: https://svn.github.com/octocat/Hello-World homepage: https://github.com organization: language: forks: 9 forks_count: 9 stargazers_count: 80 watchers_count: 80 watchers: 80 size: 108 default_branch: master open_issues: 0 open_issues_count: 0 is_template: true license: key: mit name: MIT License url: https://api.github.com/licenses/mit spdx_id: MIT node_id: MDc6TGljZW5zZW1pdA== html_url: https://api.github.com/licenses/mit topics: - octocat - atom - electron - api has_issues: true has_projects: true has_wiki: true has_pages: false has_downloads: true archived: false disabled: false visibility: public pushed_at: '2011-01-26T19:06:43Z' created_at: '2011-01-26T19:01:12Z' updated_at: '2011-01-26T19:14:43Z' permissions: admin: false push: false pull: true allow_rebase_merge: true template_repository: temp_clone_token: ABTLWHOULUVAXGTRYU7OC2876QJ2O allow_squash_merge: true delete_branch_on_merge: true allow_merge_commit: true subscribers_count: 42 network_count: 0 temp_clone_token: ABTLWHOULUVAXGTRYU7OC2876QJ2O delete_branch_on_merge: true subscribers_count: 42 network_count: 0 license: key: mit name: MIT License url: https://api.github.com/licenses/mit spdx_id: MIT node_id: MDc6TGljZW5zZW1pdA== forks: 1 open_issues: 1 watchers: 1 organization-actions-secret-paginated: value: total_count: 3 secrets: - name: GIST_ID created_at: '2019-08-10T14:59:22Z' updated_at: '2020-01-10T14:59:22Z' visibility: private - name: DEPLOY_TOKEN created_at: '2019-08-10T14:59:22Z' updated_at: '2020-01-10T14:59:22Z' visibility: all - name: GH_TOKEN created_at: '2019-08-10T14:59:22Z' updated_at: '2020-01-10T14:59:22Z' visibility: selected selected_repositories_url: https://api.github.com/orgs/octo-org/actions/secrets/SUPER_SECRET/repositories actions-public-key: value: key_id: '012345678912345678' key: 2Sg8iYjAxxmI2LvUXpJjkYrMxURPc8r+dB7TJyvv1234 organization-actions-secret: value: name: GH_TOKEN created_at: '2019-08-10T14:59:22Z' updated_at: '2020-01-10T14:59:22Z' visibility: selected selected_repositories_url: https://api.github.com/orgs/octo-org/actions/secrets/SUPER_SECRET/repositories public-repository-paginated: value: total_count: 1 repositories: - id: 1296269 node_id: MDEwOlJlcG9zaXRvcnkxMjk2MjY5 name: Hello-World full_name: octocat/Hello-World owner: login: octocat id: 1 node_id: MDQ6VXNlcjE= avatar_url: https://github.com/images/error/octocat_happy.gif gravatar_id: '' url: https://api.github.com/users/octocat html_url: https://github.com/octocat followers_url: https://api.github.com/users/octocat/followers following_url: https://api.github.com/users/octocat/following{/other_user} gists_url: https://api.github.com/users/octocat/gists{/gist_id} starred_url: https://api.github.com/users/octocat/starred{/owner}{/repo} subscriptions_url: https://api.github.com/users/octocat/subscriptions organizations_url: https://api.github.com/users/octocat/orgs repos_url: https://api.github.com/users/octocat/repos events_url: https://api.github.com/users/octocat/events{/privacy} received_events_url: https://api.github.com/users/octocat/received_events type: User site_admin: false private: false html_url: https://github.com/octocat/Hello-World description: This your first repo! fork: false url: https://api.github.com/repos/octocat/Hello-World archive_url: https://api.github.com/repos/octocat/Hello-World/{archive_format}{/ref} assignees_url: https://api.github.com/repos/octocat/Hello-World/assignees{/user} blobs_url: https://api.github.com/repos/octocat/Hello-World/git/blobs{/sha} branches_url: https://api.github.com/repos/octocat/Hello-World/branches{/branch} collaborators_url: https://api.github.com/repos/octocat/Hello-World/collaborators{/collaborator} comments_url: https://api.github.com/repos/octocat/Hello-World/comments{/number} commits_url: https://api.github.com/repos/octocat/Hello-World/commits{/sha} compare_url: https://api.github.com/repos/octocat/Hello-World/compare/{base}...{head} contents_url: https://api.github.com/repos/octocat/Hello-World/contents/{+path} contributors_url: https://api.github.com/repos/octocat/Hello-World/contributors deployments_url: https://api.github.com/repos/octocat/Hello-World/deployments downloads_url: https://api.github.com/repos/octocat/Hello-World/downloads events_url: https://api.github.com/repos/octocat/Hello-World/events forks_url: https://api.github.com/repos/octocat/Hello-World/forks git_commits_url: https://api.github.com/repos/octocat/Hello-World/git/commits{/sha} git_refs_url: https://api.github.com/repos/octocat/Hello-World/git/refs{/sha} git_tags_url: https://api.github.com/repos/octocat/Hello-World/git/tags{/sha} git_url: git:github.com/octocat/Hello-World.git issue_comment_url: https://api.github.com/repos/octocat/Hello-World/issues/comments{/number} issue_events_url: https://api.github.com/repos/octocat/Hello-World/issues/events{/number} issues_url: https://api.github.com/repos/octocat/Hello-World/issues{/number} keys_url: https://api.github.com/repos/octocat/Hello-World/keys{/key_id} labels_url: https://api.github.com/repos/octocat/Hello-World/labels{/name} languages_url: https://api.github.com/repos/octocat/Hello-World/languages merges_url: https://api.github.com/repos/octocat/Hello-World/merges milestones_url: https://api.github.com/repos/octocat/Hello-World/milestones{/number} notifications_url: https://api.github.com/repos/octocat/Hello-World/notifications{?since,all,participating} pulls_url: https://api.github.com/repos/octocat/Hello-World/pulls{/number} releases_url: https://api.github.com/repos/octocat/Hello-World/releases{/id} ssh_url: git@github.com:octocat/Hello-World.git stargazers_url: https://api.github.com/repos/octocat/Hello-World/stargazers statuses_url: https://api.github.com/repos/octocat/Hello-World/statuses/{sha} subscribers_url: https://api.github.com/repos/octocat/Hello-World/subscribers subscription_url: https://api.github.com/repos/octocat/Hello-World/subscription tags_url: https://api.github.com/repos/octocat/Hello-World/tags teams_url: https://api.github.com/repos/octocat/Hello-World/teams trees_url: https://api.github.com/repos/octocat/Hello-World/git/trees{/sha} hooks_url: http://api.github.com/repos/octocat/Hello-World/hooks org-hook-items: value: - id: 1 url: https://api.github.com/orgs/octocat/hooks/1 ping_url: https://api.github.com/orgs/octocat/hooks/1/pings name: web events: - push - pull_request active: true config: url: http://example.com content_type: json updated_at: '2011-09-06T20:39:23Z' created_at: '2011-09-06T17:26:27Z' type: Organization org-hook: value: id: 1 url: https://api.github.com/orgs/octocat/hooks/1 ping_url: https://api.github.com/orgs/octocat/hooks/1/pings name: web events: - push - pull_request active: true config: url: http://example.com content_type: json updated_at: '2011-09-06T20:39:23Z' created_at: '2011-09-06T17:26:27Z' type: Organization org-hook-2: value: id: 1 url: https://api.github.com/orgs/octocat/hooks/1 ping_url: https://api.github.com/orgs/octocat/hooks/1/pings name: web events: - pull_request active: true config: url: http://example.com content_type: json updated_at: '2011-09-06T20:39:23Z' created_at: '2011-09-06T17:26:27Z' type: Organization installation: value: id: 1 account: login: github id: 1 node_id: MDEyOk9yZ2FuaXphdGlvbjE= avatar_url: https://github.com/images/error/hubot_happy.gif gravatar_id: '' url: https://api.github.com/orgs/github html_url: https://github.com/github followers_url: https://api.github.com/users/github/followers following_url: https://api.github.com/users/github/following{/other_user} gists_url: https://api.github.com/users/github/gists{/gist_id} starred_url: https://api.github.com/users/github/starred{/owner}{/repo} subscriptions_url: https://api.github.com/users/github/subscriptions organizations_url: https://api.github.com/users/github/orgs repos_url: https://api.github.com/orgs/github/repos events_url: https://api.github.com/orgs/github/events received_events_url: https://api.github.com/users/github/received_events type: Organization site_admin: false repository_selection: all access_tokens_url: https://api.github.com/installations/1/access_tokens repositories_url: https://api.github.com/installation/repositories html_url: https://github.com/organizations/github/settings/installations/1 app_id: 1 target_id: 1 target_type: Organization permissions: checks: write metadata: read contents: read events: - push - pull_request created_at: '2018-02-09T20:51:14Z' updated_at: '2018-02-09T20:51:14Z' single_file_name: config.yml has_multiple_single_files: true single_file_paths: - config.yml - ".github/issue_TEMPLATE.md" app_slug: github-actions suspended_at: suspended_by: installation-paginated: value: total_count: 1 installations: - id: 25381 account: login: octo-org id: 6811672 node_id: MDEyOk9yZ2FuaXphdGlvbjY4MTE2NzI= avatar_url: https://avatars3.githubusercontent.com/u/6811672?v=4 gravatar_id: '' url: https://api.github.com/users/octo-org html_url: https://github.com/octo-org followers_url: https://api.github.com/users/octo-org/followers following_url: https://api.github.com/users/octo-org/following{/other_user} gists_url: https://api.github.com/users/octo-org/gists{/gist_id} starred_url: https://api.github.com/users/octo-org/starred{/owner}{/repo} subscriptions_url: https://api.github.com/users/octo-org/subscriptions organizations_url: https://api.github.com/users/octo-org/orgs repos_url: https://api.github.com/users/octo-org/repos events_url: https://api.github.com/users/octo-org/events{/privacy} received_events_url: https://api.github.com/users/octo-org/received_events type: Organization site_admin: false repository_selection: selected access_tokens_url: https://api.github.com/app/installations/25381/access_tokens repositories_url: https://api.github.com/installation/repositories html_url: https://github.com/organizations/octo-org/settings/installations/25381 app_id: 2218 target_id: 6811672 target_type: Organization permissions: deployments: write metadata: read pull_requests: read statuses: read events: - deployment - deployment_status created_at: '2017-05-16T08:47:09.000-07:00' updated_at: '2017-06-06T11:23:23.000-07:00' single_file_name: config.yml has_multiple_single_files: true single_file_paths: - config.yml - ".github/issue_TEMPLATE.md" app_slug: github-actions suspended_at: suspended_by: simple-user-items: value: - login: octocat id: 1 node_id: MDQ6VXNlcjE= avatar_url: https://github.com/images/error/octocat_happy.gif gravatar_id: '' url: https://api.github.com/users/octocat html_url: https://github.com/octocat followers_url: https://api.github.com/users/octocat/followers following_url: https://api.github.com/users/octocat/following{/other_user} gists_url: https://api.github.com/users/octocat/gists{/gist_id} starred_url: https://api.github.com/users/octocat/starred{/owner}{/repo} subscriptions_url: https://api.github.com/users/octocat/subscriptions organizations_url: https://api.github.com/users/octocat/orgs repos_url: https://api.github.com/users/octocat/repos events_url: https://api.github.com/users/octocat/events{/privacy} received_events_url: https://api.github.com/users/octocat/received_events type: User site_admin: false org-membership-response-if-user-has-an-active-admin-membership-with-organization: summary: Response if user has an active admin membership with organization value: url: https://api.github.com/orgs/octocat/memberships/defunkt state: active role: admin organization_url: https://api.github.com/orgs/octocat organization: login: github id: 1 node_id: MDEyOk9yZ2FuaXphdGlvbjE= url: https://api.github.com/orgs/github repos_url: https://api.github.com/orgs/github/repos events_url: https://api.github.com/orgs/github/events hooks_url: https://api.github.com/orgs/github/hooks issues_url: https://api.github.com/orgs/github/issues members_url: https://api.github.com/orgs/github/members{/member} public_members_url: https://api.github.com/orgs/github/public_members{/member} avatar_url: https://github.com/images/error/octocat_happy.gif description: A great organization user: login: octocat id: 1 node_id: MDQ6VXNlcjE= avatar_url: https://github.com/images/error/octocat_happy.gif gravatar_id: '' url: https://api.github.com/users/octocat html_url: https://github.com/octocat followers_url: https://api.github.com/users/octocat/followers following_url: https://api.github.com/users/octocat/following{/other_user} gists_url: https://api.github.com/users/octocat/gists{/gist_id} starred_url: https://api.github.com/users/octocat/starred{/owner}{/repo} subscriptions_url: https://api.github.com/users/octocat/subscriptions organizations_url: https://api.github.com/users/octocat/orgs repos_url: https://api.github.com/users/octocat/repos events_url: https://api.github.com/users/octocat/events{/privacy} received_events_url: https://api.github.com/users/octocat/received_events type: User site_admin: false org-pre-receive-hook-items: value: - id: 42 name: Check Commits enforcement: disabled configuration_url: https://github.example.com/api/v3/admin/pre-receive-hooks/42 allow_downstream_configuration: true org-pre-receive-hook: value: id: 42 name: Check Commits enforcement: disabled configuration_url: https://github.example.com/api/v3/admin/pre-receive-hooks/42 allow_downstream_configuration: true org-pre-receive-hook-2: value: id: 42 name: Check Commits enforcement: enabled configuration_url: https://github.example.com/api/v3/orgs/octocat/pre-receive-hooks/42 allow_downstream_configuration: false project-items: value: - owner_url: https://api.github.com/orgs/octocat url: https://api.github.com/projects/1002605 html_url: https://github.com/orgs/api-playground/projects/1 columns_url: https://api.github.com/projects/1002605/columns id: 1002605 node_id: MDc6UHJvamVjdDEwMDI2MDU= name: Organization Roadmap body: High-level roadmap for the upcoming year. number: 1 state: open creator: login: octocat id: 1 node_id: MDQ6VXNlcjE= avatar_url: https://github.com/images/error/octocat_happy.gif gravatar_id: '' url: https://api.github.com/users/octocat html_url: https://github.com/octocat followers_url: https://api.github.com/users/octocat/followers following_url: https://api.github.com/users/octocat/following{/other_user} gists_url: https://api.github.com/users/octocat/gists{/gist_id} starred_url: https://api.github.com/users/octocat/starred{/owner}{/repo} subscriptions_url: https://api.github.com/users/octocat/subscriptions organizations_url: https://api.github.com/users/octocat/orgs repos_url: https://api.github.com/users/octocat/repos events_url: https://api.github.com/users/octocat/events{/privacy} received_events_url: https://api.github.com/users/octocat/received_events type: User site_admin: false created_at: '2011-04-11T20:09:31Z' updated_at: '2014-03-04T18:58:10Z' project-2: value: owner_url: https://api.github.com/orgs/octocat url: https://api.github.com/projects/1002605 html_url: https://github.com/orgs/api-playground/projects/1 columns_url: https://api.github.com/projects/1002605/columns id: 1002605 node_id: MDc6UHJvamVjdDEwMDI2MDU= name: Organization Roadmap body: High-level roadmap for the upcoming year. number: 1 state: open creator: login: octocat id: 1 node_id: MDQ6VXNlcjE= avatar_url: https://github.com/images/error/octocat_happy.gif gravatar_id: '' url: https://api.github.com/users/octocat html_url: https://github.com/octocat followers_url: https://api.github.com/users/octocat/followers following_url: https://api.github.com/users/octocat/following{/other_user} gists_url: https://api.github.com/users/octocat/gists{/gist_id} starred_url: https://api.github.com/users/octocat/starred{/owner}{/repo} subscriptions_url: https://api.github.com/users/octocat/subscriptions organizations_url: https://api.github.com/users/octocat/orgs repos_url: https://api.github.com/users/octocat/repos events_url: https://api.github.com/users/octocat/events{/privacy} received_events_url: https://api.github.com/users/octocat/received_events type: User site_admin: false created_at: '2011-04-11T20:09:31Z' updated_at: '2014-03-04T18:58:10Z' minimal-repository-items: value: - id: 1296269 node_id: MDEwOlJlcG9zaXRvcnkxMjk2MjY5 name: Hello-World full_name: octocat/Hello-World owner: login: octocat id: 1 node_id: MDQ6VXNlcjE= avatar_url: https://github.com/images/error/octocat_happy.gif gravatar_id: '' url: https://api.github.com/users/octocat html_url: https://github.com/octocat followers_url: https://api.github.com/users/octocat/followers following_url: https://api.github.com/users/octocat/following{/other_user} gists_url: https://api.github.com/users/octocat/gists{/gist_id} starred_url: https://api.github.com/users/octocat/starred{/owner}{/repo} subscriptions_url: https://api.github.com/users/octocat/subscriptions organizations_url: https://api.github.com/users/octocat/orgs repos_url: https://api.github.com/users/octocat/repos events_url: https://api.github.com/users/octocat/events{/privacy} received_events_url: https://api.github.com/users/octocat/received_events type: User site_admin: false private: false html_url: https://github.com/octocat/Hello-World description: This your first repo! fork: false url: https://api.github.com/repos/octocat/Hello-World archive_url: https://api.github.com/repos/octocat/Hello-World/{archive_format}{/ref} assignees_url: https://api.github.com/repos/octocat/Hello-World/assignees{/user} blobs_url: https://api.github.com/repos/octocat/Hello-World/git/blobs{/sha} branches_url: https://api.github.com/repos/octocat/Hello-World/branches{/branch} collaborators_url: https://api.github.com/repos/octocat/Hello-World/collaborators{/collaborator} comments_url: https://api.github.com/repos/octocat/Hello-World/comments{/number} commits_url: https://api.github.com/repos/octocat/Hello-World/commits{/sha} compare_url: https://api.github.com/repos/octocat/Hello-World/compare/{base}...{head} contents_url: https://api.github.com/repos/octocat/Hello-World/contents/{+path} contributors_url: https://api.github.com/repos/octocat/Hello-World/contributors deployments_url: https://api.github.com/repos/octocat/Hello-World/deployments downloads_url: https://api.github.com/repos/octocat/Hello-World/downloads events_url: https://api.github.com/repos/octocat/Hello-World/events forks_url: https://api.github.com/repos/octocat/Hello-World/forks git_commits_url: https://api.github.com/repos/octocat/Hello-World/git/commits{/sha} git_refs_url: https://api.github.com/repos/octocat/Hello-World/git/refs{/sha} git_tags_url: https://api.github.com/repos/octocat/Hello-World/git/tags{/sha} git_url: git:github.com/octocat/Hello-World.git issue_comment_url: https://api.github.com/repos/octocat/Hello-World/issues/comments{/number} issue_events_url: https://api.github.com/repos/octocat/Hello-World/issues/events{/number} issues_url: https://api.github.com/repos/octocat/Hello-World/issues{/number} keys_url: https://api.github.com/repos/octocat/Hello-World/keys{/key_id} labels_url: https://api.github.com/repos/octocat/Hello-World/labels{/name} languages_url: https://api.github.com/repos/octocat/Hello-World/languages merges_url: https://api.github.com/repos/octocat/Hello-World/merges milestones_url: https://api.github.com/repos/octocat/Hello-World/milestones{/number} notifications_url: https://api.github.com/repos/octocat/Hello-World/notifications{?since,all,participating} pulls_url: https://api.github.com/repos/octocat/Hello-World/pulls{/number} releases_url: https://api.github.com/repos/octocat/Hello-World/releases{/id} ssh_url: git@github.com:octocat/Hello-World.git stargazers_url: https://api.github.com/repos/octocat/Hello-World/stargazers statuses_url: https://api.github.com/repos/octocat/Hello-World/statuses/{sha} subscribers_url: https://api.github.com/repos/octocat/Hello-World/subscribers subscription_url: https://api.github.com/repos/octocat/Hello-World/subscription tags_url: https://api.github.com/repos/octocat/Hello-World/tags teams_url: https://api.github.com/repos/octocat/Hello-World/teams trees_url: https://api.github.com/repos/octocat/Hello-World/git/trees{/sha} clone_url: https://github.com/octocat/Hello-World.git mirror_url: git:git.example.com/octocat/Hello-World hooks_url: https://api.github.com/repos/octocat/Hello-World/hooks svn_url: https://svn.github.com/octocat/Hello-World homepage: https://github.com language: forks_count: 9 stargazers_count: 80 watchers_count: 80 size: 108 default_branch: master open_issues_count: 0 is_template: false topics: - octocat - atom - electron - api has_issues: true has_projects: true has_wiki: true has_pages: false has_downloads: true archived: false disabled: false visibility: public pushed_at: '2011-01-26T19:06:43Z' created_at: '2011-01-26T19:01:12Z' updated_at: '2011-01-26T19:14:43Z' permissions: admin: false push: false pull: true template_repository: repository: value: id: 1296269 node_id: MDEwOlJlcG9zaXRvcnkxMjk2MjY5 name: Hello-World full_name: octocat/Hello-World owner: login: octocat id: 1 node_id: MDQ6VXNlcjE= avatar_url: https://github.com/images/error/octocat_happy.gif gravatar_id: '' url: https://api.github.com/users/octocat html_url: https://github.com/octocat followers_url: https://api.github.com/users/octocat/followers following_url: https://api.github.com/users/octocat/following{/other_user} gists_url: https://api.github.com/users/octocat/gists{/gist_id} starred_url: https://api.github.com/users/octocat/starred{/owner}{/repo} subscriptions_url: https://api.github.com/users/octocat/subscriptions organizations_url: https://api.github.com/users/octocat/orgs repos_url: https://api.github.com/users/octocat/repos events_url: https://api.github.com/users/octocat/events{/privacy} received_events_url: https://api.github.com/users/octocat/received_events type: User site_admin: false private: false html_url: https://github.com/octocat/Hello-World description: This your first repo! fork: false url: https://api.github.com/repos/octocat/Hello-World archive_url: https://api.github.com/repos/octocat/Hello-World/{archive_format}{/ref} assignees_url: https://api.github.com/repos/octocat/Hello-World/assignees{/user} blobs_url: https://api.github.com/repos/octocat/Hello-World/git/blobs{/sha} branches_url: https://api.github.com/repos/octocat/Hello-World/branches{/branch} collaborators_url: https://api.github.com/repos/octocat/Hello-World/collaborators{/collaborator} comments_url: https://api.github.com/repos/octocat/Hello-World/comments{/number} commits_url: https://api.github.com/repos/octocat/Hello-World/commits{/sha} compare_url: https://api.github.com/repos/octocat/Hello-World/compare/{base}...{head} contents_url: https://api.github.com/repos/octocat/Hello-World/contents/{+path} contributors_url: https://api.github.com/repos/octocat/Hello-World/contributors deployments_url: https://api.github.com/repos/octocat/Hello-World/deployments downloads_url: https://api.github.com/repos/octocat/Hello-World/downloads events_url: https://api.github.com/repos/octocat/Hello-World/events forks_url: https://api.github.com/repos/octocat/Hello-World/forks git_commits_url: https://api.github.com/repos/octocat/Hello-World/git/commits{/sha} git_refs_url: https://api.github.com/repos/octocat/Hello-World/git/refs{/sha} git_tags_url: https://api.github.com/repos/octocat/Hello-World/git/tags{/sha} git_url: git:github.com/octocat/Hello-World.git issue_comment_url: https://api.github.com/repos/octocat/Hello-World/issues/comments{/number} issue_events_url: https://api.github.com/repos/octocat/Hello-World/issues/events{/number} issues_url: https://api.github.com/repos/octocat/Hello-World/issues{/number} keys_url: https://api.github.com/repos/octocat/Hello-World/keys{/key_id} labels_url: https://api.github.com/repos/octocat/Hello-World/labels{/name} languages_url: https://api.github.com/repos/octocat/Hello-World/languages merges_url: https://api.github.com/repos/octocat/Hello-World/merges milestones_url: https://api.github.com/repos/octocat/Hello-World/milestones{/number} notifications_url: https://api.github.com/repos/octocat/Hello-World/notifications{?since,all,participating} pulls_url: https://api.github.com/repos/octocat/Hello-World/pulls{/number} releases_url: https://api.github.com/repos/octocat/Hello-World/releases{/id} ssh_url: git@github.com:octocat/Hello-World.git stargazers_url: https://api.github.com/repos/octocat/Hello-World/stargazers statuses_url: https://api.github.com/repos/octocat/Hello-World/statuses/{sha} subscribers_url: https://api.github.com/repos/octocat/Hello-World/subscribers subscription_url: https://api.github.com/repos/octocat/Hello-World/subscription tags_url: https://api.github.com/repos/octocat/Hello-World/tags teams_url: https://api.github.com/repos/octocat/Hello-World/teams trees_url: https://api.github.com/repos/octocat/Hello-World/git/trees{/sha} clone_url: https://github.com/octocat/Hello-World.git mirror_url: git:git.example.com/octocat/Hello-World hooks_url: https://api.github.com/repos/octocat/Hello-World/hooks svn_url: https://svn.github.com/octocat/Hello-World homepage: https://github.com forks: 9 forks_count: 9 stargazers_count: 80 watchers_count: 80 watchers: 80 size: 108 default_branch: master open_issues: 0 open_issues_count: 0 is_template: true license: key: mit name: MIT License url: https://api.github.com/licenses/mit spdx_id: MIT node_id: MDc6TGljZW5zZW1pdA== html_url: https://api.github.com/licenses/mit topics: - octocat - atom - electron - api has_issues: true has_projects: true has_wiki: true has_pages: false has_downloads: true archived: false disabled: false visibility: public pushed_at: '2011-01-26T19:06:43Z' created_at: '2011-01-26T19:01:12Z' updated_at: '2011-01-26T19:14:43Z' permissions: admin: false push: false pull: true allow_rebase_merge: true temp_clone_token: ABTLWHOULUVAXGTRYU7OC2876QJ2O allow_squash_merge: true delete_branch_on_merge: true allow_merge_commit: true subscribers_count: 42 network_count: 0 team-items: value: - id: 1 node_id: MDQ6VGVhbTE= url: https://api.github.com/teams/1 html_url: https://github.com/orgs/github/teams/justice-league name: Justice League slug: justice-league description: A great team. privacy: closed permission: admin members_url: https://api.github.com/teams/1/members{/member} repositories_url: https://api.github.com/teams/1/repos parent: team-full: value: id: 1 node_id: MDQ6VGVhbTE= url: https://api.github.com/teams/1 html_url: https://github.com/orgs/github/teams/justice-league name: Justice League slug: justice-league description: A great team. privacy: closed permission: admin members_url: https://api.github.com/teams/1/members{/member} repositories_url: https://api.github.com/teams/1/repos members_count: 3 repos_count: 10 created_at: '2017-07-14T16:53:42Z' updated_at: '2017-08-17T12:37:15Z' organization: login: github id: 1 node_id: MDEyOk9yZ2FuaXphdGlvbjE= url: https://api.github.com/orgs/github repos_url: https://api.github.com/orgs/github/repos events_url: https://api.github.com/orgs/github/events hooks_url: https://api.github.com/orgs/github/hooks issues_url: https://api.github.com/orgs/github/issues members_url: https://api.github.com/orgs/github/members{/member} public_members_url: https://api.github.com/orgs/github/public_members{/member} avatar_url: https://github.com/images/error/octocat_happy.gif description: A great organization name: github company: GitHub blog: https://github.com/blog location: San Francisco email: octocat@github.com has_organization_projects: true has_repository_projects: true public_repos: 2 public_gists: 1 followers: 20 following: 0 html_url: https://github.com/octocat created_at: '2008-01-14T04:33:35Z' updated_at: '2017-08-17T12:37:15Z' type: Organization ldap_dn: uid=asdf,ou=users,dc=github,dc=com team-discussion-items: value: - author: login: octocat id: 1 node_id: MDQ6VXNlcjE= avatar_url: https://github.com/images/error/octocat_happy.gif gravatar_id: '' url: https://api.github.com/users/octocat html_url: https://github.com/octocat followers_url: https://api.github.com/users/octocat/followers following_url: https://api.github.com/users/octocat/following{/other_user} gists_url: https://api.github.com/users/octocat/gists{/gist_id} starred_url: https://api.github.com/users/octocat/starred{/owner}{/repo} subscriptions_url: https://api.github.com/users/octocat/subscriptions organizations_url: https://api.github.com/users/octocat/orgs repos_url: https://api.github.com/users/octocat/repos events_url: https://api.github.com/users/octocat/events{/privacy} received_events_url: https://api.github.com/users/octocat/received_events type: User site_admin: false body: Hi! This is an area for us to collaborate as a team. body_html: "

      Hi! This is an area for us to collaborate as a team

      " body_version: 0d495416a700fb06133c612575d92bfb comments_count: 0 comments_url: https://api.github.com/teams/2343027/discussions/1/comments created_at: '2018-01-25T18:56:31Z' last_edited_at: html_url: https://github.com/orgs/github/teams/justice-league/discussions/1 node_id: MDE0OlRlYW1EaXNjdXNzaW9uMQ== number: 1 pinned: false private: false team_url: https://api.github.com/teams/2343027 title: Our first team post updated_at: '2018-01-25T18:56:31Z' url: https://api.github.com/teams/2343027/discussions/1 reactions: url: https://api.github.com/teams/2343027/discussions/1/reactions total_count: 5 "+1": 3 "-1": 1 laugh: 0 confused: 0 heart: 1 hooray: 0 eyes: 1 rocket: 1 team-discussion: value: author: login: octocat id: 1 node_id: MDQ6VXNlcjE= avatar_url: https://github.com/images/error/octocat_happy.gif gravatar_id: '' url: https://api.github.com/users/octocat html_url: https://github.com/octocat followers_url: https://api.github.com/users/octocat/followers following_url: https://api.github.com/users/octocat/following{/other_user} gists_url: https://api.github.com/users/octocat/gists{/gist_id} starred_url: https://api.github.com/users/octocat/starred{/owner}{/repo} subscriptions_url: https://api.github.com/users/octocat/subscriptions organizations_url: https://api.github.com/users/octocat/orgs repos_url: https://api.github.com/users/octocat/repos events_url: https://api.github.com/users/octocat/events{/privacy} received_events_url: https://api.github.com/users/octocat/received_events type: User site_admin: false body: Hi! This is an area for us to collaborate as a team. body_html: "

      Hi! This is an area for us to collaborate as a team

      " body_version: 0d495416a700fb06133c612575d92bfb comments_count: 0 comments_url: https://api.github.com/teams/2343027/discussions/1/comments created_at: '2018-01-25T18:56:31Z' last_edited_at: html_url: https://github.com/orgs/github/teams/justice-league/discussions/1 node_id: MDE0OlRlYW1EaXNjdXNzaW9uMQ== number: 1 pinned: false private: false team_url: https://api.github.com/teams/2343027 title: Our first team post updated_at: '2018-01-25T18:56:31Z' url: https://api.github.com/teams/2343027/discussions/1 reactions: url: https://api.github.com/teams/2343027/discussions/1/reactions total_count: 5 "+1": 3 "-1": 1 laugh: 0 confused: 0 heart: 1 hooray: 0 eyes: 1 rocket: 1 team-discussion-2: value: author: login: octocat id: 1 node_id: MDQ6VXNlcjE= avatar_url: https://github.com/images/error/octocat_happy.gif gravatar_id: '' url: https://api.github.com/users/octocat html_url: https://github.com/octocat followers_url: https://api.github.com/users/octocat/followers following_url: https://api.github.com/users/octocat/following{/other_user} gists_url: https://api.github.com/users/octocat/gists{/gist_id} starred_url: https://api.github.com/users/octocat/starred{/owner}{/repo} subscriptions_url: https://api.github.com/users/octocat/subscriptions organizations_url: https://api.github.com/users/octocat/orgs repos_url: https://api.github.com/users/octocat/repos events_url: https://api.github.com/users/octocat/events{/privacy} received_events_url: https://api.github.com/users/octocat/received_events type: User site_admin: false body: Hi! This is an area for us to collaborate as a team. body_html: "

      Hi! This is an area for us to collaborate as a team

      " body_version: 0d495416a700fb06133c612575d92bfb comments_count: 1 comments_url: https://api.github.com/teams/2343027/discussions/1/comments created_at: '2018-01-25T18:56:31Z' last_edited_at: '2018-01-26T18:22:20Z' html_url: https://github.com/orgs/github/teams/justice-league/discussions/1 node_id: MDE0OlRlYW1EaXNjdXNzaW9uMQ== number: 1 pinned: false private: false team_url: https://api.github.com/teams/2343027 title: Welcome to our first team post updated_at: '2018-01-26T18:22:20Z' url: https://api.github.com/teams/2343027/discussions/1 reactions: url: https://api.github.com/teams/2343027/discussions/1/reactions total_count: 5 "+1": 3 "-1": 1 laugh: 0 confused: 0 heart: 1 hooray: 0 eyes: 1 rocket: 1 team-discussion-comment-items: value: - author: login: octocat id: 1 node_id: MDQ6VXNlcjE= avatar_url: https://github.com/images/error/octocat_happy.gif gravatar_id: '' url: https://api.github.com/users/octocat html_url: https://github.com/octocat followers_url: https://api.github.com/users/octocat/followers following_url: https://api.github.com/users/octocat/following{/other_user} gists_url: https://api.github.com/users/octocat/gists{/gist_id} starred_url: https://api.github.com/users/octocat/starred{/owner}{/repo} subscriptions_url: https://api.github.com/users/octocat/subscriptions organizations_url: https://api.github.com/users/octocat/orgs repos_url: https://api.github.com/users/octocat/repos events_url: https://api.github.com/users/octocat/events{/privacy} received_events_url: https://api.github.com/users/octocat/received_events type: User site_admin: false body: Do you like apples? body_html: "

      Do you like apples?

      " body_version: 5eb32b219cdc6a5a9b29ba5d6caa9c51 created_at: '2018-01-15T23:53:58Z' last_edited_at: discussion_url: https://api.github.com/teams/2403582/discussions/1 html_url: https://github.com/orgs/github/teams/justice-league/discussions/1/comments/1 node_id: MDIxOlRlYW1EaXNjdXNzaW9uQ29tbWVudDE= number: 1 updated_at: '2018-01-15T23:53:58Z' url: https://api.github.com/teams/2403582/discussions/1/comments/1 reactions: url: https://api.github.com/teams/2403582/discussions/1/reactions total_count: 5 "+1": 3 "-1": 1 laugh: 0 confused: 0 heart: 1 hooray: 0 eyes: 1 rocket: 1 team-discussion-comment: value: author: login: octocat id: 1 node_id: MDQ6VXNlcjE= avatar_url: https://github.com/images/error/octocat_happy.gif gravatar_id: '' url: https://api.github.com/users/octocat html_url: https://github.com/octocat followers_url: https://api.github.com/users/octocat/followers following_url: https://api.github.com/users/octocat/following{/other_user} gists_url: https://api.github.com/users/octocat/gists{/gist_id} starred_url: https://api.github.com/users/octocat/starred{/owner}{/repo} subscriptions_url: https://api.github.com/users/octocat/subscriptions organizations_url: https://api.github.com/users/octocat/orgs repos_url: https://api.github.com/users/octocat/repos events_url: https://api.github.com/users/octocat/events{/privacy} received_events_url: https://api.github.com/users/octocat/received_events type: User site_admin: false body: Do you like apples? body_html: "

      Do you like apples?

      " body_version: 5eb32b219cdc6a5a9b29ba5d6caa9c51 created_at: '2018-01-15T23:53:58Z' last_edited_at: discussion_url: https://api.github.com/teams/2403582/discussions/1 html_url: https://github.com/orgs/github/teams/justice-league/discussions/1/comments/1 node_id: MDIxOlRlYW1EaXNjdXNzaW9uQ29tbWVudDE= number: 1 updated_at: '2018-01-15T23:53:58Z' url: https://api.github.com/teams/2403582/discussions/1/comments/1 reactions: url: https://api.github.com/teams/2403582/discussions/1/reactions total_count: 5 "+1": 3 "-1": 1 laugh: 0 confused: 0 heart: 1 hooray: 0 eyes: 1 rocket: 1 team-discussion-comment-2: value: author: login: octocat id: 1 node_id: MDQ6VXNlcjE= avatar_url: https://github.com/images/error/octocat_happy.gif gravatar_id: '' url: https://api.github.com/users/octocat html_url: https://github.com/octocat followers_url: https://api.github.com/users/octocat/followers following_url: https://api.github.com/users/octocat/following{/other_user} gists_url: https://api.github.com/users/octocat/gists{/gist_id} starred_url: https://api.github.com/users/octocat/starred{/owner}{/repo} subscriptions_url: https://api.github.com/users/octocat/subscriptions organizations_url: https://api.github.com/users/octocat/orgs repos_url: https://api.github.com/users/octocat/repos events_url: https://api.github.com/users/octocat/events{/privacy} received_events_url: https://api.github.com/users/octocat/received_events type: User site_admin: false body: Do you like pineapples? body_html: "

      Do you like pineapples?

      " body_version: e6907b24d9c93cc0c5024a7af5888116 created_at: '2018-01-15T23:53:58Z' last_edited_at: '2018-01-26T18:22:20Z' discussion_url: https://api.github.com/teams/2403582/discussions/1 html_url: https://github.com/orgs/github/teams/justice-league/discussions/1/comments/1 node_id: MDIxOlRlYW1EaXNjdXNzaW9uQ29tbWVudDE= number: 1 updated_at: '2018-01-26T18:22:20Z' url: https://api.github.com/teams/2403582/discussions/1/comments/1 reactions: url: https://api.github.com/teams/2403582/discussions/1/reactions total_count: 5 "+1": 3 "-1": 1 laugh: 0 confused: 0 heart: 1 hooray: 0 eyes: 1 rocket: 1 reaction-items: value: - id: 1 node_id: MDg6UmVhY3Rpb24x user: login: octocat id: 1 node_id: MDQ6VXNlcjE= avatar_url: https://github.com/images/error/octocat_happy.gif gravatar_id: '' url: https://api.github.com/users/octocat html_url: https://github.com/octocat followers_url: https://api.github.com/users/octocat/followers following_url: https://api.github.com/users/octocat/following{/other_user} gists_url: https://api.github.com/users/octocat/gists{/gist_id} starred_url: https://api.github.com/users/octocat/starred{/owner}{/repo} subscriptions_url: https://api.github.com/users/octocat/subscriptions organizations_url: https://api.github.com/users/octocat/orgs repos_url: https://api.github.com/users/octocat/repos events_url: https://api.github.com/users/octocat/events{/privacy} received_events_url: https://api.github.com/users/octocat/received_events type: User site_admin: false content: heart created_at: '2016-05-20T20:09:31Z' reaction: value: id: 1 node_id: MDg6UmVhY3Rpb24x user: login: octocat id: 1 node_id: MDQ6VXNlcjE= avatar_url: https://github.com/images/error/octocat_happy.gif gravatar_id: '' url: https://api.github.com/users/octocat html_url: https://github.com/octocat followers_url: https://api.github.com/users/octocat/followers following_url: https://api.github.com/users/octocat/following{/other_user} gists_url: https://api.github.com/users/octocat/gists{/gist_id} starred_url: https://api.github.com/users/octocat/starred{/owner}{/repo} subscriptions_url: https://api.github.com/users/octocat/subscriptions organizations_url: https://api.github.com/users/octocat/orgs repos_url: https://api.github.com/users/octocat/repos events_url: https://api.github.com/users/octocat/events{/privacy} received_events_url: https://api.github.com/users/octocat/received_events type: User site_admin: false content: heart created_at: '2016-05-20T20:09:31Z' team-membership-response-if-user-is-a-team-maintainer: summary: Response if user is a team maintainer value: url: https://api.github.com/teams/1/memberships/octocat role: maintainer state: active team-membership-response-if-users-membership-with-team-is-now-pending: summary: Response if user's membership with team is now pending value: url: https://api.github.com/teams/1/memberships/octocat role: member state: pending team-project-items: value: - owner_url: https://api.github.com/orgs/octocat url: https://api.github.com/projects/1002605 html_url: https://github.com/orgs/api-playground/projects/1 columns_url: https://api.github.com/projects/1002605/columns id: 1002605 node_id: MDc6UHJvamVjdDEwMDI2MDU= name: Organization Roadmap body: High-level roadmap for the upcoming year. number: 1 state: open creator: login: octocat id: 1 node_id: MDQ6VXNlcjE= avatar_url: https://github.com/images/error/octocat_happy.gif gravatar_id: '' url: https://api.github.com/users/octocat html_url: https://github.com/octocat followers_url: https://api.github.com/users/octocat/followers following_url: https://api.github.com/users/octocat/following{/other_user} gists_url: https://api.github.com/users/octocat/gists{/gist_id} starred_url: https://api.github.com/users/octocat/starred{/owner}{/repo} subscriptions_url: https://api.github.com/users/octocat/subscriptions organizations_url: https://api.github.com/users/octocat/orgs repos_url: https://api.github.com/users/octocat/repos events_url: https://api.github.com/users/octocat/events{/privacy} received_events_url: https://api.github.com/users/octocat/received_events type: User site_admin: false created_at: '2011-04-11T20:09:31Z' updated_at: '2014-03-04T18:58:10Z' organization_permission: write private: false permissions: read: true write: true admin: false team-project: value: owner_url: https://api.github.com/orgs/octocat url: https://api.github.com/projects/1002605 html_url: https://github.com/orgs/api-playground/projects/1 columns_url: https://api.github.com/projects/1002605/columns id: 1002605 node_id: MDc6UHJvamVjdDEwMDI2MDU= name: Organization Roadmap body: High-level roadmap for the upcoming year. number: 1 state: open creator: login: octocat id: 1 node_id: MDQ6VXNlcjE= avatar_url: https://github.com/images/error/octocat_happy.gif gravatar_id: '' url: https://api.github.com/users/octocat html_url: https://github.com/octocat followers_url: https://api.github.com/users/octocat/followers following_url: https://api.github.com/users/octocat/following{/other_user} gists_url: https://api.github.com/users/octocat/gists{/gist_id} starred_url: https://api.github.com/users/octocat/starred{/owner}{/repo} subscriptions_url: https://api.github.com/users/octocat/subscriptions organizations_url: https://api.github.com/users/octocat/orgs repos_url: https://api.github.com/users/octocat/repos events_url: https://api.github.com/users/octocat/events{/privacy} received_events_url: https://api.github.com/users/octocat/received_events type: User site_admin: false created_at: '2011-04-11T20:09:31Z' updated_at: '2014-03-04T18:58:10Z' organization_permission: write private: false permissions: read: true write: true admin: false team-repository-alternative-response-with-repository-permissions: value: id: 1296269 node_id: MDEwOlJlcG9zaXRvcnkxMjk2MjY5 name: Hello-World full_name: octocat/Hello-World owner: login: octocat id: 1 node_id: MDQ6VXNlcjE= avatar_url: https://github.com/images/error/octocat_happy.gif gravatar_id: '' url: https://api.github.com/users/octocat html_url: https://github.com/octocat followers_url: https://api.github.com/users/octocat/followers following_url: https://api.github.com/users/octocat/following{/other_user} gists_url: https://api.github.com/users/octocat/gists{/gist_id} starred_url: https://api.github.com/users/octocat/starred{/owner}{/repo} subscriptions_url: https://api.github.com/users/octocat/subscriptions organizations_url: https://api.github.com/users/octocat/orgs repos_url: https://api.github.com/users/octocat/repos events_url: https://api.github.com/users/octocat/events{/privacy} received_events_url: https://api.github.com/users/octocat/received_events type: User site_admin: false private: false html_url: https://github.com/octocat/Hello-World description: This your first repo! fork: false url: https://api.github.com/repos/octocat/Hello-World archive_url: https://api.github.com/repos/octocat/Hello-World/{archive_format}{/ref} assignees_url: https://api.github.com/repos/octocat/Hello-World/assignees{/user} blobs_url: https://api.github.com/repos/octocat/Hello-World/git/blobs{/sha} branches_url: https://api.github.com/repos/octocat/Hello-World/branches{/branch} collaborators_url: https://api.github.com/repos/octocat/Hello-World/collaborators{/collaborator} comments_url: https://api.github.com/repos/octocat/Hello-World/comments{/number} commits_url: https://api.github.com/repos/octocat/Hello-World/commits{/sha} compare_url: https://api.github.com/repos/octocat/Hello-World/compare/{base}...{head} contents_url: https://api.github.com/repos/octocat/Hello-World/contents/{+path} contributors_url: https://api.github.com/repos/octocat/Hello-World/contributors deployments_url: https://api.github.com/repos/octocat/Hello-World/deployments downloads_url: https://api.github.com/repos/octocat/Hello-World/downloads events_url: https://api.github.com/repos/octocat/Hello-World/events forks_url: https://api.github.com/repos/octocat/Hello-World/forks git_commits_url: https://api.github.com/repos/octocat/Hello-World/git/commits{/sha} git_refs_url: https://api.github.com/repos/octocat/Hello-World/git/refs{/sha} git_tags_url: https://api.github.com/repos/octocat/Hello-World/git/tags{/sha} git_url: git:github.com/octocat/Hello-World.git issue_comment_url: https://api.github.com/repos/octocat/Hello-World/issues/comments{/number} issue_events_url: https://api.github.com/repos/octocat/Hello-World/issues/events{/number} issues_url: https://api.github.com/repos/octocat/Hello-World/issues{/number} keys_url: https://api.github.com/repos/octocat/Hello-World/keys{/key_id} labels_url: https://api.github.com/repos/octocat/Hello-World/labels{/name} languages_url: https://api.github.com/repos/octocat/Hello-World/languages merges_url: https://api.github.com/repos/octocat/Hello-World/merges milestones_url: https://api.github.com/repos/octocat/Hello-World/milestones{/number} notifications_url: https://api.github.com/repos/octocat/Hello-World/notifications{?since,all,participating} pulls_url: https://api.github.com/repos/octocat/Hello-World/pulls{/number} releases_url: https://api.github.com/repos/octocat/Hello-World/releases{/id} ssh_url: git@github.com:octocat/Hello-World.git stargazers_url: https://api.github.com/repos/octocat/Hello-World/stargazers statuses_url: https://api.github.com/repos/octocat/Hello-World/statuses/{sha} subscribers_url: https://api.github.com/repos/octocat/Hello-World/subscribers subscription_url: https://api.github.com/repos/octocat/Hello-World/subscription tags_url: https://api.github.com/repos/octocat/Hello-World/tags teams_url: https://api.github.com/repos/octocat/Hello-World/teams trees_url: https://api.github.com/repos/octocat/Hello-World/git/trees{/sha} clone_url: https://github.com/octocat/Hello-World.git mirror_url: git:git.example.com/octocat/Hello-World hooks_url: https://api.github.com/repos/octocat/Hello-World/hooks svn_url: https://svn.github.com/octocat/Hello-World homepage: https://github.com forks_count: 9 stargazers_count: 80 watchers_count: 80 size: 108 default_branch: master open_issues_count: 0 is_template: false topics: - octocat - atom - electron - api has_issues: true has_projects: true has_wiki: true has_pages: false has_downloads: true archived: false disabled: false visibility: public pushed_at: '2011-01-26T19:06:43Z' created_at: '2011-01-26T19:01:12Z' updated_at: '2011-01-26T19:14:43Z' permissions: admin: false maintain: false push: false triage: false pull: true allow_rebase_merge: true template_repository: id: 1296269 node_id: MDEwOlJlcG9zaXRvcnkxMjk2MjY5 name: Hello-World-Template full_name: octocat/Hello-World-Template owner: login: octocat id: 1 node_id: MDQ6VXNlcjE= avatar_url: https://github.com/images/error/octocat_happy.gif gravatar_id: '' url: https://api.github.com/users/octocat html_url: https://github.com/octocat followers_url: https://api.github.com/users/octocat/followers following_url: https://api.github.com/users/octocat/following{/other_user} gists_url: https://api.github.com/users/octocat/gists{/gist_id} starred_url: https://api.github.com/users/octocat/starred{/owner}{/repo} subscriptions_url: https://api.github.com/users/octocat/subscriptions organizations_url: https://api.github.com/users/octocat/orgs repos_url: https://api.github.com/users/octocat/repos events_url: https://api.github.com/users/octocat/events{/privacy} received_events_url: https://api.github.com/users/octocat/received_events type: User site_admin: false private: false html_url: https://github.com/octocat/Hello-World-Template description: This your first repo! fork: false url: https://api.github.com/repos/octocat/Hello-World-Template archive_url: https://api.github.com/repos/octocat/Hello-World-Template/{archive_format}{/ref} assignees_url: https://api.github.com/repos/octocat/Hello-World-Template/assignees{/user} blobs_url: https://api.github.com/repos/octocat/Hello-World-Template/git/blobs{/sha} branches_url: https://api.github.com/repos/octocat/Hello-World-Template/branches{/branch} collaborators_url: https://api.github.com/repos/octocat/Hello-World-Template/collaborators{/collaborator} comments_url: https://api.github.com/repos/octocat/Hello-World-Template/comments{/number} commits_url: https://api.github.com/repos/octocat/Hello-World-Template/commits{/sha} compare_url: https://api.github.com/repos/octocat/Hello-World-Template/compare/{base}...{head} contents_url: https://api.github.com/repos/octocat/Hello-World-Template/contents/{+path} contributors_url: https://api.github.com/repos/octocat/Hello-World-Template/contributors deployments_url: https://api.github.com/repos/octocat/Hello-World-Template/deployments downloads_url: https://api.github.com/repos/octocat/Hello-World-Template/downloads events_url: https://api.github.com/repos/octocat/Hello-World-Template/events forks_url: https://api.github.com/repos/octocat/Hello-World-Template/forks git_commits_url: https://api.github.com/repos/octocat/Hello-World-Template/git/commits{/sha} git_refs_url: https://api.github.com/repos/octocat/Hello-World-Template/git/refs{/sha} git_tags_url: https://api.github.com/repos/octocat/Hello-World-Template/git/tags{/sha} git_url: git:github.com/octocat/Hello-World-Template.git issue_comment_url: https://api.github.com/repos/octocat/Hello-World-Template/issues/comments{/number} issue_events_url: https://api.github.com/repos/octocat/Hello-World-Template/issues/events{/number} issues_url: https://api.github.com/repos/octocat/Hello-World-Template/issues{/number} keys_url: https://api.github.com/repos/octocat/Hello-World-Template/keys{/key_id} labels_url: https://api.github.com/repos/octocat/Hello-World-Template/labels{/name} languages_url: https://api.github.com/repos/octocat/Hello-World-Template/languages merges_url: https://api.github.com/repos/octocat/Hello-World-Template/merges milestones_url: https://api.github.com/repos/octocat/Hello-World-Template/milestones{/number} notifications_url: https://api.github.com/repos/octocat/Hello-World-Template/notifications{?since,all,participating} pulls_url: https://api.github.com/repos/octocat/Hello-World-Template/pulls{/number} releases_url: https://api.github.com/repos/octocat/Hello-World-Template/releases{/id} ssh_url: git@github.com:octocat/Hello-World-Template.git stargazers_url: https://api.github.com/repos/octocat/Hello-World-Template/stargazers statuses_url: https://api.github.com/repos/octocat/Hello-World-Template/statuses/{sha} subscribers_url: https://api.github.com/repos/octocat/Hello-World-Template/subscribers subscription_url: https://api.github.com/repos/octocat/Hello-World-Template/subscription tags_url: https://api.github.com/repos/octocat/Hello-World-Template/tags teams_url: https://api.github.com/repos/octocat/Hello-World-Template/teams trees_url: https://api.github.com/repos/octocat/Hello-World-Template/git/trees{/sha} clone_url: https://github.com/octocat/Hello-World-Template.git mirror_url: git:git.example.com/octocat/Hello-World-Template hooks_url: https://api.github.com/repos/octocat/Hello-World-Template/hooks svn_url: https://svn.github.com/octocat/Hello-World-Template homepage: https://github.com forks: 9 forks_count: 9 stargazers_count: 80 watchers_count: 80 watchers: 80 size: 108 default_branch: master open_issues: 0 open_issues_count: 0 is_template: true license: key: mit name: MIT License url: https://api.github.com/licenses/mit spdx_id: MIT node_id: MDc6TGljZW5zZW1pdA== html_url: https://api.github.com/licenses/mit topics: - octocat - atom - electron - api has_issues: true has_projects: true has_wiki: true has_pages: false has_downloads: true archived: false disabled: false visibility: public pushed_at: '2011-01-26T19:06:43Z' created_at: '2011-01-26T19:01:12Z' updated_at: '2011-01-26T19:14:43Z' permissions: pull: true triage: false push: false maintain: false admin: false allow_rebase_merge: true temp_clone_token: ABTLWHOULUVAXGTRYU7OC2876QJ2O allow_squash_merge: true delete_branch_on_merge: true allow_merge_commit: true subscribers_count: 42 network_count: 0 temp_clone_token: ABTLWHOULUVAXGTRYU7OC2876QJ2O allow_squash_merge: true delete_branch_on_merge: true allow_merge_commit: true subscribers_count: 42 network_count: 0 license: key: mit name: MIT License url: https://api.github.com/licenses/mit spdx_id: MIT node_id: MDc6TGljZW5zZW1pdA== html_url: https://api.github.com/licenses/mit forks: 1 open_issues: 1 watchers: 1 team-items-response-if-child-teams-exist: value: - id: 2 node_id: MDQ6VGVhbTI= url: https://api.github.com/teams/2 name: Original Roster slug: original-roster description: Started it all. privacy: closed permission: admin members_url: https://api.github.com/teams/2/members{/member} repositories_url: https://api.github.com/teams/2/repos parent: id: 1 node_id: MDQ6VGVhbTE= url: https://api.github.com/teams/1 html_url: https://github.com/orgs/github/teams/justice-league name: Justice League slug: justice-league description: A great team. privacy: closed permission: admin members_url: https://api.github.com/teams/1/members{/member} repositories_url: https://api.github.com/teams/1/repos html_url: https://github.com/orgs/rails/teams/core project-card: value: url: https://api.github.com/projects/columns/cards/1478 id: 1478 node_id: MDExOlByb2plY3RDYXJkMTQ3OA== note: Add payload for delete Project column creator: login: octocat id: 1 node_id: MDQ6VXNlcjE= avatar_url: https://github.com/images/error/octocat_happy.gif gravatar_id: '' url: https://api.github.com/users/octocat html_url: https://github.com/octocat followers_url: https://api.github.com/users/octocat/followers following_url: https://api.github.com/users/octocat/following{/other_user} gists_url: https://api.github.com/users/octocat/gists{/gist_id} starred_url: https://api.github.com/users/octocat/starred{/owner}{/repo} subscriptions_url: https://api.github.com/users/octocat/subscriptions organizations_url: https://api.github.com/users/octocat/orgs repos_url: https://api.github.com/users/octocat/repos events_url: https://api.github.com/users/octocat/events{/privacy} received_events_url: https://api.github.com/users/octocat/received_events type: User site_admin: false created_at: '2016-09-05T14:21:06Z' updated_at: '2016-09-05T14:20:22Z' archived: false column_url: https://api.github.com/projects/columns/367 content_url: https://api.github.com/repos/api-playground/projects-test/issues/3 project_url: https://api.github.com/projects/120 project-column: value: url: https://api.github.com/projects/columns/367 project_url: https://api.github.com/projects/120 cards_url: https://api.github.com/projects/columns/367/cards id: 367 node_id: MDEzOlByb2plY3RDb2x1bW4zNjc= name: To Do created_at: '2016-09-05T14:18:44Z' updated_at: '2016-09-05T14:22:28Z' project-card-items: value: - url: https://api.github.com/projects/columns/cards/1478 id: 1478 node_id: MDExOlByb2plY3RDYXJkMTQ3OA== note: Add payload for delete Project column creator: login: octocat id: 1 node_id: MDQ6VXNlcjE= avatar_url: https://github.com/images/error/octocat_happy.gif gravatar_id: '' url: https://api.github.com/users/octocat html_url: https://github.com/octocat followers_url: https://api.github.com/users/octocat/followers following_url: https://api.github.com/users/octocat/following{/other_user} gists_url: https://api.github.com/users/octocat/gists{/gist_id} starred_url: https://api.github.com/users/octocat/starred{/owner}{/repo} subscriptions_url: https://api.github.com/users/octocat/subscriptions organizations_url: https://api.github.com/users/octocat/orgs repos_url: https://api.github.com/users/octocat/repos events_url: https://api.github.com/users/octocat/events{/privacy} received_events_url: https://api.github.com/users/octocat/received_events type: User site_admin: false created_at: '2016-09-05T14:21:06Z' updated_at: '2016-09-05T14:20:22Z' archived: false column_url: https://api.github.com/projects/columns/367 content_url: https://api.github.com/repos/api-playground/projects-test/issues/3 project_url: https://api.github.com/projects/120 project-3: value: owner_url: https://api.github.com/repos/api-playground/projects-test url: https://api.github.com/projects/1002604 html_url: https://github.com/api-playground/projects-test/projects/1 columns_url: https://api.github.com/projects/1002604/columns id: 1002604 node_id: MDc6UHJvamVjdDEwMDI2MDQ= name: Projects Documentation body: Developer documentation project for the developer site. number: 1 state: open creator: login: octocat id: 1 node_id: MDQ6VXNlcjE= avatar_url: https://github.com/images/error/octocat_happy.gif gravatar_id: '' url: https://api.github.com/users/octocat html_url: https://github.com/octocat followers_url: https://api.github.com/users/octocat/followers following_url: https://api.github.com/users/octocat/following{/other_user} gists_url: https://api.github.com/users/octocat/gists{/gist_id} starred_url: https://api.github.com/users/octocat/starred{/owner}{/repo} subscriptions_url: https://api.github.com/users/octocat/subscriptions organizations_url: https://api.github.com/users/octocat/orgs repos_url: https://api.github.com/users/octocat/repos events_url: https://api.github.com/users/octocat/events{/privacy} received_events_url: https://api.github.com/users/octocat/received_events type: User site_admin: false created_at: '2011-04-10T20:09:31Z' updated_at: '2014-03-03T18:58:10Z' project-collaborator-permission: value: permission: admin user: login: octocat id: 1 node_id: MDQ6VXNlcjE= avatar_url: https://github.com/images/error/octocat_happy.gif gravatar_id: '' url: https://api.github.com/users/octocat html_url: https://github.com/octocat followers_url: https://api.github.com/users/octocat/followers following_url: https://api.github.com/users/octocat/following{/other_user} gists_url: https://api.github.com/users/octocat/gists{/gist_id} starred_url: https://api.github.com/users/octocat/starred{/owner}{/repo} subscriptions_url: https://api.github.com/users/octocat/subscriptions organizations_url: https://api.github.com/users/octocat/orgs repos_url: https://api.github.com/users/octocat/repos events_url: https://api.github.com/users/octocat/events{/privacy} received_events_url: https://api.github.com/users/octocat/received_events type: User site_admin: false project-column-items: value: - url: https://api.github.com/projects/columns/367 project_url: https://api.github.com/projects/120 cards_url: https://api.github.com/projects/columns/367/cards id: 367 node_id: MDEzOlByb2plY3RDb2x1bW4zNjc= name: To Do created_at: '2016-09-05T14:18:44Z' updated_at: '2016-09-05T14:22:28Z' rate-limit-overview: value: resources: core: limit: 5000 remaining: 4999 reset: 1372700873 used: 1 search: limit: 30 remaining: 18 reset: 1372697452 used: 12 graphql: limit: 5000 remaining: 4993 reset: 1372700389 used: 7 integration_manifest: limit: 5000 remaining: 4999 reset: 1551806725 used: 1 code_scanning_upload: limit: 500 remaining: 499 reset: 1551806725 used: 1 rate: limit: 5000 remaining: 4999 reset: 1372700873 used: 1 full-repository-default-response: summary: Default response value: id: 1296269 node_id: MDEwOlJlcG9zaXRvcnkxMjk2MjY5 name: Hello-World full_name: octocat/Hello-World owner: login: octocat id: 1 node_id: MDQ6VXNlcjE= avatar_url: https://github.com/images/error/octocat_happy.gif gravatar_id: '' url: https://api.github.com/users/octocat html_url: https://github.com/octocat followers_url: https://api.github.com/users/octocat/followers following_url: https://api.github.com/users/octocat/following{/other_user} gists_url: https://api.github.com/users/octocat/gists{/gist_id} starred_url: https://api.github.com/users/octocat/starred{/owner}{/repo} subscriptions_url: https://api.github.com/users/octocat/subscriptions organizations_url: https://api.github.com/users/octocat/orgs repos_url: https://api.github.com/users/octocat/repos events_url: https://api.github.com/users/octocat/events{/privacy} received_events_url: https://api.github.com/users/octocat/received_events type: User site_admin: false private: false html_url: https://github.com/octocat/Hello-World description: This your first repo! fork: false url: https://api.github.com/repos/octocat/Hello-World archive_url: https://api.github.com/repos/octocat/Hello-World/{archive_format}{/ref} assignees_url: https://api.github.com/repos/octocat/Hello-World/assignees{/user} blobs_url: https://api.github.com/repos/octocat/Hello-World/git/blobs{/sha} branches_url: https://api.github.com/repos/octocat/Hello-World/branches{/branch} collaborators_url: https://api.github.com/repos/octocat/Hello-World/collaborators{/collaborator} comments_url: https://api.github.com/repos/octocat/Hello-World/comments{/number} commits_url: https://api.github.com/repos/octocat/Hello-World/commits{/sha} compare_url: https://api.github.com/repos/octocat/Hello-World/compare/{base}...{head} contents_url: https://api.github.com/repos/octocat/Hello-World/contents/{+path} contributors_url: https://api.github.com/repos/octocat/Hello-World/contributors deployments_url: https://api.github.com/repos/octocat/Hello-World/deployments downloads_url: https://api.github.com/repos/octocat/Hello-World/downloads events_url: https://api.github.com/repos/octocat/Hello-World/events forks_url: https://api.github.com/repos/octocat/Hello-World/forks git_commits_url: https://api.github.com/repos/octocat/Hello-World/git/commits{/sha} git_refs_url: https://api.github.com/repos/octocat/Hello-World/git/refs{/sha} git_tags_url: https://api.github.com/repos/octocat/Hello-World/git/tags{/sha} git_url: git:github.com/octocat/Hello-World.git issue_comment_url: https://api.github.com/repos/octocat/Hello-World/issues/comments{/number} issue_events_url: https://api.github.com/repos/octocat/Hello-World/issues/events{/number} issues_url: https://api.github.com/repos/octocat/Hello-World/issues{/number} keys_url: https://api.github.com/repos/octocat/Hello-World/keys{/key_id} labels_url: https://api.github.com/repos/octocat/Hello-World/labels{/name} languages_url: https://api.github.com/repos/octocat/Hello-World/languages merges_url: https://api.github.com/repos/octocat/Hello-World/merges milestones_url: https://api.github.com/repos/octocat/Hello-World/milestones{/number} notifications_url: https://api.github.com/repos/octocat/Hello-World/notifications{?since,all,participating} pulls_url: https://api.github.com/repos/octocat/Hello-World/pulls{/number} releases_url: https://api.github.com/repos/octocat/Hello-World/releases{/id} ssh_url: git@github.com:octocat/Hello-World.git stargazers_url: https://api.github.com/repos/octocat/Hello-World/stargazers statuses_url: https://api.github.com/repos/octocat/Hello-World/statuses/{sha} subscribers_url: https://api.github.com/repos/octocat/Hello-World/subscribers subscription_url: https://api.github.com/repos/octocat/Hello-World/subscription tags_url: https://api.github.com/repos/octocat/Hello-World/tags teams_url: https://api.github.com/repos/octocat/Hello-World/teams trees_url: https://api.github.com/repos/octocat/Hello-World/git/trees{/sha} clone_url: https://github.com/octocat/Hello-World.git mirror_url: git:git.example.com/octocat/Hello-World hooks_url: https://api.github.com/repos/octocat/Hello-World/hooks svn_url: https://svn.github.com/octocat/Hello-World homepage: https://github.com forks_count: 9 forks: 9 stargazers_count: 80 watchers_count: 80 watchers: 80 size: 108 default_branch: master open_issues_count: 0 open_issues: 0 is_template: false topics: - octocat - atom - electron - api has_issues: true has_projects: true has_wiki: true has_pages: false has_downloads: true archived: false disabled: false visibility: public pushed_at: '2011-01-26T19:06:43Z' created_at: '2011-01-26T19:01:12Z' updated_at: '2011-01-26T19:14:43Z' permissions: pull: true push: false admin: false allow_rebase_merge: true template_repository: id: 1296269 node_id: MDEwOlJlcG9zaXRvcnkxMjk2MjY5 name: Hello-World-Template full_name: octocat/Hello-World-Template owner: login: octocat id: 1 node_id: MDQ6VXNlcjE= avatar_url: https://github.com/images/error/octocat_happy.gif gravatar_id: '' url: https://api.github.com/users/octocat html_url: https://github.com/octocat followers_url: https://api.github.com/users/octocat/followers following_url: https://api.github.com/users/octocat/following{/other_user} gists_url: https://api.github.com/users/octocat/gists{/gist_id} starred_url: https://api.github.com/users/octocat/starred{/owner}{/repo} subscriptions_url: https://api.github.com/users/octocat/subscriptions organizations_url: https://api.github.com/users/octocat/orgs repos_url: https://api.github.com/users/octocat/repos events_url: https://api.github.com/users/octocat/events{/privacy} received_events_url: https://api.github.com/users/octocat/received_events type: User site_admin: false private: false html_url: https://github.com/octocat/Hello-World-Template description: This your first repo! fork: false url: https://api.github.com/repos/octocat/Hello-World-Template archive_url: https://api.github.com/repos/octocat/Hello-World-Template/{archive_format}{/ref} assignees_url: https://api.github.com/repos/octocat/Hello-World-Template/assignees{/user} blobs_url: https://api.github.com/repos/octocat/Hello-World-Template/git/blobs{/sha} branches_url: https://api.github.com/repos/octocat/Hello-World-Template/branches{/branch} collaborators_url: https://api.github.com/repos/octocat/Hello-World-Template/collaborators{/collaborator} comments_url: https://api.github.com/repos/octocat/Hello-World-Template/comments{/number} commits_url: https://api.github.com/repos/octocat/Hello-World-Template/commits{/sha} compare_url: https://api.github.com/repos/octocat/Hello-World-Template/compare/{base}...{head} contents_url: https://api.github.com/repos/octocat/Hello-World-Template/contents/{+path} contributors_url: https://api.github.com/repos/octocat/Hello-World-Template/contributors deployments_url: https://api.github.com/repos/octocat/Hello-World-Template/deployments downloads_url: https://api.github.com/repos/octocat/Hello-World-Template/downloads events_url: https://api.github.com/repos/octocat/Hello-World-Template/events forks_url: https://api.github.com/repos/octocat/Hello-World-Template/forks git_commits_url: https://api.github.com/repos/octocat/Hello-World-Template/git/commits{/sha} git_refs_url: https://api.github.com/repos/octocat/Hello-World-Template/git/refs{/sha} git_tags_url: https://api.github.com/repos/octocat/Hello-World-Template/git/tags{/sha} git_url: git:github.com/octocat/Hello-World-Template.git issue_comment_url: https://api.github.com/repos/octocat/Hello-World-Template/issues/comments{/number} issue_events_url: https://api.github.com/repos/octocat/Hello-World-Template/issues/events{/number} issues_url: https://api.github.com/repos/octocat/Hello-World-Template/issues{/number} keys_url: https://api.github.com/repos/octocat/Hello-World-Template/keys{/key_id} labels_url: https://api.github.com/repos/octocat/Hello-World-Template/labels{/name} languages_url: https://api.github.com/repos/octocat/Hello-World-Template/languages merges_url: https://api.github.com/repos/octocat/Hello-World-Template/merges milestones_url: https://api.github.com/repos/octocat/Hello-World-Template/milestones{/number} notifications_url: https://api.github.com/repos/octocat/Hello-World-Template/notifications{?since,all,participating} pulls_url: https://api.github.com/repos/octocat/Hello-World-Template/pulls{/number} releases_url: https://api.github.com/repos/octocat/Hello-World-Template/releases{/id} ssh_url: git@github.com:octocat/Hello-World-Template.git stargazers_url: https://api.github.com/repos/octocat/Hello-World-Template/stargazers statuses_url: https://api.github.com/repos/octocat/Hello-World-Template/statuses/{sha} subscribers_url: https://api.github.com/repos/octocat/Hello-World-Template/subscribers subscription_url: https://api.github.com/repos/octocat/Hello-World-Template/subscription tags_url: https://api.github.com/repos/octocat/Hello-World-Template/tags teams_url: https://api.github.com/repos/octocat/Hello-World-Template/teams trees_url: https://api.github.com/repos/octocat/Hello-World-Template/git/trees{/sha} clone_url: https://github.com/octocat/Hello-World-Template.git mirror_url: git:git.example.com/octocat/Hello-World-Template hooks_url: https://api.github.com/repos/octocat/Hello-World-Template/hooks svn_url: https://svn.github.com/octocat/Hello-World-Template homepage: https://github.com forks: 9 forks_count: 9 stargazers_count: 80 watchers_count: 80 watchers: 80 size: 108 default_branch: master open_issues: 0 open_issues_count: 0 is_template: true license: key: mit name: MIT License url: https://api.github.com/licenses/mit spdx_id: MIT node_id: MDc6TGljZW5zZW1pdA== html_url: https://api.github.com/licenses/mit topics: - octocat - atom - electron - api has_issues: true has_projects: true has_wiki: true has_pages: false has_downloads: true archived: false disabled: false visibility: public pushed_at: '2011-01-26T19:06:43Z' created_at: '2011-01-26T19:01:12Z' updated_at: '2011-01-26T19:14:43Z' permissions: admin: false push: false pull: true allow_rebase_merge: true temp_clone_token: ABTLWHOULUVAXGTRYU7OC2876QJ2O allow_squash_merge: true delete_branch_on_merge: true allow_merge_commit: true subscribers_count: 42 network_count: 0 temp_clone_token: ABTLWHOULUVAXGTRYU7OC2876QJ2O allow_squash_merge: true delete_branch_on_merge: true allow_merge_commit: true subscribers_count: 42 network_count: 0 license: key: mit name: MIT License spdx_id: MIT url: https://api.github.com/licenses/mit node_id: MDc6TGljZW5zZW1pdA== organization: login: octocat id: 1 node_id: MDQ6VXNlcjE= avatar_url: https://github.com/images/error/octocat_happy.gif gravatar_id: '' url: https://api.github.com/users/octocat html_url: https://github.com/octocat followers_url: https://api.github.com/users/octocat/followers following_url: https://api.github.com/users/octocat/following{/other_user} gists_url: https://api.github.com/users/octocat/gists{/gist_id} starred_url: https://api.github.com/users/octocat/starred{/owner}{/repo} subscriptions_url: https://api.github.com/users/octocat/subscriptions organizations_url: https://api.github.com/users/octocat/orgs repos_url: https://api.github.com/users/octocat/repos events_url: https://api.github.com/users/octocat/events{/privacy} received_events_url: https://api.github.com/users/octocat/received_events type: Organization site_admin: false parent: id: 1296269 node_id: MDEwOlJlcG9zaXRvcnkxMjk2MjY5 name: Hello-World full_name: octocat/Hello-World owner: login: octocat id: 1 node_id: MDQ6VXNlcjE= avatar_url: https://github.com/images/error/octocat_happy.gif gravatar_id: '' url: https://api.github.com/users/octocat html_url: https://github.com/octocat followers_url: https://api.github.com/users/octocat/followers following_url: https://api.github.com/users/octocat/following{/other_user} gists_url: https://api.github.com/users/octocat/gists{/gist_id} starred_url: https://api.github.com/users/octocat/starred{/owner}{/repo} subscriptions_url: https://api.github.com/users/octocat/subscriptions organizations_url: https://api.github.com/users/octocat/orgs repos_url: https://api.github.com/users/octocat/repos events_url: https://api.github.com/users/octocat/events{/privacy} received_events_url: https://api.github.com/users/octocat/received_events type: User site_admin: false private: false html_url: https://github.com/octocat/Hello-World description: This your first repo! fork: false url: https://api.github.com/repos/octocat/Hello-World archive_url: https://api.github.com/repos/octocat/Hello-World/{archive_format}{/ref} assignees_url: https://api.github.com/repos/octocat/Hello-World/assignees{/user} blobs_url: https://api.github.com/repos/octocat/Hello-World/git/blobs{/sha} branches_url: https://api.github.com/repos/octocat/Hello-World/branches{/branch} collaborators_url: https://api.github.com/repos/octocat/Hello-World/collaborators{/collaborator} comments_url: https://api.github.com/repos/octocat/Hello-World/comments{/number} commits_url: https://api.github.com/repos/octocat/Hello-World/commits{/sha} compare_url: https://api.github.com/repos/octocat/Hello-World/compare/{base}...{head} contents_url: https://api.github.com/repos/octocat/Hello-World/contents/{+path} contributors_url: https://api.github.com/repos/octocat/Hello-World/contributors deployments_url: https://api.github.com/repos/octocat/Hello-World/deployments downloads_url: https://api.github.com/repos/octocat/Hello-World/downloads events_url: https://api.github.com/repos/octocat/Hello-World/events forks_url: https://api.github.com/repos/octocat/Hello-World/forks git_commits_url: https://api.github.com/repos/octocat/Hello-World/git/commits{/sha} git_refs_url: https://api.github.com/repos/octocat/Hello-World/git/refs{/sha} git_tags_url: https://api.github.com/repos/octocat/Hello-World/git/tags{/sha} git_url: git:github.com/octocat/Hello-World.git issue_comment_url: https://api.github.com/repos/octocat/Hello-World/issues/comments{/number} issue_events_url: https://api.github.com/repos/octocat/Hello-World/issues/events{/number} issues_url: https://api.github.com/repos/octocat/Hello-World/issues{/number} keys_url: https://api.github.com/repos/octocat/Hello-World/keys{/key_id} labels_url: https://api.github.com/repos/octocat/Hello-World/labels{/name} languages_url: https://api.github.com/repos/octocat/Hello-World/languages merges_url: https://api.github.com/repos/octocat/Hello-World/merges milestones_url: https://api.github.com/repos/octocat/Hello-World/milestones{/number} notifications_url: https://api.github.com/repos/octocat/Hello-World/notifications{?since,all,participating} pulls_url: https://api.github.com/repos/octocat/Hello-World/pulls{/number} releases_url: https://api.github.com/repos/octocat/Hello-World/releases{/id} ssh_url: git@github.com:octocat/Hello-World.git stargazers_url: https://api.github.com/repos/octocat/Hello-World/stargazers statuses_url: https://api.github.com/repos/octocat/Hello-World/statuses/{sha} subscribers_url: https://api.github.com/repos/octocat/Hello-World/subscribers subscription_url: https://api.github.com/repos/octocat/Hello-World/subscription tags_url: https://api.github.com/repos/octocat/Hello-World/tags teams_url: https://api.github.com/repos/octocat/Hello-World/teams trees_url: https://api.github.com/repos/octocat/Hello-World/git/trees{/sha} clone_url: https://github.com/octocat/Hello-World.git mirror_url: git:git.example.com/octocat/Hello-World hooks_url: https://api.github.com/repos/octocat/Hello-World/hooks svn_url: https://svn.github.com/octocat/Hello-World homepage: https://github.com forks_count: 9 stargazers_count: 80 watchers_count: 80 size: 108 default_branch: master open_issues_count: 0 is_template: true topics: - octocat - atom - electron - api has_issues: true has_projects: true has_wiki: true has_pages: false has_downloads: true archived: false disabled: false visibility: public pushed_at: '2011-01-26T19:06:43Z' created_at: '2011-01-26T19:01:12Z' updated_at: '2011-01-26T19:14:43Z' permissions: admin: false push: false pull: true allow_rebase_merge: true temp_clone_token: ABTLWHOULUVAXGTRYU7OC2876QJ2O allow_squash_merge: true delete_branch_on_merge: true allow_merge_commit: true subscribers_count: 42 network_count: 0 license: key: mit name: MIT License url: https://api.github.com/licenses/mit spdx_id: MIT node_id: MDc6TGljZW5zZW1pdA== html_url: https://api.github.com/licenses/mit forks: 1 open_issues: 1 watchers: 1 source: id: 1296269 node_id: MDEwOlJlcG9zaXRvcnkxMjk2MjY5 name: Hello-World full_name: octocat/Hello-World owner: login: octocat id: 1 node_id: MDQ6VXNlcjE= avatar_url: https://github.com/images/error/octocat_happy.gif gravatar_id: '' url: https://api.github.com/users/octocat html_url: https://github.com/octocat followers_url: https://api.github.com/users/octocat/followers following_url: https://api.github.com/users/octocat/following{/other_user} gists_url: https://api.github.com/users/octocat/gists{/gist_id} starred_url: https://api.github.com/users/octocat/starred{/owner}{/repo} subscriptions_url: https://api.github.com/users/octocat/subscriptions organizations_url: https://api.github.com/users/octocat/orgs repos_url: https://api.github.com/users/octocat/repos events_url: https://api.github.com/users/octocat/events{/privacy} received_events_url: https://api.github.com/users/octocat/received_events type: User site_admin: false private: false html_url: https://github.com/octocat/Hello-World description: This your first repo! fork: false url: https://api.github.com/repos/octocat/Hello-World archive_url: https://api.github.com/repos/octocat/Hello-World/{archive_format}{/ref} assignees_url: https://api.github.com/repos/octocat/Hello-World/assignees{/user} blobs_url: https://api.github.com/repos/octocat/Hello-World/git/blobs{/sha} branches_url: https://api.github.com/repos/octocat/Hello-World/branches{/branch} collaborators_url: https://api.github.com/repos/octocat/Hello-World/collaborators{/collaborator} comments_url: https://api.github.com/repos/octocat/Hello-World/comments{/number} commits_url: https://api.github.com/repos/octocat/Hello-World/commits{/sha} compare_url: https://api.github.com/repos/octocat/Hello-World/compare/{base}...{head} contents_url: https://api.github.com/repos/octocat/Hello-World/contents/{+path} contributors_url: https://api.github.com/repos/octocat/Hello-World/contributors deployments_url: https://api.github.com/repos/octocat/Hello-World/deployments downloads_url: https://api.github.com/repos/octocat/Hello-World/downloads events_url: https://api.github.com/repos/octocat/Hello-World/events forks_url: https://api.github.com/repos/octocat/Hello-World/forks git_commits_url: https://api.github.com/repos/octocat/Hello-World/git/commits{/sha} git_refs_url: https://api.github.com/repos/octocat/Hello-World/git/refs{/sha} git_tags_url: https://api.github.com/repos/octocat/Hello-World/git/tags{/sha} git_url: git:github.com/octocat/Hello-World.git issue_comment_url: https://api.github.com/repos/octocat/Hello-World/issues/comments{/number} issue_events_url: https://api.github.com/repos/octocat/Hello-World/issues/events{/number} issues_url: https://api.github.com/repos/octocat/Hello-World/issues{/number} keys_url: https://api.github.com/repos/octocat/Hello-World/keys{/key_id} labels_url: https://api.github.com/repos/octocat/Hello-World/labels{/name} languages_url: https://api.github.com/repos/octocat/Hello-World/languages merges_url: https://api.github.com/repos/octocat/Hello-World/merges milestones_url: https://api.github.com/repos/octocat/Hello-World/milestones{/number} notifications_url: https://api.github.com/repos/octocat/Hello-World/notifications{?since,all,participating} pulls_url: https://api.github.com/repos/octocat/Hello-World/pulls{/number} releases_url: https://api.github.com/repos/octocat/Hello-World/releases{/id} ssh_url: git@github.com:octocat/Hello-World.git stargazers_url: https://api.github.com/repos/octocat/Hello-World/stargazers statuses_url: https://api.github.com/repos/octocat/Hello-World/statuses/{sha} subscribers_url: https://api.github.com/repos/octocat/Hello-World/subscribers subscription_url: https://api.github.com/repos/octocat/Hello-World/subscription tags_url: https://api.github.com/repos/octocat/Hello-World/tags teams_url: https://api.github.com/repos/octocat/Hello-World/teams trees_url: https://api.github.com/repos/octocat/Hello-World/git/trees{/sha} clone_url: https://github.com/octocat/Hello-World.git mirror_url: git:git.example.com/octocat/Hello-World hooks_url: https://api.github.com/repos/octocat/Hello-World/hooks svn_url: https://svn.github.com/octocat/Hello-World homepage: https://github.com forks_count: 9 stargazers_count: 80 watchers_count: 80 size: 108 default_branch: master open_issues_count: 0 is_template: true topics: - octocat - atom - electron - api has_issues: true has_projects: true has_wiki: true has_pages: false has_downloads: true archived: false disabled: false visibility: public pushed_at: '2011-01-26T19:06:43Z' created_at: '2011-01-26T19:01:12Z' updated_at: '2011-01-26T19:14:43Z' permissions: admin: false push: false pull: true allow_rebase_merge: true temp_clone_token: ABTLWHOULUVAXGTRYU7OC2876QJ2O allow_squash_merge: true delete_branch_on_merge: true allow_merge_commit: true subscribers_count: 42 network_count: 0 license: key: mit name: MIT License url: https://api.github.com/licenses/mit spdx_id: MIT node_id: MDc6TGljZW5zZW1pdA== html_url: https://api.github.com/licenses/mit forks: 1 open_issues: 1 watchers: 1 full-repository-response-with-scarlet-witch-preview-media-type: summary: Response with scarlet-witch-preview media type value: id: 1296269 node_id: MDEwOlJlcG9zaXRvcnkxMjk2MjY5 name: Hello-World full_name: octocat/Hello-World owner: login: octocat id: 1 node_id: MDQ6VXNlcjE= avatar_url: https://github.com/images/error/octocat_happy.gif gravatar_id: '' url: https://api.github.com/users/octocat html_url: https://github.com/octocat followers_url: https://api.github.com/users/octocat/followers following_url: https://api.github.com/users/octocat/following{/other_user} gists_url: https://api.github.com/users/octocat/gists{/gist_id} starred_url: https://api.github.com/users/octocat/starred{/owner}{/repo} subscriptions_url: https://api.github.com/users/octocat/subscriptions organizations_url: https://api.github.com/users/octocat/orgs repos_url: https://api.github.com/users/octocat/repos events_url: https://api.github.com/users/octocat/events{/privacy} received_events_url: https://api.github.com/users/octocat/received_events type: User site_admin: false private: false html_url: https://github.com/octocat/Hello-World description: This your first repo! fork: false url: https://api.github.com/repos/octocat/Hello-World archive_url: https://api.github.com/repos/octocat/Hello-World/{archive_format}{/ref} assignees_url: https://api.github.com/repos/octocat/Hello-World/assignees{/user} blobs_url: https://api.github.com/repos/octocat/Hello-World/git/blobs{/sha} branches_url: https://api.github.com/repos/octocat/Hello-World/branches{/branch} collaborators_url: https://api.github.com/repos/octocat/Hello-World/collaborators{/collaborator} comments_url: https://api.github.com/repos/octocat/Hello-World/comments{/number} commits_url: https://api.github.com/repos/octocat/Hello-World/commits{/sha} compare_url: https://api.github.com/repos/octocat/Hello-World/compare/{base}...{head} contents_url: https://api.github.com/repos/octocat/Hello-World/contents/{+path} contributors_url: https://api.github.com/repos/octocat/Hello-World/contributors deployments_url: https://api.github.com/repos/octocat/Hello-World/deployments downloads_url: https://api.github.com/repos/octocat/Hello-World/downloads events_url: https://api.github.com/repos/octocat/Hello-World/events forks_url: https://api.github.com/repos/octocat/Hello-World/forks git_commits_url: https://api.github.com/repos/octocat/Hello-World/git/commits{/sha} git_refs_url: https://api.github.com/repos/octocat/Hello-World/git/refs{/sha} git_tags_url: https://api.github.com/repos/octocat/Hello-World/git/tags{/sha} git_url: git:github.com/octocat/Hello-World.git issue_comment_url: https://api.github.com/repos/octocat/Hello-World/issues/comments{/number} issue_events_url: https://api.github.com/repos/octocat/Hello-World/issues/events{/number} issues_url: https://api.github.com/repos/octocat/Hello-World/issues{/number} keys_url: https://api.github.com/repos/octocat/Hello-World/keys{/key_id} labels_url: https://api.github.com/repos/octocat/Hello-World/labels{/name} languages_url: https://api.github.com/repos/octocat/Hello-World/languages merges_url: https://api.github.com/repos/octocat/Hello-World/merges milestones_url: https://api.github.com/repos/octocat/Hello-World/milestones{/number} notifications_url: https://api.github.com/repos/octocat/Hello-World/notifications{?since,all,participating} pulls_url: https://api.github.com/repos/octocat/Hello-World/pulls{/number} releases_url: https://api.github.com/repos/octocat/Hello-World/releases{/id} ssh_url: git@github.com:octocat/Hello-World.git stargazers_url: https://api.github.com/repos/octocat/Hello-World/stargazers statuses_url: https://api.github.com/repos/octocat/Hello-World/statuses/{sha} subscribers_url: https://api.github.com/repos/octocat/Hello-World/subscribers subscription_url: https://api.github.com/repos/octocat/Hello-World/subscription tags_url: https://api.github.com/repos/octocat/Hello-World/tags teams_url: https://api.github.com/repos/octocat/Hello-World/teams trees_url: https://api.github.com/repos/octocat/Hello-World/git/trees{/sha} clone_url: https://github.com/octocat/Hello-World.git mirror_url: git:git.example.com/octocat/Hello-World hooks_url: https://api.github.com/repos/octocat/Hello-World/hooks svn_url: https://svn.github.com/octocat/Hello-World homepage: https://github.com forks_count: 9 forks: 9 stargazers_count: 80 watchers_count: 80 watchers: 80 size: 108 default_branch: master open_issues_count: 0 open_issues: 0 is_template: false topics: - octocat - atom - electron - api has_issues: true has_projects: true has_wiki: true has_pages: false has_downloads: true archived: false disabled: false visibility: public pushed_at: '2011-01-26T19:06:43Z' created_at: '2011-01-26T19:01:12Z' updated_at: '2011-01-26T19:14:43Z' permissions: pull: true push: false admin: false allow_rebase_merge: true template_repository: id: 1296269 node_id: MDEwOlJlcG9zaXRvcnkxMjk2MjY5 name: Hello-World-Template full_name: octocat/Hello-World-Template owner: login: octocat id: 1 node_id: MDQ6VXNlcjE= avatar_url: https://github.com/images/error/octocat_happy.gif gravatar_id: '' url: https://api.github.com/users/octocat html_url: https://github.com/octocat followers_url: https://api.github.com/users/octocat/followers following_url: https://api.github.com/users/octocat/following{/other_user} gists_url: https://api.github.com/users/octocat/gists{/gist_id} starred_url: https://api.github.com/users/octocat/starred{/owner}{/repo} subscriptions_url: https://api.github.com/users/octocat/subscriptions organizations_url: https://api.github.com/users/octocat/orgs repos_url: https://api.github.com/users/octocat/repos events_url: https://api.github.com/users/octocat/events{/privacy} received_events_url: https://api.github.com/users/octocat/received_events type: User site_admin: false private: false html_url: https://github.com/octocat/Hello-World-Template description: This your first repo! fork: false url: https://api.github.com/repos/octocat/Hello-World-Template archive_url: https://api.github.com/repos/octocat/Hello-World-Template/{archive_format}{/ref} assignees_url: https://api.github.com/repos/octocat/Hello-World-Template/assignees{/user} blobs_url: https://api.github.com/repos/octocat/Hello-World-Template/git/blobs{/sha} branches_url: https://api.github.com/repos/octocat/Hello-World-Template/branches{/branch} collaborators_url: https://api.github.com/repos/octocat/Hello-World-Template/collaborators{/collaborator} comments_url: https://api.github.com/repos/octocat/Hello-World-Template/comments{/number} commits_url: https://api.github.com/repos/octocat/Hello-World-Template/commits{/sha} compare_url: https://api.github.com/repos/octocat/Hello-World-Template/compare/{base}...{head} contents_url: https://api.github.com/repos/octocat/Hello-World-Template/contents/{+path} contributors_url: https://api.github.com/repos/octocat/Hello-World-Template/contributors deployments_url: https://api.github.com/repos/octocat/Hello-World-Template/deployments downloads_url: https://api.github.com/repos/octocat/Hello-World-Template/downloads events_url: https://api.github.com/repos/octocat/Hello-World-Template/events forks_url: https://api.github.com/repos/octocat/Hello-World-Template/forks git_commits_url: https://api.github.com/repos/octocat/Hello-World-Template/git/commits{/sha} git_refs_url: https://api.github.com/repos/octocat/Hello-World-Template/git/refs{/sha} git_tags_url: https://api.github.com/repos/octocat/Hello-World-Template/git/tags{/sha} git_url: git:github.com/octocat/Hello-World-Template.git issue_comment_url: https://api.github.com/repos/octocat/Hello-World-Template/issues/comments{/number} issue_events_url: https://api.github.com/repos/octocat/Hello-World-Template/issues/events{/number} issues_url: https://api.github.com/repos/octocat/Hello-World-Template/issues{/number} keys_url: https://api.github.com/repos/octocat/Hello-World-Template/keys{/key_id} labels_url: https://api.github.com/repos/octocat/Hello-World-Template/labels{/name} languages_url: https://api.github.com/repos/octocat/Hello-World-Template/languages merges_url: https://api.github.com/repos/octocat/Hello-World-Template/merges milestones_url: https://api.github.com/repos/octocat/Hello-World-Template/milestones{/number} notifications_url: https://api.github.com/repos/octocat/Hello-World-Template/notifications{?since,all,participating} pulls_url: https://api.github.com/repos/octocat/Hello-World-Template/pulls{/number} releases_url: https://api.github.com/repos/octocat/Hello-World-Template/releases{/id} ssh_url: git@github.com:octocat/Hello-World-Template.git stargazers_url: https://api.github.com/repos/octocat/Hello-World-Template/stargazers statuses_url: https://api.github.com/repos/octocat/Hello-World-Template/statuses/{sha} subscribers_url: https://api.github.com/repos/octocat/Hello-World-Template/subscribers subscription_url: https://api.github.com/repos/octocat/Hello-World-Template/subscription tags_url: https://api.github.com/repos/octocat/Hello-World-Template/tags teams_url: https://api.github.com/repos/octocat/Hello-World-Template/teams trees_url: https://api.github.com/repos/octocat/Hello-World-Template/git/trees{/sha} clone_url: https://github.com/octocat/Hello-World-Template.git mirror_url: git:git.example.com/octocat/Hello-World-Template hooks_url: https://api.github.com/repos/octocat/Hello-World-Template/hooks svn_url: https://svn.github.com/octocat/Hello-World-Template homepage: https://github.com forks: 9 forks_count: 9 stargazers_count: 80 watchers_count: 80 watchers: 80 size: 108 default_branch: master open_issues: 0 open_issues_count: 0 is_template: true license: key: mit name: MIT License url: https://api.github.com/licenses/mit spdx_id: MIT node_id: MDc6TGljZW5zZW1pdA== html_url: https://api.github.com/licenses/mit topics: - octocat - atom - electron - api has_issues: true has_projects: true has_wiki: true has_pages: false has_downloads: true archived: false disabled: false visibility: public pushed_at: '2011-01-26T19:06:43Z' created_at: '2011-01-26T19:01:12Z' updated_at: '2011-01-26T19:14:43Z' permissions: admin: false push: false pull: true allow_rebase_merge: true temp_clone_token: ABTLWHOULUVAXGTRYU7OC2876QJ2O allow_squash_merge: true delete_branch_on_merge: true allow_merge_commit: true subscribers_count: 42 network_count: 0 temp_clone_token: ABTLWHOULUVAXGTRYU7OC2876QJ2O allow_squash_merge: true delete_branch_on_merge: true allow_merge_commit: true subscribers_count: 42 network_count: 0 license: key: mit name: MIT License spdx_id: MIT url: https://api.github.com/licenses/mit node_id: MDc6TGljZW5zZW1pdA== organization: login: octocat id: 1 node_id: MDQ6VXNlcjE= avatar_url: https://github.com/images/error/octocat_happy.gif gravatar_id: '' url: https://api.github.com/users/octocat html_url: https://github.com/octocat followers_url: https://api.github.com/users/octocat/followers following_url: https://api.github.com/users/octocat/following{/other_user} gists_url: https://api.github.com/users/octocat/gists{/gist_id} starred_url: https://api.github.com/users/octocat/starred{/owner}{/repo} subscriptions_url: https://api.github.com/users/octocat/subscriptions organizations_url: https://api.github.com/users/octocat/orgs repos_url: https://api.github.com/users/octocat/repos events_url: https://api.github.com/users/octocat/events{/privacy} received_events_url: https://api.github.com/users/octocat/received_events type: Organization site_admin: false parent: id: 1296269 node_id: MDEwOlJlcG9zaXRvcnkxMjk2MjY5 name: Hello-World full_name: octocat/Hello-World owner: login: octocat id: 1 node_id: MDQ6VXNlcjE= avatar_url: https://github.com/images/error/octocat_happy.gif gravatar_id: '' url: https://api.github.com/users/octocat html_url: https://github.com/octocat followers_url: https://api.github.com/users/octocat/followers following_url: https://api.github.com/users/octocat/following{/other_user} gists_url: https://api.github.com/users/octocat/gists{/gist_id} starred_url: https://api.github.com/users/octocat/starred{/owner}{/repo} subscriptions_url: https://api.github.com/users/octocat/subscriptions organizations_url: https://api.github.com/users/octocat/orgs repos_url: https://api.github.com/users/octocat/repos events_url: https://api.github.com/users/octocat/events{/privacy} received_events_url: https://api.github.com/users/octocat/received_events type: User site_admin: false private: false html_url: https://github.com/octocat/Hello-World description: This your first repo! fork: false url: https://api.github.com/repos/octocat/Hello-World archive_url: https://api.github.com/repos/octocat/Hello-World/{archive_format}{/ref} assignees_url: https://api.github.com/repos/octocat/Hello-World/assignees{/user} blobs_url: https://api.github.com/repos/octocat/Hello-World/git/blobs{/sha} branches_url: https://api.github.com/repos/octocat/Hello-World/branches{/branch} collaborators_url: https://api.github.com/repos/octocat/Hello-World/collaborators{/collaborator} comments_url: https://api.github.com/repos/octocat/Hello-World/comments{/number} commits_url: https://api.github.com/repos/octocat/Hello-World/commits{/sha} compare_url: https://api.github.com/repos/octocat/Hello-World/compare/{base}...{head} contents_url: https://api.github.com/repos/octocat/Hello-World/contents/{+path} contributors_url: https://api.github.com/repos/octocat/Hello-World/contributors deployments_url: https://api.github.com/repos/octocat/Hello-World/deployments downloads_url: https://api.github.com/repos/octocat/Hello-World/downloads events_url: https://api.github.com/repos/octocat/Hello-World/events forks_url: https://api.github.com/repos/octocat/Hello-World/forks git_commits_url: https://api.github.com/repos/octocat/Hello-World/git/commits{/sha} git_refs_url: https://api.github.com/repos/octocat/Hello-World/git/refs{/sha} git_tags_url: https://api.github.com/repos/octocat/Hello-World/git/tags{/sha} git_url: git:github.com/octocat/Hello-World.git issue_comment_url: https://api.github.com/repos/octocat/Hello-World/issues/comments{/number} issue_events_url: https://api.github.com/repos/octocat/Hello-World/issues/events{/number} issues_url: https://api.github.com/repos/octocat/Hello-World/issues{/number} keys_url: https://api.github.com/repos/octocat/Hello-World/keys{/key_id} labels_url: https://api.github.com/repos/octocat/Hello-World/labels{/name} languages_url: https://api.github.com/repos/octocat/Hello-World/languages merges_url: https://api.github.com/repos/octocat/Hello-World/merges milestones_url: https://api.github.com/repos/octocat/Hello-World/milestones{/number} notifications_url: https://api.github.com/repos/octocat/Hello-World/notifications{?since,all,participating} pulls_url: https://api.github.com/repos/octocat/Hello-World/pulls{/number} releases_url: https://api.github.com/repos/octocat/Hello-World/releases{/id} ssh_url: git@github.com:octocat/Hello-World.git stargazers_url: https://api.github.com/repos/octocat/Hello-World/stargazers statuses_url: https://api.github.com/repos/octocat/Hello-World/statuses/{sha} subscribers_url: https://api.github.com/repos/octocat/Hello-World/subscribers subscription_url: https://api.github.com/repos/octocat/Hello-World/subscription tags_url: https://api.github.com/repos/octocat/Hello-World/tags teams_url: https://api.github.com/repos/octocat/Hello-World/teams trees_url: https://api.github.com/repos/octocat/Hello-World/git/trees{/sha} clone_url: https://github.com/octocat/Hello-World.git mirror_url: git:git.example.com/octocat/Hello-World hooks_url: https://api.github.com/repos/octocat/Hello-World/hooks svn_url: https://svn.github.com/octocat/Hello-World homepage: https://github.com forks_count: 9 stargazers_count: 80 watchers_count: 80 size: 108 default_branch: master open_issues_count: 0 is_template: true topics: - octocat - atom - electron - api has_issues: true has_projects: true has_wiki: true has_pages: false has_downloads: true archived: false disabled: false visibility: public pushed_at: '2011-01-26T19:06:43Z' created_at: '2011-01-26T19:01:12Z' updated_at: '2011-01-26T19:14:43Z' permissions: admin: false push: false pull: true allow_rebase_merge: true temp_clone_token: ABTLWHOULUVAXGTRYU7OC2876QJ2O allow_squash_merge: true delete_branch_on_merge: true allow_merge_commit: true subscribers_count: 42 network_count: 0 license: key: mit name: MIT License url: https://api.github.com/licenses/mit spdx_id: MIT node_id: MDc6TGljZW5zZW1pdA== html_url: https://api.github.com/licenses/mit forks: 1 open_issues: 1 watchers: 1 source: id: 1296269 node_id: MDEwOlJlcG9zaXRvcnkxMjk2MjY5 name: Hello-World full_name: octocat/Hello-World owner: login: octocat id: 1 node_id: MDQ6VXNlcjE= avatar_url: https://github.com/images/error/octocat_happy.gif gravatar_id: '' url: https://api.github.com/users/octocat html_url: https://github.com/octocat followers_url: https://api.github.com/users/octocat/followers following_url: https://api.github.com/users/octocat/following{/other_user} gists_url: https://api.github.com/users/octocat/gists{/gist_id} starred_url: https://api.github.com/users/octocat/starred{/owner}{/repo} subscriptions_url: https://api.github.com/users/octocat/subscriptions organizations_url: https://api.github.com/users/octocat/orgs repos_url: https://api.github.com/users/octocat/repos events_url: https://api.github.com/users/octocat/events{/privacy} received_events_url: https://api.github.com/users/octocat/received_events type: User site_admin: false private: false html_url: https://github.com/octocat/Hello-World description: This your first repo! fork: false url: https://api.github.com/repos/octocat/Hello-World archive_url: https://api.github.com/repos/octocat/Hello-World/{archive_format}{/ref} assignees_url: https://api.github.com/repos/octocat/Hello-World/assignees{/user} blobs_url: https://api.github.com/repos/octocat/Hello-World/git/blobs{/sha} branches_url: https://api.github.com/repos/octocat/Hello-World/branches{/branch} collaborators_url: https://api.github.com/repos/octocat/Hello-World/collaborators{/collaborator} comments_url: https://api.github.com/repos/octocat/Hello-World/comments{/number} commits_url: https://api.github.com/repos/octocat/Hello-World/commits{/sha} compare_url: https://api.github.com/repos/octocat/Hello-World/compare/{base}...{head} contents_url: https://api.github.com/repos/octocat/Hello-World/contents/{+path} contributors_url: https://api.github.com/repos/octocat/Hello-World/contributors deployments_url: https://api.github.com/repos/octocat/Hello-World/deployments downloads_url: https://api.github.com/repos/octocat/Hello-World/downloads events_url: https://api.github.com/repos/octocat/Hello-World/events forks_url: https://api.github.com/repos/octocat/Hello-World/forks git_commits_url: https://api.github.com/repos/octocat/Hello-World/git/commits{/sha} git_refs_url: https://api.github.com/repos/octocat/Hello-World/git/refs{/sha} git_tags_url: https://api.github.com/repos/octocat/Hello-World/git/tags{/sha} git_url: git:github.com/octocat/Hello-World.git issue_comment_url: https://api.github.com/repos/octocat/Hello-World/issues/comments{/number} issue_events_url: https://api.github.com/repos/octocat/Hello-World/issues/events{/number} issues_url: https://api.github.com/repos/octocat/Hello-World/issues{/number} keys_url: https://api.github.com/repos/octocat/Hello-World/keys{/key_id} labels_url: https://api.github.com/repos/octocat/Hello-World/labels{/name} languages_url: https://api.github.com/repos/octocat/Hello-World/languages merges_url: https://api.github.com/repos/octocat/Hello-World/merges milestones_url: https://api.github.com/repos/octocat/Hello-World/milestones{/number} notifications_url: https://api.github.com/repos/octocat/Hello-World/notifications{?since,all,participating} pulls_url: https://api.github.com/repos/octocat/Hello-World/pulls{/number} releases_url: https://api.github.com/repos/octocat/Hello-World/releases{/id} ssh_url: git@github.com:octocat/Hello-World.git stargazers_url: https://api.github.com/repos/octocat/Hello-World/stargazers statuses_url: https://api.github.com/repos/octocat/Hello-World/statuses/{sha} subscribers_url: https://api.github.com/repos/octocat/Hello-World/subscribers subscription_url: https://api.github.com/repos/octocat/Hello-World/subscription tags_url: https://api.github.com/repos/octocat/Hello-World/tags teams_url: https://api.github.com/repos/octocat/Hello-World/teams trees_url: https://api.github.com/repos/octocat/Hello-World/git/trees{/sha} clone_url: https://github.com/octocat/Hello-World.git mirror_url: git:git.example.com/octocat/Hello-World hooks_url: https://api.github.com/repos/octocat/Hello-World/hooks svn_url: https://svn.github.com/octocat/Hello-World homepage: https://github.com forks_count: 9 stargazers_count: 80 watchers_count: 80 size: 108 default_branch: master open_issues_count: 0 is_template: true topics: - octocat - atom - electron - api has_issues: true has_projects: true has_wiki: true has_pages: false has_downloads: true archived: false disabled: false visibility: public pushed_at: '2011-01-26T19:06:43Z' created_at: '2011-01-26T19:01:12Z' updated_at: '2011-01-26T19:14:43Z' permissions: admin: false push: false pull: true allow_rebase_merge: true temp_clone_token: ABTLWHOULUVAXGTRYU7OC2876QJ2O allow_squash_merge: true delete_branch_on_merge: true allow_merge_commit: true subscribers_count: 42 network_count: 0 license: key: mit name: MIT License url: https://api.github.com/licenses/mit spdx_id: MIT node_id: MDc6TGljZW5zZW1pdA== html_url: https://api.github.com/licenses/mit forks: 1 open_issues: 1 watchers: 1 code_of_conduct: key: other name: Other html_url: https://github.com/github/docs/blob/main/CODE_OF_CONDUCT.md url: https://api.github.com/repos/github/docs/community/code_of_conduct full-repository: value: id: 1296269 node_id: MDEwOlJlcG9zaXRvcnkxMjk2MjY5 name: Hello-World full_name: octocat/Hello-World owner: login: octocat id: 1 node_id: MDQ6VXNlcjE= avatar_url: https://github.com/images/error/octocat_happy.gif gravatar_id: '' url: https://api.github.com/users/octocat html_url: https://github.com/octocat followers_url: https://api.github.com/users/octocat/followers following_url: https://api.github.com/users/octocat/following{/other_user} gists_url: https://api.github.com/users/octocat/gists{/gist_id} starred_url: https://api.github.com/users/octocat/starred{/owner}{/repo} subscriptions_url: https://api.github.com/users/octocat/subscriptions organizations_url: https://api.github.com/users/octocat/orgs repos_url: https://api.github.com/users/octocat/repos events_url: https://api.github.com/users/octocat/events{/privacy} received_events_url: https://api.github.com/users/octocat/received_events type: User site_admin: false private: false html_url: https://github.com/octocat/Hello-World description: This your first repo! fork: false url: https://api.github.com/repos/octocat/Hello-World archive_url: https://api.github.com/repos/octocat/Hello-World/{archive_format}{/ref} assignees_url: https://api.github.com/repos/octocat/Hello-World/assignees{/user} blobs_url: https://api.github.com/repos/octocat/Hello-World/git/blobs{/sha} branches_url: https://api.github.com/repos/octocat/Hello-World/branches{/branch} collaborators_url: https://api.github.com/repos/octocat/Hello-World/collaborators{/collaborator} comments_url: https://api.github.com/repos/octocat/Hello-World/comments{/number} commits_url: https://api.github.com/repos/octocat/Hello-World/commits{/sha} compare_url: https://api.github.com/repos/octocat/Hello-World/compare/{base}...{head} contents_url: https://api.github.com/repos/octocat/Hello-World/contents/{+path} contributors_url: https://api.github.com/repos/octocat/Hello-World/contributors deployments_url: https://api.github.com/repos/octocat/Hello-World/deployments downloads_url: https://api.github.com/repos/octocat/Hello-World/downloads events_url: https://api.github.com/repos/octocat/Hello-World/events forks_url: https://api.github.com/repos/octocat/Hello-World/forks git_commits_url: https://api.github.com/repos/octocat/Hello-World/git/commits{/sha} git_refs_url: https://api.github.com/repos/octocat/Hello-World/git/refs{/sha} git_tags_url: https://api.github.com/repos/octocat/Hello-World/git/tags{/sha} git_url: git:github.com/octocat/Hello-World.git issue_comment_url: https://api.github.com/repos/octocat/Hello-World/issues/comments{/number} issue_events_url: https://api.github.com/repos/octocat/Hello-World/issues/events{/number} issues_url: https://api.github.com/repos/octocat/Hello-World/issues{/number} keys_url: https://api.github.com/repos/octocat/Hello-World/keys{/key_id} labels_url: https://api.github.com/repos/octocat/Hello-World/labels{/name} languages_url: https://api.github.com/repos/octocat/Hello-World/languages merges_url: https://api.github.com/repos/octocat/Hello-World/merges milestones_url: https://api.github.com/repos/octocat/Hello-World/milestones{/number} notifications_url: https://api.github.com/repos/octocat/Hello-World/notifications{?since,all,participating} pulls_url: https://api.github.com/repos/octocat/Hello-World/pulls{/number} releases_url: https://api.github.com/repos/octocat/Hello-World/releases{/id} ssh_url: git@github.com:octocat/Hello-World.git stargazers_url: https://api.github.com/repos/octocat/Hello-World/stargazers statuses_url: https://api.github.com/repos/octocat/Hello-World/statuses/{sha} subscribers_url: https://api.github.com/repos/octocat/Hello-World/subscribers subscription_url: https://api.github.com/repos/octocat/Hello-World/subscription tags_url: https://api.github.com/repos/octocat/Hello-World/tags teams_url: https://api.github.com/repos/octocat/Hello-World/teams trees_url: https://api.github.com/repos/octocat/Hello-World/git/trees{/sha} clone_url: https://github.com/octocat/Hello-World.git mirror_url: git:git.example.com/octocat/Hello-World hooks_url: https://api.github.com/repos/octocat/Hello-World/hooks svn_url: https://svn.github.com/octocat/Hello-World homepage: https://github.com license: key: mit name: MIT License url: https://api.github.com/licenses/mit spdx_id: MIT node_id: MDc6TGljZW5zZW1pdA== html_url: https://github.com/licenses/mit forks_count: 9 forks: 9 stargazers_count: 80 watchers_count: 80 watchers: 80 size: 108 default_branch: master open_issues_count: 0 open_issues: 0 is_template: false topics: - octocat - atom - electron - api has_issues: true has_projects: true has_wiki: true has_pages: false has_downloads: true archived: false disabled: false visibility: public pushed_at: '2011-01-26T19:06:43Z' created_at: '2011-01-26T19:01:12Z' updated_at: '2011-01-26T19:14:43Z' permissions: pull: true push: false admin: false allow_rebase_merge: true template_repository: id: 1296269 node_id: MDEwOlJlcG9zaXRvcnkxMjk2MjY5 name: Hello-World-Template full_name: octocat/Hello-World-Template owner: login: octocat id: 1 node_id: MDQ6VXNlcjE= avatar_url: https://github.com/images/error/octocat_happy.gif gravatar_id: '' url: https://api.github.com/users/octocat html_url: https://github.com/octocat followers_url: https://api.github.com/users/octocat/followers following_url: https://api.github.com/users/octocat/following{/other_user} gists_url: https://api.github.com/users/octocat/gists{/gist_id} starred_url: https://api.github.com/users/octocat/starred{/owner}{/repo} subscriptions_url: https://api.github.com/users/octocat/subscriptions organizations_url: https://api.github.com/users/octocat/orgs repos_url: https://api.github.com/users/octocat/repos events_url: https://api.github.com/users/octocat/events{/privacy} received_events_url: https://api.github.com/users/octocat/received_events type: User site_admin: false private: false html_url: https://github.com/octocat/Hello-World-Template description: This your first repo! fork: false url: https://api.github.com/repos/octocat/Hello-World-Template archive_url: https://api.github.com/repos/octocat/Hello-World-Template/{archive_format}{/ref} assignees_url: https://api.github.com/repos/octocat/Hello-World-Template/assignees{/user} blobs_url: https://api.github.com/repos/octocat/Hello-World-Template/git/blobs{/sha} branches_url: https://api.github.com/repos/octocat/Hello-World-Template/branches{/branch} collaborators_url: https://api.github.com/repos/octocat/Hello-World-Template/collaborators{/collaborator} comments_url: https://api.github.com/repos/octocat/Hello-World-Template/comments{/number} commits_url: https://api.github.com/repos/octocat/Hello-World-Template/commits{/sha} compare_url: https://api.github.com/repos/octocat/Hello-World-Template/compare/{base}...{head} contents_url: https://api.github.com/repos/octocat/Hello-World-Template/contents/{+path} contributors_url: https://api.github.com/repos/octocat/Hello-World-Template/contributors deployments_url: https://api.github.com/repos/octocat/Hello-World-Template/deployments downloads_url: https://api.github.com/repos/octocat/Hello-World-Template/downloads events_url: https://api.github.com/repos/octocat/Hello-World-Template/events forks_url: https://api.github.com/repos/octocat/Hello-World-Template/forks git_commits_url: https://api.github.com/repos/octocat/Hello-World-Template/git/commits{/sha} git_refs_url: https://api.github.com/repos/octocat/Hello-World-Template/git/refs{/sha} git_tags_url: https://api.github.com/repos/octocat/Hello-World-Template/git/tags{/sha} git_url: git:github.com/octocat/Hello-World-Template.git issue_comment_url: https://api.github.com/repos/octocat/Hello-World-Template/issues/comments{/number} issue_events_url: https://api.github.com/repos/octocat/Hello-World-Template/issues/events{/number} issues_url: https://api.github.com/repos/octocat/Hello-World-Template/issues{/number} keys_url: https://api.github.com/repos/octocat/Hello-World-Template/keys{/key_id} labels_url: https://api.github.com/repos/octocat/Hello-World-Template/labels{/name} languages_url: https://api.github.com/repos/octocat/Hello-World-Template/languages merges_url: https://api.github.com/repos/octocat/Hello-World-Template/merges milestones_url: https://api.github.com/repos/octocat/Hello-World-Template/milestones{/number} notifications_url: https://api.github.com/repos/octocat/Hello-World-Template/notifications{?since,all,participating} pulls_url: https://api.github.com/repos/octocat/Hello-World-Template/pulls{/number} releases_url: https://api.github.com/repos/octocat/Hello-World-Template/releases{/id} ssh_url: git@github.com:octocat/Hello-World-Template.git stargazers_url: https://api.github.com/repos/octocat/Hello-World-Template/stargazers statuses_url: https://api.github.com/repos/octocat/Hello-World-Template/statuses/{sha} subscribers_url: https://api.github.com/repos/octocat/Hello-World-Template/subscribers subscription_url: https://api.github.com/repos/octocat/Hello-World-Template/subscription tags_url: https://api.github.com/repos/octocat/Hello-World-Template/tags teams_url: https://api.github.com/repos/octocat/Hello-World-Template/teams trees_url: https://api.github.com/repos/octocat/Hello-World-Template/git/trees{/sha} clone_url: https://github.com/octocat/Hello-World-Template.git mirror_url: git:git.example.com/octocat/Hello-World-Template hooks_url: https://api.github.com/repos/octocat/Hello-World-Template/hooks svn_url: https://svn.github.com/octocat/Hello-World-Template homepage: https://github.com forks: 9 forks_count: 9 stargazers_count: 80 watchers_count: 80 watchers: 80 size: 108 default_branch: master open_issues: 0 open_issues_count: 0 is_template: true license: key: mit name: MIT License url: https://api.github.com/licenses/mit spdx_id: MIT node_id: MDc6TGljZW5zZW1pdA== html_url: https://api.github.com/licenses/mit topics: - octocat - atom - electron - api has_issues: true has_projects: true has_wiki: true has_pages: false has_downloads: true archived: false disabled: false visibility: public pushed_at: '2011-01-26T19:06:43Z' created_at: '2011-01-26T19:01:12Z' updated_at: '2011-01-26T19:14:43Z' permissions: admin: false push: false pull: true allow_rebase_merge: true temp_clone_token: ABTLWHOULUVAXGTRYU7OC2876QJ2O allow_squash_merge: true delete_branch_on_merge: true allow_merge_commit: true subscribers_count: 42 network_count: 0 temp_clone_token: ABTLWHOULUVAXGTRYU7OC2876QJ2O allow_squash_merge: true delete_branch_on_merge: true allow_merge_commit: true allow_forking: true subscribers_count: 42 network_count: 0 organization: login: octocat id: 1 node_id: MDQ6VXNlcjE= avatar_url: https://github.com/images/error/octocat_happy.gif gravatar_id: '' url: https://api.github.com/users/octocat html_url: https://github.com/octocat followers_url: https://api.github.com/users/octocat/followers following_url: https://api.github.com/users/octocat/following{/other_user} gists_url: https://api.github.com/users/octocat/gists{/gist_id} starred_url: https://api.github.com/users/octocat/starred{/owner}{/repo} subscriptions_url: https://api.github.com/users/octocat/subscriptions organizations_url: https://api.github.com/users/octocat/orgs repos_url: https://api.github.com/users/octocat/repos events_url: https://api.github.com/users/octocat/events{/privacy} received_events_url: https://api.github.com/users/octocat/received_events type: Organization site_admin: false parent: id: 1296269 node_id: MDEwOlJlcG9zaXRvcnkxMjk2MjY5 name: Hello-World full_name: octocat/Hello-World owner: login: octocat id: 1 node_id: MDQ6VXNlcjE= avatar_url: https://github.com/images/error/octocat_happy.gif gravatar_id: '' url: https://api.github.com/users/octocat html_url: https://github.com/octocat followers_url: https://api.github.com/users/octocat/followers following_url: https://api.github.com/users/octocat/following{/other_user} gists_url: https://api.github.com/users/octocat/gists{/gist_id} starred_url: https://api.github.com/users/octocat/starred{/owner}{/repo} subscriptions_url: https://api.github.com/users/octocat/subscriptions organizations_url: https://api.github.com/users/octocat/orgs repos_url: https://api.github.com/users/octocat/repos events_url: https://api.github.com/users/octocat/events{/privacy} received_events_url: https://api.github.com/users/octocat/received_events type: User site_admin: false private: false html_url: https://github.com/octocat/Hello-World description: This your first repo! fork: false url: https://api.github.com/repos/octocat/Hello-World archive_url: https://api.github.com/repos/octocat/Hello-World/{archive_format}{/ref} assignees_url: https://api.github.com/repos/octocat/Hello-World/assignees{/user} blobs_url: https://api.github.com/repos/octocat/Hello-World/git/blobs{/sha} branches_url: https://api.github.com/repos/octocat/Hello-World/branches{/branch} collaborators_url: https://api.github.com/repos/octocat/Hello-World/collaborators{/collaborator} comments_url: https://api.github.com/repos/octocat/Hello-World/comments{/number} commits_url: https://api.github.com/repos/octocat/Hello-World/commits{/sha} compare_url: https://api.github.com/repos/octocat/Hello-World/compare/{base}...{head} contents_url: https://api.github.com/repos/octocat/Hello-World/contents/{+path} contributors_url: https://api.github.com/repos/octocat/Hello-World/contributors deployments_url: https://api.github.com/repos/octocat/Hello-World/deployments downloads_url: https://api.github.com/repos/octocat/Hello-World/downloads events_url: https://api.github.com/repos/octocat/Hello-World/events forks_url: https://api.github.com/repos/octocat/Hello-World/forks git_commits_url: https://api.github.com/repos/octocat/Hello-World/git/commits{/sha} git_refs_url: https://api.github.com/repos/octocat/Hello-World/git/refs{/sha} git_tags_url: https://api.github.com/repos/octocat/Hello-World/git/tags{/sha} git_url: git:github.com/octocat/Hello-World.git issue_comment_url: https://api.github.com/repos/octocat/Hello-World/issues/comments{/number} issue_events_url: https://api.github.com/repos/octocat/Hello-World/issues/events{/number} issues_url: https://api.github.com/repos/octocat/Hello-World/issues{/number} keys_url: https://api.github.com/repos/octocat/Hello-World/keys{/key_id} labels_url: https://api.github.com/repos/octocat/Hello-World/labels{/name} languages_url: https://api.github.com/repos/octocat/Hello-World/languages merges_url: https://api.github.com/repos/octocat/Hello-World/merges milestones_url: https://api.github.com/repos/octocat/Hello-World/milestones{/number} notifications_url: https://api.github.com/repos/octocat/Hello-World/notifications{?since,all,participating} pulls_url: https://api.github.com/repos/octocat/Hello-World/pulls{/number} releases_url: https://api.github.com/repos/octocat/Hello-World/releases{/id} ssh_url: git@github.com:octocat/Hello-World.git stargazers_url: https://api.github.com/repos/octocat/Hello-World/stargazers statuses_url: https://api.github.com/repos/octocat/Hello-World/statuses/{sha} subscribers_url: https://api.github.com/repos/octocat/Hello-World/subscribers subscription_url: https://api.github.com/repos/octocat/Hello-World/subscription tags_url: https://api.github.com/repos/octocat/Hello-World/tags teams_url: https://api.github.com/repos/octocat/Hello-World/teams trees_url: https://api.github.com/repos/octocat/Hello-World/git/trees{/sha} clone_url: https://github.com/octocat/Hello-World.git mirror_url: git:git.example.com/octocat/Hello-World hooks_url: https://api.github.com/repos/octocat/Hello-World/hooks svn_url: https://svn.github.com/octocat/Hello-World homepage: https://github.com forks_count: 9 stargazers_count: 80 watchers_count: 80 size: 108 default_branch: master open_issues_count: 0 is_template: true topics: - octocat - atom - electron - api has_issues: true has_projects: true has_wiki: true has_pages: false has_downloads: true archived: false disabled: false visibility: public pushed_at: '2011-01-26T19:06:43Z' created_at: '2011-01-26T19:01:12Z' updated_at: '2011-01-26T19:14:43Z' permissions: admin: false push: false pull: true allow_rebase_merge: true temp_clone_token: ABTLWHOULUVAXGTRYU7OC2876QJ2O allow_squash_merge: true delete_branch_on_merge: true allow_merge_commit: true subscribers_count: 42 network_count: 0 license: key: mit name: MIT License url: https://api.github.com/licenses/mit spdx_id: MIT node_id: MDc6TGljZW5zZW1pdA== html_url: https://api.github.com/licenses/mit forks: 1 open_issues: 1 watchers: 1 source: id: 1296269 node_id: MDEwOlJlcG9zaXRvcnkxMjk2MjY5 name: Hello-World full_name: octocat/Hello-World owner: login: octocat id: 1 node_id: MDQ6VXNlcjE= avatar_url: https://github.com/images/error/octocat_happy.gif gravatar_id: '' url: https://api.github.com/users/octocat html_url: https://github.com/octocat followers_url: https://api.github.com/users/octocat/followers following_url: https://api.github.com/users/octocat/following{/other_user} gists_url: https://api.github.com/users/octocat/gists{/gist_id} starred_url: https://api.github.com/users/octocat/starred{/owner}{/repo} subscriptions_url: https://api.github.com/users/octocat/subscriptions organizations_url: https://api.github.com/users/octocat/orgs repos_url: https://api.github.com/users/octocat/repos events_url: https://api.github.com/users/octocat/events{/privacy} received_events_url: https://api.github.com/users/octocat/received_events type: User site_admin: false private: false html_url: https://github.com/octocat/Hello-World description: This your first repo! fork: false url: https://api.github.com/repos/octocat/Hello-World archive_url: https://api.github.com/repos/octocat/Hello-World/{archive_format}{/ref} assignees_url: https://api.github.com/repos/octocat/Hello-World/assignees{/user} blobs_url: https://api.github.com/repos/octocat/Hello-World/git/blobs{/sha} branches_url: https://api.github.com/repos/octocat/Hello-World/branches{/branch} collaborators_url: https://api.github.com/repos/octocat/Hello-World/collaborators{/collaborator} comments_url: https://api.github.com/repos/octocat/Hello-World/comments{/number} commits_url: https://api.github.com/repos/octocat/Hello-World/commits{/sha} compare_url: https://api.github.com/repos/octocat/Hello-World/compare/{base}...{head} contents_url: https://api.github.com/repos/octocat/Hello-World/contents/{+path} contributors_url: https://api.github.com/repos/octocat/Hello-World/contributors deployments_url: https://api.github.com/repos/octocat/Hello-World/deployments downloads_url: https://api.github.com/repos/octocat/Hello-World/downloads events_url: https://api.github.com/repos/octocat/Hello-World/events forks_url: https://api.github.com/repos/octocat/Hello-World/forks git_commits_url: https://api.github.com/repos/octocat/Hello-World/git/commits{/sha} git_refs_url: https://api.github.com/repos/octocat/Hello-World/git/refs{/sha} git_tags_url: https://api.github.com/repos/octocat/Hello-World/git/tags{/sha} git_url: git:github.com/octocat/Hello-World.git issue_comment_url: https://api.github.com/repos/octocat/Hello-World/issues/comments{/number} issue_events_url: https://api.github.com/repos/octocat/Hello-World/issues/events{/number} issues_url: https://api.github.com/repos/octocat/Hello-World/issues{/number} keys_url: https://api.github.com/repos/octocat/Hello-World/keys{/key_id} labels_url: https://api.github.com/repos/octocat/Hello-World/labels{/name} languages_url: https://api.github.com/repos/octocat/Hello-World/languages merges_url: https://api.github.com/repos/octocat/Hello-World/merges milestones_url: https://api.github.com/repos/octocat/Hello-World/milestones{/number} notifications_url: https://api.github.com/repos/octocat/Hello-World/notifications{?since,all,participating} pulls_url: https://api.github.com/repos/octocat/Hello-World/pulls{/number} releases_url: https://api.github.com/repos/octocat/Hello-World/releases{/id} ssh_url: git@github.com:octocat/Hello-World.git stargazers_url: https://api.github.com/repos/octocat/Hello-World/stargazers statuses_url: https://api.github.com/repos/octocat/Hello-World/statuses/{sha} subscribers_url: https://api.github.com/repos/octocat/Hello-World/subscribers subscription_url: https://api.github.com/repos/octocat/Hello-World/subscription tags_url: https://api.github.com/repos/octocat/Hello-World/tags teams_url: https://api.github.com/repos/octocat/Hello-World/teams trees_url: https://api.github.com/repos/octocat/Hello-World/git/trees{/sha} clone_url: https://github.com/octocat/Hello-World.git mirror_url: git:git.example.com/octocat/Hello-World hooks_url: https://api.github.com/repos/octocat/Hello-World/hooks svn_url: https://svn.github.com/octocat/Hello-World homepage: https://github.com forks_count: 9 stargazers_count: 80 watchers_count: 80 size: 108 default_branch: master open_issues_count: 0 is_template: true topics: - octocat - atom - electron - api has_issues: true has_projects: true has_wiki: true has_pages: false has_downloads: true archived: false disabled: false visibility: public pushed_at: '2011-01-26T19:06:43Z' created_at: '2011-01-26T19:01:12Z' updated_at: '2011-01-26T19:14:43Z' permissions: admin: false push: false pull: true allow_rebase_merge: true temp_clone_token: ABTLWHOULUVAXGTRYU7OC2876QJ2O allow_squash_merge: true delete_branch_on_merge: true allow_merge_commit: true subscribers_count: 42 network_count: 0 license: key: mit name: MIT License url: https://api.github.com/licenses/mit spdx_id: MIT node_id: MDc6TGljZW5zZW1pdA== html_url: https://api.github.com/licenses/mit forks: 1 open_issues: 1 watchers: 1 artifact-paginated: value: total_count: 2 artifacts: - id: 11 node_id: MDg6QXJ0aWZhY3QxMQ== name: Rails size_in_bytes: 556 url: https://api.github.com/repos/octo-org/octo-docs/actions/artifacts/11 archive_download_url: https://api.github.com/repos/octo-org/octo-docs/actions/artifacts/11/zip expired: false created_at: '2020-01-10T14:59:22Z' expires_at: '2020-03-21T14:59:22Z' updated_at: '2020-02-21T14:59:22Z' - id: 13 node_id: MDg6QXJ0aWZhY3QxMw== name: '' size_in_bytes: 453 url: https://api.github.com/repos/octo-org/octo-docs/actions/artifacts/13 archive_download_url: https://api.github.com/repos/octo-org/octo-docs/actions/artifacts/13/zip expired: false created_at: '2020-01-10T14:59:22Z' expires_at: '2020-03-21T14:59:22Z' updated_at: '2020-02-21T14:59:22Z' artifact: value: id: 11 node_id: MDg6QXJ0aWZhY3QxMQ== name: Rails size_in_bytes: 556 url: https://api.github.com/repos/octo-org/octo-docs/actions/artifacts/11 archive_download_url: https://api.github.com/repos/octo-org/octo-docs/actions/artifacts/11/zip expired: false created_at: '2020-01-10T14:59:22Z' expires_at: '2020-01-21T14:59:22Z' updated_at: '2020-01-21T14:59:22Z' job: value: id: 399444496 run_id: 29679449 run_url: https://api.github.com/repos/octo-org/octo-repo/actions/runs/29679449 node_id: MDEyOldvcmtmbG93IEpvYjM5OTQ0NDQ5Ng== head_sha: f83a356604ae3c5d03e1b46ef4d1ca77d64a90b0 url: https://api.github.com/repos/octo-org/octo-repo/actions/jobs/399444496 html_url: https://github.com/octo-org/octo-repo/runs/399444496 status: completed conclusion: success started_at: '2020-01-20T17:42:40Z' completed_at: '2020-01-20T17:44:39Z' name: build steps: - name: Set up job status: completed conclusion: success number: 1 started_at: '2020-01-20T09:42:40.000-08:00' completed_at: '2020-01-20T09:42:41.000-08:00' - name: Run actions/checkout@v2 status: completed conclusion: success number: 2 started_at: '2020-01-20T09:42:41.000-08:00' completed_at: '2020-01-20T09:42:45.000-08:00' - name: Set up Ruby status: completed conclusion: success number: 3 started_at: '2020-01-20T09:42:45.000-08:00' completed_at: '2020-01-20T09:42:45.000-08:00' - name: Run actions/cache@v2 status: completed conclusion: success number: 4 started_at: '2020-01-20T09:42:45.000-08:00' completed_at: '2020-01-20T09:42:48.000-08:00' - name: Install Bundler status: completed conclusion: success number: 5 started_at: '2020-01-20T09:42:48.000-08:00' completed_at: '2020-01-20T09:42:52.000-08:00' - name: Install Gems status: completed conclusion: success number: 6 started_at: '2020-01-20T09:42:52.000-08:00' completed_at: '2020-01-20T09:42:53.000-08:00' - name: Run Tests status: completed conclusion: success number: 7 started_at: '2020-01-20T09:42:53.000-08:00' completed_at: '2020-01-20T09:42:59.000-08:00' - name: Deploy to Heroku status: completed conclusion: success number: 8 started_at: '2020-01-20T09:42:59.000-08:00' completed_at: '2020-01-20T09:44:39.000-08:00' - name: Post actions/cache@v2 status: completed conclusion: success number: 16 started_at: '2020-01-20T09:44:39.000-08:00' completed_at: '2020-01-20T09:44:39.000-08:00' - name: Complete job status: completed conclusion: success number: 17 started_at: '2020-01-20T09:44:39.000-08:00' completed_at: '2020-01-20T09:44:39.000-08:00' check_run_url: https://api.github.com/repos/octo-org/octo-repo/check-runs/399444496 actions-repository-permissions: value: enabled: true allowed_actions: selected selected_actions_url: https://api.github.com/repositories/42/actions/permissions/selected-actions workflow-run-paginated: value: total_count: 1 workflow_runs: - id: 30433642 name: Build node_id: MDEyOldvcmtmbG93IFJ1bjI2OTI4OQ== head_branch: master head_sha: acb5820ced9479c074f688cc328bf03f341a511d run_number: 562 event: push status: queued conclusion: workflow_id: 159038 url: https://api.github.com/repos/octo-org/octo-repo/actions/runs/30433642 html_url: https://github.com/octo-org/octo-repo/actions/runs/30433642 pull_requests: [] created_at: '2020-01-22T19:33:08Z' updated_at: '2020-01-22T19:33:08Z' jobs_url: https://api.github.com/repos/octo-org/octo-repo/actions/runs/30433642/jobs logs_url: https://api.github.com/repos/octo-org/octo-repo/actions/runs/30433642/logs check_suite_url: https://api.github.com/repos/octo-org/octo-repo/check-suites/414944374 artifacts_url: https://api.github.com/repos/octo-org/octo-repo/actions/runs/30433642/artifacts cancel_url: https://api.github.com/repos/octo-org/octo-repo/actions/runs/30433642/cancel rerun_url: https://api.github.com/repos/octo-org/octo-repo/actions/runs/30433642/rerun workflow_url: https://api.github.com/repos/octo-org/octo-repo/actions/workflows/159038 head_commit: id: acb5820ced9479c074f688cc328bf03f341a511d tree_id: d23f6eedb1e1b9610bbc754ddb5197bfe7271223 message: Create linter.yaml timestamp: '2020-01-22T19:33:05Z' author: name: Octo Cat email: octocat@github.com committer: name: GitHub email: noreply@github.com repository: id: 1296269 node_id: MDEwOlJlcG9zaXRvcnkxMjk2MjY5 name: Hello-World full_name: octocat/Hello-World owner: login: octocat id: 1 node_id: MDQ6VXNlcjE= avatar_url: https://github.com/images/error/octocat_happy.gif gravatar_id: '' url: https://api.github.com/users/octocat html_url: https://github.com/octocat followers_url: https://api.github.com/users/octocat/followers following_url: https://api.github.com/users/octocat/following{/other_user} gists_url: https://api.github.com/users/octocat/gists{/gist_id} starred_url: https://api.github.com/users/octocat/starred{/owner}{/repo} subscriptions_url: https://api.github.com/users/octocat/subscriptions organizations_url: https://api.github.com/users/octocat/orgs repos_url: https://api.github.com/users/octocat/repos events_url: https://api.github.com/users/octocat/events{/privacy} received_events_url: https://api.github.com/users/octocat/received_events type: User site_admin: false private: false html_url: https://github.com/octocat/Hello-World description: This your first repo! fork: false url: https://api.github.com/repos/octocat/Hello-World archive_url: https://api.github.com/repos/octocat/Hello-World/{archive_format}{/ref} assignees_url: https://api.github.com/repos/octocat/Hello-World/assignees{/user} blobs_url: https://api.github.com/repos/octocat/Hello-World/git/blobs{/sha} branches_url: https://api.github.com/repos/octocat/Hello-World/branches{/branch} collaborators_url: https://api.github.com/repos/octocat/Hello-World/collaborators{/collaborator} comments_url: https://api.github.com/repos/octocat/Hello-World/comments{/number} commits_url: https://api.github.com/repos/octocat/Hello-World/commits{/sha} compare_url: https://api.github.com/repos/octocat/Hello-World/compare/{base}...{head} contents_url: https://api.github.com/repos/octocat/Hello-World/contents/{+path} contributors_url: https://api.github.com/repos/octocat/Hello-World/contributors deployments_url: https://api.github.com/repos/octocat/Hello-World/deployments downloads_url: https://api.github.com/repos/octocat/Hello-World/downloads events_url: https://api.github.com/repos/octocat/Hello-World/events forks_url: https://api.github.com/repos/octocat/Hello-World/forks git_commits_url: https://api.github.com/repos/octocat/Hello-World/git/commits{/sha} git_refs_url: https://api.github.com/repos/octocat/Hello-World/git/refs{/sha} git_tags_url: https://api.github.com/repos/octocat/Hello-World/git/tags{/sha} git_url: git:github.com/octocat/Hello-World.git issue_comment_url: https://api.github.com/repos/octocat/Hello-World/issues/comments{/number} issue_events_url: https://api.github.com/repos/octocat/Hello-World/issues/events{/number} issues_url: https://api.github.com/repos/octocat/Hello-World/issues{/number} keys_url: https://api.github.com/repos/octocat/Hello-World/keys{/key_id} labels_url: https://api.github.com/repos/octocat/Hello-World/labels{/name} languages_url: https://api.github.com/repos/octocat/Hello-World/languages merges_url: https://api.github.com/repos/octocat/Hello-World/merges milestones_url: https://api.github.com/repos/octocat/Hello-World/milestones{/number} notifications_url: https://api.github.com/repos/octocat/Hello-World/notifications{?since,all,participating} pulls_url: https://api.github.com/repos/octocat/Hello-World/pulls{/number} releases_url: https://api.github.com/repos/octocat/Hello-World/releases{/id} ssh_url: git@github.com:octocat/Hello-World.git stargazers_url: https://api.github.com/repos/octocat/Hello-World/stargazers statuses_url: https://api.github.com/repos/octocat/Hello-World/statuses/{sha} subscribers_url: https://api.github.com/repos/octocat/Hello-World/subscribers subscription_url: https://api.github.com/repos/octocat/Hello-World/subscription tags_url: https://api.github.com/repos/octocat/Hello-World/tags teams_url: https://api.github.com/repos/octocat/Hello-World/teams trees_url: https://api.github.com/repos/octocat/Hello-World/git/trees{/sha} hooks_url: http://api.github.com/repos/octocat/Hello-World/hooks head_repository: id: 217723378 node_id: MDEwOlJlcG9zaXRvcnkyMTc3MjMzNzg= name: octo-repo full_name: octo-org/octo-repo private: true owner: login: octocat id: 1 node_id: MDQ6VXNlcjE= avatar_url: https://github.com/images/error/octocat_happy.gif gravatar_id: '' url: https://api.github.com/users/octocat html_url: https://github.com/octocat followers_url: https://api.github.com/users/octocat/followers following_url: https://api.github.com/users/octocat/following{/other_user} gists_url: https://api.github.com/users/octocat/gists{/gist_id} starred_url: https://api.github.com/users/octocat/starred{/owner}{/repo} subscriptions_url: https://api.github.com/users/octocat/subscriptions organizations_url: https://api.github.com/users/octocat/orgs repos_url: https://api.github.com/users/octocat/repos events_url: https://api.github.com/users/octocat/events{/privacy} received_events_url: https://api.github.com/users/octocat/received_events type: User site_admin: false html_url: https://github.com/octo-org/octo-repo description: fork: false url: https://api.github.com/repos/octo-org/octo-repo forks_url: https://api.github.com/repos/octo-org/octo-repo/forks keys_url: https://api.github.com/repos/octo-org/octo-repo/keys{/key_id} collaborators_url: https://api.github.com/repos/octo-org/octo-repo/collaborators{/collaborator} teams_url: https://api.github.com/repos/octo-org/octo-repo/teams hooks_url: https://api.github.com/repos/octo-org/octo-repo/hooks issue_events_url: https://api.github.com/repos/octo-org/octo-repo/issues/events{/number} events_url: https://api.github.com/repos/octo-org/octo-repo/events assignees_url: https://api.github.com/repos/octo-org/octo-repo/assignees{/user} branches_url: https://api.github.com/repos/octo-org/octo-repo/branches{/branch} tags_url: https://api.github.com/repos/octo-org/octo-repo/tags blobs_url: https://api.github.com/repos/octo-org/octo-repo/git/blobs{/sha} git_tags_url: https://api.github.com/repos/octo-org/octo-repo/git/tags{/sha} git_refs_url: https://api.github.com/repos/octo-org/octo-repo/git/refs{/sha} trees_url: https://api.github.com/repos/octo-org/octo-repo/git/trees{/sha} statuses_url: https://api.github.com/repos/octo-org/octo-repo/statuses/{sha} languages_url: https://api.github.com/repos/octo-org/octo-repo/languages stargazers_url: https://api.github.com/repos/octo-org/octo-repo/stargazers contributors_url: https://api.github.com/repos/octo-org/octo-repo/contributors subscribers_url: https://api.github.com/repos/octo-org/octo-repo/subscribers subscription_url: https://api.github.com/repos/octo-org/octo-repo/subscription commits_url: https://api.github.com/repos/octo-org/octo-repo/commits{/sha} git_commits_url: https://api.github.com/repos/octo-org/octo-repo/git/commits{/sha} comments_url: https://api.github.com/repos/octo-org/octo-repo/comments{/number} issue_comment_url: https://api.github.com/repos/octo-org/octo-repo/issues/comments{/number} contents_url: https://api.github.com/repos/octo-org/octo-repo/contents/{+path} compare_url: https://api.github.com/repos/octo-org/octo-repo/compare/{base}...{head} merges_url: https://api.github.com/repos/octo-org/octo-repo/merges archive_url: https://api.github.com/repos/octo-org/octo-repo/{archive_format}{/ref} downloads_url: https://api.github.com/repos/octo-org/octo-repo/downloads issues_url: https://api.github.com/repos/octo-org/octo-repo/issues{/number} pulls_url: https://api.github.com/repos/octo-org/octo-repo/pulls{/number} milestones_url: https://api.github.com/repos/octo-org/octo-repo/milestones{/number} notifications_url: https://api.github.com/repos/octo-org/octo-repo/notifications{?since,all,participating} labels_url: https://api.github.com/repos/octo-org/octo-repo/labels{/name} releases_url: https://api.github.com/repos/octo-org/octo-repo/releases{/id} deployments_url: https://api.github.com/repos/octo-org/octo-repo/deployments workflow-run: value: id: 30433642 name: Build node_id: MDEyOldvcmtmbG93IFJ1bjI2OTI4OQ== check_suite_id: 42 check_suite_node_id: MDEwOkNoZWNrU3VpdGU0Mg== head_branch: master head_sha: acb5820ced9479c074f688cc328bf03f341a511d run_number: 562 event: push status: queued workflow_id: 159038 url: https://api.github.com/repos/octo-org/octo-repo/actions/runs/30433642 html_url: https://github.com/octo-org/octo-repo/actions/runs/30433642 pull_requests: [] created_at: '2020-01-22T19:33:08Z' updated_at: '2020-01-22T19:33:08Z' jobs_url: https://api.github.com/repos/octo-org/octo-repo/actions/runs/30433642/jobs logs_url: https://api.github.com/repos/octo-org/octo-repo/actions/runs/30433642/logs check_suite_url: https://api.github.com/repos/octo-org/octo-repo/check-suites/414944374 artifacts_url: https://api.github.com/repos/octo-org/octo-repo/actions/runs/30433642/artifacts cancel_url: https://api.github.com/repos/octo-org/octo-repo/actions/runs/30433642/cancel rerun_url: https://api.github.com/repos/octo-org/octo-repo/actions/runs/30433642/rerun workflow_url: https://api.github.com/repos/octo-org/octo-repo/actions/workflows/159038 head_commit: id: acb5820ced9479c074f688cc328bf03f341a511d tree_id: d23f6eedb1e1b9610bbc754ddb5197bfe7271223 message: Create linter.yaml timestamp: '2020-01-22T19:33:05Z' author: name: Octo Cat email: octocat@github.com committer: name: GitHub email: noreply@github.com repository: id: 1296269 node_id: MDEwOlJlcG9zaXRvcnkxMjk2MjY5 name: Hello-World full_name: octocat/Hello-World owner: login: octocat id: 1 node_id: MDQ6VXNlcjE= avatar_url: https://github.com/images/error/octocat_happy.gif gravatar_id: '' url: https://api.github.com/users/octocat html_url: https://github.com/octocat followers_url: https://api.github.com/users/octocat/followers following_url: https://api.github.com/users/octocat/following{/other_user} gists_url: https://api.github.com/users/octocat/gists{/gist_id} starred_url: https://api.github.com/users/octocat/starred{/owner}{/repo} subscriptions_url: https://api.github.com/users/octocat/subscriptions organizations_url: https://api.github.com/users/octocat/orgs repos_url: https://api.github.com/users/octocat/repos events_url: https://api.github.com/users/octocat/events{/privacy} received_events_url: https://api.github.com/users/octocat/received_events type: User site_admin: false private: false html_url: https://github.com/octocat/Hello-World description: This your first repo! fork: false url: https://api.github.com/repos/octocat/Hello-World archive_url: https://api.github.com/repos/octocat/Hello-World/{archive_format}{/ref} assignees_url: https://api.github.com/repos/octocat/Hello-World/assignees{/user} blobs_url: https://api.github.com/repos/octocat/Hello-World/git/blobs{/sha} branches_url: https://api.github.com/repos/octocat/Hello-World/branches{/branch} collaborators_url: https://api.github.com/repos/octocat/Hello-World/collaborators{/collaborator} comments_url: https://api.github.com/repos/octocat/Hello-World/comments{/number} commits_url: https://api.github.com/repos/octocat/Hello-World/commits{/sha} compare_url: https://api.github.com/repos/octocat/Hello-World/compare/{base}...{head} contents_url: https://api.github.com/repos/octocat/Hello-World/contents/{+path} contributors_url: https://api.github.com/repos/octocat/Hello-World/contributors deployments_url: https://api.github.com/repos/octocat/Hello-World/deployments downloads_url: https://api.github.com/repos/octocat/Hello-World/downloads events_url: https://api.github.com/repos/octocat/Hello-World/events forks_url: https://api.github.com/repos/octocat/Hello-World/forks git_commits_url: https://api.github.com/repos/octocat/Hello-World/git/commits{/sha} git_refs_url: https://api.github.com/repos/octocat/Hello-World/git/refs{/sha} git_tags_url: https://api.github.com/repos/octocat/Hello-World/git/tags{/sha} git_url: git:github.com/octocat/Hello-World.git issue_comment_url: https://api.github.com/repos/octocat/Hello-World/issues/comments{/number} issue_events_url: https://api.github.com/repos/octocat/Hello-World/issues/events{/number} issues_url: https://api.github.com/repos/octocat/Hello-World/issues{/number} keys_url: https://api.github.com/repos/octocat/Hello-World/keys{/key_id} labels_url: https://api.github.com/repos/octocat/Hello-World/labels{/name} languages_url: https://api.github.com/repos/octocat/Hello-World/languages merges_url: https://api.github.com/repos/octocat/Hello-World/merges milestones_url: https://api.github.com/repos/octocat/Hello-World/milestones{/number} notifications_url: https://api.github.com/repos/octocat/Hello-World/notifications{?since,all,participating} pulls_url: https://api.github.com/repos/octocat/Hello-World/pulls{/number} releases_url: https://api.github.com/repos/octocat/Hello-World/releases{/id} ssh_url: git@github.com:octocat/Hello-World.git stargazers_url: https://api.github.com/repos/octocat/Hello-World/stargazers statuses_url: https://api.github.com/repos/octocat/Hello-World/statuses/{sha} subscribers_url: https://api.github.com/repos/octocat/Hello-World/subscribers subscription_url: https://api.github.com/repos/octocat/Hello-World/subscription tags_url: https://api.github.com/repos/octocat/Hello-World/tags teams_url: https://api.github.com/repos/octocat/Hello-World/teams trees_url: https://api.github.com/repos/octocat/Hello-World/git/trees{/sha} hooks_url: http://api.github.com/repos/octocat/Hello-World/hooks head_repository: id: 217723378 node_id: MDEwOlJlcG9zaXRvcnkyMTc3MjMzNzg= name: octo-repo full_name: octo-org/octo-repo private: true owner: login: octocat id: 1 node_id: MDQ6VXNlcjE= avatar_url: https://github.com/images/error/octocat_happy.gif gravatar_id: '' url: https://api.github.com/users/octocat html_url: https://github.com/octocat followers_url: https://api.github.com/users/octocat/followers following_url: https://api.github.com/users/octocat/following{/other_user} gists_url: https://api.github.com/users/octocat/gists{/gist_id} starred_url: https://api.github.com/users/octocat/starred{/owner}{/repo} subscriptions_url: https://api.github.com/users/octocat/subscriptions organizations_url: https://api.github.com/users/octocat/orgs repos_url: https://api.github.com/users/octocat/repos events_url: https://api.github.com/users/octocat/events{/privacy} received_events_url: https://api.github.com/users/octocat/received_events type: User site_admin: false html_url: https://github.com/octo-org/octo-repo description: fork: false url: https://api.github.com/repos/octo-org/octo-repo forks_url: https://api.github.com/repos/octo-org/octo-repo/forks keys_url: https://api.github.com/repos/octo-org/octo-repo/keys{/key_id} collaborators_url: https://api.github.com/repos/octo-org/octo-repo/collaborators{/collaborator} teams_url: https://api.github.com/repos/octo-org/octo-repo/teams hooks_url: https://api.github.com/repos/octo-org/octo-repo/hooks issue_events_url: https://api.github.com/repos/octo-org/octo-repo/issues/events{/number} events_url: https://api.github.com/repos/octo-org/octo-repo/events assignees_url: https://api.github.com/repos/octo-org/octo-repo/assignees{/user} branches_url: https://api.github.com/repos/octo-org/octo-repo/branches{/branch} tags_url: https://api.github.com/repos/octo-org/octo-repo/tags blobs_url: https://api.github.com/repos/octo-org/octo-repo/git/blobs{/sha} git_tags_url: https://api.github.com/repos/octo-org/octo-repo/git/tags{/sha} git_refs_url: https://api.github.com/repos/octo-org/octo-repo/git/refs{/sha} trees_url: https://api.github.com/repos/octo-org/octo-repo/git/trees{/sha} statuses_url: https://api.github.com/repos/octo-org/octo-repo/statuses/{sha} languages_url: https://api.github.com/repos/octo-org/octo-repo/languages stargazers_url: https://api.github.com/repos/octo-org/octo-repo/stargazers contributors_url: https://api.github.com/repos/octo-org/octo-repo/contributors subscribers_url: https://api.github.com/repos/octo-org/octo-repo/subscribers subscription_url: https://api.github.com/repos/octo-org/octo-repo/subscription commits_url: https://api.github.com/repos/octo-org/octo-repo/commits{/sha} git_commits_url: https://api.github.com/repos/octo-org/octo-repo/git/commits{/sha} comments_url: https://api.github.com/repos/octo-org/octo-repo/comments{/number} issue_comment_url: https://api.github.com/repos/octo-org/octo-repo/issues/comments{/number} contents_url: https://api.github.com/repos/octo-org/octo-repo/contents/{+path} compare_url: https://api.github.com/repos/octo-org/octo-repo/compare/{base}...{head} merges_url: https://api.github.com/repos/octo-org/octo-repo/merges archive_url: https://api.github.com/repos/octo-org/octo-repo/{archive_format}{/ref} downloads_url: https://api.github.com/repos/octo-org/octo-repo/downloads issues_url: https://api.github.com/repos/octo-org/octo-repo/issues{/number} pulls_url: https://api.github.com/repos/octo-org/octo-repo/pulls{/number} milestones_url: https://api.github.com/repos/octo-org/octo-repo/milestones{/number} notifications_url: https://api.github.com/repos/octo-org/octo-repo/notifications{?since,all,participating} labels_url: https://api.github.com/repos/octo-org/octo-repo/labels{/name} releases_url: https://api.github.com/repos/octo-org/octo-repo/releases{/id} deployments_url: https://api.github.com/repos/octo-org/octo-repo/deployments job-paginated: value: total_count: 1 jobs: - id: 399444496 run_id: 29679449 run_url: https://api.github.com/repos/octo-org/octo-repo/actions/runs/29679449 node_id: MDEyOldvcmtmbG93IEpvYjM5OTQ0NDQ5Ng== head_sha: f83a356604ae3c5d03e1b46ef4d1ca77d64a90b0 url: https://api.github.com/repos/octo-org/octo-repo/actions/jobs/399444496 html_url: https://github.com/octo-org/octo-repo/runs/399444496 status: completed conclusion: success started_at: '2020-01-20T17:42:40Z' completed_at: '2020-01-20T17:44:39Z' name: build steps: - name: Set up job status: completed conclusion: success number: 1 started_at: '2020-01-20T09:42:40.000-08:00' completed_at: '2020-01-20T09:42:41.000-08:00' - name: Run actions/checkout@v2 status: completed conclusion: success number: 2 started_at: '2020-01-20T09:42:41.000-08:00' completed_at: '2020-01-20T09:42:45.000-08:00' - name: Set up Ruby status: completed conclusion: success number: 3 started_at: '2020-01-20T09:42:45.000-08:00' completed_at: '2020-01-20T09:42:45.000-08:00' - name: Run actions/cache@v2 status: completed conclusion: success number: 4 started_at: '2020-01-20T09:42:45.000-08:00' completed_at: '2020-01-20T09:42:48.000-08:00' - name: Install Bundler status: completed conclusion: success number: 5 started_at: '2020-01-20T09:42:48.000-08:00' completed_at: '2020-01-20T09:42:52.000-08:00' - name: Install Gems status: completed conclusion: success number: 6 started_at: '2020-01-20T09:42:52.000-08:00' completed_at: '2020-01-20T09:42:53.000-08:00' - name: Run Tests status: completed conclusion: success number: 7 started_at: '2020-01-20T09:42:53.000-08:00' completed_at: '2020-01-20T09:42:59.000-08:00' - name: Deploy to Heroku status: completed conclusion: success number: 8 started_at: '2020-01-20T09:42:59.000-08:00' completed_at: '2020-01-20T09:44:39.000-08:00' - name: Post actions/cache@v2 status: completed conclusion: success number: 16 started_at: '2020-01-20T09:44:39.000-08:00' completed_at: '2020-01-20T09:44:39.000-08:00' - name: Complete job status: completed conclusion: success number: 17 started_at: '2020-01-20T09:44:39.000-08:00' completed_at: '2020-01-20T09:44:39.000-08:00' check_run_url: https://api.github.com/repos/octo-org/octo-repo/check-runs/399444496 actions-secret-paginated: value: total_count: 2 secrets: - name: GH_TOKEN created_at: '2019-08-10T14:59:22Z' updated_at: '2020-01-10T14:59:22Z' - name: GIST_ID created_at: '2020-01-10T10:59:22Z' updated_at: '2020-01-11T11:59:22Z' actions-secret: value: name: GH_TOKEN created_at: '2019-08-10T14:59:22Z' updated_at: '2020-01-10T14:59:22Z' workflow-paginated: value: total_count: 2 workflows: - id: 161335 node_id: MDg6V29ya2Zsb3cxNjEzMzU= name: CI path: ".github/workflows/blank.yaml" state: active created_at: '2020-01-08T23:48:37.000-08:00' updated_at: '2020-01-08T23:50:21.000-08:00' url: https://api.github.com/repos/octo-org/octo-repo/actions/workflows/161335 html_url: https://github.com/octo-org/octo-repo/blob/master/.github/workflows/161335 badge_url: https://github.com/octo-org/octo-repo/workflows/CI/badge.svg - id: 269289 node_id: MDE4OldvcmtmbG93IFNlY29uZGFyeTI2OTI4OQ== name: Linter path: ".github/workflows/linter.yaml" state: active created_at: '2020-01-08T23:48:37.000-08:00' updated_at: '2020-01-08T23:50:21.000-08:00' url: https://api.github.com/repos/octo-org/octo-repo/actions/workflows/269289 html_url: https://github.com/octo-org/octo-repo/blob/master/.github/workflows/269289 badge_url: https://github.com/octo-org/octo-repo/workflows/Linter/badge.svg workflow: value: id: 161335 node_id: MDg6V29ya2Zsb3cxNjEzMzU= name: CI path: ".github/workflows/blank.yaml" state: active created_at: '2020-01-08T23:48:37.000-08:00' updated_at: '2020-01-08T23:50:21.000-08:00' url: https://api.github.com/repos/octo-org/octo-repo/actions/workflows/161335 html_url: https://github.com/octo-org/octo-repo/blob/master/.github/workflows/161335 badge_url: https://github.com/octo-org/octo-repo/workflows/CI/badge.svg short-branch-with-protection-items: value: - name: master commit: sha: c5b97d5ae6c19d5c5df71a34c7fbeeda2479ccbc url: https://api.github.com/repos/octocat/Hello-World/commits/c5b97d5ae6c19d5c5df71a34c7fbeeda2479ccbc protected: true protection: required_status_checks: enforcement_level: non_admins contexts: - ci-test - linter protection_url: https://api.github.com/repos/octocat/hello-world/branches/master/protection branch-protection: value: url: https://api.github.com/repos/octocat/Hello-World/branches/master/protection required_status_checks: url: https://api.github.com/repos/octocat/Hello-World/branches/master/protection/required_status_checks contexts: - continuous-integration/travis-ci contexts_url: https://api.github.com/repos/octocat/Hello-World/branches/master/protection/required_status_checks/contexts enforcement_level: non_admins enforce_admins: url: https://api.github.com/repos/octocat/Hello-World/branches/master/protection/enforce_admins enabled: true required_pull_request_reviews: url: https://api.github.com/repos/octocat/Hello-World/branches/master/protection/required_pull_request_reviews dismissal_restrictions: url: https://api.github.com/repos/octocat/Hello-World/branches/master/protection/dismissal_restrictions users_url: https://api.github.com/repos/octocat/Hello-World/branches/master/protection/dismissal_restrictions/users teams_url: https://api.github.com/repos/octocat/Hello-World/branches/master/protection/dismissal_restrictions/teams users: - login: octocat id: 1 node_id: MDQ6VXNlcjE= avatar_url: https://github.com/images/error/octocat_happy.gif gravatar_id: '' url: https://api.github.com/users/octocat html_url: https://github.com/octocat followers_url: https://api.github.com/users/octocat/followers following_url: https://api.github.com/users/octocat/following{/other_user} gists_url: https://api.github.com/users/octocat/gists{/gist_id} starred_url: https://api.github.com/users/octocat/starred{/owner}{/repo} subscriptions_url: https://api.github.com/users/octocat/subscriptions organizations_url: https://api.github.com/users/octocat/orgs repos_url: https://api.github.com/users/octocat/repos events_url: https://api.github.com/users/octocat/events{/privacy} received_events_url: https://api.github.com/users/octocat/received_events type: User site_admin: false teams: - id: 1 node_id: MDQ6VGVhbTE= url: https://api.github.com/teams/1 html_url: https://github.com/orgs/github/teams/justice-league name: Justice League slug: justice-league description: A great team. privacy: closed permission: admin members_url: https://api.github.com/teams/1/members{/member} repositories_url: https://api.github.com/teams/1/repos parent: dismiss_stale_reviews: true require_code_owner_reviews: true required_approving_review_count: 2 restrictions: url: https://api.github.com/repos/octocat/Hello-World/branches/master/protection/restrictions users_url: https://api.github.com/repos/octocat/Hello-World/branches/master/protection/restrictions/users teams_url: https://api.github.com/repos/octocat/Hello-World/branches/master/protection/restrictions/teams apps_url: https://api.github.com/repos/octocat/Hello-World/branches/master/protection/restrictions/teams users: - login: octocat id: 1 node_id: MDQ6VXNlcjE= avatar_url: https://github.com/images/error/octocat_happy.gif gravatar_id: '' url: https://api.github.com/users/octocat html_url: https://github.com/octocat followers_url: https://api.github.com/users/octocat/followers following_url: https://api.github.com/users/octocat/following{/other_user} gists_url: https://api.github.com/users/octocat/gists{/gist_id} starred_url: https://api.github.com/users/octocat/starred{/owner}{/repo} subscriptions_url: https://api.github.com/users/octocat/subscriptions organizations_url: https://api.github.com/users/octocat/orgs repos_url: https://api.github.com/users/octocat/repos events_url: https://api.github.com/users/octocat/events{/privacy} received_events_url: https://api.github.com/users/octocat/received_events type: User site_admin: false teams: - id: 1 node_id: MDQ6VGVhbTE= url: https://api.github.com/teams/1 html_url: https://github.com/orgs/github/teams/justice-league name: Justice League slug: justice-league description: A great team. privacy: closed permission: admin members_url: https://api.github.com/teams/1/members{/member} repositories_url: https://api.github.com/teams/1/repos parent: apps: - id: 1 slug: octoapp node_id: MDExOkludGVncmF0aW9uMQ== owner: login: github id: 1 node_id: MDEyOk9yZ2FuaXphdGlvbjE= url: https://api.github.com/orgs/github repos_url: https://api.github.com/orgs/github/repos events_url: https://api.github.com/orgs/github/events hooks_url: https://api.github.com/orgs/github/hooks issues_url: https://api.github.com/orgs/github/issues members_url: https://api.github.com/orgs/github/members{/member} public_members_url: https://api.github.com/orgs/github/public_members{/member} avatar_url: https://github.com/images/error/octocat_happy.gif description: A great organization name: Octocat App description: '' external_url: https://example.com html_url: https://github.com/apps/octoapp created_at: '2017-07-08T16:18:44-04:00' updated_at: '2017-07-08T16:18:44-04:00' permissions: metadata: read contents: read issues: write single_file: write events: - push - pull_request required_linear_history: enabled: true allow_force_pushes: enabled: true allow_deletions: enabled: true required_conversation_resolution: enabled: true protected-branch-admin-enforced-2: value: url: https://api.github.com/repos/octocat/Hello-World/branches/master/protection/enforce_admins enabled: true protected-branch-pull-request-review: value: url: https://api.github.com/repos/octocat/Hello-World/branches/master/protection/required_pull_request_reviews dismissal_restrictions: url: https://api.github.com/repos/octocat/Hello-World/branches/master/protection/dismissal_restrictions users_url: https://api.github.com/repos/octocat/Hello-World/branches/master/protection/dismissal_restrictions/users teams_url: https://api.github.com/repos/octocat/Hello-World/branches/master/protection/dismissal_restrictions/teams users: - login: octocat id: 1 node_id: MDQ6VXNlcjE= avatar_url: https://github.com/images/error/octocat_happy.gif gravatar_id: '' url: https://api.github.com/users/octocat html_url: https://github.com/octocat followers_url: https://api.github.com/users/octocat/followers following_url: https://api.github.com/users/octocat/following{/other_user} gists_url: https://api.github.com/users/octocat/gists{/gist_id} starred_url: https://api.github.com/users/octocat/starred{/owner}{/repo} subscriptions_url: https://api.github.com/users/octocat/subscriptions organizations_url: https://api.github.com/users/octocat/orgs repos_url: https://api.github.com/users/octocat/repos events_url: https://api.github.com/users/octocat/events{/privacy} received_events_url: https://api.github.com/users/octocat/received_events type: User site_admin: false teams: - id: 1 node_id: MDQ6VGVhbTE= url: https://api.github.com/teams/1 html_url: https://github.com/orgs/github/teams/justice-league name: Justice League slug: justice-league description: A great team. privacy: closed permission: admin members_url: https://api.github.com/teams/1/members{/member} repositories_url: https://api.github.com/teams/1/repos parent: dismiss_stale_reviews: true require_code_owner_reviews: true required_approving_review_count: 2 protected-branch-admin-enforced: value: url: https://api.github.com/repos/octocat/Hello-World/branches/master/protection/required_signatures enabled: true status-check-policy: value: url: https://api.github.com/repos/octocat/Hello-World/branches/master/protection/required_status_checks strict: true contexts: - continuous-integration/travis-ci contexts_url: https://api.github.com/repos/octocat/Hello-World/branches/master/protection/required_status_checks/contexts branch-restriction-policy: value: url: https://api.github.com/repos/octocat/Hello-World/branches/master/protection/restrictions users_url: https://api.github.com/repos/octocat/Hello-World/branches/master/protection/restrictions/users teams_url: https://api.github.com/repos/octocat/Hello-World/branches/master/protection/restrictions/teams apps_url: https://api.github.com/repos/octocat/Hello-World/branches/master/protection/restrictions/teams users: - login: octocat id: 1 node_id: MDQ6VXNlcjE= avatar_url: https://github.com/images/error/octocat_happy.gif gravatar_id: '' url: https://api.github.com/users/octocat html_url: https://github.com/octocat followers_url: https://api.github.com/users/octocat/followers following_url: https://api.github.com/users/octocat/following{/other_user} gists_url: https://api.github.com/users/octocat/gists{/gist_id} starred_url: https://api.github.com/users/octocat/starred{/owner}{/repo} subscriptions_url: https://api.github.com/users/octocat/subscriptions organizations_url: https://api.github.com/users/octocat/orgs repos_url: https://api.github.com/users/octocat/repos events_url: https://api.github.com/users/octocat/events{/privacy} received_events_url: https://api.github.com/users/octocat/received_events type: User site_admin: false teams: - id: 1 node_id: MDQ6VGVhbTE= url: https://api.github.com/teams/1 html_url: https://github.com/orgs/github/teams/justice-league name: Justice League slug: justice-league description: A great team. privacy: closed permission: admin members_url: https://api.github.com/teams/1/members{/member} repositories_url: https://api.github.com/teams/1/repos parent: apps: - id: 1 slug: octoapp node_id: MDExOkludGVncmF0aW9uMQ== owner: login: github id: 1 node_id: MDEyOk9yZ2FuaXphdGlvbjE= url: https://api.github.com/orgs/github repos_url: https://api.github.com/orgs/github/repos events_url: https://api.github.com/orgs/github/events hooks_url: https://api.github.com/orgs/github/hooks issues_url: https://api.github.com/orgs/github/issues members_url: https://api.github.com/orgs/github/members{/member} public_members_url: https://api.github.com/orgs/github/public_members{/member} avatar_url: https://github.com/images/error/octocat_happy.gif description: A great organization name: Octocat App description: '' external_url: https://example.com html_url: https://github.com/apps/octoapp created_at: '2017-07-08T16:18:44-04:00' updated_at: '2017-07-08T16:18:44-04:00' permissions: metadata: read contents: read issues: write single_file: write events: - push - pull_request integration-items: value: - id: 1 slug: octoapp node_id: MDExOkludGVncmF0aW9uMQ== owner: login: github id: 1 node_id: MDEyOk9yZ2FuaXphdGlvbjE= url: https://api.github.com/orgs/github repos_url: https://api.github.com/orgs/github/repos events_url: https://api.github.com/orgs/github/events avatar_url: https://github.com/images/error/octocat_happy.gif gravatar_id: '' html_url: https://github.com/octocat followers_url: https://api.github.com/users/octocat/followers following_url: https://api.github.com/users/octocat/following{/other_user} gists_url: https://api.github.com/users/octocat/gists{/gist_id} starred_url: https://api.github.com/users/octocat/starred{/owner}{/repo} subscriptions_url: https://api.github.com/users/octocat/subscriptions organizations_url: https://api.github.com/users/octocat/orgs received_events_url: https://api.github.com/users/octocat/received_events type: User site_admin: true name: Octocat App description: '' external_url: https://example.com html_url: https://github.com/apps/octoapp created_at: '2017-07-08T16:18:44-04:00' updated_at: '2017-07-08T16:18:44-04:00' permissions: metadata: read contents: read issues: write single_file: write events: - push - pull_request check-run-example-of-completed-conclusion: summary: Response for completed conclusion value: id: 4 head_sha: ce587453ced02b1526dfb4cb910479d431683101 node_id: MDg6Q2hlY2tSdW40 external_id: '' url: https://api.github.com/repos/github/hello-world/check-runs/4 html_url: https://github.com/github/hello-world/runs/4 details_url: https://example.com status: completed conclusion: neutral started_at: '2018-05-04T01:14:52Z' completed_at: '2018-05-04T01:14:52Z' output: title: Mighty Readme report summary: There are 0 failures, 2 warnings, and 1 notice. text: You may have some misspelled words on lines 2 and 4. You also may want to add a section in your README about how to install your app. annotations_count: 2 annotations_url: https://api.github.com/repos/github/hello-world/check-runs/4/annotations name: mighty_readme check_suite: id: 5 app: id: 1 slug: octoapp node_id: MDExOkludGVncmF0aW9uMQ== owner: login: github id: 1 node_id: MDEyOk9yZ2FuaXphdGlvbjE= url: https://api.github.com/orgs/github repos_url: https://api.github.com/orgs/github/repos events_url: https://api.github.com/orgs/github/events avatar_url: https://github.com/images/error/octocat_happy.gif gravatar_id: '' html_url: https://github.com/octocat followers_url: https://api.github.com/users/octocat/followers following_url: https://api.github.com/users/octocat/following{/other_user} gists_url: https://api.github.com/users/octocat/gists{/gist_id} starred_url: https://api.github.com/users/octocat/starred{/owner}{/repo} subscriptions_url: https://api.github.com/users/octocat/subscriptions organizations_url: https://api.github.com/users/octocat/orgs received_events_url: https://api.github.com/users/octocat/received_events type: User site_admin: true name: Octocat App description: '' external_url: https://example.com html_url: https://github.com/apps/octoapp created_at: '2017-07-08T16:18:44-04:00' updated_at: '2017-07-08T16:18:44-04:00' permissions: metadata: read contents: read issues: write single_file: write events: - push - pull_request pull_requests: - url: https://api.github.com/repos/github/hello-world/pulls/1 id: 1934 number: 3956 head: ref: say-hello sha: 3dca65fa3e8d4b3da3f3d056c59aee1c50f41390 repo: id: 526 url: https://api.github.com/repos/github/hello-world name: hello-world base: ref: master sha: e7fdf7640066d71ad16a86fbcbb9c6a10a18af4f repo: id: 526 url: https://api.github.com/repos/github/hello-world name: hello-world check-run: value: id: 4 head_sha: ce587453ced02b1526dfb4cb910479d431683101 node_id: MDg6Q2hlY2tSdW40 external_id: '' url: https://api.github.com/repos/github/hello-world/check-runs/4 html_url: https://github.com/github/hello-world/runs/4 details_url: https://example.com status: completed conclusion: neutral started_at: '2018-05-04T01:14:52Z' completed_at: '2018-05-04T01:14:52Z' output: title: Mighty Readme report summary: There are 0 failures, 2 warnings, and 1 notice. text: You may have some misspelled words on lines 2 and 4. You also may want to add a section in your README about how to install your app. annotations_count: 2 annotations_url: https://api.github.com/repos/github/hello-world/check-runs/4/annotations name: mighty_readme check_suite: id: 5 app: id: 1 slug: octoapp node_id: MDExOkludGVncmF0aW9uMQ== owner: login: github id: 1 node_id: MDEyOk9yZ2FuaXphdGlvbjE= url: https://api.github.com/orgs/github repos_url: https://api.github.com/orgs/github/repos events_url: https://api.github.com/orgs/github/events avatar_url: https://github.com/images/error/octocat_happy.gif gravatar_id: '' html_url: https://github.com/octocat followers_url: https://api.github.com/users/octocat/followers following_url: https://api.github.com/users/octocat/following{/other_user} gists_url: https://api.github.com/users/octocat/gists{/gist_id} starred_url: https://api.github.com/users/octocat/starred{/owner}{/repo} subscriptions_url: https://api.github.com/users/octocat/subscriptions organizations_url: https://api.github.com/users/octocat/orgs received_events_url: https://api.github.com/users/octocat/received_events type: User site_admin: true name: Octocat App description: '' external_url: https://example.com html_url: https://github.com/apps/octoapp created_at: '2017-07-08T16:18:44-04:00' updated_at: '2017-07-08T16:18:44-04:00' permissions: metadata: read contents: read issues: write single_file: write events: - push - pull_request pull_requests: - url: https://api.github.com/repos/github/hello-world/pulls/1 id: 1934 number: 3956 head: ref: say-hello sha: 3dca65fa3e8d4b3da3f3d056c59aee1c50f41390 repo: id: 526 url: https://api.github.com/repos/github/hello-world name: hello-world base: ref: master sha: e7fdf7640066d71ad16a86fbcbb9c6a10a18af4f repo: id: 526 url: https://api.github.com/repos/github/hello-world name: hello-world check-annotation-items: value: - path: README.md start_line: 2 end_line: 2 start_column: 5 end_column: 10 annotation_level: warning title: Spell Checker message: Check your spelling for 'banaas'. raw_details: Do you mean 'bananas' or 'banana'? blob_href: https://api.github.com/repos/github/rest-api-description/git/blobs/abc check-suite: value: id: 5 node_id: MDEwOkNoZWNrU3VpdGU1 head_branch: master head_sha: d6fde92930d4715a2b49857d24b940956b26d2d3 status: completed conclusion: neutral url: https://api.github.com/repos/github/hello-world/check-suites/5 before: 146e867f55c26428e5f9fade55a9bbf5e95a7912 after: d6fde92930d4715a2b49857d24b940956b26d2d3 pull_requests: [] created_at: '2017-07-08T16:18:44-04:00' updated_at: '2017-07-08T16:18:44-04:00' app: id: 1 slug: octoapp node_id: MDExOkludGVncmF0aW9uMQ== owner: login: github id: 1 node_id: MDEyOk9yZ2FuaXphdGlvbjE= url: https://api.github.com/orgs/github repos_url: https://api.github.com/orgs/github/repos events_url: https://api.github.com/orgs/github/events avatar_url: https://github.com/images/error/octocat_happy.gif gravatar_id: '' html_url: https://github.com/octocat followers_url: https://api.github.com/users/octocat/followers following_url: https://api.github.com/users/octocat/following{/other_user} gists_url: https://api.github.com/users/octocat/gists{/gist_id} starred_url: https://api.github.com/users/octocat/starred{/owner}{/repo} subscriptions_url: https://api.github.com/users/octocat/subscriptions organizations_url: https://api.github.com/users/octocat/orgs received_events_url: https://api.github.com/users/octocat/received_events type: User site_admin: true name: Octocat App description: '' external_url: https://example.com html_url: https://github.com/apps/octoapp created_at: '2017-07-08T16:18:44-04:00' updated_at: '2017-07-08T16:18:44-04:00' permissions: metadata: read contents: read issues: write single_file: write events: - push - pull_request repository: id: 1296269 node_id: MDEwOlJlcG9zaXRvcnkxMjk2MjY5 name: Hello-World full_name: octocat/Hello-World template_repository: id: 1296269 node_id: MDEwOlJlcG9zaXRvcnkxMjk2MjY5 name: Hello-World-Template full_name: octocat/Hello-World-Template owner: login: octocat id: 1 node_id: MDQ6VXNlcjE= avatar_url: https://github.com/images/error/octocat_happy.gif gravatar_id: '' url: https://api.github.com/users/octocat html_url: https://github.com/octocat followers_url: https://api.github.com/users/octocat/followers following_url: https://api.github.com/users/octocat/following{/other_user} gists_url: https://api.github.com/users/octocat/gists{/gist_id} starred_url: https://api.github.com/users/octocat/starred{/owner}{/repo} subscriptions_url: https://api.github.com/users/octocat/subscriptions organizations_url: https://api.github.com/users/octocat/orgs repos_url: https://api.github.com/users/octocat/repos events_url: https://api.github.com/users/octocat/events{/privacy} received_events_url: https://api.github.com/users/octocat/received_events type: User site_admin: false private: false html_url: https://github.com/octocat/Hello-World-Template description: This your first repo! fork: false url: https://api.github.com/repos/octocat/Hello-World-Template archive_url: https://api.github.com/repos/octocat/Hello-World-Template/{archive_format}{/ref} assignees_url: https://api.github.com/repos/octocat/Hello-World-Template/assignees{/user} blobs_url: https://api.github.com/repos/octocat/Hello-World-Template/git/blobs{/sha} branches_url: https://api.github.com/repos/octocat/Hello-World-Template/branches{/branch} collaborators_url: https://api.github.com/repos/octocat/Hello-World-Template/collaborators{/collaborator} comments_url: https://api.github.com/repos/octocat/Hello-World-Template/comments{/number} commits_url: https://api.github.com/repos/octocat/Hello-World-Template/commits{/sha} compare_url: https://api.github.com/repos/octocat/Hello-World-Template/compare/{base}...{head} contents_url: https://api.github.com/repos/octocat/Hello-World-Template/contents/{+path} contributors_url: https://api.github.com/repos/octocat/Hello-World-Template/contributors deployments_url: https://api.github.com/repos/octocat/Hello-World-Template/deployments downloads_url: https://api.github.com/repos/octocat/Hello-World-Template/downloads events_url: https://api.github.com/repos/octocat/Hello-World-Template/events forks_url: https://api.github.com/repos/octocat/Hello-World-Template/forks git_commits_url: https://api.github.com/repos/octocat/Hello-World-Template/git/commits{/sha} git_refs_url: https://api.github.com/repos/octocat/Hello-World-Template/git/refs{/sha} git_tags_url: https://api.github.com/repos/octocat/Hello-World-Template/git/tags{/sha} git_url: git:github.com/octocat/Hello-World-Template.git issue_comment_url: https://api.github.com/repos/octocat/Hello-World-Template/issues/comments{/number} issue_events_url: https://api.github.com/repos/octocat/Hello-World-Template/issues/events{/number} issues_url: https://api.github.com/repos/octocat/Hello-World-Template/issues{/number} keys_url: https://api.github.com/repos/octocat/Hello-World-Template/keys{/key_id} labels_url: https://api.github.com/repos/octocat/Hello-World-Template/labels{/name} languages_url: https://api.github.com/repos/octocat/Hello-World-Template/languages merges_url: https://api.github.com/repos/octocat/Hello-World-Template/merges milestones_url: https://api.github.com/repos/octocat/Hello-World-Template/milestones{/number} notifications_url: https://api.github.com/repos/octocat/Hello-World-Template/notifications{?since,all,participating} pulls_url: https://api.github.com/repos/octocat/Hello-World-Template/pulls{/number} releases_url: https://api.github.com/repos/octocat/Hello-World-Template/releases{/id} ssh_url: git@github.com:octocat/Hello-World-Template.git stargazers_url: https://api.github.com/repos/octocat/Hello-World-Template/stargazers statuses_url: https://api.github.com/repos/octocat/Hello-World-Template/statuses/{sha} subscribers_url: https://api.github.com/repos/octocat/Hello-World-Template/subscribers subscription_url: https://api.github.com/repos/octocat/Hello-World-Template/subscription tags_url: https://api.github.com/repos/octocat/Hello-World-Template/tags teams_url: https://api.github.com/repos/octocat/Hello-World-Template/teams trees_url: https://api.github.com/repos/octocat/Hello-World-Template/git/trees{/sha} clone_url: https://github.com/octocat/Hello-World-Template.git mirror_url: git:git.example.com/octocat/Hello-World-Template hooks_url: https://api.github.com/repos/octocat/Hello-World-Template/hooks svn_url: https://svn.github.com/octocat/Hello-World-Template homepage: https://github.com forks: 9 forks_count: 9 stargazers_count: 80 watchers_count: 80 watchers: 80 size: 108 default_branch: master open_issues: 0 open_issues_count: 0 is_template: true license: key: mit name: MIT License url: https://api.github.com/licenses/mit spdx_id: MIT node_id: MDc6TGljZW5zZW1pdA== html_url: https://api.github.com/licenses/mit topics: - octocat - atom - electron - api has_issues: true has_projects: true has_wiki: true has_pages: false has_downloads: true archived: false disabled: false visibility: public pushed_at: '2011-01-26T19:06:43Z' created_at: '2011-01-26T19:01:12Z' updated_at: '2011-01-26T19:14:43Z' permissions: admin: false push: false pull: true allow_rebase_merge: true temp_clone_token: ABTLWHOULUVAXGTRYU7OC2876QJ2O allow_squash_merge: true delete_branch_on_merge: true allow_merge_commit: true subscribers_count: 42 network_count: 0 owner: login: octocat id: 1 node_id: MDQ6VXNlcjE= avatar_url: https://github.com/images/error/octocat_happy.gif gravatar_id: '' url: https://api.github.com/users/octocat html_url: https://github.com/octocat followers_url: https://api.github.com/users/octocat/followers following_url: https://api.github.com/users/octocat/following{/other_user} gists_url: https://api.github.com/users/octocat/gists{/gist_id} starred_url: https://api.github.com/users/octocat/starred{/owner}{/repo} subscriptions_url: https://api.github.com/users/octocat/subscriptions organizations_url: https://api.github.com/users/octocat/orgs repos_url: https://api.github.com/users/octocat/repos events_url: https://api.github.com/users/octocat/events{/privacy} received_events_url: https://api.github.com/users/octocat/received_events type: User site_admin: false private: false html_url: https://github.com/octocat/Hello-World description: This your first repo! fork: false url: https://api.github.com/repos/octocat/Hello-World archive_url: https://api.github.com/repos/octocat/Hello-World/{archive_format}{/ref} assignees_url: https://api.github.com/repos/octocat/Hello-World/assignees{/user} blobs_url: https://api.github.com/repos/octocat/Hello-World/git/blobs{/sha} branches_url: https://api.github.com/repos/octocat/Hello-World/branches{/branch} collaborators_url: https://api.github.com/repos/octocat/Hello-World/collaborators{/collaborator} comments_url: https://api.github.com/repos/octocat/Hello-World/comments{/number} commits_url: https://api.github.com/repos/octocat/Hello-World/commits{/sha} compare_url: https://api.github.com/repos/octocat/Hello-World/compare/{base}...{head} contents_url: https://api.github.com/repos/octocat/Hello-World/contents/{+path} contributors_url: https://api.github.com/repos/octocat/Hello-World/contributors deployments_url: https://api.github.com/repos/octocat/Hello-World/deployments downloads_url: https://api.github.com/repos/octocat/Hello-World/downloads events_url: https://api.github.com/repos/octocat/Hello-World/events forks_url: https://api.github.com/repos/octocat/Hello-World/forks git_commits_url: https://api.github.com/repos/octocat/Hello-World/git/commits{/sha} git_refs_url: https://api.github.com/repos/octocat/Hello-World/git/refs{/sha} git_tags_url: https://api.github.com/repos/octocat/Hello-World/git/tags{/sha} git_url: git:github.com/octocat/Hello-World.git issue_comment_url: https://api.github.com/repos/octocat/Hello-World/issues/comments{/number} issue_events_url: https://api.github.com/repos/octocat/Hello-World/issues/events{/number} issues_url: https://api.github.com/repos/octocat/Hello-World/issues{/number} keys_url: https://api.github.com/repos/octocat/Hello-World/keys{/key_id} labels_url: https://api.github.com/repos/octocat/Hello-World/labels{/name} languages_url: https://api.github.com/repos/octocat/Hello-World/languages merges_url: https://api.github.com/repos/octocat/Hello-World/merges milestones_url: https://api.github.com/repos/octocat/Hello-World/milestones{/number} notifications_url: https://api.github.com/repos/octocat/Hello-World/notifications{?since,all,participating} pulls_url: https://api.github.com/repos/octocat/Hello-World/pulls{/number} releases_url: https://api.github.com/repos/octocat/Hello-World/releases{/id} ssh_url: git@github.com:octocat/Hello-World.git stargazers_url: https://api.github.com/repos/octocat/Hello-World/stargazers statuses_url: https://api.github.com/repos/octocat/Hello-World/statuses/{sha} subscribers_url: https://api.github.com/repos/octocat/Hello-World/subscribers subscription_url: https://api.github.com/repos/octocat/Hello-World/subscription tags_url: https://api.github.com/repos/octocat/Hello-World/tags teams_url: https://api.github.com/repos/octocat/Hello-World/teams trees_url: https://api.github.com/repos/octocat/Hello-World/git/trees{/sha} clone_url: https://github.com/octocat/Hello-World.git mirror_url: git:git.example.com/octocat/Hello-World hooks_url: https://api.github.com/repos/octocat/Hello-World/hooks svn_url: https://svn.github.com/octocat/Hello-World homepage: https://github.com forks_count: 9 stargazers_count: 80 watchers_count: 80 size: 108 default_branch: master open_issues_count: 0 is_template: false topics: - octocat - atom - electron - api has_issues: true has_projects: true has_wiki: true has_pages: false has_downloads: true archived: false disabled: false visibility: public pushed_at: '2011-01-26T19:06:43Z' created_at: '2011-01-26T19:01:12Z' updated_at: '2011-01-26T19:14:43Z' permissions: admin: false push: false pull: true temp_clone_token: ABTLWHOULUVAXGTRYU7OC2876QJ2O delete_branch_on_merge: true subscribers_count: 42 network_count: 0 head_commit: id: 7fd1a60b01f91b314f59955a4e4d4e80d8edf11d tree_id: 7fd1a60b01f91b314f59955a4e4d4e80d8edf11d message: |- Merge pull request #6 from Spaceghost/patch-1 New line at end of file. timestamp: '2016-10-10T00:00:00Z' author: name: The Octocat email: octocat@nowhere.com committer: name: The Octocat email: octocat@nowhere.com latest_check_runs_count: 1 check_runs_url: https://api.github.com/repos/octocat/Hello-World/check-suites/5/check-runs check-suite-preference: value: preferences: auto_trigger_checks: - app_id: 2 setting: true - app_id: 4 setting: false repository: id: 1296269 node_id: MDEwOlJlcG9zaXRvcnkxMjk2MjY5 name: Hello-World full_name: octocat/Hello-World owner: login: octocat id: 1 node_id: MDQ6VXNlcjE= avatar_url: https://github.com/images/error/octocat_happy.gif gravatar_id: '' url: https://api.github.com/users/octocat html_url: https://github.com/octocat followers_url: https://api.github.com/users/octocat/followers following_url: https://api.github.com/users/octocat/following{/other_user} gists_url: https://api.github.com/users/octocat/gists{/gist_id} starred_url: https://api.github.com/users/octocat/starred{/owner}{/repo} subscriptions_url: https://api.github.com/users/octocat/subscriptions organizations_url: https://api.github.com/users/octocat/orgs repos_url: https://api.github.com/users/octocat/repos events_url: https://api.github.com/users/octocat/events{/privacy} received_events_url: https://api.github.com/users/octocat/received_events type: User site_admin: false private: false html_url: https://github.com/octocat/Hello-World description: This your first repo! fork: false url: https://api.github.com/repos/octocat/Hello-World archive_url: https://api.github.com/repos/octocat/Hello-World/{archive_format}{/ref} assignees_url: https://api.github.com/repos/octocat/Hello-World/assignees{/user} blobs_url: https://api.github.com/repos/octocat/Hello-World/git/blobs{/sha} branches_url: https://api.github.com/repos/octocat/Hello-World/branches{/branch} collaborators_url: https://api.github.com/repos/octocat/Hello-World/collaborators{/collaborator} comments_url: https://api.github.com/repos/octocat/Hello-World/comments{/number} commits_url: https://api.github.com/repos/octocat/Hello-World/commits{/sha} compare_url: https://api.github.com/repos/octocat/Hello-World/compare/{base}...{head} contents_url: https://api.github.com/repos/octocat/Hello-World/contents/{+path} contributors_url: https://api.github.com/repos/octocat/Hello-World/contributors deployments_url: https://api.github.com/repos/octocat/Hello-World/deployments downloads_url: https://api.github.com/repos/octocat/Hello-World/downloads events_url: https://api.github.com/repos/octocat/Hello-World/events forks_url: https://api.github.com/repos/octocat/Hello-World/forks git_commits_url: https://api.github.com/repos/octocat/Hello-World/git/commits{/sha} git_refs_url: https://api.github.com/repos/octocat/Hello-World/git/refs{/sha} git_tags_url: https://api.github.com/repos/octocat/Hello-World/git/tags{/sha} git_url: git:github.com/octocat/Hello-World.git issue_comment_url: https://api.github.com/repos/octocat/Hello-World/issues/comments{/number} issue_events_url: https://api.github.com/repos/octocat/Hello-World/issues/events{/number} issues_url: https://api.github.com/repos/octocat/Hello-World/issues{/number} keys_url: https://api.github.com/repos/octocat/Hello-World/keys{/key_id} labels_url: https://api.github.com/repos/octocat/Hello-World/labels{/name} languages_url: https://api.github.com/repos/octocat/Hello-World/languages merges_url: https://api.github.com/repos/octocat/Hello-World/merges milestones_url: https://api.github.com/repos/octocat/Hello-World/milestones{/number} notifications_url: https://api.github.com/repos/octocat/Hello-World/notifications{?since,all,participating} pulls_url: https://api.github.com/repos/octocat/Hello-World/pulls{/number} releases_url: https://api.github.com/repos/octocat/Hello-World/releases{/id} ssh_url: git@github.com:octocat/Hello-World.git stargazers_url: https://api.github.com/repos/octocat/Hello-World/stargazers statuses_url: https://api.github.com/repos/octocat/Hello-World/statuses/{sha} subscribers_url: https://api.github.com/repos/octocat/Hello-World/subscribers subscription_url: https://api.github.com/repos/octocat/Hello-World/subscription tags_url: https://api.github.com/repos/octocat/Hello-World/tags teams_url: https://api.github.com/repos/octocat/Hello-World/teams trees_url: https://api.github.com/repos/octocat/Hello-World/git/trees{/sha} clone_url: https://github.com/octocat/Hello-World.git mirror_url: git:git.example.com/octocat/Hello-World hooks_url: https://api.github.com/repos/octocat/Hello-World/hooks svn_url: https://svn.github.com/octocat/Hello-World homepage: https://github.com forks_count: 9 stargazers_count: 80 watchers_count: 80 size: 108 default_branch: master open_issues_count: 0 is_template: false topics: - octocat - atom - electron - api has_issues: true has_projects: true has_wiki: true has_pages: false has_downloads: true archived: false disabled: false visibility: public pushed_at: '2011-01-26T19:06:43Z' created_at: '2011-01-26T19:01:12Z' updated_at: '2011-01-26T19:14:43Z' permissions: admin: false push: false pull: true template_repository: id: 1296269 node_id: MDEwOlJlcG9zaXRvcnkxMjk2MjY5 name: Hello-World-Template full_name: octocat/Hello-World-Template owner: login: octocat id: 1 node_id: MDQ6VXNlcjE= avatar_url: https://github.com/images/error/octocat_happy.gif gravatar_id: '' url: https://api.github.com/users/octocat html_url: https://github.com/octocat followers_url: https://api.github.com/users/octocat/followers following_url: https://api.github.com/users/octocat/following{/other_user} gists_url: https://api.github.com/users/octocat/gists{/gist_id} starred_url: https://api.github.com/users/octocat/starred{/owner}{/repo} subscriptions_url: https://api.github.com/users/octocat/subscriptions organizations_url: https://api.github.com/users/octocat/orgs repos_url: https://api.github.com/users/octocat/repos events_url: https://api.github.com/users/octocat/events{/privacy} received_events_url: https://api.github.com/users/octocat/received_events type: User site_admin: false private: false html_url: https://github.com/octocat/Hello-World-Template description: This your first repo! fork: false url: https://api.github.com/repos/octocat/Hello-World-Template archive_url: https://api.github.com/repos/octocat/Hello-World-Template/{archive_format}{/ref} assignees_url: https://api.github.com/repos/octocat/Hello-World-Template/assignees{/user} blobs_url: https://api.github.com/repos/octocat/Hello-World-Template/git/blobs{/sha} branches_url: https://api.github.com/repos/octocat/Hello-World-Template/branches{/branch} collaborators_url: https://api.github.com/repos/octocat/Hello-World-Template/collaborators{/collaborator} comments_url: https://api.github.com/repos/octocat/Hello-World-Template/comments{/number} commits_url: https://api.github.com/repos/octocat/Hello-World-Template/commits{/sha} compare_url: https://api.github.com/repos/octocat/Hello-World-Template/compare/{base}...{head} contents_url: https://api.github.com/repos/octocat/Hello-World-Template/contents/{+path} contributors_url: https://api.github.com/repos/octocat/Hello-World-Template/contributors deployments_url: https://api.github.com/repos/octocat/Hello-World-Template/deployments downloads_url: https://api.github.com/repos/octocat/Hello-World-Template/downloads events_url: https://api.github.com/repos/octocat/Hello-World-Template/events forks_url: https://api.github.com/repos/octocat/Hello-World-Template/forks git_commits_url: https://api.github.com/repos/octocat/Hello-World-Template/git/commits{/sha} git_refs_url: https://api.github.com/repos/octocat/Hello-World-Template/git/refs{/sha} git_tags_url: https://api.github.com/repos/octocat/Hello-World-Template/git/tags{/sha} git_url: git:github.com/octocat/Hello-World-Template.git issue_comment_url: https://api.github.com/repos/octocat/Hello-World-Template/issues/comments{/number} issue_events_url: https://api.github.com/repos/octocat/Hello-World-Template/issues/events{/number} issues_url: https://api.github.com/repos/octocat/Hello-World-Template/issues{/number} keys_url: https://api.github.com/repos/octocat/Hello-World-Template/keys{/key_id} labels_url: https://api.github.com/repos/octocat/Hello-World-Template/labels{/name} languages_url: https://api.github.com/repos/octocat/Hello-World-Template/languages merges_url: https://api.github.com/repos/octocat/Hello-World-Template/merges milestones_url: https://api.github.com/repos/octocat/Hello-World-Template/milestones{/number} notifications_url: https://api.github.com/repos/octocat/Hello-World-Template/notifications{?since,all,participating} pulls_url: https://api.github.com/repos/octocat/Hello-World-Template/pulls{/number} releases_url: https://api.github.com/repos/octocat/Hello-World-Template/releases{/id} ssh_url: git@github.com:octocat/Hello-World-Template.git stargazers_url: https://api.github.com/repos/octocat/Hello-World-Template/stargazers statuses_url: https://api.github.com/repos/octocat/Hello-World-Template/statuses/{sha} subscribers_url: https://api.github.com/repos/octocat/Hello-World-Template/subscribers subscription_url: https://api.github.com/repos/octocat/Hello-World-Template/subscription tags_url: https://api.github.com/repos/octocat/Hello-World-Template/tags teams_url: https://api.github.com/repos/octocat/Hello-World-Template/teams trees_url: https://api.github.com/repos/octocat/Hello-World-Template/git/trees{/sha} clone_url: https://github.com/octocat/Hello-World-Template.git mirror_url: git:git.example.com/octocat/Hello-World-Template hooks_url: https://api.github.com/repos/octocat/Hello-World-Template/hooks svn_url: https://svn.github.com/octocat/Hello-World-Template homepage: https://github.com forks: 9 forks_count: 9 stargazers_count: 80 watchers_count: 80 watchers: 80 size: 108 default_branch: master open_issues: 0 open_issues_count: 0 is_template: true license: key: mit name: MIT License url: https://api.github.com/licenses/mit spdx_id: MIT node_id: MDc6TGljZW5zZW1pdA== html_url: https://api.github.com/licenses/mit topics: - octocat - atom - electron - api has_issues: true has_projects: true has_wiki: true has_pages: false has_downloads: true archived: false disabled: false visibility: public pushed_at: '2011-01-26T19:06:43Z' created_at: '2011-01-26T19:01:12Z' updated_at: '2011-01-26T19:14:43Z' permissions: admin: false push: false pull: true allow_rebase_merge: true temp_clone_token: ABTLWHOULUVAXGTRYU7OC2876QJ2O allow_squash_merge: true delete_branch_on_merge: true allow_merge_commit: true subscribers_count: 42 network_count: 0 check-run-paginated: value: total_count: 1 check_runs: - id: 4 head_sha: ce587453ced02b1526dfb4cb910479d431683101 node_id: MDg6Q2hlY2tSdW40 external_id: '' url: https://api.github.com/repos/github/hello-world/check-runs/4 html_url: https://github.com/github/hello-world/runs/4 details_url: https://example.com status: completed conclusion: neutral started_at: '2018-05-04T01:14:52Z' completed_at: '2018-05-04T01:14:52Z' output: title: Mighty Readme report summary: There are 0 failures, 2 warnings, and 1 notice. text: You may have some misspelled words on lines 2 and 4. You also may want to add a section in your README about how to install your app. annotations_count: 2 annotations_url: https://api.github.com/repos/github/hello-world/check-runs/4/annotations name: mighty_readme check_suite: id: 5 app: id: 1 slug: octoapp node_id: MDExOkludGVncmF0aW9uMQ== owner: login: github id: 1 node_id: MDEyOk9yZ2FuaXphdGlvbjE= url: https://api.github.com/orgs/github repos_url: https://api.github.com/orgs/github/repos events_url: https://api.github.com/orgs/github/events avatar_url: https://github.com/images/error/octocat_happy.gif gravatar_id: '' html_url: https://github.com/octocat followers_url: https://api.github.com/users/octocat/followers following_url: https://api.github.com/users/octocat/following{/other_user} gists_url: https://api.github.com/users/octocat/gists{/gist_id} starred_url: https://api.github.com/users/octocat/starred{/owner}{/repo} subscriptions_url: https://api.github.com/users/octocat/subscriptions organizations_url: https://api.github.com/users/octocat/orgs received_events_url: https://api.github.com/users/octocat/received_events type: User site_admin: true name: Octocat App description: '' external_url: https://example.com html_url: https://github.com/apps/octoapp created_at: '2017-07-08T16:18:44-04:00' updated_at: '2017-07-08T16:18:44-04:00' permissions: metadata: read contents: read issues: write single_file: write events: - push - pull_request pull_requests: - url: https://api.github.com/repos/github/hello-world/pulls/1 id: 1934 number: 3956 head: ref: say-hello sha: 3dca65fa3e8d4b3da3f3d056c59aee1c50f41390 repo: id: 526 url: https://api.github.com/repos/github/hello-world name: hello-world base: ref: master sha: e7fdf7640066d71ad16a86fbcbb9c6a10a18af4f repo: id: 526 url: https://api.github.com/repos/github/hello-world name: hello-world code-scanning-alert-items: value: - number: 4 created_at: '2020-02-13T12:29:18Z' url: https://api.github.com/repos/octocat/hello-world/code-scanning/alerts/4 html_url: https://github.com/octocat/hello-world/code-scanning/4 state: open dismissed_by: dismissed_at: dismissed_reason: rule: id: js/zipslip severity: error description: Arbitrary file write during zip extraction name: js/zipslip tool: name: CodeQL guid: version: 2.4.0 most_recent_instance: ref: refs/heads/main analysis_key: ".github/workflows/codeql-analysis.yml:CodeQL-Build" environment: "{}" state: open commit_sha: 39406e42cb832f683daa691dd652a8dc36ee8930 message: text: This path depends on a user-provided value. location: path: spec-main/api-session-spec.ts start_line: 917 end_line: 917 start_column: 7 end_column: 18 classifications: - test instances_url: https://api.github.com/repos/octocat/hello-world/code-scanning/alerts/4/instances - number: 3 created_at: '2020-02-13T12:29:18Z' url: https://api.github.com/repos/octocat/hello-world/code-scanning/alerts/3 html_url: https://github.com/octocat/hello-world/code-scanning/3 state: dismissed dismissed_by: login: octocat id: 1 node_id: MDQ6VXNlcjE= avatar_url: https://github.com/images/error/octocat_happy.gif gravatar_id: '' url: https://api.github.com/users/octocat html_url: https://github.com/octocat followers_url: https://api.github.com/users/octocat/followers following_url: https://api.github.com/users/octocat/following{/other_user} gists_url: https://api.github.com/users/octocat/gists{/gist_id} starred_url: https://api.github.com/users/octocat/starred{/owner}{/repo} subscriptions_url: https://api.github.com/users/octocat/subscriptions organizations_url: https://api.github.com/users/octocat/orgs repos_url: https://api.github.com/users/octocat/repos events_url: https://api.github.com/users/octocat/events{/privacy} received_events_url: https://api.github.com/users/octocat/received_events type: User site_admin: false dismissed_at: '2020-02-14T12:29:18Z' dismissed_reason: false positive rule: id: js/zipslip severity: error description: Arbitrary file write during zip extraction name: js/zipslip tool: name: CodeQL guid: version: 2.4.0 most_recent_instance: ref: refs/heads/main analysis_key: ".github/workflows/codeql-analysis.yml:CodeQL-Build" environment: "{}" state: open commit_sha: 39406e42cb832f683daa691dd652a8dc36ee8930 message: text: This path depends on a user-provided value. location: path: lib/ab12-gen.js start_line: 917 end_line: 917 start_column: 7 end_column: 18 classifications: [] instances_url: https://api.github.com/repos/octocat/hello-world/code-scanning/alerts/3/instances code-scanning-alert: value: number: 42 created_at: '2020-06-19T11:21:34Z' url: https://api.github.com/repos/octocat/hello-world/code-scanning/alerts/42 html_url: https://github.com/octocat/hello-world/code-scanning/42 state: dismissed dismissed_by: login: octocat id: 54933897 node_id: MDQ6VXNlcjE= avatar_url: https://github.com/images/error/octocat_happy.gif gravatar_id: '' url: https://api.github.com/users/octocat html_url: https://github.com/octocat followers_url: https://api.github.com/users/octocat/followers following_url: https://api.github.com/users/octocat/following{/other_user} gists_url: https://api.github.com/users/octocat/gists{/gist_id} starred_url: https://api.github.com/users/octocat/starred{/owner}{/repo} subscriptions_url: https://api.github.com/users/octocat/subscriptions organizations_url: https://api.github.com/users/octocat/orgs repos_url: https://api.github.com/users/octocat/repos events_url: https://api.github.com/users/octocat/events{/privacy} received_events_url: https://api.github.com/users/octocat/received_events type: User site_admin: false dismissed_at: '2020-02-14T12:29:18Z' dismissed_reason: false positive rule: id: js/zipslip severity: error description: Arbitrary file write during zip extraction ("Zip Slip") name: js/zipslip full_description: Extracting files from a malicious zip archive without validating that the destination file path is within the destination directory can cause files outside the destination directory to be overwritten. tags: - security - external/cwe/cwe-022 help: '# Arbitrary file write during zip extraction ("Zip Slip")\nExtracting files from a malicious zip archive without validating that the destination file path is within the destination directory can cause files outside the destination directory to be overwritten ...' tool: name: CodeQL guid: version: 2.4.0 most_recent_instance: ref: refs/heads/main analysis_key: ".github/workflows/codeql-analysis.yml:CodeQL-Build" environment: "{}" state: dismissed commit_sha: 39406e42cb832f683daa691dd652a8dc36ee8930 message: text: This path depends on a user-provided value. location: path: spec-main/api-session-spec.ts start_line: 917 end_line: 917 start_column: 7 end_column: 18 classifications: - test instances_url: https://api.github.com/repos/octocat/hello-world/code-scanning/alerts/42/instances code-scanning-alert-dismissed: value: number: 42 created_at: '2020-08-25T21:28:36Z' url: https://api.github.com/repos/octocat/hello-world/code-scanning/alerts/42 html_url: https://github.com/octocat/hello-world/code-scanning/42 state: dismissed dismissed_by: login: octocat id: 1 node_id: MDQ6VXNlcjE= avatar_url: https://github.com/images/error/octocat_happy.gif gravatar_id: '' url: https://api.github.com/users/octocat html_url: https://github.com/octocat followers_url: https://api.github.com/users/octocat/followers following_url: https://api.github.com/users/octocat/following{/other_user} gists_url: https://api.github.com/users/octocat/gists{/gist_id} starred_url: https://api.github.com/users/octocat/starred{/owner}{/repo} subscriptions_url: https://api.github.com/users/octocat/subscriptions organizations_url: https://api.github.com/users/octocat/orgs repos_url: https://api.github.com/users/octocat/repos events_url: https://api.github.com/users/octocat/events{/privacy} received_events_url: https://api.github.com/users/octocat/received_events type: User site_admin: false dismissed_at: '2020-09-02T22:34:56Z' dismissed_reason: false positive rule: id: js/zipslip severity: error description: Arbitrary file write during zip extraction ("Zip Slip") name: js/zipslip full_description: Extracting files from a malicious zip archive without validating that the destination file path is within the destination directory can cause files outside the destination directory to be overwritten. tags: - security - external/cwe/cwe-022 help: '# Arbitrary file write during zip extraction ("Zip Slip")\nExtracting files from a malicious zip archive without validating that the destination file path is within the destination directory can cause files outside the destination directory to be overwritten ...' tool: name: CodeQL guid: version: 2.4.0 most_recent_instance: ref: refs/heads/main analysis_key: ".github/workflows/codeql-analysis.yml:CodeQL-Build" environment: "{}" state: dismissed commit_sha: 39406e42cb832f683daa691dd652a8dc36ee8930 message: text: This path depends on a user-provided value. location: path: spec-main/api-session-spec.ts start_line: 917 end_line: 917 start_column: 7 end_column: 18 classifications: - test instances_url: https://api.github.com/repos/octocat/hello-world/code-scanning/alerts/42/instances code-scanning-analysis-items: value: - ref: refs/heads/main commit_sha: d99612c3e1f2970085cfbaeadf8f010ef69bad83 analysis_key: ".github/workflows/codeql-analysis.yml:analyze" environment: '{"language":"python"}' error: '' category: ".github/workflows/codeql-analysis.yml:analyze/language:python" created_at: '2020-08-27T15:05:21Z' results_count: 17 rules_count: 49 id: 201 url: https://api.github.com/repos/octocat/hello-world/code-scanning/analyses/201 sarif_id: 6c81cd8e-b078-4ac3-a3be-1dad7dbd0b53 tool: name: CodeQL guid: version: 2.4.0 deletable: true warning: '' - ref: refs/heads/my-branch commit_sha: c8cff6510d4d084fb1b4aa13b64b97ca12b07321 analysis_key: ".github/workflows/shiftleft.yml:build" environment: "{}" error: '' category: ".github/workflows/shiftleft.yml:build/" created_at: '2020-08-31T22:46:44Z' results_count: 17 rules_count: 32 id: 200 url: https://api.github.com/repos/octocat/hello-world/code-scanning/analyses/200 sarif_id: 8981cd8e-b078-4ac3-a3be-1dad7dbd0b582 tool: name: Python Security Analysis guid: version: 1.2.0 deletable: true warning: '' code-scanning-sarif-upload: summary: Default response value: id: 47177e22-5596-11eb-80a1-c1e54ef945c6 url: https://api.github.com/repos/octocat/hello-world/code-scanning/sarifs/47177e22-5596-11eb-80a1-c1e54ef945c6 collaborator-items: value: - login: octocat id: 1 node_id: MDQ6VXNlcjE= avatar_url: https://github.com/images/error/octocat_happy.gif gravatar_id: '' url: https://api.github.com/users/octocat html_url: https://github.com/octocat followers_url: https://api.github.com/users/octocat/followers following_url: https://api.github.com/users/octocat/following{/other_user} gists_url: https://api.github.com/users/octocat/gists{/gist_id} starred_url: https://api.github.com/users/octocat/starred{/owner}{/repo} subscriptions_url: https://api.github.com/users/octocat/subscriptions organizations_url: https://api.github.com/users/octocat/orgs repos_url: https://api.github.com/users/octocat/repos events_url: https://api.github.com/users/octocat/events{/privacy} received_events_url: https://api.github.com/users/octocat/received_events type: User site_admin: false permissions: pull: true push: true admin: false repository-invitation-response-when-a-new-invitation-is-created: value: id: 1 node_id: MDEwOlJlcG9zaXRvcnkxMjk2MjY5 repository: id: 1296269 node_id: MDEwOlJlcG9zaXRvcnkxMjk2MjY5 name: Hello-World full_name: octocat/Hello-World owner: login: octocat id: 1 node_id: MDQ6VXNlcjE= avatar_url: https://github.com/images/error/octocat_happy.gif gravatar_id: '' url: https://api.github.com/users/octocat html_url: https://github.com/octocat followers_url: https://api.github.com/users/octocat/followers following_url: https://api.github.com/users/octocat/following{/other_user} gists_url: https://api.github.com/users/octocat/gists{/gist_id} starred_url: https://api.github.com/users/octocat/starred{/owner}{/repo} subscriptions_url: https://api.github.com/users/octocat/subscriptions organizations_url: https://api.github.com/users/octocat/orgs repos_url: https://api.github.com/users/octocat/repos events_url: https://api.github.com/users/octocat/events{/privacy} received_events_url: https://api.github.com/users/octocat/received_events type: User site_admin: false private: false html_url: https://github.com/octocat/Hello-World description: This your first repo! fork: false url: https://api.github.com/repos/octocat/Hello-World archive_url: https://api.github.com/repos/octocat/Hello-World/{archive_format}{/ref} assignees_url: https://api.github.com/repos/octocat/Hello-World/assignees{/user} blobs_url: https://api.github.com/repos/octocat/Hello-World/git/blobs{/sha} branches_url: https://api.github.com/repos/octocat/Hello-World/branches{/branch} collaborators_url: https://api.github.com/repos/octocat/Hello-World/collaborators{/collaborator} comments_url: https://api.github.com/repos/octocat/Hello-World/comments{/number} commits_url: https://api.github.com/repos/octocat/Hello-World/commits{/sha} compare_url: https://api.github.com/repos/octocat/Hello-World/compare/{base}...{head} contents_url: https://api.github.com/repos/octocat/Hello-World/contents/{+path} contributors_url: https://api.github.com/repos/octocat/Hello-World/contributors deployments_url: https://api.github.com/repos/octocat/Hello-World/deployments downloads_url: https://api.github.com/repos/octocat/Hello-World/downloads events_url: https://api.github.com/repos/octocat/Hello-World/events forks_url: https://api.github.com/repos/octocat/Hello-World/forks git_commits_url: https://api.github.com/repos/octocat/Hello-World/git/commits{/sha} git_refs_url: https://api.github.com/repos/octocat/Hello-World/git/refs{/sha} git_tags_url: https://api.github.com/repos/octocat/Hello-World/git/tags{/sha} git_url: git:github.com/octocat/Hello-World.git issue_comment_url: https://api.github.com/repos/octocat/Hello-World/issues/comments{/number} issue_events_url: https://api.github.com/repos/octocat/Hello-World/issues/events{/number} issues_url: https://api.github.com/repos/octocat/Hello-World/issues{/number} keys_url: https://api.github.com/repos/octocat/Hello-World/keys{/key_id} labels_url: https://api.github.com/repos/octocat/Hello-World/labels{/name} languages_url: https://api.github.com/repos/octocat/Hello-World/languages merges_url: https://api.github.com/repos/octocat/Hello-World/merges milestones_url: https://api.github.com/repos/octocat/Hello-World/milestones{/number} notifications_url: https://api.github.com/repos/octocat/Hello-World/notifications{?since,all,participating} pulls_url: https://api.github.com/repos/octocat/Hello-World/pulls{/number} releases_url: https://api.github.com/repos/octocat/Hello-World/releases{/id} ssh_url: git@github.com:octocat/Hello-World.git stargazers_url: https://api.github.com/repos/octocat/Hello-World/stargazers statuses_url: https://api.github.com/repos/octocat/Hello-World/statuses/{sha} subscribers_url: https://api.github.com/repos/octocat/Hello-World/subscribers subscription_url: https://api.github.com/repos/octocat/Hello-World/subscription tags_url: https://api.github.com/repos/octocat/Hello-World/tags teams_url: https://api.github.com/repos/octocat/Hello-World/teams trees_url: https://api.github.com/repos/octocat/Hello-World/git/trees{/sha} hooks_url: http://api.github.com/repos/octocat/Hello-World/hooks invitee: login: octocat id: 1 node_id: MDQ6VXNlcjE= avatar_url: https://github.com/images/error/octocat_happy.gif gravatar_id: '' url: https://api.github.com/users/octocat html_url: https://github.com/octocat followers_url: https://api.github.com/users/octocat/followers following_url: https://api.github.com/users/octocat/following{/other_user} gists_url: https://api.github.com/users/octocat/gists{/gist_id} starred_url: https://api.github.com/users/octocat/starred{/owner}{/repo} subscriptions_url: https://api.github.com/users/octocat/subscriptions organizations_url: https://api.github.com/users/octocat/orgs repos_url: https://api.github.com/users/octocat/repos events_url: https://api.github.com/users/octocat/events{/privacy} received_events_url: https://api.github.com/users/octocat/received_events type: User site_admin: false inviter: login: octocat id: 1 node_id: MDQ6VXNlcjE= avatar_url: https://github.com/images/error/octocat_happy.gif gravatar_id: '' url: https://api.github.com/users/octocat html_url: https://github.com/octocat followers_url: https://api.github.com/users/octocat/followers following_url: https://api.github.com/users/octocat/following{/other_user} gists_url: https://api.github.com/users/octocat/gists{/gist_id} starred_url: https://api.github.com/users/octocat/starred{/owner}{/repo} subscriptions_url: https://api.github.com/users/octocat/subscriptions organizations_url: https://api.github.com/users/octocat/orgs repos_url: https://api.github.com/users/octocat/repos events_url: https://api.github.com/users/octocat/events{/privacy} received_events_url: https://api.github.com/users/octocat/received_events type: User site_admin: false permissions: write created_at: '2016-06-13T14:52:50-05:00' url: https://api.github.com/user/repository_invitations/1296269 html_url: https://github.com/octocat/Hello-World/invitations repository-collaborator-permission-response-if-user-has-admin-permissions: value: permission: admin user: login: octocat id: 1 node_id: MDQ6VXNlcjE= avatar_url: https://github.com/images/error/octocat_happy.gif gravatar_id: '' url: https://api.github.com/users/octocat html_url: https://github.com/octocat followers_url: https://api.github.com/users/octocat/followers following_url: https://api.github.com/users/octocat/following{/other_user} gists_url: https://api.github.com/users/octocat/gists{/gist_id} starred_url: https://api.github.com/users/octocat/starred{/owner}{/repo} subscriptions_url: https://api.github.com/users/octocat/subscriptions organizations_url: https://api.github.com/users/octocat/orgs repos_url: https://api.github.com/users/octocat/repos events_url: https://api.github.com/users/octocat/events{/privacy} received_events_url: https://api.github.com/users/octocat/received_events type: User site_admin: false commit-comment-items: value: - html_url: https://github.com/octocat/Hello-World/commit/6dcb09b5b57875f334f61aebed695e2e4193db5e#commitcomment-1 url: https://api.github.com/repos/octocat/Hello-World/comments/1 id: 1 node_id: MDEzOkNvbW1pdENvbW1lbnQx body: Great stuff path: file1.txt position: 4 line: 14 commit_id: 6dcb09b5b57875f334f61aebed695e2e4193db5e user: login: octocat id: 1 node_id: MDQ6VXNlcjE= avatar_url: https://github.com/images/error/octocat_happy.gif gravatar_id: '' url: https://api.github.com/users/octocat html_url: https://github.com/octocat followers_url: https://api.github.com/users/octocat/followers following_url: https://api.github.com/users/octocat/following{/other_user} gists_url: https://api.github.com/users/octocat/gists{/gist_id} starred_url: https://api.github.com/users/octocat/starred{/owner}{/repo} subscriptions_url: https://api.github.com/users/octocat/subscriptions organizations_url: https://api.github.com/users/octocat/orgs repos_url: https://api.github.com/users/octocat/repos events_url: https://api.github.com/users/octocat/events{/privacy} received_events_url: https://api.github.com/users/octocat/received_events type: User site_admin: false created_at: '2011-04-14T16:00:49Z' updated_at: '2011-04-14T16:00:49Z' author_association: COLLABORATOR commit-comment: value: html_url: https://github.com/octocat/Hello-World/commit/6dcb09b5b57875f334f61aebed695e2e4193db5e#commitcomment-1 url: https://api.github.com/repos/octocat/Hello-World/comments/1 id: 1 node_id: MDEzOkNvbW1pdENvbW1lbnQx body: Great stuff path: file1.txt position: 4 line: 14 commit_id: 6dcb09b5b57875f334f61aebed695e2e4193db5e author_association: COLLABORATOR user: login: octocat id: 1 node_id: MDQ6VXNlcjE= avatar_url: https://github.com/images/error/octocat_happy.gif gravatar_id: '' url: https://api.github.com/users/octocat html_url: https://github.com/octocat followers_url: https://api.github.com/users/octocat/followers following_url: https://api.github.com/users/octocat/following{/other_user} gists_url: https://api.github.com/users/octocat/gists{/gist_id} starred_url: https://api.github.com/users/octocat/starred{/owner}{/repo} subscriptions_url: https://api.github.com/users/octocat/subscriptions organizations_url: https://api.github.com/users/octocat/orgs repos_url: https://api.github.com/users/octocat/repos events_url: https://api.github.com/users/octocat/events{/privacy} received_events_url: https://api.github.com/users/octocat/received_events type: User site_admin: false created_at: '2011-04-14T16:00:49Z' updated_at: '2011-04-14T16:00:49Z' commit-comment-2: value: html_url: https://github.com/octocat/Hello-World/commit/6dcb09b5b57875f334f61aebed695e2e4193db5e#commitcomment-1 url: https://api.github.com/repos/octocat/Hello-World/comments/1 id: 1 node_id: MDEzOkNvbW1pdENvbW1lbnQx body: Nice change path: file1.txt position: 4 line: 14 commit_id: 6dcb09b5b57875f334f61aebed695e2e4193db5e author_association: COLLABORATOR user: login: octocat id: 1 node_id: MDQ6VXNlcjE= avatar_url: https://github.com/images/error/octocat_happy.gif gravatar_id: '' url: https://api.github.com/users/octocat html_url: https://github.com/octocat followers_url: https://api.github.com/users/octocat/followers following_url: https://api.github.com/users/octocat/following{/other_user} gists_url: https://api.github.com/users/octocat/gists{/gist_id} starred_url: https://api.github.com/users/octocat/starred{/owner}{/repo} subscriptions_url: https://api.github.com/users/octocat/subscriptions organizations_url: https://api.github.com/users/octocat/orgs repos_url: https://api.github.com/users/octocat/repos events_url: https://api.github.com/users/octocat/events{/privacy} received_events_url: https://api.github.com/users/octocat/received_events type: User site_admin: false created_at: '2011-04-14T16:00:49Z' updated_at: '2011-04-14T16:00:49Z' commit-items: value: - url: https://api.github.com/repos/octocat/Hello-World/commits/6dcb09b5b57875f334f61aebed695e2e4193db5e sha: 6dcb09b5b57875f334f61aebed695e2e4193db5e node_id: MDY6Q29tbWl0NmRjYjA5YjViNTc4NzVmMzM0ZjYxYWViZWQ2OTVlMmU0MTkzZGI1ZQ== html_url: https://github.com/octocat/Hello-World/commit/6dcb09b5b57875f334f61aebed695e2e4193db5e comments_url: https://api.github.com/repos/octocat/Hello-World/commits/6dcb09b5b57875f334f61aebed695e2e4193db5e/comments commit: url: https://api.github.com/repos/octocat/Hello-World/git/commits/6dcb09b5b57875f334f61aebed695e2e4193db5e author: name: Monalisa Octocat email: support@github.com date: '2011-04-14T16:00:49Z' committer: name: Monalisa Octocat email: support@github.com date: '2011-04-14T16:00:49Z' message: Fix all the bugs tree: url: https://api.github.com/repos/octocat/Hello-World/tree/6dcb09b5b57875f334f61aebed695e2e4193db5e sha: 6dcb09b5b57875f334f61aebed695e2e4193db5e comment_count: 0 verification: verified: false reason: unsigned signature: payload: author: login: octocat id: 1 node_id: MDQ6VXNlcjE= avatar_url: https://github.com/images/error/octocat_happy.gif gravatar_id: '' url: https://api.github.com/users/octocat html_url: https://github.com/octocat followers_url: https://api.github.com/users/octocat/followers following_url: https://api.github.com/users/octocat/following{/other_user} gists_url: https://api.github.com/users/octocat/gists{/gist_id} starred_url: https://api.github.com/users/octocat/starred{/owner}{/repo} subscriptions_url: https://api.github.com/users/octocat/subscriptions organizations_url: https://api.github.com/users/octocat/orgs repos_url: https://api.github.com/users/octocat/repos events_url: https://api.github.com/users/octocat/events{/privacy} received_events_url: https://api.github.com/users/octocat/received_events type: User site_admin: false committer: login: octocat id: 1 node_id: MDQ6VXNlcjE= avatar_url: https://github.com/images/error/octocat_happy.gif gravatar_id: '' url: https://api.github.com/users/octocat html_url: https://github.com/octocat followers_url: https://api.github.com/users/octocat/followers following_url: https://api.github.com/users/octocat/following{/other_user} gists_url: https://api.github.com/users/octocat/gists{/gist_id} starred_url: https://api.github.com/users/octocat/starred{/owner}{/repo} subscriptions_url: https://api.github.com/users/octocat/subscriptions organizations_url: https://api.github.com/users/octocat/orgs repos_url: https://api.github.com/users/octocat/repos events_url: https://api.github.com/users/octocat/events{/privacy} received_events_url: https://api.github.com/users/octocat/received_events type: User site_admin: false parents: - url: https://api.github.com/repos/octocat/Hello-World/commits/6dcb09b5b57875f334f61aebed695e2e4193db5e sha: 6dcb09b5b57875f334f61aebed695e2e4193db5e branch-short-items: value: - name: branch_5 commit: sha: c5b97d5ae6c19d5c5df71a34c7fbeeda2479ccbc url: https://api.github.com/repos/octocat/Hello-World/commits/c5b97d5ae6c19d5c5df71a34c7fbeeda2479ccbc protected: false pull-request-simple-items: value: - url: https://api.github.com/repos/octocat/Hello-World/pulls/1347 id: 1 node_id: MDExOlB1bGxSZXF1ZXN0MQ== html_url: https://github.com/octocat/Hello-World/pull/1347 diff_url: https://github.com/octocat/Hello-World/pull/1347.diff patch_url: https://github.com/octocat/Hello-World/pull/1347.patch issue_url: https://api.github.com/repos/octocat/Hello-World/issues/1347 commits_url: https://api.github.com/repos/octocat/Hello-World/pulls/1347/commits review_comments_url: https://api.github.com/repos/octocat/Hello-World/pulls/1347/comments review_comment_url: https://api.github.com/repos/octocat/Hello-World/pulls/comments{/number} comments_url: https://api.github.com/repos/octocat/Hello-World/issues/1347/comments statuses_url: https://api.github.com/repos/octocat/Hello-World/statuses/6dcb09b5b57875f334f61aebed695e2e4193db5e number: 1347 state: open locked: true title: Amazing new feature user: login: octocat id: 1 node_id: MDQ6VXNlcjE= avatar_url: https://github.com/images/error/octocat_happy.gif gravatar_id: '' url: https://api.github.com/users/octocat html_url: https://github.com/octocat followers_url: https://api.github.com/users/octocat/followers following_url: https://api.github.com/users/octocat/following{/other_user} gists_url: https://api.github.com/users/octocat/gists{/gist_id} starred_url: https://api.github.com/users/octocat/starred{/owner}{/repo} subscriptions_url: https://api.github.com/users/octocat/subscriptions organizations_url: https://api.github.com/users/octocat/orgs repos_url: https://api.github.com/users/octocat/repos events_url: https://api.github.com/users/octocat/events{/privacy} received_events_url: https://api.github.com/users/octocat/received_events type: User site_admin: false body: Please pull these awesome changes in! labels: - id: 208045946 node_id: MDU6TGFiZWwyMDgwNDU5NDY= url: https://api.github.com/repos/octocat/Hello-World/labels/bug name: bug description: Something isn't working color: f29513 default: true milestone: url: https://api.github.com/repos/octocat/Hello-World/milestones/1 html_url: https://github.com/octocat/Hello-World/milestones/v1.0 labels_url: https://api.github.com/repos/octocat/Hello-World/milestones/1/labels id: 1002604 node_id: MDk6TWlsZXN0b25lMTAwMjYwNA== number: 1 state: open title: v1.0 description: Tracking milestone for version 1.0 creator: login: octocat id: 1 node_id: MDQ6VXNlcjE= avatar_url: https://github.com/images/error/octocat_happy.gif gravatar_id: '' url: https://api.github.com/users/octocat html_url: https://github.com/octocat followers_url: https://api.github.com/users/octocat/followers following_url: https://api.github.com/users/octocat/following{/other_user} gists_url: https://api.github.com/users/octocat/gists{/gist_id} starred_url: https://api.github.com/users/octocat/starred{/owner}{/repo} subscriptions_url: https://api.github.com/users/octocat/subscriptions organizations_url: https://api.github.com/users/octocat/orgs repos_url: https://api.github.com/users/octocat/repos events_url: https://api.github.com/users/octocat/events{/privacy} received_events_url: https://api.github.com/users/octocat/received_events type: User site_admin: false open_issues: 4 closed_issues: 8 created_at: '2011-04-10T20:09:31Z' updated_at: '2014-03-03T18:58:10Z' closed_at: '2013-02-12T13:22:01Z' due_on: '2012-10-09T23:39:01Z' active_lock_reason: too heated created_at: '2011-01-26T19:01:12Z' updated_at: '2011-01-26T19:01:12Z' closed_at: '2011-01-26T19:01:12Z' merged_at: '2011-01-26T19:01:12Z' merge_commit_sha: e5bd3914e2e596debea16f433f57875b5b90bcd6 assignee: login: octocat id: 1 node_id: MDQ6VXNlcjE= avatar_url: https://github.com/images/error/octocat_happy.gif gravatar_id: '' url: https://api.github.com/users/octocat html_url: https://github.com/octocat followers_url: https://api.github.com/users/octocat/followers following_url: https://api.github.com/users/octocat/following{/other_user} gists_url: https://api.github.com/users/octocat/gists{/gist_id} starred_url: https://api.github.com/users/octocat/starred{/owner}{/repo} subscriptions_url: https://api.github.com/users/octocat/subscriptions organizations_url: https://api.github.com/users/octocat/orgs repos_url: https://api.github.com/users/octocat/repos events_url: https://api.github.com/users/octocat/events{/privacy} received_events_url: https://api.github.com/users/octocat/received_events type: User site_admin: false assignees: - login: octocat id: 1 node_id: MDQ6VXNlcjE= avatar_url: https://github.com/images/error/octocat_happy.gif gravatar_id: '' url: https://api.github.com/users/octocat html_url: https://github.com/octocat followers_url: https://api.github.com/users/octocat/followers following_url: https://api.github.com/users/octocat/following{/other_user} gists_url: https://api.github.com/users/octocat/gists{/gist_id} starred_url: https://api.github.com/users/octocat/starred{/owner}{/repo} subscriptions_url: https://api.github.com/users/octocat/subscriptions organizations_url: https://api.github.com/users/octocat/orgs repos_url: https://api.github.com/users/octocat/repos events_url: https://api.github.com/users/octocat/events{/privacy} received_events_url: https://api.github.com/users/octocat/received_events type: User site_admin: false - login: hubot id: 1 node_id: MDQ6VXNlcjE= avatar_url: https://github.com/images/error/hubot_happy.gif gravatar_id: '' url: https://api.github.com/users/hubot html_url: https://github.com/hubot followers_url: https://api.github.com/users/hubot/followers following_url: https://api.github.com/users/hubot/following{/other_user} gists_url: https://api.github.com/users/hubot/gists{/gist_id} starred_url: https://api.github.com/users/hubot/starred{/owner}{/repo} subscriptions_url: https://api.github.com/users/hubot/subscriptions organizations_url: https://api.github.com/users/hubot/orgs repos_url: https://api.github.com/users/hubot/repos events_url: https://api.github.com/users/hubot/events{/privacy} received_events_url: https://api.github.com/users/hubot/received_events type: User site_admin: true requested_reviewers: - login: other_user id: 1 node_id: MDQ6VXNlcjE= avatar_url: https://github.com/images/error/other_user_happy.gif gravatar_id: '' url: https://api.github.com/users/other_user html_url: https://github.com/other_user followers_url: https://api.github.com/users/other_user/followers following_url: https://api.github.com/users/other_user/following{/other_user} gists_url: https://api.github.com/users/other_user/gists{/gist_id} starred_url: https://api.github.com/users/other_user/starred{/owner}{/repo} subscriptions_url: https://api.github.com/users/other_user/subscriptions organizations_url: https://api.github.com/users/other_user/orgs repos_url: https://api.github.com/users/other_user/repos events_url: https://api.github.com/users/other_user/events{/privacy} received_events_url: https://api.github.com/users/other_user/received_events type: User site_admin: false requested_teams: - id: 1 node_id: MDQ6VGVhbTE= url: https://api.github.com/teams/1 html_url: https://github.com/orgs/github/teams/justice-league name: Justice League slug: justice-league description: A great team. privacy: closed permission: admin members_url: https://api.github.com/teams/1/members{/member} repositories_url: https://api.github.com/teams/1/repos head: label: octocat:new-topic ref: new-topic sha: 6dcb09b5b57875f334f61aebed695e2e4193db5e user: login: octocat id: 1 node_id: MDQ6VXNlcjE= avatar_url: https://github.com/images/error/octocat_happy.gif gravatar_id: '' url: https://api.github.com/users/octocat html_url: https://github.com/octocat followers_url: https://api.github.com/users/octocat/followers following_url: https://api.github.com/users/octocat/following{/other_user} gists_url: https://api.github.com/users/octocat/gists{/gist_id} starred_url: https://api.github.com/users/octocat/starred{/owner}{/repo} subscriptions_url: https://api.github.com/users/octocat/subscriptions organizations_url: https://api.github.com/users/octocat/orgs repos_url: https://api.github.com/users/octocat/repos events_url: https://api.github.com/users/octocat/events{/privacy} received_events_url: https://api.github.com/users/octocat/received_events type: User site_admin: false repo: id: 1296269 node_id: MDEwOlJlcG9zaXRvcnkxMjk2MjY5 name: Hello-World full_name: octocat/Hello-World owner: login: octocat id: 1 node_id: MDQ6VXNlcjE= avatar_url: https://github.com/images/error/octocat_happy.gif gravatar_id: '' url: https://api.github.com/users/octocat html_url: https://github.com/octocat followers_url: https://api.github.com/users/octocat/followers following_url: https://api.github.com/users/octocat/following{/other_user} gists_url: https://api.github.com/users/octocat/gists{/gist_id} starred_url: https://api.github.com/users/octocat/starred{/owner}{/repo} subscriptions_url: https://api.github.com/users/octocat/subscriptions organizations_url: https://api.github.com/users/octocat/orgs repos_url: https://api.github.com/users/octocat/repos events_url: https://api.github.com/users/octocat/events{/privacy} received_events_url: https://api.github.com/users/octocat/received_events type: User site_admin: false private: false html_url: https://github.com/octocat/Hello-World description: This your first repo! fork: false url: https://api.github.com/repos/octocat/Hello-World archive_url: https://api.github.com/repos/octocat/Hello-World/{archive_format}{/ref} assignees_url: https://api.github.com/repos/octocat/Hello-World/assignees{/user} blobs_url: https://api.github.com/repos/octocat/Hello-World/git/blobs{/sha} branches_url: https://api.github.com/repos/octocat/Hello-World/branches{/branch} collaborators_url: https://api.github.com/repos/octocat/Hello-World/collaborators{/collaborator} comments_url: https://api.github.com/repos/octocat/Hello-World/comments{/number} commits_url: https://api.github.com/repos/octocat/Hello-World/commits{/sha} compare_url: https://api.github.com/repos/octocat/Hello-World/compare/{base}...{head} contents_url: https://api.github.com/repos/octocat/Hello-World/contents/{+path} contributors_url: https://api.github.com/repos/octocat/Hello-World/contributors deployments_url: https://api.github.com/repos/octocat/Hello-World/deployments downloads_url: https://api.github.com/repos/octocat/Hello-World/downloads events_url: https://api.github.com/repos/octocat/Hello-World/events forks_url: https://api.github.com/repos/octocat/Hello-World/forks git_commits_url: https://api.github.com/repos/octocat/Hello-World/git/commits{/sha} git_refs_url: https://api.github.com/repos/octocat/Hello-World/git/refs{/sha} git_tags_url: https://api.github.com/repos/octocat/Hello-World/git/tags{/sha} git_url: git:github.com/octocat/Hello-World.git issue_comment_url: https://api.github.com/repos/octocat/Hello-World/issues/comments{/number} issue_events_url: https://api.github.com/repos/octocat/Hello-World/issues/events{/number} issues_url: https://api.github.com/repos/octocat/Hello-World/issues{/number} keys_url: https://api.github.com/repos/octocat/Hello-World/keys{/key_id} labels_url: https://api.github.com/repos/octocat/Hello-World/labels{/name} languages_url: https://api.github.com/repos/octocat/Hello-World/languages merges_url: https://api.github.com/repos/octocat/Hello-World/merges milestones_url: https://api.github.com/repos/octocat/Hello-World/milestones{/number} notifications_url: https://api.github.com/repos/octocat/Hello-World/notifications{?since,all,participating} pulls_url: https://api.github.com/repos/octocat/Hello-World/pulls{/number} releases_url: https://api.github.com/repos/octocat/Hello-World/releases{/id} ssh_url: git@github.com:octocat/Hello-World.git stargazers_url: https://api.github.com/repos/octocat/Hello-World/stargazers statuses_url: https://api.github.com/repos/octocat/Hello-World/statuses/{sha} subscribers_url: https://api.github.com/repos/octocat/Hello-World/subscribers subscription_url: https://api.github.com/repos/octocat/Hello-World/subscription tags_url: https://api.github.com/repos/octocat/Hello-World/tags teams_url: https://api.github.com/repos/octocat/Hello-World/teams trees_url: https://api.github.com/repos/octocat/Hello-World/git/trees{/sha} clone_url: https://github.com/octocat/Hello-World.git mirror_url: git:git.example.com/octocat/Hello-World hooks_url: https://api.github.com/repos/octocat/Hello-World/hooks svn_url: https://svn.github.com/octocat/Hello-World homepage: https://github.com language: forks_count: 9 stargazers_count: 80 watchers_count: 80 size: 108 default_branch: master open_issues_count: 0 is_template: true topics: - octocat - atom - electron - api has_issues: true has_projects: true has_wiki: true has_pages: false has_downloads: true archived: false disabled: false visibility: public pushed_at: '2011-01-26T19:06:43Z' created_at: '2011-01-26T19:01:12Z' updated_at: '2011-01-26T19:14:43Z' permissions: admin: false push: false pull: true allow_rebase_merge: true template_repository: temp_clone_token: ABTLWHOULUVAXGTRYU7OC2876QJ2O allow_squash_merge: true delete_branch_on_merge: true allow_merge_commit: true subscribers_count: 42 network_count: 0 license: key: mit name: MIT License url: https://api.github.com/licenses/mit spdx_id: MIT node_id: MDc6TGljZW5zZW1pdA== html_url: https://github.com/licenses/mit forks: 1 open_issues: 1 watchers: 1 base: label: octocat:master ref: master sha: 6dcb09b5b57875f334f61aebed695e2e4193db5e user: login: octocat id: 1 node_id: MDQ6VXNlcjE= avatar_url: https://github.com/images/error/octocat_happy.gif gravatar_id: '' url: https://api.github.com/users/octocat html_url: https://github.com/octocat followers_url: https://api.github.com/users/octocat/followers following_url: https://api.github.com/users/octocat/following{/other_user} gists_url: https://api.github.com/users/octocat/gists{/gist_id} starred_url: https://api.github.com/users/octocat/starred{/owner}{/repo} subscriptions_url: https://api.github.com/users/octocat/subscriptions organizations_url: https://api.github.com/users/octocat/orgs repos_url: https://api.github.com/users/octocat/repos events_url: https://api.github.com/users/octocat/events{/privacy} received_events_url: https://api.github.com/users/octocat/received_events type: User site_admin: false repo: id: 1296269 node_id: MDEwOlJlcG9zaXRvcnkxMjk2MjY5 name: Hello-World full_name: octocat/Hello-World owner: login: octocat id: 1 node_id: MDQ6VXNlcjE= avatar_url: https://github.com/images/error/octocat_happy.gif gravatar_id: '' url: https://api.github.com/users/octocat html_url: https://github.com/octocat followers_url: https://api.github.com/users/octocat/followers following_url: https://api.github.com/users/octocat/following{/other_user} gists_url: https://api.github.com/users/octocat/gists{/gist_id} starred_url: https://api.github.com/users/octocat/starred{/owner}{/repo} subscriptions_url: https://api.github.com/users/octocat/subscriptions organizations_url: https://api.github.com/users/octocat/orgs repos_url: https://api.github.com/users/octocat/repos events_url: https://api.github.com/users/octocat/events{/privacy} received_events_url: https://api.github.com/users/octocat/received_events type: User site_admin: false private: false html_url: https://github.com/octocat/Hello-World description: This your first repo! fork: false url: https://api.github.com/repos/octocat/Hello-World archive_url: https://api.github.com/repos/octocat/Hello-World/{archive_format}{/ref} assignees_url: https://api.github.com/repos/octocat/Hello-World/assignees{/user} blobs_url: https://api.github.com/repos/octocat/Hello-World/git/blobs{/sha} branches_url: https://api.github.com/repos/octocat/Hello-World/branches{/branch} collaborators_url: https://api.github.com/repos/octocat/Hello-World/collaborators{/collaborator} comments_url: https://api.github.com/repos/octocat/Hello-World/comments{/number} commits_url: https://api.github.com/repos/octocat/Hello-World/commits{/sha} compare_url: https://api.github.com/repos/octocat/Hello-World/compare/{base}...{head} contents_url: https://api.github.com/repos/octocat/Hello-World/contents/{+path} contributors_url: https://api.github.com/repos/octocat/Hello-World/contributors deployments_url: https://api.github.com/repos/octocat/Hello-World/deployments downloads_url: https://api.github.com/repos/octocat/Hello-World/downloads events_url: https://api.github.com/repos/octocat/Hello-World/events forks_url: https://api.github.com/repos/octocat/Hello-World/forks git_commits_url: https://api.github.com/repos/octocat/Hello-World/git/commits{/sha} git_refs_url: https://api.github.com/repos/octocat/Hello-World/git/refs{/sha} git_tags_url: https://api.github.com/repos/octocat/Hello-World/git/tags{/sha} git_url: git:github.com/octocat/Hello-World.git issue_comment_url: https://api.github.com/repos/octocat/Hello-World/issues/comments{/number} issue_events_url: https://api.github.com/repos/octocat/Hello-World/issues/events{/number} issues_url: https://api.github.com/repos/octocat/Hello-World/issues{/number} keys_url: https://api.github.com/repos/octocat/Hello-World/keys{/key_id} labels_url: https://api.github.com/repos/octocat/Hello-World/labels{/name} languages_url: https://api.github.com/repos/octocat/Hello-World/languages merges_url: https://api.github.com/repos/octocat/Hello-World/merges milestones_url: https://api.github.com/repos/octocat/Hello-World/milestones{/number} notifications_url: https://api.github.com/repos/octocat/Hello-World/notifications{?since,all,participating} pulls_url: https://api.github.com/repos/octocat/Hello-World/pulls{/number} releases_url: https://api.github.com/repos/octocat/Hello-World/releases{/id} ssh_url: git@github.com:octocat/Hello-World.git stargazers_url: https://api.github.com/repos/octocat/Hello-World/stargazers statuses_url: https://api.github.com/repos/octocat/Hello-World/statuses/{sha} subscribers_url: https://api.github.com/repos/octocat/Hello-World/subscribers subscription_url: https://api.github.com/repos/octocat/Hello-World/subscription tags_url: https://api.github.com/repos/octocat/Hello-World/tags teams_url: https://api.github.com/repos/octocat/Hello-World/teams trees_url: https://api.github.com/repos/octocat/Hello-World/git/trees{/sha} clone_url: https://github.com/octocat/Hello-World.git mirror_url: git:git.example.com/octocat/Hello-World hooks_url: https://api.github.com/repos/octocat/Hello-World/hooks svn_url: https://svn.github.com/octocat/Hello-World homepage: https://github.com language: forks_count: 9 stargazers_count: 80 watchers_count: 80 size: 108 default_branch: master open_issues_count: 0 is_template: true topics: - octocat - atom - electron - api has_issues: true has_projects: true has_wiki: true has_pages: false has_downloads: true archived: false disabled: false visibility: public pushed_at: '2011-01-26T19:06:43Z' created_at: '2011-01-26T19:01:12Z' updated_at: '2011-01-26T19:14:43Z' permissions: admin: false push: false pull: true allow_rebase_merge: true template_repository: temp_clone_token: ABTLWHOULUVAXGTRYU7OC2876QJ2O allow_squash_merge: true delete_branch_on_merge: true allow_merge_commit: true subscribers_count: 42 network_count: 0 license: key: mit name: MIT License url: https://api.github.com/licenses/mit spdx_id: MIT node_id: MDc6TGljZW5zZW1pdA== html_url: https://github.com/licenses/mit forks: 1 open_issues: 1 watchers: 1 _links: self: href: https://api.github.com/repos/octocat/Hello-World/pulls/1347 html: href: https://github.com/octocat/Hello-World/pull/1347 issue: href: https://api.github.com/repos/octocat/Hello-World/issues/1347 comments: href: https://api.github.com/repos/octocat/Hello-World/issues/1347/comments review_comments: href: https://api.github.com/repos/octocat/Hello-World/pulls/1347/comments review_comment: href: https://api.github.com/repos/octocat/Hello-World/pulls/comments{/number} commits: href: https://api.github.com/repos/octocat/Hello-World/pulls/1347/commits statuses: href: https://api.github.com/repos/octocat/Hello-World/statuses/6dcb09b5b57875f334f61aebed695e2e4193db5e author_association: OWNER draft: false commit: value: url: https://api.github.com/repos/octocat/Hello-World/commits/6dcb09b5b57875f334f61aebed695e2e4193db5e sha: 6dcb09b5b57875f334f61aebed695e2e4193db5e node_id: MDY6Q29tbWl0NmRjYjA5YjViNTc4NzVmMzM0ZjYxYWViZWQ2OTVlMmU0MTkzZGI1ZQ== html_url: https://github.com/octocat/Hello-World/commit/6dcb09b5b57875f334f61aebed695e2e4193db5e comments_url: https://api.github.com/repos/octocat/Hello-World/commits/6dcb09b5b57875f334f61aebed695e2e4193db5e/comments commit: url: https://api.github.com/repos/octocat/Hello-World/git/commits/6dcb09b5b57875f334f61aebed695e2e4193db5e author: name: Monalisa Octocat email: mona@github.com date: '2011-04-14T16:00:49Z' committer: name: Monalisa Octocat email: mona@github.com date: '2011-04-14T16:00:49Z' message: Fix all the bugs tree: url: https://api.github.com/repos/octocat/Hello-World/tree/6dcb09b5b57875f334f61aebed695e2e4193db5e sha: 6dcb09b5b57875f334f61aebed695e2e4193db5e comment_count: 0 verification: verified: false reason: unsigned signature: payload: author: login: octocat id: 1 node_id: MDQ6VXNlcjE= avatar_url: https://github.com/images/error/octocat_happy.gif gravatar_id: '' url: https://api.github.com/users/octocat html_url: https://github.com/octocat followers_url: https://api.github.com/users/octocat/followers following_url: https://api.github.com/users/octocat/following{/other_user} gists_url: https://api.github.com/users/octocat/gists{/gist_id} starred_url: https://api.github.com/users/octocat/starred{/owner}{/repo} subscriptions_url: https://api.github.com/users/octocat/subscriptions organizations_url: https://api.github.com/users/octocat/orgs repos_url: https://api.github.com/users/octocat/repos events_url: https://api.github.com/users/octocat/events{/privacy} received_events_url: https://api.github.com/users/octocat/received_events type: User site_admin: false committer: login: octocat id: 1 node_id: MDQ6VXNlcjE= avatar_url: https://github.com/images/error/octocat_happy.gif gravatar_id: '' url: https://api.github.com/users/octocat html_url: https://github.com/octocat followers_url: https://api.github.com/users/octocat/followers following_url: https://api.github.com/users/octocat/following{/other_user} gists_url: https://api.github.com/users/octocat/gists{/gist_id} starred_url: https://api.github.com/users/octocat/starred{/owner}{/repo} subscriptions_url: https://api.github.com/users/octocat/subscriptions organizations_url: https://api.github.com/users/octocat/orgs repos_url: https://api.github.com/users/octocat/repos events_url: https://api.github.com/users/octocat/events{/privacy} received_events_url: https://api.github.com/users/octocat/received_events type: User site_admin: false parents: - url: https://api.github.com/repos/octocat/Hello-World/commits/6dcb09b5b57875f334f61aebed695e2e4193db5e sha: 6dcb09b5b57875f334f61aebed695e2e4193db5e stats: additions: 104 deletions: 4 total: 108 files: - filename: file1.txt additions: 10 deletions: 2 changes: 12 status: modified raw_url: https://github.com/octocat/Hello-World/raw/7ca483543807a51b6079e54ac4cc392bc29ae284/file1.txt blob_url: https://github.com/octocat/Hello-World/blob/7ca483543807a51b6079e54ac4cc392bc29ae284/file1.txt patch: |- @@ -29,7 +29,7 @@ ..... check-suite-paginated: value: total_count: 1 check_suites: - id: 5 node_id: MDEwOkNoZWNrU3VpdGU1 head_branch: master head_sha: d6fde92930d4715a2b49857d24b940956b26d2d3 status: completed conclusion: neutral url: https://api.github.com/repos/github/hello-world/check-suites/5 before: 146e867f55c26428e5f9fade55a9bbf5e95a7912 after: d6fde92930d4715a2b49857d24b940956b26d2d3 pull_requests: [] app: id: 1 slug: octoapp node_id: MDExOkludGVncmF0aW9uMQ== owner: login: github id: 1 node_id: MDEyOk9yZ2FuaXphdGlvbjE= url: https://api.github.com/orgs/github repos_url: https://api.github.com/orgs/github/repos events_url: https://api.github.com/orgs/github/events avatar_url: https://github.com/images/error/octocat_happy.gif gravatar_id: '' html_url: https://github.com/octocat followers_url: https://api.github.com/users/octocat/followers following_url: https://api.github.com/users/octocat/following{/other_user} gists_url: https://api.github.com/users/octocat/gists{/gist_id} starred_url: https://api.github.com/users/octocat/starred{/owner}{/repo} subscriptions_url: https://api.github.com/users/octocat/subscriptions organizations_url: https://api.github.com/users/octocat/orgs received_events_url: https://api.github.com/users/octocat/received_events type: User site_admin: true name: Octocat App description: '' external_url: https://example.com html_url: https://github.com/apps/octoapp created_at: '2017-07-08T16:18:44-04:00' updated_at: '2017-07-08T16:18:44-04:00' permissions: metadata: read contents: read issues: write single_file: write events: - push - pull_request repository: id: 1296269 node_id: MDEwOlJlcG9zaXRvcnkxMjk2MjY5 name: Hello-World full_name: octocat/Hello-World owner: login: octocat id: 1 node_id: MDQ6VXNlcjE= avatar_url: https://github.com/images/error/octocat_happy.gif gravatar_id: '' url: https://api.github.com/users/octocat html_url: https://github.com/octocat followers_url: https://api.github.com/users/octocat/followers following_url: https://api.github.com/users/octocat/following{/other_user} gists_url: https://api.github.com/users/octocat/gists{/gist_id} starred_url: https://api.github.com/users/octocat/starred{/owner}{/repo} subscriptions_url: https://api.github.com/users/octocat/subscriptions organizations_url: https://api.github.com/users/octocat/orgs repos_url: https://api.github.com/users/octocat/repos events_url: https://api.github.com/users/octocat/events{/privacy} received_events_url: https://api.github.com/users/octocat/received_events type: User site_admin: false private: false html_url: https://github.com/octocat/Hello-World description: This your first repo! fork: false url: https://api.github.com/repos/octocat/Hello-World archive_url: https://api.github.com/repos/octocat/Hello-World/{archive_format}{/ref} assignees_url: https://api.github.com/repos/octocat/Hello-World/assignees{/user} blobs_url: https://api.github.com/repos/octocat/Hello-World/git/blobs{/sha} branches_url: https://api.github.com/repos/octocat/Hello-World/branches{/branch} collaborators_url: https://api.github.com/repos/octocat/Hello-World/collaborators{/collaborator} comments_url: https://api.github.com/repos/octocat/Hello-World/comments{/number} commits_url: https://api.github.com/repos/octocat/Hello-World/commits{/sha} compare_url: https://api.github.com/repos/octocat/Hello-World/compare/{base}...{head} contents_url: https://api.github.com/repos/octocat/Hello-World/contents/{+path} contributors_url: https://api.github.com/repos/octocat/Hello-World/contributors deployments_url: https://api.github.com/repos/octocat/Hello-World/deployments downloads_url: https://api.github.com/repos/octocat/Hello-World/downloads events_url: https://api.github.com/repos/octocat/Hello-World/events forks_url: https://api.github.com/repos/octocat/Hello-World/forks git_commits_url: https://api.github.com/repos/octocat/Hello-World/git/commits{/sha} git_refs_url: https://api.github.com/repos/octocat/Hello-World/git/refs{/sha} git_tags_url: https://api.github.com/repos/octocat/Hello-World/git/tags{/sha} git_url: git:github.com/octocat/Hello-World.git issue_comment_url: https://api.github.com/repos/octocat/Hello-World/issues/comments{/number} issue_events_url: https://api.github.com/repos/octocat/Hello-World/issues/events{/number} issues_url: https://api.github.com/repos/octocat/Hello-World/issues{/number} keys_url: https://api.github.com/repos/octocat/Hello-World/keys{/key_id} labels_url: https://api.github.com/repos/octocat/Hello-World/labels{/name} languages_url: https://api.github.com/repos/octocat/Hello-World/languages merges_url: https://api.github.com/repos/octocat/Hello-World/merges milestones_url: https://api.github.com/repos/octocat/Hello-World/milestones{/number} notifications_url: https://api.github.com/repos/octocat/Hello-World/notifications{?since,all,participating} pulls_url: https://api.github.com/repos/octocat/Hello-World/pulls{/number} releases_url: https://api.github.com/repos/octocat/Hello-World/releases{/id} ssh_url: git@github.com:octocat/Hello-World.git stargazers_url: https://api.github.com/repos/octocat/Hello-World/stargazers statuses_url: https://api.github.com/repos/octocat/Hello-World/statuses/{sha} subscribers_url: https://api.github.com/repos/octocat/Hello-World/subscribers subscription_url: https://api.github.com/repos/octocat/Hello-World/subscription tags_url: https://api.github.com/repos/octocat/Hello-World/tags teams_url: https://api.github.com/repos/octocat/Hello-World/teams trees_url: https://api.github.com/repos/octocat/Hello-World/git/trees{/sha} clone_url: https://github.com/octocat/Hello-World.git mirror_url: git:git.example.com/octocat/Hello-World hooks_url: https://api.github.com/repos/octocat/Hello-World/hooks svn_url: https://svn.github.com/octocat/Hello-World homepage: https://github.com language: forks_count: 9 stargazers_count: 80 watchers_count: 80 size: 108 default_branch: master open_issues_count: 0 is_template: true topics: - octocat - atom - electron - api has_issues: true has_projects: true has_wiki: true has_pages: false has_downloads: true archived: false disabled: false visibility: public pushed_at: '2011-01-26T19:06:43Z' created_at: '2011-01-26T19:01:12Z' updated_at: '2011-01-26T19:14:43Z' permissions: admin: false push: false pull: true temp_clone_token: ABTLWHOULUVAXGTRYU7OC2876QJ2O delete_branch_on_merge: true subscribers_count: 42 network_count: 0 created_at: '2011-01-26T19:01:12Z' updated_at: '2011-01-26T19:14:43Z' head_commit: id: 7fd1a60b01f91b314f59955a4e4d4e80d8edf11d tree_id: 7fd1a60b01f91b314f59955a4e4d4e80d8edf11d message: |- Merge pull request #6 from Spaceghost/patch-1 New line at end of file. timestamp: '2016-10-10T00:00:00Z' author: name: The Octocat email: octocat@nowhere.com committer: name: The Octocat email: octocat@nowhere.com latest_check_runs_count: 1 check_runs_url: https://api.github.com/repos/octocat/Hello-World/check-suites/5/check-runs combined-commit-status: value: state: success statuses: - url: https://api.github.com/repos/octocat/Hello-World/statuses/6dcb09b5b57875f334f61aebed695e2e4193db5e avatar_url: https://github.com/images/error/hubot_happy.gif id: 1 node_id: MDY6U3RhdHVzMQ== state: success description: Build has completed successfully target_url: https://ci.example.com/1000/output context: continuous-integration/jenkins created_at: '2012-07-20T01:19:13Z' updated_at: '2012-07-20T01:19:13Z' - url: https://api.github.com/repos/octocat/Hello-World/statuses/6dcb09b5b57875f334f61aebed695e2e4193db5e avatar_url: https://github.com/images/error/other_user_happy.gif id: 2 node_id: MDY6U3RhdHVzMg== state: success description: Testing has completed successfully target_url: https://ci.example.com/2000/output context: security/brakeman created_at: '2012-08-20T01:19:13Z' updated_at: '2012-08-20T01:19:13Z' sha: 6dcb09b5b57875f334f61aebed695e2e4193db5e total_count: 2 repository: id: 1296269 node_id: MDEwOlJlcG9zaXRvcnkxMjk2MjY5 name: Hello-World full_name: octocat/Hello-World owner: login: octocat id: 1 node_id: MDQ6VXNlcjE= avatar_url: https://github.com/images/error/octocat_happy.gif gravatar_id: '' url: https://api.github.com/users/octocat html_url: https://github.com/octocat followers_url: https://api.github.com/users/octocat/followers following_url: https://api.github.com/users/octocat/following{/other_user} gists_url: https://api.github.com/users/octocat/gists{/gist_id} starred_url: https://api.github.com/users/octocat/starred{/owner}{/repo} subscriptions_url: https://api.github.com/users/octocat/subscriptions organizations_url: https://api.github.com/users/octocat/orgs repos_url: https://api.github.com/users/octocat/repos events_url: https://api.github.com/users/octocat/events{/privacy} received_events_url: https://api.github.com/users/octocat/received_events type: User site_admin: false private: false html_url: https://github.com/octocat/Hello-World description: This your first repo! fork: false url: https://api.github.com/repos/octocat/Hello-World archive_url: https://api.github.com/repos/octocat/Hello-World/{archive_format}{/ref} assignees_url: https://api.github.com/repos/octocat/Hello-World/assignees{/user} blobs_url: https://api.github.com/repos/octocat/Hello-World/git/blobs{/sha} branches_url: https://api.github.com/repos/octocat/Hello-World/branches{/branch} collaborators_url: https://api.github.com/repos/octocat/Hello-World/collaborators{/collaborator} comments_url: https://api.github.com/repos/octocat/Hello-World/comments{/number} commits_url: https://api.github.com/repos/octocat/Hello-World/commits{/sha} compare_url: https://api.github.com/repos/octocat/Hello-World/compare/{base}...{head} contents_url: https://api.github.com/repos/octocat/Hello-World/contents/{+path} contributors_url: https://api.github.com/repos/octocat/Hello-World/contributors deployments_url: https://api.github.com/repos/octocat/Hello-World/deployments downloads_url: https://api.github.com/repos/octocat/Hello-World/downloads events_url: https://api.github.com/repos/octocat/Hello-World/events forks_url: https://api.github.com/repos/octocat/Hello-World/forks git_commits_url: https://api.github.com/repos/octocat/Hello-World/git/commits{/sha} git_refs_url: https://api.github.com/repos/octocat/Hello-World/git/refs{/sha} git_tags_url: https://api.github.com/repos/octocat/Hello-World/git/tags{/sha} git_url: git:github.com/octocat/Hello-World.git issue_comment_url: https://api.github.com/repos/octocat/Hello-World/issues/comments{/number} issue_events_url: https://api.github.com/repos/octocat/Hello-World/issues/events{/number} issues_url: https://api.github.com/repos/octocat/Hello-World/issues{/number} keys_url: https://api.github.com/repos/octocat/Hello-World/keys{/key_id} labels_url: https://api.github.com/repos/octocat/Hello-World/labels{/name} languages_url: https://api.github.com/repos/octocat/Hello-World/languages merges_url: https://api.github.com/repos/octocat/Hello-World/merges milestones_url: https://api.github.com/repos/octocat/Hello-World/milestones{/number} notifications_url: https://api.github.com/repos/octocat/Hello-World/notifications{?since,all,participating} pulls_url: https://api.github.com/repos/octocat/Hello-World/pulls{/number} releases_url: https://api.github.com/repos/octocat/Hello-World/releases{/id} ssh_url: git@github.com:octocat/Hello-World.git stargazers_url: https://api.github.com/repos/octocat/Hello-World/stargazers statuses_url: https://api.github.com/repos/octocat/Hello-World/statuses/{sha} subscribers_url: https://api.github.com/repos/octocat/Hello-World/subscribers subscription_url: https://api.github.com/repos/octocat/Hello-World/subscription tags_url: https://api.github.com/repos/octocat/Hello-World/tags teams_url: https://api.github.com/repos/octocat/Hello-World/teams trees_url: https://api.github.com/repos/octocat/Hello-World/git/trees{/sha} hooks_url: http://api.github.com/repos/octocat/Hello-World/hooks commit_url: https://api.github.com/repos/octocat/Hello-World/6dcb09b5b57875f334f61aebed695e2e4193db5e url: https://api.github.com/repos/octocat/Hello-World/6dcb09b5b57875f334f61aebed695e2e4193db5e/status status-items: value: - url: https://api.github.com/repos/octocat/Hello-World/statuses/6dcb09b5b57875f334f61aebed695e2e4193db5e avatar_url: https://github.com/images/error/hubot_happy.gif id: 1 node_id: MDY6U3RhdHVzMQ== state: success description: Build has completed successfully target_url: https://ci.example.com/1000/output context: continuous-integration/jenkins created_at: '2012-07-20T01:19:13Z' updated_at: '2012-07-20T01:19:13Z' creator: login: octocat id: 1 node_id: MDQ6VXNlcjE= avatar_url: https://github.com/images/error/octocat_happy.gif gravatar_id: '' url: https://api.github.com/users/octocat html_url: https://github.com/octocat followers_url: https://api.github.com/users/octocat/followers following_url: https://api.github.com/users/octocat/following{/other_user} gists_url: https://api.github.com/users/octocat/gists{/gist_id} starred_url: https://api.github.com/users/octocat/starred{/owner}{/repo} subscriptions_url: https://api.github.com/users/octocat/subscriptions organizations_url: https://api.github.com/users/octocat/orgs repos_url: https://api.github.com/users/octocat/repos events_url: https://api.github.com/users/octocat/events{/privacy} received_events_url: https://api.github.com/users/octocat/received_events type: User site_admin: false commit-comparison: value: url: https://api.github.com/repos/octocat/Hello-World/compare/master...topic html_url: https://github.com/octocat/Hello-World/compare/master...topic permalink_url: https://github.com/octocat/Hello-World/compare/octocat:bbcd538c8e72b8c175046e27cc8f907076331401...octocat:0328041d1152db8ae77652d1618a02e57f745f17 diff_url: https://github.com/octocat/Hello-World/compare/master...topic.diff patch_url: https://github.com/octocat/Hello-World/compare/master...topic.patch base_commit: url: https://api.github.com/repos/octocat/Hello-World/commits/6dcb09b5b57875f334f61aebed695e2e4193db5e sha: 6dcb09b5b57875f334f61aebed695e2e4193db5e node_id: MDY6Q29tbWl0NmRjYjA5YjViNTc4NzVmMzM0ZjYxYWViZWQ2OTVlMmU0MTkzZGI1ZQ== html_url: https://github.com/octocat/Hello-World/commit/6dcb09b5b57875f334f61aebed695e2e4193db5e comments_url: https://api.github.com/repos/octocat/Hello-World/commits/6dcb09b5b57875f334f61aebed695e2e4193db5e/comments commit: url: https://api.github.com/repos/octocat/Hello-World/git/commits/6dcb09b5b57875f334f61aebed695e2e4193db5e author: name: Monalisa Octocat email: mona@github.com date: '2011-04-14T16:00:49Z' committer: name: Monalisa Octocat email: mona@github.com date: '2011-04-14T16:00:49Z' message: Fix all the bugs tree: url: https://api.github.com/repos/octocat/Hello-World/tree/6dcb09b5b57875f334f61aebed695e2e4193db5e sha: 6dcb09b5b57875f334f61aebed695e2e4193db5e comment_count: 0 verification: verified: false reason: unsigned signature: payload: author: login: octocat id: 1 node_id: MDQ6VXNlcjE= avatar_url: https://github.com/images/error/octocat_happy.gif gravatar_id: '' url: https://api.github.com/users/octocat html_url: https://github.com/octocat followers_url: https://api.github.com/users/octocat/followers following_url: https://api.github.com/users/octocat/following{/other_user} gists_url: https://api.github.com/users/octocat/gists{/gist_id} starred_url: https://api.github.com/users/octocat/starred{/owner}{/repo} subscriptions_url: https://api.github.com/users/octocat/subscriptions organizations_url: https://api.github.com/users/octocat/orgs repos_url: https://api.github.com/users/octocat/repos events_url: https://api.github.com/users/octocat/events{/privacy} received_events_url: https://api.github.com/users/octocat/received_events type: User site_admin: false committer: login: octocat id: 1 node_id: MDQ6VXNlcjE= avatar_url: https://github.com/images/error/octocat_happy.gif gravatar_id: '' url: https://api.github.com/users/octocat html_url: https://github.com/octocat followers_url: https://api.github.com/users/octocat/followers following_url: https://api.github.com/users/octocat/following{/other_user} gists_url: https://api.github.com/users/octocat/gists{/gist_id} starred_url: https://api.github.com/users/octocat/starred{/owner}{/repo} subscriptions_url: https://api.github.com/users/octocat/subscriptions organizations_url: https://api.github.com/users/octocat/orgs repos_url: https://api.github.com/users/octocat/repos events_url: https://api.github.com/users/octocat/events{/privacy} received_events_url: https://api.github.com/users/octocat/received_events type: User site_admin: false parents: - url: https://api.github.com/repos/octocat/Hello-World/commits/6dcb09b5b57875f334f61aebed695e2e4193db5e sha: 6dcb09b5b57875f334f61aebed695e2e4193db5e merge_base_commit: url: https://api.github.com/repos/octocat/Hello-World/commits/6dcb09b5b57875f334f61aebed695e2e4193db5e sha: 6dcb09b5b57875f334f61aebed695e2e4193db5e node_id: MDY6Q29tbWl0NmRjYjA5YjViNTc4NzVmMzM0ZjYxYWViZWQ2OTVlMmU0MTkzZGI1ZQ== html_url: https://github.com/octocat/Hello-World/commit/6dcb09b5b57875f334f61aebed695e2e4193db5e comments_url: https://api.github.com/repos/octocat/Hello-World/commits/6dcb09b5b57875f334f61aebed695e2e4193db5e/comments commit: url: https://api.github.com/repos/octocat/Hello-World/git/commits/6dcb09b5b57875f334f61aebed695e2e4193db5e author: name: Monalisa Octocat email: mona@github.com date: '2011-04-14T16:00:49Z' committer: name: Monalisa Octocat email: mona@github.com date: '2011-04-14T16:00:49Z' message: Fix all the bugs tree: url: https://api.github.com/repos/octocat/Hello-World/tree/6dcb09b5b57875f334f61aebed695e2e4193db5e sha: 6dcb09b5b57875f334f61aebed695e2e4193db5e comment_count: 0 verification: verified: false reason: unsigned signature: payload: author: login: octocat id: 1 node_id: MDQ6VXNlcjE= avatar_url: https://github.com/images/error/octocat_happy.gif gravatar_id: '' url: https://api.github.com/users/octocat html_url: https://github.com/octocat followers_url: https://api.github.com/users/octocat/followers following_url: https://api.github.com/users/octocat/following{/other_user} gists_url: https://api.github.com/users/octocat/gists{/gist_id} starred_url: https://api.github.com/users/octocat/starred{/owner}{/repo} subscriptions_url: https://api.github.com/users/octocat/subscriptions organizations_url: https://api.github.com/users/octocat/orgs repos_url: https://api.github.com/users/octocat/repos events_url: https://api.github.com/users/octocat/events{/privacy} received_events_url: https://api.github.com/users/octocat/received_events type: User site_admin: false committer: login: octocat id: 1 node_id: MDQ6VXNlcjE= avatar_url: https://github.com/images/error/octocat_happy.gif gravatar_id: '' url: https://api.github.com/users/octocat html_url: https://github.com/octocat followers_url: https://api.github.com/users/octocat/followers following_url: https://api.github.com/users/octocat/following{/other_user} gists_url: https://api.github.com/users/octocat/gists{/gist_id} starred_url: https://api.github.com/users/octocat/starred{/owner}{/repo} subscriptions_url: https://api.github.com/users/octocat/subscriptions organizations_url: https://api.github.com/users/octocat/orgs repos_url: https://api.github.com/users/octocat/repos events_url: https://api.github.com/users/octocat/events{/privacy} received_events_url: https://api.github.com/users/octocat/received_events type: User site_admin: false parents: - url: https://api.github.com/repos/octocat/Hello-World/commits/6dcb09b5b57875f334f61aebed695e2e4193db5e sha: 6dcb09b5b57875f334f61aebed695e2e4193db5e status: behind ahead_by: 1 behind_by: 2 total_commits: 1 commits: - url: https://api.github.com/repos/octocat/Hello-World/commits/6dcb09b5b57875f334f61aebed695e2e4193db5e sha: 6dcb09b5b57875f334f61aebed695e2e4193db5e node_id: MDY6Q29tbWl0NmRjYjA5YjViNTc4NzVmMzM0ZjYxYWViZWQ2OTVlMmU0MTkzZGI1ZQ== html_url: https://github.com/octocat/Hello-World/commit/6dcb09b5b57875f334f61aebed695e2e4193db5e comments_url: https://api.github.com/repos/octocat/Hello-World/commits/6dcb09b5b57875f334f61aebed695e2e4193db5e/comments commit: url: https://api.github.com/repos/octocat/Hello-World/git/commits/6dcb09b5b57875f334f61aebed695e2e4193db5e author: name: Monalisa Octocat email: mona@github.com date: '2011-04-14T16:00:49Z' committer: name: Monalisa Octocat email: mona@github.com date: '2011-04-14T16:00:49Z' message: Fix all the bugs tree: url: https://api.github.com/repos/octocat/Hello-World/tree/6dcb09b5b57875f334f61aebed695e2e4193db5e sha: 6dcb09b5b57875f334f61aebed695e2e4193db5e comment_count: 0 verification: verified: false reason: unsigned signature: payload: author: login: octocat id: 1 node_id: MDQ6VXNlcjE= avatar_url: https://github.com/images/error/octocat_happy.gif gravatar_id: '' url: https://api.github.com/users/octocat html_url: https://github.com/octocat followers_url: https://api.github.com/users/octocat/followers following_url: https://api.github.com/users/octocat/following{/other_user} gists_url: https://api.github.com/users/octocat/gists{/gist_id} starred_url: https://api.github.com/users/octocat/starred{/owner}{/repo} subscriptions_url: https://api.github.com/users/octocat/subscriptions organizations_url: https://api.github.com/users/octocat/orgs repos_url: https://api.github.com/users/octocat/repos events_url: https://api.github.com/users/octocat/events{/privacy} received_events_url: https://api.github.com/users/octocat/received_events type: User site_admin: false committer: login: octocat id: 1 node_id: MDQ6VXNlcjE= avatar_url: https://github.com/images/error/octocat_happy.gif gravatar_id: '' url: https://api.github.com/users/octocat html_url: https://github.com/octocat followers_url: https://api.github.com/users/octocat/followers following_url: https://api.github.com/users/octocat/following{/other_user} gists_url: https://api.github.com/users/octocat/gists{/gist_id} starred_url: https://api.github.com/users/octocat/starred{/owner}{/repo} subscriptions_url: https://api.github.com/users/octocat/subscriptions organizations_url: https://api.github.com/users/octocat/orgs repos_url: https://api.github.com/users/octocat/repos events_url: https://api.github.com/users/octocat/events{/privacy} received_events_url: https://api.github.com/users/octocat/received_events type: User site_admin: false parents: - url: https://api.github.com/repos/octocat/Hello-World/commits/6dcb09b5b57875f334f61aebed695e2e4193db5e sha: 6dcb09b5b57875f334f61aebed695e2e4193db5e files: - sha: bbcd538c8e72b8c175046e27cc8f907076331401 filename: file1.txt status: added additions: 103 deletions: 21 changes: 124 blob_url: https://github.com/octocat/Hello-World/blob/6dcb09b5b57875f334f61aebed695e2e4193db5e/file1.txt raw_url: https://github.com/octocat/Hello-World/raw/6dcb09b5b57875f334f61aebed695e2e4193db5e/file1.txt contents_url: https://api.github.com/repos/octocat/Hello-World/contents/file1.txt?ref=6dcb09b5b57875f334f61aebed695e2e4193db5e patch: "@@ -132,7 +132,7 @@ module Test @@ -1000,7 +1000,7 @@ module Test" content-reference-attachment: value: id: 101 title: "[A-1234] Error found in core/models.py file'" body: |- You have used an email that already exists for the user_email_uniq field. ## DETAILS: The (email)=(Octocat@github.com) already exists. The error was found in core/models.py in get_or_create_user at line 62. self.save() content-file-response-if-content-is-a-file: summary: Response if content is a file value: type: file encoding: base64 size: 5362 name: README.md path: README.md content: encoded content ... sha: 3d21ec53a331a6f037a91c368710b99387d012c1 url: https://api.github.com/repos/octokit/octokit.rb/contents/README.md git_url: https://api.github.com/repos/octokit/octokit.rb/git/blobs/3d21ec53a331a6f037a91c368710b99387d012c1 html_url: https://github.com/octokit/octokit.rb/blob/master/README.md download_url: https://raw.githubusercontent.com/octokit/octokit.rb/master/README.md _links: git: https://api.github.com/repos/octokit/octokit.rb/git/blobs/3d21ec53a331a6f037a91c368710b99387d012c1 self: https://api.github.com/repos/octokit/octokit.rb/contents/README.md html: https://github.com/octokit/octokit.rb/blob/master/README.md content-file-response-if-content-is-a-directory: summary: Response if content is a directory value: - type: file size: 625 name: octokit.rb path: lib/octokit.rb sha: fff6fe3a23bf1c8ea0692b4a883af99bee26fd3b url: https://api.github.com/repos/octokit/octokit.rb/contents/lib/octokit.rb git_url: https://api.github.com/repos/octokit/octokit.rb/git/blobs/fff6fe3a23bf1c8ea0692b4a883af99bee26fd3b html_url: https://github.com/octokit/octokit.rb/blob/master/lib/octokit.rb download_url: https://raw.githubusercontent.com/octokit/octokit.rb/master/lib/octokit.rb _links: self: https://api.github.com/repos/octokit/octokit.rb/contents/lib/octokit.rb git: https://api.github.com/repos/octokit/octokit.rb/git/blobs/fff6fe3a23bf1c8ea0692b4a883af99bee26fd3b html: https://github.com/octokit/octokit.rb/blob/master/lib/octokit.rb - type: dir size: 0 name: octokit path: lib/octokit sha: a84d88e7554fc1fa21bcbc4efae3c782a70d2b9d url: https://api.github.com/repos/octokit/octokit.rb/contents/lib/octokit git_url: https://api.github.com/repos/octokit/octokit.rb/git/trees/a84d88e7554fc1fa21bcbc4efae3c782a70d2b9d html_url: https://github.com/octokit/octokit.rb/tree/master/lib/octokit download_url: _links: self: https://api.github.com/repos/octokit/octokit.rb/contents/lib/octokit git: https://api.github.com/repos/octokit/octokit.rb/git/trees/a84d88e7554fc1fa21bcbc4efae3c782a70d2b9d html: https://github.com/octokit/octokit.rb/tree/master/lib/octokit content-file-response-if-content-is-a-symlink: summary: Response if content is a symlink value: type: symlink target: "/path/to/symlink/target" size: 23 name: some-symlink path: bin/some-symlink sha: 452a98979c88e093d682cab404a3ec82babebb48 url: https://api.github.com/repos/octokit/octokit.rb/contents/bin/some-symlink git_url: https://api.github.com/repos/octokit/octokit.rb/git/blobs/452a98979c88e093d682cab404a3ec82babebb48 html_url: https://github.com/octokit/octokit.rb/blob/master/bin/some-symlink download_url: https://raw.githubusercontent.com/octokit/octokit.rb/master/bin/some-symlink _links: git: https://api.github.com/repos/octokit/octokit.rb/git/blobs/452a98979c88e093d682cab404a3ec82babebb48 self: https://api.github.com/repos/octokit/octokit.rb/contents/bin/some-symlink html: https://github.com/octokit/octokit.rb/blob/master/bin/some-symlink content-file-response-if-content-is-a-submodule: summary: Response if content is a submodule value: type: submodule submodule_git_url: git://github.com/jquery/qunit.git size: 0 name: qunit path: test/qunit sha: 6ca3721222109997540bd6d9ccd396902e0ad2f9 url: https://api.github.com/repos/jquery/jquery/contents/test/qunit?ref=master git_url: https://api.github.com/repos/jquery/qunit/git/trees/6ca3721222109997540bd6d9ccd396902e0ad2f9 html_url: https://github.com/jquery/qunit/tree/6ca3721222109997540bd6d9ccd396902e0ad2f9 download_url: _links: git: https://api.github.com/repos/jquery/qunit/git/trees/6ca3721222109997540bd6d9ccd396902e0ad2f9 self: https://api.github.com/repos/jquery/jquery/contents/test/qunit?ref=master html: https://github.com/jquery/qunit/tree/6ca3721222109997540bd6d9ccd396902e0ad2f9 file-commit-example-for-updating-a-file: value: content: name: hello.txt path: notes/hello.txt sha: a56507ed892d05a37c6d6128c260937ea4d287bd size: 9 url: https://api.github.com/repos/octocat/Hello-World/contents/notes/hello.txt html_url: https://github.com/octocat/Hello-World/blob/master/notes/hello.txt git_url: https://api.github.com/repos/octocat/Hello-World/git/blobs/a56507ed892d05a37c6d6128c260937ea4d287bd download_url: https://raw.githubusercontent.com/octocat/HelloWorld/master/notes/hello.txt type: file _links: self: https://api.github.com/repos/octocat/Hello-World/contents/notes/hello.txt git: https://api.github.com/repos/octocat/Hello-World/git/blobs/a56507ed892d05a37c6d6128c260937ea4d287bd html: https://github.com/octocat/Hello-World/blob/master/notes/hello.txt commit: sha: 18a43cd8e1e3a79c786e3d808a73d23b6d212b16 node_id: MDY6Q29tbWl0MThhNDNjZDhlMWUzYTc5Yzc4NmUzZDgwOGE3M2QyM2I2ZDIxMmIxNg== url: https://api.github.com/repos/octocat/Hello-World/git/commits/18a43cd8e1e3a79c786e3d808a73d23b6d212b16 html_url: https://github.com/octocat/Hello-World/git/commit/18a43cd8e1e3a79c786e3d808a73d23b6d212b16 author: date: '2014-11-07T22:01:45Z' name: Monalisa Octocat email: octocat@github.com committer: date: '2014-11-07T22:01:45Z' name: Monalisa Octocat email: octocat@github.com message: my commit message tree: url: https://api.github.com/repos/octocat/Hello-World/git/trees/9a21f8e2018f42ffcf369b24d2cd20bc25c9e66f sha: 9a21f8e2018f42ffcf369b24d2cd20bc25c9e66f parents: - url: https://api.github.com/repos/octocat/Hello-World/git/commits/da5a433788da5c255edad7979b328b67d79f53f6 html_url: https://github.com/octocat/Hello-World/git/commit/da5a433788da5c255edad7979b328b67d79f53f6 sha: da5a433788da5c255edad7979b328b67d79f53f6 verification: verified: false reason: unsigned signature: payload: file-commit-example-for-creating-a-file: value: content: name: hello.txt path: notes/hello.txt sha: 95b966ae1c166bd92f8ae7d1c313e738c731dfc3 size: 9 url: https://api.github.com/repos/octocat/Hello-World/contents/notes/hello.txt html_url: https://github.com/octocat/Hello-World/blob/master/notes/hello.txt git_url: https://api.github.com/repos/octocat/Hello-World/git/blobs/95b966ae1c166bd92f8ae7d1c313e738c731dfc3 download_url: https://raw.githubusercontent.com/octocat/HelloWorld/master/notes/hello.txt type: file _links: self: https://api.github.com/repos/octocat/Hello-World/contents/notes/hello.txt git: https://api.github.com/repos/octocat/Hello-World/git/blobs/95b966ae1c166bd92f8ae7d1c313e738c731dfc3 html: https://github.com/octocat/Hello-World/blob/master/notes/hello.txt commit: sha: 7638417db6d59f3c431d3e1f261cc637155684cd node_id: MDY6Q29tbWl0NzYzODQxN2RiNmQ1OWYzYzQzMWQzZTFmMjYxY2M2MzcxNTU2ODRjZA== url: https://api.github.com/repos/octocat/Hello-World/git/commits/7638417db6d59f3c431d3e1f261cc637155684cd html_url: https://github.com/octocat/Hello-World/git/commit/7638417db6d59f3c431d3e1f261cc637155684cd author: date: '2014-11-07T22:01:45Z' name: Monalisa Octocat email: octocat@github.com committer: date: '2014-11-07T22:01:45Z' name: Monalisa Octocat email: octocat@github.com message: my commit message tree: url: https://api.github.com/repos/octocat/Hello-World/git/trees/691272480426f78a0138979dd3ce63b77f706feb sha: 691272480426f78a0138979dd3ce63b77f706feb parents: - url: https://api.github.com/repos/octocat/Hello-World/git/commits/1acc419d4d6a9ce985db7be48c6349a0475975b5 html_url: https://github.com/octocat/Hello-World/git/commit/1acc419d4d6a9ce985db7be48c6349a0475975b5 sha: 1acc419d4d6a9ce985db7be48c6349a0475975b5 verification: verified: false reason: unsigned signature: payload: file-commit: value: content: commit: sha: 7638417db6d59f3c431d3e1f261cc637155684cd node_id: MDY6Q29tbWl0NzYzODQxN2RiNmQ1OWYzYzQzMWQzZTFmMjYxY2M2MzcxNTU2ODRjZA== url: https://api.github.com/repos/octocat/Hello-World/git/commits/7638417db6d59f3c431d3e1f261cc637155684cd html_url: https://github.com/octocat/Hello-World/git/commit/7638417db6d59f3c431d3e1f261cc637155684cd author: date: '2014-11-07T22:01:45Z' name: Monalisa Octocat email: octocat@github.com committer: date: '2014-11-07T22:01:45Z' name: Monalisa Octocat email: octocat@github.com message: my commit message tree: url: https://api.github.com/repos/octocat/Hello-World/git/trees/691272480426f78a0138979dd3ce63b77f706feb sha: 691272480426f78a0138979dd3ce63b77f706feb parents: - url: https://api.github.com/repos/octocat/Hello-World/git/commits/1acc419d4d6a9ce985db7be48c6349a0475975b5 html_url: https://github.com/octocat/Hello-World/git/commit/1acc419d4d6a9ce985db7be48c6349a0475975b5 sha: 1acc419d4d6a9ce985db7be48c6349a0475975b5 verification: verified: false reason: unsigned signature: payload: contributor-items-response-if-repository-contains-content: value: - login: octocat id: 1 node_id: MDQ6VXNlcjE= avatar_url: https://github.com/images/error/octocat_happy.gif gravatar_id: '' url: https://api.github.com/users/octocat html_url: https://github.com/octocat followers_url: https://api.github.com/users/octocat/followers following_url: https://api.github.com/users/octocat/following{/other_user} gists_url: https://api.github.com/users/octocat/gists{/gist_id} starred_url: https://api.github.com/users/octocat/starred{/owner}{/repo} subscriptions_url: https://api.github.com/users/octocat/subscriptions organizations_url: https://api.github.com/users/octocat/orgs repos_url: https://api.github.com/users/octocat/repos events_url: https://api.github.com/users/octocat/events{/privacy} received_events_url: https://api.github.com/users/octocat/received_events type: User site_admin: false contributions: 32 deployment-items: value: - url: https://api.github.com/repos/octocat/example/deployments/1 id: 1 node_id: MDEwOkRlcGxveW1lbnQx sha: a84d88e7554fc1fa21bcbc4efae3c782a70d2b9d ref: topic-branch task: deploy payload: {} original_environment: staging environment: production description: Deploy request from hubot creator: login: octocat id: 1 node_id: MDQ6VXNlcjE= avatar_url: https://github.com/images/error/octocat_happy.gif gravatar_id: '' url: https://api.github.com/users/octocat html_url: https://github.com/octocat followers_url: https://api.github.com/users/octocat/followers following_url: https://api.github.com/users/octocat/following{/other_user} gists_url: https://api.github.com/users/octocat/gists{/gist_id} starred_url: https://api.github.com/users/octocat/starred{/owner}{/repo} subscriptions_url: https://api.github.com/users/octocat/subscriptions organizations_url: https://api.github.com/users/octocat/orgs repos_url: https://api.github.com/users/octocat/repos events_url: https://api.github.com/users/octocat/events{/privacy} received_events_url: https://api.github.com/users/octocat/received_events type: User site_admin: false created_at: '2012-07-20T01:19:13Z' updated_at: '2012-07-20T01:19:13Z' statuses_url: https://api.github.com/repos/octocat/example/deployments/1/statuses repository_url: https://api.github.com/repos/octocat/example transient_environment: false production_environment: true deployment-simple-example: summary: Simple example value: url: https://api.github.com/repos/octocat/example/deployments/1 id: 1 node_id: MDEwOkRlcGxveW1lbnQx sha: a84d88e7554fc1fa21bcbc4efae3c782a70d2b9d ref: topic-branch task: deploy payload: {} original_environment: staging environment: production description: Deploy request from hubot creator: login: octocat id: 1 node_id: MDQ6VXNlcjE= avatar_url: https://github.com/images/error/octocat_happy.gif gravatar_id: '' url: https://api.github.com/users/octocat html_url: https://github.com/octocat followers_url: https://api.github.com/users/octocat/followers following_url: https://api.github.com/users/octocat/following{/other_user} gists_url: https://api.github.com/users/octocat/gists{/gist_id} starred_url: https://api.github.com/users/octocat/starred{/owner}{/repo} subscriptions_url: https://api.github.com/users/octocat/subscriptions organizations_url: https://api.github.com/users/octocat/orgs repos_url: https://api.github.com/users/octocat/repos events_url: https://api.github.com/users/octocat/events{/privacy} received_events_url: https://api.github.com/users/octocat/received_events type: User site_admin: false created_at: '2012-07-20T01:19:13Z' updated_at: '2012-07-20T01:19:13Z' statuses_url: https://api.github.com/repos/octocat/example/deployments/1/statuses repository_url: https://api.github.com/repos/octocat/example transient_environment: false production_environment: true deployment: value: url: https://api.github.com/repos/octocat/example/deployments/1 id: 1 node_id: MDEwOkRlcGxveW1lbnQx sha: a84d88e7554fc1fa21bcbc4efae3c782a70d2b9d ref: topic-branch task: deploy payload: {} original_environment: staging environment: production description: Deploy request from hubot creator: login: octocat id: 1 node_id: MDQ6VXNlcjE= avatar_url: https://github.com/images/error/octocat_happy.gif gravatar_id: '' url: https://api.github.com/users/octocat html_url: https://github.com/octocat followers_url: https://api.github.com/users/octocat/followers following_url: https://api.github.com/users/octocat/following{/other_user} gists_url: https://api.github.com/users/octocat/gists{/gist_id} starred_url: https://api.github.com/users/octocat/starred{/owner}{/repo} subscriptions_url: https://api.github.com/users/octocat/subscriptions organizations_url: https://api.github.com/users/octocat/orgs repos_url: https://api.github.com/users/octocat/repos events_url: https://api.github.com/users/octocat/events{/privacy} received_events_url: https://api.github.com/users/octocat/received_events type: User site_admin: false created_at: '2012-07-20T01:19:13Z' updated_at: '2012-07-20T01:19:13Z' statuses_url: https://api.github.com/repos/octocat/example/deployments/1/statuses repository_url: https://api.github.com/repos/octocat/example transient_environment: false production_environment: true deployment-status-items: value: - url: https://api.github.com/repos/octocat/example/deployments/42/statuses/1 id: 1 node_id: MDE2OkRlcGxveW1lbnRTdGF0dXMx state: success creator: login: octocat id: 1 node_id: MDQ6VXNlcjE= avatar_url: https://github.com/images/error/octocat_happy.gif gravatar_id: '' url: https://api.github.com/users/octocat html_url: https://github.com/octocat followers_url: https://api.github.com/users/octocat/followers following_url: https://api.github.com/users/octocat/following{/other_user} gists_url: https://api.github.com/users/octocat/gists{/gist_id} starred_url: https://api.github.com/users/octocat/starred{/owner}{/repo} subscriptions_url: https://api.github.com/users/octocat/subscriptions organizations_url: https://api.github.com/users/octocat/orgs repos_url: https://api.github.com/users/octocat/repos events_url: https://api.github.com/users/octocat/events{/privacy} received_events_url: https://api.github.com/users/octocat/received_events type: User site_admin: false description: Deployment finished successfully. environment: production target_url: https://example.com/deployment/42/output created_at: '2012-07-20T01:19:13Z' updated_at: '2012-07-20T01:19:13Z' deployment_url: https://api.github.com/repos/octocat/example/deployments/42 repository_url: https://api.github.com/repos/octocat/example environment_url: https://test-branch.lab.acme.com log_url: https://example.com/deployment/42/output deployment-status: value: url: https://api.github.com/repos/octocat/example/deployments/42/statuses/1 id: 1 node_id: MDE2OkRlcGxveW1lbnRTdGF0dXMx state: success creator: login: octocat id: 1 node_id: MDQ6VXNlcjE= avatar_url: https://github.com/images/error/octocat_happy.gif gravatar_id: '' url: https://api.github.com/users/octocat html_url: https://github.com/octocat followers_url: https://api.github.com/users/octocat/followers following_url: https://api.github.com/users/octocat/following{/other_user} gists_url: https://api.github.com/users/octocat/gists{/gist_id} starred_url: https://api.github.com/users/octocat/starred{/owner}{/repo} subscriptions_url: https://api.github.com/users/octocat/subscriptions organizations_url: https://api.github.com/users/octocat/orgs repos_url: https://api.github.com/users/octocat/repos events_url: https://api.github.com/users/octocat/events{/privacy} received_events_url: https://api.github.com/users/octocat/received_events type: User site_admin: false description: Deployment finished successfully. environment: production target_url: https://example.com/deployment/42/output created_at: '2012-07-20T01:19:13Z' updated_at: '2012-07-20T01:19:13Z' deployment_url: https://api.github.com/repos/octocat/example/deployments/42 repository_url: https://api.github.com/repos/octocat/example environment_url: https://test-branch.lab.acme.com log_url: https://example.com/deployment/42/output minimal-repository-items-2: value: - id: 1296269 node_id: MDEwOlJlcG9zaXRvcnkxMjk2MjY5 name: Hello-World full_name: octocat/Hello-World owner: login: octocat id: 1 node_id: MDQ6VXNlcjE= avatar_url: https://github.com/images/error/octocat_happy.gif gravatar_id: '' url: https://api.github.com/users/octocat html_url: https://github.com/octocat followers_url: https://api.github.com/users/octocat/followers following_url: https://api.github.com/users/octocat/following{/other_user} gists_url: https://api.github.com/users/octocat/gists{/gist_id} starred_url: https://api.github.com/users/octocat/starred{/owner}{/repo} subscriptions_url: https://api.github.com/users/octocat/subscriptions organizations_url: https://api.github.com/users/octocat/orgs repos_url: https://api.github.com/users/octocat/repos events_url: https://api.github.com/users/octocat/events{/privacy} received_events_url: https://api.github.com/users/octocat/received_events type: User site_admin: false private: false html_url: https://github.com/octocat/Hello-World description: This your first repo! fork: true url: https://api.github.com/repos/octocat/Hello-World archive_url: https://api.github.com/repos/octocat/Hello-World/{archive_format}{/ref} assignees_url: https://api.github.com/repos/octocat/Hello-World/assignees{/user} blobs_url: https://api.github.com/repos/octocat/Hello-World/git/blobs{/sha} branches_url: https://api.github.com/repos/octocat/Hello-World/branches{/branch} collaborators_url: https://api.github.com/repos/octocat/Hello-World/collaborators{/collaborator} comments_url: https://api.github.com/repos/octocat/Hello-World/comments{/number} commits_url: https://api.github.com/repos/octocat/Hello-World/commits{/sha} compare_url: https://api.github.com/repos/octocat/Hello-World/compare/{base}...{head} contents_url: https://api.github.com/repos/octocat/Hello-World/contents/{+path} contributors_url: https://api.github.com/repos/octocat/Hello-World/contributors deployments_url: https://api.github.com/repos/octocat/Hello-World/deployments downloads_url: https://api.github.com/repos/octocat/Hello-World/downloads events_url: https://api.github.com/repos/octocat/Hello-World/events forks_url: https://api.github.com/repos/octocat/Hello-World/forks git_commits_url: https://api.github.com/repos/octocat/Hello-World/git/commits{/sha} git_refs_url: https://api.github.com/repos/octocat/Hello-World/git/refs{/sha} git_tags_url: https://api.github.com/repos/octocat/Hello-World/git/tags{/sha} git_url: git:github.com/octocat/Hello-World.git issue_comment_url: https://api.github.com/repos/octocat/Hello-World/issues/comments{/number} issue_events_url: https://api.github.com/repos/octocat/Hello-World/issues/events{/number} issues_url: https://api.github.com/repos/octocat/Hello-World/issues{/number} keys_url: https://api.github.com/repos/octocat/Hello-World/keys{/key_id} labels_url: https://api.github.com/repos/octocat/Hello-World/labels{/name} languages_url: https://api.github.com/repos/octocat/Hello-World/languages merges_url: https://api.github.com/repos/octocat/Hello-World/merges milestones_url: https://api.github.com/repos/octocat/Hello-World/milestones{/number} notifications_url: https://api.github.com/repos/octocat/Hello-World/notifications{?since,all,participating} pulls_url: https://api.github.com/repos/octocat/Hello-World/pulls{/number} releases_url: https://api.github.com/repos/octocat/Hello-World/releases{/id} ssh_url: git@github.com:octocat/Hello-World.git stargazers_url: https://api.github.com/repos/octocat/Hello-World/stargazers statuses_url: https://api.github.com/repos/octocat/Hello-World/statuses/{sha} subscribers_url: https://api.github.com/repos/octocat/Hello-World/subscribers subscription_url: https://api.github.com/repos/octocat/Hello-World/subscription tags_url: https://api.github.com/repos/octocat/Hello-World/tags teams_url: https://api.github.com/repos/octocat/Hello-World/teams trees_url: https://api.github.com/repos/octocat/Hello-World/git/trees{/sha} clone_url: https://github.com/octocat/Hello-World.git mirror_url: git:git.example.com/octocat/Hello-World hooks_url: https://api.github.com/repos/octocat/Hello-World/hooks svn_url: https://svn.github.com/octocat/Hello-World homepage: https://github.com language: forks_count: 9 stargazers_count: 80 watchers_count: 80 size: 108 default_branch: master open_issues_count: 0 is_template: true topics: - octocat - atom - electron - api has_issues: true has_projects: true has_wiki: true has_pages: false has_downloads: true archived: false disabled: false visibility: public pushed_at: '2011-01-26T19:06:43Z' created_at: '2011-01-26T19:01:12Z' updated_at: '2011-01-26T19:14:43Z' permissions: admin: false push: false pull: true temp_clone_token: ABTLWHOULUVAXGTRYU7OC2876QJ2O delete_branch_on_merge: true subscribers_count: 42 network_count: 0 license: key: mit name: MIT License spdx_id: MIT url: https://api.github.com/licenses/mit node_id: MDc6TGljZW5zZW1pdA== short-blob: value: url: https://api.github.com/repos/octocat/example/git/blobs/3a0f86fb8db8eea7ccbb9a95f325ddbedfb25e15 sha: 3a0f86fb8db8eea7ccbb9a95f325ddbedfb25e15 blob: value: content: Q29udGVudCBvZiB0aGUgYmxvYg== encoding: base64 url: https://api.github.com/repos/octocat/example/git/blobs/3a0f86fb8db8eea7ccbb9a95f325ddbedfb25e15 sha: 3a0f86fb8db8eea7ccbb9a95f325ddbedfb25e15 size: 19 node_id: Q29udGVudCBvZiB0aGUgYmxvYg== git-commit: value: sha: 7638417db6d59f3c431d3e1f261cc637155684cd node_id: MDY6Q29tbWl0NzYzODQxN2RiNmQ1OWYzYzQzMWQzZTFmMjYxY2M2MzcxNTU2ODRjZA== url: https://api.github.com/repos/octocat/Hello-World/git/commits/7638417db6d59f3c431d3e1f261cc637155684cd author: date: '2014-11-07T22:01:45Z' name: Monalisa Octocat email: octocat@github.com committer: date: '2014-11-07T22:01:45Z' name: Monalisa Octocat email: octocat@github.com message: my commit message tree: url: https://api.github.com/repos/octocat/Hello-World/git/trees/827efc6d56897b048c772eb4087f854f46256132 sha: 827efc6d56897b048c772eb4087f854f46256132 parents: - url: https://api.github.com/repos/octocat/Hello-World/git/commits/7d1b31e74ee336d15cbd21741bc88a537ed063a0 sha: 7d1b31e74ee336d15cbd21741bc88a537ed063a0 html_url: https://github.com/octocat/Hello-World/commit/7d1b31e74ee336d15cbd21741bc88a537ed063a0 verification: verified: false reason: unsigned signature: payload: html_url: https://github.com/octocat/Hello-World/commit/7638417db6d59f3c431d3e1f261cc637155684cd git-commit-2: value: sha: 7638417db6d59f3c431d3e1f261cc637155684cd node_id: MDY6Q29tbWl0NmRjYjA5YjViNTc4NzVmMzM0ZjYxYWViZWQ2OTVlMmU0MTkzZGI1ZQ== url: https://api.github.com/repos/octocat/Hello-World/git/commits/7638417db6d59f3c431d3e1f261cc637155684cd html_url: https://github.com/octocat/Hello-World/commit/7638417db6d59f3c431d3e1f261cc637155684cd author: date: '2014-11-07T22:01:45Z' name: Monalisa Octocat email: octocat@github.com committer: date: '2014-11-07T22:01:45Z' name: Monalisa Octocat email: octocat@github.com message: added readme, because im a good github citizen tree: url: https://api.github.com/repos/octocat/Hello-World/git/trees/691272480426f78a0138979dd3ce63b77f706feb sha: 691272480426f78a0138979dd3ce63b77f706feb parents: - url: https://api.github.com/repos/octocat/Hello-World/git/commits/1acc419d4d6a9ce985db7be48c6349a0475975b5 sha: 1acc419d4d6a9ce985db7be48c6349a0475975b5 html_url: https://github.com/octocat/Hello-World/commit/7638417db6d59f3c431d3e1f261cc637155684cd verification: verified: false reason: unsigned signature: payload: git-ref-items: value: - ref: refs/heads/feature-a node_id: MDM6UmVmcmVmcy9oZWFkcy9mZWF0dXJlLWE= url: https://api.github.com/repos/octocat/Hello-World/git/refs/heads/feature-a object: type: commit sha: aa218f56b14c9653891f9e74264a383fa43fefbd url: https://api.github.com/repos/octocat/Hello-World/git/commits/aa218f56b14c9653891f9e74264a383fa43fefbd - ref: refs/heads/feature-b node_id: MDM6UmVmcmVmcy9oZWFkcy9mZWF0dXJlLWI= url: https://api.github.com/repos/octocat/Hello-World/git/refs/heads/feature-b object: type: commit sha: 612077ae6dffb4d2fbd8ce0cccaa58893b07b5ac url: https://api.github.com/repos/octocat/Hello-World/git/commits/612077ae6dffb4d2fbd8ce0cccaa58893b07b5ac git-ref: value: ref: refs/heads/featureA node_id: MDM6UmVmcmVmcy9oZWFkcy9mZWF0dXJlQQ== url: https://api.github.com/repos/octocat/Hello-World/git/refs/heads/featureA object: type: commit sha: aa218f56b14c9653891f9e74264a383fa43fefbd url: https://api.github.com/repos/octocat/Hello-World/git/commits/aa218f56b14c9653891f9e74264a383fa43fefbd git-tag: value: node_id: MDM6VGFnOTQwYmQzMzYyNDhlZmFlMGY5ZWU1YmM3YjJkNWM5ODU4ODdiMTZhYw== tag: v0.0.1 sha: 940bd336248efae0f9ee5bc7b2d5c985887b16ac url: https://api.github.com/repos/octocat/Hello-World/git/tags/940bd336248efae0f9ee5bc7b2d5c985887b16ac message: initial version tagger: name: Monalisa Octocat email: octocat@github.com date: '2014-11-07T22:01:45Z' object: type: commit sha: c3d0be41ecbe669545ee3e94d31ed9a4bc91ee3c url: https://api.github.com/repos/octocat/Hello-World/git/commits/c3d0be41ecbe669545ee3e94d31ed9a4bc91ee3c verification: verified: false reason: unsigned signature: payload: git-tree: value: sha: cd8274d15fa3ae2ab983129fb037999f264ba9a7 url: https://api.github.com/repos/octocat/Hello-World/trees/cd8274d15fa3ae2ab983129fb037999f264ba9a7 tree: - path: file.rb mode: '100644' type: blob size: 132 sha: 7c258a9869f33c1e1e1f74fbb32f07c86cb5a75b url: https://api.github.com/repos/octocat/Hello-World/git/blobs/7c258a9869f33c1e1e1f74fbb32f07c86cb5a75b truncated: true git-tree-default-response: summary: Default response value: sha: 9fb037999f264ba9a7fc6274d15fa3ae2ab98312 url: https://api.github.com/repos/octocat/Hello-World/trees/9fb037999f264ba9a7fc6274d15fa3ae2ab98312 tree: - path: file.rb mode: '100644' type: blob size: 30 sha: 44b4fc6d56897b048c772eb4087f854f46256132 url: https://api.github.com/repos/octocat/Hello-World/git/blobs/44b4fc6d56897b048c772eb4087f854f46256132 - path: subdir mode: '040000' type: tree sha: f484d249c660418515fb01c2b9662073663c242e url: https://api.github.com/repos/octocat/Hello-World/git/blobs/f484d249c660418515fb01c2b9662073663c242e - path: exec_file mode: '100755' type: blob size: 75 sha: 45b983be36b73c0788dc9cbcb76cbb80fc7bb057 url: https://api.github.com/repos/octocat/Hello-World/git/blobs/45b983be36b73c0788dc9cbcb76cbb80fc7bb057 truncated: false git-tree-response-recursively-retrieving-a-tree: summary: Response recursively retrieving a tree value: sha: fc6274d15fa3ae2ab983129fb037999f264ba9a7 url: https://api.github.com/repos/octocat/Hello-World/trees/fc6274d15fa3ae2ab983129fb037999f264ba9a7 tree: - path: subdir/file.txt mode: '100644' type: blob size: 132 sha: 7c258a9869f33c1e1e1f74fbb32f07c86cb5a75b url: https://api.github.com/repos/octocat/Hello-World/git/7c258a9869f33c1e1e1f74fbb32f07c86cb5a75b truncated: false hook-items: value: - type: Repository id: 12345678 name: web active: true events: - push - pull_request config: content_type: json insecure_ssl: '0' url: https://example.com/webhook updated_at: '2019-06-03T00:57:16Z' created_at: '2019-06-03T00:57:16Z' url: https://api.github.com/repos/octocat/Hello-World/hooks/12345678 test_url: https://api.github.com/repos/octocat/Hello-World/hooks/12345678/test ping_url: https://api.github.com/repos/octocat/Hello-World/hooks/12345678/pings last_response: code: status: unused message: hook: value: type: Repository id: 12345678 name: web active: true events: - push - pull_request config: content_type: json insecure_ssl: '0' url: https://example.com/webhook updated_at: '2019-06-03T00:57:16Z' created_at: '2019-06-03T00:57:16Z' url: https://api.github.com/repos/octocat/Hello-World/hooks/12345678 test_url: https://api.github.com/repos/octocat/Hello-World/hooks/12345678/test ping_url: https://api.github.com/repos/octocat/Hello-World/hooks/12345678/pings last_response: code: status: unused message: repository-invitation-items: value: - id: 1 repository: id: 1296269 node_id: MDEwOlJlcG9zaXRvcnkxMjk2MjY5 name: Hello-World full_name: octocat/Hello-World owner: login: octocat id: 1 node_id: MDQ6VXNlcjE= avatar_url: https://github.com/images/error/octocat_happy.gif gravatar_id: '' url: https://api.github.com/users/octocat html_url: https://github.com/octocat followers_url: https://api.github.com/users/octocat/followers following_url: https://api.github.com/users/octocat/following{/other_user} gists_url: https://api.github.com/users/octocat/gists{/gist_id} starred_url: https://api.github.com/users/octocat/starred{/owner}{/repo} subscriptions_url: https://api.github.com/users/octocat/subscriptions organizations_url: https://api.github.com/users/octocat/orgs repos_url: https://api.github.com/users/octocat/repos events_url: https://api.github.com/users/octocat/events{/privacy} received_events_url: https://api.github.com/users/octocat/received_events type: User site_admin: false private: false html_url: https://github.com/octocat/Hello-World description: This your first repo! fork: false url: https://api.github.com/repos/octocat/Hello-World archive_url: https://api.github.com/repos/octocat/Hello-World/{archive_format}{/ref} assignees_url: https://api.github.com/repos/octocat/Hello-World/assignees{/user} blobs_url: https://api.github.com/repos/octocat/Hello-World/git/blobs{/sha} branches_url: https://api.github.com/repos/octocat/Hello-World/branches{/branch} collaborators_url: https://api.github.com/repos/octocat/Hello-World/collaborators{/collaborator} comments_url: https://api.github.com/repos/octocat/Hello-World/comments{/number} commits_url: https://api.github.com/repos/octocat/Hello-World/commits{/sha} compare_url: https://api.github.com/repos/octocat/Hello-World/compare/{base}...{head} contents_url: https://api.github.com/repos/octocat/Hello-World/contents/{+path} contributors_url: https://api.github.com/repos/octocat/Hello-World/contributors deployments_url: https://api.github.com/repos/octocat/Hello-World/deployments downloads_url: https://api.github.com/repos/octocat/Hello-World/downloads events_url: https://api.github.com/repos/octocat/Hello-World/events forks_url: https://api.github.com/repos/octocat/Hello-World/forks git_commits_url: https://api.github.com/repos/octocat/Hello-World/git/commits{/sha} git_refs_url: https://api.github.com/repos/octocat/Hello-World/git/refs{/sha} git_tags_url: https://api.github.com/repos/octocat/Hello-World/git/tags{/sha} git_url: git:github.com/octocat/Hello-World.git issue_comment_url: https://api.github.com/repos/octocat/Hello-World/issues/comments{/number} issue_events_url: https://api.github.com/repos/octocat/Hello-World/issues/events{/number} issues_url: https://api.github.com/repos/octocat/Hello-World/issues{/number} keys_url: https://api.github.com/repos/octocat/Hello-World/keys{/key_id} labels_url: https://api.github.com/repos/octocat/Hello-World/labels{/name} languages_url: https://api.github.com/repos/octocat/Hello-World/languages merges_url: https://api.github.com/repos/octocat/Hello-World/merges milestones_url: https://api.github.com/repos/octocat/Hello-World/milestones{/number} notifications_url: https://api.github.com/repos/octocat/Hello-World/notifications{?since,all,participating} pulls_url: https://api.github.com/repos/octocat/Hello-World/pulls{/number} releases_url: https://api.github.com/repos/octocat/Hello-World/releases{/id} ssh_url: git@github.com:octocat/Hello-World.git stargazers_url: https://api.github.com/repos/octocat/Hello-World/stargazers statuses_url: https://api.github.com/repos/octocat/Hello-World/statuses/{sha} subscribers_url: https://api.github.com/repos/octocat/Hello-World/subscribers subscription_url: https://api.github.com/repos/octocat/Hello-World/subscription tags_url: https://api.github.com/repos/octocat/Hello-World/tags teams_url: https://api.github.com/repos/octocat/Hello-World/teams trees_url: https://api.github.com/repos/octocat/Hello-World/git/trees{/sha} hooks_url: http://api.github.com/repos/octocat/Hello-World/hooks invitee: login: octocat id: 1 node_id: MDQ6VXNlcjE= avatar_url: https://github.com/images/error/octocat_happy.gif gravatar_id: '' url: https://api.github.com/users/octocat html_url: https://github.com/octocat followers_url: https://api.github.com/users/octocat/followers following_url: https://api.github.com/users/octocat/following{/other_user} gists_url: https://api.github.com/users/octocat/gists{/gist_id} starred_url: https://api.github.com/users/octocat/starred{/owner}{/repo} subscriptions_url: https://api.github.com/users/octocat/subscriptions organizations_url: https://api.github.com/users/octocat/orgs repos_url: https://api.github.com/users/octocat/repos events_url: https://api.github.com/users/octocat/events{/privacy} received_events_url: https://api.github.com/users/octocat/received_events type: User site_admin: false inviter: login: octocat id: 1 node_id: MDQ6VXNlcjE= avatar_url: https://github.com/images/error/octocat_happy.gif gravatar_id: '' url: https://api.github.com/users/octocat html_url: https://github.com/octocat followers_url: https://api.github.com/users/octocat/followers following_url: https://api.github.com/users/octocat/following{/other_user} gists_url: https://api.github.com/users/octocat/gists{/gist_id} starred_url: https://api.github.com/users/octocat/starred{/owner}{/repo} subscriptions_url: https://api.github.com/users/octocat/subscriptions organizations_url: https://api.github.com/users/octocat/orgs repos_url: https://api.github.com/users/octocat/repos events_url: https://api.github.com/users/octocat/events{/privacy} received_events_url: https://api.github.com/users/octocat/received_events type: User site_admin: false permissions: write created_at: '2016-06-13T14:52:50-05:00' url: https://api.github.com/user/repository_invitations/1296269 html_url: https://github.com/octocat/Hello-World/invitations node_id: MDQ6VXNlcjE= repository-invitation: value: id: 1 node_id: MDEwOlJlcG9zaXRvcnkxMjk2MjY5 repository: id: 1296269 node_id: MDEwOlJlcG9zaXRvcnkxMjk2MjY5 name: Hello-World full_name: octocat/Hello-World owner: login: octocat id: 1 node_id: MDQ6VXNlcjE= avatar_url: https://github.com/images/error/octocat_happy.gif gravatar_id: '' url: https://api.github.com/users/octocat html_url: https://github.com/octocat followers_url: https://api.github.com/users/octocat/followers following_url: https://api.github.com/users/octocat/following{/other_user} gists_url: https://api.github.com/users/octocat/gists{/gist_id} starred_url: https://api.github.com/users/octocat/starred{/owner}{/repo} subscriptions_url: https://api.github.com/users/octocat/subscriptions organizations_url: https://api.github.com/users/octocat/orgs repos_url: https://api.github.com/users/octocat/repos events_url: https://api.github.com/users/octocat/events{/privacy} received_events_url: https://api.github.com/users/octocat/received_events type: User site_admin: false private: false html_url: https://github.com/octocat/Hello-World description: This your first repo! fork: false url: https://api.github.com/repos/octocat/Hello-World archive_url: https://api.github.com/repos/octocat/Hello-World/{archive_format}{/ref} assignees_url: https://api.github.com/repos/octocat/Hello-World/assignees{/user} blobs_url: https://api.github.com/repos/octocat/Hello-World/git/blobs{/sha} branches_url: https://api.github.com/repos/octocat/Hello-World/branches{/branch} collaborators_url: https://api.github.com/repos/octocat/Hello-World/collaborators{/collaborator} comments_url: https://api.github.com/repos/octocat/Hello-World/comments{/number} commits_url: https://api.github.com/repos/octocat/Hello-World/commits{/sha} compare_url: https://api.github.com/repos/octocat/Hello-World/compare/{base}...{head} contents_url: https://api.github.com/repos/octocat/Hello-World/contents/{+path} contributors_url: https://api.github.com/repos/octocat/Hello-World/contributors deployments_url: https://api.github.com/repos/octocat/Hello-World/deployments downloads_url: https://api.github.com/repos/octocat/Hello-World/downloads events_url: https://api.github.com/repos/octocat/Hello-World/events forks_url: https://api.github.com/repos/octocat/Hello-World/forks git_commits_url: https://api.github.com/repos/octocat/Hello-World/git/commits{/sha} git_refs_url: https://api.github.com/repos/octocat/Hello-World/git/refs{/sha} git_tags_url: https://api.github.com/repos/octocat/Hello-World/git/tags{/sha} git_url: git:github.com/octocat/Hello-World.git issue_comment_url: https://api.github.com/repos/octocat/Hello-World/issues/comments{/number} issue_events_url: https://api.github.com/repos/octocat/Hello-World/issues/events{/number} issues_url: https://api.github.com/repos/octocat/Hello-World/issues{/number} keys_url: https://api.github.com/repos/octocat/Hello-World/keys{/key_id} labels_url: https://api.github.com/repos/octocat/Hello-World/labels{/name} languages_url: https://api.github.com/repos/octocat/Hello-World/languages merges_url: https://api.github.com/repos/octocat/Hello-World/merges milestones_url: https://api.github.com/repos/octocat/Hello-World/milestones{/number} notifications_url: https://api.github.com/repos/octocat/Hello-World/notifications{?since,all,participating} pulls_url: https://api.github.com/repos/octocat/Hello-World/pulls{/number} releases_url: https://api.github.com/repos/octocat/Hello-World/releases{/id} ssh_url: git@github.com:octocat/Hello-World.git stargazers_url: https://api.github.com/repos/octocat/Hello-World/stargazers statuses_url: https://api.github.com/repos/octocat/Hello-World/statuses/{sha} subscribers_url: https://api.github.com/repos/octocat/Hello-World/subscribers subscription_url: https://api.github.com/repos/octocat/Hello-World/subscription tags_url: https://api.github.com/repos/octocat/Hello-World/tags teams_url: https://api.github.com/repos/octocat/Hello-World/teams trees_url: https://api.github.com/repos/octocat/Hello-World/git/trees{/sha} hooks_url: http://api.github.com/repos/octocat/Hello-World/hooks invitee: login: octocat id: 1 node_id: MDQ6VXNlcjE= avatar_url: https://github.com/images/error/octocat_happy.gif gravatar_id: '' url: https://api.github.com/users/octocat html_url: https://github.com/octocat followers_url: https://api.github.com/users/octocat/followers following_url: https://api.github.com/users/octocat/following{/other_user} gists_url: https://api.github.com/users/octocat/gists{/gist_id} starred_url: https://api.github.com/users/octocat/starred{/owner}{/repo} subscriptions_url: https://api.github.com/users/octocat/subscriptions organizations_url: https://api.github.com/users/octocat/orgs repos_url: https://api.github.com/users/octocat/repos events_url: https://api.github.com/users/octocat/events{/privacy} received_events_url: https://api.github.com/users/octocat/received_events type: User site_admin: false inviter: login: octocat id: 1 node_id: MDQ6VXNlcjE= avatar_url: https://github.com/images/error/octocat_happy.gif gravatar_id: '' url: https://api.github.com/users/octocat html_url: https://github.com/octocat followers_url: https://api.github.com/users/octocat/followers following_url: https://api.github.com/users/octocat/following{/other_user} gists_url: https://api.github.com/users/octocat/gists{/gist_id} starred_url: https://api.github.com/users/octocat/starred{/owner}{/repo} subscriptions_url: https://api.github.com/users/octocat/subscriptions organizations_url: https://api.github.com/users/octocat/orgs repos_url: https://api.github.com/users/octocat/repos events_url: https://api.github.com/users/octocat/events{/privacy} received_events_url: https://api.github.com/users/octocat/received_events type: User site_admin: false permissions: write created_at: '2016-06-13T14:52:50-05:00' expired: false url: https://api.github.com/user/repository_invitations/1296269 html_url: https://github.com/octocat/Hello-World/invitations issue-items: value: - id: 1 node_id: MDU6SXNzdWUx url: https://api.github.com/repos/octocat/Hello-World/issues/1347 repository_url: https://api.github.com/repos/octocat/Hello-World labels_url: https://api.github.com/repos/octocat/Hello-World/issues/1347/labels{/name} comments_url: https://api.github.com/repos/octocat/Hello-World/issues/1347/comments events_url: https://api.github.com/repos/octocat/Hello-World/issues/1347/events html_url: https://github.com/octocat/Hello-World/issues/1347 number: 1347 state: open title: Found a bug body: I'm having a problem with this. user: login: octocat id: 1 node_id: MDQ6VXNlcjE= avatar_url: https://github.com/images/error/octocat_happy.gif gravatar_id: '' url: https://api.github.com/users/octocat html_url: https://github.com/octocat followers_url: https://api.github.com/users/octocat/followers following_url: https://api.github.com/users/octocat/following{/other_user} gists_url: https://api.github.com/users/octocat/gists{/gist_id} starred_url: https://api.github.com/users/octocat/starred{/owner}{/repo} subscriptions_url: https://api.github.com/users/octocat/subscriptions organizations_url: https://api.github.com/users/octocat/orgs repos_url: https://api.github.com/users/octocat/repos events_url: https://api.github.com/users/octocat/events{/privacy} received_events_url: https://api.github.com/users/octocat/received_events type: User site_admin: false labels: - id: 208045946 node_id: MDU6TGFiZWwyMDgwNDU5NDY= url: https://api.github.com/repos/octocat/Hello-World/labels/bug name: bug description: Something isn't working color: f29513 default: true assignee: login: octocat id: 1 node_id: MDQ6VXNlcjE= avatar_url: https://github.com/images/error/octocat_happy.gif gravatar_id: '' url: https://api.github.com/users/octocat html_url: https://github.com/octocat followers_url: https://api.github.com/users/octocat/followers following_url: https://api.github.com/users/octocat/following{/other_user} gists_url: https://api.github.com/users/octocat/gists{/gist_id} starred_url: https://api.github.com/users/octocat/starred{/owner}{/repo} subscriptions_url: https://api.github.com/users/octocat/subscriptions organizations_url: https://api.github.com/users/octocat/orgs repos_url: https://api.github.com/users/octocat/repos events_url: https://api.github.com/users/octocat/events{/privacy} received_events_url: https://api.github.com/users/octocat/received_events type: User site_admin: false assignees: - login: octocat id: 1 node_id: MDQ6VXNlcjE= avatar_url: https://github.com/images/error/octocat_happy.gif gravatar_id: '' url: https://api.github.com/users/octocat html_url: https://github.com/octocat followers_url: https://api.github.com/users/octocat/followers following_url: https://api.github.com/users/octocat/following{/other_user} gists_url: https://api.github.com/users/octocat/gists{/gist_id} starred_url: https://api.github.com/users/octocat/starred{/owner}{/repo} subscriptions_url: https://api.github.com/users/octocat/subscriptions organizations_url: https://api.github.com/users/octocat/orgs repos_url: https://api.github.com/users/octocat/repos events_url: https://api.github.com/users/octocat/events{/privacy} received_events_url: https://api.github.com/users/octocat/received_events type: User site_admin: false milestone: url: https://api.github.com/repos/octocat/Hello-World/milestones/1 html_url: https://github.com/octocat/Hello-World/milestones/v1.0 labels_url: https://api.github.com/repos/octocat/Hello-World/milestones/1/labels id: 1002604 node_id: MDk6TWlsZXN0b25lMTAwMjYwNA== number: 1 state: open title: v1.0 description: Tracking milestone for version 1.0 creator: login: octocat id: 1 node_id: MDQ6VXNlcjE= avatar_url: https://github.com/images/error/octocat_happy.gif gravatar_id: '' url: https://api.github.com/users/octocat html_url: https://github.com/octocat followers_url: https://api.github.com/users/octocat/followers following_url: https://api.github.com/users/octocat/following{/other_user} gists_url: https://api.github.com/users/octocat/gists{/gist_id} starred_url: https://api.github.com/users/octocat/starred{/owner}{/repo} subscriptions_url: https://api.github.com/users/octocat/subscriptions organizations_url: https://api.github.com/users/octocat/orgs repos_url: https://api.github.com/users/octocat/repos events_url: https://api.github.com/users/octocat/events{/privacy} received_events_url: https://api.github.com/users/octocat/received_events type: User site_admin: false open_issues: 4 closed_issues: 8 created_at: '2011-04-10T20:09:31Z' updated_at: '2014-03-03T18:58:10Z' closed_at: '2013-02-12T13:22:01Z' due_on: '2012-10-09T23:39:01Z' locked: true active_lock_reason: too heated comments: 0 pull_request: url: https://api.github.com/repos/octocat/Hello-World/pulls/1347 html_url: https://github.com/octocat/Hello-World/pull/1347 diff_url: https://github.com/octocat/Hello-World/pull/1347.diff patch_url: https://github.com/octocat/Hello-World/pull/1347.patch closed_at: created_at: '2011-04-22T13:33:48Z' updated_at: '2011-04-22T13:33:48Z' closed_by: login: octocat id: 1 node_id: MDQ6VXNlcjE= avatar_url: https://github.com/images/error/octocat_happy.gif gravatar_id: '' url: https://api.github.com/users/octocat html_url: https://github.com/octocat followers_url: https://api.github.com/users/octocat/followers following_url: https://api.github.com/users/octocat/following{/other_user} gists_url: https://api.github.com/users/octocat/gists{/gist_id} starred_url: https://api.github.com/users/octocat/starred{/owner}{/repo} subscriptions_url: https://api.github.com/users/octocat/subscriptions organizations_url: https://api.github.com/users/octocat/orgs repos_url: https://api.github.com/users/octocat/repos events_url: https://api.github.com/users/octocat/events{/privacy} received_events_url: https://api.github.com/users/octocat/received_events type: User site_admin: false author_association: COLLABORATOR issue: value: id: 1 node_id: MDU6SXNzdWUx url: https://api.github.com/repos/octocat/Hello-World/issues/1347 repository_url: https://api.github.com/repos/octocat/Hello-World labels_url: https://api.github.com/repos/octocat/Hello-World/issues/1347/labels{/name} comments_url: https://api.github.com/repos/octocat/Hello-World/issues/1347/comments events_url: https://api.github.com/repos/octocat/Hello-World/issues/1347/events html_url: https://github.com/octocat/Hello-World/issues/1347 number: 1347 state: open title: Found a bug body: I'm having a problem with this. user: login: octocat id: 1 node_id: MDQ6VXNlcjE= avatar_url: https://github.com/images/error/octocat_happy.gif gravatar_id: '' url: https://api.github.com/users/octocat html_url: https://github.com/octocat followers_url: https://api.github.com/users/octocat/followers following_url: https://api.github.com/users/octocat/following{/other_user} gists_url: https://api.github.com/users/octocat/gists{/gist_id} starred_url: https://api.github.com/users/octocat/starred{/owner}{/repo} subscriptions_url: https://api.github.com/users/octocat/subscriptions organizations_url: https://api.github.com/users/octocat/orgs repos_url: https://api.github.com/users/octocat/repos events_url: https://api.github.com/users/octocat/events{/privacy} received_events_url: https://api.github.com/users/octocat/received_events type: User site_admin: false labels: - id: 208045946 node_id: MDU6TGFiZWwyMDgwNDU5NDY= url: https://api.github.com/repos/octocat/Hello-World/labels/bug name: bug description: Something isn't working color: f29513 default: true assignee: login: octocat id: 1 node_id: MDQ6VXNlcjE= avatar_url: https://github.com/images/error/octocat_happy.gif gravatar_id: '' url: https://api.github.com/users/octocat html_url: https://github.com/octocat followers_url: https://api.github.com/users/octocat/followers following_url: https://api.github.com/users/octocat/following{/other_user} gists_url: https://api.github.com/users/octocat/gists{/gist_id} starred_url: https://api.github.com/users/octocat/starred{/owner}{/repo} subscriptions_url: https://api.github.com/users/octocat/subscriptions organizations_url: https://api.github.com/users/octocat/orgs repos_url: https://api.github.com/users/octocat/repos events_url: https://api.github.com/users/octocat/events{/privacy} received_events_url: https://api.github.com/users/octocat/received_events type: User site_admin: false assignees: - login: octocat id: 1 node_id: MDQ6VXNlcjE= avatar_url: https://github.com/images/error/octocat_happy.gif gravatar_id: '' url: https://api.github.com/users/octocat html_url: https://github.com/octocat followers_url: https://api.github.com/users/octocat/followers following_url: https://api.github.com/users/octocat/following{/other_user} gists_url: https://api.github.com/users/octocat/gists{/gist_id} starred_url: https://api.github.com/users/octocat/starred{/owner}{/repo} subscriptions_url: https://api.github.com/users/octocat/subscriptions organizations_url: https://api.github.com/users/octocat/orgs repos_url: https://api.github.com/users/octocat/repos events_url: https://api.github.com/users/octocat/events{/privacy} received_events_url: https://api.github.com/users/octocat/received_events type: User site_admin: false milestone: url: https://api.github.com/repos/octocat/Hello-World/milestones/1 html_url: https://github.com/octocat/Hello-World/milestones/v1.0 labels_url: https://api.github.com/repos/octocat/Hello-World/milestones/1/labels id: 1002604 node_id: MDk6TWlsZXN0b25lMTAwMjYwNA== number: 1 state: open title: v1.0 description: Tracking milestone for version 1.0 creator: login: octocat id: 1 node_id: MDQ6VXNlcjE= avatar_url: https://github.com/images/error/octocat_happy.gif gravatar_id: '' url: https://api.github.com/users/octocat html_url: https://github.com/octocat followers_url: https://api.github.com/users/octocat/followers following_url: https://api.github.com/users/octocat/following{/other_user} gists_url: https://api.github.com/users/octocat/gists{/gist_id} starred_url: https://api.github.com/users/octocat/starred{/owner}{/repo} subscriptions_url: https://api.github.com/users/octocat/subscriptions organizations_url: https://api.github.com/users/octocat/orgs repos_url: https://api.github.com/users/octocat/repos events_url: https://api.github.com/users/octocat/events{/privacy} received_events_url: https://api.github.com/users/octocat/received_events type: User site_admin: false open_issues: 4 closed_issues: 8 created_at: '2011-04-10T20:09:31Z' updated_at: '2014-03-03T18:58:10Z' closed_at: '2013-02-12T13:22:01Z' due_on: '2012-10-09T23:39:01Z' locked: true active_lock_reason: too heated comments: 0 pull_request: url: https://api.github.com/repos/octocat/Hello-World/pulls/1347 html_url: https://github.com/octocat/Hello-World/pull/1347 diff_url: https://github.com/octocat/Hello-World/pull/1347.diff patch_url: https://github.com/octocat/Hello-World/pull/1347.patch closed_at: created_at: '2011-04-22T13:33:48Z' updated_at: '2011-04-22T13:33:48Z' closed_by: login: octocat id: 1 node_id: MDQ6VXNlcjE= avatar_url: https://github.com/images/error/octocat_happy.gif gravatar_id: '' url: https://api.github.com/users/octocat html_url: https://github.com/octocat followers_url: https://api.github.com/users/octocat/followers following_url: https://api.github.com/users/octocat/following{/other_user} gists_url: https://api.github.com/users/octocat/gists{/gist_id} starred_url: https://api.github.com/users/octocat/starred{/owner}{/repo} subscriptions_url: https://api.github.com/users/octocat/subscriptions organizations_url: https://api.github.com/users/octocat/orgs repos_url: https://api.github.com/users/octocat/repos events_url: https://api.github.com/users/octocat/events{/privacy} received_events_url: https://api.github.com/users/octocat/received_events type: User site_admin: false author_association: COLLABORATOR issue-comment-items: value: - id: 1 node_id: MDEyOklzc3VlQ29tbWVudDE= url: https://api.github.com/repos/octocat/Hello-World/issues/comments/1 html_url: https://github.com/octocat/Hello-World/issues/1347#issuecomment-1 body: Me too user: login: octocat id: 1 node_id: MDQ6VXNlcjE= avatar_url: https://github.com/images/error/octocat_happy.gif gravatar_id: '' url: https://api.github.com/users/octocat html_url: https://github.com/octocat followers_url: https://api.github.com/users/octocat/followers following_url: https://api.github.com/users/octocat/following{/other_user} gists_url: https://api.github.com/users/octocat/gists{/gist_id} starred_url: https://api.github.com/users/octocat/starred{/owner}{/repo} subscriptions_url: https://api.github.com/users/octocat/subscriptions organizations_url: https://api.github.com/users/octocat/orgs repos_url: https://api.github.com/users/octocat/repos events_url: https://api.github.com/users/octocat/events{/privacy} received_events_url: https://api.github.com/users/octocat/received_events type: User site_admin: false created_at: '2011-04-14T16:00:49Z' updated_at: '2011-04-14T16:00:49Z' issue_url: https://api.github.com/repos/octocat/Hello-World/issues/1347 author_association: COLLABORATOR issue-comment: value: id: 1 node_id: MDEyOklzc3VlQ29tbWVudDE= url: https://api.github.com/repos/octocat/Hello-World/issues/comments/1 html_url: https://github.com/octocat/Hello-World/issues/1347#issuecomment-1 body: Me too user: login: octocat id: 1 node_id: MDQ6VXNlcjE= avatar_url: https://github.com/images/error/octocat_happy.gif gravatar_id: '' url: https://api.github.com/users/octocat html_url: https://github.com/octocat followers_url: https://api.github.com/users/octocat/followers following_url: https://api.github.com/users/octocat/following{/other_user} gists_url: https://api.github.com/users/octocat/gists{/gist_id} starred_url: https://api.github.com/users/octocat/starred{/owner}{/repo} subscriptions_url: https://api.github.com/users/octocat/subscriptions organizations_url: https://api.github.com/users/octocat/orgs repos_url: https://api.github.com/users/octocat/repos events_url: https://api.github.com/users/octocat/events{/privacy} received_events_url: https://api.github.com/users/octocat/received_events type: User site_admin: false created_at: '2011-04-14T16:00:49Z' updated_at: '2011-04-14T16:00:49Z' issue_url: https://api.github.com/repos/octocat/Hello-World/issues/1347 author_association: COLLABORATOR issue-event-items: value: - id: 1 node_id: MDEwOklzc3VlRXZlbnQx url: https://api.github.com/repos/octocat/Hello-World/issues/events/1 actor: login: octocat id: 1 node_id: MDQ6VXNlcjE= avatar_url: https://github.com/images/error/octocat_happy.gif gravatar_id: '' url: https://api.github.com/users/octocat html_url: https://github.com/octocat followers_url: https://api.github.com/users/octocat/followers following_url: https://api.github.com/users/octocat/following{/other_user} gists_url: https://api.github.com/users/octocat/gists{/gist_id} starred_url: https://api.github.com/users/octocat/starred{/owner}{/repo} subscriptions_url: https://api.github.com/users/octocat/subscriptions organizations_url: https://api.github.com/users/octocat/orgs repos_url: https://api.github.com/users/octocat/repos events_url: https://api.github.com/users/octocat/events{/privacy} received_events_url: https://api.github.com/users/octocat/received_events type: User site_admin: false event: closed commit_id: 6dcb09b5b57875f334f61aebed695e2e4193db5e commit_url: https://api.github.com/repos/octocat/Hello-World/commits/6dcb09b5b57875f334f61aebed695e2e4193db5e created_at: '2011-04-14T16:00:49Z' issue: id: 1 node_id: MDU6SXNzdWUx url: https://api.github.com/repos/octocat/Hello-World/issues/1347 repository_url: https://api.github.com/repos/octocat/Hello-World labels_url: https://api.github.com/repos/octocat/Hello-World/issues/1347/labels{/name} comments_url: https://api.github.com/repos/octocat/Hello-World/issues/1347/comments events_url: https://api.github.com/repos/octocat/Hello-World/issues/1347/events html_url: https://github.com/octocat/Hello-World/issues/1347 number: 1347 state: open title: Found a bug body: I'm having a problem with this. user: login: octocat id: 1 node_id: MDQ6VXNlcjE= avatar_url: https://github.com/images/error/octocat_happy.gif gravatar_id: '' url: https://api.github.com/users/octocat html_url: https://github.com/octocat followers_url: https://api.github.com/users/octocat/followers following_url: https://api.github.com/users/octocat/following{/other_user} gists_url: https://api.github.com/users/octocat/gists{/gist_id} starred_url: https://api.github.com/users/octocat/starred{/owner}{/repo} subscriptions_url: https://api.github.com/users/octocat/subscriptions organizations_url: https://api.github.com/users/octocat/orgs repos_url: https://api.github.com/users/octocat/repos events_url: https://api.github.com/users/octocat/events{/privacy} received_events_url: https://api.github.com/users/octocat/received_events type: User site_admin: false labels: - id: 208045946 node_id: MDU6TGFiZWwyMDgwNDU5NDY= url: https://api.github.com/repos/octocat/Hello-World/labels/bug name: bug description: Something isn't working color: f29513 default: true assignee: login: octocat id: 1 node_id: MDQ6VXNlcjE= avatar_url: https://github.com/images/error/octocat_happy.gif gravatar_id: '' url: https://api.github.com/users/octocat html_url: https://github.com/octocat followers_url: https://api.github.com/users/octocat/followers following_url: https://api.github.com/users/octocat/following{/other_user} gists_url: https://api.github.com/users/octocat/gists{/gist_id} starred_url: https://api.github.com/users/octocat/starred{/owner}{/repo} subscriptions_url: https://api.github.com/users/octocat/subscriptions organizations_url: https://api.github.com/users/octocat/orgs repos_url: https://api.github.com/users/octocat/repos events_url: https://api.github.com/users/octocat/events{/privacy} received_events_url: https://api.github.com/users/octocat/received_events type: User site_admin: false assignees: - login: octocat id: 1 node_id: MDQ6VXNlcjE= avatar_url: https://github.com/images/error/octocat_happy.gif gravatar_id: '' url: https://api.github.com/users/octocat html_url: https://github.com/octocat followers_url: https://api.github.com/users/octocat/followers following_url: https://api.github.com/users/octocat/following{/other_user} gists_url: https://api.github.com/users/octocat/gists{/gist_id} starred_url: https://api.github.com/users/octocat/starred{/owner}{/repo} subscriptions_url: https://api.github.com/users/octocat/subscriptions organizations_url: https://api.github.com/users/octocat/orgs repos_url: https://api.github.com/users/octocat/repos events_url: https://api.github.com/users/octocat/events{/privacy} received_events_url: https://api.github.com/users/octocat/received_events type: User site_admin: false milestone: url: https://api.github.com/repos/octocat/Hello-World/milestones/1 html_url: https://github.com/octocat/Hello-World/milestones/v1.0 labels_url: https://api.github.com/repos/octocat/Hello-World/milestones/1/labels id: 1002604 node_id: MDk6TWlsZXN0b25lMTAwMjYwNA== number: 1 state: open title: v1.0 description: Tracking milestone for version 1.0 creator: login: octocat id: 1 node_id: MDQ6VXNlcjE= avatar_url: https://github.com/images/error/octocat_happy.gif gravatar_id: '' url: https://api.github.com/users/octocat html_url: https://github.com/octocat followers_url: https://api.github.com/users/octocat/followers following_url: https://api.github.com/users/octocat/following{/other_user} gists_url: https://api.github.com/users/octocat/gists{/gist_id} starred_url: https://api.github.com/users/octocat/starred{/owner}{/repo} subscriptions_url: https://api.github.com/users/octocat/subscriptions organizations_url: https://api.github.com/users/octocat/orgs repos_url: https://api.github.com/users/octocat/repos events_url: https://api.github.com/users/octocat/events{/privacy} received_events_url: https://api.github.com/users/octocat/received_events type: User site_admin: false open_issues: 4 closed_issues: 8 created_at: '2011-04-10T20:09:31Z' updated_at: '2014-03-03T18:58:10Z' closed_at: '2013-02-12T13:22:01Z' due_on: '2012-10-09T23:39:01Z' locked: true active_lock_reason: too heated comments: 0 pull_request: url: https://api.github.com/repos/octocat/Hello-World/pulls/1347 html_url: https://github.com/octocat/Hello-World/pull/1347 diff_url: https://github.com/octocat/Hello-World/pull/1347.diff patch_url: https://github.com/octocat/Hello-World/pull/1347.patch closed_at: created_at: '2011-04-22T13:33:48Z' updated_at: '2011-04-22T13:33:48Z' author_association: COLLABORATOR issue-event: value: id: 1 node_id: MDEwOklzc3VlRXZlbnQx url: https://api.github.com/repos/octocat/Hello-World/issues/events/1 actor: login: octocat id: 1 node_id: MDQ6VXNlcjE= avatar_url: https://github.com/images/error/octocat_happy.gif gravatar_id: '' url: https://api.github.com/users/octocat html_url: https://github.com/octocat followers_url: https://api.github.com/users/octocat/followers following_url: https://api.github.com/users/octocat/following{/other_user} gists_url: https://api.github.com/users/octocat/gists{/gist_id} starred_url: https://api.github.com/users/octocat/starred{/owner}{/repo} subscriptions_url: https://api.github.com/users/octocat/subscriptions organizations_url: https://api.github.com/users/octocat/orgs repos_url: https://api.github.com/users/octocat/repos events_url: https://api.github.com/users/octocat/events{/privacy} received_events_url: https://api.github.com/users/octocat/received_events type: User site_admin: false event: closed commit_id: 6dcb09b5b57875f334f61aebed695e2e4193db5e commit_url: https://api.github.com/repos/octocat/Hello-World/commits/6dcb09b5b57875f334f61aebed695e2e4193db5e created_at: '2011-04-14T16:00:49Z' issue: id: 1 node_id: MDU6SXNzdWUx url: https://api.github.com/repos/octocat/Hello-World/issues/1347 repository_url: https://api.github.com/repos/octocat/Hello-World labels_url: https://api.github.com/repos/octocat/Hello-World/issues/1347/labels{/name} comments_url: https://api.github.com/repos/octocat/Hello-World/issues/1347/comments events_url: https://api.github.com/repos/octocat/Hello-World/issues/1347/events html_url: https://github.com/octocat/Hello-World/issues/1347 number: 1347 state: open title: Found a bug body: I'm having a problem with this. user: login: octocat id: 1 node_id: MDQ6VXNlcjE= avatar_url: https://github.com/images/error/octocat_happy.gif gravatar_id: '' url: https://api.github.com/users/octocat html_url: https://github.com/octocat followers_url: https://api.github.com/users/octocat/followers following_url: https://api.github.com/users/octocat/following{/other_user} gists_url: https://api.github.com/users/octocat/gists{/gist_id} starred_url: https://api.github.com/users/octocat/starred{/owner}{/repo} subscriptions_url: https://api.github.com/users/octocat/subscriptions organizations_url: https://api.github.com/users/octocat/orgs repos_url: https://api.github.com/users/octocat/repos events_url: https://api.github.com/users/octocat/events{/privacy} received_events_url: https://api.github.com/users/octocat/received_events type: User site_admin: false labels: - id: 208045946 node_id: MDU6TGFiZWwyMDgwNDU5NDY= url: https://api.github.com/repos/octocat/Hello-World/labels/bug name: bug description: Something isn't working color: f29513 default: true assignee: login: octocat id: 1 node_id: MDQ6VXNlcjE= avatar_url: https://github.com/images/error/octocat_happy.gif gravatar_id: '' url: https://api.github.com/users/octocat html_url: https://github.com/octocat followers_url: https://api.github.com/users/octocat/followers following_url: https://api.github.com/users/octocat/following{/other_user} gists_url: https://api.github.com/users/octocat/gists{/gist_id} starred_url: https://api.github.com/users/octocat/starred{/owner}{/repo} subscriptions_url: https://api.github.com/users/octocat/subscriptions organizations_url: https://api.github.com/users/octocat/orgs repos_url: https://api.github.com/users/octocat/repos events_url: https://api.github.com/users/octocat/events{/privacy} received_events_url: https://api.github.com/users/octocat/received_events type: User site_admin: false assignees: - login: octocat id: 1 node_id: MDQ6VXNlcjE= avatar_url: https://github.com/images/error/octocat_happy.gif gravatar_id: '' url: https://api.github.com/users/octocat html_url: https://github.com/octocat followers_url: https://api.github.com/users/octocat/followers following_url: https://api.github.com/users/octocat/following{/other_user} gists_url: https://api.github.com/users/octocat/gists{/gist_id} starred_url: https://api.github.com/users/octocat/starred{/owner}{/repo} subscriptions_url: https://api.github.com/users/octocat/subscriptions organizations_url: https://api.github.com/users/octocat/orgs repos_url: https://api.github.com/users/octocat/repos events_url: https://api.github.com/users/octocat/events{/privacy} received_events_url: https://api.github.com/users/octocat/received_events type: User site_admin: false milestone: url: https://api.github.com/repos/octocat/Hello-World/milestones/1 html_url: https://github.com/octocat/Hello-World/milestones/v1.0 labels_url: https://api.github.com/repos/octocat/Hello-World/milestones/1/labels id: 1002604 node_id: MDk6TWlsZXN0b25lMTAwMjYwNA== number: 1 state: open title: v1.0 description: Tracking milestone for version 1.0 creator: login: octocat id: 1 node_id: MDQ6VXNlcjE= avatar_url: https://github.com/images/error/octocat_happy.gif gravatar_id: '' url: https://api.github.com/users/octocat html_url: https://github.com/octocat followers_url: https://api.github.com/users/octocat/followers following_url: https://api.github.com/users/octocat/following{/other_user} gists_url: https://api.github.com/users/octocat/gists{/gist_id} starred_url: https://api.github.com/users/octocat/starred{/owner}{/repo} subscriptions_url: https://api.github.com/users/octocat/subscriptions organizations_url: https://api.github.com/users/octocat/orgs repos_url: https://api.github.com/users/octocat/repos events_url: https://api.github.com/users/octocat/events{/privacy} received_events_url: https://api.github.com/users/octocat/received_events type: User site_admin: false open_issues: 4 closed_issues: 8 created_at: '2011-04-10T20:09:31Z' updated_at: '2014-03-03T18:58:10Z' closed_at: '2013-02-12T13:22:01Z' due_on: '2012-10-09T23:39:01Z' locked: true performed_via_github_app: id: 1 slug: octoapp node_id: MDExOkludGVncmF0aW9uMQ== owner: login: github id: 1 node_id: MDEyOk9yZ2FuaXphdGlvbjE= url: https://api.github.com/orgs/github repos_url: https://api.github.com/orgs/github/repos events_url: https://api.github.com/orgs/github/events avatar_url: https://github.com/images/error/octocat_happy.gif gravatar_id: '' html_url: https://github.com/octocat followers_url: https://api.github.com/users/octocat/followers following_url: https://api.github.com/users/octocat/following{/other_user} gists_url: https://api.github.com/users/octocat/gists{/gist_id} starred_url: https://api.github.com/users/octocat/starred{/owner}{/repo} subscriptions_url: https://api.github.com/users/octocat/subscriptions organizations_url: https://api.github.com/users/octocat/orgs received_events_url: https://api.github.com/users/octocat/received_events type: User site_admin: true name: Octocat App description: '' external_url: https://example.com html_url: https://github.com/apps/octoapp created_at: '2017-07-08T16:18:44-04:00' updated_at: '2017-07-08T16:18:44-04:00' permissions: metadata: read contents: read issues: write single_file: write events: - push - pull_request comments: 0 pull_request: url: https://api.github.com/repos/octocat/Hello-World/pulls/1347 html_url: https://github.com/octocat/Hello-World/pull/1347 diff_url: https://github.com/octocat/Hello-World/pull/1347.diff patch_url: https://github.com/octocat/Hello-World/pull/1347.patch closed_at: created_at: '2011-04-22T13:33:48Z' updated_at: '2011-04-22T13:33:48Z' author_association: COLLABORATOR issue-event-for-issue-items: value: - id: 1 node_id: MDEwOklzc3VlRXZlbnQx url: https://api.github.com/repos/octocat/Hello-World/issues/events/1 actor: login: octocat id: 1 node_id: MDQ6VXNlcjE= avatar_url: https://github.com/images/error/octocat_happy.gif gravatar_id: '' url: https://api.github.com/users/octocat html_url: https://github.com/octocat followers_url: https://api.github.com/users/octocat/followers following_url: https://api.github.com/users/octocat/following{/other_user} gists_url: https://api.github.com/users/octocat/gists{/gist_id} starred_url: https://api.github.com/users/octocat/starred{/owner}{/repo} subscriptions_url: https://api.github.com/users/octocat/subscriptions organizations_url: https://api.github.com/users/octocat/orgs repos_url: https://api.github.com/users/octocat/repos events_url: https://api.github.com/users/octocat/events{/privacy} received_events_url: https://api.github.com/users/octocat/received_events type: User site_admin: false event: closed commit_id: 6dcb09b5b57875f334f61aebed695e2e4193db5e commit_url: https://api.github.com/repos/octocat/Hello-World/commits/6dcb09b5b57875f334f61aebed695e2e4193db5e created_at: '2011-04-14T16:00:49Z' performed_via_github_app: label: name: label color: red label-items: value: - id: 208045946 node_id: MDU6TGFiZWwyMDgwNDU5NDY= url: https://api.github.com/repos/octocat/Hello-World/labels/bug name: bug description: Something isn't working color: f29513 default: true - id: 208045947 node_id: MDU6TGFiZWwyMDgwNDU5NDc= url: https://api.github.com/repos/octocat/Hello-World/labels/enhancement name: enhancement description: New feature or request color: a2eeef default: false label-items-2: value: - id: 208045946 node_id: MDU6TGFiZWwyMDgwNDU5NDY= url: https://api.github.com/repos/octocat/Hello-World/labels/bug name: bug description: Something isn't working color: f29513 default: true deploy-key-items: value: - id: 1 key: ssh-rsa AAA... url: https://api.github.com/repos/octocat/Hello-World/keys/1 title: octocat@octomac verified: true created_at: '2014-12-10T15:53:42Z' read_only: true deploy-key: value: id: 1 key: ssh-rsa AAA... url: https://api.github.com/repos/octocat/Hello-World/keys/1 title: octocat@octomac verified: true created_at: '2014-12-10T15:53:42Z' read_only: true label: value: id: 208045946 node_id: MDU6TGFiZWwyMDgwNDU5NDY= url: https://api.github.com/repos/octocat/Hello-World/labels/bug name: bug description: Something isn't working color: f29513 default: true label-2: value: id: 208045946 node_id: MDU6TGFiZWwyMDgwNDU5NDY= url: 'https://api.github.com/repos/octocat/Hello-World/labels/bug%20:bug:' name: 'bug :bug:' description: Small bug fix required color: b01f26 default: true language: value: C: 78769 Python: 7769 license-content: value: name: LICENSE path: LICENSE sha: 401c59dcc4570b954dd6d345e76199e1f4e76266 size: 1077 url: https://api.github.com/repos/benbalter/gman/contents/LICENSE?ref=master html_url: https://github.com/benbalter/gman/blob/master/LICENSE git_url: https://api.github.com/repos/benbalter/gman/git/blobs/401c59dcc4570b954dd6d345e76199e1f4e76266 download_url: https://raw.githubusercontent.com/benbalter/gman/master/LICENSE?lab=true type: file content: | VGhlIE1JVCBMaWNlbnNlIChNSVQpCgpDb3B5cmlnaHQgKGMpIDIwMTMgQmVu IEJhbHRlcgoKUGVybWlzc2lvbiBpcyBoZXJlYnkgZ3JhbnRlZCwgZnJlZSBv ZiBjaGFyZ2UsIHRvIGFueSBwZXJzb24gb2J0YWluaW5nIGEgY29weSBvZgp0 aGlzIHNvZnR3YXJlIGFuZCBhc3NvY2lhdGVkIGRvY3VtZW50YXRpb24gZmls ZXMgKHRoZSAiU29mdHdhcmUiKSwgdG8gZGVhbCBpbgp0aGUgU29mdHdhcmUg d2l0aG91dCByZXN0cmljdGlvbiwgaW5jbHVkaW5nIHdpdGhvdXQgbGltaXRh dGlvbiB0aGUgcmlnaHRzIHRvCnVzZSwgY29weSwgbW9kaWZ5LCBtZXJnZSwg cHVibGlzaCwgZGlzdHJpYnV0ZSwgc3VibGljZW5zZSwgYW5kL29yIHNlbGwg Y29waWVzIG9mCnRoZSBTb2Z0d2FyZSwgYW5kIHRvIHBlcm1pdCBwZXJzb25z IHRvIHdob20gdGhlIFNvZnR3YXJlIGlzIGZ1cm5pc2hlZCB0byBkbyBzbywK c3ViamVjdCB0byB0aGUgZm9sbG93aW5nIGNvbmRpdGlvbnM6CgpUaGUgYWJv dmUgY29weXJpZ2h0IG5vdGljZSBhbmQgdGhpcyBwZXJtaXNzaW9uIG5vdGlj ZSBzaGFsbCBiZSBpbmNsdWRlZCBpbiBhbGwKY29waWVzIG9yIHN1YnN0YW50 aWFsIHBvcnRpb25zIG9mIHRoZSBTb2Z0d2FyZS4KClRIRSBTT0ZUV0FSRSBJ UyBQUk9WSURFRCAiQVMgSVMiLCBXSVRIT1VUIFdBUlJBTlRZIE9GIEFOWSBL SU5ELCBFWFBSRVNTIE9SCklNUExJRUQsIElOQ0xVRElORyBCVVQgTk9UIExJ TUlURUQgVE8gVEhFIFdBUlJBTlRJRVMgT0YgTUVSQ0hBTlRBQklMSVRZLCBG SVRORVNTCkZPUiBBIFBBUlRJQ1VMQVIgUFVSUE9TRSBBTkQgTk9OSU5GUklO R0VNRU5ULiBJTiBOTyBFVkVOVCBTSEFMTCBUSEUgQVVUSE9SUyBPUgpDT1BZ UklHSFQgSE9MREVSUyBCRSBMSUFCTEUgRk9SIEFOWSBDTEFJTSwgREFNQUdF UyBPUiBPVEhFUiBMSUFCSUxJVFksIFdIRVRIRVIKSU4gQU4gQUNUSU9OIE9G IENPTlRSQUNULCBUT1JUIE9SIE9USEVSV0lTRSwgQVJJU0lORyBGUk9NLCBP VVQgT0YgT1IgSU4KQ09OTkVDVElPTiBXSVRIIFRIRSBTT0ZUV0FSRSBPUiBU SEUgVVNFIE9SIE9USEVSIERFQUxJTkdTIElOIFRIRSBTT0ZUV0FSRS4K encoding: base64 _links: self: https://api.github.com/repos/benbalter/gman/contents/LICENSE?ref=master git: https://api.github.com/repos/benbalter/gman/git/blobs/401c59dcc4570b954dd6d345e76199e1f4e76266 html: https://github.com/benbalter/gman/blob/master/LICENSE license: key: mit name: MIT License spdx_id: MIT url: https://api.github.com/licenses/mit node_id: MDc6TGljZW5zZW1pdA== milestone-items: value: - url: https://api.github.com/repos/octocat/Hello-World/milestones/1 html_url: https://github.com/octocat/Hello-World/milestones/v1.0 labels_url: https://api.github.com/repos/octocat/Hello-World/milestones/1/labels id: 1002604 node_id: MDk6TWlsZXN0b25lMTAwMjYwNA== number: 1 state: open title: v1.0 description: Tracking milestone for version 1.0 creator: login: octocat id: 1 node_id: MDQ6VXNlcjE= avatar_url: https://github.com/images/error/octocat_happy.gif gravatar_id: '' url: https://api.github.com/users/octocat html_url: https://github.com/octocat followers_url: https://api.github.com/users/octocat/followers following_url: https://api.github.com/users/octocat/following{/other_user} gists_url: https://api.github.com/users/octocat/gists{/gist_id} starred_url: https://api.github.com/users/octocat/starred{/owner}{/repo} subscriptions_url: https://api.github.com/users/octocat/subscriptions organizations_url: https://api.github.com/users/octocat/orgs repos_url: https://api.github.com/users/octocat/repos events_url: https://api.github.com/users/octocat/events{/privacy} received_events_url: https://api.github.com/users/octocat/received_events type: User site_admin: false open_issues: 4 closed_issues: 8 created_at: '2011-04-10T20:09:31Z' updated_at: '2014-03-03T18:58:10Z' closed_at: '2013-02-12T13:22:01Z' due_on: '2012-10-09T23:39:01Z' milestone: value: url: https://api.github.com/repos/octocat/Hello-World/milestones/1 html_url: https://github.com/octocat/Hello-World/milestones/v1.0 labels_url: https://api.github.com/repos/octocat/Hello-World/milestones/1/labels id: 1002604 node_id: MDk6TWlsZXN0b25lMTAwMjYwNA== number: 1 state: open title: v1.0 description: Tracking milestone for version 1.0 creator: login: octocat id: 1 node_id: MDQ6VXNlcjE= avatar_url: https://github.com/images/error/octocat_happy.gif gravatar_id: '' url: https://api.github.com/users/octocat html_url: https://github.com/octocat followers_url: https://api.github.com/users/octocat/followers following_url: https://api.github.com/users/octocat/following{/other_user} gists_url: https://api.github.com/users/octocat/gists{/gist_id} starred_url: https://api.github.com/users/octocat/starred{/owner}{/repo} subscriptions_url: https://api.github.com/users/octocat/subscriptions organizations_url: https://api.github.com/users/octocat/orgs repos_url: https://api.github.com/users/octocat/repos events_url: https://api.github.com/users/octocat/events{/privacy} received_events_url: https://api.github.com/users/octocat/received_events type: User site_admin: false open_issues: 4 closed_issues: 8 created_at: '2011-04-10T20:09:31Z' updated_at: '2014-03-03T18:58:10Z' closed_at: '2013-02-12T13:22:01Z' due_on: '2012-10-09T23:39:01Z' page: value: url: https://api.github.com/repos/github/developer.github.com/pages status: built cname: developer.github.com custom_404: false html_url: https://developer.github.com source: branch: master path: "/" public: true https_certificate: state: approved description: Certificate is approved domains: - developer.github.com expires_at: '2021-05-22' https_enforced: true page-build-items: value: - url: https://api.github.com/repos/github/developer.github.com/pages/builds/5472601 status: built error: message: pusher: login: octocat id: 1 node_id: MDQ6VXNlcjE= avatar_url: https://github.com/images/error/octocat_happy.gif gravatar_id: '' url: https://api.github.com/users/octocat html_url: https://github.com/octocat followers_url: https://api.github.com/users/octocat/followers following_url: https://api.github.com/users/octocat/following{/other_user} gists_url: https://api.github.com/users/octocat/gists{/gist_id} starred_url: https://api.github.com/users/octocat/starred{/owner}{/repo} subscriptions_url: https://api.github.com/users/octocat/subscriptions organizations_url: https://api.github.com/users/octocat/orgs repos_url: https://api.github.com/users/octocat/repos events_url: https://api.github.com/users/octocat/events{/privacy} received_events_url: https://api.github.com/users/octocat/received_events type: User site_admin: false commit: 351391cdcb88ffae71ec3028c91f375a8036a26b duration: 2104 created_at: '2014-02-10T19:00:49Z' updated_at: '2014-02-10T19:00:51Z' page-build-status: value: url: https://api.github.com/repos/github/developer.github.com/pages/builds/latest status: queued page-build: value: url: https://api.github.com/repos/github/developer.github.com/pages/builds/5472601 status: built error: message: pusher: login: octocat id: 1 node_id: MDQ6VXNlcjE= avatar_url: https://github.com/images/error/octocat_happy.gif gravatar_id: '' url: https://api.github.com/users/octocat html_url: https://github.com/octocat followers_url: https://api.github.com/users/octocat/followers following_url: https://api.github.com/users/octocat/following{/other_user} gists_url: https://api.github.com/users/octocat/gists{/gist_id} starred_url: https://api.github.com/users/octocat/starred{/owner}{/repo} subscriptions_url: https://api.github.com/users/octocat/subscriptions organizations_url: https://api.github.com/users/octocat/orgs repos_url: https://api.github.com/users/octocat/repos events_url: https://api.github.com/users/octocat/events{/privacy} received_events_url: https://api.github.com/users/octocat/received_events type: User site_admin: false commit: 351391cdcb88ffae71ec3028c91f375a8036a26b duration: 2104 created_at: '2014-02-10T19:00:49Z' updated_at: '2014-02-10T19:00:51Z' repository-pre-receive-hook-items: value: - id: 42 name: Check Commits enforcement: disabled configuration_url: https://github.example.com/api/v3/orgs/octocat/pre-receive-hooks/42 repository-pre-receive-hook: value: id: 42 name: Check Commits enforcement: disabled configuration_url: https://github.example.com/api/v3/orgs/octocat/pre-receive-hooks/42 repository-pre-receive-hook-2: value: id: 42 name: Check Commits enforcement: enabled configuration_url: https://github.example.com/api/v3/repos/octocat/hello-world/pre-receive-hooks/42 project-items-2: value: - owner_url: https://api.github.com/repos/api-playground/projects-test url: https://api.github.com/projects/1002604 html_url: https://github.com/api-playground/projects-test/projects/1 columns_url: https://api.github.com/projects/1002604/columns id: 1002604 node_id: MDc6UHJvamVjdDEwMDI2MDQ= name: Projects Documentation body: Developer documentation project for the developer site. number: 1 state: open creator: login: octocat id: 1 node_id: MDQ6VXNlcjE= avatar_url: https://github.com/images/error/octocat_happy.gif gravatar_id: '' url: https://api.github.com/users/octocat html_url: https://github.com/octocat followers_url: https://api.github.com/users/octocat/followers following_url: https://api.github.com/users/octocat/following{/other_user} gists_url: https://api.github.com/users/octocat/gists{/gist_id} starred_url: https://api.github.com/users/octocat/starred{/owner}{/repo} subscriptions_url: https://api.github.com/users/octocat/subscriptions organizations_url: https://api.github.com/users/octocat/orgs repos_url: https://api.github.com/users/octocat/repos events_url: https://api.github.com/users/octocat/events{/privacy} received_events_url: https://api.github.com/users/octocat/received_events type: User site_admin: false created_at: '2011-04-10T20:09:31Z' updated_at: '2014-03-03T18:58:10Z' pull-request: value: url: https://api.github.com/repos/octocat/Hello-World/pulls/1347 id: 1 node_id: MDExOlB1bGxSZXF1ZXN0MQ== html_url: https://github.com/octocat/Hello-World/pull/1347 diff_url: https://github.com/octocat/Hello-World/pull/1347.diff patch_url: https://github.com/octocat/Hello-World/pull/1347.patch issue_url: https://api.github.com/repos/octocat/Hello-World/issues/1347 commits_url: https://api.github.com/repos/octocat/Hello-World/pulls/1347/commits review_comments_url: https://api.github.com/repos/octocat/Hello-World/pulls/1347/comments review_comment_url: https://api.github.com/repos/octocat/Hello-World/pulls/comments{/number} comments_url: https://api.github.com/repos/octocat/Hello-World/issues/1347/comments statuses_url: https://api.github.com/repos/octocat/Hello-World/statuses/6dcb09b5b57875f334f61aebed695e2e4193db5e number: 1347 state: open locked: true title: Amazing new feature user: login: octocat id: 1 node_id: MDQ6VXNlcjE= avatar_url: https://github.com/images/error/octocat_happy.gif gravatar_id: '' url: https://api.github.com/users/octocat html_url: https://github.com/octocat followers_url: https://api.github.com/users/octocat/followers following_url: https://api.github.com/users/octocat/following{/other_user} gists_url: https://api.github.com/users/octocat/gists{/gist_id} starred_url: https://api.github.com/users/octocat/starred{/owner}{/repo} subscriptions_url: https://api.github.com/users/octocat/subscriptions organizations_url: https://api.github.com/users/octocat/orgs repos_url: https://api.github.com/users/octocat/repos events_url: https://api.github.com/users/octocat/events{/privacy} received_events_url: https://api.github.com/users/octocat/received_events type: User site_admin: false body: Please pull these awesome changes in! labels: - id: 208045946 node_id: MDU6TGFiZWwyMDgwNDU5NDY= url: https://api.github.com/repos/octocat/Hello-World/labels/bug name: bug description: Something isn't working color: f29513 default: true milestone: url: https://api.github.com/repos/octocat/Hello-World/milestones/1 html_url: https://github.com/octocat/Hello-World/milestones/v1.0 labels_url: https://api.github.com/repos/octocat/Hello-World/milestones/1/labels id: 1002604 node_id: MDk6TWlsZXN0b25lMTAwMjYwNA== number: 1 state: open title: v1.0 description: Tracking milestone for version 1.0 creator: login: octocat id: 1 node_id: MDQ6VXNlcjE= avatar_url: https://github.com/images/error/octocat_happy.gif gravatar_id: '' url: https://api.github.com/users/octocat html_url: https://github.com/octocat followers_url: https://api.github.com/users/octocat/followers following_url: https://api.github.com/users/octocat/following{/other_user} gists_url: https://api.github.com/users/octocat/gists{/gist_id} starred_url: https://api.github.com/users/octocat/starred{/owner}{/repo} subscriptions_url: https://api.github.com/users/octocat/subscriptions organizations_url: https://api.github.com/users/octocat/orgs repos_url: https://api.github.com/users/octocat/repos events_url: https://api.github.com/users/octocat/events{/privacy} received_events_url: https://api.github.com/users/octocat/received_events type: User site_admin: false open_issues: 4 closed_issues: 8 created_at: '2011-04-10T20:09:31Z' updated_at: '2014-03-03T18:58:10Z' closed_at: '2013-02-12T13:22:01Z' due_on: '2012-10-09T23:39:01Z' active_lock_reason: too heated created_at: '2011-01-26T19:01:12Z' updated_at: '2011-01-26T19:01:12Z' closed_at: '2011-01-26T19:01:12Z' merged_at: '2011-01-26T19:01:12Z' merge_commit_sha: e5bd3914e2e596debea16f433f57875b5b90bcd6 assignee: login: octocat id: 1 node_id: MDQ6VXNlcjE= avatar_url: https://github.com/images/error/octocat_happy.gif gravatar_id: '' url: https://api.github.com/users/octocat html_url: https://github.com/octocat followers_url: https://api.github.com/users/octocat/followers following_url: https://api.github.com/users/octocat/following{/other_user} gists_url: https://api.github.com/users/octocat/gists{/gist_id} starred_url: https://api.github.com/users/octocat/starred{/owner}{/repo} subscriptions_url: https://api.github.com/users/octocat/subscriptions organizations_url: https://api.github.com/users/octocat/orgs repos_url: https://api.github.com/users/octocat/repos events_url: https://api.github.com/users/octocat/events{/privacy} received_events_url: https://api.github.com/users/octocat/received_events type: User site_admin: false assignees: - login: octocat id: 1 node_id: MDQ6VXNlcjE= avatar_url: https://github.com/images/error/octocat_happy.gif gravatar_id: '' url: https://api.github.com/users/octocat html_url: https://github.com/octocat followers_url: https://api.github.com/users/octocat/followers following_url: https://api.github.com/users/octocat/following{/other_user} gists_url: https://api.github.com/users/octocat/gists{/gist_id} starred_url: https://api.github.com/users/octocat/starred{/owner}{/repo} subscriptions_url: https://api.github.com/users/octocat/subscriptions organizations_url: https://api.github.com/users/octocat/orgs repos_url: https://api.github.com/users/octocat/repos events_url: https://api.github.com/users/octocat/events{/privacy} received_events_url: https://api.github.com/users/octocat/received_events type: User site_admin: false - login: hubot id: 1 node_id: MDQ6VXNlcjE= avatar_url: https://github.com/images/error/hubot_happy.gif gravatar_id: '' url: https://api.github.com/users/hubot html_url: https://github.com/hubot followers_url: https://api.github.com/users/hubot/followers following_url: https://api.github.com/users/hubot/following{/other_user} gists_url: https://api.github.com/users/hubot/gists{/gist_id} starred_url: https://api.github.com/users/hubot/starred{/owner}{/repo} subscriptions_url: https://api.github.com/users/hubot/subscriptions organizations_url: https://api.github.com/users/hubot/orgs repos_url: https://api.github.com/users/hubot/repos events_url: https://api.github.com/users/hubot/events{/privacy} received_events_url: https://api.github.com/users/hubot/received_events type: User site_admin: true requested_reviewers: - login: other_user id: 1 node_id: MDQ6VXNlcjE= avatar_url: https://github.com/images/error/other_user_happy.gif gravatar_id: '' url: https://api.github.com/users/other_user html_url: https://github.com/other_user followers_url: https://api.github.com/users/other_user/followers following_url: https://api.github.com/users/other_user/following{/other_user} gists_url: https://api.github.com/users/other_user/gists{/gist_id} starred_url: https://api.github.com/users/other_user/starred{/owner}{/repo} subscriptions_url: https://api.github.com/users/other_user/subscriptions organizations_url: https://api.github.com/users/other_user/orgs repos_url: https://api.github.com/users/other_user/repos events_url: https://api.github.com/users/other_user/events{/privacy} received_events_url: https://api.github.com/users/other_user/received_events type: User site_admin: false requested_teams: - id: 1 node_id: MDQ6VGVhbTE= url: https://api.github.com/teams/1 html_url: https://github.com/orgs/github/teams/justice-league name: Justice League slug: justice-league description: A great team. privacy: closed permission: admin members_url: https://api.github.com/teams/1/members{/member} repositories_url: https://api.github.com/teams/1/repos head: label: octocat:new-topic ref: new-topic sha: 6dcb09b5b57875f334f61aebed695e2e4193db5e user: login: octocat id: 1 node_id: MDQ6VXNlcjE= avatar_url: https://github.com/images/error/octocat_happy.gif gravatar_id: '' url: https://api.github.com/users/octocat html_url: https://github.com/octocat followers_url: https://api.github.com/users/octocat/followers following_url: https://api.github.com/users/octocat/following{/other_user} gists_url: https://api.github.com/users/octocat/gists{/gist_id} starred_url: https://api.github.com/users/octocat/starred{/owner}{/repo} subscriptions_url: https://api.github.com/users/octocat/subscriptions organizations_url: https://api.github.com/users/octocat/orgs repos_url: https://api.github.com/users/octocat/repos events_url: https://api.github.com/users/octocat/events{/privacy} received_events_url: https://api.github.com/users/octocat/received_events type: User site_admin: false repo: id: 1296269 node_id: MDEwOlJlcG9zaXRvcnkxMjk2MjY5 name: Hello-World full_name: octocat/Hello-World owner: login: octocat id: 1 node_id: MDQ6VXNlcjE= avatar_url: https://github.com/images/error/octocat_happy.gif gravatar_id: '' url: https://api.github.com/users/octocat html_url: https://github.com/octocat followers_url: https://api.github.com/users/octocat/followers following_url: https://api.github.com/users/octocat/following{/other_user} gists_url: https://api.github.com/users/octocat/gists{/gist_id} starred_url: https://api.github.com/users/octocat/starred{/owner}{/repo} subscriptions_url: https://api.github.com/users/octocat/subscriptions organizations_url: https://api.github.com/users/octocat/orgs repos_url: https://api.github.com/users/octocat/repos events_url: https://api.github.com/users/octocat/events{/privacy} received_events_url: https://api.github.com/users/octocat/received_events type: User site_admin: false private: false html_url: https://github.com/octocat/Hello-World description: This your first repo! fork: false url: https://api.github.com/repos/octocat/Hello-World archive_url: https://api.github.com/repos/octocat/Hello-World/{archive_format}{/ref} assignees_url: https://api.github.com/repos/octocat/Hello-World/assignees{/user} blobs_url: https://api.github.com/repos/octocat/Hello-World/git/blobs{/sha} branches_url: https://api.github.com/repos/octocat/Hello-World/branches{/branch} collaborators_url: https://api.github.com/repos/octocat/Hello-World/collaborators{/collaborator} comments_url: https://api.github.com/repos/octocat/Hello-World/comments{/number} commits_url: https://api.github.com/repos/octocat/Hello-World/commits{/sha} compare_url: https://api.github.com/repos/octocat/Hello-World/compare/{base}...{head} contents_url: https://api.github.com/repos/octocat/Hello-World/contents/{+path} contributors_url: https://api.github.com/repos/octocat/Hello-World/contributors deployments_url: https://api.github.com/repos/octocat/Hello-World/deployments downloads_url: https://api.github.com/repos/octocat/Hello-World/downloads events_url: https://api.github.com/repos/octocat/Hello-World/events forks_url: https://api.github.com/repos/octocat/Hello-World/forks git_commits_url: https://api.github.com/repos/octocat/Hello-World/git/commits{/sha} git_refs_url: https://api.github.com/repos/octocat/Hello-World/git/refs{/sha} git_tags_url: https://api.github.com/repos/octocat/Hello-World/git/tags{/sha} git_url: git:github.com/octocat/Hello-World.git issue_comment_url: https://api.github.com/repos/octocat/Hello-World/issues/comments{/number} issue_events_url: https://api.github.com/repos/octocat/Hello-World/issues/events{/number} issues_url: https://api.github.com/repos/octocat/Hello-World/issues{/number} keys_url: https://api.github.com/repos/octocat/Hello-World/keys{/key_id} labels_url: https://api.github.com/repos/octocat/Hello-World/labels{/name} languages_url: https://api.github.com/repos/octocat/Hello-World/languages merges_url: https://api.github.com/repos/octocat/Hello-World/merges milestones_url: https://api.github.com/repos/octocat/Hello-World/milestones{/number} notifications_url: https://api.github.com/repos/octocat/Hello-World/notifications{?since,all,participating} pulls_url: https://api.github.com/repos/octocat/Hello-World/pulls{/number} releases_url: https://api.github.com/repos/octocat/Hello-World/releases{/id} ssh_url: git@github.com:octocat/Hello-World.git stargazers_url: https://api.github.com/repos/octocat/Hello-World/stargazers statuses_url: https://api.github.com/repos/octocat/Hello-World/statuses/{sha} subscribers_url: https://api.github.com/repos/octocat/Hello-World/subscribers subscription_url: https://api.github.com/repos/octocat/Hello-World/subscription tags_url: https://api.github.com/repos/octocat/Hello-World/tags teams_url: https://api.github.com/repos/octocat/Hello-World/teams trees_url: https://api.github.com/repos/octocat/Hello-World/git/trees{/sha} clone_url: https://github.com/octocat/Hello-World.git mirror_url: git:git.example.com/octocat/Hello-World hooks_url: https://api.github.com/repos/octocat/Hello-World/hooks svn_url: https://svn.github.com/octocat/Hello-World homepage: https://github.com language: forks_count: 9 stargazers_count: 80 watchers_count: 80 size: 108 default_branch: master open_issues_count: 0 topics: - octocat - atom - electron - api has_issues: true has_projects: true has_wiki: true has_pages: false has_downloads: true archived: false disabled: false pushed_at: '2011-01-26T19:06:43Z' created_at: '2011-01-26T19:01:12Z' updated_at: '2011-01-26T19:14:43Z' permissions: admin: false push: false pull: true allow_rebase_merge: true temp_clone_token: ABTLWHOULUVAXGTRYU7OC2876QJ2O allow_squash_merge: true allow_merge_commit: true allow_forking: true forks: 123 open_issues: 123 license: key: mit name: MIT License url: https://api.github.com/licenses/mit spdx_id: MIT node_id: MDc6TGljZW5zZW1pdA== watchers: 123 base: label: octocat:master ref: master sha: 6dcb09b5b57875f334f61aebed695e2e4193db5e user: login: octocat id: 1 node_id: MDQ6VXNlcjE= avatar_url: https://github.com/images/error/octocat_happy.gif gravatar_id: '' url: https://api.github.com/users/octocat html_url: https://github.com/octocat followers_url: https://api.github.com/users/octocat/followers following_url: https://api.github.com/users/octocat/following{/other_user} gists_url: https://api.github.com/users/octocat/gists{/gist_id} starred_url: https://api.github.com/users/octocat/starred{/owner}{/repo} subscriptions_url: https://api.github.com/users/octocat/subscriptions organizations_url: https://api.github.com/users/octocat/orgs repos_url: https://api.github.com/users/octocat/repos events_url: https://api.github.com/users/octocat/events{/privacy} received_events_url: https://api.github.com/users/octocat/received_events type: User site_admin: false repo: id: 1296269 node_id: MDEwOlJlcG9zaXRvcnkxMjk2MjY5 name: Hello-World full_name: octocat/Hello-World owner: login: octocat id: 1 node_id: MDQ6VXNlcjE= avatar_url: https://github.com/images/error/octocat_happy.gif gravatar_id: '' url: https://api.github.com/users/octocat html_url: https://github.com/octocat followers_url: https://api.github.com/users/octocat/followers following_url: https://api.github.com/users/octocat/following{/other_user} gists_url: https://api.github.com/users/octocat/gists{/gist_id} starred_url: https://api.github.com/users/octocat/starred{/owner}{/repo} subscriptions_url: https://api.github.com/users/octocat/subscriptions organizations_url: https://api.github.com/users/octocat/orgs repos_url: https://api.github.com/users/octocat/repos events_url: https://api.github.com/users/octocat/events{/privacy} received_events_url: https://api.github.com/users/octocat/received_events type: User site_admin: false private: false html_url: https://github.com/octocat/Hello-World description: This your first repo! fork: false url: https://api.github.com/repos/octocat/Hello-World archive_url: https://api.github.com/repos/octocat/Hello-World/{archive_format}{/ref} assignees_url: https://api.github.com/repos/octocat/Hello-World/assignees{/user} blobs_url: https://api.github.com/repos/octocat/Hello-World/git/blobs{/sha} branches_url: https://api.github.com/repos/octocat/Hello-World/branches{/branch} collaborators_url: https://api.github.com/repos/octocat/Hello-World/collaborators{/collaborator} comments_url: https://api.github.com/repos/octocat/Hello-World/comments{/number} commits_url: https://api.github.com/repos/octocat/Hello-World/commits{/sha} compare_url: https://api.github.com/repos/octocat/Hello-World/compare/{base}...{head} contents_url: https://api.github.com/repos/octocat/Hello-World/contents/{+path} contributors_url: https://api.github.com/repos/octocat/Hello-World/contributors deployments_url: https://api.github.com/repos/octocat/Hello-World/deployments downloads_url: https://api.github.com/repos/octocat/Hello-World/downloads events_url: https://api.github.com/repos/octocat/Hello-World/events forks_url: https://api.github.com/repos/octocat/Hello-World/forks git_commits_url: https://api.github.com/repos/octocat/Hello-World/git/commits{/sha} git_refs_url: https://api.github.com/repos/octocat/Hello-World/git/refs{/sha} git_tags_url: https://api.github.com/repos/octocat/Hello-World/git/tags{/sha} git_url: git:github.com/octocat/Hello-World.git issue_comment_url: https://api.github.com/repos/octocat/Hello-World/issues/comments{/number} issue_events_url: https://api.github.com/repos/octocat/Hello-World/issues/events{/number} issues_url: https://api.github.com/repos/octocat/Hello-World/issues{/number} keys_url: https://api.github.com/repos/octocat/Hello-World/keys{/key_id} labels_url: https://api.github.com/repos/octocat/Hello-World/labels{/name} languages_url: https://api.github.com/repos/octocat/Hello-World/languages merges_url: https://api.github.com/repos/octocat/Hello-World/merges milestones_url: https://api.github.com/repos/octocat/Hello-World/milestones{/number} notifications_url: https://api.github.com/repos/octocat/Hello-World/notifications{?since,all,participating} pulls_url: https://api.github.com/repos/octocat/Hello-World/pulls{/number} releases_url: https://api.github.com/repos/octocat/Hello-World/releases{/id} ssh_url: git@github.com:octocat/Hello-World.git stargazers_url: https://api.github.com/repos/octocat/Hello-World/stargazers statuses_url: https://api.github.com/repos/octocat/Hello-World/statuses/{sha} subscribers_url: https://api.github.com/repos/octocat/Hello-World/subscribers subscription_url: https://api.github.com/repos/octocat/Hello-World/subscription tags_url: https://api.github.com/repos/octocat/Hello-World/tags teams_url: https://api.github.com/repos/octocat/Hello-World/teams trees_url: https://api.github.com/repos/octocat/Hello-World/git/trees{/sha} clone_url: https://github.com/octocat/Hello-World.git mirror_url: git:git.example.com/octocat/Hello-World hooks_url: https://api.github.com/repos/octocat/Hello-World/hooks svn_url: https://svn.github.com/octocat/Hello-World homepage: https://github.com language: forks_count: 9 stargazers_count: 80 watchers_count: 80 size: 108 default_branch: master open_issues_count: 0 topics: - octocat - atom - electron - api has_issues: true has_projects: true has_wiki: true has_pages: false has_downloads: true archived: false disabled: false pushed_at: '2011-01-26T19:06:43Z' created_at: '2011-01-26T19:01:12Z' updated_at: '2011-01-26T19:14:43Z' permissions: admin: false push: false pull: true allow_rebase_merge: true temp_clone_token: ABTLWHOULUVAXGTRYU7OC2876QJ2O allow_squash_merge: true allow_merge_commit: true forks: 123 open_issues: 123 license: key: mit name: MIT License url: https://api.github.com/licenses/mit spdx_id: MIT node_id: MDc6TGljZW5zZW1pdA== watchers: 123 _links: self: href: https://api.github.com/repos/octocat/Hello-World/pulls/1347 html: href: https://github.com/octocat/Hello-World/pull/1347 issue: href: https://api.github.com/repos/octocat/Hello-World/issues/1347 comments: href: https://api.github.com/repos/octocat/Hello-World/issues/1347/comments review_comments: href: https://api.github.com/repos/octocat/Hello-World/pulls/1347/comments review_comment: href: https://api.github.com/repos/octocat/Hello-World/pulls/comments{/number} commits: href: https://api.github.com/repos/octocat/Hello-World/pulls/1347/commits statuses: href: https://api.github.com/repos/octocat/Hello-World/statuses/6dcb09b5b57875f334f61aebed695e2e4193db5e author_association: OWNER draft: false merged: false mergeable: true rebaseable: true mergeable_state: clean merged_by: login: octocat id: 1 node_id: MDQ6VXNlcjE= avatar_url: https://github.com/images/error/octocat_happy.gif gravatar_id: '' url: https://api.github.com/users/octocat html_url: https://github.com/octocat followers_url: https://api.github.com/users/octocat/followers following_url: https://api.github.com/users/octocat/following{/other_user} gists_url: https://api.github.com/users/octocat/gists{/gist_id} starred_url: https://api.github.com/users/octocat/starred{/owner}{/repo} subscriptions_url: https://api.github.com/users/octocat/subscriptions organizations_url: https://api.github.com/users/octocat/orgs repos_url: https://api.github.com/users/octocat/repos events_url: https://api.github.com/users/octocat/events{/privacy} received_events_url: https://api.github.com/users/octocat/received_events type: User site_admin: false comments: 10 review_comments: 0 maintainer_can_modify: true commits: 3 additions: 100 deletions: 3 changed_files: 5 pull-request-review-comment-items: value: - url: https://api.github.com/repos/octocat/Hello-World/pulls/comments/1 pull_request_review_id: 42 id: 10 node_id: MDI0OlB1bGxSZXF1ZXN0UmV2aWV3Q29tbWVudDEw diff_hunk: "@@ -16,33 +16,40 @@ public class Connection : IConnection..." path: file1.txt position: 1 original_position: 4 commit_id: 6dcb09b5b57875f334f61aebed695e2e4193db5e original_commit_id: 9c48853fa3dc5c1c3d6f1f1cd1f2743e72652840 in_reply_to_id: 8 user: login: octocat id: 1 node_id: MDQ6VXNlcjE= avatar_url: https://github.com/images/error/octocat_happy.gif gravatar_id: '' url: https://api.github.com/users/octocat html_url: https://github.com/octocat followers_url: https://api.github.com/users/octocat/followers following_url: https://api.github.com/users/octocat/following{/other_user} gists_url: https://api.github.com/users/octocat/gists{/gist_id} starred_url: https://api.github.com/users/octocat/starred{/owner}{/repo} subscriptions_url: https://api.github.com/users/octocat/subscriptions organizations_url: https://api.github.com/users/octocat/orgs repos_url: https://api.github.com/users/octocat/repos events_url: https://api.github.com/users/octocat/events{/privacy} received_events_url: https://api.github.com/users/octocat/received_events type: User site_admin: false body: Great stuff! created_at: '2011-04-14T16:00:49Z' updated_at: '2011-04-14T16:00:49Z' html_url: https://github.com/octocat/Hello-World/pull/1#discussion-diff-1 pull_request_url: https://api.github.com/repos/octocat/Hello-World/pulls/1 author_association: NONE _links: self: href: https://api.github.com/repos/octocat/Hello-World/pulls/comments/1 html: href: https://github.com/octocat/Hello-World/pull/1#discussion-diff-1 pull_request: href: https://api.github.com/repos/octocat/Hello-World/pulls/1 start_line: 1 original_start_line: 1 start_side: RIGHT line: 2 original_line: 2 side: RIGHT pull-request-review-comment-2: value: url: https://api.github.com/repos/octocat/Hello-World/pulls/comments/1 pull_request_review_id: 42 id: 10 node_id: MDI0OlB1bGxSZXF1ZXN0UmV2aWV3Q29tbWVudDEw diff_hunk: "@@ -16,33 +16,40 @@ public class Connection : IConnection..." path: file1.txt position: 1 original_position: 4 commit_id: 6dcb09b5b57875f334f61aebed695e2e4193db5e original_commit_id: 9c48853fa3dc5c1c3d6f1f1cd1f2743e72652840 in_reply_to_id: 8 user: login: octocat id: 1 node_id: MDQ6VXNlcjE= avatar_url: https://github.com/images/error/octocat_happy.gif gravatar_id: '' url: https://api.github.com/users/octocat html_url: https://github.com/octocat followers_url: https://api.github.com/users/octocat/followers following_url: https://api.github.com/users/octocat/following{/other_user} gists_url: https://api.github.com/users/octocat/gists{/gist_id} starred_url: https://api.github.com/users/octocat/starred{/owner}{/repo} subscriptions_url: https://api.github.com/users/octocat/subscriptions organizations_url: https://api.github.com/users/octocat/orgs repos_url: https://api.github.com/users/octocat/repos events_url: https://api.github.com/users/octocat/events{/privacy} received_events_url: https://api.github.com/users/octocat/received_events type: User site_admin: false body: Great stuff! created_at: '2011-04-14T16:00:49Z' updated_at: '2011-04-14T16:00:49Z' html_url: https://github.com/octocat/Hello-World/pull/1#discussion-diff-1 pull_request_url: https://api.github.com/repos/octocat/Hello-World/pulls/1 author_association: NONE _links: self: href: https://api.github.com/repos/octocat/Hello-World/pulls/comments/1 html: href: https://github.com/octocat/Hello-World/pull/1#discussion-diff-1 pull_request: href: https://api.github.com/repos/octocat/Hello-World/pulls/1 start_line: 1 original_start_line: 1 start_side: RIGHT line: 2 original_line: 2 side: RIGHT pull-request-review-comment-example-for-a-multi-line-comment: value: url: https://api.github.com/repos/octocat/Hello-World/pulls/comments/1 pull_request_review_id: 42 id: 10 node_id: MDI0OlB1bGxSZXF1ZXN0UmV2aWV3Q29tbWVudDEw diff_hunk: "@@ -16,33 +16,40 @@ public class Connection : IConnection..." path: file1.txt position: 1 original_position: 4 commit_id: 6dcb09b5b57875f334f61aebed695e2e4193db5e original_commit_id: 9c48853fa3dc5c1c3d6f1f1cd1f2743e72652840 in_reply_to_id: 8 user: login: octocat id: 1 node_id: MDQ6VXNlcjE= avatar_url: https://github.com/images/error/octocat_happy.gif gravatar_id: '' url: https://api.github.com/users/octocat html_url: https://github.com/octocat followers_url: https://api.github.com/users/octocat/followers following_url: https://api.github.com/users/octocat/following{/other_user} gists_url: https://api.github.com/users/octocat/gists{/gist_id} starred_url: https://api.github.com/users/octocat/starred{/owner}{/repo} subscriptions_url: https://api.github.com/users/octocat/subscriptions organizations_url: https://api.github.com/users/octocat/orgs repos_url: https://api.github.com/users/octocat/repos events_url: https://api.github.com/users/octocat/events{/privacy} received_events_url: https://api.github.com/users/octocat/received_events type: User site_admin: false body: Great stuff! created_at: '2011-04-14T16:00:49Z' updated_at: '2011-04-14T16:00:49Z' html_url: https://github.com/octocat/Hello-World/pull/1#discussion-diff-1 pull_request_url: https://api.github.com/repos/octocat/Hello-World/pulls/1 author_association: NONE _links: self: href: https://api.github.com/repos/octocat/Hello-World/pulls/comments/1 html: href: https://github.com/octocat/Hello-World/pull/1#discussion-diff-1 pull_request: href: https://api.github.com/repos/octocat/Hello-World/pulls/1 start_line: 1 original_start_line: 1 start_side: RIGHT line: 2 original_line: 2 side: RIGHT pull-request-review-comment: value: url: https://api.github.com/repos/octocat/Hello-World/pulls/comments/1 pull_request_review_id: 42 id: 10 node_id: MDI0OlB1bGxSZXF1ZXN0UmV2aWV3Q29tbWVudDEw diff_hunk: "@@ -16,33 +16,40 @@ public class Connection : IConnection..." path: file1.txt position: 1 original_position: 4 commit_id: 6dcb09b5b57875f334f61aebed695e2e4193db5e original_commit_id: 9c48853fa3dc5c1c3d6f1f1cd1f2743e72652840 in_reply_to_id: 426899381 user: login: octocat id: 1 node_id: MDQ6VXNlcjE= avatar_url: https://github.com/images/error/octocat_happy.gif gravatar_id: '' url: https://api.github.com/users/octocat html_url: https://github.com/octocat followers_url: https://api.github.com/users/octocat/followers following_url: https://api.github.com/users/octocat/following{/other_user} gists_url: https://api.github.com/users/octocat/gists{/gist_id} starred_url: https://api.github.com/users/octocat/starred{/owner}{/repo} subscriptions_url: https://api.github.com/users/octocat/subscriptions organizations_url: https://api.github.com/users/octocat/orgs repos_url: https://api.github.com/users/octocat/repos events_url: https://api.github.com/users/octocat/events{/privacy} received_events_url: https://api.github.com/users/octocat/received_events type: User site_admin: false body: Great stuff! created_at: '2011-04-14T16:00:49Z' updated_at: '2011-04-14T16:00:49Z' html_url: https://github.com/octocat/Hello-World/pull/1#discussion-diff-1 pull_request_url: https://api.github.com/repos/octocat/Hello-World/pulls/1 author_association: NONE _links: self: href: https://api.github.com/repos/octocat/Hello-World/pulls/comments/1 html: href: https://github.com/octocat/Hello-World/pull/1#discussion-diff-1 pull_request: href: https://api.github.com/repos/octocat/Hello-World/pulls/1 start_line: 1 original_start_line: 1 start_side: RIGHT line: 2 original_line: 2 side: RIGHT diff-entry-items: value: - sha: bbcd538c8e72b8c175046e27cc8f907076331401 filename: file1.txt status: added additions: 103 deletions: 21 changes: 124 blob_url: https://github.com/octocat/Hello-World/blob/6dcb09b5b57875f334f61aebed695e2e4193db5e/file1.txt raw_url: https://github.com/octocat/Hello-World/raw/6dcb09b5b57875f334f61aebed695e2e4193db5e/file1.txt contents_url: https://api.github.com/repos/octocat/Hello-World/contents/file1.txt?ref=6dcb09b5b57875f334f61aebed695e2e4193db5e patch: "@@ -132,7 +132,7 @@ module Test @@ -1000,7 +1000,7 @@ module Test" pull-request-merge-result-response-if-merge-was-successful: value: sha: 6dcb09b5b57875f334f61aebed695e2e4193db5e merged: true message: Pull Request successfully merged simple-pull-request-review-request: value: users: - login: octocat id: 1 node_id: MDQ6VXNlcjE= avatar_url: https://github.com/images/error/octocat_happy.gif gravatar_id: '' url: https://api.github.com/users/octocat html_url: https://github.com/octocat followers_url: https://api.github.com/users/octocat/followers following_url: https://api.github.com/users/octocat/following{/other_user} gists_url: https://api.github.com/users/octocat/gists{/gist_id} starred_url: https://api.github.com/users/octocat/starred{/owner}{/repo} subscriptions_url: https://api.github.com/users/octocat/subscriptions organizations_url: https://api.github.com/users/octocat/orgs repos_url: https://api.github.com/users/octocat/repos events_url: https://api.github.com/users/octocat/events{/privacy} received_events_url: https://api.github.com/users/octocat/received_events type: User site_admin: false teams: - id: 1 node_id: MDQ6VGVhbTE= url: https://api.github.com/teams/1 html_url: https://github.com/orgs/github/teams/justice-league name: Justice League slug: justice-league description: A great team. privacy: closed permission: admin members_url: https://api.github.com/teams/1/members{/member} repositories_url: https://api.github.com/teams/1/repos parent: pull-request-review-request: value: url: https://api.github.com/repos/octocat/Hello-World/pulls/1347 id: 1 node_id: MDExOlB1bGxSZXF1ZXN0MQ== html_url: https://github.com/octocat/Hello-World/pull/1347 diff_url: https://github.com/octocat/Hello-World/pull/1347.diff patch_url: https://github.com/octocat/Hello-World/pull/1347.patch issue_url: https://api.github.com/repos/octocat/Hello-World/issues/1347 commits_url: https://api.github.com/repos/octocat/Hello-World/pulls/1347/commits review_comments_url: https://api.github.com/repos/octocat/Hello-World/pulls/1347/comments review_comment_url: https://api.github.com/repos/octocat/Hello-World/pulls/comments{/number} comments_url: https://api.github.com/repos/octocat/Hello-World/issues/1347/comments statuses_url: https://api.github.com/repos/octocat/Hello-World/statuses/6dcb09b5b57875f334f61aebed695e2e4193db5e number: 1347 state: open locked: true title: Amazing new feature user: login: octocat id: 1 node_id: MDQ6VXNlcjE= avatar_url: https://github.com/images/error/octocat_happy.gif gravatar_id: '' url: https://api.github.com/users/octocat html_url: https://github.com/octocat followers_url: https://api.github.com/users/octocat/followers following_url: https://api.github.com/users/octocat/following{/other_user} gists_url: https://api.github.com/users/octocat/gists{/gist_id} starred_url: https://api.github.com/users/octocat/starred{/owner}{/repo} subscriptions_url: https://api.github.com/users/octocat/subscriptions organizations_url: https://api.github.com/users/octocat/orgs repos_url: https://api.github.com/users/octocat/repos events_url: https://api.github.com/users/octocat/events{/privacy} received_events_url: https://api.github.com/users/octocat/received_events type: User site_admin: false body: Please pull these awesome changes in! labels: - id: 208045946 node_id: MDU6TGFiZWwyMDgwNDU5NDY= url: https://api.github.com/repos/octocat/Hello-World/labels/bug name: bug description: Something isn't working color: f29513 default: true milestone: url: https://api.github.com/repos/octocat/Hello-World/milestones/1 html_url: https://github.com/octocat/Hello-World/milestones/v1.0 labels_url: https://api.github.com/repos/octocat/Hello-World/milestones/1/labels id: 1002604 node_id: MDk6TWlsZXN0b25lMTAwMjYwNA== number: 1 state: open title: v1.0 description: Tracking milestone for version 1.0 creator: login: octocat id: 1 node_id: MDQ6VXNlcjE= avatar_url: https://github.com/images/error/octocat_happy.gif gravatar_id: '' url: https://api.github.com/users/octocat html_url: https://github.com/octocat followers_url: https://api.github.com/users/octocat/followers following_url: https://api.github.com/users/octocat/following{/other_user} gists_url: https://api.github.com/users/octocat/gists{/gist_id} starred_url: https://api.github.com/users/octocat/starred{/owner}{/repo} subscriptions_url: https://api.github.com/users/octocat/subscriptions organizations_url: https://api.github.com/users/octocat/orgs repos_url: https://api.github.com/users/octocat/repos events_url: https://api.github.com/users/octocat/events{/privacy} received_events_url: https://api.github.com/users/octocat/received_events type: User site_admin: false open_issues: 4 closed_issues: 8 created_at: '2011-04-10T20:09:31Z' updated_at: '2014-03-03T18:58:10Z' closed_at: '2013-02-12T13:22:01Z' due_on: '2012-10-09T23:39:01Z' active_lock_reason: too heated created_at: '2011-01-26T19:01:12Z' updated_at: '2011-01-26T19:01:12Z' closed_at: '2011-01-26T19:01:12Z' merged_at: '2011-01-26T19:01:12Z' merge_commit_sha: e5bd3914e2e596debea16f433f57875b5b90bcd6 assignee: login: octocat id: 1 node_id: MDQ6VXNlcjE= avatar_url: https://github.com/images/error/octocat_happy.gif gravatar_id: '' url: https://api.github.com/users/octocat html_url: https://github.com/octocat followers_url: https://api.github.com/users/octocat/followers following_url: https://api.github.com/users/octocat/following{/other_user} gists_url: https://api.github.com/users/octocat/gists{/gist_id} starred_url: https://api.github.com/users/octocat/starred{/owner}{/repo} subscriptions_url: https://api.github.com/users/octocat/subscriptions organizations_url: https://api.github.com/users/octocat/orgs repos_url: https://api.github.com/users/octocat/repos events_url: https://api.github.com/users/octocat/events{/privacy} received_events_url: https://api.github.com/users/octocat/received_events type: User site_admin: false assignees: - login: octocat id: 1 node_id: MDQ6VXNlcjE= avatar_url: https://github.com/images/error/octocat_happy.gif gravatar_id: '' url: https://api.github.com/users/octocat html_url: https://github.com/octocat followers_url: https://api.github.com/users/octocat/followers following_url: https://api.github.com/users/octocat/following{/other_user} gists_url: https://api.github.com/users/octocat/gists{/gist_id} starred_url: https://api.github.com/users/octocat/starred{/owner}{/repo} subscriptions_url: https://api.github.com/users/octocat/subscriptions organizations_url: https://api.github.com/users/octocat/orgs repos_url: https://api.github.com/users/octocat/repos events_url: https://api.github.com/users/octocat/events{/privacy} received_events_url: https://api.github.com/users/octocat/received_events type: User site_admin: false - login: hubot id: 1 node_id: MDQ6VXNlcjE= avatar_url: https://github.com/images/error/hubot_happy.gif gravatar_id: '' url: https://api.github.com/users/hubot html_url: https://github.com/hubot followers_url: https://api.github.com/users/hubot/followers following_url: https://api.github.com/users/hubot/following{/other_user} gists_url: https://api.github.com/users/hubot/gists{/gist_id} starred_url: https://api.github.com/users/hubot/starred{/owner}{/repo} subscriptions_url: https://api.github.com/users/hubot/subscriptions organizations_url: https://api.github.com/users/hubot/orgs repos_url: https://api.github.com/users/hubot/repos events_url: https://api.github.com/users/hubot/events{/privacy} received_events_url: https://api.github.com/users/hubot/received_events type: User site_admin: true requested_reviewers: - login: octocat id: 1 node_id: MDQ6VXNlcjE= avatar_url: https://github.com/images/error/octocat_happy.gif gravatar_id: '' url: https://api.github.com/users/octocat html_url: https://github.com/octocat followers_url: https://api.github.com/users/octocat/followers following_url: https://api.github.com/users/octocat/following{/other_user} gists_url: https://api.github.com/users/octocat/gists{/gist_id} starred_url: https://api.github.com/users/octocat/starred{/owner}{/repo} subscriptions_url: https://api.github.com/users/octocat/subscriptions organizations_url: https://api.github.com/users/octocat/orgs repos_url: https://api.github.com/users/octocat/repos events_url: https://api.github.com/users/octocat/events{/privacy} received_events_url: https://api.github.com/users/octocat/received_events type: User site_admin: false - login: hubot id: 1 node_id: MDQ6VXNlcjE= avatar_url: https://github.com/images/error/hubot_happy.gif gravatar_id: '' url: https://api.github.com/users/hubot html_url: https://github.com/hubot followers_url: https://api.github.com/users/hubot/followers following_url: https://api.github.com/users/hubot/following{/other_user} gists_url: https://api.github.com/users/hubot/gists{/gist_id} starred_url: https://api.github.com/users/hubot/starred{/owner}{/repo} subscriptions_url: https://api.github.com/users/hubot/subscriptions organizations_url: https://api.github.com/users/hubot/orgs repos_url: https://api.github.com/users/hubot/repos events_url: https://api.github.com/users/hubot/events{/privacy} received_events_url: https://api.github.com/users/hubot/received_events type: User site_admin: true - login: other_user id: 1 node_id: MDQ6VXNlcjE= avatar_url: https://github.com/images/error/other_user_happy.gif gravatar_id: '' url: https://api.github.com/users/other_user html_url: https://github.com/other_user followers_url: https://api.github.com/users/other_user/followers following_url: https://api.github.com/users/other_user/following{/other_user} gists_url: https://api.github.com/users/other_user/gists{/gist_id} starred_url: https://api.github.com/users/other_user/starred{/owner}{/repo} subscriptions_url: https://api.github.com/users/other_user/subscriptions organizations_url: https://api.github.com/users/other_user/orgs repos_url: https://api.github.com/users/other_user/repos events_url: https://api.github.com/users/other_user/events{/privacy} received_events_url: https://api.github.com/users/other_user/received_events type: User site_admin: false requested_teams: - id: 1 node_id: MDQ6VGVhbTE= url: https://api.github.com/teams/1 html_url: https://github.com/orgs/github/teams/justice-league name: Justice League slug: justice-league description: A great team. privacy: closed permission: admin members_url: https://api.github.com/teams/1/members{/member} repositories_url: https://api.github.com/teams/1/repos parent: head: label: octocat:new-topic ref: new-topic sha: 6dcb09b5b57875f334f61aebed695e2e4193db5e user: login: octocat id: 1 node_id: MDQ6VXNlcjE= avatar_url: https://github.com/images/error/octocat_happy.gif gravatar_id: '' url: https://api.github.com/users/octocat html_url: https://github.com/octocat followers_url: https://api.github.com/users/octocat/followers following_url: https://api.github.com/users/octocat/following{/other_user} gists_url: https://api.github.com/users/octocat/gists{/gist_id} starred_url: https://api.github.com/users/octocat/starred{/owner}{/repo} subscriptions_url: https://api.github.com/users/octocat/subscriptions organizations_url: https://api.github.com/users/octocat/orgs repos_url: https://api.github.com/users/octocat/repos events_url: https://api.github.com/users/octocat/events{/privacy} received_events_url: https://api.github.com/users/octocat/received_events type: User site_admin: false repo: id: 1296269 node_id: MDEwOlJlcG9zaXRvcnkxMjk2MjY5 name: Hello-World full_name: octocat/Hello-World owner: login: octocat id: 1 node_id: MDQ6VXNlcjE= avatar_url: https://github.com/images/error/octocat_happy.gif gravatar_id: '' url: https://api.github.com/users/octocat html_url: https://github.com/octocat followers_url: https://api.github.com/users/octocat/followers following_url: https://api.github.com/users/octocat/following{/other_user} gists_url: https://api.github.com/users/octocat/gists{/gist_id} starred_url: https://api.github.com/users/octocat/starred{/owner}{/repo} subscriptions_url: https://api.github.com/users/octocat/subscriptions organizations_url: https://api.github.com/users/octocat/orgs repos_url: https://api.github.com/users/octocat/repos events_url: https://api.github.com/users/octocat/events{/privacy} received_events_url: https://api.github.com/users/octocat/received_events type: User site_admin: false private: false html_url: https://github.com/octocat/Hello-World description: This your first repo! fork: false url: https://api.github.com/repos/octocat/Hello-World archive_url: https://api.github.com/repos/octocat/Hello-World/{archive_format}{/ref} assignees_url: https://api.github.com/repos/octocat/Hello-World/assignees{/user} blobs_url: https://api.github.com/repos/octocat/Hello-World/git/blobs{/sha} branches_url: https://api.github.com/repos/octocat/Hello-World/branches{/branch} collaborators_url: https://api.github.com/repos/octocat/Hello-World/collaborators{/collaborator} comments_url: https://api.github.com/repos/octocat/Hello-World/comments{/number} commits_url: https://api.github.com/repos/octocat/Hello-World/commits{/sha} compare_url: https://api.github.com/repos/octocat/Hello-World/compare/{base}...{head} contents_url: https://api.github.com/repos/octocat/Hello-World/contents/{+path} contributors_url: https://api.github.com/repos/octocat/Hello-World/contributors deployments_url: https://api.github.com/repos/octocat/Hello-World/deployments downloads_url: https://api.github.com/repos/octocat/Hello-World/downloads events_url: https://api.github.com/repos/octocat/Hello-World/events forks_url: https://api.github.com/repos/octocat/Hello-World/forks git_commits_url: https://api.github.com/repos/octocat/Hello-World/git/commits{/sha} git_refs_url: https://api.github.com/repos/octocat/Hello-World/git/refs{/sha} git_tags_url: https://api.github.com/repos/octocat/Hello-World/git/tags{/sha} git_url: git:github.com/octocat/Hello-World.git issue_comment_url: https://api.github.com/repos/octocat/Hello-World/issues/comments{/number} issue_events_url: https://api.github.com/repos/octocat/Hello-World/issues/events{/number} issues_url: https://api.github.com/repos/octocat/Hello-World/issues{/number} keys_url: https://api.github.com/repos/octocat/Hello-World/keys{/key_id} labels_url: https://api.github.com/repos/octocat/Hello-World/labels{/name} languages_url: https://api.github.com/repos/octocat/Hello-World/languages merges_url: https://api.github.com/repos/octocat/Hello-World/merges milestones_url: https://api.github.com/repos/octocat/Hello-World/milestones{/number} notifications_url: https://api.github.com/repos/octocat/Hello-World/notifications{?since,all,participating} pulls_url: https://api.github.com/repos/octocat/Hello-World/pulls{/number} releases_url: https://api.github.com/repos/octocat/Hello-World/releases{/id} ssh_url: git@github.com:octocat/Hello-World.git stargazers_url: https://api.github.com/repos/octocat/Hello-World/stargazers statuses_url: https://api.github.com/repos/octocat/Hello-World/statuses/{sha} subscribers_url: https://api.github.com/repos/octocat/Hello-World/subscribers subscription_url: https://api.github.com/repos/octocat/Hello-World/subscription tags_url: https://api.github.com/repos/octocat/Hello-World/tags teams_url: https://api.github.com/repos/octocat/Hello-World/teams trees_url: https://api.github.com/repos/octocat/Hello-World/git/trees{/sha} clone_url: https://github.com/octocat/Hello-World.git mirror_url: git:git.example.com/octocat/Hello-World hooks_url: https://api.github.com/repos/octocat/Hello-World/hooks svn_url: https://svn.github.com/octocat/Hello-World homepage: https://github.com forks_count: 9 stargazers_count: 80 watchers_count: 80 size: 108 default_branch: master open_issues_count: 0 is_template: true topics: - octocat - atom - electron - api has_issues: true has_projects: true has_wiki: true has_pages: false has_downloads: true archived: false disabled: false visibility: public pushed_at: '2011-01-26T19:06:43Z' created_at: '2011-01-26T19:01:12Z' updated_at: '2011-01-26T19:14:43Z' permissions: admin: false push: false pull: true allow_rebase_merge: true temp_clone_token: ABTLWHOULUVAXGTRYU7OC2876QJ2O allow_squash_merge: true delete_branch_on_merge: true allow_merge_commit: true subscribers_count: 42 network_count: 0 license: key: mit name: MIT License url: https://api.github.com/licenses/mit spdx_id: MIT node_id: MDc6TGljZW5zZW1pdA== html_url: https://github.com/licenses/mit forks: 1 open_issues: 1 watchers: 1 base: label: octocat:master ref: master sha: 6dcb09b5b57875f334f61aebed695e2e4193db5e user: login: octocat id: 1 node_id: MDQ6VXNlcjE= avatar_url: https://github.com/images/error/octocat_happy.gif gravatar_id: '' url: https://api.github.com/users/octocat html_url: https://github.com/octocat followers_url: https://api.github.com/users/octocat/followers following_url: https://api.github.com/users/octocat/following{/other_user} gists_url: https://api.github.com/users/octocat/gists{/gist_id} starred_url: https://api.github.com/users/octocat/starred{/owner}{/repo} subscriptions_url: https://api.github.com/users/octocat/subscriptions organizations_url: https://api.github.com/users/octocat/orgs repos_url: https://api.github.com/users/octocat/repos events_url: https://api.github.com/users/octocat/events{/privacy} received_events_url: https://api.github.com/users/octocat/received_events type: User site_admin: false repo: id: 1296269 node_id: MDEwOlJlcG9zaXRvcnkxMjk2MjY5 name: Hello-World full_name: octocat/Hello-World owner: login: octocat id: 1 node_id: MDQ6VXNlcjE= avatar_url: https://github.com/images/error/octocat_happy.gif gravatar_id: '' url: https://api.github.com/users/octocat html_url: https://github.com/octocat followers_url: https://api.github.com/users/octocat/followers following_url: https://api.github.com/users/octocat/following{/other_user} gists_url: https://api.github.com/users/octocat/gists{/gist_id} starred_url: https://api.github.com/users/octocat/starred{/owner}{/repo} subscriptions_url: https://api.github.com/users/octocat/subscriptions organizations_url: https://api.github.com/users/octocat/orgs repos_url: https://api.github.com/users/octocat/repos events_url: https://api.github.com/users/octocat/events{/privacy} received_events_url: https://api.github.com/users/octocat/received_events type: User site_admin: false private: false html_url: https://github.com/octocat/Hello-World description: This your first repo! fork: false url: https://api.github.com/repos/octocat/Hello-World archive_url: https://api.github.com/repos/octocat/Hello-World/{archive_format}{/ref} assignees_url: https://api.github.com/repos/octocat/Hello-World/assignees{/user} blobs_url: https://api.github.com/repos/octocat/Hello-World/git/blobs{/sha} branches_url: https://api.github.com/repos/octocat/Hello-World/branches{/branch} collaborators_url: https://api.github.com/repos/octocat/Hello-World/collaborators{/collaborator} comments_url: https://api.github.com/repos/octocat/Hello-World/comments{/number} commits_url: https://api.github.com/repos/octocat/Hello-World/commits{/sha} compare_url: https://api.github.com/repos/octocat/Hello-World/compare/{base}...{head} contents_url: https://api.github.com/repos/octocat/Hello-World/contents/{+path} contributors_url: https://api.github.com/repos/octocat/Hello-World/contributors deployments_url: https://api.github.com/repos/octocat/Hello-World/deployments downloads_url: https://api.github.com/repos/octocat/Hello-World/downloads events_url: https://api.github.com/repos/octocat/Hello-World/events forks_url: https://api.github.com/repos/octocat/Hello-World/forks git_commits_url: https://api.github.com/repos/octocat/Hello-World/git/commits{/sha} git_refs_url: https://api.github.com/repos/octocat/Hello-World/git/refs{/sha} git_tags_url: https://api.github.com/repos/octocat/Hello-World/git/tags{/sha} git_url: git:github.com/octocat/Hello-World.git issue_comment_url: https://api.github.com/repos/octocat/Hello-World/issues/comments{/number} issue_events_url: https://api.github.com/repos/octocat/Hello-World/issues/events{/number} issues_url: https://api.github.com/repos/octocat/Hello-World/issues{/number} keys_url: https://api.github.com/repos/octocat/Hello-World/keys{/key_id} labels_url: https://api.github.com/repos/octocat/Hello-World/labels{/name} languages_url: https://api.github.com/repos/octocat/Hello-World/languages merges_url: https://api.github.com/repos/octocat/Hello-World/merges milestones_url: https://api.github.com/repos/octocat/Hello-World/milestones{/number} notifications_url: https://api.github.com/repos/octocat/Hello-World/notifications{?since,all,participating} pulls_url: https://api.github.com/repos/octocat/Hello-World/pulls{/number} releases_url: https://api.github.com/repos/octocat/Hello-World/releases{/id} ssh_url: git@github.com:octocat/Hello-World.git stargazers_url: https://api.github.com/repos/octocat/Hello-World/stargazers statuses_url: https://api.github.com/repos/octocat/Hello-World/statuses/{sha} subscribers_url: https://api.github.com/repos/octocat/Hello-World/subscribers subscription_url: https://api.github.com/repos/octocat/Hello-World/subscription tags_url: https://api.github.com/repos/octocat/Hello-World/tags teams_url: https://api.github.com/repos/octocat/Hello-World/teams trees_url: https://api.github.com/repos/octocat/Hello-World/git/trees{/sha} clone_url: https://github.com/octocat/Hello-World.git mirror_url: git:git.example.com/octocat/Hello-World hooks_url: https://api.github.com/repos/octocat/Hello-World/hooks svn_url: https://svn.github.com/octocat/Hello-World homepage: https://github.com forks_count: 9 stargazers_count: 80 watchers_count: 80 size: 108 default_branch: master open_issues_count: 0 is_template: true topics: - octocat - atom - electron - api has_issues: true has_projects: true has_wiki: true has_pages: false has_downloads: true archived: false disabled: false visibility: public pushed_at: '2011-01-26T19:06:43Z' created_at: '2011-01-26T19:01:12Z' updated_at: '2011-01-26T19:14:43Z' permissions: admin: false push: false pull: true allow_rebase_merge: true temp_clone_token: ABTLWHOULUVAXGTRYU7OC2876QJ2O allow_squash_merge: true delete_branch_on_merge: true allow_merge_commit: true subscribers_count: 42 network_count: 0 license: key: mit name: MIT License url: https://api.github.com/licenses/mit spdx_id: MIT node_id: MDc6TGljZW5zZW1pdA== html_url: https://api.github.com/licenses/mit forks: 1 open_issues: 1 watchers: 1 _links: self: href: https://api.github.com/repos/octocat/Hello-World/pulls/1347 html: href: https://github.com/octocat/Hello-World/pull/1347 issue: href: https://api.github.com/repos/octocat/Hello-World/issues/1347 comments: href: https://api.github.com/repos/octocat/Hello-World/issues/1347/comments review_comments: href: https://api.github.com/repos/octocat/Hello-World/pulls/1347/comments review_comment: href: https://api.github.com/repos/octocat/Hello-World/pulls/comments{/number} commits: href: https://api.github.com/repos/octocat/Hello-World/pulls/1347/commits statuses: href: https://api.github.com/repos/octocat/Hello-World/statuses/6dcb09b5b57875f334f61aebed695e2e4193db5e author_association: OWNER draft: false pull-request-review-items: value: - id: 80 node_id: MDE3OlB1bGxSZXF1ZXN0UmV2aWV3ODA= user: login: octocat id: 1 node_id: MDQ6VXNlcjE= avatar_url: https://github.com/images/error/octocat_happy.gif gravatar_id: '' url: https://api.github.com/users/octocat html_url: https://github.com/octocat followers_url: https://api.github.com/users/octocat/followers following_url: https://api.github.com/users/octocat/following{/other_user} gists_url: https://api.github.com/users/octocat/gists{/gist_id} starred_url: https://api.github.com/users/octocat/starred{/owner}{/repo} subscriptions_url: https://api.github.com/users/octocat/subscriptions organizations_url: https://api.github.com/users/octocat/orgs repos_url: https://api.github.com/users/octocat/repos events_url: https://api.github.com/users/octocat/events{/privacy} received_events_url: https://api.github.com/users/octocat/received_events type: User site_admin: false body: Here is the body for the review. state: APPROVED html_url: https://github.com/octocat/Hello-World/pull/12#pullrequestreview-80 pull_request_url: https://api.github.com/repos/octocat/Hello-World/pulls/12 _links: html: href: https://github.com/octocat/Hello-World/pull/12#pullrequestreview-80 pull_request: href: https://api.github.com/repos/octocat/Hello-World/pulls/12 submitted_at: '2019-11-17T17:43:43Z' commit_id: ecdd80bb57125d7ba9641ffaa4d7d2c19d3f3091 author_association: COLLABORATOR pull-request-review: value: id: 80 node_id: MDE3OlB1bGxSZXF1ZXN0UmV2aWV3ODA= user: login: octocat id: 1 node_id: MDQ6VXNlcjE= avatar_url: https://github.com/images/error/octocat_happy.gif gravatar_id: '' url: https://api.github.com/users/octocat html_url: https://github.com/octocat followers_url: https://api.github.com/users/octocat/followers following_url: https://api.github.com/users/octocat/following{/other_user} gists_url: https://api.github.com/users/octocat/gists{/gist_id} starred_url: https://api.github.com/users/octocat/starred{/owner}{/repo} subscriptions_url: https://api.github.com/users/octocat/subscriptions organizations_url: https://api.github.com/users/octocat/orgs repos_url: https://api.github.com/users/octocat/repos events_url: https://api.github.com/users/octocat/events{/privacy} received_events_url: https://api.github.com/users/octocat/received_events type: User site_admin: false body: This is close to perfect! Please address the suggested inline change. state: CHANGES_REQUESTED html_url: https://github.com/octocat/Hello-World/pull/12#pullrequestreview-80 pull_request_url: https://api.github.com/repos/octocat/Hello-World/pulls/12 _links: html: href: https://github.com/octocat/Hello-World/pull/12#pullrequestreview-80 pull_request: href: https://api.github.com/repos/octocat/Hello-World/pulls/12 submitted_at: '2019-11-17T17:43:43Z' commit_id: ecdd80bb57125d7ba9641ffaa4d7d2c19d3f3091 author_association: COLLABORATOR pull-request-review-4: value: id: 80 node_id: MDE3OlB1bGxSZXF1ZXN0UmV2aWV3ODA= user: login: octocat id: 1 node_id: MDQ6VXNlcjE= avatar_url: https://github.com/images/error/octocat_happy.gif gravatar_id: '' url: https://api.github.com/users/octocat html_url: https://github.com/octocat followers_url: https://api.github.com/users/octocat/followers following_url: https://api.github.com/users/octocat/following{/other_user} gists_url: https://api.github.com/users/octocat/gists{/gist_id} starred_url: https://api.github.com/users/octocat/starred{/owner}{/repo} subscriptions_url: https://api.github.com/users/octocat/subscriptions organizations_url: https://api.github.com/users/octocat/orgs repos_url: https://api.github.com/users/octocat/repos events_url: https://api.github.com/users/octocat/events{/privacy} received_events_url: https://api.github.com/users/octocat/received_events type: User site_admin: false body: Here is the body for the review. state: APPROVED html_url: https://github.com/octocat/Hello-World/pull/12#pullrequestreview-80 pull_request_url: https://api.github.com/repos/octocat/Hello-World/pulls/12 _links: html: href: https://github.com/octocat/Hello-World/pull/12#pullrequestreview-80 pull_request: href: https://api.github.com/repos/octocat/Hello-World/pulls/12 submitted_at: '2019-11-17T17:43:43Z' commit_id: ecdd80bb57125d7ba9641ffaa4d7d2c19d3f3091 author_association: COLLABORATOR pull-request-review-5: value: id: 80 node_id: MDE3OlB1bGxSZXF1ZXN0UmV2aWV3ODA= user: login: octocat id: 1 node_id: MDQ6VXNlcjE= avatar_url: https://github.com/images/error/octocat_happy.gif gravatar_id: '' url: https://api.github.com/users/octocat html_url: https://github.com/octocat followers_url: https://api.github.com/users/octocat/followers following_url: https://api.github.com/users/octocat/following{/other_user} gists_url: https://api.github.com/users/octocat/gists{/gist_id} starred_url: https://api.github.com/users/octocat/starred{/owner}{/repo} subscriptions_url: https://api.github.com/users/octocat/subscriptions organizations_url: https://api.github.com/users/octocat/orgs repos_url: https://api.github.com/users/octocat/repos events_url: https://api.github.com/users/octocat/events{/privacy} received_events_url: https://api.github.com/users/octocat/received_events type: User site_admin: false body: This is close to perfect! Please address the suggested inline change. And add more about this. state: CHANGES_REQUESTED html_url: https://github.com/octocat/Hello-World/pull/12#pullrequestreview-80 pull_request_url: https://api.github.com/repos/octocat/Hello-World/pulls/12 _links: html: href: https://github.com/octocat/Hello-World/pull/12#pullrequestreview-80 pull_request: href: https://api.github.com/repos/octocat/Hello-World/pulls/12 submitted_at: '2019-11-17T17:43:43Z' commit_id: ecdd80bb57125d7ba9641ffaa4d7d2c19d3f3091 author_association: COLLABORATOR review-comment-items: value: - url: https://api.github.com/repos/octocat/Hello-World/pulls/comments/1 pull_request_review_id: 42 id: 10 node_id: MDI0OlB1bGxSZXF1ZXN0UmV2aWV3Q29tbWVudDEw diff_hunk: "@@ -16,33 +16,40 @@ public class Connection : IConnection..." path: file1.txt position: 1 original_position: 4 commit_id: 6dcb09b5b57875f334f61aebed695e2e4193db5e original_commit_id: 9c48853fa3dc5c1c3d6f1f1cd1f2743e72652840 in_reply_to_id: 8 user: login: octocat id: 1 node_id: MDQ6VXNlcjE= avatar_url: https://github.com/images/error/octocat_happy.gif gravatar_id: '' url: https://api.github.com/users/octocat html_url: https://github.com/octocat followers_url: https://api.github.com/users/octocat/followers following_url: https://api.github.com/users/octocat/following{/other_user} gists_url: https://api.github.com/users/octocat/gists{/gist_id} starred_url: https://api.github.com/users/octocat/starred{/owner}{/repo} subscriptions_url: https://api.github.com/users/octocat/subscriptions organizations_url: https://api.github.com/users/octocat/orgs repos_url: https://api.github.com/users/octocat/repos events_url: https://api.github.com/users/octocat/events{/privacy} received_events_url: https://api.github.com/users/octocat/received_events type: User site_admin: false body: Great stuff! created_at: '2011-04-14T16:00:49Z' updated_at: '2011-04-14T16:00:49Z' html_url: https://github.com/octocat/Hello-World/pull/1#discussion-diff-1 pull_request_url: https://api.github.com/repos/octocat/Hello-World/pulls/1 author_association: NONE _links: self: href: https://api.github.com/repos/octocat/Hello-World/pulls/comments/1 html: href: https://github.com/octocat/Hello-World/pull/1#discussion-diff-1 pull_request: href: https://api.github.com/repos/octocat/Hello-World/pulls/1 pull-request-review-3: value: id: 80 node_id: MDE3OlB1bGxSZXF1ZXN0UmV2aWV3ODA= user: login: octocat id: 1 node_id: MDQ6VXNlcjE= avatar_url: https://github.com/images/error/octocat_happy.gif gravatar_id: '' url: https://api.github.com/users/octocat html_url: https://github.com/octocat followers_url: https://api.github.com/users/octocat/followers following_url: https://api.github.com/users/octocat/following{/other_user} gists_url: https://api.github.com/users/octocat/gists{/gist_id} starred_url: https://api.github.com/users/octocat/starred{/owner}{/repo} subscriptions_url: https://api.github.com/users/octocat/subscriptions organizations_url: https://api.github.com/users/octocat/orgs repos_url: https://api.github.com/users/octocat/repos events_url: https://api.github.com/users/octocat/events{/privacy} received_events_url: https://api.github.com/users/octocat/received_events type: User site_admin: false body: Here is the body for the review. state: DISMISSED html_url: https://github.com/octocat/Hello-World/pull/12#pullrequestreview-80 pull_request_url: https://api.github.com/repos/octocat/Hello-World/pulls/12 _links: html: href: https://github.com/octocat/Hello-World/pull/12#pullrequestreview-80 pull_request: href: https://api.github.com/repos/octocat/Hello-World/pulls/12 submitted_at: '2019-11-17T17:43:43Z' commit_id: ecdd80bb57125d7ba9641ffaa4d7d2c19d3f3091 author_association: COLLABORATOR content-file: value: type: file encoding: base64 size: 5362 name: README.md path: README.md content: encoded content ... sha: 3d21ec53a331a6f037a91c368710b99387d012c1 url: https://api.github.com/repos/octokit/octokit.rb/contents/README.md git_url: https://api.github.com/repos/octokit/octokit.rb/git/blobs/3d21ec53a331a6f037a91c368710b99387d012c1 html_url: https://github.com/octokit/octokit.rb/blob/master/README.md download_url: https://raw.githubusercontent.com/octokit/octokit.rb/master/README.md _links: git: https://api.github.com/repos/octokit/octokit.rb/git/blobs/3d21ec53a331a6f037a91c368710b99387d012c1 self: https://api.github.com/repos/octokit/octokit.rb/contents/README.md html: https://github.com/octokit/octokit.rb/blob/master/README.md release-items: value: - url: https://api.github.com/repos/octocat/Hello-World/releases/1 html_url: https://github.com/octocat/Hello-World/releases/v1.0.0 assets_url: https://api.github.com/repos/octocat/Hello-World/releases/1/assets upload_url: https://uploads.github.com/repos/octocat/Hello-World/releases/1/assets{?name,label} tarball_url: https://api.github.com/repos/octocat/Hello-World/tarball/v1.0.0 zipball_url: https://api.github.com/repos/octocat/Hello-World/zipball/v1.0.0 id: 1 node_id: MDc6UmVsZWFzZTE= tag_name: v1.0.0 target_commitish: master name: v1.0.0 body: Description of the release draft: false prerelease: false created_at: '2013-02-27T19:35:32Z' published_at: '2013-02-27T19:35:32Z' author: login: octocat id: 1 node_id: MDQ6VXNlcjE= avatar_url: https://github.com/images/error/octocat_happy.gif gravatar_id: '' url: https://api.github.com/users/octocat html_url: https://github.com/octocat followers_url: https://api.github.com/users/octocat/followers following_url: https://api.github.com/users/octocat/following{/other_user} gists_url: https://api.github.com/users/octocat/gists{/gist_id} starred_url: https://api.github.com/users/octocat/starred{/owner}{/repo} subscriptions_url: https://api.github.com/users/octocat/subscriptions organizations_url: https://api.github.com/users/octocat/orgs repos_url: https://api.github.com/users/octocat/repos events_url: https://api.github.com/users/octocat/events{/privacy} received_events_url: https://api.github.com/users/octocat/received_events type: User site_admin: false assets: - url: https://api.github.com/repos/octocat/Hello-World/releases/assets/1 browser_download_url: https://github.com/octocat/Hello-World/releases/download/v1.0.0/example.zip id: 1 node_id: MDEyOlJlbGVhc2VBc3NldDE= name: example.zip label: short description state: uploaded content_type: application/zip size: 1024 download_count: 42 created_at: '2013-02-27T19:35:32Z' updated_at: '2013-02-27T19:35:32Z' uploader: login: octocat id: 1 node_id: MDQ6VXNlcjE= avatar_url: https://github.com/images/error/octocat_happy.gif gravatar_id: '' url: https://api.github.com/users/octocat html_url: https://github.com/octocat followers_url: https://api.github.com/users/octocat/followers following_url: https://api.github.com/users/octocat/following{/other_user} gists_url: https://api.github.com/users/octocat/gists{/gist_id} starred_url: https://api.github.com/users/octocat/starred{/owner}{/repo} subscriptions_url: https://api.github.com/users/octocat/subscriptions organizations_url: https://api.github.com/users/octocat/orgs repos_url: https://api.github.com/users/octocat/repos events_url: https://api.github.com/users/octocat/events{/privacy} received_events_url: https://api.github.com/users/octocat/received_events type: User site_admin: false release: value: url: https://api.github.com/repos/octocat/Hello-World/releases/1 html_url: https://github.com/octocat/Hello-World/releases/v1.0.0 assets_url: https://api.github.com/repos/octocat/Hello-World/releases/1/assets upload_url: https://uploads.github.com/repos/octocat/Hello-World/releases/1/assets{?name,label} tarball_url: https://api.github.com/repos/octocat/Hello-World/tarball/v1.0.0 zipball_url: https://api.github.com/repos/octocat/Hello-World/zipball/v1.0.0 discussion_url: https://github.com/octocat/Hello-World/discussions/90 id: 1 node_id: MDc6UmVsZWFzZTE= tag_name: v1.0.0 target_commitish: master name: v1.0.0 body: Description of the release draft: false prerelease: false created_at: '2013-02-27T19:35:32Z' published_at: '2013-02-27T19:35:32Z' author: login: octocat id: 1 node_id: MDQ6VXNlcjE= avatar_url: https://github.com/images/error/octocat_happy.gif gravatar_id: '' url: https://api.github.com/users/octocat html_url: https://github.com/octocat followers_url: https://api.github.com/users/octocat/followers following_url: https://api.github.com/users/octocat/following{/other_user} gists_url: https://api.github.com/users/octocat/gists{/gist_id} starred_url: https://api.github.com/users/octocat/starred{/owner}{/repo} subscriptions_url: https://api.github.com/users/octocat/subscriptions organizations_url: https://api.github.com/users/octocat/orgs repos_url: https://api.github.com/users/octocat/repos events_url: https://api.github.com/users/octocat/events{/privacy} received_events_url: https://api.github.com/users/octocat/received_events type: User site_admin: false assets: - url: https://api.github.com/repos/octocat/Hello-World/releases/assets/1 browser_download_url: https://github.com/octocat/Hello-World/releases/download/v1.0.0/example.zip id: 1 node_id: MDEyOlJlbGVhc2VBc3NldDE= name: example.zip label: short description state: uploaded content_type: application/zip size: 1024 download_count: 42 created_at: '2013-02-27T19:35:32Z' updated_at: '2013-02-27T19:35:32Z' uploader: login: octocat id: 1 node_id: MDQ6VXNlcjE= avatar_url: https://github.com/images/error/octocat_happy.gif gravatar_id: '' url: https://api.github.com/users/octocat html_url: https://github.com/octocat followers_url: https://api.github.com/users/octocat/followers following_url: https://api.github.com/users/octocat/following{/other_user} gists_url: https://api.github.com/users/octocat/gists{/gist_id} starred_url: https://api.github.com/users/octocat/starred{/owner}{/repo} subscriptions_url: https://api.github.com/users/octocat/subscriptions organizations_url: https://api.github.com/users/octocat/orgs repos_url: https://api.github.com/users/octocat/repos events_url: https://api.github.com/users/octocat/events{/privacy} received_events_url: https://api.github.com/users/octocat/received_events type: User site_admin: false release-asset: value: url: https://api.github.com/repos/octocat/Hello-World/releases/assets/1 browser_download_url: https://github.com/octocat/Hello-World/releases/download/v1.0.0/example.zip id: 1 node_id: MDEyOlJlbGVhc2VBc3NldDE= name: example.zip label: short description state: uploaded content_type: application/zip size: 1024 download_count: 42 created_at: '2013-02-27T19:35:32Z' updated_at: '2013-02-27T19:35:32Z' uploader: login: octocat id: 1 node_id: MDQ6VXNlcjE= avatar_url: https://github.com/images/error/octocat_happy.gif gravatar_id: '' url: https://api.github.com/users/octocat html_url: https://github.com/octocat followers_url: https://api.github.com/users/octocat/followers following_url: https://api.github.com/users/octocat/following{/other_user} gists_url: https://api.github.com/users/octocat/gists{/gist_id} starred_url: https://api.github.com/users/octocat/starred{/owner}{/repo} subscriptions_url: https://api.github.com/users/octocat/subscriptions organizations_url: https://api.github.com/users/octocat/orgs repos_url: https://api.github.com/users/octocat/repos events_url: https://api.github.com/users/octocat/events{/privacy} received_events_url: https://api.github.com/users/octocat/received_events type: User site_admin: false release-asset-items: value: - url: https://api.github.com/repos/octocat/Hello-World/releases/assets/1 browser_download_url: https://github.com/octocat/Hello-World/releases/download/v1.0.0/example.zip id: 1 node_id: MDEyOlJlbGVhc2VBc3NldDE= name: example.zip label: short description state: uploaded content_type: application/zip size: 1024 download_count: 42 created_at: '2013-02-27T19:35:32Z' updated_at: '2013-02-27T19:35:32Z' uploader: login: octocat id: 1 node_id: MDQ6VXNlcjE= avatar_url: https://github.com/images/error/octocat_happy.gif gravatar_id: '' url: https://api.github.com/users/octocat html_url: https://github.com/octocat followers_url: https://api.github.com/users/octocat/followers following_url: https://api.github.com/users/octocat/following{/other_user} gists_url: https://api.github.com/users/octocat/gists{/gist_id} starred_url: https://api.github.com/users/octocat/starred{/owner}{/repo} subscriptions_url: https://api.github.com/users/octocat/subscriptions organizations_url: https://api.github.com/users/octocat/orgs repos_url: https://api.github.com/users/octocat/repos events_url: https://api.github.com/users/octocat/events{/privacy} received_events_url: https://api.github.com/users/octocat/received_events type: User site_admin: false release-asset-response-for-successful-upload: value: url: https://api.github.com/repos/octocat/Hello-World/releases/assets/1 browser_download_url: https://github.com/octocat/Hello-World/releases/download/v1.0.0/example.zip id: 1 node_id: MDEyOlJlbGVhc2VBc3NldDE= name: example.zip label: short description state: uploaded content_type: application/zip size: 1024 download_count: 42 created_at: '2013-02-27T19:35:32Z' updated_at: '2013-02-27T19:35:32Z' uploader: login: octocat id: 1 node_id: MDQ6VXNlcjE= avatar_url: https://github.com/images/error/octocat_happy.gif gravatar_id: '' url: https://api.github.com/users/octocat html_url: https://github.com/octocat followers_url: https://api.github.com/users/octocat/followers following_url: https://api.github.com/users/octocat/following{/other_user} gists_url: https://api.github.com/users/octocat/gists{/gist_id} starred_url: https://api.github.com/users/octocat/starred{/owner}{/repo} subscriptions_url: https://api.github.com/users/octocat/subscriptions organizations_url: https://api.github.com/users/octocat/orgs repos_url: https://api.github.com/users/octocat/repos events_url: https://api.github.com/users/octocat/events{/privacy} received_events_url: https://api.github.com/users/octocat/received_events type: User site_admin: false simple-user-items-default-response: summary: Default response value: - login: octocat id: 1 node_id: MDQ6VXNlcjE= avatar_url: https://github.com/images/error/octocat_happy.gif gravatar_id: '' url: https://api.github.com/users/octocat html_url: https://github.com/octocat followers_url: https://api.github.com/users/octocat/followers following_url: https://api.github.com/users/octocat/following{/other_user} gists_url: https://api.github.com/users/octocat/gists{/gist_id} starred_url: https://api.github.com/users/octocat/starred{/owner}{/repo} subscriptions_url: https://api.github.com/users/octocat/subscriptions organizations_url: https://api.github.com/users/octocat/orgs repos_url: https://api.github.com/users/octocat/repos events_url: https://api.github.com/users/octocat/events{/privacy} received_events_url: https://api.github.com/users/octocat/received_events type: User site_admin: false stargazer-items-alternative-response-with-star-creation-timestamps: summary: Alternative response with star creation timestamps value: - starred_at: '2011-01-16T19:06:43Z' user: login: octocat id: 1 node_id: MDQ6VXNlcjE= avatar_url: https://github.com/images/error/octocat_happy.gif gravatar_id: '' url: https://api.github.com/users/octocat html_url: https://github.com/octocat followers_url: https://api.github.com/users/octocat/followers following_url: https://api.github.com/users/octocat/following{/other_user} gists_url: https://api.github.com/users/octocat/gists{/gist_id} starred_url: https://api.github.com/users/octocat/starred{/owner}{/repo} subscriptions_url: https://api.github.com/users/octocat/subscriptions organizations_url: https://api.github.com/users/octocat/orgs repos_url: https://api.github.com/users/octocat/repos events_url: https://api.github.com/users/octocat/events{/privacy} received_events_url: https://api.github.com/users/octocat/received_events type: User site_admin: false code-frequency-stat-items: value: - - 1302998400 - 1124 - -435 commit-activity-items: value: - days: - 0 - 3 - 26 - 20 - 39 - 1 - 0 total: 89 week: 1336280400 contributor-activity-items: value: - author: login: octocat id: 1 node_id: MDQ6VXNlcjE= avatar_url: https://github.com/images/error/octocat_happy.gif gravatar_id: '' url: https://api.github.com/users/octocat html_url: https://github.com/octocat followers_url: https://api.github.com/users/octocat/followers following_url: https://api.github.com/users/octocat/following{/other_user} gists_url: https://api.github.com/users/octocat/gists{/gist_id} starred_url: https://api.github.com/users/octocat/starred{/owner}{/repo} subscriptions_url: https://api.github.com/users/octocat/subscriptions organizations_url: https://api.github.com/users/octocat/orgs repos_url: https://api.github.com/users/octocat/repos events_url: https://api.github.com/users/octocat/events{/privacy} received_events_url: https://api.github.com/users/octocat/received_events type: User site_admin: false total: 135 weeks: - w: 1367712000 a: 6898 d: 77 c: 10 participation-stats: value: all: - 11 - 21 - 15 - 2 - 8 - 1 - 8 - 23 - 17 - 21 - 11 - 10 - 33 - 91 - 38 - 34 - 22 - 23 - 32 - 3 - 43 - 87 - 71 - 18 - 13 - 5 - 13 - 16 - 66 - 27 - 12 - 45 - 110 - 117 - 13 - 8 - 18 - 9 - 19 - 26 - 39 - 12 - 20 - 31 - 46 - 91 - 45 - 10 - 24 - 9 - 29 - 7 owner: - 3 - 2 - 3 - 0 - 2 - 0 - 5 - 14 - 7 - 9 - 1 - 5 - 0 - 48 - 19 - 2 - 0 - 1 - 10 - 2 - 23 - 40 - 35 - 8 - 8 - 2 - 10 - 6 - 30 - 0 - 2 - 9 - 53 - 104 - 3 - 3 - 10 - 4 - 7 - 11 - 21 - 4 - 4 - 22 - 26 - 63 - 11 - 2 - 14 - 1 - 10 - 3 code-frequency-stat-items-2: value: - - 0 - 0 - 5 - - 0 - 1 - 43 - - 0 - 2 - 21 status: value: url: https://api.github.com/repos/octocat/Hello-World/statuses/6dcb09b5b57875f334f61aebed695e2e4193db5e avatar_url: https://github.com/images/error/hubot_happy.gif id: 1 node_id: MDY6U3RhdHVzMQ== state: success description: Build has completed successfully target_url: https://ci.example.com/1000/output context: continuous-integration/jenkins created_at: '2012-07-20T01:19:13Z' updated_at: '2012-07-20T01:19:13Z' creator: login: octocat id: 1 node_id: MDQ6VXNlcjE= avatar_url: https://github.com/images/error/octocat_happy.gif gravatar_id: '' url: https://api.github.com/users/octocat html_url: https://github.com/octocat followers_url: https://api.github.com/users/octocat/followers following_url: https://api.github.com/users/octocat/following{/other_user} gists_url: https://api.github.com/users/octocat/gists{/gist_id} starred_url: https://api.github.com/users/octocat/starred{/owner}{/repo} subscriptions_url: https://api.github.com/users/octocat/subscriptions organizations_url: https://api.github.com/users/octocat/orgs repos_url: https://api.github.com/users/octocat/repos events_url: https://api.github.com/users/octocat/events{/privacy} received_events_url: https://api.github.com/users/octocat/received_events type: User site_admin: false repository-subscription-response-if-you-subscribe-to-the-repository: value: subscribed: true ignored: false reason: created_at: '2012-10-06T21:34:12Z' url: https://api.github.com/repos/octocat/example/subscription repository_url: https://api.github.com/repos/octocat/example repository-subscription: value: subscribed: true ignored: false reason: created_at: '2012-10-06T21:34:12Z' url: https://api.github.com/repos/octocat/example/subscription repository_url: https://api.github.com/repos/octocat/example tag-items: value: - name: v0.1 commit: sha: c5b97d5ae6c19d5c5df71a34c7fbeeda2479ccbc url: https://api.github.com/repos/octocat/Hello-World/commits/c5b97d5ae6c19d5c5df71a34c7fbeeda2479ccbc zipball_url: https://github.com/octocat/Hello-World/zipball/v0.1 tarball_url: https://github.com/octocat/Hello-World/tarball/v0.1 node_id: MDQ6VXNlcjE= topic: value: names: - octocat - atom - electron - api minimal-repository: value: id: 1296269 node_id: MDEwOlJlcG9zaXRvcnkxMjk2MjY5 name: Hello-World full_name: octocat/Hello-World owner: login: octocat id: 1 node_id: MDQ6VXNlcjE= avatar_url: https://github.com/images/error/octocat_happy.gif gravatar_id: '' url: https://api.github.com/users/octocat html_url: https://github.com/octocat followers_url: https://api.github.com/users/octocat/followers following_url: https://api.github.com/users/octocat/following{/other_user} gists_url: https://api.github.com/users/octocat/gists{/gist_id} starred_url: https://api.github.com/users/octocat/starred{/owner}{/repo} subscriptions_url: https://api.github.com/users/octocat/subscriptions organizations_url: https://api.github.com/users/octocat/orgs repos_url: https://api.github.com/users/octocat/repos events_url: https://api.github.com/users/octocat/events{/privacy} received_events_url: https://api.github.com/users/octocat/received_events type: User site_admin: false private: false html_url: https://github.com/octocat/Hello-World description: This your first repo! fork: false url: https://api.github.com/repos/octocat/Hello-World archive_url: https://api.github.com/repos/octocat/Hello-World/{archive_format}{/ref} assignees_url: https://api.github.com/repos/octocat/Hello-World/assignees{/user} blobs_url: https://api.github.com/repos/octocat/Hello-World/git/blobs{/sha} branches_url: https://api.github.com/repos/octocat/Hello-World/branches{/branch} collaborators_url: https://api.github.com/repos/octocat/Hello-World/collaborators{/collaborator} comments_url: https://api.github.com/repos/octocat/Hello-World/comments{/number} commits_url: https://api.github.com/repos/octocat/Hello-World/commits{/sha} compare_url: https://api.github.com/repos/octocat/Hello-World/compare/{base}...{head} contents_url: https://api.github.com/repos/octocat/Hello-World/contents/{+path} contributors_url: https://api.github.com/repos/octocat/Hello-World/contributors deployments_url: https://api.github.com/repos/octocat/Hello-World/deployments downloads_url: https://api.github.com/repos/octocat/Hello-World/downloads events_url: https://api.github.com/repos/octocat/Hello-World/events forks_url: https://api.github.com/repos/octocat/Hello-World/forks git_commits_url: https://api.github.com/repos/octocat/Hello-World/git/commits{/sha} git_refs_url: https://api.github.com/repos/octocat/Hello-World/git/refs{/sha} git_tags_url: https://api.github.com/repos/octocat/Hello-World/git/tags{/sha} git_url: git:github.com/octocat/Hello-World.git issue_comment_url: https://api.github.com/repos/octocat/Hello-World/issues/comments{/number} issue_events_url: https://api.github.com/repos/octocat/Hello-World/issues/events{/number} issues_url: https://api.github.com/repos/octocat/Hello-World/issues{/number} keys_url: https://api.github.com/repos/octocat/Hello-World/keys{/key_id} labels_url: https://api.github.com/repos/octocat/Hello-World/labels{/name} languages_url: https://api.github.com/repos/octocat/Hello-World/languages merges_url: https://api.github.com/repos/octocat/Hello-World/merges milestones_url: https://api.github.com/repos/octocat/Hello-World/milestones{/number} notifications_url: https://api.github.com/repos/octocat/Hello-World/notifications{?since,all,participating} pulls_url: https://api.github.com/repos/octocat/Hello-World/pulls{/number} releases_url: https://api.github.com/repos/octocat/Hello-World/releases{/id} ssh_url: git@github.com:octocat/Hello-World.git stargazers_url: https://api.github.com/repos/octocat/Hello-World/stargazers statuses_url: https://api.github.com/repos/octocat/Hello-World/statuses/{sha} subscribers_url: https://api.github.com/repos/octocat/Hello-World/subscribers subscription_url: https://api.github.com/repos/octocat/Hello-World/subscription tags_url: https://api.github.com/repos/octocat/Hello-World/tags teams_url: https://api.github.com/repos/octocat/Hello-World/teams trees_url: https://api.github.com/repos/octocat/Hello-World/git/trees{/sha} clone_url: https://github.com/octocat/Hello-World.git mirror_url: git:git.example.com/octocat/Hello-World hooks_url: https://api.github.com/repos/octocat/Hello-World/hooks svn_url: https://svn.github.com/octocat/Hello-World homepage: https://github.com forks_count: 9 stargazers_count: 80 watchers_count: 80 size: 108 default_branch: master open_issues_count: 0 is_template: false topics: - octocat - atom - electron - api has_issues: true has_projects: true has_wiki: true has_pages: false has_downloads: true archived: false disabled: false visibility: public pushed_at: '2011-01-26T19:06:43Z' created_at: '2011-01-26T19:01:12Z' updated_at: '2011-01-26T19:14:43Z' permissions: admin: false push: false pull: true template_repository: id: 1296269 node_id: MDEwOlJlcG9zaXRvcnkxMjk2MjY5 name: Hello-World-Template full_name: octocat/Hello-World-Template owner: login: octocat id: 1 node_id: MDQ6VXNlcjE= avatar_url: https://github.com/images/error/octocat_happy.gif gravatar_id: '' url: https://api.github.com/users/octocat html_url: https://github.com/octocat followers_url: https://api.github.com/users/octocat/followers following_url: https://api.github.com/users/octocat/following{/other_user} gists_url: https://api.github.com/users/octocat/gists{/gist_id} starred_url: https://api.github.com/users/octocat/starred{/owner}{/repo} subscriptions_url: https://api.github.com/users/octocat/subscriptions organizations_url: https://api.github.com/users/octocat/orgs repos_url: https://api.github.com/users/octocat/repos events_url: https://api.github.com/users/octocat/events{/privacy} received_events_url: https://api.github.com/users/octocat/received_events type: User site_admin: false private: false html_url: https://github.com/octocat/Hello-World-Template description: This your first repo! fork: false url: https://api.github.com/repos/octocat/Hello-World-Template archive_url: https://api.github.com/repos/octocat/Hello-World-Template/{archive_format}{/ref} assignees_url: https://api.github.com/repos/octocat/Hello-World-Template/assignees{/user} blobs_url: https://api.github.com/repos/octocat/Hello-World-Template/git/blobs{/sha} branches_url: https://api.github.com/repos/octocat/Hello-World-Template/branches{/branch} collaborators_url: https://api.github.com/repos/octocat/Hello-World-Template/collaborators{/collaborator} comments_url: https://api.github.com/repos/octocat/Hello-World-Template/comments{/number} commits_url: https://api.github.com/repos/octocat/Hello-World-Template/commits{/sha} compare_url: https://api.github.com/repos/octocat/Hello-World-Template/compare/{base}...{head} contents_url: https://api.github.com/repos/octocat/Hello-World-Template/contents/{+path} contributors_url: https://api.github.com/repos/octocat/Hello-World-Template/contributors deployments_url: https://api.github.com/repos/octocat/Hello-World-Template/deployments downloads_url: https://api.github.com/repos/octocat/Hello-World-Template/downloads events_url: https://api.github.com/repos/octocat/Hello-World-Template/events forks_url: https://api.github.com/repos/octocat/Hello-World-Template/forks git_commits_url: https://api.github.com/repos/octocat/Hello-World-Template/git/commits{/sha} git_refs_url: https://api.github.com/repos/octocat/Hello-World-Template/git/refs{/sha} git_tags_url: https://api.github.com/repos/octocat/Hello-World-Template/git/tags{/sha} git_url: git:github.com/octocat/Hello-World-Template.git issue_comment_url: https://api.github.com/repos/octocat/Hello-World-Template/issues/comments{/number} issue_events_url: https://api.github.com/repos/octocat/Hello-World-Template/issues/events{/number} issues_url: https://api.github.com/repos/octocat/Hello-World-Template/issues{/number} keys_url: https://api.github.com/repos/octocat/Hello-World-Template/keys{/key_id} labels_url: https://api.github.com/repos/octocat/Hello-World-Template/labels{/name} languages_url: https://api.github.com/repos/octocat/Hello-World-Template/languages merges_url: https://api.github.com/repos/octocat/Hello-World-Template/merges milestones_url: https://api.github.com/repos/octocat/Hello-World-Template/milestones{/number} notifications_url: https://api.github.com/repos/octocat/Hello-World-Template/notifications{?since,all,participating} pulls_url: https://api.github.com/repos/octocat/Hello-World-Template/pulls{/number} releases_url: https://api.github.com/repos/octocat/Hello-World-Template/releases{/id} ssh_url: git@github.com:octocat/Hello-World-Template.git stargazers_url: https://api.github.com/repos/octocat/Hello-World-Template/stargazers statuses_url: https://api.github.com/repos/octocat/Hello-World-Template/statuses/{sha} subscribers_url: https://api.github.com/repos/octocat/Hello-World-Template/subscribers subscription_url: https://api.github.com/repos/octocat/Hello-World-Template/subscription tags_url: https://api.github.com/repos/octocat/Hello-World-Template/tags teams_url: https://api.github.com/repos/octocat/Hello-World-Template/teams trees_url: https://api.github.com/repos/octocat/Hello-World-Template/git/trees{/sha} clone_url: https://github.com/octocat/Hello-World-Template.git mirror_url: git:git.example.com/octocat/Hello-World-Template hooks_url: https://api.github.com/repos/octocat/Hello-World-Template/hooks svn_url: https://svn.github.com/octocat/Hello-World-Template homepage: https://github.com forks: 9 forks_count: 9 stargazers_count: 80 watchers_count: 80 watchers: 80 size: 108 default_branch: master open_issues: 0 open_issues_count: 0 is_template: true license: key: mit name: MIT License url: https://api.github.com/licenses/mit spdx_id: MIT node_id: MDc6TGljZW5zZW1pdA== html_url: https://api.github.com/licenses/mit topics: - octocat - atom - electron - api has_issues: true has_projects: true has_wiki: true has_pages: false has_downloads: true archived: false disabled: false visibility: public pushed_at: '2011-01-26T19:06:43Z' created_at: '2011-01-26T19:01:12Z' updated_at: '2011-01-26T19:14:43Z' permissions: admin: false push: false pull: true allow_rebase_merge: true temp_clone_token: ABTLWHOULUVAXGTRYU7OC2876QJ2O allow_squash_merge: true delete_branch_on_merge: true allow_merge_commit: true allow_forking: true subscribers_count: 42 network_count: 0 repository-3: value: id: 1296269 node_id: MDEwOlJlcG9zaXRvcnkxMjk2MjY5 name: Hello-World full_name: octocat/Hello-World owner: login: octocat id: 1 node_id: MDQ6VXNlcjE= avatar_url: https://github.com/images/error/octocat_happy.gif gravatar_id: '' url: https://api.github.com/users/octocat html_url: https://github.com/octocat followers_url: https://api.github.com/users/octocat/followers following_url: https://api.github.com/users/octocat/following{/other_user} gists_url: https://api.github.com/users/octocat/gists{/gist_id} starred_url: https://api.github.com/users/octocat/starred{/owner}{/repo} subscriptions_url: https://api.github.com/users/octocat/subscriptions organizations_url: https://api.github.com/users/octocat/orgs repos_url: https://api.github.com/users/octocat/repos events_url: https://api.github.com/users/octocat/events{/privacy} received_events_url: https://api.github.com/users/octocat/received_events type: User site_admin: false private: false html_url: https://github.com/octocat/Hello-World description: This your first repo! fork: false url: https://api.github.com/repos/octocat/Hello-World archive_url: https://api.github.com/repos/octocat/Hello-World/{archive_format}{/ref} assignees_url: https://api.github.com/repos/octocat/Hello-World/assignees{/user} blobs_url: https://api.github.com/repos/octocat/Hello-World/git/blobs{/sha} branches_url: https://api.github.com/repos/octocat/Hello-World/branches{/branch} collaborators_url: https://api.github.com/repos/octocat/Hello-World/collaborators{/collaborator} comments_url: https://api.github.com/repos/octocat/Hello-World/comments{/number} commits_url: https://api.github.com/repos/octocat/Hello-World/commits{/sha} compare_url: https://api.github.com/repos/octocat/Hello-World/compare/{base}...{head} contents_url: https://api.github.com/repos/octocat/Hello-World/contents/{+path} contributors_url: https://api.github.com/repos/octocat/Hello-World/contributors deployments_url: https://api.github.com/repos/octocat/Hello-World/deployments downloads_url: https://api.github.com/repos/octocat/Hello-World/downloads events_url: https://api.github.com/repos/octocat/Hello-World/events forks_url: https://api.github.com/repos/octocat/Hello-World/forks git_commits_url: https://api.github.com/repos/octocat/Hello-World/git/commits{/sha} git_refs_url: https://api.github.com/repos/octocat/Hello-World/git/refs{/sha} git_tags_url: https://api.github.com/repos/octocat/Hello-World/git/tags{/sha} git_url: git:github.com/octocat/Hello-World.git issue_comment_url: https://api.github.com/repos/octocat/Hello-World/issues/comments{/number} issue_events_url: https://api.github.com/repos/octocat/Hello-World/issues/events{/number} issues_url: https://api.github.com/repos/octocat/Hello-World/issues{/number} keys_url: https://api.github.com/repos/octocat/Hello-World/keys{/key_id} labels_url: https://api.github.com/repos/octocat/Hello-World/labels{/name} languages_url: https://api.github.com/repos/octocat/Hello-World/languages merges_url: https://api.github.com/repos/octocat/Hello-World/merges milestones_url: https://api.github.com/repos/octocat/Hello-World/milestones{/number} notifications_url: https://api.github.com/repos/octocat/Hello-World/notifications{?since,all,participating} pulls_url: https://api.github.com/repos/octocat/Hello-World/pulls{/number} releases_url: https://api.github.com/repos/octocat/Hello-World/releases{/id} ssh_url: git@github.com:octocat/Hello-World.git stargazers_url: https://api.github.com/repos/octocat/Hello-World/stargazers statuses_url: https://api.github.com/repos/octocat/Hello-World/statuses/{sha} subscribers_url: https://api.github.com/repos/octocat/Hello-World/subscribers subscription_url: https://api.github.com/repos/octocat/Hello-World/subscription tags_url: https://api.github.com/repos/octocat/Hello-World/tags teams_url: https://api.github.com/repos/octocat/Hello-World/teams trees_url: https://api.github.com/repos/octocat/Hello-World/git/trees{/sha} clone_url: https://github.com/octocat/Hello-World.git mirror_url: git:git.example.com/octocat/Hello-World hooks_url: https://api.github.com/repos/octocat/Hello-World/hooks svn_url: https://svn.github.com/octocat/Hello-World homepage: https://github.com forks_count: 9 forks: 9 stargazers_count: 80 watchers_count: 80 watchers: 80 size: 108 default_branch: master open_issues_count: 0 open_issues: 0 is_template: false topics: - octocat - atom - electron - api has_issues: true has_projects: true has_wiki: true has_pages: false has_downloads: true archived: false disabled: false visibility: public pushed_at: '2011-01-26T19:06:43Z' created_at: '2011-01-26T19:01:12Z' updated_at: '2011-01-26T19:14:43Z' permissions: admin: false push: false pull: true allow_rebase_merge: true license: key: mit name: MIT License url: https://api.github.com/licenses/mit spdx_id: MIT node_id: MDc6TGljZW5zZW1pdA== html_url: https://github.com/licenses/mit template_repository: {} public-repository-items: value: - id: 1296269 node_id: MDEwOlJlcG9zaXRvcnkxMjk2MjY5 name: Hello-World full_name: octocat/Hello-World owner: login: octocat id: 1 node_id: MDQ6VXNlcjE= avatar_url: https://github.com/images/error/octocat_happy.gif gravatar_id: '' url: https://api.github.com/users/octocat html_url: https://github.com/octocat followers_url: https://api.github.com/users/octocat/followers following_url: https://api.github.com/users/octocat/following{/other_user} gists_url: https://api.github.com/users/octocat/gists{/gist_id} starred_url: https://api.github.com/users/octocat/starred{/owner}{/repo} subscriptions_url: https://api.github.com/users/octocat/subscriptions organizations_url: https://api.github.com/users/octocat/orgs repos_url: https://api.github.com/users/octocat/repos events_url: https://api.github.com/users/octocat/events{/privacy} received_events_url: https://api.github.com/users/octocat/received_events type: User site_admin: false private: false html_url: https://github.com/octocat/Hello-World description: This your first repo! fork: false url: https://api.github.com/repos/octocat/Hello-World archive_url: https://api.github.com/repos/octocat/Hello-World/{archive_format}{/ref} assignees_url: https://api.github.com/repos/octocat/Hello-World/assignees{/user} blobs_url: https://api.github.com/repos/octocat/Hello-World/git/blobs{/sha} branches_url: https://api.github.com/repos/octocat/Hello-World/branches{/branch} collaborators_url: https://api.github.com/repos/octocat/Hello-World/collaborators{/collaborator} comments_url: https://api.github.com/repos/octocat/Hello-World/comments{/number} commits_url: https://api.github.com/repos/octocat/Hello-World/commits{/sha} compare_url: https://api.github.com/repos/octocat/Hello-World/compare/{base}...{head} contents_url: https://api.github.com/repos/octocat/Hello-World/contents/{+path} contributors_url: https://api.github.com/repos/octocat/Hello-World/contributors deployments_url: https://api.github.com/repos/octocat/Hello-World/deployments downloads_url: https://api.github.com/repos/octocat/Hello-World/downloads events_url: https://api.github.com/repos/octocat/Hello-World/events forks_url: https://api.github.com/repos/octocat/Hello-World/forks git_commits_url: https://api.github.com/repos/octocat/Hello-World/git/commits{/sha} git_refs_url: https://api.github.com/repos/octocat/Hello-World/git/refs{/sha} git_tags_url: https://api.github.com/repos/octocat/Hello-World/git/tags{/sha} git_url: git:github.com/octocat/Hello-World.git issue_comment_url: https://api.github.com/repos/octocat/Hello-World/issues/comments{/number} issue_events_url: https://api.github.com/repos/octocat/Hello-World/issues/events{/number} issues_url: https://api.github.com/repos/octocat/Hello-World/issues{/number} keys_url: https://api.github.com/repos/octocat/Hello-World/keys{/key_id} labels_url: https://api.github.com/repos/octocat/Hello-World/labels{/name} languages_url: https://api.github.com/repos/octocat/Hello-World/languages merges_url: https://api.github.com/repos/octocat/Hello-World/merges milestones_url: https://api.github.com/repos/octocat/Hello-World/milestones{/number} notifications_url: https://api.github.com/repos/octocat/Hello-World/notifications{?since,all,participating} pulls_url: https://api.github.com/repos/octocat/Hello-World/pulls{/number} releases_url: https://api.github.com/repos/octocat/Hello-World/releases{/id} ssh_url: git@github.com:octocat/Hello-World.git stargazers_url: https://api.github.com/repos/octocat/Hello-World/stargazers statuses_url: https://api.github.com/repos/octocat/Hello-World/statuses/{sha} subscribers_url: https://api.github.com/repos/octocat/Hello-World/subscribers subscription_url: https://api.github.com/repos/octocat/Hello-World/subscription tags_url: https://api.github.com/repos/octocat/Hello-World/tags teams_url: https://api.github.com/repos/octocat/Hello-World/teams trees_url: https://api.github.com/repos/octocat/Hello-World/git/trees{/sha} hooks_url: http://api.github.com/repos/octocat/Hello-World/hooks code-search-result-item-paginated: value: total_count: 7 incomplete_results: false items: - name: classes.js path: src/attributes/classes.js sha: d7212f9dee2dcc18f084d7df8f417b80846ded5a url: https://api.github.com/repositories/167174/contents/src/attributes/classes.js?ref=825ac3773694e0cd23ee74895fd5aeb535b27da4 git_url: https://api.github.com/repositories/167174/git/blobs/d7212f9dee2dcc18f084d7df8f417b80846ded5a html_url: https://github.com/jquery/jquery/blob/825ac3773694e0cd23ee74895fd5aeb535b27da4/src/attributes/classes.js repository: id: 167174 node_id: MDEwOlJlcG9zaXRvcnkxNjcxNzQ= name: jquery full_name: jquery/jquery owner: login: jquery id: 70142 node_id: MDQ6VXNlcjcwMTQy avatar_url: https://0.gravatar.com/avatar/6906f317a4733f4379b06c32229ef02f?d=https%3A%2F%2Fidenticons.github.com%2Ff426f04f2f9813718fb806b30e0093de.png gravatar_id: '' url: https://api.github.com/users/jquery html_url: https://github.com/jquery followers_url: https://api.github.com/users/jquery/followers following_url: https://api.github.com/users/jquery/following{/other_user} gists_url: https://api.github.com/users/jquery/gists{/gist_id} starred_url: https://api.github.com/users/jquery/starred{/owner}{/repo} subscriptions_url: https://api.github.com/users/jquery/subscriptions organizations_url: https://api.github.com/users/jquery/orgs repos_url: https://api.github.com/users/jquery/repos events_url: https://api.github.com/users/jquery/events{/privacy} received_events_url: https://api.github.com/users/jquery/received_events type: Organization site_admin: false private: false html_url: https://github.com/jquery/jquery description: jQuery JavaScript Library fork: false url: https://api.github.com/repos/jquery/jquery forks_url: https://api.github.com/repos/jquery/jquery/forks keys_url: https://api.github.com/repos/jquery/jquery/keys{/key_id} collaborators_url: https://api.github.com/repos/jquery/jquery/collaborators{/collaborator} teams_url: https://api.github.com/repos/jquery/jquery/teams hooks_url: https://api.github.com/repos/jquery/jquery/hooks issue_events_url: https://api.github.com/repos/jquery/jquery/issues/events{/number} events_url: https://api.github.com/repos/jquery/jquery/events assignees_url: https://api.github.com/repos/jquery/jquery/assignees{/user} branches_url: https://api.github.com/repos/jquery/jquery/branches{/branch} tags_url: https://api.github.com/repos/jquery/jquery/tags blobs_url: https://api.github.com/repos/jquery/jquery/git/blobs{/sha} git_tags_url: https://api.github.com/repos/jquery/jquery/git/tags{/sha} git_refs_url: https://api.github.com/repos/jquery/jquery/git/refs{/sha} trees_url: https://api.github.com/repos/jquery/jquery/git/trees{/sha} statuses_url: https://api.github.com/repos/jquery/jquery/statuses/{sha} languages_url: https://api.github.com/repos/jquery/jquery/languages stargazers_url: https://api.github.com/repos/jquery/jquery/stargazers contributors_url: https://api.github.com/repos/jquery/jquery/contributors subscribers_url: https://api.github.com/repos/jquery/jquery/subscribers subscription_url: https://api.github.com/repos/jquery/jquery/subscription commits_url: https://api.github.com/repos/jquery/jquery/commits{/sha} git_commits_url: https://api.github.com/repos/jquery/jquery/git/commits{/sha} comments_url: https://api.github.com/repos/jquery/jquery/comments{/number} issue_comment_url: https://api.github.com/repos/jquery/jquery/issues/comments/{number} contents_url: https://api.github.com/repos/jquery/jquery/contents/{+path} compare_url: https://api.github.com/repos/jquery/jquery/compare/{base}...{head} merges_url: https://api.github.com/repos/jquery/jquery/merges archive_url: https://api.github.com/repos/jquery/jquery/{archive_format}{/ref} downloads_url: https://api.github.com/repos/jquery/jquery/downloads issues_url: https://api.github.com/repos/jquery/jquery/issues{/number} pulls_url: https://api.github.com/repos/jquery/jquery/pulls{/number} milestones_url: https://api.github.com/repos/jquery/jquery/milestones{/number} notifications_url: https://api.github.com/repos/jquery/jquery/notifications{?since,all,participating} labels_url: https://api.github.com/repos/jquery/jquery/labels{/name} deployments_url: http://api.github.com/repos/octocat/Hello-World/deployments releases_url: http://api.github.com/repos/octocat/Hello-World/releases{/id} score: 1 commit-search-result-item-paginated: value: total_count: 1 incomplete_results: false items: - url: https://api.github.com/repos/octocat/Spoon-Knife/commits/bb4cc8d3b2e14b3af5df699876dd4ff3acd00b7f sha: bb4cc8d3b2e14b3af5df699876dd4ff3acd00b7f html_url: https://github.com/octocat/Spoon-Knife/commit/bb4cc8d3b2e14b3af5df699876dd4ff3acd00b7f comments_url: https://api.github.com/repos/octocat/Spoon-Knife/commits/bb4cc8d3b2e14b3af5df699876dd4ff3acd00b7f/comments commit: url: https://api.github.com/repos/octocat/Spoon-Knife/git/commits/bb4cc8d3b2e14b3af5df699876dd4ff3acd00b7f author: date: '2014-02-04T14:38:36-08:00' name: The Octocat email: octocat@nowhere.com committer: date: '2014-02-12T15:18:55-08:00' name: The Octocat email: octocat@nowhere.com message: Create styles.css and updated README tree: url: https://api.github.com/repos/octocat/Spoon-Knife/git/trees/a639e96f9038797fba6e0469f94a4b0cc459fa68 sha: a639e96f9038797fba6e0469f94a4b0cc459fa68 comment_count: 8 author: login: octocat id: 583231 node_id: MDQ6VXNlcjU4MzIzMQ== avatar_url: https://avatars.githubusercontent.com/u/583231?v=3 gravatar_id: '' url: https://api.github.com/users/octocat html_url: https://github.com/octocat followers_url: https://api.github.com/users/octocat/followers following_url: https://api.github.com/users/octocat/following{/other_user} gists_url: https://api.github.com/users/octocat/gists{/gist_id} starred_url: https://api.github.com/users/octocat/starred{/owner}{/repo} subscriptions_url: https://api.github.com/users/octocat/subscriptions organizations_url: https://api.github.com/users/octocat/orgs repos_url: https://api.github.com/users/octocat/repos events_url: https://api.github.com/users/octocat/events{/privacy} received_events_url: https://api.github.com/users/octocat/received_events type: User site_admin: false committer: {} parents: - url: https://api.github.com/repos/octocat/Spoon-Knife/commits/a30c19e3f13765a3b48829788bc1cb8b4e95cee4 html_url: https://github.com/octocat/Spoon-Knife/commit/a30c19e3f13765a3b48829788bc1cb8b4e95cee4 sha: a30c19e3f13765a3b48829788bc1cb8b4e95cee4 repository: id: 1300192 node_id: MDEwOlJlcG9zaXRvcnkxMzAwMTky name: Spoon-Knife full_name: octocat/Spoon-Knife owner: login: octocat id: 583231 node_id: MDQ6VXNlcjU4MzIzMQ== avatar_url: https://avatars.githubusercontent.com/u/583231?v=3 gravatar_id: '' url: https://api.github.com/users/octocat html_url: https://github.com/octocat followers_url: https://api.github.com/users/octocat/followers following_url: https://api.github.com/users/octocat/following{/other_user} gists_url: https://api.github.com/users/octocat/gists{/gist_id} starred_url: https://api.github.com/users/octocat/starred{/owner}{/repo} subscriptions_url: https://api.github.com/users/octocat/subscriptions organizations_url: https://api.github.com/users/octocat/orgs repos_url: https://api.github.com/users/octocat/repos events_url: https://api.github.com/users/octocat/events{/privacy} received_events_url: https://api.github.com/users/octocat/received_events type: User site_admin: false private: false html_url: https://github.com/octocat/Spoon-Knife description: This repo is for demonstration purposes only. fork: false url: https://api.github.com/repos/octocat/Spoon-Knife forks_url: https://api.github.com/repos/octocat/Spoon-Knife/forks keys_url: https://api.github.com/repos/octocat/Spoon-Knife/keys{/key_id} collaborators_url: https://api.github.com/repos/octocat/Spoon-Knife/collaborators{/collaborator} teams_url: https://api.github.com/repos/octocat/Spoon-Knife/teams hooks_url: https://api.github.com/repos/octocat/Spoon-Knife/hooks issue_events_url: https://api.github.com/repos/octocat/Spoon-Knife/issues/events{/number} events_url: https://api.github.com/repos/octocat/Spoon-Knife/events assignees_url: https://api.github.com/repos/octocat/Spoon-Knife/assignees{/user} branches_url: https://api.github.com/repos/octocat/Spoon-Knife/branches{/branch} tags_url: https://api.github.com/repos/octocat/Spoon-Knife/tags blobs_url: https://api.github.com/repos/octocat/Spoon-Knife/git/blobs{/sha} git_tags_url: https://api.github.com/repos/octocat/Spoon-Knife/git/tags{/sha} git_refs_url: https://api.github.com/repos/octocat/Spoon-Knife/git/refs{/sha} trees_url: https://api.github.com/repos/octocat/Spoon-Knife/git/trees{/sha} statuses_url: https://api.github.com/repos/octocat/Spoon-Knife/statuses/{sha} languages_url: https://api.github.com/repos/octocat/Spoon-Knife/languages stargazers_url: https://api.github.com/repos/octocat/Spoon-Knife/stargazers contributors_url: https://api.github.com/repos/octocat/Spoon-Knife/contributors subscribers_url: https://api.github.com/repos/octocat/Spoon-Knife/subscribers subscription_url: https://api.github.com/repos/octocat/Spoon-Knife/subscription commits_url: https://api.github.com/repos/octocat/Spoon-Knife/commits{/sha} git_commits_url: https://api.github.com/repos/octocat/Spoon-Knife/git/commits{/sha} comments_url: https://api.github.com/repos/octocat/Spoon-Knife/comments{/number} issue_comment_url: https://api.github.com/repos/octocat/Spoon-Knife/issues/comments{/number} contents_url: https://api.github.com/repos/octocat/Spoon-Knife/contents/{+path} compare_url: https://api.github.com/repos/octocat/Spoon-Knife/compare/{base}...{head} merges_url: https://api.github.com/repos/octocat/Spoon-Knife/merges archive_url: https://api.github.com/repos/octocat/Spoon-Knife/{archive_format}{/ref} downloads_url: https://api.github.com/repos/octocat/Spoon-Knife/downloads issues_url: https://api.github.com/repos/octocat/Spoon-Knife/issues{/number} pulls_url: https://api.github.com/repos/octocat/Spoon-Knife/pulls{/number} milestones_url: https://api.github.com/repos/octocat/Spoon-Knife/milestones{/number} notifications_url: https://api.github.com/repos/octocat/Spoon-Knife/notifications{?since,all,participating} labels_url: https://api.github.com/repos/octocat/Spoon-Knife/labels{/name} releases_url: https://api.github.com/repos/octocat/Spoon-Knife/releases{/id} deployments_url: https://api.github.com/repos/octocat/Spoon-Knife/deployments score: 1 node_id: MDQ6VXNlcjU4MzIzMQ== issue-search-result-item-paginated: value: total_count: 280 incomplete_results: false items: - url: https://api.github.com/repos/batterseapower/pinyin-toolkit/issues/132 repository_url: https://api.github.com/repos/batterseapower/pinyin-toolkit labels_url: https://api.github.com/repos/batterseapower/pinyin-toolkit/issues/132/labels{/name} comments_url: https://api.github.com/repos/batterseapower/pinyin-toolkit/issues/132/comments events_url: https://api.github.com/repos/batterseapower/pinyin-toolkit/issues/132/events html_url: https://github.com/batterseapower/pinyin-toolkit/issues/132 id: 35802 node_id: MDU6SXNzdWUzNTgwMg== number: 132 title: Line Number Indexes Beyond 20 Not Displayed user: login: Nick3C id: 90254 node_id: MDQ6VXNlcjkwMjU0 avatar_url: https://secure.gravatar.com/avatar/934442aadfe3b2f4630510de416c5718?d=https://a248.e.akamai.net/assets.github.com%2Fimages%2Fgravatars%2Fgravatar-user-420.png gravatar_id: '' url: https://api.github.com/users/Nick3C html_url: https://github.com/Nick3C followers_url: https://api.github.com/users/Nick3C/followers following_url: https://api.github.com/users/Nick3C/following{/other_user} gists_url: https://api.github.com/users/Nick3C/gists{/gist_id} starred_url: https://api.github.com/users/Nick3C/starred{/owner}{/repo} subscriptions_url: https://api.github.com/users/Nick3C/subscriptions organizations_url: https://api.github.com/users/Nick3C/orgs repos_url: https://api.github.com/users/Nick3C/repos events_url: https://api.github.com/users/Nick3C/events{/privacy} received_events_url: https://api.github.com/users/Nick3C/received_events type: User site_admin: true labels: - id: 4 node_id: MDU6TGFiZWw0 url: https://api.github.com/repos/batterseapower/pinyin-toolkit/labels/bug name: bug color: ff0000 state: open assignee: milestone: url: https://api.github.com/repos/octocat/Hello-World/milestones/1 html_url: https://github.com/octocat/Hello-World/milestones/v1.0 labels_url: https://api.github.com/repos/octocat/Hello-World/milestones/1/labels id: 1002604 node_id: MDk6TWlsZXN0b25lMTAwMjYwNA== number: 1 state: open title: v1.0 description: Tracking milestone for version 1.0 creator: login: octocat id: 1 node_id: MDQ6VXNlcjE= avatar_url: https://github.com/images/error/octocat_happy.gif gravatar_id: '' url: https://api.github.com/users/octocat html_url: https://github.com/octocat followers_url: https://api.github.com/users/octocat/followers following_url: https://api.github.com/users/octocat/following{/other_user} gists_url: https://api.github.com/users/octocat/gists{/gist_id} starred_url: https://api.github.com/users/octocat/starred{/owner}{/repo} subscriptions_url: https://api.github.com/users/octocat/subscriptions organizations_url: https://api.github.com/users/octocat/orgs repos_url: https://api.github.com/users/octocat/repos events_url: https://api.github.com/users/octocat/events{/privacy} received_events_url: https://api.github.com/users/octocat/received_events type: User site_admin: false open_issues: 4 closed_issues: 8 created_at: '2011-04-10T20:09:31Z' updated_at: '2014-03-03T18:58:10Z' closed_at: '2013-02-12T13:22:01Z' due_on: '2012-10-09T23:39:01Z' comments: 15 created_at: '2009-07-12T20:10:41Z' updated_at: '2009-07-19T09:23:43Z' closed_at: pull_request: url: https://api/github.com/repos/octocat/Hello-World/pull/1347 html_url: https://github.com/octocat/Hello-World/pull/1347 diff_url: https://github.com/octocat/Hello-World/pull/1347.diff patch_url: https://api.github.com/repos/octocat/Hello-World/pulls/1347 body: "..." score: 1 locked: true author_association: COLLABORATOR label-search-result-item-paginated: value: total_count: 2 incomplete_results: false items: - id: 418327088 node_id: MDU6TGFiZWw0MTgzMjcwODg= url: https://api.github.com/repos/octocat/linguist/labels/enhancement name: enhancement color: 84b6eb default: true description: New feature or request. score: 1 - id: 418327086 node_id: MDU6TGFiZWw0MTgzMjcwODY= url: https://api.github.com/repos/octocat/linguist/labels/bug name: bug color: ee0701 default: true description: Something isn't working. score: 1 repo-search-result-item-paginated: value: total_count: 40 incomplete_results: false items: - id: 3081286 node_id: MDEwOlJlcG9zaXRvcnkzMDgxMjg2 name: Tetris full_name: dtrupenn/Tetris owner: login: dtrupenn id: 872147 node_id: MDQ6VXNlcjg3MjE0Nw== avatar_url: https://secure.gravatar.com/avatar/e7956084e75f239de85d3a31bc172ace?d=https://a248.e.akamai.net/assets.github.com%2Fimages%2Fgravatars%2Fgravatar-user-420.png gravatar_id: '' url: https://api.github.com/users/dtrupenn received_events_url: https://api.github.com/users/dtrupenn/received_events type: User html_url: https://github.com/octocat followers_url: https://api.github.com/users/octocat/followers following_url: https://api.github.com/users/octocat/following{/other_user} gists_url: https://api.github.com/users/octocat/gists{/gist_id} starred_url: https://api.github.com/users/octocat/starred{/owner}{/repo} subscriptions_url: https://api.github.com/users/octocat/subscriptions organizations_url: https://api.github.com/users/octocat/orgs repos_url: https://api.github.com/users/octocat/repos events_url: https://api.github.com/users/octocat/events{/privacy} site_admin: true private: false html_url: https://github.com/dtrupenn/Tetris description: A C implementation of Tetris using Pennsim through LC4 fork: false url: https://api.github.com/repos/dtrupenn/Tetris created_at: '2012-01-01T00:31:50Z' updated_at: '2013-01-05T17:58:47Z' pushed_at: '2012-01-01T00:37:02Z' homepage: https://github.com size: 524 stargazers_count: 1 watchers_count: 1 language: Assembly forks_count: 0 open_issues_count: 0 master_branch: master default_branch: master score: 1 archive_url: https://api.github.com/repos/dtrupenn/Tetris/{archive_format}{/ref} assignees_url: https://api.github.com/repos/dtrupenn/Tetris/assignees{/user} blobs_url: https://api.github.com/repos/dtrupenn/Tetris/git/blobs{/sha} branches_url: https://api.github.com/repos/dtrupenn/Tetris/branches{/branch} collaborators_url: https://api.github.com/repos/dtrupenn/Tetris/collaborators{/collaborator} comments_url: https://api.github.com/repos/dtrupenn/Tetris/comments{/number} commits_url: https://api.github.com/repos/dtrupenn/Tetris/commits{/sha} compare_url: https://api.github.com/repos/dtrupenn/Tetris/compare/{base}...{head} contents_url: https://api.github.com/repos/dtrupenn/Tetris/contents/{+path} contributors_url: https://api.github.com/repos/dtrupenn/Tetris/contributors deployments_url: https://api.github.com/repos/dtrupenn/Tetris/deployments downloads_url: https://api.github.com/repos/dtrupenn/Tetris/downloads events_url: https://api.github.com/repos/dtrupenn/Tetris/events forks_url: https://api.github.com/repos/dtrupenn/Tetris/forks git_commits_url: https://api.github.com/repos/dtrupenn/Tetris/git/commits{/sha} git_refs_url: https://api.github.com/repos/dtrupenn/Tetris/git/refs{/sha} git_tags_url: https://api.github.com/repos/dtrupenn/Tetris/git/tags{/sha} git_url: git:github.com/dtrupenn/Tetris.git issue_comment_url: https://api.github.com/repos/dtrupenn/Tetris/issues/comments{/number} issue_events_url: https://api.github.com/repos/dtrupenn/Tetris/issues/events{/number} issues_url: https://api.github.com/repos/dtrupenn/Tetris/issues{/number} keys_url: https://api.github.com/repos/dtrupenn/Tetris/keys{/key_id} labels_url: https://api.github.com/repos/dtrupenn/Tetris/labels{/name} languages_url: https://api.github.com/repos/dtrupenn/Tetris/languages merges_url: https://api.github.com/repos/dtrupenn/Tetris/merges milestones_url: https://api.github.com/repos/dtrupenn/Tetris/milestones{/number} notifications_url: https://api.github.com/repos/dtrupenn/Tetris/notifications{?since,all,participating} pulls_url: https://api.github.com/repos/dtrupenn/Tetris/pulls{/number} releases_url: https://api.github.com/repos/dtrupenn/Tetris/releases{/id} ssh_url: git@github.com:dtrupenn/Tetris.git stargazers_url: https://api.github.com/repos/dtrupenn/Tetris/stargazers statuses_url: https://api.github.com/repos/dtrupenn/Tetris/statuses/{sha} subscribers_url: https://api.github.com/repos/dtrupenn/Tetris/subscribers subscription_url: https://api.github.com/repos/dtrupenn/Tetris/subscription tags_url: https://api.github.com/repos/dtrupenn/Tetris/tags teams_url: https://api.github.com/repos/dtrupenn/Tetris/teams trees_url: https://api.github.com/repos/dtrupenn/Tetris/git/trees{/sha} clone_url: https://github.com/dtrupenn/Tetris.git mirror_url: git:git.example.com/dtrupenn/Tetris hooks_url: https://api.github.com/repos/dtrupenn/Tetris/hooks svn_url: https://svn.github.com/dtrupenn/Tetris forks: 1 open_issues: 1 watchers: 1 has_issues: true has_projects: true has_pages: true has_wiki: true has_downloads: true archived: true disabled: true visibility: private license: key: mit name: MIT License url: https://api.github.com/licenses/mit spdx_id: MIT node_id: MDc6TGljZW5zZW1pdA== html_url: https://api.github.com/licenses/mit topic-search-result-item-paginated: value: total_count: 6 incomplete_results: false items: - name: ruby display_name: Ruby short_description: Ruby is a scripting language designed for simplified object-oriented programming. description: Ruby was developed by Yukihiro "Matz" Matsumoto in 1995 with the intent of having an easily readable programming language. It is integrated with the Rails framework to create dynamic web-applications. Ruby's syntax is similar to that of Perl and Python. created_by: Yukihiro Matsumoto released: December 21, 1995 created_at: '2016-11-28T22:03:59Z' updated_at: '2017-10-30T18:16:32Z' featured: true curated: true score: 1 - name: rails display_name: Rails short_description: Ruby on Rails (Rails) is a web application framework written in Ruby. description: Ruby on Rails (Rails) is a web application framework written in Ruby. It is meant to help simplify the building of complex websites. created_by: David Heinemeier Hansson released: December 13 2005 created_at: '2016-12-09T17:03:50Z' updated_at: '2017-10-30T16:20:19Z' featured: true curated: true score: 1 - name: python display_name: Python short_description: Python is a dynamically typed programming language. description: Python is a dynamically typed programming language designed by Guido Van Rossum. Much like the programming language Ruby, Python was designed to be easily read by programmers. Because of its large following and many libraries, Python can be implemented and used to do anything from webpages to scientific research. created_by: Guido van Rossum released: February 20, 1991 created_at: '2016-12-07T00:07:02Z' updated_at: '2017-10-27T22:45:43Z' featured: true curated: true score: 1 - name: jekyll display_name: Jekyll short_description: Jekyll is a simple, blog-aware static site generator. description: Jekyll is a blog-aware, site generator written in Ruby. It takes raw text files, runs it through a renderer and produces a publishable static website. created_by: Tom Preston-Werner released: '2008' created_at: '2016-12-16T21:53:08Z' updated_at: '2017-10-27T19:00:24Z' featured: true curated: true score: 1 - name: sass display_name: Sass short_description: Sass is a stable extension to classic CSS. description: Sass is a stylesheet language with a main implementation in Ruby. It is an extension of CSS that makes improvements to the old stylesheet format, such as being able to declare variables and using a cleaner nesting syntax. created_by: Hampton Catlin, Natalie Weizenbaum, Chris Eppstein released: November 28, 2006 created_at: '2016-12-16T21:53:45Z' updated_at: '2018-01-16T16:30:40Z' featured: true curated: true score: 1 - name: homebrew display_name: Homebrew short_description: Homebrew is a package manager for macOS. description: Homebrew is a package manager for Apple's macOS operating system. It simplifies the installation of software and is popular in the Ruby on Rails community. created_by: Max Howell released: '2009' created_at: '2016-12-17T20:30:44Z' updated_at: '2018-02-06T16:14:56Z' featured: true curated: true score: 1 user-search-result-item-paginated: value: total_count: 12 incomplete_results: false items: - login: mojombo id: 1 node_id: MDQ6VXNlcjE= avatar_url: https://secure.gravatar.com/avatar/25c7c18223fb42a4c6ae1c8db6f50f9b?d=https://a248.e.akamai.net/assets.github.com%2Fimages%2Fgravatars%2Fgravatar-user-420.png gravatar_id: '' url: https://api.github.com/users/mojombo html_url: https://github.com/mojombo followers_url: https://api.github.com/users/mojombo/followers subscriptions_url: https://api.github.com/users/mojombo/subscriptions organizations_url: https://api.github.com/users/mojombo/orgs repos_url: https://api.github.com/users/mojombo/repos received_events_url: https://api.github.com/users/mojombo/received_events type: User score: 1 following_url: https://api.github.com/users/mojombo/following{/other_user} gists_url: https://api.github.com/users/mojombo/gists{/gist_id} starred_url: https://api.github.com/users/mojombo/starred{/owner}{/repo} events_url: https://api.github.com/users/mojombo/events{/privacy} site_admin: true configuration-status: value: status: running progress: - status: DONE key: Appliance core components - status: DONE key: GitHub utilities - status: DONE key: GitHub applications - status: CONFIGURING key: GitHub services - status: PENDING key: Reloading appliance services maintenance-status: value: status: scheduled scheduled_time: Tuesday, January 22 at 15:34 -0800 connection_services: - name: git operations number: 0 - name: mysql queries number: 233 - name: resque jobs number: 54 enterprise-settings: value: enterprise: private_mode: false public_pages: false subdomain_isolation: true signup_enabled: false github_hostname: ghe.local identicons_host: dotcom http_proxy: auth_mode: default expire_sessions: false admin_password: configuration_id: 1401777404 configuration_run_count: 4 avatar: enabled: false uri: '' customer: name: GitHub email: stannis@themannis.biz uuid: af6cac80-e4e1-012e-d822-1231380e52e9 secret_key_data: | -----BEGIN PGP PRIVATE KEY BLOCK----- Version: GnuPG v1.4.10 (GNU/Linux) lQcYBE5TCgsBEACk4yHpUcapplebaumBMXYMiLF+nCQ0lxpx... -----END PGP PRIVATE KEY BLOCK----- public_key_data: | -----BEGIN PGP PUBLIC KEY BLOCK----- Version: GnuPG v1.4.10 (GNU/Linux) mI0ETqzZYgEEALSe6snowdenXyqvLfSQ34HWD6C7.... -----END PGP PUBLIC KEY BLOCK----- license: seats: 0 evaluation: false perpetual: false unlimited_seating: true support_key: ssh-rsa AAAAB3N.... ssh_allowed: true cluster_support: false expire_at: '2016-04-27T00:00:00-07:00' github_ssl: enabled: false cert: key: ldap: host: port: 0 base: [] uid: bind_dn: password: method: Plain search_strategy: detect user_groups: [] admin_group: virtual_attribute_enabled: false recursive_group_search: false posix_support: true user_sync_emails: false user_sync_keys: false user_sync_interval: 4 team_sync_interval: 4 sync_enabled: false reconciliation: user: org: profile: uid: uid name: mail: key: cas: url: saml: sso_url: certificate: certificate_path: issuer: idp_initiated_sso: false disable_admin_demote: false github_oauth: client_id: '12313412' client_secret: kj123131132 organization_name: Homestar Runners organization_team: homestarrunners/characters smtp: enabled: true address: smtp.example.com authentication: plain port: '1234' domain: blah username: foo user_name: mr_foo enable_starttls_auto: true password: bar discard-to-noreply-address: true support_address: enterprise@github.com support_address_type: email noreply_address: noreply@github.com ntp: primary_server: 0.pool.ntp.org secondary_server: 1.pool.ntp.org timezone: snmp: enabled: false community: '' syslog: enabled: false server: protocol_name: udp assets: pages: enabled: true collectd: enabled: false server: port: 0 encryption: username: password: mapping: enabled: true tileserver: basemap: company.map-qsz2zrvs token: load_balancer: run_list: - recipe[enterprise-configure] ssh-key-items: value: - key: ssh-rsa AAAAB3NzaC1yc2EAAAAB... pretty-print: ssh-rsa 01:14:0f:f2:0f:e2:fe:e8:f4:72:62:af:75:f7:1a:88:3e:04:92:64 - key: ssh-rsa AAAAB3NzaC1yc2EAAAAB... pretty-print: ssh-rsa 01:14:0f:f2:0f:e2:fe:e8:f4:72:62:af:75:f7:1a:88:3e:04:92:64 - key: ssh-rsa AAAAB3NzaC1yc2EAAAAB... pretty-print: ssh-rsa 01:14:0f:f2:0f:e2:fe:e8:f4:72:62:af:75:f7:1a:88:3e:04:92:64 team-repository-alternative-response-with-extra-repository-information: value: id: 1296269 node_id: MDEwOlJlcG9zaXRvcnkxMjk2MjY5 name: Hello-World full_name: octocat/Hello-World owner: login: octocat id: 1 node_id: MDQ6VXNlcjE= avatar_url: https://github.com/images/error/octocat_happy.gif gravatar_id: '' url: https://api.github.com/users/octocat html_url: https://github.com/octocat followers_url: https://api.github.com/users/octocat/followers following_url: https://api.github.com/users/octocat/following{/other_user} gists_url: https://api.github.com/users/octocat/gists{/gist_id} starred_url: https://api.github.com/users/octocat/starred{/owner}{/repo} subscriptions_url: https://api.github.com/users/octocat/subscriptions organizations_url: https://api.github.com/users/octocat/orgs repos_url: https://api.github.com/users/octocat/repos events_url: https://api.github.com/users/octocat/events{/privacy} received_events_url: https://api.github.com/users/octocat/received_events type: User site_admin: false private: false html_url: https://github.com/octocat/Hello-World description: This your first repo! fork: false url: https://api.github.com/repos/octocat/Hello-World archive_url: https://api.github.com/repos/octocat/Hello-World/{archive_format}{/ref} assignees_url: https://api.github.com/repos/octocat/Hello-World/assignees{/user} blobs_url: https://api.github.com/repos/octocat/Hello-World/git/blobs{/sha} branches_url: https://api.github.com/repos/octocat/Hello-World/branches{/branch} collaborators_url: https://api.github.com/repos/octocat/Hello-World/collaborators{/collaborator} comments_url: https://api.github.com/repos/octocat/Hello-World/comments{/number} commits_url: https://api.github.com/repos/octocat/Hello-World/commits{/sha} compare_url: https://api.github.com/repos/octocat/Hello-World/compare/{base}...{head} contents_url: https://api.github.com/repos/octocat/Hello-World/contents/{+path} contributors_url: https://api.github.com/repos/octocat/Hello-World/contributors deployments_url: https://api.github.com/repos/octocat/Hello-World/deployments downloads_url: https://api.github.com/repos/octocat/Hello-World/downloads events_url: https://api.github.com/repos/octocat/Hello-World/events forks_url: https://api.github.com/repos/octocat/Hello-World/forks git_commits_url: https://api.github.com/repos/octocat/Hello-World/git/commits{/sha} git_refs_url: https://api.github.com/repos/octocat/Hello-World/git/refs{/sha} git_tags_url: https://api.github.com/repos/octocat/Hello-World/git/tags{/sha} git_url: git:github.com/octocat/Hello-World.git issue_comment_url: https://api.github.com/repos/octocat/Hello-World/issues/comments{/number} issue_events_url: https://api.github.com/repos/octocat/Hello-World/issues/events{/number} issues_url: https://api.github.com/repos/octocat/Hello-World/issues{/number} keys_url: https://api.github.com/repos/octocat/Hello-World/keys{/key_id} labels_url: https://api.github.com/repos/octocat/Hello-World/labels{/name} languages_url: https://api.github.com/repos/octocat/Hello-World/languages merges_url: https://api.github.com/repos/octocat/Hello-World/merges milestones_url: https://api.github.com/repos/octocat/Hello-World/milestones{/number} notifications_url: https://api.github.com/repos/octocat/Hello-World/notifications{?since,all,participating} pulls_url: https://api.github.com/repos/octocat/Hello-World/pulls{/number} releases_url: https://api.github.com/repos/octocat/Hello-World/releases{/id} ssh_url: git@github.com:octocat/Hello-World.git stargazers_url: https://api.github.com/repos/octocat/Hello-World/stargazers statuses_url: https://api.github.com/repos/octocat/Hello-World/statuses/{sha} subscribers_url: https://api.github.com/repos/octocat/Hello-World/subscribers subscription_url: https://api.github.com/repos/octocat/Hello-World/subscription tags_url: https://api.github.com/repos/octocat/Hello-World/tags teams_url: https://api.github.com/repos/octocat/Hello-World/teams trees_url: https://api.github.com/repos/octocat/Hello-World/git/trees{/sha} clone_url: https://github.com/octocat/Hello-World.git mirror_url: git:git.example.com/octocat/Hello-World hooks_url: https://api.github.com/repos/octocat/Hello-World/hooks svn_url: https://svn.github.com/octocat/Hello-World homepage: https://github.com forks_count: 9 stargazers_count: 80 watchers_count: 80 size: 108 default_branch: master open_issues_count: 0 is_template: false topics: - octocat - atom - electron - api has_issues: true has_projects: true has_wiki: true has_pages: false has_downloads: true archived: false disabled: false visibility: public pushed_at: '2011-01-26T19:06:43Z' created_at: '2011-01-26T19:01:12Z' updated_at: '2011-01-26T19:14:43Z' permissions: admin: false maintain: false push: false triage: false pull: true allow_rebase_merge: true template_repository: id: 1296269 node_id: MDEwOlJlcG9zaXRvcnkxMjk2MjY5 name: Hello-World-Template full_name: octocat/Hello-World-Template owner: login: octocat id: 1 node_id: MDQ6VXNlcjE= avatar_url: https://github.com/images/error/octocat_happy.gif gravatar_id: '' url: https://api.github.com/users/octocat html_url: https://github.com/octocat followers_url: https://api.github.com/users/octocat/followers following_url: https://api.github.com/users/octocat/following{/other_user} gists_url: https://api.github.com/users/octocat/gists{/gist_id} starred_url: https://api.github.com/users/octocat/starred{/owner}{/repo} subscriptions_url: https://api.github.com/users/octocat/subscriptions organizations_url: https://api.github.com/users/octocat/orgs repos_url: https://api.github.com/users/octocat/repos events_url: https://api.github.com/users/octocat/events{/privacy} received_events_url: https://api.github.com/users/octocat/received_events type: User site_admin: false private: false html_url: https://github.com/octocat/Hello-World-Template description: This your first repo! fork: false url: https://api.github.com/repos/octocat/Hello-World-Template archive_url: https://api.github.com/repos/octocat/Hello-World-Template/{archive_format}{/ref} assignees_url: https://api.github.com/repos/octocat/Hello-World-Template/assignees{/user} blobs_url: https://api.github.com/repos/octocat/Hello-World-Template/git/blobs{/sha} branches_url: https://api.github.com/repos/octocat/Hello-World-Template/branches{/branch} collaborators_url: https://api.github.com/repos/octocat/Hello-World-Template/collaborators{/collaborator} comments_url: https://api.github.com/repos/octocat/Hello-World-Template/comments{/number} commits_url: https://api.github.com/repos/octocat/Hello-World-Template/commits{/sha} compare_url: https://api.github.com/repos/octocat/Hello-World-Template/compare/{base}...{head} contents_url: https://api.github.com/repos/octocat/Hello-World-Template/contents/{+path} contributors_url: https://api.github.com/repos/octocat/Hello-World-Template/contributors deployments_url: https://api.github.com/repos/octocat/Hello-World-Template/deployments downloads_url: https://api.github.com/repos/octocat/Hello-World-Template/downloads events_url: https://api.github.com/repos/octocat/Hello-World-Template/events forks_url: https://api.github.com/repos/octocat/Hello-World-Template/forks git_commits_url: https://api.github.com/repos/octocat/Hello-World-Template/git/commits{/sha} git_refs_url: https://api.github.com/repos/octocat/Hello-World-Template/git/refs{/sha} git_tags_url: https://api.github.com/repos/octocat/Hello-World-Template/git/tags{/sha} git_url: git:github.com/octocat/Hello-World-Template.git issue_comment_url: https://api.github.com/repos/octocat/Hello-World-Template/issues/comments{/number} issue_events_url: https://api.github.com/repos/octocat/Hello-World-Template/issues/events{/number} issues_url: https://api.github.com/repos/octocat/Hello-World-Template/issues{/number} keys_url: https://api.github.com/repos/octocat/Hello-World-Template/keys{/key_id} labels_url: https://api.github.com/repos/octocat/Hello-World-Template/labels{/name} languages_url: https://api.github.com/repos/octocat/Hello-World-Template/languages merges_url: https://api.github.com/repos/octocat/Hello-World-Template/merges milestones_url: https://api.github.com/repos/octocat/Hello-World-Template/milestones{/number} notifications_url: https://api.github.com/repos/octocat/Hello-World-Template/notifications{?since,all,participating} pulls_url: https://api.github.com/repos/octocat/Hello-World-Template/pulls{/number} releases_url: https://api.github.com/repos/octocat/Hello-World-Template/releases{/id} ssh_url: git@github.com:octocat/Hello-World-Template.git stargazers_url: https://api.github.com/repos/octocat/Hello-World-Template/stargazers statuses_url: https://api.github.com/repos/octocat/Hello-World-Template/statuses/{sha} subscribers_url: https://api.github.com/repos/octocat/Hello-World-Template/subscribers subscription_url: https://api.github.com/repos/octocat/Hello-World-Template/subscription tags_url: https://api.github.com/repos/octocat/Hello-World-Template/tags teams_url: https://api.github.com/repos/octocat/Hello-World-Template/teams trees_url: https://api.github.com/repos/octocat/Hello-World-Template/git/trees{/sha} clone_url: https://github.com/octocat/Hello-World-Template.git mirror_url: git:git.example.com/octocat/Hello-World-Template hooks_url: https://api.github.com/repos/octocat/Hello-World-Template/hooks svn_url: https://svn.github.com/octocat/Hello-World-Template homepage: https://github.com forks: 9 forks_count: 9 stargazers_count: 80 watchers_count: 80 watchers: 80 size: 108 default_branch: master open_issues: 0 open_issues_count: 0 is_template: true license: key: mit name: MIT License url: https://api.github.com/licenses/mit spdx_id: MIT node_id: MDc6TGljZW5zZW1pdA== html_url: https://api.github.com/licenses/mit topics: - octocat - atom - electron - api has_issues: true has_projects: true has_wiki: true has_pages: false has_downloads: true archived: false disabled: false visibility: public pushed_at: '2011-01-26T19:06:43Z' created_at: '2011-01-26T19:01:12Z' updated_at: '2011-01-26T19:14:43Z' permissions: pull: true triage: false push: false maintain: false admin: false allow_rebase_merge: true temp_clone_token: ABTLWHOULUVAXGTRYU7OC2876QJ2O allow_squash_merge: true delete_branch_on_merge: true allow_merge_commit: true subscribers_count: 42 network_count: 0 temp_clone_token: ABTLWHOULUVAXGTRYU7OC2876QJ2O allow_squash_merge: true delete_branch_on_merge: true allow_merge_commit: true subscribers_count: 42 network_count: 0 license: key: mit name: MIT License url: https://api.github.com/licenses/mit spdx_id: MIT node_id: MDc6TGljZW5zZW1pdA== html_url: https://api.github.com/licenses/mit forks: 1 open_issues: 1 watchers: 1 private-user-response-with-public-and-private-profile-information: summary: Response with public and private profile information value: login: octocat id: 1 node_id: MDQ6VXNlcjE= avatar_url: https://github.com/images/error/octocat_happy.gif gravatar_id: '' url: https://api.github.com/users/octocat html_url: https://github.com/octocat followers_url: https://api.github.com/users/octocat/followers following_url: https://api.github.com/users/octocat/following{/other_user} gists_url: https://api.github.com/users/octocat/gists{/gist_id} starred_url: https://api.github.com/users/octocat/starred{/owner}{/repo} subscriptions_url: https://api.github.com/users/octocat/subscriptions organizations_url: https://api.github.com/users/octocat/orgs repos_url: https://api.github.com/users/octocat/repos events_url: https://api.github.com/users/octocat/events{/privacy} received_events_url: https://api.github.com/users/octocat/received_events type: User site_admin: false name: monalisa octocat company: GitHub blog: https://github.com/blog location: San Francisco email: octocat@github.com hireable: false bio: There once was... public_repos: 2 public_gists: 1 followers: 20 following: 0 created_at: '2008-01-14T04:33:35Z' updated_at: '2008-01-14T04:33:35Z' private_gists: 81 total_private_repos: 100 owned_private_repos: 100 disk_usage: 10000 collaborators: 8 two_factor_authentication: true plan: name: Medium space: 400 private_repos: 20 collaborators: 0 private-user-response-with-public-profile-information: summary: Response with public profile information value: login: octocat id: 1 node_id: MDQ6VXNlcjE= avatar_url: https://github.com/images/error/octocat_happy.gif gravatar_id: '' url: https://api.github.com/users/octocat html_url: https://github.com/octocat followers_url: https://api.github.com/users/octocat/followers following_url: https://api.github.com/users/octocat/following{/other_user} gists_url: https://api.github.com/users/octocat/gists{/gist_id} starred_url: https://api.github.com/users/octocat/starred{/owner}{/repo} subscriptions_url: https://api.github.com/users/octocat/subscriptions organizations_url: https://api.github.com/users/octocat/orgs repos_url: https://api.github.com/users/octocat/repos events_url: https://api.github.com/users/octocat/events{/privacy} received_events_url: https://api.github.com/users/octocat/received_events type: User site_admin: false name: monalisa octocat company: GitHub blog: https://github.com/blog location: San Francisco email: octocat@github.com hireable: false bio: There once was... public_repos: 2 public_gists: 1 followers: 20 following: 0 created_at: '2008-01-14T04:33:35Z' updated_at: '2008-01-14T04:33:35Z' private-user: value: login: octocat id: 1 node_id: MDQ6VXNlcjE= avatar_url: https://github.com/images/error/octocat_happy.gif gravatar_id: '' url: https://api.github.com/users/octocat html_url: https://github.com/octocat followers_url: https://api.github.com/users/octocat/followers following_url: https://api.github.com/users/octocat/following{/other_user} gists_url: https://api.github.com/users/octocat/gists{/gist_id} starred_url: https://api.github.com/users/octocat/starred{/owner}{/repo} subscriptions_url: https://api.github.com/users/octocat/subscriptions organizations_url: https://api.github.com/users/octocat/orgs repos_url: https://api.github.com/users/octocat/repos events_url: https://api.github.com/users/octocat/events{/privacy} received_events_url: https://api.github.com/users/octocat/received_events type: User site_admin: false name: monalisa octocat company: GitHub blog: https://github.com/blog location: San Francisco email: octocat@github.com hireable: false bio: There once was... public_repos: 2 public_gists: 1 followers: 20 following: 0 created_at: '2008-01-14T04:33:35Z' updated_at: '2008-01-14T04:33:35Z' private_gists: 81 total_private_repos: 100 owned_private_repos: 100 disk_usage: 10000 collaborators: 8 two_factor_authentication: true plan: name: Medium space: 400 private_repos: 20 collaborators: 0 email-items-2: value: - email: octocat@github.com verified: true primary: true visibility: public email-items: value: - email: octocat@octocat.org primary: false verified: false visibility: public - email: octocat@github.com primary: false verified: false visibility: - email: mona@github.com primary: false verified: false visibility: gpg-key-items: value: - id: 3 primary_key_id: 2 key_id: 3262EFF25BA0D270 public_key: xsBNBFayYZ... emails: - email: mastahyeti@users.noreply.github.com verified: true subkeys: - id: 4 primary_key_id: 3 key_id: 4A595D4C72EE49C7 public_key: zsBNBFayYZ... emails: [] subkeys: [] can_sign: false can_encrypt_comms: true can_encrypt_storage: true can_certify: false created_at: '2016-03-24T11:31:04-06:00' expires_at: '2016-03-24T11:31:04-07:00' can_sign: true can_encrypt_comms: false can_encrypt_storage: false can_certify: true created_at: '2016-03-24T11:31:04-06:00' expires_at: '2016-03-24T11:31:04-07:00' raw_key: string gpg-key: value: id: 3 primary_key_id: 2 key_id: 3262EFF25BA0D270 public_key: xsBNBFayYZ... emails: - email: mastahyeti@users.noreply.github.com verified: true subkeys: - id: 4 primary_key_id: 3 key_id: 4A595D4C72EE49C7 public_key: zsBNBFayYZ... emails: [] subkeys: [] can_sign: false can_encrypt_comms: true can_encrypt_storage: true can_certify: false created_at: '2016-03-24T11:31:04-06:00' expires_at: '2016-03-24T11:31:04-07:00' can_sign: true can_encrypt_comms: false can_encrypt_storage: false can_certify: true created_at: '2016-03-24T11:31:04-06:00' expires_at: '2016-03-24T11:31:04-07:00' raw_key: '"-----BEGIN PGP PUBLIC KEY BLOCK-----\nVersion: GnuPG v2\n\nmQENBFayYZ0BCAC4hScoJXXpyR+MXGcrBxElqw3FzCVvkViuyeko+Jp76QJhg8kr\nucRTxbnOoHfda/FmilEa/wxf9ch5/PSrrL26FxEoPHhJolp8fnIDLQeITn94NYdB\nZtnnEKslpPrG97qSUWIchvyqCPtvOb8+8fWvGx9K/ZWcEEdh1X8+WFR2jMENMeoX\nwxHWQoPnS7LpX/85/M7VUcJxvDVfv+eHsnQupmE5bGarKNih0oMe3LbdN3qA5PTz\nSCm6Iudar1VsQ+xTz08ymL7t4pnEtLguQ7EyatFHCjxNblv5RzxoL0tDgN3HqoDz\nc7TEA+q4RtDQl9amcvQ95emnXmZ974u7UkYdABEBAAG0HlNvbWUgVXNlciA8c29t\nZXVzZXJAZ21haWwuY29tPokBOAQTAQIAIgUCVrJhnQIbAwYLCQgHAwIGFQgCCQoL\nBBYCAwECHgECF4AACgkQMmLv8lug0nAViQgArWjI55+7p48URr2z9Jvak+yrBTx1\nzkufltQAnHTJkq+Kl9dySSmTnOop8o3rE4++IOpYV5Y36PkKf9EZMk4n1RQiDPKE\nAFtRVTkRaoWzOir9KQXJPfhKrl01j/QzY+utfiMvUoBJZ9ybq8Pa885SljW9lbaX\nIYw+hl8ZdJ2KStvGrEyfQvRyq3aN5c9TV//4BdGnwx7Qabq/U+G18lizG6f/yq15\ned7t0KELaCfeKPvytp4VE9/z/Ksah/h3+Qilx07/oG2Ae5kC1bEC9coD/ogPUhbv\nb2bsBIoY9E9YwsLoif2lU+o1t76zLgUktuNscRRUKobW028H1zuFS/XQhrkBDQRW\nsmGdAQgApnyyv3i144OLYy0O4UKQxd3e10Y3WpDwfnGIBefAI1m7RxnUxBag/DsU\n7gi9qLEC4VHSfq4eiNfr1LJOyCL2edTgCWFgBhVjbXjZe6YAOrAnhxwCErnN0Y7N\n6s8wVh9fObSOyf8ZE6G7JeKpcq9Q6gd/KxagfD48a1v+fyRHpyQc6J9pUEmtrDJ7\nBjmsd2VWzLBvNWdHyxDNtZweIaqIO9VUYYpr1mtTliNBOZLUelmgrt7HBRcJpWMA\nS8muVVbuP5MK0trLBq/JB8qUH3zRzB/PhMgzmkIfjEK1VYDWm4E8DYyTWEJcHqkb\neqFsNjrIlwPaA122BWC6gUOPwwH+oQARAQABiQEfBBgBAgAJBQJWsmGdAhsMAAoJ\nEDJi7/JboNJwAyAIALd4xcdmGbZD98gScJzqwzkOMcO8zFHqHNvJ42xIFvGny7c0\n1Rx7iyrdypOby5AxE+viQcjG4rpLZW/xKYBNGrCfDyQO7511I0v8x20EICMlMfD/\nNrWQCzesEPcUlKTP07d+sFyP8AyseOidbzY/92CpskTgdSBjY/ntLSaoknl/fjJE\nQM8OkPqU7IraO1Jzzdnm20d5PZL9+PIwIWdSTedU/vBMTJyNcoqvSfKf1wNC66XP\nhqfYgXJE564AdWZKA3C0IyCqiv+LHwxLnUHio1a4/r91C8KPzxs6tGxRDjXLd7ms\nuYFGWymiUGOE/giHlcxdYcHzwLnPDliMQOLiTkK5AQ0EVuxMygEIAOD+bW1cDTmE\nBxh5JECoqeHuwgl6DlLhnubWPkQ4ZeRzBRAsFcEJQlwlJjrzFDicL+lnm6Qq4tt0\n560TwHdf15/AKTZIZu7H25axvGNzgeaUkJEJdYAq9zTKWwX7wKyzBszi485nQg97\nMfAqwhMpDW0Qqf8+7Ug+WEmfBSGv9uL3aQC6WEeIsHfri0n0n8v4XgwhfShXguxO\nCsOztEsuW7WWKW9P4TngKKv4lCHdPlV6FwxeMzODBJvc2fkHVHnqc0PqszJ5xcF8\n6gZCpMM027SbpeYWCAD5zwJyYP9ntfO1p2HjnQ1dZaP9FeNcO7uIV1Lnd1eGCu6I\nsrVp5k1f3isAEQEAAYkCPgQYAQIACQUCVuxMygIbAgEpCRAyYu/yW6DScMBdIAQZ\nAQIABgUCVuxMygAKCRCKohN4dhq2b4tcCACHxmOHVXNpu47OvUGYQydLgMACUlXN\nlj+HfE0VReqShxdDmpasAY9IRpuMB2RsGK8GbNP+4SlOlAiPf5SMhS7nZNkNDgQQ\naZ3HFpgrFmFwmE10BKT4iQtoxELLM57z0qGOAfTsEjWFQa4sF+6IHAQR/ptkdkkI\nBUEXiMnAwVwBysLIJiLO8qdjB6qp52QkT074JVrwywT/P+DkMfC2k4r/AfEbf6eF\ndmPDuPk6KD87+hJZsSa5MaMUBQVvRO/mgEkhJRITVu58eWGaBOcQJ8gqurhCqM5P\nDfUA4TJ7wiqM6sS764vV1rOioTTXkszzhClQqET7hPVnVQjenYgv0EZHNyQH/1f1\n/CYqvV1vFjM9vJjMbxXsATCkZe6wvBVKD8vLsJAr8N+onKQz+4OPc3kmKq7aESu3\nCi/iuie5KKVwnuNhr9AzT61vEkKxwHcVFEvHB77F6ZAAInhRvjzmQbD2dlPLLQCC\nqDj71ODSSAPTEmUy6969bgD9PfWei7kNkBIx7s3eBv8yzytSc2EcuUgopqFazquw\nFs1+tqGHjBvQfTo6bqbJjp/9Ci2pvde3ElV2rAgUlb3lqXyXjRDqrXosh5GcRPQj\nK8Nhj1BNhnrCVskE4BP0LYbOHuzgm86uXwGCFsY+w2VOsSm16Jx5GHyG5S5WU3+D\nIts/HFYRLiFgDLmTlxo=\n=+OzK\n-----END PGP PUBLIC KEY BLOCK-----"' base-installation-for-auth-user-paginated: value: total_count: 2 installations: - id: 1 account: login: octocat id: 1 node_id: MDQ6VXNlcjE= avatar_url: https://github.com/images/error/octocat_happy.gif gravatar_id: '' url: https://api.github.com/users/octocat html_url: https://github.com/octocat followers_url: https://api.github.com/users/octocat/followers following_url: https://api.github.com/users/octocat/following{/other_user} gists_url: https://api.github.com/users/octocat/gists{/gist_id} starred_url: https://api.github.com/users/octocat/starred{/owner}{/repo} subscriptions_url: https://api.github.com/users/octocat/subscriptions organizations_url: https://api.github.com/users/octocat/orgs repos_url: https://api.github.com/users/octocat/repos events_url: https://api.github.com/users/octocat/events{/privacy} received_events_url: https://api.github.com/users/octocat/received_events type: User site_admin: false access_tokens_url: https://api.github.com/installations/1/access_tokens repositories_url: https://api.github.com/installation/repositories html_url: https://github.com/organizations/github/settings/installations/1 app_id: 1 target_id: 1 target_type: Organization permissions: checks: write metadata: read contents: read events: - push - pull_request single_file_name: config.yaml has_multiple_single_files: true single_file_paths: - config.yml - ".github/issue_TEMPLATE.md" repository_selection: all created_at: '2017-07-08T16:18:44-04:00' updated_at: '2017-07-08T16:18:44-04:00' app_slug: github-actions suspended_at: suspended_by: - id: 3 account: login: octocat id: 2 node_id: MDQ6VXNlcjE= avatar_url: https://github.com/images/error/octocat_happy.gif gravatar_id: '' url: https://api.github.com/users/octocat html_url: https://github.com/octocat followers_url: https://api.github.com/users/octocat/followers following_url: https://api.github.com/users/octocat/following{/other_user} gists_url: https://api.github.com/users/octocat/gists{/gist_id} starred_url: https://api.github.com/users/octocat/starred{/owner}{/repo} subscriptions_url: https://api.github.com/users/octocat/subscriptions organizations_url: https://api.github.com/users/octocat/orgs repos_url: https://api.github.com/users/octocat/repos events_url: https://api.github.com/users/octocat/events{/privacy} received_events_url: https://api.github.com/users/octocat/received_events type: User site_admin: false access_tokens_url: https://api.github.com/installations/1/access_tokens repositories_url: https://api.github.com/installation/repositories html_url: https://github.com/organizations/github/settings/installations/1 app_id: 1 target_id: 1 target_type: Organization permissions: checks: write metadata: read contents: read events: - push - pull_request single_file_name: config.yaml has_multiple_single_files: true single_file_paths: - config.yml - ".github/issue_TEMPLATE.md" repository_selection: all created_at: '2017-07-08T16:18:44-04:00' updated_at: '2017-07-08T16:18:44-04:00' app_slug: github-actions suspended_at: suspended_by: key-items: value: - key: 2Sg8iYjAxxmI2LvUXpJjkYrMxURPc8r+dB7TJyvv1234 id: 2 url: https://api.github.com/user/keys/2 title: ssh-rsa AAAAB3NzaC1yc2EAAA created_at: '2020-06-11T21:31:57Z' verified: false read_only: false - key: 2Sg8iYjAxxmI2LvUXpJjkYrMxURPc8r+dB7TJy931234 id: 3 url: https://api.github.com/user/keys/3 title: ssh-rsa AAAAB3NzaC1yc2EAAB created_at: '2020-07-11T21:31:57Z' verified: false read_only: false key: value: key: 2Sg8iYjAxxmI2LvUXpJjkYrMxURPc8r+dB7TJyvv1234 id: 2 url: https://api.github.com/user/keys/2 title: ssh-rsa AAAAB3NzaC1yc2EAAA created_at: '2020-06-11T21:31:57Z' verified: false read_only: false org-membership-items: value: - url: https://api.github.com/orgs/octocat/memberships/defunkt state: active role: admin organization_url: https://api.github.com/orgs/octocat organization: login: github id: 1 node_id: MDEyOk9yZ2FuaXphdGlvbjE= url: https://api.github.com/orgs/github repos_url: https://api.github.com/orgs/github/repos events_url: https://api.github.com/orgs/github/events hooks_url: https://api.github.com/orgs/github/hooks issues_url: https://api.github.com/orgs/github/issues members_url: https://api.github.com/orgs/github/members{/member} public_members_url: https://api.github.com/orgs/github/public_members{/member} avatar_url: https://github.com/images/error/octocat_happy.gif description: A great organization user: login: octocat id: 1 node_id: MDQ6VXNlcjE= avatar_url: https://github.com/images/error/octocat_happy.gif gravatar_id: '' url: https://api.github.com/users/octocat html_url: https://github.com/octocat followers_url: https://api.github.com/users/octocat/followers following_url: https://api.github.com/users/octocat/following{/other_user} gists_url: https://api.github.com/users/octocat/gists{/gist_id} starred_url: https://api.github.com/users/octocat/starred{/owner}{/repo} subscriptions_url: https://api.github.com/users/octocat/subscriptions organizations_url: https://api.github.com/users/octocat/orgs repos_url: https://api.github.com/users/octocat/repos events_url: https://api.github.com/users/octocat/events{/privacy} received_events_url: https://api.github.com/users/octocat/received_events type: User site_admin: false - url: https://api.github.com/orgs/invitocat/memberships/defunkt state: pending role: admin organization_url: https://api.github.com/orgs/invitocat organization: login: github id: 1 node_id: MDEyOk9yZ2FuaXphdGlvbjE= url: https://api.github.com/orgs/github repos_url: https://api.github.com/orgs/github/repos events_url: https://api.github.com/orgs/github/events hooks_url: https://api.github.com/orgs/github/hooks issues_url: https://api.github.com/orgs/github/issues members_url: https://api.github.com/orgs/github/members{/member} public_members_url: https://api.github.com/orgs/github/public_members{/member} avatar_url: https://github.com/images/error/octocat_happy.gif description: A great organization user: login: octocat id: 1 node_id: MDQ6VXNlcjE= avatar_url: https://github.com/images/error/octocat_happy.gif gravatar_id: '' url: https://api.github.com/users/octocat html_url: https://github.com/octocat followers_url: https://api.github.com/users/octocat/followers following_url: https://api.github.com/users/octocat/following{/other_user} gists_url: https://api.github.com/users/octocat/gists{/gist_id} starred_url: https://api.github.com/users/octocat/starred{/owner}{/repo} subscriptions_url: https://api.github.com/users/octocat/subscriptions organizations_url: https://api.github.com/users/octocat/orgs repos_url: https://api.github.com/users/octocat/repos events_url: https://api.github.com/users/octocat/events{/privacy} received_events_url: https://api.github.com/users/octocat/received_events type: User site_admin: false org-membership: value: url: https://api.github.com/orgs/invitocat/memberships/defunkt state: pending role: admin organization_url: https://api.github.com/orgs/invitocat organization: login: github id: 1 node_id: MDEyOk9yZ2FuaXphdGlvbjE= url: https://api.github.com/orgs/github repos_url: https://api.github.com/orgs/github/repos events_url: https://api.github.com/orgs/github/events hooks_url: https://api.github.com/orgs/github/hooks issues_url: https://api.github.com/orgs/github/issues members_url: https://api.github.com/orgs/github/members{/member} public_members_url: https://api.github.com/orgs/github/public_members{/member} avatar_url: https://github.com/images/error/octocat_happy.gif description: A great organization user: login: octocat id: 1 node_id: MDQ6VXNlcjE= avatar_url: https://github.com/images/error/octocat_happy.gif gravatar_id: '' url: https://api.github.com/users/octocat html_url: https://github.com/octocat followers_url: https://api.github.com/users/octocat/followers following_url: https://api.github.com/users/octocat/following{/other_user} gists_url: https://api.github.com/users/octocat/gists{/gist_id} starred_url: https://api.github.com/users/octocat/starred{/owner}{/repo} subscriptions_url: https://api.github.com/users/octocat/subscriptions organizations_url: https://api.github.com/users/octocat/orgs repos_url: https://api.github.com/users/octocat/repos events_url: https://api.github.com/users/octocat/events{/privacy} received_events_url: https://api.github.com/users/octocat/received_events type: User site_admin: false org-membership-2: value: url: https://api.github.com/orgs/octocat/memberships/defunkt state: active role: admin organization_url: https://api.github.com/orgs/octocat organization: login: github id: 1 node_id: MDEyOk9yZ2FuaXphdGlvbjE= url: https://api.github.com/orgs/github repos_url: https://api.github.com/orgs/github/repos events_url: https://api.github.com/orgs/github/events hooks_url: https://api.github.com/orgs/github/hooks issues_url: https://api.github.com/orgs/github/issues members_url: https://api.github.com/orgs/github/members{/member} public_members_url: https://api.github.com/orgs/github/public_members{/member} avatar_url: https://github.com/images/error/octocat_happy.gif description: A great organization user: login: octocat id: 1 node_id: MDQ6VXNlcjE= avatar_url: https://github.com/images/error/octocat_happy.gif gravatar_id: '' url: https://api.github.com/users/octocat html_url: https://github.com/octocat followers_url: https://api.github.com/users/octocat/followers following_url: https://api.github.com/users/octocat/following{/other_user} gists_url: https://api.github.com/users/octocat/gists{/gist_id} starred_url: https://api.github.com/users/octocat/starred{/owner}{/repo} subscriptions_url: https://api.github.com/users/octocat/subscriptions organizations_url: https://api.github.com/users/octocat/orgs repos_url: https://api.github.com/users/octocat/repos events_url: https://api.github.com/users/octocat/events{/privacy} received_events_url: https://api.github.com/users/octocat/received_events type: User site_admin: false project: value: owner_url: https://api.github.com/users/octocat url: https://api.github.com/projects/1002603 html_url: https://github.com/users/octocat/projects/1 columns_url: https://api.github.com/projects/1002603/columns id: 1002603 node_id: MDc6UHJvamVjdDEwMDI2MDM= name: My Projects body: A board to manage my personal projects. number: 1 state: open creator: login: octocat id: 1 node_id: MDQ6VXNlcjE= avatar_url: https://github.com/images/error/octocat_happy.gif gravatar_id: '' url: https://api.github.com/users/octocat html_url: https://github.com/octocat followers_url: https://api.github.com/users/octocat/followers following_url: https://api.github.com/users/octocat/following{/other_user} gists_url: https://api.github.com/users/octocat/gists{/gist_id} starred_url: https://api.github.com/users/octocat/starred{/owner}{/repo} subscriptions_url: https://api.github.com/users/octocat/subscriptions organizations_url: https://api.github.com/users/octocat/orgs repos_url: https://api.github.com/users/octocat/repos events_url: https://api.github.com/users/octocat/events{/privacy} received_events_url: https://api.github.com/users/octocat/received_events type: User site_admin: false created_at: '2011-04-10T20:09:31Z' updated_at: '2014-03-03T18:58:10Z' repository-items-default-response: summary: Default response value: - id: 1296269 node_id: MDEwOlJlcG9zaXRvcnkxMjk2MjY5 name: Hello-World full_name: octocat/Hello-World owner: login: octocat id: 1 node_id: MDQ6VXNlcjE= avatar_url: https://github.com/images/error/octocat_happy.gif gravatar_id: '' url: https://api.github.com/users/octocat html_url: https://github.com/octocat followers_url: https://api.github.com/users/octocat/followers following_url: https://api.github.com/users/octocat/following{/other_user} gists_url: https://api.github.com/users/octocat/gists{/gist_id} starred_url: https://api.github.com/users/octocat/starred{/owner}{/repo} subscriptions_url: https://api.github.com/users/octocat/subscriptions organizations_url: https://api.github.com/users/octocat/orgs repos_url: https://api.github.com/users/octocat/repos events_url: https://api.github.com/users/octocat/events{/privacy} received_events_url: https://api.github.com/users/octocat/received_events type: User site_admin: false private: false html_url: https://github.com/octocat/Hello-World description: This your first repo! fork: false url: https://api.github.com/repos/octocat/Hello-World archive_url: https://api.github.com/repos/octocat/Hello-World/{archive_format}{/ref} assignees_url: https://api.github.com/repos/octocat/Hello-World/assignees{/user} blobs_url: https://api.github.com/repos/octocat/Hello-World/git/blobs{/sha} branches_url: https://api.github.com/repos/octocat/Hello-World/branches{/branch} collaborators_url: https://api.github.com/repos/octocat/Hello-World/collaborators{/collaborator} comments_url: https://api.github.com/repos/octocat/Hello-World/comments{/number} commits_url: https://api.github.com/repos/octocat/Hello-World/commits{/sha} compare_url: https://api.github.com/repos/octocat/Hello-World/compare/{base}...{head} contents_url: https://api.github.com/repos/octocat/Hello-World/contents/{+path} contributors_url: https://api.github.com/repos/octocat/Hello-World/contributors deployments_url: https://api.github.com/repos/octocat/Hello-World/deployments downloads_url: https://api.github.com/repos/octocat/Hello-World/downloads events_url: https://api.github.com/repos/octocat/Hello-World/events forks_url: https://api.github.com/repos/octocat/Hello-World/forks git_commits_url: https://api.github.com/repos/octocat/Hello-World/git/commits{/sha} git_refs_url: https://api.github.com/repos/octocat/Hello-World/git/refs{/sha} git_tags_url: https://api.github.com/repos/octocat/Hello-World/git/tags{/sha} git_url: git:github.com/octocat/Hello-World.git issue_comment_url: https://api.github.com/repos/octocat/Hello-World/issues/comments{/number} issue_events_url: https://api.github.com/repos/octocat/Hello-World/issues/events{/number} issues_url: https://api.github.com/repos/octocat/Hello-World/issues{/number} keys_url: https://api.github.com/repos/octocat/Hello-World/keys{/key_id} labels_url: https://api.github.com/repos/octocat/Hello-World/labels{/name} languages_url: https://api.github.com/repos/octocat/Hello-World/languages merges_url: https://api.github.com/repos/octocat/Hello-World/merges milestones_url: https://api.github.com/repos/octocat/Hello-World/milestones{/number} notifications_url: https://api.github.com/repos/octocat/Hello-World/notifications{?since,all,participating} pulls_url: https://api.github.com/repos/octocat/Hello-World/pulls{/number} releases_url: https://api.github.com/repos/octocat/Hello-World/releases{/id} ssh_url: git@github.com:octocat/Hello-World.git stargazers_url: https://api.github.com/repos/octocat/Hello-World/stargazers statuses_url: https://api.github.com/repos/octocat/Hello-World/statuses/{sha} subscribers_url: https://api.github.com/repos/octocat/Hello-World/subscribers subscription_url: https://api.github.com/repos/octocat/Hello-World/subscription tags_url: https://api.github.com/repos/octocat/Hello-World/tags teams_url: https://api.github.com/repos/octocat/Hello-World/teams trees_url: https://api.github.com/repos/octocat/Hello-World/git/trees{/sha} clone_url: https://github.com/octocat/Hello-World.git mirror_url: git:git.example.com/octocat/Hello-World hooks_url: https://api.github.com/repos/octocat/Hello-World/hooks svn_url: https://svn.github.com/octocat/Hello-World homepage: https://github.com language: forks_count: 9 stargazers_count: 80 watchers_count: 80 size: 108 default_branch: master open_issues_count: 0 is_template: true topics: - octocat - atom - electron - api has_issues: true has_projects: true has_wiki: true has_pages: false has_downloads: true archived: false disabled: false visibility: public pushed_at: '2011-01-26T19:06:43Z' created_at: '2011-01-26T19:01:12Z' updated_at: '2011-01-26T19:14:43Z' permissions: admin: false push: false pull: true allow_rebase_merge: true template_repository: temp_clone_token: ABTLWHOULUVAXGTRYU7OC2876QJ2O allow_squash_merge: true delete_branch_on_merge: true allow_merge_commit: true subscribers_count: 42 network_count: 0 license: key: mit name: MIT License url: https://api.github.com/licenses/mit spdx_id: MIT node_id: MDc6TGljZW5zZW1pdA== html_url: https://github.com/licenses/mit forks: 1 open_issues: 1 watchers: 1 starred-repository-items-alternative-response-with-star-creation-timestamps: summary: Alternative response with star creation timestamps value: - starred_at: '2011-01-16T19:06:43Z' repo: id: 1296269 node_id: MDEwOlJlcG9zaXRvcnkxMjk2MjY5 name: Hello-World full_name: octocat/Hello-World owner: login: octocat id: 1 node_id: MDQ6VXNlcjE= avatar_url: https://github.com/images/error/octocat_happy.gif gravatar_id: '' url: https://api.github.com/users/octocat html_url: https://github.com/octocat followers_url: https://api.github.com/users/octocat/followers following_url: https://api.github.com/users/octocat/following{/other_user} gists_url: https://api.github.com/users/octocat/gists{/gist_id} starred_url: https://api.github.com/users/octocat/starred{/owner}{/repo} subscriptions_url: https://api.github.com/users/octocat/subscriptions organizations_url: https://api.github.com/users/octocat/orgs repos_url: https://api.github.com/users/octocat/repos events_url: https://api.github.com/users/octocat/events{/privacy} received_events_url: https://api.github.com/users/octocat/received_events type: User site_admin: false private: false html_url: https://github.com/octocat/Hello-World description: This your first repo! fork: false url: https://api.github.com/repos/octocat/Hello-World archive_url: https://api.github.com/repos/octocat/Hello-World/{archive_format}{/ref} assignees_url: https://api.github.com/repos/octocat/Hello-World/assignees{/user} blobs_url: https://api.github.com/repos/octocat/Hello-World/git/blobs{/sha} branches_url: https://api.github.com/repos/octocat/Hello-World/branches{/branch} collaborators_url: https://api.github.com/repos/octocat/Hello-World/collaborators{/collaborator} comments_url: https://api.github.com/repos/octocat/Hello-World/comments{/number} commits_url: https://api.github.com/repos/octocat/Hello-World/commits{/sha} compare_url: https://api.github.com/repos/octocat/Hello-World/compare/{base}...{head} contents_url: https://api.github.com/repos/octocat/Hello-World/contents/{+path} contributors_url: https://api.github.com/repos/octocat/Hello-World/contributors deployments_url: https://api.github.com/repos/octocat/Hello-World/deployments downloads_url: https://api.github.com/repos/octocat/Hello-World/downloads events_url: https://api.github.com/repos/octocat/Hello-World/events forks_url: https://api.github.com/repos/octocat/Hello-World/forks git_commits_url: https://api.github.com/repos/octocat/Hello-World/git/commits{/sha} git_refs_url: https://api.github.com/repos/octocat/Hello-World/git/refs{/sha} git_tags_url: https://api.github.com/repos/octocat/Hello-World/git/tags{/sha} git_url: git:github.com/octocat/Hello-World.git issue_comment_url: https://api.github.com/repos/octocat/Hello-World/issues/comments{/number} issue_events_url: https://api.github.com/repos/octocat/Hello-World/issues/events{/number} issues_url: https://api.github.com/repos/octocat/Hello-World/issues{/number} keys_url: https://api.github.com/repos/octocat/Hello-World/keys{/key_id} labels_url: https://api.github.com/repos/octocat/Hello-World/labels{/name} languages_url: https://api.github.com/repos/octocat/Hello-World/languages merges_url: https://api.github.com/repos/octocat/Hello-World/merges milestones_url: https://api.github.com/repos/octocat/Hello-World/milestones{/number} notifications_url: https://api.github.com/repos/octocat/Hello-World/notifications{?since,all,participating} pulls_url: https://api.github.com/repos/octocat/Hello-World/pulls{/number} releases_url: https://api.github.com/repos/octocat/Hello-World/releases{/id} ssh_url: git@github.com:octocat/Hello-World.git stargazers_url: https://api.github.com/repos/octocat/Hello-World/stargazers statuses_url: https://api.github.com/repos/octocat/Hello-World/statuses/{sha} subscribers_url: https://api.github.com/repos/octocat/Hello-World/subscribers subscription_url: https://api.github.com/repos/octocat/Hello-World/subscription tags_url: https://api.github.com/repos/octocat/Hello-World/tags teams_url: https://api.github.com/repos/octocat/Hello-World/teams trees_url: https://api.github.com/repos/octocat/Hello-World/git/trees{/sha} clone_url: https://github.com/octocat/Hello-World.git mirror_url: git:git.example.com/octocat/Hello-World hooks_url: https://api.github.com/repos/octocat/Hello-World/hooks svn_url: https://svn.github.com/octocat/Hello-World homepage: https://github.com language: forks_count: 9 stargazers_count: 80 watchers_count: 80 size: 108 default_branch: master open_issues_count: 0 is_template: true topics: - octocat - atom - electron - api has_issues: true has_projects: true has_wiki: true has_pages: false has_downloads: true archived: false disabled: false visibility: public pushed_at: '2011-01-26T19:06:43Z' created_at: '2011-01-26T19:01:12Z' updated_at: '2011-01-26T19:14:43Z' permissions: admin: false push: false pull: true allow_rebase_merge: true template_repository: temp_clone_token: ABTLWHOULUVAXGTRYU7OC2876QJ2O allow_squash_merge: true delete_branch_on_merge: true allow_merge_commit: true subscribers_count: 42 network_count: 0 license: key: mit name: MIT License url: https://api.github.com/licenses/mit spdx_id: MIT node_id: MDc6TGljZW5zZW1pdA== html_url: https://github.com/licenses/mit forks: 1 open_issues: 1 watchers: 1 team-full-items: value: - id: 1 node_id: MDQ6VGVhbTE= url: https://api.github.com/teams/1 html_url: https://github.com/orgs/github/teams/justice-league name: Justice League slug: justice-league description: A great team. privacy: closed permission: admin members_url: https://api.github.com/teams/1/members{/member} repositories_url: https://api.github.com/teams/1/repos parent: members_count: 3 repos_count: 10 created_at: '2017-07-14T16:53:42Z' updated_at: '2017-08-17T12:37:15Z' organization: login: github id: 1 node_id: MDEyOk9yZ2FuaXphdGlvbjE= url: https://api.github.com/orgs/github repos_url: https://api.github.com/orgs/github/repos events_url: https://api.github.com/orgs/github/events hooks_url: https://api.github.com/orgs/github/hooks issues_url: https://api.github.com/orgs/github/issues members_url: https://api.github.com/orgs/github/members{/member} public_members_url: https://api.github.com/orgs/github/public_members{/member} avatar_url: https://github.com/images/error/octocat_happy.gif description: A great organization name: github company: GitHub blog: https://github.com/blog location: San Francisco email: octocat@github.com has_organization_projects: true has_repository_projects: true public_repos: 2 public_gists: 1 followers: 20 following: 0 html_url: https://github.com/octocat created_at: '2008-01-14T04:33:35Z' type: Organization ldap_dn: uid=asdf,ou=users,dc=github,dc=com public-user-default-response: summary: Default response value: login: octocat id: 1 node_id: MDQ6VXNlcjE= avatar_url: https://github.com/images/error/octocat_happy.gif gravatar_id: '' url: https://api.github.com/users/octocat html_url: https://github.com/octocat followers_url: https://api.github.com/users/octocat/followers following_url: https://api.github.com/users/octocat/following{/other_user} gists_url: https://api.github.com/users/octocat/gists{/gist_id} starred_url: https://api.github.com/users/octocat/starred{/owner}{/repo} subscriptions_url: https://api.github.com/users/octocat/subscriptions organizations_url: https://api.github.com/users/octocat/orgs repos_url: https://api.github.com/users/octocat/repos events_url: https://api.github.com/users/octocat/events{/privacy} received_events_url: https://api.github.com/users/octocat/received_events type: User site_admin: false name: monalisa octocat company: GitHub blog: https://github.com/blog location: San Francisco email: octocat@github.com hireable: false bio: There once was... twitter_username: monatheoctocat public_repos: 2 public_gists: 1 followers: 20 following: 0 created_at: '2008-01-14T04:33:35Z' updated_at: '2008-01-14T04:33:35Z' public-user-response-with-git-hub-plan-information: summary: Response with GitHub plan information value: login: octocat id: 1 node_id: MDQ6VXNlcjE= avatar_url: https://github.com/images/error/octocat_happy.gif gravatar_id: '' url: https://api.github.com/users/octocat html_url: https://github.com/octocat followers_url: https://api.github.com/users/octocat/followers following_url: https://api.github.com/users/octocat/following{/other_user} gists_url: https://api.github.com/users/octocat/gists{/gist_id} starred_url: https://api.github.com/users/octocat/starred{/owner}{/repo} subscriptions_url: https://api.github.com/users/octocat/subscriptions organizations_url: https://api.github.com/users/octocat/orgs repos_url: https://api.github.com/users/octocat/repos events_url: https://api.github.com/users/octocat/events{/privacy} received_events_url: https://api.github.com/users/octocat/received_events type: User site_admin: false name: monalisa octocat company: GitHub blog: https://github.com/blog location: San Francisco email: octocat@github.com hireable: false bio: There once was... twitter_username: monatheoctocat public_repos: 2 public_gists: 1 followers: 20 following: 0 created_at: '2008-01-14T04:33:35Z' updated_at: '2008-01-14T04:33:35Z' plan: name: pro space: 976562499 collaborators: 0 private_repos: 9999 hovercard: value: contexts: - message: Owns this repository octicon: repo key-simple-items: value: - id: 1 key: ssh-rsa AAA... project-items-3: value: - owner_url: https://api.github.com/users/octocat url: https://api.github.com/projects/1002603 html_url: https://github.com/users/octocat/projects/1 columns_url: https://api.github.com/projects/1002603/columns id: 1002603 node_id: MDc6UHJvamVjdDEwMDI2MDM= name: My Projects body: A board to manage my personal projects. number: 1 state: open creator: login: octocat id: 1 node_id: MDQ6VXNlcjE= avatar_url: https://github.com/images/error/octocat_happy.gif gravatar_id: '' url: https://api.github.com/users/octocat html_url: https://github.com/octocat followers_url: https://api.github.com/users/octocat/followers following_url: https://api.github.com/users/octocat/following{/other_user} gists_url: https://api.github.com/users/octocat/gists{/gist_id} starred_url: https://api.github.com/users/octocat/starred{/owner}{/repo} subscriptions_url: https://api.github.com/users/octocat/subscriptions organizations_url: https://api.github.com/users/octocat/orgs repos_url: https://api.github.com/users/octocat/repos events_url: https://api.github.com/users/octocat/events{/privacy} received_events_url: https://api.github.com/users/octocat/received_events type: User site_admin: false created_at: '2011-04-10T20:09:31Z' updated_at: '2014-03-03T18:58:10Z' headers: link: example: ; rel="next", ; rel="last" schema: type: string content-type: example: text/html schema: type: string x-common-marker-version: example: 0.17.4 schema: type: string x-rate-limit-limit: example: 5000 schema: type: integer x-rate-limit-remaining: example: 4999 schema: type: integer x-rate-limit-reset: example: 1590701888 schema: type: integer format: timestamp location: example: https://pipelines.actions.githubusercontent.com/OhgS4QRKqmgx7bKC27GKU83jnQjyeqG8oIMTge8eqtheppcmw8/_apis/pipelines/1/runs/176/signedlogcontent?urlExpires=2020-01-24T18%3A10%3A31.5729946Z&urlSigningMethod=HMACV1&urlSignature=agG73JakPYkHrh06seAkvmH7rBR4Ji4c2%2B6a2ejYh3E%3D schema: type: string responses: not_found: description: Resource not found content: application/json: schema: "$ref": "#/components/schemas/basic-error" validation_failed_simple: description: Validation failed content: application/json: schema: "$ref": "#/components/schemas/validation-error-simple" preview_header_missing: description: Preview header missing content: application/json: schema: type: object required: - message - documentation_url properties: message: type: string documentation_url: type: string forbidden: description: Forbidden content: application/json: schema: "$ref": "#/components/schemas/basic-error" requires_authentication: description: Requires authentication content: application/json: schema: "$ref": "#/components/schemas/basic-error" validation_failed: description: Validation failed content: application/json: schema: "$ref": "#/components/schemas/validation-error" not_modified: description: Not modified gone: description: Gone content: application/json: schema: "$ref": "#/components/schemas/basic-error" service_unavailable: description: Service unavailable content: application/json: schema: type: object properties: code: type: string message: type: string documentation_url: type: string forbidden_gist: description: Forbidden Gist content: application/json: schema: type: object properties: block: type: object properties: reason: type: string created_at: type: string html_url: type: - string - 'null' message: type: string documentation_url: type: string moved_permanently: description: Moved permanently content: application/json: schema: "$ref": "#/components/schemas/basic-error" conflict: description: Conflict content: application/json: schema: "$ref": "#/components/schemas/basic-error" temporary_redirect: description: Temporary Redirect content: application/json: schema: "$ref": "#/components/schemas/basic-error" internal_error: description: Internal Error content: application/json: schema: "$ref": "#/components/schemas/basic-error" code_scanning_forbidden_read: description: Response if GitHub Advanced Security is not enabled for this repository content: application/json: schema: "$ref": "#/components/schemas/basic-error" code_scanning_forbidden_write: description: Response if the repository is archived or if github advanced security is not enabled for this repository content: application/json: schema: "$ref": "#/components/schemas/basic-error" bad_request: description: Bad Request content: application/json: schema: "$ref": "#/components/schemas/basic-error" application/scim+json: schema: "$ref": "#/components/schemas/scim-error" found: description: Found accepted: description: Accepted content: application/json: schema: type: object no_content: description: A header with no content is returned. ================================================ FILE: python/tests/data/mcp_component_server_sample.py ================================================ # Copyright (c) 2025 Baidu, Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from appbuilder.mcp_server.server import MCPComponentServer if __name__ == "__main__": from appbuilder.core.components.v2 import ( Translation, StyleWriting, OralQueryGeneration, ) server = MCPComponentServer(name="AB Component Server") model = "DeepSeek-V3.1" server.add_component(Translation()) server.add_component(StyleWriting(model=model)) server.add_component( OralQueryGeneration(model=model) ) server.run() ================================================ FILE: python/tests/data/mcp_knowledge_base_case.txt ================================================ 物质都是由分子构成的,分子又由原子构成——错的!因为有些物质是不含分子的!比如原子晶体中就只有原子而没有分子,像金刚石,只有C原子,SI‘O2只有硅原子和O原子!还有NaCL这种离子晶体只有Na+和CL-组成 ================================================ FILE: python/tests/data/mcp_official_server_sample.py ================================================ # https://github.com/modelcontextprotocol/quickstart-resources/blob/main/weather-server-python/weather.py from typing import Any import httpx from mcp.server.fastmcp import FastMCP # Initialize FastMCP server mcp = FastMCP("weather") # Constants NWS_API_BASE = "https://api.weather.gov" USER_AGENT = "weather-app/1.0" async def make_nws_request(url: str) -> dict[str, Any] | None: """Make a request to the NWS API with proper error handling.""" headers = {"User-Agent": USER_AGENT, "Accept": "application/geo+json"} async with httpx.AsyncClient() as client: try: response = await client.get(url, headers=headers, timeout=30.0) response.raise_for_status() return response.json() except Exception: return None def format_alert(feature: dict) -> str: """Format an alert feature into a readable string.""" props = feature["properties"] return f""" Event: {props.get('event', 'Unknown')} Area: {props.get('areaDesc', 'Unknown')} Severity: {props.get('severity', 'Unknown')} Description: {props.get('description', 'No description available')} Instructions: {props.get('instruction', 'No specific instructions provided')} """ @mcp.tool() async def get_alerts(state: str) -> str: """Get weather alerts for a US state. Args: state: Two-letter US state code (e.g. CA, NY) """ url = f"{NWS_API_BASE}/alerts/active/area/{state}" data = await make_nws_request(url) if not data or "features" not in data: return "Unable to fetch alerts or no alerts found." if not data["features"]: return "No active alerts for this state." alerts = [format_alert(feature) for feature in data["features"]] return "\n---\n".join(alerts) @mcp.tool() async def get_forecast(latitude: float, longitude: float) -> str: """Get weather forecast for a location. Args: latitude: Latitude of the location longitude: Longitude of the location """ # First get the forecast grid endpoint points_url = f"{NWS_API_BASE}/points/{latitude},{longitude}" points_data = await make_nws_request(points_url) if not points_data: return "Unable to fetch forecast data for this location." # Get the forecast URL from the points response forecast_url = points_data["properties"]["forecast"] forecast_data = await make_nws_request(forecast_url) if not forecast_data: return "Unable to fetch detailed forecast." # Format the periods into a readable forecast periods = forecast_data["properties"]["periods"] forecasts = [] for period in periods[:5]: # Only show next 5 periods forecast = f""" {period['name']}: Temperature: {period['temperature']}°{period['temperatureUnit']} Wind: {period['windSpeed']} {period['windDirection']} Forecast: {period['detailedForecast']} """ forecasts.append(forecast) return "\n---\n".join(forecasts) if __name__ == "__main__": # Initialize and run the server mcp.run(transport="stdio") ================================================ FILE: python/tests/parallel_ut_run.py ================================================ # Copyright (c) 2024 Baidu, Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # add test import os import sys import multiprocessing import subprocess import shutil import copy import time from collections import deque import logging import coverage logger = logging.getLogger("root") logger.setLevel(logging.INFO) handler = logging.StreamHandler(sys.stdout) logger.addHandler(handler) logger.propagate = False current_path = os.path.dirname(os.path.abspath(__file__)) parent_path = os.path.dirname(current_path) """ 将Unittest Case分为以下几类 1、SKIP_UNITTEST 2、CPU_PARALLEL_RUN_UNITTEST 3、CPU_SERIAL_RUN_UNITTEST 4、UNKNOWN_UNITTEST """ # Coverage 运行命令 COVERAGE_CMD = ["coverage", "run", "--pylib", "--source=appbuilder.core,appbuilder.utils", "--parallel-mode"] # 需要跳过的单测用例 SKIP_UNITTEST = [] # 可以CPU并行的单测用例 CPU_PARALLEL_RUN_UNITTEST = [] # 分类未知,故在CPU上串行执行的单测用例 UNKNOWN_UNITTEST = [] def choose_test_case(file): """ 选择测试用例,根据不同的环境变量选择对应的测试用例。如果没有找到指定的测试用例,则返回。 Args: file (str): 文件路径,包含完整路径和文件名。 Returns: None, str: 无返回值,如果找到了指定的测试用例,将其添加到相应的列表中;否则,返回None。 """ skip_case_str = '@unittest.skip(' cpu_parallel_str = '@unittest.skipUnless(os.getenv("TEST_CASE", "UNKNOWN") == "CPU_PARALLEL"' with open(file, 'r') as f: all_line = f.readlines() if list(set([line.strip().find(skip_case_str) for line in all_line])) != [-1]: SKIP_UNITTEST.append(file.split("/")[-1]) return if list(set([line.strip().find(cpu_parallel_str) for line in all_line])) != [-1]: CPU_PARALLEL_RUN_UNITTEST.append(file.split("/")[-1]) return UNKNOWN_UNITTEST.append(file.split("/")[-1]) return def get_all_unittest_file(): """ 获取当前目录下所有以test开头的.py文件,并返回一个列表,包含这些文件的完整路径名。 Args: 无参数。 Returns: list (list[str]): 返回一个列表,包含所有以test开头的.py文件的完整路径名。如果没有找到任何文件,则返回一个空列表。 """ for root, _, fs in os.walk(current_path): for f in fs: file = f.split(".")[-1] prefix = f.split(".")[0].split("_")[0] if file == "py" and prefix == "test": fullname = os.path.join(root, f) choose_test_case(fullname) logger.info("\n需要跳过的单测用例:{}个".format(len(SKIP_UNITTEST))) for idx, case in enumerate(SKIP_UNITTEST): logger.info("--> {}. {}".format(idx+1, case)) logger.info("\nCPU并行的单测用例:{}个".format(len(CPU_PARALLEL_RUN_UNITTEST))) for idx, case in enumerate(CPU_PARALLEL_RUN_UNITTEST): logger.info("--> {}. {}".format(idx+1, case)) logger.info("\nCPU串行执行的单测用例:{}个".format(len(UNKNOWN_UNITTEST))) for idx, case in enumerate(UNKNOWN_UNITTEST): logger.info("--> {}. {}".format(idx+1, case)) def pull_last_n_log(ut_context, file_name, line_count=80): """ 打印最后的line_count行日志,默认为80行。 Args: ut_context (dict): 测试用例上下文字典,包含了log_file字段,表示错误日志文件路径。 file_name (str): 要打印的日志文件名称,将会显示在日志前面。 line_count (int, optional): 要打印的行数,默认为80行。 Returns: None. """ sys.stdout.write("\nError LOG of {}, at {} :\n".format( file_name, os.path.abspath(ut_context["log_file"]))) if ut_context["log_file"]: prefix = "|{} Error LOG| ".format(file_name) sys.stdout.write( prefix + prefix.join(deque(open(ut_context["log_file"], 'r', encoding='utf-8'), line_count))) def run_sync_unittest(test_file): """ 同步运行单元测试 Args: test_file (str): 测试文件名 Returns: dict: 包含进程对象、日志文件对象以及开始时间的字典 """ default_env = os.environ.copy() current_env = copy.copy(default_env) current_env["PYTHONPATH"] = parent_path + os.pathsep + current_env.get("PYTHONPATH", "") cmd = COVERAGE_CMD + [test_file] log = open("{}/ut_logs/{}_run.log".format(current_path, test_file), "w") begin_time = time.time() proc = subprocess.Popen( cmd, env=current_env, cwd=current_path, stdout=log, stderr=log) return {"process": proc, "log": log, "begin_time": begin_time} def run_async_unittest(test_file, case_idx, case_num, timeout=1200): """ 异步运行单元测试,并记录日志文件和结果。 Args: test_file (str): 测试文件名,包含路径。 case_idx (int): 当前测试用例在所有测试用例中的索引值,从1开始。 case_num (int): 所有测试用例的数量。 timeout (int, optional): 超时时间,默认为1200秒(20分钟)。 Returns: None, str: 无返回值,会将结果写入到一个文件中。 """ default_env = os.environ.copy() current_env = copy.copy(default_env) current_env["PYTHONPATH"] = parent_path + os.pathsep + current_env.get("PYTHONPATH", "") cmd = COVERAGE_CMD + [test_file] log_file = "{}/ut_logs/{}_run.log".format(current_path, test_file) log = open(log_file, "w") begin_time = time.time() proc = subprocess.Popen( cmd, env=current_env, cwd=current_path, stdout=log, stderr=log) proc.wait(timeout) ret = proc.poll() end_time = time.time() with open("ut_logs/{}_res".format(test_file), "w+") as f: f.write(str({"name": test_file, "time": end_time - begin_time, "status": ret, "log_file": log_file})) logger.info("[{}] Test Case : {}/{} 耗时: {:.2f} s --> {}".format("OK" if ret == 0 else "ERROR", case_idx, case_num, end_time - begin_time, test_file,)) return def parallel_execute_unittest(test_cases, parallel_num=2): case_num = len(test_cases) success_cases = [] failed_cases = [] process_pool = multiprocessing.Pool(processes=6) for idx, test_file in enumerate(test_cases): process_pool.apply_async( run_async_unittest, args=(test_file, idx+1, case_num,)) process_pool.close() process_pool.join() total_case_time = 0 for case in test_cases: if not os.path.exists("ut_logs/{}_res".format(case)): continue with open("ut_logs/{}_res".format(case), 'r') as f: line = f.readlines()[0] message = eval(line.split("\n")[0]) if message["status"] == 0: if message["name"] not in success_cases: success_cases.append(message["name"]) else: if message["name"] not in failed_cases: failed_cases.append(message["name"]) pull_last_n_log(message, message["name"], ) total_case_time += message["time"] return success_cases, failed_cases, total_case_time def run_cpu_parallel_unittest(): os.environ["TEST_CASE"] = "CPU_PARALLEL" logger.info("\n================ CPU_PARALLEL ================\n") begin_time = time.time() success_cases, failed_cases, total_case_time = parallel_execute_unittest( CPU_PARALLEL_RUN_UNITTEST) logger.info("\n CPU_PARALLEL 运行成功单测:{} 个".format(len(success_cases))) if len(failed_cases) > 0: logger.info("\n以下单测失败,将重试运行 2 次") for case in failed_cases: logger.info("retry case --> {}".format(case)) retry_success_cases, retry_failed_cases, retry_case_time = parallel_execute_unittest( failed_cases, 1) total_case_time += retry_case_time for success in retry_success_cases: failed_cases.remove(success) if len(retry_failed_cases) > 0: logger.info("\n以下单测失败,将重试运行 1 次") for case in retry_failed_cases: logger.info("retry case --> {}".format(case)) second_success_cases, second_failed_cases, second_case_time = parallel_execute_unittest( retry_failed_cases, 1) total_case_time += second_case_time for success in second_success_cases: failed_cases.remove(success) end_time = time.time() logger.info("\n CPU_PARALLEL 运行失败单测: {} 个".format(len(failed_cases))) for failed in failed_cases: logger.info("--> {}".format(failed)) logger.info("\n CPU_PARALLEL 单测并行运行总计耗时 {} s".format( end_time - begin_time)) logger.info("\n CPU_PARALLEL 单测串行运行总计耗时 {} s".format( total_case_time)) return success_cases, failed_cases, end_time - begin_time def run_unknown_unittest(): os.environ["TEST_CASE"] = "CPU_SERIAL" logger.info("\n================ CPU_SERIAL ================\n") begin_time = time.time() success_cases, failed_cases, total_case_time = parallel_execute_unittest( UNKNOWN_UNITTEST, 1) logger.info("\n CPU_SERIAL 运行成功单测:{} 个".format(len(success_cases))) if len(failed_cases) > 0: logger.info("\n以下单测失败,将重试运行一次") for case in failed_cases: logger.info("retry case --> {}".format(case)) retry_success_cases, retry_failed_cases, retry_case_time = parallel_execute_unittest( failed_cases, 1) total_case_time += retry_case_time for success in retry_success_cases: failed_cases.remove(success) end_time = time.time() logger.info("\n CPU_SERIAL 运行失败单测: {} 个".format(len(failed_cases))) for failed in failed_cases: logger.info("--> {}".format(failed)) logger.info("\n CPU_SERIAL 单测并行运行总计耗时 {} s".format( end_time - begin_time)) logger.info("\n CPU_SERIAL 单测串行运行总计耗时 {} s".format( total_case_time)) return success_cases, failed_cases, end_time - begin_time def create_unittest_report(): """ 生成单元测试报告。 Args: 无。 Returns: 无返回值。 """ # 创建日志目录 if not os.path.exists("./ut_logs"): os.mkdir("./ut_logs") get_all_unittest_file() total_success_cases = [] total_failed_cases = [] total_ut_time = 0 test_suite = [run_cpu_parallel_unittest, run_unknown_unittest] for suite in test_suite: success_cases, failed_cases, suite_time = suite() total_success_cases += success_cases total_failed_cases += failed_cases total_ut_time += suite_time logger.info("============== Summary Report =============") logger.info("\nCI运行结束,总耗时:{}".format(total_ut_time)) if len(total_failed_cases) != 0: logger.info("\nCI 运行失败!Failed Case 如下: ") for case in total_failed_cases: logger.info("ERROR: {}".format(case)) exit(1) else: logger.info("\nCI 运行成功!") # shutil.rmtree("./ut_logs") if __name__ == '__main__': create_unittest_report() ================================================ FILE: python/tests/print_components_error_info.py ================================================ import os def pretty_print_dict(kv_dict, header=["Key", "Value"]): spacing = 2 max_k = 25 max_v = 80 for k, v in kv_dict.items(): max_k = max(max_k, len(k)) h_format = " " + "{{:^{}s}}{}{{:^{}s}}\n".format(max_k, " " * spacing, max_v) l_format = " " + "{{:^{}s}}{{}}{{:<{}s}}\n".format(max_k, max_v) length = max_k + max_v + spacing front_border = " ╔" + "".join(["═"] * length) + "╗" line = " ╠" + "".join(["═"] * length) + "╣" back_border = " ╚" + "".join(["═"] * length) + "╝" draws = "" draws += front_border + "\n" draws += h_format.format(header[0], header[1]) draws += line + "\n" for k, v in kv_dict.items(): if isinstance(v, str) and len(v) >= max_v: str_v = "... " + v[-46:] else: str_v = v draws += l_format.format(k, " " * spacing, str(str_v)) draws += back_border _str = "\n{}\n".format(draws) return _str def read_error_file(filename): kv_dict = {} with open(filename, 'r', encoding='utf-8') as file: lines = file.readlines() header = lines[0].strip().split('\t') for line in lines[1:-3]: components = line.strip().split('\t') if len(components) == 2: kv_dict[components[0]] = components[1] return kv_dict, header if __name__ == "__main__": if os.path.exists('components_error_info.txt'): print("旧组件:") filename = 'components_error_info.txt' kv_dict, header = read_error_file(filename) print(pretty_print_dict(kv_dict, header=header)) if os.path.exists('v2_components_error_info.txt'): print("v2组件:") filename = 'v2_components_error_info.txt' kv_dict, header = read_error_file(filename) print(pretty_print_dict(kv_dict, header=header)) ================================================ FILE: python/tests/pytest_config.py ================================================ # Copyright (c) 2024 Baidu, Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import os from appbuilder.utils.logger_util import get_logger log = get_logger(__name__) class LoadConfig(object): """ config """ def __init__(self): """ 初始化函数,读取配置文件并设置实例属性。 """ self.token = os.environ.get("APPBUILDER_TOKEN", "") self.console_url = os.environ.get("GATEWAY_URL", "https://appbuilder.baidu.com") self.cookie = os.environ.get("COOKIE", "") self.csrftoken = os.environ.get('CSRFTOKEN', "") log.info("token: %s" % self.token) log.info("console_url: %s" % self.console_url) log.info("cookie: %s" % self.cookie) log.info("csrftoken: %s" % self.csrftoken) ================================================ FILE: python/tests/pytest_utils.py ================================================ # Copyright (c) 2023 Baidu, Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import random import string import os class Utils(object): """ utils 方法父类 """ @staticmethod def get_random_string(str_len, prefix=None): """ 生成随机字符串,可指定前缀 """ gen_name = ''.join( random.choice(string.ascii_letters + string.digits) for _ in range(str_len) ) if prefix: name = str(prefix) + gen_name else: name = gen_name return name @staticmethod def get_data_file(filename): current_dir = os.path.dirname(os.path.abspath(__file__)) full_file_path = os.path.join(current_dir, "data", filename) return full_file_path ================================================ FILE: python/tests/run_python_test.sh ================================================ # Copyright (c) 2024 Baidu, Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # 该脚本执行以下功能 # 1、克隆git仓库: # 2、基于环境变量,checkout到指定commit # 3、执行setup.sh,生产whl包,并更新当前环境的python库 # 4、执行parallel_ut_run.py,运行python单元测试 # 5、基于测试结果计算单测覆盖率 # # 1、克隆git仓库 # git clone https://github.com/baidubce/app-builder.git # cd app-builder # 1.1、添加提交者的源 # fork_repo="https://github.com/$AGILE_MODULE_NAME.git" # git clone $fork_repo # cd app-builder # git remote add upstream https://github.com/baidubce/app-builder.git # git fetch upstream # # 2、checkout到制定commit # # 环境变量形如:AGILE_REVISION=2352a2574bdfcfff22f0ba7413d9318781a85b3d # export AGILE_REVISION=2352a2574bdfcfff22f0ba7413d9318781a85b3d # commit_id=$AGILE_REVISION # # checkout 到指定commit # git checkout $commit_id # 代码Pass,保存在流水线配置中,并在流水线环境执行 # 3、单测环境的涉密准备 # 3.1、首先是各个单测所需的token、appid、secret等信息,会保存在仅在百度内网可以下载的环境中 # 代码Pass,保存在流水线配置中,并在流水线环境执行 # 4、执行setup.py,生产whl包,并更新当前环境的python库 python3 -m pip install wheel python3 -m pip install coverage python3 -m pip install diff-cover python3 setup.py bdist_wheel python3 -m pip install --force-reinstall dist/*.whl python3 -m pip uninstall numpy -y python3 -m pip install numpy==1.26.4 echo "重新安装pydantic包,设置版本为2.7.4" python3 -m pip uninstall -y pydantic python3 -m pip install pydantic==2.7.4 python3 -m pip install langchain==0.3.0 python3 -m pip install datamodel-code-generator==0.25.8 python3 -m pip install jsonschema python3 -m pip install mcp; true cd python/tests/ # 5、执行parallel_ut_run.py,运行python单元测试 python3 parallel_ut_run.py run_result=$? # 6、基于coverage 测试结果计算全量单测覆盖率 # coverage combine ./python/tests/ coverage combine coverage xml -o coverage.xml coverage html -d coverage_html echo "--------------------------" echo "全量代码覆盖率为:" coverage report -m echo "--------------------------" # 7、计算增量代码的单测覆盖率 # 首先需要将coverage.xml里的文件路径替换 # 规则是:从python lib的安装目录,替换为git clone的目录,举例: # 替换前 /Users/chengmo/Library/Python/3.9/lib/python/site-packages/ # 替换后 /Users/chengmo/workspace/baidu_code/app-builder/ # 首先获取appbuilder-sdk的python lib的安装目录 python_lib=$(python3 -m pip show appbuilder-sdk | grep Location | awk '{print $2}') # 再获取git clone的目录, 当前目录为 app-builder/python/tests, 取 app-builder/目录 git_dir=$(pwd | sed 's/python\/tests//') # 批量替换coverage.xml文件中的python_lib为git_dir,并将源文件备份一个orignal.xml后缀 python3 -u sed_str.py coverage.xml $python_lib $git_dir sed -i 's|/appbuilder|python|g' coverage.xml # 最后进行增量代码覆盖率测试 echo "增量代码覆盖率为:" diff-cover coverage.xml --compare-branch=upstream/master --html-report coverage_diff.html --fail-under=90 cover_result=$? echo "--------------------------" echo "CI 流水线运行结果如下: " echo "单测运行结果: $run_result" echo "单测覆盖率结果: $cover_result" echo "--------------------------" echo "--------------------------" echo "Components组件检查规范性检测结果: " python3 print_components_error_info.py echo "--------------------------" # 若单测失败,则退出 if [ $run_result -ne 0 ]; then echo "单测运行失败,请检查错误日志,修复单测后重试" && exit 1; fi if [ $cover_result -ne 0 ]; then echo "增量代码的单元测试覆盖率低于90%,请完善单元测试后重试" && exit 1; fi ================================================ FILE: python/tests/sed_str.py ================================================ # Copyright (c) 2024 Baidu, Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # 该文件的作用等同于以 sed -i 命令,对文件进行修改 # 接受三个输入,分别为文件名,替换原始字符串,替换目标字符串 # 会将文件中的原始字符串替换为目标字符串 import sys import os def sed_str(file, old_str, new_str): """ 使用sed命令替换文件中的字符串,并返回修改后的结果。 Args: file (str): 需要进行字符串替换的文件路径。 old_str (str): 需要被替换的原始字符串。 new_str (str): 需要替换成的新字符串。 Returns: int: 返回值为0表示操作成功,其他值表示失败。 Raises: 无。 """ with open(file, 'r') as f: lines = f.read() new_lines = lines.replace( old_str, new_str) with open(file, 'w') as f: f.write(new_lines) f.close() os.chmod(file, 0o755) print("sed success!") return 0 if __name__ == '__main__': if len(sys.argv) != 4: print("Usage: python sed_str.py file old_str new_str") exit(-1) file = sys.argv[1] old_str = sys.argv[2] new_str = sys.argv[3] sed_str(file, old_str, new_str) ================================================ FILE: python/tests/test_agent.py ================================================ import os import sys import json import subprocess import unittest import pydantic import appbuilder from appbuilder.core.component import Component from appbuilder.utils.sse_util import SSEClient from appbuilder import ( AgentRuntime, Message, Playground, AppBuilderClient ) class TestAgentRuntime(unittest.TestCase): def setUp(self): """ 设置环境变量。 Args: 无参数,默认值为空。 Returns: 无返回值,方法中执行了环境变量的赋值操作。 """ self.app_id = "aa8af334-df27-4855-b3d1-0d249c61fc08" def test_no_token_http(self): """ 测试http """ component = appbuilder.Playground( prompt_template="{query}", model="DeepSeek-V3.1", lazy_certification=True, ) agent = appbuilder.AgentRuntime(component=component) app = agent.create_flask_app(url_rule="/chat") app.config['TESTING'] = True client = app.test_client() payload = { "message": {"query": "你好"}, "stream": False } headers = {} response = client.post('/chat', json=payload, headers=headers) self.assertNotEqual(response.json.get('code'), 0) def test_err_http(self): """ 测试http """ component = appbuilder.Playground( prompt_template="{query}", model="DeepSeek-V3.1", lazy_certification=True, ) agent = appbuilder.AgentRuntime(component=component) app = agent.create_flask_app(url_rule="/chat") app.config['TESTING'] = True client = app.test_client() payload = { "message": {"query": "你好"}, "stream": False } headers = { "X-Appbuilder-Authorization": "...", "X-Appbuilder-Token": "..." } response = client.post('/chat', json=payload, headers=headers) self.assertNotEqual(response.json.get('code'), 0) def test_stream_http(self): """ 测试http """ component = appbuilder.Playground( prompt_template="{query}", model="DeepSeek-V3.1", lazy_certification=True, ) agent = appbuilder.AgentRuntime(component=component) app = agent.create_flask_app(url_rule="/chat") app.config['TESTING'] = True client = app.test_client() payload = { "message": {"query": "你好"}, "stream": True } headers = { "X-Appbuilder-Authorization": os.environ.get("APPBUILDER_TOKEN", ""), "X-Appbuilder-Token": os.environ.get("APPBUILDER_TOKEN", "") } response = client.post('/chat', json=payload, headers=headers) for e in response.text.split("\n\n"): data_str = e.strip() if data_str: data_str = data_str[len("data: "):] data = json.loads(data_str) self.assertEqual(data.get('code'), 0) def test_http(self): """ 测试http """ component = appbuilder.Playground( prompt_template="{query}", model="DeepSeek-V3.1", lazy_certification=True, ) agent = appbuilder.AgentRuntime(component=component) app = agent.create_flask_app(url_rule="/chat") app.config['TESTING'] = True client = app.test_client() payload = { "message": {"query": "你好"}, "stream": False } headers = { "X-Appbuilder-Authorization": os.environ.get("APPBUILDER_TOKEN", ""), "X-Appbuilder-Token": os.environ.get("APPBUILDER_TOKEN", "") } response = client.post('/chat', json=payload, headers=headers) self.assertEqual(response.status_code, 200) self.assertEqual(response.json.get('code'), 0) def test_init_with_valid_component(self): """ 测试在component有效时运行 """ component = Playground( prompt_template="{query}", model="DeepSeek-V3.1" ) agent = AgentRuntime(component=component) def test_init_with_invalid_component(self): """ 测试在component非法时运行 """ component = "invalid_component" with self.assertRaises(pydantic.ValidationError): agent = AgentRuntime(component=component) def test_chat_with_valid_message_and_blocking(self): """ 测试在消息有效时处理 """ component = Playground( prompt_template="{query}", model="DeepSeek-V3.1" ) agent = appbuilder.AgentRuntime(component=component) message = appbuilder.Message({"query": "你好"}) answer = agent.chat(message, stream=False) self.assertIs(type(answer.content), str) def test_chat_with_valid_message_and_streaming(self): """ 测试在消息有效时处理 """ component = Playground( prompt_template="{query}", model="DeepSeek-V3.1" ) agent = AgentRuntime(component=component) message = Message({"query": "你好"}) answer = agent.chat(message, stream=True) for it in answer.content: self.assertIs(type(it), str) # def test_chainlit_agent_component_error(self): # """ 测试chainlit agent组件错误 """ # component = Component() # agent = AgentRuntime(component=component) # subprocess.check_call( # [sys.executable, "-m", "pip", "uninstall", "-y", "chainlit"] # ) # with self.assertRaises(ImportError): # agent.chainlit_agent() # subprocess.check_call( # [sys.executable, "-m", "pip", "install", "chainlit~=1.0.200"] # ) # with self.assertRaises(ValueError): # agent.chainlit_agent() # os.environ["APPBUILDER_RUN_CHAINLIT"] = "1" # agent_builder = AppBuilderClient(self.app_id) # agent = AgentRuntime(component=agent_builder) # agent.chainlit_agent() if __name__ == '__main__': unittest.main() ================================================ FILE: python/tests/test_ai_search.py ================================================ import unittest import appbuilder import os @unittest.skipUnless(os.getenv("TEST_CASE", "UNKNOWN") == "CPU_SERIAL", "") class TestAgentRuntime(unittest.TestCase): def test_base_search(self): client = appbuilder.AISearch() messages = [ { "role": "user", "content": "请帮我写一个Python程序,实现斐波那契数列的输出。", } ] msg = client.run(messages=messages) assert msg.content is not None def test_ai_search(self): client = appbuilder.AISearch() messages = [ { "role": "user", "content": "请帮我写一个Python程序,实现斐波那契数列的输出。", } ] msg = client.run(messages=messages, model="deepseek-v3.1-250821") assert msg.content is not None if __name__ == "__main__": unittest.main() ================================================ FILE: python/tests/test_ai_search_stream.py ================================================ import unittest import appbuilder import os # @unittest.skipUnless(os.getenv("TEST_CASE", "UNKNOWN") == "CPU_SERIAL", "") class TestAgentRuntime(unittest.TestCase): def test_base_search_stream(self): client = appbuilder.AISearch() messages = [ { "role": "user", "content": "请帮我写一个Python程序,实现斐波那契数列的输出。", } ] msg = client.run(messages=messages, stream=True) for data in msg.content: print(data) def test_ai_search_stream(self): client = appbuilder.AISearch() messages = [ { "role": "user", "content": "请帮我写一个Python程序,实现斐波那契数列的输出。", } ] msg = client.run(messages=messages, model="deepseek-v3.1-250821", stream=True) for data in msg.content: print(data) if __name__ == "__main__": unittest.main() ================================================ FILE: python/tests/test_all_components.py ================================================ from multiprocessing import Pool import os import numpy as np import pandas as pd import unittest import os from appbuilder.core._exception import AppbuilderBuildexException from component_tool_eval_cases import component_tool_eval_cases from component_collector import get_all_components, get_v2_components, get_component_white_list from component_check import check_component_with_retry, write_error_data @unittest.skipUnless(os.getenv("TEST_CASE", "UNKNOWN") == "CPU_SERIAL", "") class TestComponentManifestsAndToolEval(unittest.TestCase): """ 组件manifests和tool_eval入参测试类 Args: 无 Returns: 无返回值 Raises: 无 """ def setUp(self) -> None: """初始化测试用例,设置component名单和白名单,并初始化ComponentCheckBase实例 Args: 无 Returns: 无 """ self.all_components = get_all_components() self.v2_components = get_v2_components() self.whitelist_components = get_component_white_list() def _test_component(self, components, component_cases, whitelist_components, txt_file_path): """测试所有组件的manifests和tool_eval入参 Args: 无 Raises: AppbuilderBuildexException: 如果有任何组件不在白名单中,则抛出异常 """ error_data = [] error_stats ={} with Pool(processes=os.cpu_count()) as pool: # 使用pool.map来执行多进程 args = [] for component, import_res in components.items(): if component not in component_cases: error_data.append({"Component Name": component, "Error Message": "{} 没有添加测试case到 \ component_tool_eval_cases 中".format(component)}) continue else: args.append((component, import_res, component_tool_eval_cases[component])) results = pool.map(check_component_with_retry, args) # 合并每个进程返回的错误数据 for result in results: error_data.extend(result) error_df = pd.DataFrame(error_data) if len(error_data) > 0 else None if error_df is not None: print("\n错误信息表格:") print(error_df) # 使用 NumPy 进行统计 unique_errors, counts = np.unique(error_df["Error Message"], return_counts=True) error_stats = dict(zip(unique_errors, counts)) print("\n错误统计信息:") for error, count in error_stats.items(): print(f"错误信息: {error}, 出现次数: {count}") # 将报错信息写入文件 write_error_data(txt_file_path, error_df, error_stats) # 判断报错组件是否位于白名单中 component_names = error_df["Component Name"].tolist() for component_name in component_names: if component_name in whitelist_components: print("{}在白名单中,暂时忽略报错。".format(component_name), flush=True) else: raise AppbuilderBuildexException(f"组件 {component_name} 未在白名单中,请检查是否需要添加到白名单。") else: print("\n所有组件测试通过,无错误信息。") def _test_all_components(self): """测试旧版本组件""" self._test_component(self.all_components, [], self.whitelist_components, 'components_error_info.txt') def test_v2_components(self): """测试v2版本组件""" self._test_component(self.v2_components, component_tool_eval_cases, [], 'v2_components_error_info.txt') if __name__ == '__main__': unittest.main() ================================================ FILE: python/tests/test_animal_recognize.py ================================================ # Copyright (c) 2023 Baidu, Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import unittest import requests import appbuilder import os class TestAnimalRecognition(unittest.TestCase): def setUp(self): """ 设置环境变量。 """ self.animal_recognition = appbuilder.AnimalRecognition() def test_run_with_raw_image(self): """ 使用原始图片进行单测 Args: None Returns: None """ image_url = "https://bj.bcebos.com/v1/appbuilder/animal_recognize_test.png?" \ "authorization=bce-auth-v1%2FALTAKGa8m4qCUasgoljdEDAzLm%2F2024-01-24T" \ "12%3A19%3A16Z%2F-1%2Fhost%2F411bad53034fa8f9c6edbe5c4909d76ecf6fad68" \ "62cf937c03f8c5260d51c6ae" raw_image = requests.get(image_url).content # Create message with raw_image message = appbuilder.Message(content={"raw_image": raw_image}) # Recognize animal output = self.animal_recognition.run(message) # Assert output is not None self.assertIsNotNone(output) def test_run_with_url(self): """ 使用图片 URL 进行单测 Args: None Returns: None """ image_url = "https://bj.bcebos.com/v1/appbuilder/animal_recognize_test.png?" \ "authorization=bce-auth-v1%2FALTAKGa8m4qCUasgoljdEDAzLm%2F2024-01-24T" \ "12%3A19%3A16Z%2F-1%2Fhost%2F411bad53034fa8f9c6edbe5c4909d76ecf6fad68" \ "62cf937c03f8c5260d51c6ae" # Create message with image URL message = appbuilder.Message(content={"url": image_url}) # Recognize animal output = self.animal_recognition.run(message) # Assert output is not None self.assertIsNotNone(output) def test_run_with_timeout_and_retry(self): """ 测试run方法,timeout、retry参数 Args: None Returns: None """ image_url = "https://bj.bcebos.com/v1/appbuilder/animal_recognize_test.png?" \ "authorization=bce-auth-v1%2FALTAKGa8m4qCUasgoljdEDAzLm%2F2024-01-24T" \ "12%3A19%3A16Z%2F-1%2Fhost%2F411bad53034fa8f9c6edbe5c4909d76ecf6fad68" \ "62cf937c03f8c5260d51c6ae" raw_image = requests.get(image_url).content # Create message with raw_image message = appbuilder.Message(content={"raw_image": raw_image}) # Recognize animal with timeout and retry parameters output = self.animal_recognition.run(message, timeout=5.0, retry=3) # Assert output is not None self.assertIsNotNone(output) def test_run_with_invalid_input(self): """ 测试run函数在传入无效输入的情况下的行为。 Args: None Returns: None """ # create empty message message = appbuilder.Message(content={}) # Assert ValueError is raised with self.assertRaises(ValueError): self.animal_recognition.run(message) def test_run_with_invalid_url(self): """ 测试run函数在传入无效URL的情况下的行为。 Args: None Returns: None """ url = "http://example.com/invalid_url.jpg" message = appbuilder.Message(content={"url": url}) with self.assertRaises(appbuilder.AppBuilderServerException): self.animal_recognition.run(message) def test_tool_eval_valid(self): """测试 tool 方法对有效请求的处理。""" img_url = "https://bj.bcebos.com/v1/appbuilder/animal_recognize_test.png?" \ "authorization=bce-auth-v1%2FALTAKGa8m4qCUasgoljdEDAzLm%2F2024-01-24T" \ "12%3A19%3A16Z%2F-1%2Fhost%2F411bad53034fa8f9c6edbe5c4909d76ecf6fad68" \ "62cf937c03f8c5260d51c6ae" img_name = "test_img.jpg" file_urls = {img_name: img_url} result = self.animal_recognition.tool_eval(name="animal_recognition", streaming=True, img_name=img_name, file_urls=file_urls, origin_query="") res = [item for item in result] self.assertNotEqual(len(res), 0) def test_tool_eval_invalid(self): """测试 tool 方法对无效请求的处理。""" with self.assertRaises(ValueError): result = self.animal_recognition.tool_eval(name="animal_recognition", streaming=True, origin_query="") next(result) if __name__ == '__main__': unittest.main() ================================================ FILE: python/tests/test_appbuilder_assistant_trace.py ================================================ # Copyright (c) 2024 Baidu, Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import os import unittest import appbuilder from appbuilder import AppBuilderTracer from appbuilder import AssistantEventHandler from tests.pytest_utils import Utils check_tool = { "name": "get_cur_whether", "description": "这是一个获得指定地点天气的工具", "parameters": { "type": "object", "properties": { "location": { "type": "string", "description": "省,市名,例如:河北省" }, "unit": { "type": "string", "enum": [ "摄氏度", "华氏度" ] } }, "required": [ "location" ] } } class MyEventHandler(AssistantEventHandler): def get_cur_whether(self, location:str, unit:str): return "{} 的当前温度是30 {}".format(location, unit) def run_begin(self, status_event): run_id = self.stream_run_context.current_run_id thread_id = self.stream_run_context.current_thread_id print("Run_id: {}, Thread_id: {}".format(run_id, thread_id)) def run_end(self, status_event): print("\n", status_event) def tool_step_begin(self, status_event): step_id = self.stream_run_context.current_run_step_id print("Step_id: {}".format(step_id)) def tool_calls(self, status_event): current_tool_calls = self.stream_run_context.current_tool_calls for tool_call in current_tool_calls: name = tool_call.function.name if name == "get_cur_whether": arguments = tool_call.function.arguments func_res = self.get_cur_whether(**eval(arguments)) submit_res = appbuilder.assistant.threads.runs.submit_tool_outputs( run_id=self.stream_run_context.current_run_id, thread_id=self.stream_run_context.current_thread_id, tool_outputs=[ {"tool_call_id": tool_call.id, "output": func_res,} ] ) class TestAppBuilderTrace(unittest.TestCase): def setUp(self): """ 设置测试环境所需的变量。 Args: 无参数。 Returns: 无返回值。 """ os.environ["APPBUILDER_TOKEN"] = os.environ["APPBUILDER_TOKEN_V2"] def test_appbuilder_assistant_trace(self): """ 测试AppBuilder Assistant的追踪功能。 Args: 无参数。 Returns: 无返回值。 """ tracer=AppBuilderTracer( enable_phoenix = True, enable_console = True, ) tracer.start_trace() assistant = appbuilder.assistant.assistants.create( name="test_assistant", description="test assistant", instructions="每句话回复前都加上我是秦始皇" ) file_path = Utils.get_data_file("qa_doc_parser_extract_table_from_doc.png") file = appbuilder.assistant.assistants.files.create(file_path) thread = appbuilder.assistant.threads.create() appbuilder.assistant.threads.messages.create( thread_id=thread.id, content="hello world", file_ids=[file.id] ) run_result = appbuilder.assistant.threads.runs.run( thread_id=thread.id, assistant_id=assistant.id ) tracer.end_trace() def test_appbuilder_assistant_stream_run(self): tracer=AppBuilderTracer( enable_phoenix = True, enable_console = True, ) tracer.start_trace() assistant = appbuilder.assistant.assistants.create( name="test_assistant", description="test assistant", instructions="每句话回复前都加上我是秦始皇" ) file_path = Utils.get_data_file("qa_doc_parser_extract_table_from_doc.png") file = appbuilder.assistant.assistants.files.create(file_path) thread = appbuilder.assistant.threads.create() appbuilder.assistant.threads.messages.create( thread_id=thread.id, content="hello world", file_ids=[file.id] ) generator = appbuilder.assistant.threads.runs.stream_run( thread_id=thread.id, assistant_id=assistant.id ) for run_step in generator: print(run_step) tracer.end_trace() if __name__ == "__main__": unittest.main() ================================================ FILE: python/tests/test_appbuilder_client.py ================================================ import unittest import appbuilder import requests import tempfile import os from tests.pytest_utils import Utils @unittest.skipUnless(os.getenv("TEST_CASE", "UNKNOWN") == "CPU_SERIAL","") class TestAgentRuntime(unittest.TestCase): def setUp(self): """ 设置环境变量。 Args: 无参数,默认值为空。 Returns: 无返回值,方法中执行了环境变量的赋值操作。 """ self.app_id = "aa8af334-df27-4855-b3d1-0d249c61fc08" def test_agent_builder_client(self): agent_builder = appbuilder.AppBuilderClient(self.app_id) def test_agent_builder_run(self): # 如果app_id为空,则跳过单测执行, 避免单测因配置无效而失败 """ 如果app_id为空,则跳过单测执行, 避免单测因配置无效而失败 Args: self (unittest.TestCase): unittest的TestCase对象 Raises: None: 如果app_id不为空,则不会引发任何异常 unittest.SkipTest (optional): 如果app_id为空,则跳过单测执行 """ import tests.pytest_utils as pu if len(self.app_id) == 0: self.skipTest("self.app_id is empty") builder = appbuilder.AppBuilderClient(self.app_id) conversation_id = builder.create_conversation() msg = builder.run(conversation_id, "你可以做什么?") print(msg) file_path = Utils.get_data_file("qa_doc_parser_extract_table_from_doc.png") respid = builder.upload_local_file(conversation_id, file_path) print(respid) def test_upload_local_file_raise(self): builder = appbuilder.AppBuilderClient(self.app_id) with self.assertRaises(ValueError): builder.upload_local_file(conversation_id='', local_file_path='') with self.assertRaises(ValueError): builder.run(conversation_id='', query='') conversation_id = builder.create_conversation() with self.assertRaises(FileNotFoundError): builder.upload_local_file(conversation_id=conversation_id, local_file_path='not_exist') def test_upload_file_url(self): file_url = "https://bj.bcebos.com/v1/appbuilder/animal_recognize_test.png?authorization=bce-auth-v1%2FALTAKGa8m4qCUasgoljdEDAzLm%2F2024-01-24T12%3A19%3A16Z%2F-1%2Fhost%2F411bad53034fa8f9c6edbe5c4909d76ecf6fad6862cf937c03f8c5260d51c6ae" builder = appbuilder.AppBuilderClient(self.app_id) conversation_id = builder.create_conversation() builder.upload_file(conversation_id=conversation_id, file_url=file_url) if __name__ == '__main__': unittest.main() ================================================ FILE: python/tests/test_appbuilder_client_app_detail.py ================================================ # Copyright (c) 2024 Baidu, Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import unittest import appbuilder import os @unittest.skipUnless(os.getenv("TEST_CASE", "UNKNOWN") == "CPU_PARALLEL", "") class TestGetAppList(unittest.TestCase): def setUp(self): """ 设置环境变量。 Args: 无参数,默认值为空。 Returns: 无返回值,方法中执行了环境变量的赋值操作。 """ self.app_id = "b2a972c5-e082-46e5-b313-acbf51792422" self.chatflow_app_id = "4403205e-fb83-4fac-96d8-943bdb63796f" def test_describe_app_agent(self): app_case = appbuilder.describe_app(self.app_id) self.assertIsInstance(app_case.id, str) self.assertIsInstance(app_case.name, str) self.assertIsInstance(app_case.description, str) def test_describe_app_chatflow(self): app_case = appbuilder.describe_app(self.chatflow_app_id) print(app_case) self.assertIsInstance(app_case.id, str) self.assertIsInstance(app_case.name, str) self.assertIsInstance(app_case.description, str) if __name__ == '__main__': unittest.main() ================================================ FILE: python/tests/test_appbuilder_client_app_list.py ================================================ # Copyright (c) 2024 Baidu, Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import unittest import appbuilder import os @unittest.skipUnless(os.getenv("TEST_CASE", "UNKNOWN") == "CPU_PARALLEL", "") class TestGetAppList(unittest.TestCase): def test_get_app_list_v1(self): app_list = appbuilder.get_app_list() self.assertIsInstance(app_list, list) def test_describe_apps(self): app_list = appbuilder.describe_apps() self.assertIsInstance(app_list, list) app_case = app_list[0] self.assertIsInstance(app_case.id, str) self.assertIsInstance(app_case.name, str) self.assertIsInstance(app_case.description, str) self.assertIn(app_case.appType, ["chatflow", "agent"]) self.assertIsInstance(app_case.isPublished, bool) isSecondTimestamp = str(app_case.updateTime).isdigit() and len(str(app_case.updateTime)) < 13 self.assertTrue(isSecondTimestamp) if __name__ == '__main__': unittest.main() ================================================ FILE: python/tests/test_appbuilder_client_chatflow.py ================================================ # Copyright (c) 2024 Baidu, Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import unittest import os import appbuilder from appbuilder.core.console.appbuilder_client import data_class class TestAppBuilderClientChatflow(unittest.TestCase): def setUp(self): """ 设置环境变量。 Args: 无参数,默认值为空。 Returns: 无返回值,方法中执行了环境变量的赋值操作。 """ self.app_id = "4403205e-fb83-4fac-96d8-943bdb63796f" def test_appbuilder_run_chatflow(self): # 如果app_id为空,则跳过单测执行, 避免单测因配置无效而失败 """ 如果app_id为空,则跳过单测执行, 避免单测因配置无效而失败 Args: self (unittest.TestCase): unittest的TestCase对象 Raises: None: 如果app_id不为空,则不会引发任何异常 unittest.SkipTest (optional): 如果app_id为空,则跳过单测执行 """ if len(self.app_id) == 0: self.skipTest("self.app_id is empty") appbuilder.logger.setLevel("ERROR") interrupt_ids = [] builder = appbuilder.AppBuilderClient(self.app_id) conversation_id = builder.create_conversation() msg = builder.run(conversation_id, "查天气", stream=True) interrupt_event_id = None for ans in msg.content: for event in ans.events: if event.content_type == "chatflow_interrupt": assert event.event_type == "chatflow" interrupt_event_id = event.detail.get("interrupt_event_id") break self.assertIsNotNone(interrupt_event_id) interrupt_ids.append(interrupt_event_id) msg = builder.run( conversation_id, "查航班", stream=True, action=data_class.Action.create_resume_action(interrupt_event_id), ) interrupt_event_id = None for ans in msg.content: for event in ans.events: if event.content_type == "chatflow_interrupt": assert event.event_type == "chatflow" interrupt_event_id = event.detail.get("interrupt_event_id") break self.assertIsNotNone(interrupt_event_id) interrupt_ids.append(interrupt_event_id) msg2 = builder.run(conversation_id=conversation_id, query="CA1234", stream=True, action=data_class.Action.create_resume_action(interrupt_ids.pop())) interrupt_event_id = None for ans in msg2.content: for event in ans.events: if event.content_type == "chatflow_interrupt": assert event.event_type == "chatflow" interrupt_event_id = event.detail.get("interrupt_event_id") interrupt_ids.append(interrupt_event_id) break msg2 = builder.run(conversation_id=conversation_id, query="北京的", stream=True, action=data_class.Action.create_resume_action(interrupt_ids.pop())) has_multiple_dialog_event = False for ans in msg2.content: for event in ans.events: if event.content_type == "multiple_dialog_event": assert event.event_type == "chatflow" has_multiple_dialog_event = True break self.assertTrue(has_multiple_dialog_event) if __name__ == "__main__": unittest.main() ================================================ FILE: python/tests/test_appbuilder_client_chatflow_event_handler.py ================================================ # Copyright (c) 2024 Baidu, Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import os import unittest import appbuilder from appbuilder.core.console.appbuilder_client.event_handler import ( AppBuilderEventHandler, ) class MyEventHandler(AppBuilderEventHandler): def __init__(self): super().__init__() self.interrupt_ids = [] def handle_content_type(self, run_context, run_response): interrupt_event_id = None event = run_response.events[-1] if event.content_type == "chatflow_interrupt": interrupt_event_id = event.detail.get("interrupt_event_id") if interrupt_event_id is not None: self.interrupt_ids.append(interrupt_event_id) def _create_action(self): if len(self.interrupt_ids) == 0: return None event_id = self.interrupt_ids.pop() return { "action_type": "resume", "parameters": {"interrupt_event": {"id": event_id, "type": "chat"}}, } def run(self, query=None): super().new_dialog( query=query, action=self._create_action(), ) class TestAppBuilderClientChatflow(unittest.TestCase): def setUp(self): """ 设置环境变量。 Args: 无参数,默认值为空。 Returns: 无返回值,方法中执行了环境变量的赋值操作。 """ self.app_id = "4403205e-fb83-4fac-96d8-943bdb63796f" def test_appbuilder_client_run_with_handler_stream(self): if len(self.app_id) == 0: self.skipTest("self.app_id is empty") appbuilder.logger.setLevel("ERROR") builder = appbuilder.AppBuilderClient(self.app_id) conversation_id = builder.create_conversation() event_handler = MyEventHandler() event_handler.init(appbuilder_client=builder, conversation_id=conversation_id, stream=True, query="查天气") for data in event_handler: pass event_handler.run( query="查航班", ) for data in event_handler: pass event_handler.run( query="CA1234", ) for data in event_handler: pass event_handler.run( query="北京的", ) for data in event_handler: pass def test_appbuilder_client_run_with_handler(self): if len(self.app_id) == 0: self.skipTest("self.app_id is empty") appbuilder.logger.setLevel("ERROR") builder = appbuilder.AppBuilderClient(self.app_id) conversation_id = builder.create_conversation() event_handler = MyEventHandler() event_handler.init( appbuilder_client=builder, conversation_id=conversation_id, stream=False, query="查天气", ) for data in event_handler: pass event_handler.run( query="查航班", ) for data in event_handler: pass event_handler.run( query="CA1234", ) for data in event_handler: pass event_handler.run( query="北京的", ) for data in event_handler: pass if __name__ == "__main__": unittest.main() ================================================ FILE: python/tests/test_appbuilder_client_chatflow_event_handler_v2.py ================================================ # Copyright (c) 2024 Baidu, Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import os import unittest import appbuilder from appbuilder.core.console.appbuilder_client.event_handler import ( AppBuilderEventHandler, ) class MyEventHandler(AppBuilderEventHandler): def __init__(self): super().__init__() self.interrupt_ids = [] def handle_content_type(self, run_context, run_response): interrupt_event_id = None event = run_response.events[-1] if event.content_type == "chatflow_interrupt": interrupt_event_id = event.detail.get("interrupt_event_id") if interrupt_event_id is not None: self.interrupt_ids.append(interrupt_event_id) def _create_action(self): if len(self.interrupt_ids) == 0: return None event_id = self.interrupt_ids.pop() return { "action_type": "resume", "parameters": {"interrupt_event": {"id": event_id, "type": "chat"}}, } def gen_action(self): while True: yield self._create_action() class TestAppBuilderClientChatflow(unittest.TestCase): def setUp(self): """ 设置环境变量。 Args: 无参数,默认值为空。 Returns: 无返回值,方法中执行了环境变量的赋值操作。 """ self.app_id = "4403205e-fb83-4fac-96d8-943bdb63796f" def test_appbuilder_client_run_with_handler_multiple_dialog(self): if len(self.app_id) == 0: self.skipTest("self.app_id is empty") appbuilder.logger.setLevel("DEBUG") builder = appbuilder.AppBuilderClient(self.app_id) conversation_id = builder.create_conversation() queries = ["查天气", "查航班", "CA1234", "北京的"] event_handler = MyEventHandler() event_handler = builder.run_multiple_dialog_with_handler( conversation_id=conversation_id, queries=queries, event_handler=event_handler, stream=True, actions=event_handler.gen_action(), ) for data in event_handler: for ans in data: pass if __name__ == "__main__": unittest.main() ================================================ FILE: python/tests/test_appbuilder_client_custom_metadata.py ================================================ # Copyright (c) 2025 Baidu, Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import os import unittest import appbuilder from appbuilder.core.console.appbuilder_client.data_class import CustomMetadata @unittest.skipUnless(os.getenv("TEST_CASE", "UNKNOWN") == "CPU_SERIAL", "") class TestAppBuilderClientFeedback(unittest.TestCase): def setUp(self): """ 设置环境变量。 Args: 无参数,默认值为空。 Returns: 无返回值,方法中执行了环境变量的赋值操作。 """ self.app_id = "a3654cd9-378a-4b46-a33b-2259ca3b304e" def test_appbuilder_custom_metadata(self): # 如果app_id为空,则跳过单测执行, 避免单测因配置无效而失败 """ 如果app_id为空,则跳过单测执行, 避免单测因配置无效而失败 Args: self (unittest.TestCase): unittest的TestCase对象 Raises: None: 如果app_id不为空,则不会引发任何异常 unittest.SkipTest (optional): 如果app_id为空,则跳过单测执行 """ if len(self.app_id) == 0: self.skipTest("self.app_id is empty") appbuilder.logger.setLoglevel("ERROR") builder = appbuilder.AppBuilderClient(self.app_id) conversation_id = builder.create_conversation() msg = builder.run(conversation_id, "我要回老家相亲", stream=False, custom_metadata=CustomMetadata( override_role_instruction="# 角色任务\n" + "作为高情商大师,你的主要任务是根据提问,做出最佳的建议。\n" + "\n" + "# 工具能力\n" + "\n" + "无工具集提供\n" + "\n" + "# 要求与限制\n" + "\n" + "1. 输出内容的风格为幽默\n" + "2.输出的字数限制为100字以内", )) print(msg.content.answer) def test_appbuilder_custom_metadata_stream(self): # 如果app_id为空,则跳过单测执行, 避免单测因配置无效而失败 """ 如果app_id为空,则跳过单测执行, 避免单测因配置无效而失败 Args: self (unittest.TestCase): unittest的TestCase对象 Raises: None: 如果app_id不为空,则不会引发任何异常 unittest.SkipTest (optional): 如果app_id为空,则跳过单测执行 """ if len(self.app_id) == 0: self.skipTest("self.app_id is empty") appbuilder.logger.setLoglevel("ERROR") builder = appbuilder.AppBuilderClient(self.app_id) conversation_id = builder.create_conversation() msg = builder.run(conversation_id, "我要回老家相亲", stream=True, custom_metadata=CustomMetadata( override_role_instruction="# 角色任务\n" + "作为高情商大师,你的主要任务是根据提问,做出最佳的建议。\n" + "\n" + "# 工具能力\n" + "\n" + "无工具集提供\n" + "\n" + "# 要求与限制\n" + "\n" + "1. 输出内容的风格为幽默\n" + "2.输出的字数限制为100字以内", )) for content in msg.content: print(content.answer) if __name__ == "__main__": unittest.main() ================================================ FILE: python/tests/test_appbuilder_client_feedback.py ================================================ # Copyright (c) 2025 Baidu, Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import unittest import os import appbuilder @unittest.skipUnless(os.getenv("TEST_CASE", "UNKNOWN") == "CPU_SERIAL", "") class TestAppBuilderClientFeedback(unittest.TestCase): def setUp(self): """ 设置环境变量。 Args: 无参数,默认值为空。 Returns: 无返回值,方法中执行了环境变量的赋值操作。 """ self.app_id = "fb64d96b-f828-4385-ba1d-835298d635a9" def test_appbuilder_feedback(self): # 如果app_id为空,则跳过单测执行, 避免单测因配置无效而失败 """ 如果app_id为空,则跳过单测执行, 避免单测因配置无效而失败 Args: self (unittest.TestCase): unittest的TestCase对象 Raises: None: 如果app_id不为空,则不会引发任何异常 unittest.SkipTest (optional): 如果app_id为空,则跳过单测执行 """ if len(self.app_id) == 0: self.skipTest("self.app_id is empty") appbuilder.logger.setLoglevel("ERROR") builder = appbuilder.AppBuilderClient(self.app_id) conversation_id = builder.create_conversation() msg = builder.run(conversation_id, "你能做什么", stream=False) message_id = msg.content.message_id builder.feedback( conversation_id=conversation_id, message_id=message_id, type="downvote", flag=["没有帮助"], reason="测试" ) if __name__ == "__main__": unittest.main() ================================================ FILE: python/tests/test_appbuilder_client_follow_up_query.py ================================================ # Copyright (c) 2024 Baidu, Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import unittest import os import appbuilder from appbuilder.core.console.appbuilder_client.event_handler import ( AppBuilderEventHandler, ) class MyEventHandler(AppBuilderEventHandler): def __init__(self): super().__init__() self.follow_up_queries = [] def handle_content_type(self, run_context, run_response): for event in run_response.events: print(event) if event.content_type == "json" and event.event_type == "FollowUpQuery": follow_up_queries = event.detail.get("json").get("follow_up_querys") self.follow_up_queries.extend(follow_up_queries) @unittest.skipUnless(os.getenv("TEST_CASE", "UNKNOWN") == "CPU_SERIAL", "") class TestAppBuilderClientChatflow(unittest.TestCase): def setUp(self): """ 设置环境变量。 Args: 无参数,默认值为空。 Returns: 无返回值,方法中执行了环境变量的赋值操作。 """ self.app_id = "fb64d96b-f828-4385-ba1d-835298d635a9" def test_appbuilder_run_follow_up_query(self): # 如果app_id为空,则跳过单测执行, 避免单测因配置无效而失败 """ 如果app_id为空,则跳过单测执行, 避免单测因配置无效而失败 Args: self (unittest.TestCase): unittest的TestCase对象 Raises: None: 如果app_id不为空,则不会引发任何异常 unittest.SkipTest (optional): 如果app_id为空,则跳过单测执行 """ if len(self.app_id) == 0: self.skipTest("self.app_id is empty") appbuilder.logger.setLoglevel("ERROR") builder = appbuilder.AppBuilderClient(self.app_id) conversation_id = builder.create_conversation() msg = builder.run(conversation_id, "你能做什么", stream=True) for ans in msg.content: for event in ans.events: if event.content_type == "json" and event.event_type == "FollowUpQuery": follow_up_query = event.detail.get( "json").get("follow_up_querys")[0] print(follow_up_query) assert follow_up_query is not None def test_appbuilder_run_followupquery_with_event_handler(self): if len(self.app_id) == 0: self.skipTest("self.app_id is empty") appbuilder.logger.setLoglevel("ERROR") builder = appbuilder.AppBuilderClient(self.app_id) conversation_id = builder.create_conversation() event_handler = MyEventHandler() with builder.run_with_handler( conversation_id = conversation_id, query = "你能做什么", stream=False, event_handler=event_handler, ) as run: run.until_done() print(event_handler.follow_up_queries) assert len(event_handler.follow_up_queries) > 0 if __name__ == "__main__": unittest.main() ================================================ FILE: python/tests/test_appbuilder_client_mcp.py ================================================ import unittest import appbuilder import os import sys import subprocess import asyncio from appbuilder.core.console.appbuilder_client.async_event_handler import ( AsyncToolCallEventHandler, ) @appbuilder.manifest( description="获取指定中国城市的当前天气信息。仅支持中国城市的天气查询。参数 `location` 为中国城市名称,其他国家城市不支持天气查询。" ) @appbuilder.manifest_parameter( name="location", description="城市名,例如:北京。" ) @appbuilder.manifest_parameter( name="unit", description="温度单位,支持 'celsius' 或 'fahrenheit'" ) def get_current_weather(location: str, unit: str) -> str: return "北京今天25度" functions = [get_current_weather] @unittest.skipUnless(os.getenv("TEST_CASE", "UNKNOWN") == "CPU_SERIAL", "") class TestAppBuilderClientMCP(unittest.TestCase): def setUp(self): """ 设置环境变量。 Args: 无参数,默认值为空。 Returns: 无返回值,方法中执行了环境变量的赋值操作。 """ self.app_id = "b2a972c5-e082-46e5-b313-acbf51792422" @unittest.skipIf(sys.version_info < (3, 10), "Only for Python >= 3.10") def test_appbuilder_client_mcp(self): # 如果app_id为空,则跳过单测执行, 避免单测因配置无效而失败 """ 如果app_id为空,则跳过单测执行, 避免单测因配置无效而失败 Args: self (unittest.TestCase): unittest的TestCase对象 Raises: None: 如果app_id不为空,则不会引发任何异常 unittest.SkipTest (optional): 如果app_id为空,则跳过单测执行 """ async def process(): tools = [appbuilder.Manifest.from_function(f) for f in functions] mcp_client = MCPClient() await mcp_client.connect_to_server("./data/mcp_component_server_sample.py") tools.extend(mcp_client.tools) appbuilder_client = appbuilder.AsyncAppBuilderClient(self.app_id) conversation_id = await appbuilder_client.create_conversation() event_handler = AsyncToolCallEventHandler( mcp_client, functions=functions) with await appbuilder_client.run_with_handler( conversation_id=conversation_id, query="北京的天气怎么样", tools=tools, event_handler=event_handler, stream=False, ) as run: await run.until_done() with await appbuilder_client.run_with_handler( conversation_id=conversation_id, query="翻译hello world为中文", tools=tools, event_handler=event_handler, stream=True, ) as run: await run.until_done() await appbuilder_client.http_client.session.close() await mcp_client.cleanup() from appbuilder.mcp_server.client import MCPClient loop = asyncio.get_event_loop() loop.run_until_complete(process()) if __name__ == "__main__": appbuilder.logger.setLoglevel("DEBUG") unittest.main() ================================================ FILE: python/tests/test_appbuilder_client_mcp_component.py ================================================ import unittest import appbuilder import os import sys import asyncio @unittest.skipUnless(os.getenv("TEST_CASE", "UNKNOWN") == "CPU_SERIAL", "") class TestAgentRuntime(unittest.TestCase): def setUp(self): """ 设置环境变量。 Args: 无参数,默认值为空。 Returns: 无返回值,方法中执行了环境变量的赋值操作。 """ self.app_id = "b2a972c5-e082-46e5-b313-acbf51792422" @unittest.skipIf(sys.version_info < (3, 10), "Only for Python >= 3.10") def test_appbuilder_client_mcp_component(self): # 如果app_id为空,则跳过单测执行, 避免单测因配置无效而失败 """ 如果app_id为空,则跳过单测执行, 避免单测因配置无效而失败 Args: self (unittest.TestCase): unittest的TestCase对象 Raises: None: 如果app_id不为空,则不会引发任何异常 unittest.SkipTest (optional): 如果app_id为空,则跳过单测执行 """ async def process(mcp_client): client = appbuilder.AppBuilderClient(self.app_id) conversation_id = client.create_conversation() await mcp_client.connect_to_server( "./data/mcp_component_server_sample.py", env={"APPBUILDER_TOKEN": os.getenv("APPBUILDER_TOKEN")}, ) msg = client.run( conversation_id=conversation_id, query="将“测试效果”翻译成英文", tools=mcp_client.tools, ) event = msg.content.events[-1] assert event.status == "interrupt" assert event.event_type == "Interrupt" assert client._mcp_context == "client" print( "\033[1;31m", "Agent思考过程:\n{}\n".format( msg.content.events[-1].model_dump_json(indent=4) ), "\033[0m", ) tool_call = msg.content.events[-1].tool_calls[-1] tool_call_id = tool_call.id tool_call_arg = tool_call.function.arguments print("\033[1;32m", "MCP参数:{}\n".format(tool_call_arg), "\033[0m") mcp_server_result = await mcp_client.session.call_tool( name=tool_call.function.name, arguments=tool_call.function.arguments ) print("\033[1;33m", "MCP结果: {}\n".format(mcp_server_result)) msg_2 = client.run( conversation_id=conversation_id, tool_outputs=[{ "tool_call_id": tool_call_id, "output": mcp_server_result.content[0].text }] ) assert client._mcp_context == "client" print( "\033[1;34m", "Agent 最终结果:{}".format(msg_2.content.answer), "\033[0m", ) async def handler(): mcp_client = MCPClient() try: await process(mcp_client) finally: await mcp_client.cleanup() from appbuilder.mcp_server.client import MCPClient loop = asyncio.get_event_loop() loop.run_until_complete(handler()) if __name__ == "__main__": unittest.main() ================================================ FILE: python/tests/test_appbuilder_client_mcp_official.py ================================================ import unittest import appbuilder import os import sys import subprocess import asyncio @unittest.skipUnless(os.getenv("TEST_CASE", "UNKNOWN") == "CPU_SERIAL", "") class TestAgentRuntime(unittest.TestCase): def setUp(self): """ 设置环境变量。 Args: 无参数,默认值为空。 Returns: 无返回值,方法中执行了环境变量的赋值操作。 """ self.app_id = "b2a972c5-e082-46e5-b313-acbf51792422" @unittest.skipIf(sys.version_info < (3, 10), "Only for Python >= 3.10") def test_appbuilder_client_mcp_official(self): # 如果app_id为空,则跳过单测执行, 避免单测因配置无效而失败 """ 如果app_id为空,则跳过单测执行, 避免单测因配置无效而失败 Args: self (unittest.TestCase): unittest的TestCase对象 Raises: None: 如果app_id不为空,则不会引发任何异常 unittest.SkipTest (optional): 如果app_id为空,则跳过单测执行 """ async def process(mcp_client): client = appbuilder.AppBuilderClient(self.app_id) conversation_id = client.create_conversation() await mcp_client.connect_to_server("./data/mcp_official_server_sample.py") msg = client.run( conversation_id=conversation_id, query="latitude:51.5,longtitude:-0.12", tools=mcp_client.tools, ) event = msg.content.events[-1] assert event.status == "interrupt" assert event.event_type == "Interrupt" print( "\033[1;31m", "Agent思考过程:\n{}\n".format( msg.content.events[-1].model_dump_json(indent=4) ), "\033[0m", ) tool_call = msg.content.events[-1].tool_calls[-1] tool_call_id = tool_call.id tool_call_arg = tool_call.function.arguments print("\033[1;32m", "MCP参数:{}\n".format(tool_call_arg), "\033[0m") mcp_server_result = await mcp_client.session.call_tool( name=tool_call.function.name, arguments=tool_call.function.arguments ) print("\033[1;33m", "MCP结果: {}\n".format(mcp_server_result)) msg_2 = client.run( conversation_id=conversation_id, tool_outputs=[{ "tool_call_id": tool_call_id, "output": mcp_server_result.content[0].text }] ) print( "\033[1;34m", "Agent 最终结果:{}".format(msg_2.content.answer), "\033[0m", ) async def handler(): mcp_client = MCPClient() try: await process(mcp_client) finally: await mcp_client.cleanup() from appbuilder.mcp_server.client import MCPClient loop = asyncio.get_event_loop() loop.run_until_complete(handler()) if __name__ == "__main__": unittest.main() ================================================ FILE: python/tests/test_appbuilder_client_parameters.py ================================================ # Copyright (c) 2025 Baidu, Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import unittest import os import appbuilder @unittest.skipUnless(os.getenv("TEST_CASE", "UNKNOWN") == "CPU_SERIAL", "") class TestAppBuilderClientFeedback(unittest.TestCase): def setUp(self): """ 设置环境变量。 Args: 无参数,默认值为空。 Returns: 无返回值,方法中执行了环境变量的赋值操作。 """ self.app_id = "2313e282-baa6-4db6-92dd-a21e99cfd59e" def test_appbuilder_parameters(self): # 如果app_id为空,则跳过单测执行, 避免单测因配置无效而失败 """ 如果app_id为空,则跳过单测执行, 避免单测因配置无效而失败 Args: self (unittest.TestCase): unittest的TestCase对象 Raises: None: 如果app_id不为空,则不会引发任何异常 unittest.SkipTest (optional): 如果app_id为空,则跳过单测执行 """ if len(self.app_id) == 0: self.skipTest("self.app_id is empty") appbuilder.logger.setLoglevel("ERROR") builder = appbuilder.AppBuilderClient(self.app_id) conversation_id = builder.create_conversation() msg = builder.run(conversation_id, "国庆长假", stream=False, parameters={"city": "北京"}) print(msg.content.answer) def test_appbuilder_parameters_stream(self): # 如果app_id为空,则跳过单测执行, 避免单测因配置无效而失败 """ 如果app_id为空,则跳过单测执行, 避免单测因配置无效而失败 Args: self (unittest.TestCase): unittest的TestCase对象 Raises: None: 如果app_id不为空,则不会引发任何异常 unittest.SkipTest (optional): 如果app_id为空,则跳过单测执行 """ if len(self.app_id) == 0: self.skipTest("self.app_id is empty") appbuilder.logger.setLoglevel("ERROR") builder = appbuilder.AppBuilderClient(self.app_id) conversation_id = builder.create_conversation() msg = builder.run(conversation_id, "国庆长假", stream=True, parameters={"city": "北京"}) for content in msg.content: print(content.answer) if __name__ == "__main__": unittest.main() ================================================ FILE: python/tests/test_appbuilder_client_run_with_handler.py ================================================ import unittest import appbuilder import requests import tempfile import os tools = { "name": "get_weather", "description": "这是一个获得指定地点天气的工具", "parameters": { "type": "object", "properties": { "location": { "type": "string", "description": "省,市名,例如:河北省" }, "unit": { "type": "string", "enum": [ "摄氏度", "华氏度" ] } }, "required": [ "location" ] } } from appbuilder.core.console.appbuilder_client.event_handler import ( AppBuilderEventHandler, ) class MyEventHandler(AppBuilderEventHandler): def get_weather(self, location: str, unit: str): return "{} 的当前温度是30 {}".format(location, unit) def messages(self, event): info = "" print("\n\033[1;31m","-> Agent 回答: ", info, "\033[0m") def tool_calls(self, event): current_tool_calls = None for tool_call in current_tool_calls: tool_call_id = tool_call.id func_name = tool_call.function.name arguments = tool_call.function.arguments result = "" if func_name == "get_weather": result = self.get_weather(**arguments) return [result] @unittest.skipUnless(os.getenv("TEST_CASE", "UNKNOWN") == "CPU_SERIAL","") class TestAgentRuntime(unittest.TestCase): def setUp(self): """ 设置环境变量。 Args: 无参数,默认值为空。 Returns: 无返回值,方法中执行了环境变量的赋值操作。 """ self.app_id = "b2a972c5-e082-46e5-b313-acbf51792422" def test_appbuilder_client_tool_call(self): # 如果app_id为空,则跳过单测执行, 避免单测因配置无效而失败 """ 如果app_id为空,则跳过单测执行, 避免单测因配置无效而失败 Args: self (unittest.TestCase): unittest的TestCase对象 Raises: None: 如果app_id不为空,则不会引发任何异常 unittest.SkipTest (optional): 如果app_id为空,则跳过单测执行 """ builder = appbuilder.AppBuilderClient(self.app_id) conversation_id = builder.create_conversation() tools = [ { "type": "function", "function": { "name": "get_current_weather", "description": "仅支持中国城市的天气查询,参数location为中国城市名称,其他国家城市不支持天气查询", "parameters": { "type": "object", "properties": { "location": { "type": "string", "description": "城市名,举例:北京", }, "unit": {"type": "string", "enum": ["celsius", "fahrenheit"]}, }, "required": ["location", "unit"], }, }, } ] msg = builder.run( conversation_id=conversation_id, query="今天北京天气怎么样?", tools=tools) print(msg.model_dump_json(indent=4)) event = msg.content.events[-1] assert event.status == "interrupt" assert event.event_type == "Interrupt" msg_2 = builder.run( conversation_id=conversation_id, tool_outputs=[ { "tool_call_id": event.tool_calls[-1].id, "output": "北京今天35度" } ] ) print(msg_2.model_dump_json(indent=4)) if __name__ == '__main__': unittest.main() ================================================ FILE: python/tests/test_appbuilder_client_toolcall.py ================================================ import unittest import appbuilder import os @unittest.skipUnless(os.getenv("TEST_CASE", "UNKNOWN") == "CPU_SERIAL","") class TestAgentRuntime(unittest.TestCase): def setUp(self): """ 设置环境变量。 Args: 无参数,默认值为空。 Returns: 无返回值,方法中执行了环境变量的赋值操作。 """ self.app_id = "b2a972c5-e082-46e5-b313-acbf51792422" def test_appbuilder_client_tool_call(self): # 如果app_id为空,则跳过单测执行, 避免单测因配置无效而失败 """ 如果app_id为空,则跳过单测执行, 避免单测因配置无效而失败 Args: self (unittest.TestCase): unittest的TestCase对象 Raises: None: 如果app_id不为空,则不会引发任何异常 unittest.SkipTest (optional): 如果app_id为空,则跳过单测执行 """ client = appbuilder.AppBuilderClient(self.app_id) conversation_id = client.create_conversation() tools = [ { "type": "function", "function": { "name": "get_current_weather", "description": "仅支持中国城市的天气查询,参数location为中国城市名称,其他国家城市不支持天气查询", "parameters": { "type": "object", "properties": { "location": { "type": "string", "description": "城市名,举例:北京", }, "unit": { "type": "string", "enum": ["celsius", "fahrenheit"], }, }, "required": ["location", "unit"], }, }, } ] msg = client.run( conversation_id=conversation_id, query="今天北京天气怎么样?", tools=tools ) print(msg.model_dump_json(indent=4)) event = msg.content.events[-1] assert event.status == "interrupt" assert event.event_type == "Interrupt" msg_2 = client.run( conversation_id=conversation_id, tool_outputs=[ {"tool_call_id": event.tool_calls[-1].id, "output": "北京今天35度"} ], ) print(msg_2.model_dump_json(indent=4)) def test_appbuilder_client_tool_call_from_function(self): """测试functions2model功能""" # 定义本地函数 def get_current_weather(location: str, unit: str) -> str: """获取指定中国城市的当前天气信息。 仅支持中国城市的天气查询。参数 `location` 为中国城市名称,其他国家城市不支持天气查询。 Args: location (str): 城市名,例如:"北京"。 unit (int): 温度单位,支持 "celsius" 或 "fahrenheit"。 Returns: str: 天气情况描述 """ return "北京今天25度" # 定义函数列表 functions = [get_current_weather] function_map = {f.__name__: f for f in functions} client = appbuilder.AppBuilderClient(self.app_id) conversation_id = client.create_conversation() msg = client.run( conversation_id=conversation_id, query="今天北京的天气怎么样?", tools=[ appbuilder.Manifest.from_function(f) for f in functions ], ) print(msg.model_dump_json(indent=4)) event = msg.content.events[-1] tool_call = event.tool_calls[-1] # 获取函数名称和参数 name = tool_call.function.name args = tool_call.function.arguments # 将函数名称映射到具体的函数并执行 raw_result = function_map[name](**args) # 传递工具的输出 msg_2 = client.run( conversation_id=conversation_id, tool_outputs=[{"tool_call_id": tool_call.id, "output": str(raw_result)}], ) print(msg_2.model_dump_json(indent=4)) def test_appbuilder_client_tool_call_from_function_decorator(self): @appbuilder.manifest( description="获取指定中国城市的当前天气信息。仅支持中国城市的天气查询。参数 `location` 为中国城市名称,其他国家城市不支持天气查询。" ) @appbuilder.manifest_parameter( name="location", description="城市名,例如:北京。" ) @appbuilder.manifest_parameter( name="unit", description="温度单位,支持 'celsius' 或 'fahrenheit'" ) # 定义示例函数 def get_current_weather(location: str, unit: str) -> str: return "北京今天25度" # 定义函数列表 functions = [get_current_weather] function_map = {f.__name__: f for f in functions} # 调用大模型 client = appbuilder.AppBuilderClient(self.app_id) conversation_id = client.create_conversation() msg = client.run( conversation_id=conversation_id, query="今天北京的天气怎么样?", tools=[ appbuilder.Manifest.from_function(f) for f in functions ], ) print(msg.model_dump_json(indent=4)) # 获取最后的事件和工具调用信息 event = msg.content.events[-1] tool_call = event.tool_calls[-1] # 获取函数名称和参数 name = tool_call.function.name args = tool_call.function.arguments # 将函数名称映射到具体的函数并执行 raw_result = function_map[name](**args) # 传递工具的输出 msg_2 = client.run( conversation_id=conversation_id, tool_outputs=[{"tool_call_id": tool_call.id, "output": str(raw_result)}], ) print(msg_2.model_dump_json(indent=4)) if __name__ == "__main__": unittest.main() ================================================ FILE: python/tests/test_appbuilder_client_toolcall_event_handler.py ================================================ import unittest import appbuilder import requests import tempfile import os from appbuilder.core.console.appbuilder_client.event_handler import AppBuilderEventHandler class MyEventHandler(AppBuilderEventHandler): def get_current_weather(self, location=None, unit="摄氏度"): return "{} 的温度是 {} {}".format(location, 20, unit) def interrupt(self, run_context, run_response): thought = run_context.current_thought # 绿色打印 print("\033[1;32m", "-> Agent 中间思考: ", thought, "\033[0m") tool_output = [] for tool_call in run_context.current_tool_calls: tool_call_id = tool_call.id tool_res = self.get_current_weather( **tool_call.function.arguments) # 蓝色打印 print("\033[1;34m", "-> 本地ToolCall结果: ", tool_res, "\033[0m\n") tool_output.append( { "tool_call_id": tool_call_id, "output": tool_res } ) return tool_output def success(self, run_context, run_response): print("\n\033[1;31m","-> Agent 非流式回答: ", run_response.answer, "\033[0m") @unittest.skipUnless(os.getenv("TEST_CASE", "UNKNOWN") == "CPU_SERIAL","") class TestAgentRuntime(unittest.TestCase): def setUp(self): """ 设置环境变量。 Args: 无参数,默认值为空。 Returns: 无返回值,方法中执行了环境变量的赋值操作。 """ self.app_id = "b2a972c5-e082-46e5-b313-acbf51792422" def test_appbuilder_client_tool_call(self): # 如果app_id为空,则跳过单测执行, 避免单测因配置无效而失败 """ 如果app_id为空,则跳过单测执行, 避免单测因配置无效而失败 Args: self (unittest.TestCase): unittest的TestCase对象 Raises: None: 如果app_id不为空,则不会引发任何异常 unittest.SkipTest (optional): 如果app_id为空,则跳过单测执行 """ builder = appbuilder.AppBuilderClient(self.app_id) conversation_id = builder.create_conversation() tools = [ { "type": "function", "function": { "name": "get_current_weather", "description": "仅支持中国城市的天气查询,参数location为中国城市名称,其他国家城市不支持天气查询", "parameters": { "type": "object", "properties": { "location": { "type": "string", "description": "城市名,举例:北京", }, "unit": {"type": "string", "enum": ["摄氏度", "华氏度"]}, }, "required": ["location", "unit"], }, }, } ] cities = ["北京", "上海", "广州"] query = "下面这些城市的天气怎么样:{}".format(",".join(cities)) with builder.run_with_handler( conversation_id = conversation_id, query = query, tools = tools, event_handler = MyEventHandler(), ) as run: run.until_done() if __name__ == '__main__': unittest.main() ================================================ FILE: python/tests/test_appbuilder_client_toolcall_event_handler_error.py ================================================ import unittest import appbuilder import requests import tempfile import os from appbuilder.core.console.appbuilder_client.event_handler import AppBuilderEventHandler class MyEventHandler(AppBuilderEventHandler): def get_current_weather(self, location=None, unit="摄氏度"): return "{} 的温度是 {} {}".format(location, 20, unit) def interrupt(self, run_context, run_response): thought = run_context.current_thought # 绿色打印 print("\033[1;32m", "-> Agent 中间思考: ", thought, "\033[0m") empty_output = [{}] return empty_output def success(self, run_context, run_response): print("\n\033[1;31m","-> Agent 非流式回答: ", run_response.answer, "\033[0m") @unittest.skipUnless(os.getenv("TEST_CASE", "UNKNOWN") == "CPU_SERIAL","") class TestAgentRuntime(unittest.TestCase): def setUp(self): """ 设置环境变量。 Args: 无参数,默认值为空。 Returns: 无返回值,方法中执行了环境变量的赋值操作。 """ self.app_id = "b2a972c5-e082-46e5-b313-acbf51792422" def test_appbuilder_client_tool_call(self): # 如果app_id为空,则跳过单测执行, 避免单测因配置无效而失败 """ 如果app_id为空,则跳过单测执行, 避免单测因配置无效而失败 Args: self (unittest.TestCase): unittest的TestCase对象 Raises: None: 如果app_id不为空,则不会引发任何异常 unittest.SkipTest (optional): 如果app_id为空,则跳过单测执行 """ builder = appbuilder.AppBuilderClient(self.app_id) conversation_id = builder.create_conversation() tools = [ { "type": "function", "function": { "name": "get_current_weather", "description": "仅支持中国城市的天气查询,参数location为中国城市名称,其他国家城市不支持天气查询", "parameters": { "type": "object", "properties": { "location": { "type": "string", "description": "城市名,举例:北京", }, "unit": {"type": "string", "enum": ["摄氏度", "华氏度"]}, }, "required": ["location", "unit"], }, }, } ] cities = ["北京", "上海", "广州"] query = "下面这些城市的天气怎么样:{}".format(",".join(cities)) with self.assertRaises(Exception): stream = builder.run_with_handler( conversation_id = conversation_id, query = query, tools = tools, event_handler = MyEventHandler(), ) for res in stream: pass conversation_id = builder.create_conversation() with self.assertRaises(Exception): stream = builder.run_with_handler( conversation_id = conversation_id, query = query, tools = tools, stream = True, event_handler = MyEventHandler(), ) for res in stream: pass if __name__ == '__main__': unittest.main() ================================================ FILE: python/tests/test_appbuilder_client_toolcall_event_handler_stream.py ================================================ import unittest import appbuilder import requests import tempfile import os from appbuilder.core.console.appbuilder_client.event_handler import AppBuilderEventHandler class MyEventHandler(AppBuilderEventHandler): def get_current_weather(self, location=None, unit="摄氏度"): return "{} 的温度是 {} {}".format(location, 20, unit) def interrupt(self, run_context, run_response): thought = run_context.current_thought # 绿色打印 print("\033[1;32m", "-> Agent 中间思考: ", thought, "\033[0m") tool_output = [] for tool_call in run_context.current_tool_calls: tool_call_id = tool_call.id tool_res = self.get_current_weather( **tool_call.function.arguments) # 蓝色打印 print("\033[1;34m", "-> 本地ToolCall结果: ", tool_res, "\033[0m\n") tool_output.append( { "tool_call_id": tool_call_id, "output": tool_res } ) return tool_output def running(self, run_context, run_response): print("\n\033[1;31m","-> Agent 流式回答: \n", run_response.answer, "\033[0m") @unittest.skipUnless(os.getenv("TEST_CASE", "UNKNOWN") == "CPU_SERIAL","") class TestAgentRuntime(unittest.TestCase): def setUp(self): """ 设置环境变量。 Args: 无参数,默认值为空。 Returns: 无返回值,方法中执行了环境变量的赋值操作。 """ self.app_id = "b2a972c5-e082-46e5-b313-acbf51792422" def test_appbuilder_client_tool_call(self): # 如果app_id为空,则跳过单测执行, 避免单测因配置无效而失败 """ 如果app_id为空,则跳过单测执行, 避免单测因配置无效而失败 Args: self (unittest.TestCase): unittest的TestCase对象 Raises: None: 如果app_id不为空,则不会引发任何异常 unittest.SkipTest (optional): 如果app_id为空,则跳过单测执行 """ builder = appbuilder.AppBuilderClient(self.app_id) conversation_id = builder.create_conversation() tools = [ { "type": "function", "function": { "name": "get_current_weather", "description": "仅支持中国城市的天气查询,参数location为中国城市名称,其他国家城市不支持天气查询", "parameters": { "type": "object", "properties": { "location": { "type": "string", "description": "城市名,举例:北京", }, "unit": {"type": "string", "enum": ["摄氏度", "华氏度"]}, }, "required": ["location", "unit"], }, }, } ] cities = ["北京", "上海", "广州"] query = "下面这些城市的天气怎么样:{}".format(",".join(cities)) with builder.run_with_handler( conversation_id = conversation_id, query = query, tools = tools, stream = True, event_handler = MyEventHandler(), ) as run: run.until_done() if __name__ == '__main__': unittest.main() ================================================ FILE: python/tests/test_appbuilder_client_toolcall_event_handler_v2.py ================================================ import unittest import appbuilder import requests import tempfile import os from appbuilder.core.console.appbuilder_client.event_handler import AppBuilderEventHandler class MyEventHandler(AppBuilderEventHandler): def get_current_weather(self, location=None, unit="摄氏度"): return "{} 的温度是 {} {}".format(location, 20, unit) def interrupt(self, run_context, run_response): thought = run_context.current_thought # 绿色打印 print("\033[1;32m", "-> Agent 中间思考: ", thought, "\033[0m") tool_output = [] for tool_call in run_context.current_tool_calls: tool_call_id = tool_call.id tool_res = self.get_current_weather( **tool_call.function.arguments) # 蓝色打印 print("\033[1;34m", "-> 本地ToolCall结果: ", tool_res, "\033[0m\n") tool_output.append( { "tool_call_id": tool_call_id, "output": tool_res } ) return tool_output def success(self, run_context, run_response): print("\n\033[1;31m","-> Agent 非流式回答: ", run_response.answer, "\033[0m") @unittest.skipUnless(os.getenv("TEST_CASE", "UNKNOWN") == "CPU_SERIAL","") class TestAgentRuntime(unittest.TestCase): def setUp(self): """ 设置环境变量。 Args: 无参数,默认值为空。 Returns: 无返回值,方法中执行了环境变量的赋值操作。 """ self.app_id = "b2a972c5-e082-46e5-b313-acbf51792422" def test_appbuilder_client_tool_call(self): # 如果app_id为空,则跳过单测执行, 避免单测因配置无效而失败 """ 如果app_id为空,则跳过单测执行, 避免单测因配置无效而失败 Args: self (unittest.TestCase): unittest的TestCase对象 Raises: None: 如果app_id不为空,则不会引发任何异常 unittest.SkipTest (optional): 如果app_id为空,则跳过单测执行 """ builder = appbuilder.AppBuilderClient(self.app_id) conversation_id = builder.create_conversation() tools = [ { "type": "function", "function": { "name": "get_current_weather", "description": "仅支持中国城市的天气查询,参数location为中国城市名称,其他国家城市不支持天气查询", "parameters": { "type": "object", "properties": { "location": { "type": "string", "description": "城市名,举例:北京", }, "unit": {"type": "string", "enum": ["摄氏度", "华氏度"]}, }, "required": ["location", "unit"], }, }, } ] query = "北京的天气怎么样" with builder.run_with_handler( conversation_id = conversation_id, query = query, tools = tools, event_handler = MyEventHandler(), ) as run: run.until_done() query = "上海的天气怎么样" run = builder.run_with_handler( conversation_id = conversation_id, query = query, tools = tools, event_handler = MyEventHandler(), ) for res in run: print(res) if __name__ == '__main__': unittest.main() ================================================ FILE: python/tests/test_appbuilder_client_toolcall_event_handler_v3.py ================================================ import unittest import appbuilder import requests import tempfile import os from appbuilder.core.console.appbuilder_client.event_handler import AppBuilderEventHandler class MyEventHandler(AppBuilderEventHandler): def get_current_weather(self, location=None, unit="摄氏度"): return "{} 的温度是 {} {}".format(location, 20, unit) def interrupt(self, run_context, run_response): thought = run_context.current_thought # 绿色打印 print("\033[1;32m", "-> Agent 中间思考: ", thought, "\033[0m") tool_output = [] for tool_call in run_context.current_tool_calls: tool_call_id = tool_call.id tool_res = self.get_current_weather( **tool_call.function.arguments) # 蓝色打印 print("\033[1;34m", "-> 本地ToolCall结果: ", tool_res, "\033[0m\n") tool_output.append( { "tool_call_id": tool_call_id, "output": tool_res } ) return tool_output def running(self, run_context, run_response): print("\n\033[1;31m","-> Agent 流式回答: \n", run_response.answer, "\033[0m") @unittest.skipUnless(os.getenv("TEST_CASE", "UNKNOWN") == "CPU_SERIAL","") class TestAgentRuntime(unittest.TestCase): def setUp(self): """ 设置环境变量。 Args: 无参数,默认值为空。 Returns: 无返回值,方法中执行了环境变量的赋值操作。 """ self.app_id = "b2a972c5-e082-46e5-b313-acbf51792422" def test_appbuilder_client_tool_call(self): # 如果app_id为空,则跳过单测执行, 避免单测因配置无效而失败 """ 如果app_id为空,则跳过单测执行, 避免单测因配置无效而失败 Args: self (unittest.TestCase): unittest的TestCase对象 Raises: None: 如果app_id不为空,则不会引发任何异常 unittest.SkipTest (optional): 如果app_id为空,则跳过单测执行 """ builder = appbuilder.AppBuilderClient(self.app_id) conversation_id = builder.create_conversation() tools = [ { "type": "function", "function": { "name": "get_current_weather", "description": "仅支持中国城市的天气查询,参数location为中国城市名称,其他国家城市不支持天气查询", "parameters": { "type": "object", "properties": { "location": { "type": "string", "description": "城市名,举例:北京", }, "unit": {"type": "string", "enum": ["摄氏度", "华氏度"]}, }, "required": ["location", "unit"], }, }, } ] query = "北京的天气怎么样" with builder.run_with_handler( conversation_id = conversation_id, query = query, tools = tools, stream = True, event_handler = MyEventHandler(), ) as run: run.until_done() query = "上海的天气怎么样" run = builder.run_with_handler( conversation_id = conversation_id, query = query, tools = tools, stream= True, event_handler = MyEventHandler(), ) for res in run: print(res) if __name__ == '__main__': unittest.main() ================================================ FILE: python/tests/test_appbuilder_client_toolcall_stream.py ================================================ import unittest import appbuilder import requests import tempfile import os @unittest.skipUnless(os.getenv("TEST_CASE", "UNKNOWN") == "CPU_SERIAL","") class TestAgentRuntime(unittest.TestCase): def setUp(self): """ 设置环境变量。 Args: 无参数,默认值为空。 Returns: 无返回值,方法中执行了环境变量的赋值操作。 """ self.app_id = "b2a972c5-e082-46e5-b313-acbf51792422" def test_appbuilder_client_tool_call(self): # 如果app_id为空,则跳过单测执行, 避免单测因配置无效而失败 """ 如果app_id为空,则跳过单测执行, 避免单测因配置无效而失败 Args: self (unittest.TestCase): unittest的TestCase对象 Raises: None: 如果app_id不为空,则不会引发任何异常 unittest.SkipTest (optional): 如果app_id为空,则跳过单测执行 """ builder = appbuilder.AppBuilderClient(self.app_id) conversation_id = builder.create_conversation() tools = [ { "type": "function", "function": { "name": "get_current_weather", "description": "仅支持中国城市的天气查询,参数location为中国城市名称,其他国家城市不支持天气查询", "parameters": { "type": "object", "properties": { "location": { "type": "string", "description": "城市名,举例:北京", }, "unit": {"type": "string", "enum": ["celsius", "fahrenheit"]}, }, "required": ["location", "unit"], }, }, } ] msg = builder.run( conversation_id=conversation_id, query="今天北京天气怎么样?", tools=tools, stream=True) for res in msg.content: print(res.model_dump_json(indent=4)) if len(res.events) > 0: event = res.events[-1] assert event.status == "interrupt" assert event.event_type == "Interrupt" msg_2 = builder.run( conversation_id=conversation_id, tool_outputs=[ { "tool_call_id": event.tool_calls[-1].id, "output": "北京今天35度" } ], stream=True ) for res in msg_2.content: print(res.model_dump_json(indent=4)) if __name__ == '__main__': unittest.main() ================================================ FILE: python/tests/test_appbuilder_client_toolcall_v2.py ================================================ import unittest import appbuilder import requests import tempfile import os @unittest.skipUnless(os.getenv("TEST_CASE", "UNKNOWN") == "CPU_SERIAL","") class TestAgentRuntime(unittest.TestCase): def setUp(self): """ 设置环境变量。 Args: 无参数,默认值为空。 Returns: 无返回值,方法中执行了环境变量的赋值操作。 """ self.app_id = "b2a972c5-e082-46e5-b313-acbf51792422" def test_appbuilder_client_tool_call(self): # 如果app_id为空,则跳过单测执行, 避免单测因配置无效而失败 """ 如果app_id为空,则跳过单测执行, 避免单测因配置无效而失败 Args: self (unittest.TestCase): unittest的TestCase对象 Raises: None: 如果app_id不为空,则不会引发任何异常 unittest.SkipTest (optional): 如果app_id为空,则跳过单测执行 """ builder = appbuilder.AppBuilderClient(self.app_id) conversation_id = builder.create_conversation() tools = [ { "type": "function", "function": { "name": "get_current_weather", "description": "支持多个中国城市的天气查询,参数location为一个list,包含多个中国城市名称", "parameters": { "type": "object", "properties": { "location": {'items': {'type': 'string'}, 'title': 'Location', 'type': 'array'}, "unit": {"type": "string", "enum": ["celsius", "fahrenheit"]}, }, "required": ["location", "unit"], }, }, } ] msg = builder.run( conversation_id=conversation_id, query="今天北京和上海天气怎么样?", tools=tools) print(msg.model_dump_json(indent=4)) event = msg.content.events[-1] assert event.status == "interrupt" assert event.event_type == "Interrupt" msg_2 = builder.run( conversation_id=conversation_id, tool_outputs=[ { "tool_call_id": event.tool_calls[-1].id, "output": "北京和上海今天都是35度" } ] ) print(msg_2.model_dump_json(indent=4)) if __name__ == '__main__': unittest.main() ================================================ FILE: python/tests/test_appbuilder_client_toolcall_v3.py ================================================ import unittest import appbuilder import requests import tempfile import os @unittest.skipUnless(os.getenv("TEST_CASE", "UNKNOWN") == "CPU_SERIAL","") class TestAgentRuntime(unittest.TestCase): def setUp(self): """ 设置环境变量。 Args: 无参数,默认值为空。 Returns: 无返回值,方法中执行了环境变量的赋值操作。 """ self.app_id = "b2a972c5-e082-46e5-b313-acbf51792422" def test_appbuilder_client_tool_call(self): # 如果app_id为空,则跳过单测执行, 避免单测因配置无效而失败 """ 如果app_id为空,则跳过单测执行, 避免单测因配置无效而失败 Args: self (unittest.TestCase): unittest的TestCase对象 Raises: None: 如果app_id不为空,则不会引发任何异常 unittest.SkipTest (optional): 如果app_id为空,则跳过单测执行 """ builder = appbuilder.AppBuilderClient(self.app_id) conversation_id = builder.create_conversation() tools = [ { "type": "function", "function": { "name": "get_current_weather", "description": "仅支持中国城市的天气查询,参数location为中国城市名称,其他国家城市不支持天气查询", "parameters": { "type": "object", "properties": { "location": { "type": "string", "description": "城市名,举例:北京", }, "unit": {"type": "string", "enum": ["celsius", "fahrenheit"]}, }, "required": ["location", "unit"], }, }, } ] cities = ["北京", "上海", "广州", "深圳", "杭州"] query = "下面这些城市的天气怎么样:{}".format(",".join(cities)) msg = builder.run( conversation_id=conversation_id, query=query, tools=tools) print("------ Response: --------\n") print(msg.model_dump_json(indent=4)) print("------ End of response--------\n") event = msg.content.events[-1] idx = 0 while True: if event.status == "success": break msg_2 = builder.run( conversation_id=conversation_id, tool_outputs=[ { "tool_call_id": event.tool_calls[-1].id, "output": "{}今天的温度是35度".format(cities[idx]) } ] ) idx += 1 print("------ Response: --------\n") print(msg_2.model_dump_json(indent=4)) print("------ End of response--------\n") event = msg_2.content.events[-1] print(msg.content.answer) if __name__ == '__main__': unittest.main() ================================================ FILE: python/tests/test_appbuilder_client_trace.py ================================================ # Copyright (c) 2024 Baidu, Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import unittest import appbuilder import os from appbuilder.utils.trace.tracer import AppBuilderTracer, AppbuilderInstrumentor from appbuilder.utils.trace.phoenix_wrapper import runtime_main,stop_phoenix,launch_phoenix from appbuilder.core.console.appbuilder_client import get_app_list class TestAppBuilderTrace(unittest.TestCase): def setUp(self): """ 初始化方法,用于设置测试前的环境。 Args: 无参数。 Returns: 无返回值。 """ self.app_id = "2a19f6dd-de02-46d9-841d-ef5c52b00466" def test_appbuilder_client_trace_un_stream(self): """ 测试AppBuilderClient的跟踪功能 Args: 无 Returns: 无返回值,该函数主要用于测试跟踪功能 """ tracer=AppBuilderTracer( enable_phoenix = True, enable_console = False, ) tracer.start_trace() builder = appbuilder.AppBuilderClient(self.app_id) conversation_id = builder.create_conversation() # test stream = True msg = builder.run(conversation_id=conversation_id, query="人参有什么用?",stream=False) print(msg) tracer.end_trace() def test_appbuilder_client_trace_stream(self): """ 测试AppBuilderClient的跟踪功能 Args: 无 Returns: 无返回值,该函数主要用于测试跟踪功能 """ tracer=AppBuilderTracer( enable_phoenix = True, enable_console = False, ) tracer.start_trace() builder = appbuilder.AppBuilderClient(self.app_id) conversation_id = builder.create_conversation() # test stream = True msg = builder.run(conversation_id=conversation_id, query="人参有什么用?",stream=True) for m in msg.content: pass # test get_app_list get_app_list() tracer.end_trace() def test_trace_tracer(self): """ 测试AppbuilderInstrumentor类的trace_tracer方法。 Args: 无参数。 Returns: 无返回值。 """ tracer=AppbuilderInstrumentor() tracer.instrumentation_dependencies() tracer._instrument() def test_appbuilder_phoenix_run(self): """ 测试appbuilder_phoenix_run方法 Args: 无参数。 Returns: 无返回值。 Raises: TypeError: 当调用runtime_main()或stop_phoenix()函数时,预期会抛出TypeError异常。 """ with self.assertRaises(ImportError): runtime_main() with self.assertRaises(ImportError): launch_phoenix() with self.assertRaises(ImportError): stop_phoenix() if __name__ == '__main__': unittest.main() ================================================ FILE: python/tests/test_appbuilder_components_trace.py ================================================ # Copyright (c) 2024 Baidu, Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import unittest import requests import appbuilder import os from appbuilder import AppBuilderTracer TEST_QUERY = '澳门新麻蒲烤肉店每天开门吗?' TEST_CONTEXT = \ ('澳门美食: 澳门新麻蒲韩国烤肉店\n' '在澳门一年四季之中除了火锅,烤肉也相当受欢迎。提到韩烧,有一间令我印象最深刻,就是号称韩国第一的烤肉店-新麻蒲韩国烤肉店,光是韩国的分店便多' '达四百多间,海外分店更是遍布世界各地,2016年便落户澳门筷子基区,在原本已经食肆林立的地方一起百花齐放!店内的装修跟韩国分店还完度几乎没差,让' '食客彷如置身于韩国的感觉,还要大赞其抽风系统不俗,离开时身上都不会沾上烤肉味耶!\n' '时间:周一至周日 下午5:00 - 上午3:00\n' '电话:+853 2823 4012\n' '地址:澳门筷子基船澳街海擎天第三座地下O号铺96号\n' '必食推介:\n' '护心肉二人套餐\n' '来新麻蒲必试的有两样东西,现在差不多每间烤肉店都有炉边烤蛋,但大家知道吗?原来新麻蒲就是炉边烤蛋的开创者,既然是始祖,这已经是个非吃不可的理' '由!还有一款必试的就是护心肉,即是猪的横隔膜与肝中间的部分,每头猪也只有200克这种肉,非常珍贵,其味道吃起来有种独特的肉香味,跟牛护心肉一样' '精彩!\n' '秘制猪皮\n' '很多怕胖的女生看到猪皮就怕怕,但其实猪皮含有大量胶原蛋白,营养价值很高呢!这里红通通的猪皮还经过韩国秘制酱汁处理过,会有一点点辣味。烤猪皮的' '时候也需特别注意火侯,这样吃起来才会有外脆内Q的口感!') TEST_ANSWER = '澳门新麻蒲烤肉店并不是每天开门,周日休息。' class TestAppBuilderComponentsTrace(unittest.TestCase): def setUp(self): """ 初始化函数,用于设置测试所需的变量和对象。 Args: 无参数。 Returns: 无返回值。 """ self.image_url = "https://bj.bcebos.com/v1/appbuilder/table_ocr_test.png?"\ "authorization=bce-auth-v1%2FALTAKGa8m4qCUasgoljdEDAzLm%2F2024-01-24T12%3A37%3A09Z%2F-1%2Fhost%2Fab528a5a9120d328dc6d18c6"\ "064079145ff4698856f477b820147768fc2187d3" self.table_ocr = appbuilder.TableOCR() self.play = appbuilder.Playground(prompt_template="你好,{name},我是{bot_name},{bot_name}是一个{bot_type},我可以{bot_function},你可以问我{bot_question}。", model="DeepSeek-V3.1") model_name = "DeepSeek-V3.1" secret_key = os.getenv('SECRET_KEY', None) self.hallucination_detection = appbuilder.HallucinationDetection(model=model_name, secret_key=secret_key) def test_trace(self): """ 测试追踪功能,包括ASR运行、工具评估、playground运行和幻觉检测工具评估。 Args: 无参数。 Returns: 无返回值。 """ tracer=AppBuilderTracer( enable_phoenix = True, enable_console = True, ) tracer.start_trace() # test asr run and tool_eval out = self.table_ocr.run(appbuilder.Message(content={"url": self.image_url})) print(out) result = self.table_ocr.tool_eval(name="asr", streaming=True, file_names=[self.image_url]) for res in result: print(res) # test playground run msg = appbuilder.Message({ "name": "小明", "bot_name": "机器人", "bot_type": "聊天机器人", "bot_function": "聊天", "bot_question": "你好吗?" }) answer = self.play.run(message=msg, stream=False, temperature=1) # test hallucination_detection tool_eval query = TEST_QUERY context = TEST_CONTEXT answer = TEST_ANSWER model_configs = {'temperature': 0.5, 'top_p': 0.5} answer = self.hallucination_detection.tool_eval(name='', stream=True, query=query, context=context, answer=answer, model_configs=model_configs) for res in answer: print(res) tracer.end_trace() if __name__ == '__main__': unittest.main() ================================================ FILE: python/tests/test_appbuilder_core_components_retriever.py ================================================ # Copyright (c) 2023 Baidu, Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import os import unittest import subprocess import sys import time from appbuilder.core.components.retriever.baidu_vdb.component import _try_import,BaiduVDBVectorStoreIndex class TestAppbuilderCoreComponentsRetriever__try_import(unittest.TestCase): def test_baidu_vdb_baiduvdb_retriever_try_import(self): subprocess.check_call([sys.executable, "-m", "pip", "uninstall", "-y", "pymochow"]) with self.assertRaises(ImportError): _try_import() subprocess.check_call([sys.executable, "-m", "pip", "install", "pymochow"]) _try_import() def test_baidu_vdb_baiduvdb_retriever_BaiduVDBVectorStoreIndex(self): # test not isinstance(instance_id, str): with self.assertRaises(TypeError): BaiduVDBVectorStoreIndex( instance_id = 1, api_key="key", ) # test not isinstance(api_key, str): with self.assertRaises(TypeError): BaiduVDBVectorStoreIndex( instance_id = "test", api_key=1, ) if __name__ == '__main__': unittest.main() ================================================ FILE: python/tests/test_appbuilder_sentry_trace_off.py ================================================ # Copyright (c) 2024 Baidu, Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import os import uuid import unittest import subprocess import importlib import requests import logging import appbuilder from appbuilder import AppBuilderTracer, AppbuilderInstrumentor from appbuilder.utils.trace._function import _components_run_trace_with_sentry,_components_stream_run_trace_with_sentry logging.basicConfig(level=logging.INFO) class TestAppbuilderForSentryOff(unittest.TestCase): def test_sentry_inport_error(self): """ 测试sentry导入错误的情况 Args: 无 Returns: 无返回值,该函数主要用于测试 Raises: ImportError: 当sentry-sdk库不存在时,会触发ImportError异常 """ # 配置测试环境 try: subprocess.check_output(['python3','-m','pip', 'uninstall', 'sentry-sdk', '-y']) except Exception as e: print('pip uninstall sentry-sdk failed') os.environ['ENABLE_SENTRY_TRACE'] = 'true' os.environ['SENTRY_DSN'] = 'test' with self.assertRaises(ImportError): tracer = AppBuilderTracer() tracer.start_trace() with self.assertRaises(ImportError): arg = () kwarg = {} _components_run_trace_with_sentry(func = 'func', args = arg, kwargs = kwarg) with self.assertRaises(ImportError): arg = () kwarg = {} res = _components_stream_run_trace_with_sentry(func = 'func', args = arg, kwargs = kwarg) for r in res: pass if __name__ == '__main__': unittest.main() ================================================ FILE: python/tests/test_appbuilder_sentry_trace_on.py ================================================ # Copyright (c) 2024 Baidu, Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import os import uuid import unittest import subprocess import importlib import requests import logging import appbuilder from appbuilder import AppbuilderInstrumentor, StyleRewrite from appbuilder.core.components.v2 import StyleRewrite as StyleRewriteV2 logging.basicConfig(level=logging.INFO) class TestAppbuilderForSentryOff(unittest.TestCase): def test_sentry_normal(self): """ 测试Sentry的追踪功能是否正常。 Args: 无。 Returns: 无返回值。 Raises: ImportError: 如果未安装sentry-sdk库,则抛出此异常。 """ try: subprocess.check_output(['python3','-m','pip', 'install', 'sentry-sdk==1.44.1']) except Exception as e: print('pip uninstall sentry-sdk failed') os.environ["ENABLE_SENTRY_TRACE"] = "true" os.environ["SENTRY_DSN"] = "test" os.environ["APPBUILDER_TRACE_DEBUG"] = "true" # 启动跟踪器(仅测试Sentry Trace功能) tracer = AppbuilderInstrumentor() tracer._instrument() # 启动Sentry try: import sentry_sdk except ImportError: raise ImportError("Please install `sentry-sdk` first.") try: sentry_sdk.init( dsn="https://c6f17a6bb2163ad7b10760e70cfdba16@appsentry-sandbox.now.baidu-int.com/59", traces_sample_rate=1.0, ) logging.info("Sentry SDK is initialized successfully.") # _patch_sentry_sdk_trace_id() logging.info("Patch_sentry_sdk_trace_id is initialized successfully.") except Exception as e: print(e) # 启动事务 with sentry_sdk.start_transaction(op="task", name="UT-Components-trace-test"): # test Components run sr = StyleRewrite(model="DeepSeek-V3.1") text = "成都是个包容的城市" style = "直播话术" msg = appbuilder.Message(content=text) run_out = sr.run(message=msg, style=style) print(run_out) sr = StyleRewrite(model="DeepSeek-V3.1") tool_eval_out = sr.tool_eval(name="name", query=text, style=style, streaming=True) for res in tool_eval_out: print(res) # test Components v2 tool_eval sr_v2 = StyleRewriteV2(model="DeepSeek-V3.1") text = "成都是个包容的城市" style = "直播话术" tool_eval_out = sr_v2.tool_eval(query=text, style=style) for res in tool_eval_out: print(res) # 清理测试环境 try: subprocess.check_output(['python3','-m','pip', 'uninstall', 'sentry-sdk', '-y']) except Exception as e: print('pip uninstall sentry-sdk failed') del os.environ["ENABLE_SENTRY_TRACE"] del os.environ["SENTRY_DSN"] del os.environ["APPBUILDER_TRACE_DEBUG"] if __name__ == '__main__': unittest.main() ================================================ FILE: python/tests/test_appbuilder_trace_raise_error.py ================================================ # Copyright (c) 2024 Baidu, Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import os import unittest from opentelemetry import trace from appbuilder import AppbuilderTraceException from appbuilder.utils.trace._function import _input,_client_trace_generator,_assistant_stream_run_with_handler_output class TestAppbuilderTraceRaiseError(unittest.TestCase): def setUp(self): tracer_provider = trace.get_tracer_provider() tracer = trace.get_tracer( instrumenting_module_name=__name__, tracer_provider=tracer_provider, ) self.tracer = tracer def test_appbuilder_trace_raise_error_input(self): """ 测试AppBuilder跟踪时输入错误时抛出AppbuilderTraceException异常 Args: 无参数 Returns: 无返回值 Raises: AppbuilderTraceException: 如果输入不满足要求,抛出AppbuilderTraceException异常 """ def sample_function(x): return x * 2 with self.assertRaises(AppbuilderTraceException): _input([sample_function], 2, 3) def test_appbuilder_trace_raise_error_client_trace_generator(self): generator = _client_trace_generator('generator', self.tracer, 'parent_context') with self.assertRaises(AppbuilderTraceException): next(generator) def test_appbuilder_trace_raise_error_assistant_stream_run_with_handler_output(self): generator = _assistant_stream_run_with_handler_output(None, self.tracer, None) with self.assertRaises(AppbuilderTraceException): next(generator) if __name__ == '__main__': unittest.main() ================================================ FILE: python/tests/test_asr.py ================================================ import unittest import uuid import requests import appbuilder from appbuilder.core._exception import InvalidRequestArgumentError from appbuilder.core.components.asr.model import ShortSpeechRecognitionRequest, ShortSpeechRecognitionResponse import os @unittest.skip("测试API超限,暂时跳过") class TestASRComponent(unittest.TestCase): def setUp(self): """ 设置环境变量。 Args: None Returns: None. """ self.audio_file_url = "https://bj.bcebos.com/v1/appbuilder/asr_test.pcm?authorization=bce-auth-v1" \ "%2FALTAKGa8m4qCUasgoljdEDAzLm%2F2024-01-11T10%3A56%3A41Z%2F-1%2Fhost" \ "%2Fa6c4d2ca8a3f0259f4cae8ae3fa98a9f75afde1a063eaec04847c99ab7d1e411" self.audio_speech_too_long_url = ("https://bj.bcebos.com/v1/agi-dev-platform-sdk-test/speech_too_long.wav?" "authorization=bce-auth-v1%2FALTAKGa8m4qCUasgoljdEDAzLm%2F2024-07-01T03%3A41%3A00Z%2F300%2Fhost%2Febd71063a7ada87a722a6c9a801d95bd41f75f363236623882586ac9d37e7665") self.asr = appbuilder.ASR() def test_run(self): """ 使用原始语音文件进行单测 Args: None Returns: None """ raw_audio = requests.get(self.audio_file_url).content inp = appbuilder.Message(content={"raw_audio": raw_audio}) out = self.asr.run(inp) self.assertIsNotNone(out) self.assertIsInstance(out, appbuilder.Message) self.assertIn('result', out.content) def test_run_different_rate(self): """ 使用不同rate进行单测 Args: None Returns: None """ raw_audio = requests.get(self.audio_file_url).content inp = appbuilder.Message(content={"raw_audio": raw_audio}) try: out = self.asr.run(inp, rate=8000) self.assertIsNotNone(out) self.assertIsInstance(out, appbuilder.Message) except appbuilder.AppBuilderServerException as ex: self.assertIsNotNone(ex, "请求捕获到异常") def test_run_invalid_audio(self): """ 使用非法语音文件进行单测 Args: None Returns: None """ inp = appbuilder.Message(content={"raw_audio": b"invalid"}) with self.assertRaises(Exception): self.asr.run(inp) def test_recognition(self): """ recognition方法单测 Args: None Returns: None """ raw_audio = requests.get(self.audio_file_url).content request = ShortSpeechRecognitionRequest() request.format = 'pcm' request.rate = 16000 request.cuid = str(uuid.uuid4()) request.dev_pid = "80001" request.speech = raw_audio response = self.asr._recognize(request) self.assertIsNotNone(response) self.assertIsInstance(response, ShortSpeechRecognitionResponse) def test_recognition_invalid_request(self): """ recognition方法单测,非法请求体 Args: None Returns: None """ with self.assertRaises(Exception): self.asr._recognize(None) def test_check_service_error(self): """ check_service_error方法单测 Args: None Returns: None """ data = {'err_msg': 'Error', 'err_no': 1} with self.assertRaises(appbuilder.AppBuilderServerException): self.asr._check_service_error("", data) data = {'err_msg': 'No Error', 'err_no': 0} self.assertIsNone(self.asr._check_service_error("", data)) def test_tool_eval_valid(self): """测试 tool 方法对有效请求的处理。""" result = self.asr.tool_eval(name="asr", streaming=True, file_url=self.audio_file_url) res = [item for item in result] self.assertNotEqual(len(res), 0) def test_tool_eval_invalid(self): """测试 tool 方法对无效请求的处理。""" with self.assertRaises(InvalidRequestArgumentError): result = self.asr.tool_eval(name="asr", streaming=True) next(result) def test_tool_eval_speech_too_long(self): """测试 tool 方法对有效请求的处理。""" result = self.asr.tool_eval(name="asr", streaming=True, file_url=self.audio_speech_too_long_url) res = [item for item in result] self.assertNotEqual(len(res), 0) if __name__ == '__main__': unittest.main() ================================================ FILE: python/tests/test_assistant_basic_import.py ================================================ import unittest import os import appbuilder @unittest.skip("QPS超限") class TestAssistantImport(unittest.TestCase): def setUp(self): os.environ["APPBUILDER_TOKEN"] = os.environ["APPBUILDER_TOKEN_V2"] def test_assistants_beta_import(self): from appbuilder import assistant from appbuilder.core.assistant.base import BetaAssistant obj = assistant self.assertIsInstance(obj, BetaAssistant) obj_dir = obj.__dir__() self.assertIn("assistants", obj_dir) self.assertIn("threads", obj_dir) def test_assistants_obj_import(self): from appbuilder import assistant obj = assistant.assistants from appbuilder.core.assistant.assistants import Assistants self.assertIsInstance(obj, Assistants) obj_dir = obj.__dir__() self.assertIn("create", obj_dir) def test_threads_obj_import(self): from appbuilder import assistant obj = assistant.threads from appbuilder.core.assistant.threads import Threads self.assertIsInstance(obj, Threads) obj_dir = obj.__dir__() self.assertIn("create", obj_dir) def test_messages_obj_import(self): from appbuilder import assistant obj = assistant.threads.messages from appbuilder.core.assistant.threads.messages import Messages self.assertIsInstance(obj, Messages) obj_dir = obj.__dir__() self.assertIn("create", obj_dir) def test_runs_obj_import(self): from appbuilder import assistant obj = assistant.threads.runs from appbuilder.core.assistant.threads.runs import Runs self.assertIsInstance(obj, Runs) obj_dir = obj.__dir__() self.assertIn("run", obj_dir) self.assertIn("stream_run", obj_dir) self.assertIn("submit_tool_outputs", obj_dir) self.assertIn("cancel", obj_dir) def test_type_obj_import(self): from appbuilder import assistant type_folder = assistant.type assistant_type = assistant.assistant_type thread_type = assistant.thread_type public_type = assistant.public_type if __name__ == '__main__': unittest.main() ================================================ FILE: python/tests/test_assistant_class_assistans.py ================================================ import unittest import os import appbuilder from tests.pytest_utils import Utils @unittest.skip("QPS超限") class TestAssistant(unittest.TestCase): def setUp(self): os.environ["APPBUILDER_TOKEN"] = os.environ["APPBUILDER_TOKEN_V2"] def test_assistants_create_v1(self): from appbuilder.core.assistant.type import assistant_type assistant = appbuilder.assistant.assistants.create( model = "ERNIE-4.0T-8K", name="Abc-_123", description="test", ) self.assertIsInstance(assistant, assistant_type.AssistantCreateResponse) self.assertEqual(assistant.name, "Abc-_123") self.assertEqual(assistant.description, "test") def test_assistants_create_v2(self): try: appbuilder.assistant.assistants.create( model = "ERNIE-4.0T-8K", name="Abc-_123@", description="test"*512, response_format="other", instructions="test"*4096, thought_instructions="test"*4096, chat_instructions="test"*4096, file_ids=["test"]*11, ) except Exception as e: self.assertEqual(e.error_count(), 7) def test_assistants_create_v3(self): try: appbuilder.assistant.assistants.create( model = "ERNIE-4.0T-8K", name="Abc-_123", description="test", metadata={ "key" * 64 : "value" * 512 } ) except Exception as e: self.assertIn("metadata", e.description) def test_assistants_create_v4(self): from appbuilder.core.assistant.type import assistant_type assistant=appbuilder.assistant.assistants.create( model = "ERNIE-4.0T-8K", name="测试", description="test", metadata={ "key": "value", } ) self.assertIsInstance(assistant, assistant_type.AssistantCreateResponse) def test_Assistant(self): from appbuilder.core.assistant.type import assistant_type assistant = appbuilder.assistant.assistants.create( model = "ERNIE-4.0T-8K", name="Abc-_123", description="test", ) # test assistant update assistant_update = appbuilder.assistant.assistants.update( assistant_id = assistant.id, model="ERNIE-4.0T-8K", name="Test_Name", description = "test" ) self.assertIsInstance(assistant_update, assistant_type.AssistantUpdateResponse) # test assistant list assistant_list = appbuilder.assistant.assistants.list() self.assertIsInstance(assistant_list, assistant_type.AssistantListResponse) # test assistant query assistant_query = appbuilder.assistant.assistants.query( assistant_id = assistant.id, ) self.assertIsInstance(assistant_query, assistant_type.AssistantQueryResponse) # test assistant mount_files # create file file_path = Utils.get_data_file("qa_doc_parser_extract_table_from_doc.png") file = appbuilder.assistant.assistants.files.create(file_path=file_path) with self.assertRaises(FileNotFoundError): appbuilder.assistant.assistants.mount_files( assistant_id = assistant.id, file_id = "test_not_exist", ) assistant_mount = appbuilder.assistant.assistants.mount_files( assistant_id = assistant.id, file_id = file.id, ) self.assertIsInstance(assistant_mount, assistant_type.AssistantFilesResponse) # test assistant files list assistant_files_list = appbuilder.assistant.assistants.mounted_files_list( assistant_id = assistant.id, ) self.assertIsInstance(assistant_files_list, assistant_type.AssistantMountedFilesListResponse) self.assertEqual(len(assistant_files_list.data), 1) # test assistant unmount_files with self.assertRaises(FileNotFoundError): appbuilder.assistant.assistants.unmount_files( assistant_id = assistant.id, file_id = "test_not_exist", ) assistant_files_delete = appbuilder.assistant.assistants.unmount_files( assistant_id = assistant.id, file_id = file.id, ) self.assertIsInstance(assistant_files_delete, assistant_type.AssistantFilesDeleteResponse) # test assistant delete assistant_delete = appbuilder.assistant.assistants.delete( assistant_id = assistant.id, ) self.assertIsInstance(assistant_delete, assistant_type.AssistantDeleteResponse) def test_unmote_raise(self): with self.assertRaises(TypeError): appbuilder.assistant.assistants.unmount_files( assistant_id = "test", file_id = 123, ) with self.assertRaises(TypeError): appbuilder.assistant.assistants.unmount_files( assistant_id = 123, file_id = "test", ) with self.assertRaises(ValueError): appbuilder.assistant.assistants.unmount_files( assistant_id = "", file_id = "test", ) with self.assertRaises(ValueError): appbuilder.assistant.assistants.unmount_files( assistant_id = "test", file_id = "", ) def test_mount_raise(self): with self.assertRaises(TypeError): appbuilder.assistant.assistants.mount_files( assistant_id = "test", file_id = 123, ) with self.assertRaises(TypeError): appbuilder.assistant.assistants.mount_files( assistant_id = 123, file_id = "test", ) with self.assertRaises(ValueError): appbuilder.assistant.assistants.mount_files( assistant_id = "", file_id = "test", ) with self.assertRaises(ValueError): appbuilder.assistant.assistants.mount_files( assistant_id = "test", file_id = "", ) if __name__ == '__main__': unittest.main() ================================================ FILE: python/tests/test_assistant_class_files.py ================================================ import unittest import os import appbuilder from appbuilder.core._exception import AssistantServerException from tests.pytest_utils import Utils @unittest.skip("QPS超限") class TestFilesCreate(unittest.TestCase): def setUp(self): os.environ["APPBUILDER_TOKEN"] = os.environ["APPBUILDER_TOKEN_V2"] def test_create_files_v1(self): from appbuilder.core.assistant.type import assistant_type file_path = Utils.get_data_file("qa_doc_parser_extract_table_from_doc.png") file = appbuilder.assistant.assistants.files.create(file_path=file_path) self.assertIsInstance(file, assistant_type.AssistantFilesCreateResponse) def test_create_files_v2(self): from appbuilder.core.assistant.type import assistant_type file_path = "test" with self.assertRaises(ValueError): file = appbuilder.assistant.assistants.files.create(file_path=file_path) def test_files(self): from appbuilder.core.assistant.type import assistant_type current_dir = os.path.dirname(os.path.abspath(__file__)) data_dir = os.path.join(current_dir, "data") file_path = os.path.join(data_dir, "qa_doc_parser_extract_table_from_doc.png") file = appbuilder.assistant.assistants.files.create(file_path=file_path) self.assertIsInstance(file, assistant_type.AssistantFilesCreateResponse) # test list files_list = appbuilder.assistant.assistants.files.list() self.assertIsInstance(files_list, assistant_type.AssistantFilesListResponse) # test query with self.assertRaises(TypeError): appbuilder.assistant.assistants.files.query(file_id=123) with self.assertRaises(ValueError): appbuilder.assistant.assistants.files.query(file_id="test") files_query = appbuilder.assistant.assistants.files.query(file_id=file.id) self.assertIsInstance(files_query, assistant_type.AssistantFilesQueryResponse) # test content with self.assertRaises(TypeError): appbuilder.assistant.assistants.files.content(file_id=123) with self.assertRaises(FileNotFoundError): appbuilder.assistant.assistants.files.content(file_id='test_not_exist') files_content=appbuilder.assistant.assistants.files.content(file_id=file.id) self.assertIsInstance(files_content, assistant_type.AssistantFilesContentResponse) self.assertIsInstance(files_content.content, bytes) # test download with self.assertRaises(TypeError): appbuilder.assistant.assistants.files.download(file_id='test', file_path=123) with self.assertRaises(TypeError): appbuilder.assistant.assistants.files.download(file_id=123, file_path=data_dir) with self.assertRaises(FileNotFoundError): appbuilder.assistant.assistants.files.download(file_id='test_not_exist', file_path=data_dir) with self.assertRaises(ValueError): appbuilder.assistant.assistants.files.download(file_id='', file_path=data_dir) with self.assertRaises(FileNotFoundError): appbuilder.assistant.assistants.files.download(file_id=file.id, file_path=os.path.join(data_dir, 'data/')) with self.assertRaises(ValueError): try: with open(os.path.join(data_dir, 'test'), 'wb') as f: f.write(b'test') appbuilder.assistant.assistants.files.download(file_id=file.id, file_path=os.path.join(data_dir, 'test')) finally: os.remove(os.path.join(data_dir, 'test')) appbuilder.assistant.assistants.files.download(file_id=file.id, file_path=data_dir) # test delete files_delete = appbuilder.assistant.assistants.files.delete(file_id=file.id) self.assertIsInstance(files_delete, assistant_type.AssistantFilesDeleteResponse) if __name__ == '__main__': unittest.main() ================================================ FILE: python/tests/test_assistant_class_messages.py ================================================ import unittest import os import appbuilder from appbuilder.core._exception import AssistantServerException @unittest.skip("QPS超限") class TestMessageCreate(unittest.TestCase): def setUp(self): os.environ["APPBUILDER_TOKEN"] = os.environ["APPBUILDER_TOKEN_V2"] def test_messages_create_v1(self): from appbuilder.core.assistant.type import thread_type thread = appbuilder.assistant.threads.create() message = appbuilder.assistant.threads.messages.create( thread_id=thread.id, content="hello world" ) self.assertIsInstance(message, thread_type.AssistantMessageCreateResponse) self.assertEqual(message.thread_id, thread.id) def test_messages_create_v2(self): from appbuilder.core.assistant.type import thread_type thread = appbuilder.assistant.threads.create() try: appbuilder.assistant.threads.messages.create( thread_id=thread.id, content="hello world", role='custom', file_ids=["file_id"]*11 ) except Exception as e: self.assertEqual(e.error_count(), 2) def test_messages(self): from appbuilder.core.assistant.type import thread_type thread = appbuilder.assistant.threads.create() msg = appbuilder.assistant.threads.messages.create( thread_id=thread.id, content="hello world?" ) # test list msg_list = appbuilder.assistant.threads.messages.list( thread_id=msg.thread_id, limit=1 ) self.assertIsInstance(msg_list, thread_type.AssistantMessageListResponse) # test query msg_query = appbuilder.assistant.threads.messages.query( thread_id=msg.thread_id, message_id=msg.id ) self.assertIsInstance(msg_query, thread_type.AssistantMessageQueryResponse) # test update msg_update= appbuilder.assistant.threads.messages.update( thread_id=msg.thread_id, message_id=msg.id, content='你好' ) self.assertIsInstance(msg_update, thread_type.AssistantMessageUpdateResponse) # test file msg_files = appbuilder.assistant.threads.messages.files( thread_id=msg_update.thread_id, message_id=msg_update.id, limit=1 ) self.assertIsInstance(msg_files, thread_type.AssistantMessageFilesResponse) if __name__ == '__main__': unittest.main() ================================================ FILE: python/tests/test_assistant_class_runs.py ================================================ import unittest import os import appbuilder # from tests.pytest_utils import Utils import random import string import os class Utils(object): """ utils 方法父类 """ @staticmethod def get_random_string(str_len, prefix=None): """ 生成随机字符串,可指定前缀 """ gen_name = ''.join( random.choice(string.ascii_letters + string.digits) for _ in range(str_len) ) if prefix: name = str(prefix) + gen_name else: name = gen_name return name @staticmethod def get_data_file(filename): current_dir = os.path.dirname(os.path.abspath(__file__)) full_file_path = os.path.join(current_dir, "data", filename) return full_file_path def get_cur_whether(location:str, unit:str): return "{} 的当前温度是30 {}".format(location, unit) @unittest.skip("QPS超限") class TestFunctionCall(unittest.TestCase): def setUp(self): os.environ["APPBUILDER_TOKEN"] = os.environ["APPBUILDER_TOKEN_V2"] def test_run_create_v1(self): from appbuilder.core.assistant.type import thread_type assistant = appbuilder.assistant.assistants.create( name="test_assistant", description="test assistant", instructions="每句话回复前都加上我是秦始皇" ) file_path = Utils.get_data_file("qa_doc_parser_extract_table_from_doc.png") file = appbuilder.assistant.assistants.files.create(file_path) self.assertIsInstance(file, appbuilder.assistant.type.AssistantFilesCreateResponse) thread = appbuilder.assistant.threads.create() appbuilder.assistant.threads.messages.create( thread_id=thread.id, content="hello world", file_ids=[file.id] ) model_parameters = appbuilder.assistant.public_type.AssistantModelParameters( chat_parameters = appbuilder.assistant.public_type.AssistantChatParameters( temperature = 0.8, top_p = 0.8, penalty_score = 1.0 ), thought_parameters = appbuilder.assistant.public_type.AssistantThoughtParameters( temperature = 0.01, top_p = 0.0, penalty_score = 1.0 ) ) run_result = appbuilder.assistant.threads.runs.run( thread_id=thread.id, assistant_id=assistant.id, model_parameters=model_parameters ) self.assertIsInstance(run_result, thread_type.RunResult) self.assertEqual(run_result.assistant_id, assistant.id) self.assertEqual(run_result.thread_id, thread.id) self.assertEqual(run_result.status, "completed") self.assertIn("我是秦始皇", run_result.final_answer.message.content[0].text.value) def test_run_create_v2(self): assistant = appbuilder.assistant.assistants.create( name="test_assistant", description="test assistant", instructions="每句话回复前都加上我是秦始皇" ) thread = appbuilder.assistant.threads.create() appbuilder.assistant.threads.messages.create( thread_id=thread.id, content="hello world", ) with self.assertRaises(ValueError): appbuilder.assistant.threads.runs.run( assistant_id=assistant.id, ) def test_threads_run_raise(self): run=appbuilder.core.assistant.threads.runs.runs.Runs() with self.assertRaises(ValueError): run._stream(assistant_id='') def test_threads_run_model_raise(self): run=appbuilder.core.assistant.threads.runs.runs.Runs() model_parameters = appbuilder.assistant.public_type.AssistantModelParameters( chat_parameters = appbuilder.assistant.public_type.AssistantChatParameters( temperature = 0.8, top_p = 0.8, penalty_score = 1.0 ), thought_parameters = appbuilder.assistant.public_type.AssistantThoughtParameters( temperature = 0.01, top_p = 0.0, penalty_score = 1.0 ) ) with self.assertRaises(ValueError): model_parameters.chat_parameters.temperature = 10 run.run(assistant_id='test', thread_id = 'thread_id', model_parameters = model_parameters) with self.assertRaises(ValueError): run._stream(assistant_id='test',thread_id = 'thread_id', model_parameters = model_parameters) model_parameters.chat_parameters.temperature = 0.8 with self.assertRaises(ValueError): model_parameters.chat_parameters.top_p = 10 run.run(assistant_id='test', thread_id = 'thread_id', model_parameters = model_parameters) with self.assertRaises(ValueError): run._stream(assistant_id='test', thread_id = 'thread_id', model_parameters = model_parameters) model_parameters.chat_parameters.top_p = 0.8 with self.assertRaises(ValueError): model_parameters.chat_parameters.penalty_score = 10 run.run(assistant_id='test', thread_id = 'thread_id', model_parameters = model_parameters) with self.assertRaises(ValueError): run._stream(assistant_id='test',thread_id = 'thread_id', model_parameters = model_parameters) if __name__ == '__main__': unittest.main() ================================================ FILE: python/tests/test_assistant_class_runs_v2.py ================================================ import unittest import os import appbuilder def get_cur_whether(location:str, unit:str): return "{} 的当前温度是30 {}".format(location, unit) @unittest.skip("QPS超限") class TestFunctionCall(unittest.TestCase): def setUp(self): os.environ["APPBUILDER_TOKEN"] = os.environ["APPBUILDER_TOKEN_V2"] from appbuilder.core.assistant.type import thread_type assistant = appbuilder.assistant.assistants.create( name="test_assistant", description="test assistant", instructions="每句话回复前都加上我是秦始皇" ) thread = appbuilder.assistant.threads.create() appbuilder.assistant.threads.messages.create( thread_id=thread.id, content="hello world", ) run_result = appbuilder.assistant.threads.runs.run( thread_id=thread.id, assistant_id=assistant.id, ) self.thread_id = thread.id self.run_id = run_result.id def test_run_list_v1(self): run_list = appbuilder.assistant.threads.runs.list( thread_id=self.thread_id, limit=5 ) self.assertEqual(len(run_list.data), 1) def test_run_query_v1(self): run = appbuilder.assistant.threads.runs.query( thread_id=self.thread_id, run_id=self.run_id ) self.assertEqual(run.status, "completed") def test_run_step_list_v1(self): step_list = appbuilder.assistant.threads.runs.steps.list( thread_id=self.thread_id, run_id=self.run_id, ) self.assertEqual(len(step_list.data), 1) last_step = step_list.data[-1] last_step_id = last_step.id step = appbuilder.assistant.threads.runs.steps.query( thread_id=self.thread_id, run_id=self.run_id, step_id=last_step_id, ) self.assertEqual(step.id, last_step_id) if __name__ == '__main__': unittest.main() ================================================ FILE: python/tests/test_assistant_class_threads.py ================================================ import unittest import os import appbuilder @unittest.skip("QPS超限") class TestThreadCreate(unittest.TestCase): def setUp(self): os.environ["APPBUILDER_TOKEN"] = os.environ["APPBUILDER_TOKEN_V2"] def test_threads_create_v1(self): from appbuilder.core.assistant.type import thread_type thread = appbuilder.assistant.threads.create() self.assertIsInstance(thread, thread_type.ThreadCreateResponse) def test_threads_create_v2(self): from appbuilder.core.assistant.type import thread_type message = thread_type.AssistantMessage( content="hello world" ) thread = appbuilder.assistant.threads.create([message]) self.assertIsInstance(thread, thread_type.ThreadCreateResponse) def test_threads_create_v3(self): from appbuilder.core.assistant.type import thread_type message = thread_type.AssistantMessage( content="hello world" ) with self.assertRaises(ValueError): appbuilder.assistant.threads.create(message) def test_threads_query_delete(self): from appbuilder.core.assistant.type import thread_type message = thread_type.AssistantMessage( content="hello world" ) thread = appbuilder.assistant.threads.create([message]) # test query thr_query = appbuilder.assistant.threads.query(thread_id=thread.id) self.assertIsInstance(thr_query, thread_type.ThreadQueryResponse) # test update with self.assertRaises(TypeError): appbuilder.assistant.threads.update(thread_id=thread.id,metadata=123) with self.assertRaises(ValueError): appbuilder.assistant.threads.update(thread_id=thread.id,metadata={'finish_reason'*10:'513value'}) with self.assertRaises(ValueError): appbuilder.assistant.threads.update(thread_id=thread.id,metadata={'finish_reason':'513value'*64+'A'}) thr_update = appbuilder.assistant.threads.update(thread_id=thread.id) self.assertIsInstance(thr_update, thread_type.ThreadUpdateResponse) # test delete thr_delete = appbuilder.assistant.threads.delete(thread_id=thread.id) self.assertIsInstance(thr_delete, thread_type.ThreadDeleteResponse) if __name__ == '__main__': unittest.main() ================================================ FILE: python/tests/test_assistant_e2e_funccall.py ================================================ import unittest import pydantic import os import appbuilder def get_cur_whether(location:str, unit:str): return "{} 的当前温度是30 {}".format(location, unit) check_tool = { "name": "get_cur_whether", "description": "这是一个获得指定地点天气的工具", "parameters": { "type": "object", "properties": { "location": { "type": "string", "description": "省,市名,例如:河北省" }, "unit": { "type": "string", "enum": [ "摄氏度", "华氏度" ] } }, "required": [ "location" ] } } @unittest.skip(reason="暂时跳过") class TestFunctionCall(unittest.TestCase): def setUp(self): os.environ["APPBUILDER_TOKEN"] = os.environ["APPBUILDER_TOKEN_V2"] def test_end_to_end(self): assistant = appbuilder.assistant.assistants.create( name="test_function", description="你是一个热心的朋友", instructions="请用友善的语气回答问题", tools=[ {'type': 'function', 'function': check_tool} ] ) thread = appbuilder.assistant.threads.create() appbuilder.assistant.threads.messages.create( thread_id=thread.id, content="今天北京的天气怎么样?", ) run_result = appbuilder.assistant.threads.runs.run( thread_id=thread.id, assistant_id=assistant.id, ) print("\nFirst run result: {}\n".format(run_result)) self.assertEqual(run_result.status, "requires_action") self.assertEqual(run_result.required_action.type, "submit_tool_outputs") self.assertEqual(len(run_result.required_action.submit_tool_outputs.tool_calls), 1) tool_call = run_result.required_action.submit_tool_outputs.tool_calls[0] self.assertEqual(tool_call.type, "function") self.assertEqual(tool_call.function.name, "get_cur_whether") self.assertEqual(tool_call.function.arguments, '{"location":"北京","unit":"摄氏度"}') func_res = get_cur_whether(**eval(tool_call.function.arguments)) print("\nFunction result: {}\n".format(func_res)) run_result = appbuilder.assistant.threads.runs.run( thread_id=thread.id, assistant_id=assistant.id, tool_output={ "tool_call_id":tool_call.id, "output": func_res, "run_id": run_result.id }, ) print("\nFinal run result: {}\n".format(run_result)) self.assertEqual(run_result.status, "completed") self.assertEqual(run_result.required_action, None) self.assertEqual(run_result.assistant_id, assistant.id) self.assertEqual(run_result.thread_id, thread.id) if __name__ == "__main__": unittest.main() ================================================ FILE: python/tests/test_assistant_e2e_funccall_component.py ================================================ import unittest import os import appbuilder @unittest.skip("QPS超限") @unittest.skip(reason="暂时跳过") class TestFunctionCall(unittest.TestCase): def setUp(self): os.environ["APPBUILDER_TOKEN"] = os.environ["APPBUILDER_TOKEN_V2"] def test_end_to_end(self): assistant = appbuilder.assistant.assistants.create( name="test_function", description="你是一个热心的朋友", instructions="请用友善的语气回答问题", tools=[ {'type': 'function', 'function': appbuilder.AnimalRecognition().manifests[0]} ] ) thread = appbuilder.assistant.threads.create() image_url = "https://bj.bcebos.com/v1/appbuilder/animal_recognize_test.png?" \ "authorization=bce-auth-v1%2FALTAKGa8m4qCUasgoljdEDAzLm%2F2024-01-24T" \ "12%3A19%3A16Z%2F-1%2Fhost%2F411bad53034fa8f9c6edbe5c4909d76ecf6fad68" \ "62cf937c03f8c5260d51c6ae" origin_query = "我有一张图片,url是: {}, 麻烦帮我看看这是什么动物".format(image_url) appbuilder.assistant.threads.messages.create( thread_id=thread.id, content=origin_query, ) run_result = appbuilder.assistant.threads.runs.run( thread_id=thread.id, assistant_id=assistant.id, ) print("\nFirst run result: {}\n".format(run_result)) self.assertEqual(run_result.status, "requires_action") self.assertEqual(run_result.required_action.type, "submit_tool_outputs") self.assertEqual(len(run_result.required_action.submit_tool_outputs.tool_calls), 1) tool_call = run_result.required_action.submit_tool_outputs.tool_calls[0] self.assertEqual(tool_call.type, "function") self.assertEqual(tool_call.function.name, "animal_rec") print(tool_call.function.arguments) func_res = appbuilder.AnimalRecognition().tool_eval( name="animal_rec", streaming=True, origin_query=origin_query, **eval(tool_call.function.arguments)) func_message = "" for res in func_res: func_message += res print("\nFunction result: {}\n".format(func_message)) run_result = appbuilder.assistant.threads.runs.run( thread_id=thread.id, assistant_id=assistant.id, tool_output={ "tool_call_id":tool_call.id, "output": func_message, "run_id": run_result.id }, ) print("\nFinal run result: {}\n".format(run_result)) self.assertEqual(run_result.status, "completed") self.assertEqual(run_result.required_action, None) self.assertEqual(run_result.assistant_id, assistant.id) self.assertEqual(run_result.thread_id, thread.id) if __name__ == "__main__": unittest.main() ================================================ FILE: python/tests/test_assistant_e2e_run.py ================================================ import unittest import pydantic import os import appbuilder @unittest.skip("QPS超限") class TestAssistantTalk(unittest.TestCase): def setUp(self): os.environ["APPBUILDER_TOKEN"] = os.environ["APPBUILDER_TOKEN_V2"] def test_end_to_end(self): assistant = appbuilder.assistant.assistants.create( name="test_assistant", description="test assistant", instructions="每句话回复前都加上我是秦始皇" ) thread = appbuilder.assistant.threads.create( [ {'content': 'hello world'} ] ) run_result = appbuilder.assistant.threads.runs.run( thread_id=thread.id, assistant_id=assistant.id, ) self.assertIsInstance(run_result, appbuilder.assistant.type.RunResult) self.assertEqual(run_result.assistant_id, assistant.id) self.assertEqual(run_result.thread_id, thread.id) self.assertEqual(run_result.status, "completed") if __name__ == "__main__": unittest.main() ================================================ FILE: python/tests/test_assistant_e2e_stream_cancel.py ================================================ import unittest import pydantic import os import appbuilder # import json def get_cur_whether(location:str, unit:str): return "{} 的当前温度是30 {}".format(location, unit) check_tool = { "name": "get_cur_whether", "description": "这是一个获得指定地点天气的工具", "parameters": { "type": "object", "properties": { "location": { "type": "string", "description": "省,市名,例如:河北省" }, "unit": { "type": "string", "enum": [ "摄氏度", "华氏度" ] } }, "required": [ "location" ] } } @unittest.skip("暂时跳过") class TestCancel(unittest.TestCase): def setUp(self): os.environ["APPBUILDER_TOKEN"] = os.environ["APPBUILDER_TOKEN_V2"] def test_end_to_end(self): assistant = appbuilder.assistant.assistants.create( name="test_function", description="你是一个热心的朋友", instructions="请用友善的语气回答问题", tools=[ {'type': 'function', 'function': check_tool} ] ) thread = appbuilder.assistant.threads.create() appbuilder.assistant.threads.messages.create( thread_id=thread.id, content="今天北京的天气怎么样?", ) run_result = appbuilder.assistant.threads.runs.stream_run( thread_id=thread.id, assistant_id=assistant.id, ) import json run_id = "" for run_step in run_result: print("\nRun result: {}\n".format( run_step.model_dump_json(indent=4) )) if run_step.status == 'queued': run_obj = run_step.details.run_object run_id = run_obj.id else: appbuilder.assistant.threads.runs.cancel( run_id=run_id, thread_id=thread.id, ) self.assertEqual(run_step.status, 'cancelled') self.assertEqual(run_step.event_type, "run_end") self.assertNotEqual(run_step.details.run_object.cancelled_at, 0) if __name__ == "__main__": unittest.main() ================================================ FILE: python/tests/test_assistant_e2e_stream_event_handler.py ================================================ import unittest import pydantic import os import appbuilder from appbuilder import AssistantEventHandler from appbuilder.core.assistant.type.thread_type import StreamRunMessage check_tool = { "name": "get_cur_whether", "description": "这是一个获得指定地点天气的工具", "parameters": { "type": "object", "properties": { "location": { "type": "string", "description": "省,市名,例如:河北省" }, "unit": { "type": "string", "enum": [ "摄氏度", "华氏度" ] } }, "required": [ "location" ] } } class MyEventHandler(AssistantEventHandler): def get_cur_whether(self, location:str, unit:str): return "{} 的当前温度是30 {}".format(location, unit) def messages(self, messages_event: StreamRunMessage): info = messages_event.content[-1].text.value # 使用红色打印 print("\n\033[1;31m","-> Assistant 回答: ", info, "\033[0m") def tool_calls(self, status_event): current_tool_calls = self.stream_run_context.current_tool_calls for tool_call in current_tool_calls: name = tool_call.function.name if name == "get_cur_whether": arguments = tool_call.function.arguments func_res = self.get_cur_whether(**eval(arguments)) submit_res = appbuilder.assistant.threads.runs.submit_tool_outputs( run_id=self.stream_run_context.current_run_id, thread_id=self.stream_run_context.current_thread_id, tool_outputs=[ {"tool_call_id": tool_call.id, "output": func_res,} ] ) @unittest.skip("QPS超限") class TestFunctionCall(unittest.TestCase): def setUp(self): os.environ["APPBUILDER_TOKEN"] = os.environ["APPBUILDER_TOKEN_V2"] def test_end_to_end_trace(self): from appbuilder.utils.trace.tracer import AppBuilderTracer tracer=AppBuilderTracer( enable_phoenix = True, enable_console = False, ) tracer.start_trace() assistant = appbuilder.assistant.assistants.create( name="test_function", description="你是一个热心的朋友", instructions="请用友善的语气回答问题", tools=[ {'type': 'function', 'function': check_tool} ] ) thread = appbuilder.assistant.threads.create() appbuilder.assistant.threads.messages.create( thread_id=thread.id, content="今天北京的天气怎么样?", ) with appbuilder.assistant.threads.runs.stream_run_with_handler( thread_id=thread.id, assistant_id=assistant.id, event_handler=MyEventHandler(), ) as stream: stream.until_done() tracer.end_trace() def test_end_to_end(self): assistant = appbuilder.assistant.assistants.create( name="test_function", description="你是一个热心的朋友", instructions="请用友善的语气回答问题", tools=[ {'type': 'function', 'function': check_tool} ] ) thread = appbuilder.assistant.threads.create() appbuilder.assistant.threads.messages.create( thread_id=thread.id, content="今天北京的天气怎么样?", ) with appbuilder.assistant.threads.runs.stream_run_with_handler( thread_id=thread.id, assistant_id=assistant.id, event_handler=MyEventHandler(), ) as stream: stream.until_done() if __name__ == "__main__": unittest.main() ================================================ FILE: python/tests/test_assistant_e2e_stream_event_handler_v2.py ================================================ import unittest import pydantic import os import appbuilder from appbuilder import AssistantEventHandler from appbuilder.core.assistant.type.thread_type import StreamRunMessage check_tool = { "name": "get_cur_whether", "description": "这是一个获得指定地点天气的工具", "parameters": { "type": "object", "properties": { "location": { "type": "string", "description": "省,市名,例如:河北省" }, "unit": { "type": "string", "enum": [ "摄氏度", "华氏度" ] } }, "required": [ "location" ] } } @unittest.skip("QPS超限") class MyEventHandler(AssistantEventHandler): def get_cur_whether(self, location:str, unit:str): return "{} 的当前温度是30 {}".format(location, unit) def run_begin(self, status_event): run_id = self.stream_run_context.current_run_id thread_id = self.stream_run_context.current_thread_id print("Run_id: {}, Thread_id: {}".format(run_id, thread_id)) def run_end(self, status_event): print("\n", status_event) def tool_step_begin(self, status_event): step_id = self.stream_run_context.current_run_step_id print("Step_id: {}".format(step_id)) def tool_calls(self, status_event): current_tool_calls = self.stream_run_context.current_tool_calls for tool_call in current_tool_calls: name = tool_call.function.name if name == "get_cur_whether": arguments = tool_call.function.arguments func_res = self.get_cur_whether(**eval(arguments)) submit_res = appbuilder.assistant.threads.runs.submit_tool_outputs( run_id=self.stream_run_context.current_run_id, thread_id=self.stream_run_context.current_thread_id, tool_outputs=[ {"tool_call_id": tool_call.id, "output": func_res,} ] ) class TestFunctionCall(unittest.TestCase): def setUp(self): os.environ["APPBUILDER_TOKEN"] = os.environ["APPBUILDER_TOKEN_V2"] def test_end_to_end(self): assistant = appbuilder.assistant.assistants.create( name="test_function", description="你是一个热心的朋友", instructions="请用友善的语气回答问题", tools=[ {'type': 'function', 'function': check_tool} ] ) thread = appbuilder.assistant.threads.create() appbuilder.assistant.threads.messages.create( thread_id=thread.id, content="今天北京的天气怎么样?", ) with appbuilder.assistant.threads.runs.stream_run_with_handler( thread_id=thread.id, assistant_id=assistant.id, event_handler=MyEventHandler(), ) as stream: for _ in stream: ... if __name__ == "__main__": unittest.main() ================================================ FILE: python/tests/test_assistant_e2e_stream_funccall.py ================================================ import unittest import pydantic import os import appbuilder def get_cur_whether(location:str, unit:str): return "{} 的当前温度是30 {}".format(location, unit) check_tool = { "name": "get_cur_whether", "description": "这是一个获得指定地点天气的工具", "parameters": { "type": "object", "properties": { "location": { "type": "string", "description": "省,市名,例如:河北省" }, "unit": { "type": "string", "enum": [ "摄氏度", "华氏度" ] } }, "required": [ "location" ] } } @unittest.skip("QPS超限") class TestFunctionCall(unittest.TestCase): def setUp(self): os.environ["APPBUILDER_TOKEN"] = os.environ["APPBUILDER_TOKEN_V2"] def test_end_to_end(self): assistant = appbuilder.assistant.assistants.create( name="test_function", description="你是一个热心的朋友", instructions="请用友善的语气回答问题", tools=[ {'type': 'function', 'function': check_tool} ] ) thread = appbuilder.assistant.threads.create() appbuilder.assistant.threads.messages.create( thread_id=thread.id, content="今天北京的天气怎么样?", ) run_result = appbuilder.assistant.threads.runs.stream_run( thread_id=thread.id, assistant_id=assistant.id, ) run_id = "" for run_step in run_result: print("\nRun result: {}\n".format(run_step)) if run_step.status == 'queued': run_obj = run_step.details.run_object run_id = run_obj.id elif run_step.status == 'requires_action': detail = run_step.details tool_call = detail.tool_calls[0] func_res = get_cur_whether(**eval(tool_call.function.arguments)) submit_res = appbuilder.assistant.threads.runs.submit_tool_outputs( run_id=run_id, thread_id=thread.id, tool_outputs=[ {"tool_call_id": tool_call.id, "output": func_res,} ] ) self.assertIsInstance(submit_res, appbuilder.assistant.type.RunResult) self.assertIsInstance(run_step, appbuilder.assistant.type.StreamRunStatus) self.assertEqual(run_step.status, 'completed') self.assertEqual(run_step.event_type, 'run_end') if __name__ == "__main__": unittest.main() ================================================ FILE: python/tests/test_assistant_e2e_stream_run.py ================================================ import unittest import pydantic import os import time import appbuilder @unittest.skip("QPS超限") class TestAssistantStreamTalk(unittest.TestCase): def setUp(self): os.environ["APPBUILDER_TOKEN"] = os.environ["APPBUILDER_TOKEN_V2"] def test_end_to_end(self): begin_time = time.time() last_time = time.time() assistant = appbuilder.assistant.assistants.create( name="test_assistant", description="test assistant", instructions="每句话回复前都加上我是秦始皇" ) thread = appbuilder.assistant.threads.create( [ {'content': 'hello world'} ] ) run_result = appbuilder.assistant.threads.runs.stream_run( thread_id=thread.id, assistant_id=assistant.id, ) for run_step in run_result: current_time = time.time() print(run_step) print("cur step use_time: {} s\n".format(current_time - last_time)) last_time = current_time self.assertIsInstance(run_step, appbuilder.assistant.type.StreamRunStatus) self.assertEqual(run_step.status, 'completed') end_time = time.time() print("total use_time: {} s".format(end_time - begin_time)) if __name__ == "__main__": unittest.main() ================================================ FILE: python/tests/test_async_appbuilder_client.py ================================================ # Copyright (c) 2024 Baidu, Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import unittest import os import asyncio import appbuilder @unittest.skipUnless(os.getenv("TEST_CASE", "UNKNOWN") == "CPU_SERIAL", "") class TestAppBuilderClientAsync(unittest.TestCase): def setUp(self): """ 设置环境变量。 Args: 无参数,默认值为空。 Returns: 无返回值,方法中执行了环境变量的赋值操作。 """ self.app_id = "fb64d96b-f828-4385-ba1d-835298d635a9" def test_async_run_stream(self): appbuilder.logger.setLoglevel("ERROR") async def agent_run(client, conversation_id, text): ans = await client.run(conversation_id, text, stream=True) async for data in ans.content: print(data) async def agent_handle(): client = appbuilder.AsyncAppBuilderClient(self.app_id) conversation_id = await client.create_conversation() task1 = asyncio.create_task( agent_run(client, conversation_id, "最早的邮展")) task2 = asyncio.create_task( agent_run(client, conversation_id, "最早的漫展")) await asyncio.gather(task1, task2) await client.http_client.session.close() loop = asyncio.get_event_loop() loop.run_until_complete(agent_handle()) def test_async_run(self): appbuilder.logger.setLoglevel("ERROR") async def agent_run(client, conversation_id, text): ans = await client.run(conversation_id, text, stream=False) print(ans.content.answer) async def agent_handle(): client = appbuilder.AsyncAppBuilderClient(self.app_id) conversation_id = await client.create_conversation() await client.upload_file(conversation_id, "./data/qa_appbuilder_client_demo.pdf") await client.upload_file( conversation_id=conversation_id, file_url="https://bj.bcebos.com/v1/appbuilder/animal_recognize_test.png?authorization=bce-auth-v1%2FALTAKGa8m4qCUasgoljdEDAzLm%2F2024-01-24T12%3A19%3A16Z%2F-1%2Fhost%2F411bad53034fa8f9c6edbe5c4909d76ecf6fad6862cf937c03f8c5260d51c6ae", ) task1 = asyncio.create_task( agent_run(client, conversation_id, "最早的邮展")) task2 = asyncio.create_task( agent_run(client, conversation_id, "最早的漫展")) await asyncio.gather(task1, task2) await client.http_client.session.close() loop = asyncio.get_event_loop() loop.run_until_complete(agent_handle()) if __name__ == "__main__": unittest.main() ================================================ FILE: python/tests/test_async_appbuilder_client_chatflow.py ================================================ # Copyright (c) 2024 Baidu, Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import os import asyncio import unittest import appbuilder from appbuilder.core.console.appbuilder_client.async_event_handler import ( AsyncAppBuilderEventHandler, ) class MyEventHandler(AsyncAppBuilderEventHandler): def __init__(self): super().__init__() self.interrupt_ids = [] async def handle_content_type(self, run_context, run_response): interrupt_event_id = None event = run_response.events[-1] if event.content_type == "chatflow_interrupt": interrupt_event_id = event.detail.get("interrupt_event_id") if interrupt_event_id is not None: self.interrupt_ids.append(interrupt_event_id) def _create_action(self): if len(self.interrupt_ids) == 0: return None event_id = self.interrupt_ids.pop() return { "action_type": "resume", "parameters": {"interrupt_event": {"id": event_id, "type": "chat"}}, } async def run(self, query=None): await super().new_dialog( query=query, action=self._create_action(), ) def gen_action(self): while True: yield self._create_action() @unittest.skipUnless(os.getenv("TEST_CASE", "UNKNOWN") == "CPU_SERIAL", "") class TestAppBuilderClientChatflow(unittest.TestCase): def setUp(self): """ 设置环境变量。 Args: 无参数,默认值为空。 Returns: 无返回值,方法中执行了环境变量的赋值操作。 """ self.app_id = "4403205e-fb83-4fac-96d8-943bdb63796f" def test_chatflow(self): appbuilder.logger.setLoglevel("DEBUG") async def agent_handle(): client = appbuilder.AsyncAppBuilderClient(self.app_id) conversation_id = await client.create_conversation() event_handler = MyEventHandler() await event_handler.init( appbuilder_client=client, conversation_id=conversation_id, stream=False, query="查天气", ) async for data in event_handler: pass await event_handler.run( query="查航班", ) async for data in event_handler: pass await event_handler.run( query="CA1234", ) async for data in event_handler: pass await event_handler.run( query="北京的", ) async for data in event_handler: pass await client.http_client.session.close() loop = asyncio.get_event_loop() loop.run_until_complete(agent_handle()) def test_chatflow_stream(self): appbuilder.logger.setLoglevel("DEBUG") async def agent_handle(): client = appbuilder.AsyncAppBuilderClient(self.app_id) conversation_id = await client.create_conversation() event_handler = MyEventHandler() await event_handler.init( appbuilder_client=client, conversation_id=conversation_id, stream=True, query="查天气", ) async for data in event_handler: pass await event_handler.run( query="查航班", ) async for data in event_handler: pass await event_handler.run( query="CA1234", ) async for data in event_handler: pass await event_handler.run( query="北京的", ) async for data in event_handler: pass await client.http_client.session.close() loop = asyncio.get_event_loop() loop.run_until_complete(agent_handle()) def test_chatflow_stream(self): appbuilder.logger.setLoglevel("DEBUG") async def agent_handle(): client = appbuilder.AsyncAppBuilderClient(self.app_id) conversation_id = await client.create_conversation() event_handler = MyEventHandler() await event_handler.init( appbuilder_client=client, conversation_id=conversation_id, stream=True, query="查天气", ) async for data in event_handler: pass await event_handler.run( query="查航班", ) async for data in event_handler: pass await event_handler.run( query="CA1234", ) async for data in event_handler: pass await event_handler.run( query="北京的", ) async for data in event_handler: pass await client.http_client.session.close() loop = asyncio.get_event_loop() loop.run_until_complete(agent_handle()) def test_chatflow_multiple_dialog(self): appbuilder.logger.setLoglevel("DEBUG") async def agent_handle(): client = appbuilder.AsyncAppBuilderClient(self.app_id) conversation_id = await client.create_conversation() queries = ["查天气", "查航班", "CA1234", "北京的"] event_handler = MyEventHandler() event_handler = client.run_multiple_dialog_with_handler( conversation_id=conversation_id, queries=queries, event_handler=event_handler, stream=False, actions=event_handler.gen_action(), ) async for data in event_handler: async for answer in data: print(answer) await client.http_client.session.close() loop = asyncio.get_event_loop() loop.run_until_complete(agent_handle()) if __name__ == "__main__": unittest.main() ================================================ FILE: python/tests/test_async_appbuilder_client_custom_metadata.py ================================================ # Copyright (c) 2025 Baidu, Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import asyncio import os import unittest import appbuilder from appbuilder.core.console.appbuilder_client.data_class import CustomMetadata @unittest.skipUnless(os.getenv("TEST_CASE", "UNKNOWN") == "CPU_SERIAL", "") class TestAppBuilderClientFeedback(unittest.TestCase): def setUp(self): """ 设置环境变量。 Args: 无参数,默认值为空。 Returns: 无返回值,方法中执行了环境变量的赋值操作。 """ self.app_id = "a3654cd9-378a-4b46-a33b-2259ca3b304e" def test_async_appbuilder_custom_metadata(self): # 如果app_id为空,则跳过单测执行, 避免单测因配置无效而失败 """ 如果app_id为空,则跳过单测执行, 避免单测因配置无效而失败 Args: self (unittest.TestCase): unittest的TestCase对象 Raises: None: 如果app_id不为空,则不会引发任何异常 unittest.SkipTest (optional): 如果app_id为空,则跳过单测执行 """ async def agent_handle(): if len(self.app_id) == 0: self.skipTest("self.app_id is empty") appbuilder.logger.setLoglevel("ERROR") builder = appbuilder.AsyncAppBuilderClient(self.app_id) conversation_id = await builder.create_conversation() msg = await builder.run(conversation_id, "我要回老家相亲", stream=False, custom_metadata=CustomMetadata( override_role_instruction="# 角色任务\n" + "作为高情商大师,你的主要任务是根据提问,做出最佳的建议。\n" + "\n" + "# 工具能力\n" + "\n" + "无工具集提供\n" + "\n" + "# 要求与限制\n" + "\n" + "1. 输出内容的风格为幽默\n" + "2.输出的字数限制为100字以内\n" + "3. 在每次回复开头都声明今天的天气情况\n" + "4. 在每次回复结尾都声明现在的btc价格", )) print(msg) await builder.http_client.session.close() asyncio.run(agent_handle()) def test_async_appbuilder_custom_metadata_stream(self): # 如果app_id为空,则跳过单测执行, 避免单测因配置无效而失败 """ 如果app_id为空,则跳过单测执行, 避免单测因配置无效而失败 Args: self (unittest.TestCase): unittest的TestCase对象 Raises: None: 如果app_id不为空,则不会引发任何异常 unittest.SkipTest (optional): 如果app_id为空,则跳过单测执行 """ async def agent_handle(): if len(self.app_id) == 0: self.skipTest("self.app_id is empty") appbuilder.logger.setLoglevel("ERROR") builder = appbuilder.AsyncAppBuilderClient(self.app_id) conversation_id = await builder.create_conversation() msg = await builder.run(conversation_id, "我要回老家相亲", stream=True, custom_metadata=CustomMetadata( override_role_instruction="# 角色任务\n" + "作为高情商大师,你的主要任务是根据提问,做出最佳的建议。\n" + "\n" + "# 工具能力\n" + "\n" + "无工具集提供\n" + "\n" + "# 要求与限制\n" + "\n" + "1. 输出内容的风格为幽默\n" + "2.输出的字数限制为100字以内\n" + "3. 在每次回复开头都声明今天的天气情况\n" + "4. 在每次回复结尾都声明现在的btc价格", )) async for content in msg.content: print(content) await builder.http_client.session.close() asyncio.run(agent_handle()) if __name__ == "__main__": unittest.main() ================================================ FILE: python/tests/test_async_appbuilder_client_follow_up_query.py ================================================ # Copyright (c) 2024 Baidu, Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import unittest import os import asyncio import appbuilder from appbuilder.core.console.appbuilder_client.async_event_handler import ( AsyncAppBuilderEventHandler, ) class MyEventHandler(AsyncAppBuilderEventHandler): def __init__(self): super().__init__() self.follow_up_queries = [] async def handle_content_type(self, run_context, run_response): event = run_response.events[-1] if event.content_type == "json" and event.event_type == "FollowUpQuery": follow_up_queries = event.detail.get("json").get("follow_up_querys") self.follow_up_queries.extend(follow_up_queries) @unittest.skipUnless(os.getenv("TEST_CASE", "UNKNOWN") == "CPU_SERIAL", "") class TestAppBuilderClientAsync(unittest.TestCase): def setUp(self): """ 设置环境变量。 Args: 无参数,默认值为空。 Returns: 无返回值,方法中执行了环境变量的赋值操作。 """ self.app_id = "fb64d96b-f828-4385-ba1d-835298d635a9" def test_async_run_stream(self): appbuilder.logger.setLoglevel("ERROR") async def agent_handle(): client = appbuilder.AsyncAppBuilderClient(self.app_id) conversation_id = await client.create_conversation() event_handler = MyEventHandler() with await client.run_with_handler( conversation_id = conversation_id, query = "你能做什么", stream=True, event_handler=event_handler, ) as run: await run.until_done() print(event_handler.follow_up_queries) await client.http_client.session.close() loop = asyncio.get_event_loop() loop.run_until_complete(agent_handle()) if __name__ == "__main__": unittest.main() ================================================ FILE: python/tests/test_async_appbuilder_client_parameters.py ================================================ # Copyright (c) 2025 Baidu, Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import asyncio import unittest import os import appbuilder @unittest.skipUnless(os.getenv("TEST_CASE", "UNKNOWN") == "CPU_SERIAL", "") class TestAppBuilderClientFeedback(unittest.TestCase): def setUp(self): """ 设置环境变量。 Args: 无参数,默认值为空。 Returns: 无返回值,方法中执行了环境变量的赋值操作。 """ self.app_id = "2313e282-baa6-4db6-92dd-a21e99cfd59e" def test_async_appbuilder_parameters(self): # 如果app_id为空,则跳过单测执行, 避免单测因配置无效而失败 """ 如果app_id为空,则跳过单测执行, 避免单测因配置无效而失败 Args: self (unittest.TestCase): unittest的TestCase对象 Raises: None: 如果app_id不为空,则不会引发任何异常 unittest.SkipTest (optional): 如果app_id为空,则跳过单测执行 """ async def agent_handle(): if len(self.app_id) == 0: self.skipTest("self.app_id is empty") appbuilder.logger.setLoglevel("ERROR") builder = appbuilder.AsyncAppBuilderClient(self.app_id) conversation_id = await builder.create_conversation() msg = await builder.run(conversation_id, "国庆长假", stream=False, parameters={"city": "北京"}) print(msg.content.answer) await builder.http_client.session.close() asyncio.run(agent_handle()) def test_async_appbuilder_parameters_stream(self): # 如果app_id为空,则跳过单测执行, 避免单测因配置无效而失败 """ 如果app_id为空,则跳过单测执行, 避免单测因配置无效而失败 Args: self (unittest.TestCase): unittest的TestCase对象 Raises: None: 如果app_id不为空,则不会引发任何异常 unittest.SkipTest (optional): 如果app_id为空,则跳过单测执行 """ async def agent_handle(): if len(self.app_id) == 0: self.skipTest("self.app_id is empty") appbuilder.logger.setLoglevel("ERROR") builder = appbuilder.AsyncAppBuilderClient(self.app_id) conversation_id = await builder.create_conversation() msg = await builder.run(conversation_id, "元旦节", stream=True, parameters={"city": "北京"}) async for content in msg.content: print(content.answer) await builder.http_client.session.close() asyncio.run(agent_handle()) if __name__ == "__main__": unittest.main() ================================================ FILE: python/tests/test_async_appbuilder_client_toolcall.py ================================================ # Copyright (c) 2024 Baidu, Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import unittest import appbuilder import asyncio import os from appbuilder.core.console.appbuilder_client.async_event_handler import ( AsyncAppBuilderEventHandler, ) class MyEventHandler(AsyncAppBuilderEventHandler): def get_current_weather(self, location=None, unit="摄氏度"): return "{} 的温度是 {} {}".format(location, 20, unit) async def interrupt(self, run_context, run_response): thought = run_context.current_thought # 绿色打印 print("\033[1;32m", "-> Agent 中间思考: ", thought, "\033[0m") tool_output = [] for tool_call in run_context.current_tool_calls: tool_call_id = tool_call.id tool_res = self.get_current_weather(**tool_call.function.arguments) # 蓝色打印 print("\033[1;34m", "-> 本地ToolCallId: ", tool_call_id, "\033[0m") print("\033[1;34m", "-> ToolCall结果: ", tool_res, "\033[0m\n") tool_output.append( {"tool_call_id": tool_call_id, "output": tool_res}) return tool_output async def success(self, run_context, run_response): print("\n\033[1;31m", "-> Agent 非流式回答: ", run_response.answer, "\033[0m") @unittest.skipUnless(os.getenv("TEST_CASE", "UNKNOWN") == "CPU_SERIAL", "") class TestAgentRuntime(unittest.TestCase): def setUp(self): """ 设置环境变量。 Args: 无参数,默认值为空。 Returns: 无返回值,方法中执行了环境变量的赋值操作。 """ self.app_id = "b2a972c5-e082-46e5-b313-acbf51792422" def test_appbuilder_client_tool_call(self): # 如果app_id为空,则跳过单测执行, 避免单测因配置无效而失败 """ 如果app_id为空,则跳过单测执行, 避免单测因配置无效而失败 Args: self (unittest.TestCase): unittest的TestCase对象 Raises: None: 如果app_id不为空,则不会引发任何异常 unittest.SkipTest (optional): 如果app_id为空,则跳过单测执行 """ tools = [ { "type": "function", "function": { "name": "get_current_weather", "description": "仅支持中国城市的天气查询,参数location为中国城市名称,其他国家城市不支持天气查询", "parameters": { "type": "object", "properties": { "location": { "type": "string", "description": "城市名,举例:北京", }, "unit": {"type": "string", "enum": ["摄氏度", "华氏度"]}, }, "required": ["location", "unit"], }, }, } ] appbuilder.logger.setLoglevel("DEBUG") async def agent_run(client, query): conversation_id = await client.create_conversation() with await client.run_with_handler( conversation_id=conversation_id, query=query, tools=tools, event_handler=MyEventHandler(), ) as run: await run.until_done() async def agent_handle(): client = appbuilder.AsyncAppBuilderClient(self.app_id) task1 = asyncio.create_task( agent_run(client, "北京的天气怎么样")) task2 = asyncio.create_task( agent_run(client, "上海的天气怎么样")) await asyncio.gather(task1, task2) await client.http_client.session.close() loop = asyncio.get_event_loop() loop.run_until_complete(agent_handle()) if __name__ == "__main__": unittest.main() ================================================ FILE: python/tests/test_base_component.py ================================================ import os import unittest from appbuilder.core.component import Component from appbuilder.core.component import ComponentOutput, Urls, Chart # @unittest.skipUnless(os.getenv("TEST_CASE", "UNKNOWN") == "CPU_PARALLEL", "") class TestBaseComponent(unittest.TestCase): def setUp(self) -> None: self.component = Component() def test_valid_output_with_str(self): out1 = self.component.create_output(type="text", text="test") out2 = self.component.create_output(type="code", text="import appbuilder") out3 = self.component.create_output(type="urls", text="http://www.baidu.com") out4 = self.component.create_output(type="oral_text", text="你是哪个") out5 = self.component.create_output(type="json", text="{'key':'value'}") out6 = self.component.create_output(type="reasoning_content", text="思考过程") self.assertIsInstance(out1, ComponentOutput) self.assertIsInstance(out2, ComponentOutput) self.assertIsInstance(out3, ComponentOutput) self.assertIsInstance(out4, ComponentOutput) self.assertIsInstance(out5, ComponentOutput) self.assertIsInstance(out6, ComponentOutput) def test_valid_output_with_dict(self): output1 = self.component.create_output(type="text", text={"info": "1"}) output2 = self.component.create_output(type="code", text={"code": "1"}) output3 = self.component.create_output(type="urls", text={"url": "http://www.baidu.com"}) output4 = self.component.create_output(type="oral_text", text={"info": "你好"}) output5 = self.component.create_output(type="files", text={"filename": "file.txt", "url": "http://www.baidu.com"}) output6 = self.component.create_output(type="image", text={"filename": "file.png", "url": "http://www.baidu.com"}) output7 = self.component.create_output(type="chart", text={"type": "chart", "data": '{"key": "value"}'}) output8 = self.component.create_output(type="audio", text={"filename": "file.mp3", "url": "http://www.baidu.com"}) output9 = self.component.create_output(type="plan", text={"detail": "hello", "steps":[{"name": "1", "arguments": {"query": "a", "chat_history": "world"}}]}) output10 = self.component.create_output(type="function_call", text={"thought": "hello", "name": "AppBuilder", "arguments": {"query": "a", "chat_history": "world"}}) output11 = self.component.create_output(type="references", text={"type": "engine", "doc_id": "1", "content": "hello, world", "title": "Have a nice day", "source": "bing", "extra": {"key": "value"}}) output12 = self.component.create_output(type="json", text={"data": "value"}) output13 = self.component.create_output(type="browser", text={"query": "go to http://www.baidu.com"}) output14 = self.component.create_output(type="progress", text={"progress": 0.5, "step": "end", "next_step_name": "step2", "message": "message"}) output15 = self.component.create_output(type="reasoning_content", text={"info": "思考过程"}) self.assertIsInstance(output1, ComponentOutput) self.assertIsInstance(output2, ComponentOutput) self.assertIsInstance(output3, ComponentOutput) self.assertIsInstance(output4, ComponentOutput) self.assertIsInstance(output5, ComponentOutput) self.assertIsInstance(output6, ComponentOutput) self.assertIsInstance(output7, ComponentOutput) self.assertIsInstance(output8, ComponentOutput) self.assertIsInstance(output9, ComponentOutput) self.assertIsInstance(output10, ComponentOutput) self.assertIsInstance(output11, ComponentOutput) self.assertIsInstance(output12, ComponentOutput) self.assertIsInstance(output13, ComponentOutput) self.assertIsInstance(output14, ComponentOutput) self.assertIsInstance(output15, ComponentOutput) self.assertEqual(output11.content[0].text.extra["key"], "value") def test_valid_output_type_with_same_key(self): output1 = self.component.create_output(type="urls", text={"url": "http://www.baidu.com"}) self.assertIsInstance(output1.content[0].text, Urls) output2 = self.component.create_output(type="chart", text={"type": "chart_sheet", "data": '{"key": "value"}'}) self.assertIsInstance(output2.content[0].text, Chart) with self.assertRaises(ValueError): output = self.component.create_output(type="files", text=["http://www.baidu.com"]) with self.assertRaises(ValueError): output = self.component.create_output(type="test", text={"filename": "file.txt", "url": ["http://www.baidu.com"]}) def test_invalid_output_type_json(self): with self.assertRaises(ValueError): output = self.component.create_output(type="test", text="") if __name__ == '__main__': unittest.main() ================================================ FILE: python/tests/test_bes_retriever.py ================================================ # Copyright (c) 2023 Baidu, Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import os import unittest import time import appbuilder @unittest.skip("ConnectionError: NotFoundError") class TestBESRetriever(unittest.TestCase): def setUp(self): # for es test self.cluster_id = "..." self.username = "..." self.password = "..." self.embedding = appbuilder.Embedding() self.index_type = "hnsw" self.vector_index = appbuilder.BESVectorStoreIndex(cluster_id=self.cluster_id, user_name=self.username, password=self.password, embedding=self.embedding) def test_generate_id(self): id_length = 16 index_id = appbuilder.BESVectorStoreIndex.generate_id(length=id_length) self.assertEqual(len(index_id), id_length) def test_create_index_mappings_linear(self): index_type = "linear" vector_dims = 100 expected_mappings = { 'properties': { 'vector': { 'type': 'bpack_vector', 'dims': vector_dims, } } } actual_mappings = self.vector_index.create_index_mappings(index_type, vector_dims) self.assertEqual(actual_mappings, expected_mappings) def test_create_index_mappings_hnsw(self): index_type = "hnsw" vector_dims = 100 expected_mappings = { 'properties': { 'vector': { 'type': 'bpack_vector', 'dims': vector_dims, 'index_type': 'hnsw', 'space_type': 'cosine', 'parameters': {"m": 4, "ef_construction": 200} } } } actual_mappings = self.vector_index.create_index_mappings(index_type, vector_dims) self.assertEqual(actual_mappings, expected_mappings) def test_add_segments(self): segments = appbuilder.Message(["文心一言大模型", "百度在线科技有限公司"]) self.vector_index.add_segments(segments) time.sleep(5) self.assertEqual(self.vector_index.get_all_segments()["hits"]["total"]["value"], len(segments.content)) def test_query(self): segments = appbuilder.Message(["文心一言大模型", "百度在线科技有限公司"]) vector_index = appbuilder.BESVectorStoreIndex.from_segments(segments, self.cluster_id, self.username, self.password) query = appbuilder.Message("文心一言") time.sleep(5) retriever = vector_index.as_retriever() res = retriever(query) self.assertEqual(res.content[0]["text"], "文心一言大模型") def test_delete_all_segments(self): segments = appbuilder.Message(["文心一言大模型"]) vector_index = appbuilder.BESVectorStoreIndex.from_segments(segments, self.cluster_id, self.username, self.password) time.sleep(5) vector_index.delete_all_segments() time.sleep(5) self.assertEqual(vector_index.get_all_segments()["hits"]["total"]["value"], 0) if __name__ == '__main__': unittest.main() ================================================ FILE: python/tests/test_component_client.py ================================================ # Copyright (c) 2024 Baidu, Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import unittest import appbuilder import os #unittest.skipUnless(os.getenv("TEST_CASE", "UNKNOWN") == "CPU_SERIAL", "") class TestComponentCLient(unittest.TestCase): def test_component_client(self): appbuilder.logger.setLoglevel("DEBUG") client = appbuilder.ComponentClient() res = client.run(component_id="44205c67-3980-41f7-aad4-37357b577fd0", version="latest", sys_origin_query="北京景点推荐") print(res.content) def test_component_client_stream(self): appbuilder.logger.setLoglevel("DEBUG") client = appbuilder.ComponentClient() res = client.run(component_id="44205c67-3980-41f7-aad4-37357b577fd0", version="latest", sys_origin_query="北京景点推荐", stream=True) for data in res.content: print(data) def test_component_header_client(self): appbuilder.logger.setLoglevel("DEBUG") client = appbuilder.ComponentClient() res = client.run(component_id="c-wf-a39ee06c-808f-4a19-9f5f-544044283749", version="latest", sys_origin_query="梦到巨人") print(res.content) def test_component_header_client_stream(self): appbuilder.logger.setLoglevel("DEBUG") client = appbuilder.ComponentClient() res = client.run(component_id="c-wf-a39ee06c-808f-4a19-9f5f-544044283749", version="latest", sys_origin_query="梦到巨人", stream=True) for data in res.content: print(data) if __name__ == "__main__": unittest.main() ================================================ FILE: python/tests/test_component_is_async.py ================================================ # Copyright (c) 2024 Baidu, Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import json import os import unittest from appbuilder.core.component import Component class MockComponent(Component): def __init__(self, *args, **kwargs): pass def tool_eval(self, *args, **kwargs): print("Success") class TestComponentInit(unittest.TestCase): def test_component_init(self): component = MockComponent() os.environ["APPBUILDER_TOKEN"] = "abc" component.set_secret_key_and_gateway() component.tool_eval() def test_private_llm_component_init(self): os.environ["PRIVATE_AB"] = "true" component = MockComponent() component.set_model_info("test_model_name", "test_model_url") os.environ["APPBUILDER_TOKEN"] = "abc" component.set_secret_key_and_gateway() component.tool_eval() if __name__ == '__main__': unittest.main() ================================================ FILE: python/tests/test_console_dataset.py ================================================ # Copyright (c) 2023 Baidu, Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import os import uuid import time import unittest import appbuilder from appbuilder.core._client import HTTPClient @unittest.skip("暂时跳过") class TestDataset(unittest.TestCase): def setUp(self): self.dataset_id = os.getenv("DATASET_ID", "UNKNOWN") @classmethod def setUpClass(cls): # 获取当前文件所在的目录路径 cls.current_dir = os.path.dirname(__file__) cls.test_pdf_path = os.path.join(cls.current_dir, 'test.pdf') def test_create_dataset(self): # test_dataset dataset_name = "baidu-test"+str(int(time.time())) dataset_id=str(uuid.uuid4()) dataset = appbuilder.console.Dataset(dataset_id=dataset_id, dataset_name=dataset_name) dataset.create_dataset http_result=dataset.http_client self.assertIsInstance(http_result, HTTPClient) def test_dataset(self): # 初始化数据库 dataset = appbuilder.console.Dataset( dataset_id=self.dataset_id, dataset_name="勿删-appbuilder-sdk测试数据集" ) self.assertIsNotNone(dataset.dataset_id) # 上传文档 file_paths = [self.test_pdf_path] document_infos = dataset.add_documents(file_paths) self.assertEqual(len(document_infos.document_ids), 1) # 获取第一页的文档列表, 每页10条 file_list = dataset.get_documents(1, 10) self.assertIsInstance(file_list.total, int) # 删除文档 file_ids = [document_infos.document_ids[0]] dataset.delete_documents(file_ids) # 获取第一页的文档列表, 每页10条 document_list = dataset.get_documents(1, 10) self.assertIsInstance(document_list.total, int) if __name__ == '__main__': unittest.main() ================================================ FILE: python/tests/test_console_rag.py ================================================ # Copyright (c) 2023 Baidu, Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import unittest import appbuilder import os from appbuilder.core.console.rag.rag import RAG @unittest.skip("暂时跳过") class TestRag(unittest.TestCase): def setUp(self): self.app_id = "06e3f5c9-885d-4f85-af57-97dc85ee4606" def test_rag(self): rag_app = RAG(self.app_id) query = "写一个200字作文,主题关于百度AI" answer = rag_app.run(appbuilder.Message(query)) self.assertIsNotNone(answer.content) # test debug rag_app.debug(appbuilder.Message(query)) if __name__ == '__main__': unittest.main() ================================================ FILE: python/tests/test_core_agent.py ================================================ # Copyright (c) 2024 Baidu, Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import json import os import unittest import random from appbuilder.core.components.llms.style_writing import StyleWriting from appbuilder.core.agent import AgentRuntime from appbuilder.core.component import Component from appbuilder.core.message import Message from appbuilder.utils.sse_util import SSEClient def generate_event(case): # 模拟正常事件 if case == "normal": yield "event1" yield "event2" yield "event3" # 模拟首包一定概率出错 elif case == "head_may_failed": num = random.randint(1, 100) if num < 20: raise Exception("事件生成报错") else: yield "event1" # 模型中包出错 elif case == "middle_failed": yield "event1" raise Exception("事件生成报错") # 模拟首包总是报错 elif case == "head_always_failed": raise Exception("事件生成报错") # 模拟流式事件生成报错 class FakeComponent1(Component): def run(self, message, stream, **kwargs): # 模拟流式调用 if stream: case = kwargs["case"] return Message(content=generate_event(case)) else: return Message(content="result") # 模拟组件内部执行报错 class FakeComponent2(Component): def run(self, message, stream, **kwargs): # 内部执行报错 raise Exception("内部执行报错") class TestCoreAgent(unittest.TestCase): def setUp(self): pass def test_core_agent_create_flask1(self): component = FakeComponent1() # agent = AgentRuntime(component=StyleWriting(model="eb")) agent = AgentRuntime(component=component) app = agent.create_flask_app() client = app.test_client() payload = { "stream": False, "message": "message", } # 非流式请求 rsp = client.post("http://127.0.0.1:8080/chat", json=payload) assert (rsp.json["code"] == 0) # 流式请求 for case in ["normal", "head_may_failed", "middle_failed", "head_always_failed"]: payload = { "stream": True, "message": "message", "case": case } if case == "normal": rsp = client.post("http://127.0.0.1:8080/chat", json=payload) data_chunks = rsp.data.splitlines(keepends=True) for event in SSEClient(data_chunks).events(): d = json.loads(event.data) self.assertEqual(d["code"], 0) if case == "head_may_failed": for i in range(5): rsp = client.post("http://127.0.0.1:8080/chat", json=payload) data_chunks = rsp.data.splitlines(keepends=True) for event in SSEClient(data_chunks).events(): d = json.loads(event.data) self.assertEqual(d["code"], 0) if case == "middle_failed": rsp = client.post("http://127.0.0.1:8080/chat", json=payload) data_chunks = rsp.data.splitlines(keepends=True) i = 0 for event in SSEClient(data_chunks).events(): d = json.loads(event.data) if i == 0: self.assertEqual(d["code"], 0) if i == 1: self.assertNotEqual(d["code"], 0) i += 1 if case == "head_always_failed": rsp = client.post("http://127.0.0.1:8080/chat", json=payload) data_chunks = rsp.data.splitlines(keepends=True) for event in SSEClient(data_chunks).events(): self.assertNotEqual(d["code"], 0) def test_core_agent_create_flask2(self): component = FakeComponent2() agent = AgentRuntime(component=component) app = agent.create_flask_app() client = app.test_client() payload = { "stream": False, "message": "message", } # 非流式请求 rsp = client.post("http://127.0.0.1:8080/chat", json=payload) assert (rsp.json["code"] != 0) payload = { "stream": True, "message": "message", } # 流式请求 rsp = client.post("http://127.0.0.1:8080/chat", json=payload) data_chunks = rsp.data.splitlines(keepends=True) for event in SSEClient(data_chunks).events(): d = json.loads(event.data) self.assertNotEqual(d["code"], 0) if __name__ == '__main__': unittest.main() ================================================ FILE: python/tests/test_core_client.py ================================================ # Copyright (c) 2023 Baidu, Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import os import unittest import json import asyncio from appbuilder.core._client import HTTPClient, AsyncHTTPClient from appbuilder.core._exception import * # 创建一个response类,模拟requests.Response class Response: def __init__(self, status_code, headers, text): self.status_code = status_code self.headers = headers self.text = text def json(self): return json.loads(self.text) class AsyncResponse: def __init__(self, status_code, headers, text): self.status = status_code self.headers = headers self.text = text def json(self): return json.loads(self.text) class TestCoreClient(unittest.TestCase): def setUp(self): # 保存原始环境变量 self.original_appbuilder_token = os.getenv('APPBUILDER_TOKEN') self.original_gateway_url = os.getenv('GATEWAY_URL') def tearDown(self): # 恢复环境变量 if self.original_appbuilder_token is None: os.unsetenv('APPBUILDER_TOKEN') else: os.environ['APPBUILDER_TOKEN'] = self.original_appbuilder_token if self.original_gateway_url is None: os.unsetenv('GATEWAY_URL') else: os.environ['GATEWAY_URL'] = self.original_gateway_url def test_core_client_init_non_APPBUILDER_TOKEN(self): os.environ['APPBUILDER_TOKEN'] = '' with self.assertRaises(ValueError): HTTPClient() def test_core_client_init_non_GATEWAY_URL(self): os.environ['GATEWAY_URL'] = 'test' hp = HTTPClient() assert hp.gateway.startswith('https://') def test_core_client_check_response_header(self): # 测试各种response报错 response = Response( status_code=400, headers={'Content-Type': 'application/json'}, text='{"code": 0, "message": "success"}' ) with self.assertRaises(BadRequestException): HTTPClient.check_response_header(response) response.status_code = 403 with self.assertRaises(ForbiddenException): HTTPClient.check_response_header(response) response.status_code = 404 with self.assertRaises(NotFoundException): HTTPClient.check_response_header(response) response.status_code = 428 with self.assertRaises(PreconditionFailedException): HTTPClient.check_response_header(response) response.status_code = 500 with self.assertRaises(InternalServerErrorException): HTTPClient.check_response_header(response) response.status_code = 201 with self.assertRaises(BaseRPCException): HTTPClient.check_response_header(response) response.status_code = 401 with self.assertRaises(UnAuthorizedException): HTTPClient.check_response_header(response) response.status_code = 405 with self.assertRaises(MethodNotAllowedException): HTTPClient.check_response_header(response) response.status_code = 409 with self.assertRaises(ConflictException): HTTPClient.check_response_header(response) response.status_code = 411 with self.assertRaises(MissingContentLengthException): HTTPClient.check_response_header(response) response.status_code = 422 with self.assertRaises(UnprocessableEntityException): HTTPClient.check_response_header(response) response.status_code = 424 with self.assertRaises(DependencyFailedException): HTTPClient.check_response_header(response) response.status_code = 429 with self.assertRaises(TooManyRequestsException): HTTPClient.check_response_header(response) response.status_code = 507 with self.assertRaises(InsufficientStorageException): HTTPClient.check_response_header(response) import requests http_error = requests.exceptions.HTTPError(response=response) with self.assertRaises(InsufficientStorageException): HTTPClient.classify_exception(http_error) def test_core_client_check_async_response_header(self): async def run_test(): # 测试各种response报错 response = AsyncResponse( status_code=400, headers={'Content-Type': 'application/json'}, text=lambda:asyncio.sleep(0) or '{"code": 0, "message": "success"}' ) with self.assertRaises(BadRequestException): await AsyncHTTPClient.check_response_header(response) response.status = 403 with self.assertRaises(ForbiddenException): await AsyncHTTPClient.check_response_header(response) response.status = 404 with self.assertRaises(NotFoundException): await AsyncHTTPClient.check_response_header(response) response.status = 428 with self.assertRaises(PreconditionFailedException): await AsyncHTTPClient.check_response_header(response) response.status = 500 with self.assertRaises(InternalServerErrorException): await AsyncHTTPClient.check_response_header(response) response.status = 201 with self.assertRaises(BaseRPCException): await AsyncHTTPClient.check_response_header(response) response.status = 401 with self.assertRaises(UnAuthorizedException): await AsyncHTTPClient.check_response_header(response) response.status = 405 with self.assertRaises(MethodNotAllowedException): await AsyncHTTPClient.check_response_header(response) response.status = 409 with self.assertRaises(ConflictException): await AsyncHTTPClient.check_response_header(response) response.status = 411 with self.assertRaises(MissingContentLengthException): await AsyncHTTPClient.check_response_header(response) response.status = 422 with self.assertRaises(UnprocessableEntityException): await AsyncHTTPClient.check_response_header(response) response.status = 424 with self.assertRaises(DependencyFailedException): await AsyncHTTPClient.check_response_header(response) response.status = 429 with self.assertRaises(TooManyRequestsException): await AsyncHTTPClient.check_response_header(response) response.status = 507 with self.assertRaises(InsufficientStorageException): await AsyncHTTPClient.check_response_header(response) import requests http_error = requests.exceptions.HTTPError(response=response) with self.assertRaises(InsufficientStorageException): await AsyncHTTPClient.classify_exception(http_error) loop = asyncio.get_event_loop() loop.run_until_complete(run_test()) def test_core_client_check_response_json(self): data = { 'code': 0, 'message': 'test', 'requestId': 'test' } with self.assertRaises(AppBuilderServerException): HTTPClient.check_response_json(data) def test_core_check_console_response(self): response = Response( status_code=400, headers={'Content-Type': 'application/json'}, text=json.dumps({ 'code': 1, 'message': 'test', 'requestId': 'test' }) ) with self.assertRaises(AppBuilderServerException): HTTPClient.check_console_response(response) def test_classify_exception(self): """测试异常分类方法""" import requests client = HTTPClient() # 测试 HTTP 错误 response = Response( status_code=requests.codes.internal_server_error, headers=client.auth_header(), text="Internal Server Error" ) http_error = requests.exceptions.HTTPError(response=response) with self.assertRaises(InternalServerErrorException): client.classify_exception(http_error) # 测试 AppBuilder 服务器异常 app_error = AppBuilderServerException( request_id="test_id", code=500, message="Interal Server Error" ) with self.assertRaises(AppBuilderServerException) as context: client.classify_exception(app_error) self.assertEqual(context.exception.code, 500) # 测试其他类型异常 other_error = ValueError("Test error") with self.assertRaises(InternalServerException) as context: client.classify_exception(other_error) self.assertEqual(str(context.exception), "Test error") def test_AsyncHTTPClient_classify_exception(self): """测试异常分类方法""" async def run_test(): import requests client = AsyncHTTPClient() # 测试 HTTP 错误 response = AsyncResponse( status_code=requests.codes.internal_server_error, headers=client.auth_header(), text=lambda:asyncio.sleep(0) or '{"code": 0, "message": "success"}' ) http_error = requests.exceptions.HTTPError(response=response) with self.assertRaises(InternalServerErrorException): await client.classify_exception(http_error) # 测试 AppBuilder 服务器异常 app_error = AppBuilderServerException( request_id="test_id", code="500", message="Interal Server Error" ) with self.assertRaises(AppBuilderServerException) as context: await client.classify_exception(app_error) self.assertEqual(context.exception.code, "500") # 测试其他类型异常 other_error = ValueError("Test error") with self.assertRaises(InternalServerException) as context: await client.classify_exception(other_error) self.assertEqual(str(context.exception), "Test error") loop = asyncio.get_event_loop() loop.run_until_complete(run_test()) if __name__ == '__main__': unittest.main() ================================================ FILE: python/tests/test_core_components_baidu_vdb_retriever.py ================================================ # Copyright (c) 2024 Baidu, Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import os import unittest import time import appbuilder from appbuilder import BESVectorStoreIndex from appbuilder import BaiduVDBVectorStoreIndex,TableParams from appbuilder.core.component import Message @unittest.skip(reason="vdb欠费了,跳过") class TestBaiduVbdRetriever(unittest.TestCase): def setUp(self): self.instance_id=os.getenv("INSTANCE_ID", "UNKNOWN") self.api_key=os.getenv("BAIDU_VDB_API_KEY", "UNKNOWN") def test_BaiduVDBVectorStoreIndex_init(self): bvvsi=BaiduVDBVectorStoreIndex(self.instance_id, self.api_key) def test_create_database_if_not_exists_and_create_table(self): bvvsi=BaiduVDBVectorStoreIndex(self.instance_id, self.api_key) dataset_name="test_dataset"+str(int(time.time())) bvvsi._create_database_if_not_exists(dataset_name) with self.assertRaises(ValueError): bvvsi._create_table(table_params=None) bvvsi._create_table(table_params=TableParams(dimension=384)) # test_as_retriever retriever=bvvsi.as_retriever() # test_add_segments message=Message() with self.assertRaises(IndexError): bvvsi.add_segments(message) if __name__ == '__main__': unittest.main() ================================================ FILE: python/tests/test_core_components_doc.py ================================================ # Copyright (c) 2024 Baidu, Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import os import unittest import copy from appbuilder.core.components.doc_crop_enhance.component import DocCropEnhance from appbuilder.core.components.doc_splitter.component import DocSplitter, ChunkSplitter, TitleSplitter from appbuilder.core.message import Message from appbuilder.core.components.doc_parser.base import ParseResult, ParaNode,Position from appbuilder.core.components.doc_format_converter.component import DocFormatConverter from appbuilder.core._exception import InvalidRequestArgumentError @unittest.skipUnless(os.getenv("TEST_CASE", "UNKNOWN") == "CPU_PARALLEL", "") class TestCoreComponentsDoc(unittest.TestCase): def test_doc_crop_enhance_component(self): message=Message() dce=DocCropEnhance() with self.assertRaises(InvalidRequestArgumentError): dce.run(message=message,enhance_type=10) def test_doc_splitter_doc_splitter_DocSplitter(self): # test_if not self.splitter_type ds=DocSplitter(splitter_type='') dr=ParseResult() message=Message() message.content=dr with self.assertRaises(ValueError): ds.run(message=message) #test_splitter_type must be split_by_chunk or split_by_title ds=DocSplitter(splitter_type='test') with self.assertRaises(ValueError): ds.run(message=message) def test_doc_splitter_doc_splitter_ChunkSplitter(self): # test if not isinstance(paser_res, ParseResult) cs=ChunkSplitter() message=Message() with self.assertRaises(ValueError): cs.run(message=message) def test_doc_splitter_doc_splitter_TitleSplitter_run(self): # test if not isinstance(paser_res, ParseResult) ts=TitleSplitter() message=Message() with self.assertRaises(ValueError): ts.run(input_message=message) def test_doc_splitter_doc_splitter_TitleSplitter(self): pos = Position( pageno=1, box=[10, 20, 30, 40] ) node=ParaNode( node_id=1, text='test', para_type= 'test', parent=None, children=[] , position=[pos], table =None ) # test if node.para_type == "head_tail" and test segment.content node_head_tail=copy.deepcopy(node) node_head_tail.para_type='head_tail' message=Message() pr=ParseResult( para_node_tree=[node,node,node_head_tail] ) message.content=pr ts=TitleSplitter() ts.run(input_message=message) def test_doc_format_converter_component_tool_eval(self): dfc=DocFormatConverter() result=dfc.tool_eval(streaming=False,origin_query='origin_query',page_num='str page') with self.assertRaises(InvalidRequestArgumentError): next(result) result=dfc.tool_eval(streaming=False,origin_query='origin_query',page_num=1) with self.assertRaises(InvalidRequestArgumentError): next(result) result=dfc.tool_eval(streaming=False,origin_query='origin_query',page_num=1,file_name='test') with self.assertRaises(InvalidRequestArgumentError): next(result) if __name__ == '__main__': unittest.main() ================================================ FILE: python/tests/test_core_components_embedding.py ================================================ # Copyright (c) 2024 Baidu, Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import os import unittest from appbuilder.core.components.embeddings.component import Embedding from appbuilder.core.components.embeddings.base import EmbeddingBaseComponent from appbuilder.core._exception import ModelNotSupportedException,AppBuilderServerException @unittest.skipUnless(os.getenv("TEST_CASE", "UNKNOWN") == "CPU_PARALLEL", "") class TestCoreComponentsEmbedding(unittest.TestCase): def test_embeddings_base(self): ebc=EmbeddingBaseComponent() message=[1,2,3] ebc.abatch(texts=message) def test_embeddings_component_init(self): # test_embeddings_component_init with self.assertRaises(ModelNotSupportedException): emb=Embedding() emb.accepted_models.append('test') emb.__init__('test') def test_embeddings_component(self): #test_embeddings_component_check_response_json emb=Embedding() data={ 'error_code':'error_code', 'error_msg': 'error_msg' } with self.assertRaises(AppBuilderServerException): emb._check_response_json(data=data) # test_embeddings_component_batchify texts=['test','test'] with self.assertRaises(ValueError): emb._batchify(texts=texts,batch_size=17) if __name__ == '__main__': unittest.main() ================================================ FILE: python/tests/test_core_components_table.py ================================================ # Copyright (c) 2024 Baidu, Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import os import unittest from appbuilder.core.components.table_ocr.component import TableOCR from appbuilder.core._exception import AppBuilderServerException from appbuilder.core.components.extract_table.component import ExtractTableFromDoc from appbuilder.core.message import Message @unittest.skipUnless(os.getenv("TEST_CASE", "UNKNOWN") == "CPU_PARALLEL", "") class TestCoreCmpsTable(unittest.TestCase): def test_table_ocr_component_get_table_markdown(self): # test_get_table_markdown to=TableOCR() table={ "body":[ {'row_end': 1, 'col_end': 2,'row_start': 0, 'col_start': 0,'words':'words'}, ] } tables=[table] md=to.get_table_markdown(tables) def test_table_ocr_component_tool_eval(self): # test_tool_eval 未测试完全 to=TableOCR() url='https://www.baidu.com/' res=to.tool_eval(name="test_name", streaming=True, file_names=["test"],file_urls={'test':url}) with self.assertRaises(AppBuilderServerException): next(res) res=to.tool_eval(name="test_name", streaming=True, files=["test"],file_urls={'test':url}) with self.assertRaises(AppBuilderServerException): next(res) def test_extract_table_component_ExtractTableFromDoc(self): # test_input_check etf=ExtractTableFromDoc() message=Message() with self.assertRaises(ValueError): etf._input_check(message=message,table_max_size=29,doc_node_num_before_table=5) with self.assertRaises(ValueError): etf._input_check(message=message,table_max_size=31,doc_node_num_before_table=11) with self.assertRaises(ValueError): etf._input_check(message=message,table_max_size=31,doc_node_num_before_table=5) #test_post_process resp={ 'result':{ 'mdtables':[[ {'para': 'test'}, {'para':'描述一表:\n|数据A|数据B表|数据A|数据B表|数据A|数据B表'} ]] } } etf.table_max_size=10 etf._post_process(resp=resp) if __name__ == '__main__': unittest.main() ================================================ FILE: python/tests/test_core_components_tts.py ================================================ # Copyright (c) 2024 Baidu, Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import os import unittest from io import BytesIO from appbuilder.core.components.tts.model import TTSRequest from appbuilder.core.components.tts.component import TTS, _iterate_chunk from appbuilder.core._exception import AppBuilderServerException # 模拟response对象 class MockResponse: def __init__(self, data): # 将字符串数据转换为字节流 self.data = BytesIO(data.encode('utf-8')) def close(self): # 模拟关闭响应 pass def iter_lines(self): # 逐行返回数据 return self.data.readlines() @unittest.skipUnless(os.getenv("TEST_CASE", "UNKNOWN") == "CPU_PARALLEL", "") class TestCoreComponentsTTS(unittest.TestCase): def test_tts_component_iterate_chunk_success(self): data = 'data: SGVsbG8sIFdvcmxkIQ==' # base64编码的"Hello, World!" response = MockResponse(data) result = list(_iterate_chunk('test_request', response)) self.assertEqual(result, [b'Hello, World!']) def test_tts_component_iterate_chunk_exception(self): # 模拟一个会导致异常的response def raise_exception(): raise ValueError("Test Exception") response = MockResponse('') response.iter_lines = raise_exception with self.assertRaises(AppBuilderServerException): list(_iterate_chunk('test_request', response)) def test_tts_model(self): tr = TTSRequest() # 定义测试参数和对应的期望结果 test_cases = [ ({'tex': ''}, ValueError, tr.validate_baidu_tts), ({'tex': 'test', 'spd': 16}, ValueError, tr.validate_baidu_tts), ({'tex': 'test', 'spd': 15, 'vol': 16}, ValueError, tr.validate_baidu_tts), ({'tex': 'test', 'spd': 15, 'vol': 15, 'per': 2}, ValueError, tr.validate_baidu_tts), ({'tex': 'test', 'spd': 15, 'vol': 15, 'per': 1, 'aue': 0}, None, tr.validate_baidu_tts), ({'tex': 'test', 'spd': 15, 'vol': 15, 'per': 1, 'aue': 2}, ValueError, tr.validate_baidu_tts), ({'tex': 'test', 'spd': 15, 'vol': 15, 'per': 1, 'aue': 0}, None, tr.validate_paddle_speech_tts), ({'tex': 'test', 'spd': 15, 'vol': 15, 'per': 1, 'aue': 1}, ValueError, tr.validate_paddle_speech_tts) ] for attrs, expected_exception, method in test_cases: # 设置属性 for attr, value in attrs.items(): setattr(tr, attr, value) # 验证期望结果 if expected_exception: with self.assertRaises(expected_exception): method() else: method() if __name__ == '__main__': unittest.main() ================================================ FILE: python/tests/test_core_console_base.py ================================================ # Copyright (c) 2023 Baidu, Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import os import unittest import json from appbuilder.core.console.base import ConsoleLLMMessage,ConsoleCompletionResponse from appbuilder.core._exception import AppBuilderServerException from appbuilder.core.message import Message # 创建一个response类,模拟requests.Response class Response: def __init__(self, status_code, headers, text): self.status_code = status_code self.headers = headers self.text = text def json(self): return json.loads(self.text) @unittest.skipUnless(os.getenv("TEST_CASE", "UNKNOWN") == "CPU_PARALLEL", "") class TestCoreConsoleBase(unittest.TestCase): def test_ConsoleLLMMessage_init(self): # 测试stream=True cr=ConsoleLLMMessage() self.assertIsInstance(str(cr), str) def test_ConsoleCompletionResponse_init(self): # 测试初始化,同时测试response.status_code != 200 and response=Response( status_code=201, headers={}, text=json.dumps({"message": "test"}) ) with self.assertRaises(AppBuilderServerException): ConsoleCompletionResponse(response) # 测试if "code" in data and "message" in data and "requestId" in data response=Response( status_code=200, headers={}, text=json.dumps({ "code": "test", "requestId":"test", "message":"test" }) ) with self.assertRaises(AppBuilderServerException): ConsoleCompletionResponse(response) # 测试if "code" in data and "message" in data and "status" in data response=Response( status_code=200, headers={}, text=json.dumps({ "code": "test", "message":"test", "status":"test" }) ) with self.assertRaises(AppBuilderServerException): ConsoleCompletionResponse(response) # if "code" in data and data.get("code") != 0 response=Response( status_code=200, headers={}, text=json.dumps({ "code": 1, "message": "test" }) ) with self.assertRaises(AppBuilderServerException): ConsoleCompletionResponse(response) # 测试init其余部分 content = [ { "content_type": "references", "outputs": { "references": [ {"from": "key"} # 确认这是一个正确的字典 ] } } ] # 序列化 content 列表为 JSON 字符串 content_json = json.dumps(content) # 使用序列化后的 JSON 字符串作为响应文本 response = Response( status_code=200, headers={}, text=json.dumps({ "code": 0, "result": { "answer": "test", "conversation_id": "test", "content": content # 这里直接使用 content 变量 } }) ) ccr=ConsoleCompletionResponse(response) # test_ConsoleCompletionResponse_message_iterable_wrapper(原代码可能冗余,迭代器未被调用) message = Message() def message_content(): resps=[ {'result': {'answer': 'test', 'conversation_id': 'test', 'content': content}}, {'result': {'answer': 'test', 'conversation_id': 'test', 'content': content}} ] for resp in resps: yield resp message.content = message_content() result = ccr.message_iterable_wrapper(message) #test_ConsoleCompletionResponse_to_message message=ccr.to_message() if __name__ == '__main__': unittest.main() ================================================ FILE: python/tests/test_core_session.py ================================================ # Copyright (c) 2024 Baidu, Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import unittest import appbuilder import asyncio import aiohttp from unittest.mock import patch, MagicMock from appbuilder.core._session import AsyncInnerSession class TestCoreSession(unittest.TestCase): @patch("aiohttp.ClientSession.put") def test_async_session_get(self, mock_put): async def demo(): return {"status": 200} async def async_magic(): pass async def get_demo(): mock_put.return_value.__aenter__.return_value.json = await demo() MagicMock.__await__ = lambda x: async_magic().__await__() session = AsyncInnerSession() await session.get("http://www.baidu.com") await session.put("https://example.com") loop = asyncio.get_event_loop() loop.run_until_complete(get_demo()) if __name__ == "__main__": unittest.main() ================================================ FILE: python/tests/test_core_user_session.py ================================================ # Copyright (c) 2023 Baidu, Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import unittest import os import uuid import sqlite3 from appbuilder.core.user_session import UserSession from appbuilder.core.session_message import SessionMessage from appbuilder.core.context import init_context,_LOCAL_KEY,get_context,context_var from appbuilder.core.message import Message @unittest.skipUnless(os.getenv("TEST_CASE", "UNKNOWN") == "CPU_PARALLEL", "") class TestCoreUserSession(unittest.TestCase): def test_usersession_init(self): UserSession._instance = None UserSession._initialized = False with self.assertRaises(ValueError): user_session=UserSession(user_session_config=1234) UserSession._instance = None UserSession._initialized = False def test_get_context(self): get_context() def test_not_startswith_LOCAL_KEY(self): user_session = UserSession() init_context( session_id=str(uuid.uuid4()), request_id=str(uuid.uuid4()) ) key = "test_key" message_dict = {key: Message(content={"key": "value"})} # if key not in ctx.session_vars_dict user_session.append(message_dict) history = user_session.get_history(key) self.assertEqual(len(history), 0) # if not isinstance(message, Message) with self.assertRaises(ValueError): user_session.append({key: "test"}) # 测试if key in ctx.session_vars_dict with self.assertRaises(KeyError): user_session.append(message_dict) # 测试_post_append(self)的try user_session._post_append() def test_startswith_LOCAL_KEY(self): user_session = UserSession() init_context( session_id=_LOCAL_KEY+str(uuid.uuid4()), request_id=_LOCAL_KEY+str(uuid.uuid4()) ) key = "test_key" message_dict = {key: Message(content={"key": "value"})} # if key not in ctx.session_vars_dict user_session.append(message_dict) history = user_session.get_history("test") self.assertEqual(len(history), 0) history = user_session.get_history(key) self.assertEqual(len(history), 1) # if not isinstance(message, Message) with self.assertRaises(ValueError): user_session.append({key: "test"}) # 测试_post_append(self)的异常 with self.assertRaises(Exception): user_session._post_append() # 验证user_session.db文件是否创建,并验证文件内容 user_session_path = 'user_session.db' conn = sqlite3.connect(user_session_path) cursor = conn.cursor() # 执行一条 SQL 语句,列出所有表 cursor.execute("SELECT name FROM sqlite_master WHERE type='table';") sql = cursor.fetchall() print('sql:{}'.format(sql)) assert sql[0][0] == 'appbuilder_session_messages' # 执行一条 SQL 语句,列出表所有列 cursor.execute("PRAGMA table_info(appbuilder_session_messages);") columns_info = cursor.fetchall() column_names = [info[1] for info in columns_info] # info[1]是列名的位置 for column_name in column_names: print(column_name) assert 'id' in column_names if __name__ == '__main__': unittest.main() ================================================ FILE: python/tests/test_core_utils.py ================================================ # Copyright (c) 2023 Baidu, Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import unittest import os import base64 import appbuilder.core.utils as ut from appbuilder.utils.sse_util import SSEClient,Event @unittest.skipUnless(os.getenv("TEST_CASE", "UNKNOWN") == "CPU_PARALLEL", "") class TestCoreUtils(unittest.TestCase): def test_utils_get_user_agent(self): user_agent=ut.utils_get_user_agent() def test_get_model_list(self): from appbuilder.core._exception import TypeNotSupportedException with self.assertRaises(TypeNotSupportedException): model_list=ut.get_model_list(api_type_filter=["unknown"]) def test_convert_cloudhub_url(self): try: from appbuilder.core._client import HTTPClient except: pass with self.assertRaises(ValueError): url=ut.convert_cloudhub_url(client=HTTPClient,qianfan_url="unknown") def test_is_url(self): is_url=ut.is_url("unknown") # def test_utils_sse_uti_events(self): # binary_data = os.urandom(100) # 生成100字节的随机数据 # encoded_data = base64.b64encode(binary_data).decode('utf-8') # sseClient=SSEClient(event_source=encoded_data) # sseClient.events() # def test_utils_sse_uti_events(self): # binary_data = os.urandom(100) # 生成100字节的随机数据 # encoded_data = base64.b64encode(binary_data).decode('utf-8') # sseClient=SSEClient(event_source=encoded_data) # sseClient.close() def test_utils_sse_uti_Events(self): event_null_data=Event(id="id") s=event_null_data.debug_str event=Event(id="id",data='data',retry="retry") s=event.debug_str event.raw="raw" s_change_raw=event.debug_str if __name__ == '__main__': unittest.main() ================================================ FILE: python/tests/test_dialog_summary.py ================================================ # Copyright (c) 2023 Baidu, Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import os import unittest import appbuilder class TestDialogSummary(unittest.TestCase): def setUp(self): """ 设置环境变量。 Args: 无参数,默认值为空。 Returns: 无返回值,方法中执行了环境变量的赋值操作。 """ self.model_name = "DeepSeek-V3.1" self.node = appbuilder.DialogSummary(model=self.model_name) def test_run_with_default_params(self): """测试 run 方法使用默认参数""" dialog_text = "用户:喂我想查一下我的话费\n坐席:好的女士您话费余的话还有87.49元钱\n用户:好的知道了谢谢\n坐席:嗯不客气祝您生活愉快再见" msg = appbuilder.Message(dialog_text) summary = self.node(msg) self.assertIsNotNone(summary) def test_run_with_stream_and_temperature(self): """测试不同的 stream 和 temperature 参数值""" dialog_text = "用户:喂我想查一下我的话费\n坐席:好的女士您话费余的话还有87.49元钱\n用户:好的知道了谢谢\n坐席:嗯不客气祝您生活愉快再见" msg = appbuilder.Message(dialog_text) summary = self.node(msg, stream=False, temperature=0.5) self.assertIsNotNone(summary) def test_run_with_model_names(self): """测试不同的 stream 和 temperature 参数值""" chats = appbuilder.get_model_list(api_type_filter=["chat"]) self.assertTrue("DeepSeek-V3.1" in chats) appbuilder.DialogSummary(model="DeepSeek-V3.1") with self.assertRaises(Exception): appbuilder.DialogSummary(model="") def test_tool_eval_valid(self): """测试 tool 方法对有效请求的处理。""" params = { 'name': 'dialog_summary', 'query': '用户:喂我想查一下我的话费\n坐席:好的女士您话费余的话还有87.49元钱\n用户:好的知道了谢谢\n坐席:嗯不客气祝您生活愉快再见' } result = self.node.tool_eval(streaming=True, **params) res = [item for item in result] self.assertNotEqual(len(res), 0) result = self.node.tool_eval(streaming=False, **params) res = [item for item in result] def test_tool_eval_invalid(self): """测试 tool 方法对无效请求的处理。""" with self.assertRaises(ValueError): params = { 'name': 'dialog_summary' } result = self.node.tool_eval(streaming=True, **params) next(result) if __name__ == '__main__': unittest.main() ================================================ FILE: python/tests/test_dish_recognize.py ================================================ import unittest import os import requests import appbuilder @unittest.skipUnless(os.getenv("TEST_CASE", "UNKNOWN") == "CPU_PARALLEL", "") class TestDishRecognitionComponent(unittest.TestCase): def setUp(self): """ 在开始测试之前配置环境和实例化DishRecognition对象。 Args: None Returns: None """ self.dish_recognition = appbuilder.DishRecognition() def test_run_with_valid_image(self): """ 测试run函数在传入有效图像的情况下的行为。 Args: None Returns: None """ image_url = "https://bj.bcebos.com/v1/appbuilder/dish_recognize_test.jpg?" \ "authorization=bce-auth-v1%2FALTAKGa8m4qCUasgoljdEDAzLm%2F2024-01-11T" \ "10%3A58%3A25Z%2F-1%2Fhost%2F7b8fc08b2be5adfaeaa4e3a0bb0d1a1281b10da" \ "3d6b798e116cce3e37feb3438" raw_image = requests.get(image_url).content message = appbuilder.Message({"raw_image": raw_image}) output_message = self.dish_recognition(message=message) self.assertIsInstance(output_message, appbuilder.Message) def test_run_with_invalid_image(self): """ 测试run函数在传入无效图像的情况下的行为。 Args: None Returns: None """ current_dir = os.path.dirname(__file__) file_path = os.path.join(current_dir, 'test_translate.py') with open(file_path, "rb") as f: message = appbuilder.Message({"raw_image": f.read()}) with self.assertRaises(appbuilder.AppBuilderServerException): self.dish_recognition(message=message) def test_run_with_valid_url(self): """ 测试run函数在传入有效URL的情况下的行为。 Args: None Returns: None """ image_url = "https://bj.bcebos.com/v1/appbuilder/dish_recognize_test.jpg?" \ "authorization=bce-auth-v1%2FALTAKGa8m4qCUasgoljdEDAzLm%2F2024-01-11T" \ "10%3A58%3A25Z%2F-1%2Fhost%2F7b8fc08b2be5adfaeaa4e3a0bb0d1a1281b10da" \ "3d6b798e116cce3e37feb3438" message = appbuilder.Message({"url": image_url}) output_message = self.dish_recognition(message=message) self.assertIsInstance(output_message, appbuilder.Message) def test_run_with_invalid_url(self): """ 测试run函数在传入无效URL的情况下的行为。 Args: None Returns: None """ url = "http://example.com/invalid_url.jpg" message = appbuilder.Message({"url": url}) with self.assertRaises(appbuilder.AppBuilderServerException): self.dish_recognition(message=message) def test_run_without_image_and_url(self): """ 测试run 函数在没有传入图像和URL的情况下的行为。 Args: None Returns: None """ message = appbuilder.Message({}) with self.assertRaises(ValueError): self.dish_recognition(message=message) if __name__ == "__main__": unittest.main() ================================================ FILE: python/tests/test_doc_crop_enhance.py ================================================ # Copyright (c) 2023 Baidu, Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import unittest import requests import appbuilder import os class TestDocCropEnhance(unittest.TestCase): def setUp(self): """ 设置环境变量。 """ self.doc_crop_enhance = appbuilder.DocCropEnhance() def test_run_with_raw_image(self): """ 使用原始图片进行单测 Args: None Returns: None """ image_url = "https://bj.bcebos.com/v1/appbuilder/doc_enhance_test.png?" \ "authorization=bce-auth-v1%2FALTAKGa8m4qCUasgoljdEDAzLm%2F2024-01" \ "-24T12%3A51%3A09Z%2F-1%2Fhost%2F2020d2433da471b40dafa933d557a1e" \ "be8abf28df78010f865e45dfcd6dc3951" raw_image = requests.get(image_url).content # Create message with raw_image message = appbuilder.Message(content={"raw_image": raw_image}) # Doc enhance output = self.doc_crop_enhance.run(message) # Assert output is not None self.assertIsNotNone(output) def test_run_with_url(self): """ 使用图片 URL 进行单测 Args: None Returns: None """ image_url = "https://bj.bcebos.com/v1/appbuilder/doc_enhance_test.png?" \ "authorization=bce-auth-v1%2FALTAKGa8m4qCUasgoljdEDAzLm%2F2024-01" \ "-24T12%3A51%3A09Z%2F-1%2Fhost%2F2020d2433da471b40dafa933d557a1e" \ "be8abf28df78010f865e45dfcd6dc3951" # Create message with image URL message = appbuilder.Message(content={"url": image_url}) # Doc enhance output = self.doc_crop_enhance.run(message) # Assert output is not None self.assertIsNotNone(output) def test_run_with_timeout_and_retry(self): """ 测试run方法,enhance_type、timeout、retry参数 Args: None Returns: None """ # 定义一个图片URL image_url = "https://bj.bcebos.com/v1/appbuilder/doc_enhance_test.png?" \ "authorization=bce-auth-v1%2FALTAKGa8m4qCUasgoljdEDAzLm%2F2024-01" \ "-24T12%3A51%3A09Z%2F-1%2Fhost%2F2020d2433da471b40dafa933d557a1e" \ "be8abf28df78010f865e45dfcd6dc3951" raw_image = requests.get(image_url).content # Create message with raw_image message = appbuilder.Message(content={"raw_image": raw_image}) # Doc enhance with timeout and retry parameters output = self.doc_crop_enhance.run(message, enhance_type=3, timeout=5.0, retry=3) # Assert output is not None self.assertIsNotNone(output) def test_run_with_invalid_input(self): """ 测试run函数在传入无效输入的情况下的行为。 Args: None Returns: None """ # create empty message message = appbuilder.Message(content={}) # Assert ValueError is raised with self.assertRaises(ValueError): self.doc_crop_enhance.run(message) def test_run_with_invalid_url(self): """ 测试run函数在传入无效URL的情况下的行为。 Args: None Returns: None """ url = "http://example.com/invalid_url.jpg" message = appbuilder.Message(content={"url": url}) with self.assertRaises(appbuilder.AppBuilderServerException): self.doc_crop_enhance.run(message) if __name__ == '__main__': unittest.main() ================================================ FILE: python/tests/test_doc_format_converter.py ================================================ # Copyright (c) 2023 Baidu, Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import unittest import os import appbuilder @unittest.skipUnless(os.getenv("TEST_CASE", "UNKNOWN") == "CPU_PARALLEL", "") class TestDocFormatConverter(unittest.TestCase): @classmethod def setUpClass(cls): pass def setUp(self): pass @classmethod def test_doc_format_url(cls): image_url = "https://ai-cape-strategy-data.bj.bcebos.com/document-restructure/1EF33F9307451C9413D5D1160.jpg" doc_format_converter = appbuilder.DocFormatConverter() resp = doc_format_converter(appbuilder.Message({"file_path": image_url})) assert "word_url" in resp.content if __name__ == '__main__': unittest.main() ================================================ FILE: python/tests/test_doc_parser.py ================================================ # Copyright (c) 2023 Baidu, Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import unittest import os import appbuilder @unittest.skipUnless(os.getenv("TEST_CASE", "UNKNOWN") == "CPU_PARALLEL", "") class TestDocParser(unittest.TestCase): @classmethod def setUpClass(cls): """ 设置测试类所需的全局变量,包括当前文件所在目录路径和测试PDF文件路径。 Args: 无 Returns: 无 """ # 获取当前文件所在的目录路径 cls.current_dir = os.path.dirname(__file__) cls.test_pdf_path = os.path.join(cls.current_dir, 'test.pdf') def test_set_config(self): self.doc_parser = appbuilder.DocParser() config = appbuilder.ParserConfig() config.convert_file_to_pdf = True config.return_para_node_tree = False config.convert_file_to_pdf = True self.doc_parser.set_config(config) self.assertEqual(self.doc_parser.config.return_para_node_tree, False) self.assertEqual(self.doc_parser.config.convert_file_to_pdf, True) def test_make_parse_result(self): self.doc_parser = appbuilder.DocParser() data = {'para_nodes': {}, 'catalog': {}, 'pdf_data': '', 'file_content': []} result = self.doc_parser.make_parse_result(data) self.assertEqual(result['para_node_tree'], {}) self.assertEqual(result['page_contents'], []) self.assertEqual(result['pdf_data'], '') def test_doc_parser_with_default_config(self): # 测试文档解析器使用默认配置 msg = appbuilder.Message(self.test_pdf_path) parser = appbuilder.DocParser() result = parser(msg) # 断言解析结果的 para_node_tree 不为空(根据实际情况调整断言) self.assertIsNotNone(result.content.para_node_tree) def test_doc_parser_with_modified_config(self): # 测试文档解析器使用修改后的配置 msg = appbuilder.Message(self.test_pdf_path) parser = appbuilder.DocParser() # 修改配置参数 config = parser.config config.return_para_node_tree = False result = parser(msg) self.assertIs(len(result.content.para_node_tree), 0) config.convert_file_to_pdf = True result = parser(msg) # 断言解析结果的 para_node_tree 根据配置更改(根据实际情况调整断言) self.assertIsNotNone(result.content.pdf_data) def test_tool_eval_valid(self): """测试 tool 方法对有效请求的处理。""" parser = appbuilder.DocParser() params = { 'file_urls': {'test.pdf': 'http://agi-dev-platform-bos.bj.bcebos.com/ut_appbuilder/test.pdf?authorization=bce-auth-v1/e464e6f951124fdbb2410c590ef9ed2f/2024-01-25T12%3A56%3A15Z/-1/host/b54178fea9be115eafa2a8589aeadfcfaeba20d726f434f871741d4a6cb0c70d'}, 'file_names': ['test.pdf'] } result = parser.tool_eval(streaming=True, **params) res = [item for item in result] self.assertNotEqual(len(res), 0) result = parser.tool_eval(streaming=False, **params) res = [item for item in result] def test_tool_eval_invalid(self): """测试 tool 方法对无效请求的处理。""" parser = appbuilder.DocParser() with self.assertRaises(ValueError): params = { 'file_names': ['test.pdf'] } result = parser.tool_eval(streaming=True, **params) next(result) with self.assertRaises(ValueError): params = { 'file_urls': {'test.pdf': 'http://agi-dev-platform-bos.bj.bcebos.com/ut_appbuilder/test.pdf?authorization=bce-auth-v1/e464e6f951124fdbb2410c590ef9ed2f/2024-01-25T12%3A56%3A15Z/-1/host/b54178fea9be115eafa2a8589aeadfcfaeba20d726f434f871741d4a6cb0c70d'} } result = parser.tool_eval(streaming=True, **params) next(result) if __name__ == '__main__': unittest.main() ================================================ FILE: python/tests/test_doc_splitter.py ================================================ # Copyright (c) 2023 Baidu, Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import json import unittest import os import appbuilder @unittest.skipUnless(os.getenv("TEST_CASE", "UNKNOWN") == "CPU_PARALLEL", "") class TestDocSplitter(unittest.TestCase): @classmethod def setUpClass(cls): pass def test_splitter_with_chunk_size(self): """ 测试文档分割: 指定最大chunk的大小\结尾分隔符\chunk块重叠的字数等参数,对文档进行分割 """ # 1. 文档解析 current_dir = os.path.dirname(__file__) file_name = "test.pdf" test_pdf_path = os.path.join(current_dir, file_name) msg = appbuilder.Message(test_pdf_path) parser = appbuilder.DocParser() xmind_output = parser(msg, return_raw=True) # 2. 按照参数进行文档分段 doc_splitter = appbuilder.DocSplitter(splitter_type="split_by_chunk", separators=["。", "!", "?", ".", "!", "?", "……", "|\n"], max_segment_length=800, overlap=200, join_symbol="") doc_splitter_result = doc_splitter(xmind_output) appbuilder.logger.info("paragraphs: {}".format( json.dumps(doc_splitter_result.content, ensure_ascii=False)) ) # 断言解析结果的不为空(根据实际情况调整断言) self.assertIsNotNone(doc_splitter_result.content["paragraphs"]) def test_splitter_with_title_level(self): """ 测试文档分割: 按照标题级别进行分割 """ config = dict(title="title_splitter.docx") # 1. 文档解析 current_dir = os.path.dirname(__file__) test_pdf_path = os.path.join(current_dir, config["title"]) msg = appbuilder.Message(test_pdf_path) parser = appbuilder.DocParser() xmind_output = parser(msg, return_raw=True) # 2. 按照文档标题层级分段 doc_splitter = appbuilder.DocSplitter(splitter_type="split_by_title") result = doc_splitter(xmind_output) appbuilder.logger.info("paragraphs: {}".format( json.dumps(result.content["paragraphs"], ensure_ascii=False)) ) # 在这里进行断言,确保你的代码达到预期的效果 self.assertIsInstance(result, appbuilder.Message) self.assertTrue("paragraphs" in result.content) def test_run_chunk_splitter_with_invalid_input(self): # 模拟DocParser的输出结果 invalid_result = "Invalid Result" message = appbuilder.Message(content=invalid_result) doc_splitter = appbuilder.DocSplitter(splitter_type="title_level") # 运行 DocSplitter,确保它能处理无效输入 with self.assertRaises(ValueError): doc_splitter.run(message) def test_run_splitter_with_invalid_input(self): config = dict(title="title_splitter.docx") # 1. 文档解析 current_dir = os.path.dirname(__file__) test_pdf_path = os.path.join(current_dir, config["title"]) msg = appbuilder.Message(test_pdf_path) parser = appbuilder.DocParser() xmind_output = parser(msg, return_raw=False) # 2. 按照文档标题层级分段 doc_splitter = appbuilder.DocSplitter(splitter_type="split_by_title") # 在这里进行断言,确保你的代码达到预期的效果 with self.assertRaises(ValueError): doc_splitter.run(xmind_output) if __name__ == '__main__': # unittest.main() suite = unittest.TestLoader().loadTestsFromTestCase(TestDocSplitter) unittest.TextTestRunner(verbosity=2).run(suite) unittest.main(verbosity=2) ================================================ FILE: python/tests/test_document_understanding.py ================================================ """ Copyright (c) 2023 Baidu, Inc. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. """ import os import unittest import appbuilder TEST_INPUT = { "query": appbuilder.Message("这篇文档讲了什么"), "instruction": "请根据文档内容回答问题", "addition_instruction": "请你用一句话简短概括", "file_path": "data/qa_demo.xlsx", "stream": True, "app_id": "87187054-78f0-4ef3-b710-fdcf2bfba7f2" } @unittest.skip(reason="组件API实现问题,暂时跳过。修复后重新打开") class TestDocumentUnderstandingComponent(unittest.TestCase): def setUp(self): """ 设置环境变量。 Args: 无参数,默认值为空。 Returns: 无返回值,方法中执行了环境变量的赋值操作。 """ self.du = appbuilder.DocumentUnderstanding() def test_run_with_stream(self): """测试 run 方法流式输出 """ query = TEST_INPUT.get("query") results = self.du.run(query, TEST_INPUT.get("file_path"), instruction=TEST_INPUT.get("instruction"), addition_instruction=TEST_INPUT.get("addition_instruction"), stream=TEST_INPUT.get("stream"), app_id=TEST_INPUT.get("app_id")) for result in results: self.assertIsNotNone(result) print(f'\n[result]\n{result}\n') def test_run_with_nostream(self): """测试 run 方法非流式输出 """ query = TEST_INPUT.get("query") results = self.du.run(query, TEST_INPUT.get("file_path"), instruction=TEST_INPUT.get("instruction"), addition_instruction=TEST_INPUT.get("addition_instruction"), stream=False, app_id=TEST_INPUT.get("app_id")) for result in results: self.assertIsNotNone(result) print(f'\n[result]\n{result}\n') def test_run_with_nofile(self): """测试 run 方法上传无效文件 """ query = TEST_INPUT.get("query") # 使用 assertRaises 捕获预期异常 with self.assertRaises(FileNotFoundError): # 假设无效文件抛出 FileNotFoundError 异常 results = self.du.run(query, "invalid_file.txt", # 使用无效文件 instruction=TEST_INPUT.get("instruction"), addition_instruction=TEST_INPUT.get("addition_instruction"), stream=False, app_id=TEST_INPUT.get("app_id")) # 如果 run 方法抛出异常,以下代码将不会执行 for result in results: self.assertIsNotNone(result) print(f'\n[result]\n{result}\n') def test_tool_eval(self): '''测试tool_eval方法''' INPUT_JON_ = { "instruction": TEST_INPUT.get("instruction", ""), "addition_instruction": TEST_INPUT.get("addition_instruction", ""), "app_id": TEST_INPUT.get("app_id") } query = TEST_INPUT.get("query", "") results = self.du.tool_eval(query, file_path=TEST_INPUT.get("file_path", ""), stream=False, **INPUT_JON_) for result in results: print(result) if __name__ == '__main__': unittest.main() ================================================ FILE: python/tests/test_embedding.py ================================================ """ test ernie bot embedding """ import os import sys sys.path.append('../..') import unittest import asyncio import appbuilder import numpy as np @unittest.skipUnless(os.getenv("TEST_CASE", "UNKNOWN") == "CPU_PARALLEL", "") class TestEmbedding(unittest.TestCase): def setUp(self): self.embedding = appbuilder.Embedding() def test_run(self): embedding_1 = self.embedding("hello world!") embedding_2 = self.embedding(appbuilder.Message("hello world!")) np.testing.assert_array_almost_equal(embedding_1.content, embedding_1.content, decimal=4) def test_batch(self): embeddings_1 = self.embedding.batch( ["hello", "world", "!"], ) self.assertEqual(len(embeddings_1.content), 3) embeddings_2 = self.embedding.batch( appbuilder.Message(["hello", "world", "!"]) ) np.testing.assert_array_almost_equal(embeddings_1.content, embeddings_2.content, decimal=4) embeddings_3 = self.embedding.batch( appbuilder.Message([]), ) self.assertListEqual(embeddings_3.content, []) def test_arun(self): embedding_1 = asyncio.run(self.embedding.arun("hello world!")) print(embedding_1.content) def test_not_support_model(self): try: embedding = appbuilder.Embedding(model="foo") except Exception as e: from appbuilder.core._exception import ModelNotSupportedException assert isinstance(e, ModelNotSupportedException) msg = str(e) assert "Model foo not supported" in msg if __name__ == '__main__': unittest.main() ================================================ FILE: python/tests/test_extract_table.py ================================================ # Copyright (c) 2023 Baidu, Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """test""" import json import unittest import os from appbuilder.utils.logger_util import logger from appbuilder import Message, ExtractTableFromDoc, DocParser @unittest.skipUnless(os.getenv("TEST_CASE", "UNKNOWN") == "CPU_PARALLEL", "") class TestExtractTableFromDoc(unittest.TestCase): """ pass """ @classmethod def setUpClass(cls): # 获取当前文件所在的目录路径 current_dir = os.path.dirname(__file__) cls.test_pdf_path = os.path.join(current_dir, 'test.pdf') # 1.解析文档,并返回原始解析结果 msg = Message(cls.test_pdf_path) parser = DocParser() cls.doc = parser(msg, return_raw=True).content.raw def test_doc_table_to_markdown_with_default_config(self): """ pass """ # 2.文档原始的解析结果,作为输入,解析表格。表格默认最大字符长度:800 parser = ExtractTableFromDoc() result = parser(Message(self.doc), table_max_size=800) logger.info("default config Tables: {}".format( json.dumps(result.content, ensure_ascii=False)) ) self.assertIsNotNone(result.content[0][0]["para"]) def test_doc_table_to_markdown(self): """ pass """ # 2.文档原始的解析结果,作为输入,解析表格。表格默认字符长度:800 table_max_size = 200 parser = ExtractTableFromDoc() result = parser(Message(self.doc), table_max_size=table_max_size, doc_node_num_before_table=10) logger.info("Tables: {}".format( json.dumps(result.content, ensure_ascii=False)) ) for table in result.content: for sub in table: self.assertLessEqual(len(sub["para"]), table_max_size) if __name__ == '__main__': unittest.main() ================================================ FILE: python/tests/test_gbi_nl2sql.py ================================================ """ Copyright (c) 2023 Baidu, Inc. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. """ import unittest import os import appbuilder from appbuilder.core.message import Message from appbuilder.core.components.gbi.basic import NL2SqlResult, SessionRecord from appbuilder.core.components.gbi.basic import ColumnItem from appbuilder.core._exception import BaseRPCException SUPER_MARKET_SCHEMA = """ ``` CREATE TABLE `supper_market_info` ( `订单编号` varchar(32) DEFAULT NULL, `订单日期` date DEFAULT NULL, `邮寄方式` varchar(32) DEFAULT NULL, `地区` varchar(32) DEFAULT NULL, `省份` varchar(32) DEFAULT NULL, `客户类型` varchar(32) DEFAULT NULL, `客户名称` varchar(32) DEFAULT NULL, `商品类别` varchar(32) DEFAULT NULL, `制造商` varchar(32) DEFAULT NULL, `商品名称` varchar(32) DEFAULT NULL, `数量` int(11) DEFAULT NULL, `销售额` int(11) DEFAULT NULL, `利润` int(11) DEFAULT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 ``` """ PRODUCT_SALES_INFO = """ 现有 mysql 表 product_sales_info, 该表的用途是: 产品收入表 ``` CREATE TABLE `product_sales_info` ( `年` int, `月` int, `产品名称` varchar, `收入` decimal, `非交付成本` decimal, `含交付毛利` decimal ) ``` """ PROMPT_TEMPLATE = """ MySql 表 Schema 如下: {schema} 请根据用户当前问题,联系历史信息,仅编写1个sql,其中 sql 语句需要使用```sql ```这种 markdown 形式给出。 请参考列选信息: {instrument} 请参考知识: {kg} 当前时间:{date} 历史信息如下:{history_prompt} 当前问题:"{query}" 回答: """ class TestGBINL2Sql(unittest.TestCase): def setUp(self): """ 设置环境变量及必要数据。 """ model_name = "ERNIE-Bot 4.0" table_schemas = [SUPER_MARKET_SCHEMA] self.nl2sql_node = appbuilder.NL2Sql(model_name=model_name, table_schemas=table_schemas) def test_run_with_column_constraint(self): session = list() query = "列出商品类别是水果的的利润率" column_constraint = [ColumnItem(ori_value="水果", column_value="新鲜水果", column_name="商品类别", table_name="超市营收明细", is_like=False)] msg = Message({"query": query, "column_constraint": column_constraint,"session": session}) try: result_message = self.nl2sql_node(msg) self.assertIsNotNone(result_message) self.assertTrue(result_message.content.sql != "") self.assertTrue(result_message.content.llm_result != "") self.assertIn("水果", result_message.content.sql) self.nl2sql_node.knowledge = dict() self.nl2sql_node.prompt_template = "" except BaseRPCException: pass except: raise Exception('单测失败') def test_nl2sql_raise(self): with self.assertRaises(ValueError): node = appbuilder.NL2Sql(model_name='test',table_schemas=['test']) if __name__ == '__main__': unittest.main() ================================================ FILE: python/tests/test_gbi_select_table.py ================================================ """ Copyright (c) 2023 Baidu, Inc. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. """ import unittest import os import appbuilder from appbuilder.core.message import Message from appbuilder.core.components.gbi.basic import SessionRecord from appbuilder.core.components.gbi.basic import NL2SqlResult from appbuilder.core._exception import BaseRPCException SUPER_MARKET_SCHEMA = """ ``` CREATE TABLE `supper_market_info` ( `订单编号` varchar(32) DEFAULT NULL, `订单日期` date DEFAULT NULL, `邮寄方式` varchar(32) DEFAULT NULL, `地区` varchar(32) DEFAULT NULL, `省份` varchar(32) DEFAULT NULL, `客户类型` varchar(32) DEFAULT NULL, `客户名称` varchar(32) DEFAULT NULL, `商品类别` varchar(32) DEFAULT NULL, `制造商` varchar(32) DEFAULT NULL, `商品名称` varchar(32) DEFAULT NULL, `数量` int(11) DEFAULT NULL, `销售额` int(11) DEFAULT NULL, `利润` int(11) DEFAULT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 ``` """ PRODUCT_SALES_INFO = """ 现有 mysql 表 product_sales_info, 该表的用途是: 产品收入表 ``` CREATE TABLE `product_sales_info` ( `年` int, `月` int, `产品名称` varchar, `收入` decimal, `非交付成本` decimal, `含交付毛利` decimal ) ``` """ PROMPT_TEMPLATE = """ 你是一个专业的业务人员,下面有{num}张表,具体表名如下: {table_desc} 请根据问题帮我选择上述1-{num}种的其中相关表并返回,可以为多表,也可以为单表, 返回多张表请用“,”隔开 返回格式请参考如下示例: 问题:有多少个审核通过的投运单? 回答: ```DWD_MAT_OPERATION``` 请严格参考示例只不要返回无关内容,直接给出最终答案后面的内容,分析步骤不要输出 问题:{query} 回答: """ class TestGBISelectTable(unittest.TestCase): def setUp(self): """ 设置环境变量及必要数据。 """ model_name = "ERNIE-Bot 4.0" self.select_table_node = \ appbuilder.SelectTable(model_name=model_name, table_descriptions={"supper_market_info": "超市营收明细表,包含超市各种信息等", "product_sales_info": "产品销售表"}) def test_run_with_default_param(self): """测试 run 方法使用有效参数""" query = "列出超市中的所有数据" msg = Message({"query": query}) try: result_message = self.select_table_node(message=msg) # print(result_message.content) self.assertIsNotNone(result_message) self.assertEqual(len(result_message.content), 1) self.assertEqual(result_message.content[0], "supper_market_info") except BaseRPCException: pass except: raise Exception('单测失败') def test_run_with_prompt_template(self): """测试 run 方法中 prompt template 模版""" query = "列出超市中的所有数据" msg = Message({"query": query}) self.select_table_node.prompt_template = PROMPT_TEMPLATE try: result_message = self.select_table_node(msg) self.assertIsNotNone(result_message) self.assertEqual(len(result_message.content), 1) self.assertTrue(result_message.content[0].startswith("supper_market_info")) self.select_table_node.prompt_template = "" except BaseRPCException: pass except: raise Exception('单测失败') def test_run_with_session(self): """测试 run 方法中 prompt template 模版""" session = list() session_record = SessionRecord(query="列出商品类别是水果的的利润率", answer=NL2SqlResult( llm_result="根据问题分析得到 sql 如下: \n " "```sql\nSELECT * FROM `超市营收明细` " "WHERE `商品类别` = '水果'\n```", sql="SELECT * FROM `超市营收明细` WHERE `商品类别` = '水果'")) session.append(session_record) query = "列出超市中的所有数据" msg = Message({"query": query, "session": session}) try: result_message = self.select_table_node(msg) self.assertIsNotNone(result_message) self.assertEqual(len(result_message.content), 1) self.assertEqual(result_message.content[0], "supper_market_info") except BaseRPCException: pass except: raise Exception('单测失败') def test_st_raise(self): with self.assertRaises(ValueError): appbuilder.SelectTable(model_name='test',table_descriptions={}) if __name__ == '__main__': unittest.main() ================================================ FILE: python/tests/test_general_ocr.py ================================================ # Copyright (c) 2023 Baidu, Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import os import unittest import base64 import requests import appbuilder from appbuilder.core._exception import InvalidRequestArgumentError @unittest.skipUnless(os.getenv("TEST_CASE", "UNKNOWN") == "CPU_PARALLEL", "") class TestGeneralOCR(unittest.TestCase): def setUp(self): """ 设置环境变量。 Args: None Returns: None. """ self.general_ocr = appbuilder.GeneralOCR() def test_run_with_raw_image(self): """ 测试只使用有效图片进行单测 Args: None Returns: None """ image_url = "https://bj.bcebos.com/v1/appbuilder/general_ocr_test.png?" \ "authorization=bce-auth-v1%2FALTAKGa8m4qCUasgoljdEDAzLm%2F2024-01-" \ "11T10%3A59%3A17Z%2F-1%2Fhost%2F081bf7bcccbda5207c82a4de074628b04ae" \ "857a27513734d765495f89ffa5f73" raw_image = requests.get(image_url).content image_base64 = base64.b64encode(raw_image) # Create message with raw_image message = appbuilder.Message(content={"image_base64": image_base64}) # Recognize landmark output = self.general_ocr.run(message) # Assert output is not None self.assertIsNotNone(output) def test_run_with_no_image(self): """ 测试run函数在传入无效图像的情况下的行为。 Args: None Returns: None """ # create empty message message = appbuilder.Message(content={}) # Assert ValueError is raised with self.assertRaises(ValueError): self.general_ocr.run(message) def test_run_with_timeout_and_retry(self): """ 测试run函数在传入timeout、retry参数 Args: None Returns: None """ image_url = "https://bj.bcebos.com/v1/appbuilder/general_ocr_test.png?" \ "authorization=bce-auth-v1%2FALTAKGa8m4qCUasgoljdEDAzLm%2F2024-01-" \ "11T10%3A59%3A17Z%2F-1%2Fhost%2F081bf7bcccbda5207c82a4de074628b04ae" \ "857a27513734d765495f89ffa5f73" raw_image = requests.get(image_url).content image_base64 = base64.b64encode(raw_image) # Create message with raw_image message = appbuilder.Message(content={"image_base64": image_base64}) # Recognize general_ocr with timeout and retry parameters output = self.general_ocr.run(message, timeout=5.0, retry=3) # Assert output is not None self.assertIsNotNone(output) def test_run_with_invalid_url(self): """ 测试run函数在传入无效URL的情况下的行为。 Args: None Returns: None """ url = "http://example.com/invalid_url.jpg" message = appbuilder.Message({"image_url": url}) with self.assertRaises(appbuilder.AppBuilderServerException): self.general_ocr.run(message=message) def test_run_without_image_and_url(self): """ 测试run 函数在没有传入图像和URL的情况下的行为。 Args: None Returns: None """ message = appbuilder.Message({}) with self.assertRaises(ValueError): self.general_ocr.run(message=message) def test_tool_eval_valid(self): """测试 tool 方法对有效请求的处理。""" image_url = "https://bj.bcebos.com/v1/appbuilder/general_ocr_test.png?" \ "authorization=bce-auth-v1%2FALTAKGa8m4qCUasgoljdEDAzLm%2F2024-01-" \ "11T10%3A59%3A17Z%2F-1%2Fhost%2F081bf7bcccbda5207c82a4de074628b04ae" \ "857a27513734d765495f89ffa5f73" result = self.general_ocr.tool_eval(name="general_ocr", streaming=True, img_url=image_url) res = [item for item in result] self.assertNotEqual(len(res), 0) def test_tool_eval_invalid(self): """测试 tool 方法对无效请求的处理。""" with self.assertRaises(InvalidRequestArgumentError): result = self.general_ocr.tool_eval(name="general_ocr", streaming=True) next(result) def test_new_tool_eval(self): img_url = "https://bj.bcebos.com/v1/appbuilder/general_ocr_test.png?" \ "authorization=bce-auth-v1%2FALTAKGa8m4qCUasgoljdEDAzLm%2F2024-01-" \ "11T10%3A59%3A17Z%2F-1%2Fhost%2F081bf7bcccbda5207c82a4de074628b04ae" \ "857a27513734d765495f89ffa5f73" result = self.general_ocr.tool_eval(img_url=img_url, language_type='CHN_ENG', name="general_ocr", streaming=True,) for res in result: print(res) if __name__ == '__main__': unittest.main() ================================================ FILE: python/tests/test_get_app_list.py ================================================ # Copyright (c) 2023 Baidu, Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import os import unittest import appbuilder from appbuilder.utils.model_util import GetModelListRequest, Models, GetModelListResponse appbuilder.logger.setLoglevel("DEBUG") @unittest.skipUnless(os.getenv("TEST_CASE", "UNKNOWN") == "CPU_PARALLEL", "") class TestApps(unittest.TestCase): def setUp(self): """ 设置环境变量。 Args: None Returns: None. """ self.model = Models() def test_get_app_list(self): response = appbuilder.get_app_list() self.assertIsInstance(response, list) def test_get_app_list_v2(self): response = appbuilder.get_app_list(limit=2) self.assertIsInstance(response, list) self.assertEqual(len(response),2) def test_get_app_list_v3(self): self.assertRaises(ValueError, appbuilder.get_app_list, limit=200) self.assertRaises(ValueError, appbuilder.get_app_list, limit=0) def test_get_app_list_v4(self): self.assertRaises(ValueError, appbuilder.get_app_list, limit="a") def test_get_app_number(self): app_list = appbuilder.get_all_apps() self.assertIsInstance(app_list, list) if __name__ == '__main__': unittest.main() ================================================ FILE: python/tests/test_get_model_list.py ================================================ # Copyright (c) 2023 Baidu, Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import os import unittest import appbuilder from appbuilder.utils.model_util import ( GetModelListRequest, Models, GetModelListResponse, GetModelListRequestV2, GetModelListResponseV2, CommonModelV2 ) # @unittest.skipUnless(os.getenv("TEST_CASE", "UNKNOWN") == "CPU_PARALLEL", "") class TestModels(unittest.TestCase): def setUp(self): """ 设置环境变量。 Args: None Returns: None. """ self.model = Models() def test_get_model_list(self): """ get_model_list方法单测 Args: None Returns: None """ token = os.getenv("APPBUILDER_TOKEN") response = appbuilder.get_model_list(secret_key=token, api_type_filter=["text2image"]) print(response) self.assertIsNotNone(response) self.assertIsInstance(response, list) def test_list(self): """ list方法单测 Args: None Returns: None """ request = GetModelListRequest() response = self.model.list(request) self.assertIsNotNone(response) self.assertIsInstance(response, GetModelListResponse) def test_check_service_error(self): """ check_service_error方法单测 Args: None Returns: None """ data = {'error_msg': 'Error', 'error_code': 1} request_id = "request_id" with self.assertRaises(appbuilder.AppBuilderServerException): self.model._check_service_error(request_id, data) data = {'error_msg': 'No Error', 'error_code': 0} self.assertIsNone(self.model._check_service_error(request_id, data)) if __name__ == '__main__': unittest.main() ================================================ FILE: python/tests/test_hallucination_detection.py ================================================ # Copyright (c) 2023 Baidu, Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import os import unittest import appbuilder from appbuilder.core._exception import AppBuilderServerException TEST_QUERY = '澳门新麻蒲烤肉店每天开门吗?' TEST_CONTEXT = \ ('澳门美食: 澳门新麻蒲韩国烤肉店\n' '在澳门一年四季之中除了火锅,烤肉也相当受欢迎。提到韩烧,有一间令我印象最深刻,就是号称韩国第一的烤肉店-新麻蒲韩国烤肉店,光是韩国的分店便多' '达四百多间,海外分店更是遍布世界各地,2016年便落户澳门筷子基区,在原本已经食肆林立的地方一起百花齐放!店内的装修跟韩国分店还完度几乎没差,让' '食客彷如置身于韩国的感觉,还要大赞其抽风系统不俗,离开时身上都不会沾上烤肉味耶!\n' '时间:周一至周日 下午5:00 - 上午3:00\n' '电话:+853 2823 4012\n' '地址:澳门筷子基船澳街海擎天第三座地下O号铺96号\n' '必食推介:\n' '护心肉二人套餐\n' '来新麻蒲必试的有两样东西,现在差不多每间烤肉店都有炉边烤蛋,但大家知道吗?原来新麻蒲就是炉边烤蛋的开创者,既然是始祖,这已经是个非吃不可的理' '由!还有一款必试的就是护心肉,即是猪的横隔膜与肝中间的部分,每头猪也只有200克这种肉,非常珍贵,其味道吃起来有种独特的肉香味,跟牛护心肉一样' '精彩!\n' '秘制猪皮\n' '很多怕胖的女生看到猪皮就怕怕,但其实猪皮含有大量胶原蛋白,营养价值很高呢!这里红通通的猪皮还经过韩国秘制酱汁处理过,会有一点点辣味。烤猪皮的' '时候也需特别注意火侯,这样吃起来才会有外脆内Q的口感!') TEST_ANSWER = '澳门新麻蒲烤肉店并不是每天开门,周日休息。' class TestHallucinationDetectionComponent(unittest.TestCase): def setUp(self): """ 设置环境变量。 Args: 无参数,默认值为空。 Returns: 无返回值,方法中执行了环境变量的赋值操作。 """ self.model_name = 'DeepSeek-V3.1' secret_key = os.getenv('SECRET_KEY', None) self.hallucination_detection = appbuilder.HallucinationDetection(model=self.model_name, secret_key=secret_key) def test_run_with_default_params(self): """测试 run 方法使用默认参数 """ query = TEST_QUERY context = TEST_CONTEXT answer = TEST_ANSWER msg = appbuilder.Message({'query': query, 'context': context, 'answer': answer}) answer = self.hallucination_detection(msg) # print(answer) self.assertIsNotNone(answer) print(f'\n[result]\n{answer.content}\n') def test_run_with_stream_and_temperature(self): """测试不同的 stream 和 temperature 参数值 """ query = TEST_QUERY context = TEST_CONTEXT answer = TEST_ANSWER msg = appbuilder.Message({'query': query, 'context': context, 'answer': answer}) answer = self.hallucination_detection(msg, stream=False, temperature=0.5) # print(answer) self.assertIsNotNone(answer) print(f'\n[result]\n{answer.content}\n') def test_tool_eval_with_default_params(self): """测试 tool_eval 方法使用默认参数 """ query = TEST_QUERY context = TEST_CONTEXT answer = TEST_ANSWER answer = self.hallucination_detection.tool_eval(name='', query=query, context=context, answer=answer) # print(answer) self.assertIsNotNone(answer) print(f'\n[result]\n{answer}\n') def test_tool_eval_with_model_configs(self): """测试 tool_eval 方法使用不同temperature和top_p参数值。 """ query = TEST_QUERY context = TEST_CONTEXT answer = TEST_ANSWER model_configs = {'temperature': 0.5, 'top_p': 0.5} answer = self.hallucination_detection.tool_eval(name='', stream=True, query=query, context=context, answer=answer, model_configs=model_configs) # print(answer) self.assertIsNotNone(answer) print(f'\n[result]\n') for ans in answer: print(ans) def test_tool_eval_with_default_params(self): """测试 tool_eval 方法使用默认参数 """ query = TEST_QUERY context = TEST_CONTEXT answer = TEST_ANSWER answer = self.hallucination_detection.tool_eval(name='', query=query, context=context, answer=answer) # print(answer) self.assertIsNotNone(answer) print(f'\n[result]\n{answer}\n') def test_tool_eval_with_model_configs(self): """测试 tool_eval 方法使用不同temperature和top_p参数值。 """ query = TEST_QUERY context = TEST_CONTEXT answer = TEST_ANSWER model_configs = {'temperature': 0.5, 'top_p': 0.5} answer = self.hallucination_detection.tool_eval(name='', stream=True, query=query, context=context, answer=answer, model_configs=model_configs) # print(answer) self.assertIsNotNone(answer) print(f'\n[result]\n') for ans in answer: print(ans) if __name__ == '__main__': unittest.main() ================================================ FILE: python/tests/test_handwrite_ocr.py ================================================ # Copyright (c) 2023 Baidu, Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import os import unittest import requests import appbuilder from appbuilder.core.message import Message from appbuilder.core._exception import InvalidRequestArgumentError @unittest.skipUnless(os.getenv("TEST_CASE", "UNKNOWN") == "CPU_PARALLEL", "") class TestPlantRecognition(unittest.TestCase): def setUp(self): """ 设置环境变量 Args: None. Returns: None. """ # 从BOS存储读取样例文件 self.image_url=("https://bj.bcebos.com/v1/appbuilder/test_handw" "rite_ocr.jpg?authorization=bce-auth-v1%2FALTAKGa8" "m4qCUasgoljdEDAzLm%2F2024-01-23T11%3A58%3A09Z%2F-1%2Fhost%2" "F677f93445fb65157bee11cd492ce213d5c56e7a41827e45ce7e32b083d195c8b") self.raw_image = requests.get(self.image_url).content self.handwrite_ocr = appbuilder.HandwriteOCR() # 输入参数为一张图片 def test_run_with_image_url(self): """ 使用图片url进行单测 Args: None Returns: None """ # Create message with raw_image inp = Message(content={"url": self.image_url}) msg = self.handwrite_ocr.run(inp) self.assertIsNotNone(msg.content) def test_run_with_raw_image(self): """ 使用原始图片进行单测 Args: None Returns: None """ # Create message with raw_image inp = Message(content={"raw_image": self.raw_image}) msg = self.handwrite_ocr.run(inp) self.assertIsNotNone(msg.content) def test_tool_eval(self): result=self.handwrite_ocr.tool_eval(name='name',streaming=False,files=['test']) with self.assertRaises(InvalidRequestArgumentError): next(result) result=self.handwrite_ocr.tool_eval( name='name', streaming=True, file_names=['test'], file_urls={'test':self.image_url} ) res=next(result) self.assertEqual(res['visible_scope'],'llm') res=next(result) self.assertEqual(res['visible_scope'],'user') if __name__ == '__main__': unittest.main() ================================================ FILE: python/tests/test_image_understand.py ================================================ # Copyright (c) 2023 Baidu, Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import os import unittest import requests import appbuilder import time from appbuilder.core.message import Message from appbuilder.core._exception import AppBuilderServerException @unittest.skipUnless(os.getenv("TEST_CASE", "UNKNOWN") == "CPU_PARALLEL", "") class TestImageUnderstand(unittest.TestCase): def setUp(self): """ 设置环境变量 Args: None. Returns: None. """ # 从BOS存储读取样例文件 self.image_url = "https://bj.bcebos.com/v1/appbuilder/test_image_understand.jpeg?authorization=bce-auth-v1%2FALTAKGa8m4qCUasgoljdEDAzLm%2F2024-01-24T09%3A41%3A01Z%2F-1%2Fhost%2Fe8665506e30e0edaec4f1cc84a2507c4cb3fdb9b769de3a5bfe25c372b7e56e6" self.raw_image = requests.get(self.image_url).content self.image_understand = appbuilder.ImageUnderstand() # 输入参数为一张图片 def test_run_with_image_url(self): """ 使用图片url进行单测 Args: None Returns: None """ # Create message with raw_image inp = Message(content={"url": self.image_url, "question": "图像内容是什么?"}) msg = self.image_understand.run(inp) self.assertIsNotNone(msg.content) time.sleep(1) def test_run_with_raw_image(self): """ 使用原始图片进行单测 Args: None Returns: None """ # Create message with raw_image inp = Message(content={"raw_image": self.raw_image, "question": "图像内容是什么?"}) msg = self.image_understand.run(inp) self.assertIsNotNone(msg.content) time.sleep(1) def test_tool_eval_valid(self): """测试 tool 方法对有效请求的处理。""" img_url = "https://bj.bcebos.com/v1/appbuilder/animal_recognize_test.png?" \ "authorization=bce-auth-v1%2FALTAKGa8m4qCUasgoljdEDAzLm%2F2024-01-24T" \ "12%3A19%3A16Z%2F-1%2Fhost%2F411bad53034fa8f9c6edbe5c4909d76ecf6fad68" \ "62cf937c03f8c5260d51c6ae" img_name = "test_img.jpg" file_urls = {img_name: img_url} result = self.image_understand.tool_eval(name="image_understand", streaming=True, img_name=img_name, file_urls=file_urls, origin_query="") res = [item for item in result] self.assertNotEqual(len(res), 0) time.sleep(1) def test_tool_eval_invalid(self): """测试 tool 方法对无效请求的处理。""" with self.assertRaises(ValueError): result = self.image_understand.tool_eval(name="image_understand", streaming=True, origin_query="") next(result) time.sleep(1) def test_run_language_en(self): """测试 tool 方法对无效请求的处理。""" inp = Message(content={"raw_image": self.raw_image, "question": "图像内容是什么?", "language": "en"}) self.image_understand.run(inp) time.sleep(1) def test_run_raise(self): # question is empty with self.assertRaises(ValueError): inp = Message(content={"raw_image": self.raw_image, "question": ""}) self.image_understand.run(inp) # question length bigger than 100 with self.assertRaises(ValueError): question="test"*26 inp = Message(content={"raw_image": self.raw_image, "question": question, "language": ""}) self.image_understand.run(inp) if __name__ == "__main__": unittest.main() ================================================ FILE: python/tests/test_is_complex_query.py ================================================ # Copyright (c) 2023 Baidu, Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import unittest import os import appbuilder @unittest.skipUnless(os.getenv("TEST_CASE", "UNKNOWN") == "CPU_PARALLEL", "") class TestIsComplexQueryComponent(unittest.TestCase): def setUp(self): """ 设置环境变量。 Args: 无参数,默认值为空。 Returns: 无返回值,方法中执行了环境变量的赋值操作。 """ self.model_name = "DeepSeek-V3.1" self.node = appbuilder.IsComplexQuery(model=self.model_name) def test_run_with_default_params(self): """测试 run 方法使用默认参数""" query = "吸塑包装盒在工业化生产和物流运输中分别有什么重要性?" msg = appbuilder.Message(query) answer = self.node(msg) self.assertIsNotNone(answer) # def test_run_with_custom_params(self): # """测试 run 方法使用自定义参数""" # query = "吸塑包装盒在工业化生产和物流运输中分别有什么重要性?" # msg = appbuilder.Message(query) # answer = self.node(msg, stream=True, temperature=0.5) # self.assertIsNotNone(answer) # # 检查 answer 是否符合预期 def test_run_with_invalid_params(self): """测试 run 方法使用无效参数""" query = "吸塑包装盒在工业化生产和物流运输中分别有什么重要性?" msg = appbuilder.Message(query) with self.assertRaises((ValueError, TypeError)): self.node(msg, invalid_param="invalid") def test_tool_eval_valid(self): """测试 tool 方法对有效请求的处理。""" params = { 'name': 'is_complex_query', 'query': '吸塑包装盒在工业化生产和物流运输中分别有什么重要性?' } result = self.node.tool_eval(streaming=True, **params) res = [item for item in result] self.assertNotEqual(len(res), 0) result = self.node.tool_eval(streaming=False, **params) res = [item for item in result] def test_tool_eval_invalid(self): """测试 tool 方法对无效请求的处理。""" with self.assertRaises(ValueError): params = { 'name': 'is_complex_query' } result = self.node.tool_eval(streaming=True, **params) next(result) if __name__ == '__main__': unittest.main() ================================================ FILE: python/tests/test_knowledge_base.py ================================================ # Copyright (c) 2024 Baidu, Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import unittest import appbuilder import os from appbuilder.core._exception import BadRequestException from appbuilder.core.console.knowledge_base import data_class class TestKnowLedge(unittest.TestCase): def setUp(self): self.whether_create_knowledge_base = False def test_doc_knowledage(self): dataset_id = os.getenv("DATASET_ID", "UNKNOWN") appbuilder.logger.setLoglevel('DEBUG') knowledge = appbuilder.KnowledgeBase(knowledge_id=dataset_id) upload_res = knowledge.upload_file( "./data/qa_appbuilder_client_demo.pdf") add_res = knowledge.add_document( content_type="raw_text", file_ids=[upload_res.id], custom_process_rule=appbuilder.CustomProcessRule( separators=["?"], target_length=400, overlap_rate=0.2 ), ) list_res = knowledge.get_documents_list() delete_res = knowledge.delete_document( document_id=add_res.document_ids[0]) all_doc = knowledge.get_all_documents() self.assertIsInstance(all_doc, list) def test_get_documents_number_raise(self): knowledge = appbuilder.KnowledgeBase() with self.assertRaises(ValueError): knowledge.get_all_documents() def test_xlsx_knowledage(self): dataset_id = os.getenv("DATASET_ID", "UNKNOWN") knowledge = appbuilder.KnowledgeBase(knowledge_id=dataset_id) upload_res = knowledge.upload_file("./data/qa_demo.xlsx") add_res = knowledge.add_document( content_type="qa", file_ids=[upload_res.id]) list_res = knowledge.get_documents_list() delete_res = knowledge.delete_document( document_id=add_res.document_ids[0]) def test_create_knowledge_base(self): knowledge = appbuilder.KnowledgeBase() appbuilder.logger.setLoglevel("DEBUG") try: resp = knowledge.create_knowledge_base( name="test", description="test", type="public", pathPrefix="/全部群组", ) knowledge_base_id = resp.id knowledge.get_knowledge_base_detail(knowledge_base_id) knowledge.get_knowledge_base_list(knowledge_base_id, maxKeys=10) self.whether_create_knowledge_base = True except BadRequestException as e: print("create_knowledge_base函数运行失败{},将调用本地DATASET_ID".format(e)) knowledge_base_id = os.getenv('DATASET_ID', 'UNKNOWN') create_documents_response = knowledge.create_documents( id=knowledge_base_id, contentFormat="rawText", source=appbuilder.DocumentSource( type="web", urls=["https://baijiahao.baidu.com/s?id=1802527379394162441"], urlDepth=1, urlConfigs=[appbuilder.DocumentSourceUrlConfig(frequency=1)] ), processOption=appbuilder.DocumentProcessOption( template="custom", parser=appbuilder.DocumentChoices( choices=["layoutAnalysis", "ocr"] ), chunker=appbuilder.DocumentChunker( choices=["separator"], separator=appbuilder.DocumentSeparator( separators=["。"], targetLength=300, overlapRate=0.25, ), prependInfo=["title", "filename"], ), knowledgeAugmentation=appbuilder.DocumentChoices(choices=[ "faq"]), ), ) self.assertIsInstance(create_documents_response.documentIds, list) upload_documents_response = knowledge.upload_documents( id=knowledge_base_id, content_format="rawText", file_path="./data/qa_appbuilder_client_demo.pdf", processOption=appbuilder.DocumentProcessOption( template="custom", parser=appbuilder.DocumentChoices( choices=["layoutAnalysis", "ocr"] ), chunker=appbuilder.DocumentChunker( choices=["separator"], separator=appbuilder.DocumentSeparator( separators=["。"], targetLength=300, overlapRate=0.25, ), prependInfo=["title", "filename"], ), knowledgeAugmentation=appbuilder.DocumentChoices(choices=[ "faq"]), ), ) self.assertIsInstance(upload_documents_response.documentId, str) knowledge.get_documents_list( knowledge_base_id=knowledge_base_id) list_res = knowledge.describe_documents(knowledge_base_id=knowledge_base_id) document_id = list_res.data[-1].id knowledge.describe_chunks(document_id, knowledgebase_id=knowledge_base_id, keyword="test") resp = knowledge.create_chunk(document_id, content="test", knowledgebase_id=knowledge_base_id) chunk_id = resp.id knowledge.modify_chunk(chunk_id, content="new test", enable=True, knowledgebase_id=knowledge_base_id) # 目前openapi有延迟,后续openapi完善后,删除注释 knowledge.describe_chunk(chunk_id, knowledgebase_id=knowledge_base_id) knowledge.delete_chunk(chunk_id, knowledgebase_id=knowledge_base_id) knowledge.modify_knowledge_base( knowledge_base_id=knowledge_base_id, name="test", pathPrefix="/全部群组", ) if self.whether_create_knowledge_base: knowledge.delete_knowledge_base(knowledge_base_id) def test_query_knowledge_base(self): knowledge = appbuilder.KnowledgeBase() appbuilder.logger.setLoglevel("DEBUG") client = appbuilder.KnowledgeBase() res = client.query_knowledge_base( query="民法典第三条", type="fulltext", knowledgebase_ids=["70c6375a-1595-41f2-9a3b-e81bc9060b7f"], top=5, skip=0, metadata_filters=data_class.MetadataFilters(filters=[], condition="or"), pipeline_config=data_class.QueryPipelineConfig( id="pipeline_001", pipeline=[ { "name": "step1", "type": "elastic_search", "threshold": 0.1, "top": 400, "pre_ranking": { "bm25_weight": 0.25, "vec_weight": 0.75, "bm25_b": 0.75, "bm25_k1": 1.5, "bm25_max_score": 50, }, }, { "name": "step2", "type": "ranking", "inputs": ["step1"], "model_name": "ranker-v1", "top": 20, }, ], ), ) chunk_id = res.chunks[0].chunk_id self.assertIsNotNone(chunk_id) if __name__ == "__main__": unittest.main() ================================================ FILE: python/tests/test_landmark_recognize.py ================================================ # Copyright (c) 2023 Baidu, Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import os import unittest import requests import appbuilder from appbuilder.core.message import Message @unittest.skipUnless(os.getenv("TEST_CASE", "UNKNOWN") == "CPU_PARALLEL", "") class TestLandmarkRecognition(unittest.TestCase): def setUp(self): """ 设置环境变量。 Args: None Returns: None. """ self.landmark_recognition = appbuilder.LandmarkRecognition() image_url = "https://bj.bcebos.com/v1/appbuilder/landmark_test.jpeg?" \ "authorization=bce-auth-v1%2FALTAKGa8m4qCUasgoljdEDAzLm%2F2024-01-" \ "11T10%3A59%3A56Z%2F-1%2Fhost%2Fc249a068c6f321b91" \ "da0d0fd629b26ded58dcac2b6a3674f32378f5eb8df1ed0" self.raw_image = requests.get(image_url).content def test_run_with_raw_image(self): """ 使用原始图片进行单测 Args: None Returns: None """ # Create message with raw_image message = Message(content={"raw_image": self.raw_image}) # Recognize landmark output = self.landmark_recognition.run(message) # Assert output is not None self.assertIsNotNone(output) def test_run_with_no_image(self): """ Testing run method with no image. This should raise a ValueError. Args: None Returns: None """ # create empty message message = Message(content={}) # Assert ValueError is raised with self.assertRaises(ValueError): self.landmark_recognition.run(message) def test_run_with_timeout_and_retry(self): """ Testing run method with timeout and retry parameters. Args: None Returns: None """ # Create message with raw_image message = Message(content={"raw_image": self.raw_image}) # Recognize landmark with timeout and retry parameters output = self.landmark_recognition.run(message, timeout=5.0, retry=3) # Assert output is not None self.assertIsNotNone(output) if __name__ == '__main__': unittest.main() ================================================ FILE: python/tests/test_langchain_adapter_run.py ================================================ # Copyright (c) 2024 Baidu, Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import os import unittest import appbuilder from appbuilder.core.message import Message from appbuilder.core.component import Component class HelloWorldComponent(Component): manifests = [ { "name": "hello_world", "description": "向使用这个工具的人打招呼", "parameters": { "type": "object", "properties": { "name": { "type": "string", "description": "使用者的名字" } } } } ] def run(self, name: str, **kwargs): return "hello world from {}".format(name) @unittest.skipUnless(os.getenv("TEST_CASE", "UNKNOWN") == "CPU_PARALLEL", "") class TestLandmarkRecognition(unittest.TestCase): def setUp(self): self.component = HelloWorldComponent() def test_to_langchain_tool(self): tool = self.component.create_langchain_tool() from langchain.tools import StructuredTool self.assertIsInstance(tool, StructuredTool) def test_langchain_tool_run(self): tool = self.component.create_langchain_tool() res = tool.run( tool_input = { "name": "test" } ) self.assertEqual(res, "hello world from test") def test_langchin_tool_elements(self): tool = self.component.create_langchain_tool() name = tool.name self.assertEqual(name, "hello_world") desc = tool.description self.assertEqual(desc, "向使用这个工具的人打招呼") args = tool.args self.assertEqual(args, {'name': {'anyOf': [{'type': 'string'}, {'type': 'null'}], 'default': None, 'description': '使用者的名字', 'title': 'Name'}}) if __name__ == '__main__': unittest.main() ================================================ FILE: python/tests/test_langchain_adapter_tool_eval.py ================================================ # Copyright (c) 2024 Baidu, Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import os import unittest import appbuilder from appbuilder.core.message import Message from appbuilder.core.component import Component class HelloWorldComponent(Component): manifests = [ { "name": "hello_world", "description": "向使用这个工具的人打招呼", "parameters": { "type": "object", "properties": { "name": { "type": "string", "description": "使用者的名字" } } } } ] def run(self, name: str, **kwargs): return Message(content="hello world from {}".format(name)) def tool_eval(self, name: str, **kwargs): print("name", name) res = self.run(name) print(res) yield { "type": "text", "text": res.content, "visible_scope": "user" } @unittest.skipUnless(os.getenv("TEST_CASE", "UNKNOWN") == "CPU_PARALLEL", "") class TestLandmarkRecognition(unittest.TestCase): def setUp(self): self.component = HelloWorldComponent() def test_to_langchain_tool(self): tool = self.component.create_langchain_tool() from langchain.tools import StructuredTool self.assertIsInstance(tool, StructuredTool) def test_langchain_tool_run(self): tool = self.component.create_langchain_tool() res = tool.run( tool_input = { "name": "test" } ) self.assertEqual(res, "hello world from test") def test_langchin_tool_elements(self): tool = self.component.create_langchain_tool() name = tool.name self.assertEqual(name, "hello_world") desc = tool.description self.assertEqual(desc, "向使用这个工具的人打招呼") args = tool.args self.assertEqual(args, {'name': {'anyOf': [{'type': 'string'}, {'type': 'null'}], 'default': None, 'description': '使用者的名字', 'title': 'Name'}}) if __name__ == '__main__': unittest.main() ================================================ FILE: python/tests/test_langchain_error.py ================================================ # Copyright (c) 2024 Baidu, Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import os import unittest import appbuilder from appbuilder.core.message import Message from appbuilder.core.component import Component class HelloWorldComponentwithoutMainfest(Component): def run(self, name: str, **kwargs): return Message(content="hello world from {}".format(name)) class HelloWorldComponentwithMultiTools(Component): manifests = [ { "name": "hello_world", "description": "向使用这个工具的人打招呼", "parameters": { "type": "object", "properties": { "name": { "type": "string", "description": "使用者的名字" } } } }, { "name": "hello_world_2", "description": "向使用这个工具的人打招呼", }, { "name": "general_ocr", "description": "提供更高精度的通用文字识别能力,能够识别图片中的文字,不支持html后缀文件的输入", "parameters": { "type": "object", "properties": { "img_url": { "type": "string", "description": "待识别图片的url,根据该url能够获取图片" }, "img_name": { "type": "string", "description": "待识别图片的文件名,用于生成图片url" }, }, "anyOf": [ { "required": [ "img_url" ] }, { "required": [ "img_name" ] } ] } } ] def run(self, name: str, **kwargs): return Message(content="hello world from {}".format(name)) @unittest.skipUnless(os.getenv("TEST_CASE", "UNKNOWN") == "CPU_PARALLEL", "") class TestLandmarkRecognition(unittest.TestCase): def test_without_mainfest(self): component = HelloWorldComponentwithoutMainfest() with self.assertRaises(ValueError): tool = component.create_langchain_tool() def test_with_multi_tools(self): component = HelloWorldComponentwithMultiTools() with self.assertRaises(ValueError): tool = component.create_langchain_tool() def test_with_multi_tools_v2(self): component = HelloWorldComponentwithMultiTools() tools = component.create_langchain_tool(tool_name="hello_world") def test_with_multi_tools_v3(self): component = HelloWorldComponentwithMultiTools() with self.assertRaises(ValueError): tools = component.create_langchain_tool(tool_name="hello_world_3") def test_with_multi_tools_v4(self): component = HelloWorldComponentwithMultiTools() with self.assertRaises(RuntimeError): tools = component.create_langchain_tool(tool_name="hello_world_2") def test_with_multi_tools_v5(self): component = HelloWorldComponentwithMultiTools() tools = component.create_langchain_tool(tool_name="general_ocr") if __name__ == '__main__': unittest.main() ================================================ FILE: python/tests/test_llm_base.py ================================================ import unittest import os import appbuilder class ErrorComponent(appbuilder.Playground): def completion( self, version, base_url, request, timeout: float = None, retry: int = 0, request_id: str = None, ): r"""Send a byte array of an audio file to obtain the result of speech recognition.""" headers = self.http_client.auth_header(request_id) headers["Content-Type"] = "application/json" completion_url = "/" + self.version + "/api/llm/" + self.name stream = True if request.response_mode == "streaming" else False url = self.http_client.service_url(completion_url, self.base_url) request.params["model_config"]["model"]["name"] = "" request.params["model_config"]["model"]["url"] = "" response = self.http_client.session.post(url, json=request.params, headers=headers, timeout=timeout, stream=stream) return self.gene_response(response, stream) @unittest.skipUnless(os.getenv("TEST_CASE", "UNKNOWN") == "CPU_PARALLEL", "") class TestLlmBase(unittest.TestCase): def test_err_request(self): """ 测试在消息有效时运行 """ cmpt = ErrorComponent(prompt_template="{query}", model="DeepSeek-V3.1") msg = appbuilder.Message({ "query": "小明", }) answer = cmpt.run(message=msg, stream=True, temperature=1) with self.assertRaises(Exception): for x in answer.content: pass if __name__ == '__main__': unittest.main() ================================================ FILE: python/tests/test_log_set_log_config.py ================================================ # Copyright (c) 2024 Baidu, Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import os import time import logging import unittest from appbuilder import SizeAndTimeRotatingFileHandler from appbuilder.utils.logger_util import LoggerWithLoggerId class TestLogSetLogConfig(unittest.TestCase): def test_set_log_config(self): lwl=LoggerWithLoggerId(logger='test_logger',extra={'logid':'test_logid'},loglevel='INFO') lwl.setLogConfig( console_output = True, loglevel='DEBUG', file_name='test.log', rotate_frequency='D', rotate_interval=0, # 测试rotate_interval<1时,自动更新为1 max_file_size=None, # 测试not max_file_size or max_file_size <= 0时,自动更新为sys.maxsize total_log_size=None, # 测试not total_log_size or total_log_size <= 0时,自动更新为sys.maxsize max_log_files=None, # 测试not max_log_files or max_log_files <= 0时,自动更新为sys.maxsize ) def test_set_log_config_log_path(self): os.environ["APPBUILDER_LOGPATH"] = "/tmp" lwl=LoggerWithLoggerId(logger='test_logger',extra={'logid':'test_logid'},loglevel='INFO') lwl.setLogConfig( console_output = True, loglevel='DEBUG', log_path='/tmp', file_name='test.log', rotate_frequency='D', rotate_interval=0, # 测试rotate_interval<1时,自动更新为1 max_file_size=None, # 测试not max_file_size or max_file_size <= 0时,自动更新为sys.maxsize total_log_size=None, # 测试not total_log_size or total_log_size <= 0时,自动更新为sys.maxsize max_log_files=None, # 测试not max_log_files or max_log_files <= 0时,自动更新为sys.maxsize ) def test_set_log_config_raise_error(self): lwl=LoggerWithLoggerId(logger='test_logger',extra={'logid':'test_logid'},loglevel='INFO') with self.assertRaises(ValueError): lwl.setLogConfig( console_output = True, loglevel='DEBUG', file_name='test.log', rotate_frequency='ERROR-FREQUENCY', rotate_interval=0, # 测试rotate_interval<1时,自动更新为1 max_file_size=None, # 测试not max_file_size or max_file_size <= 0时,自动更新为sys.maxsize total_log_size=None, # 测试not total_log_size or total_log_size <= 0时,自动更新为sys.maxsize max_log_files=None, # 测试not max_log_files or max_log_files <= 0时,自动更新为sys.maxsize ) with self.assertRaises(ValueError): lwl.setLogConfig( console_output = True, loglevel='ERROR-LEVEL', file_name='test.log', rotate_frequency='D', rotate_interval=0, # 测试rotate_interval<1时,自动更新为1 max_file_size=0, # 测试not max_file_size or max_file_size <= 0时,自动更新为sys.maxsize total_log_size=None, # 测试not total_log_size or total_log_size <= 0时,自动更新为sys.maxsize max_log_files=None, # 测试not max_log_files or max_log_files <= 0时,自动更新为sys.maxsize ) def test_rolling_with_time(self): time_msgs = ['S', 'M', 'H', 'D', 'MIDNIGHT'] for time_msg in time_msgs: logger = logging.getLogger('CustomLogger') logger.setLevel(logging.DEBUG) handler = SizeAndTimeRotatingFileHandler( file_name ='test.log', rotate_frequency=time_msg, rotate_interval=1, max_file_size=1024*100*1024, max_log_files=10, total_log_size=1024*300*1024 ) formatter = logging.Formatter('%(asctime)s - %(levelname)s - %(message)s') handler.setFormatter(formatter) logger.addHandler(handler) for _ in range(2): logger.info("This is a test log message.") time.sleep(0.1) def test_rolling_with_size(self): logger = logging.getLogger('CustomLogger') logger.setLevel(logging.DEBUG) handler = SizeAndTimeRotatingFileHandler( file_name ='test.log', rotate_frequency='S', rotate_interval=10, max_file_size=1*1024, max_log_files=2, total_log_size=1024*300*1024 ) formatter = logging.Formatter('%(asctime)s - %(levelname)s - %(message)s') handler.setFormatter(formatter) logger.addHandler(handler) for i in range(100): logger.info("This is a test log message."*100) time.sleep(0.001) def test_rolling_to_total_max_size(self): logger = logging.getLogger('CustomLogger') logger.setLevel(logging.DEBUG) handler = SizeAndTimeRotatingFileHandler( file_name ='test.log', rotate_frequency='S', rotate_interval=100, max_file_size=10*1024, max_log_files=10000, total_log_size=20*1024 ) formatter = logging.Formatter('%(asctime)s - %(levelname)s - %(message)s') handler.setFormatter(formatter) logger.addHandler(handler) for _ in range(100): logger.info("This is a test log message."*100) time.sleep(0.001) if __name__ == '__main__': unittest.main() ================================================ FILE: python/tests/test_manifest.py ================================================ import unittest import os from typing import Any, Dict, List, Optional import appbuilder from appbuilder import Manifest from appbuilder import manifest, manifest_parameter @unittest.skipUnless(os.getenv("TEST_CASE", "UNKNOWN") == "CPU_SERIAL", "") class TestManifest(unittest.TestCase): def setUp(self): """ 设置环境变量。 Args: 无参数,默认值为空。 Returns: 无返回值,方法中执行了环境变量的赋值操作。 """ os.environ["APPBUILDER_TOKEN"] = ( "your api key" ) self.app_id = "7cc4c21f-0e25-4a76-baf7-01a2b923a1a7" def test_google_style(self): # Generated by vscode plugin # https://marketplace.visualstudio.com/items?itemName=njpwerner.autodocstring def google_style( name: str, val: str = None, val_obj: Optional[Any] = None, val_list: List[str] = None, data: Dict[str, int] = None, ) -> str: """Google style docstring. Args: name (str): Name of object. val (str, optional): Value of obj. Defaults to None. val_obj (Optional[Any], optional): Real object reference. Defaults to None. val_list (List[str], optional): List of items with object. Defaults to None. data (Dict[str, int], optional): Data along with object. Defaults to None. Returns: str: Styled string. """ return "" manifest_from_function = appbuilder.Manifest.from_function(google_style) # 断言顶层的结构 assert manifest_from_function.type == "function", "Type does not match 'function'" assert ( manifest_from_function.function["name"] == "google_style" ), "Function name does not match 'google_style'" assert ( manifest_from_function.function["description"] == """Google style docstring. Args: name (str): Name of object. val (str, optional): Value of obj. Defaults to None. val_obj (Optional[Any], optional): Real object reference. Defaults to None. val_list (List[str], optional): List of items with object. Defaults to None. data (Dict[str, int], optional): Data along with object. Defaults to None. Returns: str: Styled string. """ ), "Description does not match" # 断言参数结构 parameters = manifest_from_function.function["parameters"] assert parameters["type"] == "object", "Parameters type does not match 'object'" assert "properties" in parameters, "Properties not found in parameters" # 断言各个参数的类型和描述 properties = parameters["properties"] # name 参数 assert "name" in properties, "'name' parameter missing" # 添加类型检查时的调试信息 try: assert ( properties["name"]["type"] == "str" ), f"'name' type does not match 'str'. Actual type: {properties['name']['type']}" except AssertionError as e: print(f"Debug Info: Actual 'name' type is {properties['name']['type']}") raise e # 重新抛出异常 # val 参数 assert "val" in properties, "'val' parameter missing" assert properties["val"]["type"] == "str", "'val' type does not match 'str'" # val_obj 参数 assert "val_obj" in properties, "'val_obj' parameter missing" assert ( properties["val_obj"]["type"] == "Optional[Any]" ), "'val_obj' type does not match 'object'" # val_list 参数 assert "val_list" in properties, "'val_list' parameter missing" assert ( properties["val_list"]["type"] == "List[str]" ), "'val_list' type does not match 'array'" # data 参数 assert "data" in properties, "'data' parameter missing" assert ( properties["data"]["type"] == "Dict[str, int]" ), "'data' type does not match 'object'" # 断言必需参数 assert "required" in parameters, "'required' field missing in parameters" assert parameters["required"] == ["name"], "'required' does not match ['name']" def test_google_style_bad_args_return_dict(self): def func( bad_param: str, bad_generic_param: List[str], bad_format: int, val: str = None, ) -> Dict[str, str]: """Google style docstring. Args: bad param (str): Bad parameter, name contains whitespace. bad_generic_param (List): Bad generic parameter, use <> instead of [] bad_format (int) Bad arg doc format, lost :. val (str , optional): Value of obj. Defaults to None. Returns: Dict[str, str]: Returns a dict. """ return "" manifest_from_function = appbuilder.Manifest.from_function(func) # 断言顶层的结构 assert manifest_from_function.type == "function", "Type does not match 'function'" assert ( manifest_from_function.function["name"] == "func" ), "Function name does not match 'func'" assert ( manifest_from_function.function["description"] == """Google style docstring. Args: bad param (str): Bad parameter, name contains whitespace. bad_generic_param (List): Bad generic parameter, use <> instead of [] bad_format (int) Bad arg doc format, lost :. val (str , optional): Value of obj. Defaults to None. Returns: Dict[str, str]: Returns a dict. """ ), "Description does not match" # 断言参数结构 parameters = manifest_from_function.function["parameters"] assert parameters["type"] == "object", "Parameters type does not match 'object'" assert "properties" in parameters, "Properties not found in parameters" # 断言各个参数的类型和描述 properties = parameters["properties"] # bad_param 参数 assert "bad_param" in properties, "'bad_param' parameter missing" assert ( properties["bad_param"]["type"] == "str" ), "'bad_param' type does not match 'str'" # bad_format 参数 assert "bad_format" in properties, "'bad_format' parameter missing" assert ( properties["bad_format"]["type"] == "int" ), "'bad_format' type does not match 'int'" # val 参数 assert "val" in properties, "'val' parameter missing" assert properties["val"]["type"] == "str", "'val' type does not match 'str'" # 断言必需参数 assert "required" in parameters, "'required' field missing in parameters" assert parameters["required"] == [ "bad_param", "bad_generic_param", "bad_format", ], "'required' does not match expected required parameters" # 断言没有多余参数 assert len(properties) == 4, "Unexpected number of parameters in properties" def test_google_style_no_return(self): def func( name: str, ): """Google style docstring. Args: name (str): Name of object. """ return "" manifest_from_function = appbuilder.Manifest.from_function(func) # 断言顶层的结构 assert manifest_from_function.type == "function", "Type does not match 'function'" assert ( manifest_from_function.function["name"] == "func" ), "Function name does not match 'func'" assert ( manifest_from_function.function["description"] == """Google style docstring. Args: name (str): Name of object. """ ), "Description does not match" # 断言参数结构 parameters = manifest_from_function.function["parameters"] assert parameters["type"] == "object", "Parameters type does not match 'object'" assert "properties" in parameters, "Properties not found in parameters" # 断言参数类型和描述 properties = parameters["properties"] # name 参数 assert "name" in properties, "'name' parameter missing" assert properties["name"]["type"] == "str", "'name' type does not match 'str'" # 断言必需参数 assert "required" in parameters, "'required' field missing in parameters" assert parameters["required"] == ["name"], "'required' does not match ['name']" # 断言没有["parameters"][1]的参数了 assert not ( "parameters" in manifest_from_function.function and len(manifest_from_function.function["parameters"]) == 1 ) def test_no_doc(self): def func( name: str, /, *args, val: str = None, val_obj: Optional[Any] = None, data: Dict[str, int] = None, **kwargs, ) -> str: return "" # 断言这里会抛出缺少文档字符串的 ValueError 异常 try: manifest_from_function = appbuilder.Manifest.from_function(func) except ValueError as e: assert ( str(e) == "函数 func 缺少文档字符串" ), "未抛出预期的 ValueError 或信息不匹配" def test_decorator_google_style_basic(self): @manifest(description="Function with required parameter.") def func( name: str, ) -> str: """Function with required parameter. Args: name (str): Name of object. Returns: str: Styled string. """ return "" # 获取装饰器生成的 Manifest manifest_from_function = func.__ab_manifest__ # 断言顶层的结构 assert manifest_from_function.type == "function", "Type does not match 'function'" assert ( manifest_from_function.function["name"] == "func" ), "Function name does not match 'func'" assert ( manifest_from_function.function["description"] == "Function with required parameter." ), "Description does not match" # 断言参数结构 parameters = manifest_from_function.function["parameters"] assert parameters["type"] == "object", "Parameters type does not match 'object'" assert "properties" in parameters, "Properties not found in parameters" # 断言各个参数的类型和描述 properties = parameters["properties"] # name 参数 assert "name" in properties, "'name' parameter missing" assert properties["name"]["type"] == "str", "'name' type does not match 'str'" assert ( properties["name"]["description"] == None ), "'name' description does not match" # 断言必需参数 assert "required" in parameters, "'required' field missing in parameters" assert parameters["required"] == ["name"], "'required' does not match ['name']" def test_manifest_decorator(self): @appbuilder.manifest( description="获取指定中国城市的当前天气信息。仅支持中国城市的天气查询。参数 `location` 为中国城市名称,其他国家城市不支持天气查询。" ) @appbuilder.manifest_parameter( name="location", description="城市名,例如:北京。" ) @appbuilder.manifest_parameter( name="unit", description="温度单位,支持 'celsius' 或 'fahrenheit'" ) # 定义示例函数 def get_current_weather(location: str, unit) -> str: return "北京今天25度" manifest_from_function = appbuilder.Manifest.from_function(get_current_weather) assert manifest_from_function.function.get("description") is not None if __name__ == "__main__": unittest.main() ================================================ FILE: python/tests/test_manifest_decorator.py ================================================ # Copyright (c) 2024 Baidu, Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. import os import unittest from appbuilder import Manifest, manifest, manifest_parameter from appbuilder.core.manifest.manifest_decorator import _merge_dict, _update_list @unittest.skipUnless(os.getenv("TEST_CASE", "UNKNOWN") == "CPU_PARALLEL", "") class TestManifestDecorator(unittest.TestCase): def test_disable_docstring(self): @manifest(description="anotated function") @manifest_parameter(name="param", description="a parameter", type="str") def func(param: str) -> str: return param manifest_from_function = func.__ab_manifest__ # 断言顶层的结构 assert manifest_from_function.type == "function", "Type does not match 'function'" assert ( manifest_from_function.function["name"] == "func" ), "Function name does not match 'func'" assert ( manifest_from_function.function["description"] == "anotated function" ), "Description does not match" # 断言参数结构 parameters = manifest_from_function.function["parameters"] assert parameters["type"] == "object", "Parameters type does not match 'object'" assert "properties" in parameters, "Properties not found in parameters" # 断言具体参数 properties = parameters["properties"] assert "param" in properties, "'param' parameter missing" assert properties["param"]["type"] == "str", "'param' type does not match 'str'" assert ( properties["param"]["description"] == "a parameter" ), "'param' description does not match" # 断言必需参数 assert "required" in parameters, "'required' field missing in parameters" assert parameters["required"] == [ "param" ], "'required' does not match ['param']" def test_combine(self): @manifest() @manifest_parameter(name="param") def func(param: str = "[]") -> int: """An example function. Args: param (str): A list of numbers. Returns: int: The sum of parameter. """ return param # 获取装饰器生成的 Manifest manifest_from_function = func.__ab_manifest__ # 断言顶层结构 assert manifest_from_function.type == "function", "Type does not match 'function'" assert ( manifest_from_function.function["name"] == "func" ), "Function name does not match 'func'" assert ( manifest_from_function.function["description"] == """An example function. Args: param (str): A list of numbers. Returns: int: The sum of parameter. """ ), "Description does not match" # 断言参数结构 parameters = manifest_from_function.function["parameters"] assert parameters["type"] == "object", "Parameters type does not match 'object'" assert "properties" in parameters, "Properties not found in parameters" # 断言具体参数 properties = parameters["properties"] assert "param" in properties, "'param' parameter missing" assert properties["param"]["type"] == "str", "'param' type does not match 'str'" assert "description" in properties["param"], "'param' description missing" assert ( properties["param"]["description"] == None ), "'param' description does not match" # 断言必需参数 assert "required" in parameters, "'required' field missing in parameters" assert ( "param" not in parameters["required"] ), "'param' should not be required as it has a default value" def test_reversed_decorators(self): @manifest_parameter(name="param", description="DECORATOR A list of numbers.") @manifest() def func(param: str = "[]") -> int: """An example function. Args: param (str): A list of numbers. Returns: int: The sum of parameter. """ return param # 获取装饰器生成的 Manifest manifest_from_function = func.__ab_manifest__ # 断言顶层结构 assert manifest_from_function.type == "function", "Type does not match 'function'" assert ( manifest_from_function.function["name"] == "func" ), "Function name does not match 'func'" assert ( manifest_from_function.function["description"] == """An example function. Args: param (str): A list of numbers. Returns: int: The sum of parameter. """ ), "Description does not match" # 断言参数结构 parameters = manifest_from_function.function["parameters"] assert parameters["type"] == "object", "Parameters type does not match 'object'" assert "properties" in parameters, "Properties not found in parameters" # 断言具体参数 properties = parameters["properties"] assert "param" in properties, "'param' parameter missing" assert properties["param"]["type"] == "str", "'param' type does not match 'str'" # 断言必需参数 assert "required" in parameters, "'required' field missing in parameters" assert ( "param" in parameters["required"] ), "'param' should not be required as it has a default value" def test_only_function_decorator(self): @manifest() def func(param: str = "[]") -> int: " " return param view = func.__ab_manifest__ # 获取装饰器生成的 Manifest manifest_from_function = func.__ab_manifest__ # 断言顶层结构 assert manifest_from_function.type == "function", "Type does not match 'function'" assert ( manifest_from_function.function["name"] == "func" ), "Function name does not match 'func'" assert ( manifest_from_function.function["description"] == " " ), "Description should be None when not explicitly provided" # 断言参数结构 parameters = manifest_from_function.function["parameters"] assert parameters["type"] == "object", "Parameters type does not match 'object'" assert "properties" in parameters, "Properties not found in parameters" # 断言具体参数 properties = parameters["properties"] assert "param" in properties, "'param' parameter missing" assert properties["param"]["type"] == "str", "'param' type does not match 'str'" # 检查是否为必需参数 assert "required" in parameters, "'required' field missing in parameters" assert ( "param" not in parameters["required"] ), "'param' should not be required as it has a default value" def test_merge_dict(self): self.assertEqual(_merge_dict({}, {}), {}) self.assertEqual(_merge_dict({}, {"a": 1}), {"a": 1}) def test_update_list(self): def condition(item, new_item): return item['id'] == new_item['id'] def replacer(item, new_item): item.update(new_item) return item existing_item = {'id': 1, 'value': 'a'} new_item = {'id': 1, 'value': 'b'} list = [existing_item] expected_result = [new_item] self.assertEqual(_update_list(new_item, list, condition, replacer), expected_result) if __name__ == "__main__": unittest.main() ================================================ FILE: python/tests/test_manifest_signature.py ================================================ # Copyright (c) 2024 Baidu, Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import unittest import os from typing import Any, Dict, List, Optional, Union from appbuilder import Manifest, manifest @unittest.skipUnless(os.getenv("TEST_CASE", "UNKNOWN") == "CPU_PARALLEL", "") class TestManifestSignature(unittest.TestCase): def test_is_normal(self): @manifest() def func(): return 1 view = func.__ab_manifest__ assert isinstance(view, Manifest) def test_is_async(self): @manifest(description="test") async def func(): import asyncio await asyncio.sleep(0) view = func.__ab_manifest__ assert isinstance(view, Manifest) def test_is_stream(self): @manifest() def func(): for i in range(2): yield i view = func.__ab_manifest__ assert isinstance(view, Manifest) def test_is_async_and_stream(self): @manifest() async def func(): import asyncio for i in range(1): await asyncio.sleep(0) yield i view = func.__ab_manifest__ assert isinstance(view, Manifest) def test_decorator_google_style_function_description_no_args(self): @manifest() def func(): """A function to test function description. Args: name (str): Name of object. Returns: str: Styled string. """ return "" view = func.__ab_manifest__ assert isinstance(view, Manifest) assert view.function["name"] == "func" assert ( view.function["description"] == """A function to test function description. Args: name (str): Name of object. Returns: str: Styled string. """ ) # Assert that parameters are an empty dictionary since there are no function arguments assert view.function["parameters"]["properties"] == {} assert view.function["parameters"]["required"] == [] def test_decorator_google_style_basic(self): @manifest() def func( name: str, ) -> str: """Function with required parameter. Args: name (str): Name of object. Returns: str: Styled string. """ return "" view = func.__ab_manifest__ # 检查生成的 Manifest 对象 assert isinstance(view, Manifest) # 检查函数元信息 assert view.function["name"] == "func", "Function name does not match 'func'" assert ( view.function["description"] == """Function with required parameter. Args: name (str): Name of object. Returns: str: Styled string. """ ) # 检查参数结构 parameters = view.function["parameters"] assert parameters["type"] == "object", "Parameters type does not match 'object'" assert "properties" in parameters, "Properties not found in parameters" # 检查具体参数 'name' properties = parameters["properties"] assert "name" in properties, "'name' parameter missing" name_property = properties["name"] assert name_property["type"] == "str", "'name' type does not match 'str'" assert ( name_property["description"] is None ), "'name' description does not match None" assert name_property["required"] is True, "'name' required does not match True" def test_decorator_google_style_list(self): @manifest() def func( val: List[str], ) -> str: """Function with a List parameter. Args: val (List[str]): A list of strings. Returns: str: A result string. """ return "" view = func.__ab_manifest__ # 检查生成的 Manifest 对象 assert isinstance(view, Manifest) # 检查参数的总体结构 parameters = view.function["parameters"] assert parameters["type"] == "object", "Parameters type does not match 'object'" assert "properties" in parameters, "Properties not found in parameters" # 检查具体参数 'val' properties = parameters["properties"] assert "val" in properties, "'val' parameter missing" val_property = properties["val"] # 验证 'val' 参数的各项属性 assert ( val_property["type"] == "List[str]" ), "'val' type does not match 'List[str]'" assert val_property["required"] is True, "'val' required does not match True" def test_decorator_google_style_list_of_dicts(self): @manifest() def func( val: List[Dict[str, List[str]]], ) -> str: """Function with a complex nested parameter. Args: val (List[Dict[str, List[str]]]): A list of dictionaries mapping strings to lists of strings. Returns: str: A result string. """ return "" view = func.__ab_manifest__ # 检查生成的 Manifest 对象 assert isinstance(view, Manifest), "view is not an instance of Manifest" # 检查参数的总体结构 parameters = view.function["parameters"] assert parameters["type"] == "object", "Parameters type does not match 'object'" assert "properties" in parameters, "Properties not found in parameters" # 检查具体参数 'val' properties = parameters["properties"] assert "val" in properties, "'val' parameter missing" val_property = properties["val"] # 验证 'val' 参数的各项属性 assert ( val_property["type"] == "List[Dict[str, List[str]]]" ), "'val' type does not match 'List[Dict[str, List[str]]]'" assert val_property["required"] is True, "'val' required does not match True" def test_decorator_google_style_dict(self): @manifest() def func( val: Dict[str, Any], ) -> str: """Function with a dictionary parameter. Args: val (Dict[str, Any]): A dictionary with string keys and any values. Returns: str: A result string. """ return "" view = func.__ab_manifest__ # 检查生成的 Manifest 对象 assert isinstance(view, Manifest), "view is not an instance of Manifest" # 检查参数的总体结构 parameters = view.function["parameters"] assert parameters["type"] == "object", "Parameters type does not match 'object'" assert "properties" in parameters, "Properties not found in parameters" # 检查具体参数 'val' properties = parameters["properties"] assert "val" in properties, "'val' parameter missing" val_property = properties["val"] # 验证 'val' 参数的各项属性 assert ( val_property["type"] == "Dict[str, Any]" ), "'val' type does not match 'Dict[str, Any]'" assert val_property["required"] is True, "'val' required does not match True" def test_decorator_google_style_dict_of_lists(self): @manifest() def func( val: Dict[str, List[Dict[str, List[str]]]], ) -> str: """Function with a complex nested parameter. Args: val (Dict[str, List[Dict[str, List[str]]]]): A dictionary where keys are strings and values are lists of dictionaries. Returns: str: A result string. """ return "" view = func.__ab_manifest__ # 检查生成的 Manifest 对象 assert isinstance(view, Manifest), "view is not an instance of Manifest" # 检查参数的总体结构 parameters = view.function["parameters"] assert parameters["type"] == "object", "Parameters type does not match 'object'" assert "properties" in parameters, "Properties not found in parameters" # 检查具体参数 'val' properties = parameters["properties"] assert "val" in properties, "'val' parameter missing" val_property = properties["val"] # 验证 'val' 参数的各项属性 assert ( val_property["type"] == "Dict[str, List[Dict[str, List[str]]]]" ), "'val' type does not match 'Dict[str, List[Dict[str, List[str]]]]'" assert val_property["required"] is True, "'val' required does not match True" def test_decorator_google_style_union_simple(self): @manifest() def func( val: Union[str, int, Any], ) -> str: """Function with a Union parameter. Args: val (Union[str, int, Any]): A parameter that can accept multiple types. Returns: str: A result string. """ return "" view = func.__ab_manifest__ # 检查生成的 Manifest 对象 assert isinstance(view, Manifest), "view is not an instance of Manifest" # 检查参数的总体结构 parameters = view.function["parameters"] assert parameters["type"] == "object", "Parameters type does not match 'object'" assert "properties" in parameters, "Properties not found in parameters" # 检查具体参数 'val' properties = parameters["properties"] assert "val" in properties, "'val' parameter missing" val_property = properties["val"] # 验证 'val' 参数的各项属性 assert ( val_property["type"] == "Union[str, int, Any]" ), "'val' type does not match 'Union[str, int, Any]'" assert val_property["required"] is True, "'val' required does not match True" def test_decorator_google_style_union(self): @manifest() def func( val: Union[str, List[int]], ) -> str: """Function with a Union parameter. Args: val (Union[str, List[int]]): A parameter that can accept a string or a list of integers. Returns: str: A result string. """ return "" view = func.__ab_manifest__ # 检查生成的 Manifest 对象 assert isinstance(view, Manifest), "view is not an instance of Manifest" # 检查参数的总体结构 parameters = view.function["parameters"] assert parameters["type"] == "object", "Parameters type does not match 'object'" assert "properties" in parameters, "Properties not found in parameters" # 检查具体参数 'val' properties = parameters["properties"] assert "val" in properties, "'val' parameter missing" val_property = properties["val"] # 验证 'val' 参数的各项属性 assert ( val_property["type"] == "Union[str, List[int]]" ), "'val' type does not match 'Union[str, List[int]]'" assert val_property["required"] is True, "'val' required does not match True" def test_decorator_google_style_union_nest1_dict(self): @manifest() def func( val: Union[float, Dict[str, int]], ) -> str: """Function with a nested Union parameter. Args: val (Union[float, Dict[str, int]]): A parameter that can accept a float or a dictionary with string keys and integer values. Returns: str: A result string. """ return "" view = func.__ab_manifest__ # 检查生成的 Manifest 对象 assert isinstance(view, Manifest), "view is not an instance of Manifest" # 检查参数的总体结构 parameters = view.function["parameters"] assert parameters["type"] == "object", "Parameters type does not match 'object'" assert "properties" in parameters, "Properties not found in parameters" # 检查具体参数 'val' properties = parameters["properties"] assert "val" in properties, "'val' parameter missing" val_property = properties["val"] # 验证 'val' 参数的各项属性 assert ( val_property["type"] == "Union[float, Dict[str, int]]" ), "'val' type does not match 'Union[float, Dict[str, int]]'" assert val_property["required"] is True, "'val' required does not match True" def test_decorator_google_style_union_combine(self): @manifest() def func( val: Union[float, Union[str, int]], ) -> str: """Function with a combined Union parameter. Args: val (Union[float, str, int]): A parameter that can accept a float, string, or integer. Returns: str: A result string. """ return "" view = func.__ab_manifest__ # 检查生成的 Manifest 对象 assert isinstance(view, Manifest), "view is not an instance of Manifest" # 检查参数的总体结构 parameters = view.function["parameters"] assert parameters["type"] == "object", "Parameters type does not match 'object'" assert "properties" in parameters, "Properties not found in parameters" # 检查具体参数 'val' properties = parameters["properties"] assert "val" in properties, "'val' parameter missing" val_property = properties["val"] # 验证 'val' 参数的各项属性 assert ( val_property["type"] == "Union[float, str, int]" ), "'val' type does not match 'Union[float, str, int]'" assert val_property["required"] is True, "'val' required does not match True" def test_decorator_google_style_no_annotation(self): @manifest(description="Test Function") def func( val, ) -> str: return "" view = func.__ab_manifest__ assert isinstance(view, Manifest), "view is not an instance of Manifest" parameters = view.function["parameters"] properties = parameters["properties"] assert "val" in properties, "'val' parameter missing" val_property = properties["val"] assert val_property["type"] == "Any", "'val' type does not match 'Any'" assert val_property["required"] is True, "'val' required does not match True" def test_decorator_google_style_default(self): @manifest(description="Test Function") def func(val: str = "value") -> str: return "" view = func.__ab_manifest__ assert isinstance(view, Manifest), "view is not an instance of Manifest" parameters = view.function["parameters"] properties = parameters["properties"] assert "val" in properties, "'val' parameter missing" val_property = properties["val"] assert val_property["type"] == "str", "'val' type does not match 'str'" assert val_property["required"] is False, "'val' required does not match False" def test_decorator_google_style_optional(self): @manifest(description="Test Function") def func( val: Optional[str], ) -> str: return "" view = func.__ab_manifest__ assert isinstance(view, Manifest), "view is not an instance of Manifest" parameters = view.function["parameters"] properties = parameters["properties"] assert "val" in properties, "'val' parameter missing" val_property = properties["val"] assert ( val_property["type"] == "Optional[str]" ), "'val' type does not match 'Optional[str]'" assert val_property["required"] is False, "'val' required does not match False" def test_decorator_google_style_optional_equals_none(self): @manifest(description="Test Function") def func( val: Optional[str] = None, ) -> str: return "" view = func.__ab_manifest__ assert isinstance(view, Manifest), "view is not an instance of Manifest" parameters = view.function["parameters"] properties = parameters["properties"] assert "val" in properties, "'val' parameter missing" val_property = properties["val"] assert ( val_property["type"] == "Optional[str]" ), "'val' type does not match 'Optional[str]'" assert val_property["required"] is False, "'val' required does not match False" def test_decorator_google_style_optional_list(self): @manifest(description="Test Function") def func( val: Optional[List[str]], ) -> str: return "" view = func.__ab_manifest__ assert isinstance(view, Manifest), "view is not an instance of Manifest" parameters = view.function["parameters"] properties = parameters["properties"] assert "val" in properties, "'val' parameter missing" val_property = properties["val"] assert ( val_property["type"] == "Optional[List[str]]" ), "'val' type does not match 'Optional[List[str]]'" assert val_property["required"] is False, "'val' required does not match False" def test_decorator_google_style_list_nest_optional(self): @manifest(description="Test Function") def func( val: List[Optional[str]], ) -> str: return "" view = func.__ab_manifest__ assert isinstance(view, Manifest), "view is not an instance of Manifest" parameters = view.function["parameters"] properties = parameters["properties"] assert "val" in properties, "'val' parameter missing" val_property = properties["val"] assert ( val_property["type"] == "List[Optional[str]]" ), "'val' type does not match 'List[Optional[str]]'" assert val_property["required"] is True, "'val' required does not match True" def test_decorator_google_style_union_nest_single_optional(self): @manifest(description="Test Function") def func( val: Union[Optional[str]], ) -> str: return "" view = func.__ab_manifest__ assert isinstance(view, Manifest), "view is not an instance of Manifest" parameters = view.function["parameters"] properties = parameters["properties"] assert "val" in properties, "'val' parameter missing" val_property = properties["val"] assert ( val_property["type"] == "Optional[str]" ), "'val' type does not match 'Optional[str]'" assert val_property["required"] is False, "'val' required does not match False" def test_decorator_google_style_union_nest_optional(self): @manifest(description="Test Function") def func( val: Union[Optional[int], Optional[str]], ) -> str: return "" view = func.__ab_manifest__ assert isinstance(view, Manifest), "view is not an instance of Manifest" parameters = view.function["parameters"] properties = parameters["properties"] assert "val" in properties, "'val' parameter missing" val_property = properties["val"] # 验证类型,inspect 可能优化嵌套 Union assert ( val_property["type"] == "Union[int, str]" ), "'val' type does not match 'Union[int, str]'" assert val_property["required"] is False, "'val' required does not match False" def test_decorator_google_style_union_nest1_dict_optional_value(self): @manifest(description="Test Function") def func( val: Union[float, Dict[str, Optional[int]]], ) -> str: return "" view = func.__ab_manifest__ assert isinstance(view, Manifest), "view is not an instance of Manifest" parameters = view.function["parameters"] properties = parameters["properties"] assert "val" in properties, "'val' parameter missing" val_property = properties["val"] assert ( val_property["type"] == "Union[float, Dict[str, Optional[int]]]" ), "'val' type does not match 'Union[float, Dict[str, Optional[int]]]'" assert val_property["required"] is True, "'val' required does not match True" if __name__ == "__main__": unittest.main() ================================================ FILE: python/tests/test_matching.py ================================================ """ test mathcing """ import sys sys.path.append('../..') import unittest import os import appbuilder class TestMatching(unittest.TestCase): def test_example(self): # 初始化所需要的组件 embedding = appbuilder.Embedding() matching = appbuilder.Matching(embedding) # 定义输入query和文本列表 query = appbuilder.Message("你好") contexts = appbuilder.Message(["世界", "你好"]) # 根据query,对文本列表做相似度排序 contexts_matched = matching(query, contexts) self.assertListEqual(contexts_matched.content, ['你好', '世界']) def test_run(self): embedding = appbuilder.Embedding() matching = appbuilder.Matching(embedding) query = appbuilder.Message("你好") contexts = appbuilder.Message(["世界", "你好"]) contexts_matched = matching(query, contexts) self.assertListEqual( contexts_matched.content, ['你好', '世界'] ) def test_return_score(self): embedding = appbuilder.Embedding() matching = appbuilder.Matching(embedding) query = appbuilder.Message("你好") contexts = appbuilder.Message(["世界", "你好"]) contexts_matched = matching(query, contexts, return_score=True) scores = [i[0] for i in contexts_matched.content] contexts = [i[1] for i in contexts_matched.content] self.assertListEqual( contexts, ['你好', '世界'] ) self.assertGreater(scores[0], scores[1]) def test_semantics(self): embedding = appbuilder.Embedding() matching = appbuilder.Matching(embedding) query = appbuilder.Message("你好") query_embedding = embedding(query) contexts = appbuilder.Message(["世界", "你好"]) context_embedding = embedding.batch(contexts) semantics = matching.semantics(query_embedding, context_embedding) self.assertEqual(len(semantics.content), 2) if __name__ == '__main__': unittest.main() ================================================ FILE: python/tests/test_mcp_ai_search_stdio.py ================================================ # Copyright (c) 2025 Baidu, Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import unittest import sys import subprocess import asyncio import os import inspect @unittest.skipUnless(os.getenv("TEST_CASE", "UNKNOWN") == "CPU_SERIAL", "") class TestGetAppList(unittest.TestCase): @unittest.skipIf(sys.version_info < (3, 10), "Only for Python >= 3.10") def test_ai_search_mcp_stdio(self): async def process(): mcp_client = MCPClient() env = {"APPBUILDER_TOKEN": os.getenv("APPBUILDER_TOKEN")} await mcp_client.connect_to_server( inspect.getfile(ai_search_server), env=env ) tools = mcp_client.tools assert len(tools) > 0 result = await mcp_client.call_tool("AIsearch", {"query": "今天的头条新闻"}) print(result) assert result.content[0] != "" from appbuilder.mcp_server import MCPClient from appbuilder.mcp_server.ai_search import ai_search_server loop = asyncio.get_event_loop() loop.run_until_complete(process()) if __name__ == "__main__": unittest.main() ================================================ FILE: python/tests/test_mcp_app_server_stdio.py ================================================ # Copyright (c) 2025 Baidu, Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import unittest import sys import asyncio import os import inspect @unittest.skipUnless(os.getenv("TEST_CASE", "UNKNOWN") == "CPU_SERIAL", "") class TestGetAppList(unittest.TestCase): def setUp(self): self.app_id = "aa8af334-df27-4855-b3d1-0d249c61fc08" @unittest.skipIf(sys.version_info < (3, 10), "Only for Python >= 3.10") def test_app_list_stdio(self): async def process(): mcp_client = MCPClient() env = {"APPBUILDER_TOKEN": os.getenv("APPBUILDER_TOKEN")} await mcp_client.connect_to_server( inspect.getfile(app_server), env=env ) tools = mcp_client.tools assert len(tools) > 0 result = await mcp_client.call_tool("list_apps", {}) print(result) assert result.content[0] != "" from appbuilder.mcp_server import MCPClient from appbuilder.mcp_server.app import app_server loop = asyncio.get_event_loop() loop.run_until_complete(process()) @unittest.skipIf(sys.version_info < (3, 10), "Only for Python >= 3.10") def test_app_run_stdio(self): async def process(): mcp_client = MCPClient() env = {"APPBUILDER_TOKEN": os.getenv("APPBUILDER_TOKEN")} await mcp_client.connect_to_server(inspect.getfile(app_server), env=env) tools = mcp_client.tools assert len(tools) > 0 create_conversation_result = await mcp_client.call_tool("create_conversation", {"app_id": self.app_id}) conversation_id = create_conversation_result.content[0].text print(conversation_id) assert conversation_id is not None result = await mcp_client.call_tool("run", { "app_id": self.app_id, "conversation_id": conversation_id, "query": "北京的小学生数量", }) answer = result.content[0].text print(answer) assert answer is not None await mcp_client.cleanup() from appbuilder.mcp_server import MCPClient from appbuilder.mcp_server.app import app_server loop = asyncio.get_event_loop() loop.run_until_complete(process()) if __name__ == "__main__": unittest.main() ================================================ FILE: python/tests/test_mcp_rag_stdio.py ================================================ # Copyright (c) 2025 Baidu, Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import unittest import sys import json import asyncio import os import inspect import appbuilder from appbuilder import ( KnowledgeBase, ) @unittest.skipUnless(os.getenv("TEST_CASE", "UNKNOWN") == "CPU_SERIAL", "") class TestGetAppList(unittest.TestCase): @unittest.skipIf(sys.version_info < (3, 10), "Only for Python >= 3.10") def test_knowledgebase_mcp(self): async def process(): # case list tools mcp_client = MCPClient() env = {"APPBUILDER_TOKEN": os.getenv("APPBUILDER_TOKEN")} await mcp_client.connect_to_server(inspect.getfile(knowledge_base_server), env=env) tools = mcp_client.tools print(tools) # case create_knowledge_base result = await mcp_client.call_tool( "create_knowledge_base", {"name": "mcp测试可删", "description": "mcp测试,可删"}, ) knowledge_base_info = json.loads(result.content[0].text) knowledge_base_id = knowledge_base_info.get("id") assert knowledge_base_id is not None # case describe_knowledge_base appbuilder.logger.debug( f"create knowledge base success: {knowledge_base_id}") result = await mcp_client.call_tool( "describe_knowledge_base", {"id": knowledge_base_id}, ) knowledge_base_info = json.loads(result.content[0].text) knowledge_base_id = knowledge_base_info.get("id") assert knowledge_base_id is not None appbuilder.logger.debug( f"describe knowledge base success: {knowledge_base_id}" ) # case list_knowledge_bases result = await mcp_client.call_tool( "list_knowledge_bases", {"max_keys": 10}, ) assert len(result.content) == 10 appbuilder.logger.debug( f"list knowledge bases success: {len(result.content)}" ) # case upload_document result = await mcp_client.call_tool( "upload_document", {"id": knowledge_base_id, "file_path": "./data/mcp_knowledge_base_case.txt"}, ) document_info = json.loads(result.content[0].text) print(document_info) document_id = document_info.get("documentId") assert document_id is not None appbuilder.logger.debug(f"upload document success: {document_id}") # case list_documents result = await mcp_client.call_tool( "list_documents", {"id": document_id}, ) assert len(result.content) == 1 appbuilder.logger.debug( f"list documents base success: {document_id}") # case query_knowledge_base result = await mcp_client.call_tool( "query_knowledge_base", {"query": "分子", "id_list": [ "56e82915-9642-4a03-bb02-74744c17863e"]}, ) assert result.content[0].text is not None appbuilder.logger.debug("query knowledge base success") await mcp_client.cleanup() from appbuilder.mcp_server import MCPClient from appbuilder.mcp_server.knowledge_base import knowledge_base_server loop = asyncio.get_event_loop() loop.run_until_complete(process()) def query_knowledge_base(query: str, id_list: list[str]): """ Query content from KnowledgeBases. Args: query: Search query string id_list: List of KnowledgeBase ID to search in """ client = KnowledgeBase() resp = client.query_knowledge_base(query, knowledgebase_ids=id_list) return [ { "chunk_id": chunk.chunk_id, "content": chunk.content, "document_id": chunk.document_id, "document_name": chunk.document_name, } for chunk in resp.chunks ] if __name__ == "__main__": appbuilder.logger.setLevel("DEBUG") unittest.main() ================================================ FILE: python/tests/test_message.py ================================================ # Copyright (c) 2023 Baidu, Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import os import unittest from appbuilder.core.message import Message @unittest.skipUnless(os.getenv("TEST_CASE", "UNKNOWN") == "CPU_PARALLEL", "") class TestMessage(unittest.TestCase): def setUp(self): """ pass """ pass def test_message(self): """ test message """ m = Message({"query": "my message"}, name="m") print(m) m = Message(content={"query": "my message"}, name="m") print(m) if __name__ == "__main__": unittest.main() ================================================ FILE: python/tests/test_mix_card_ocr.py ================================================ # Copyright (c) 2023 Baidu, Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import os import unittest import requests import appbuilder from appbuilder.core.message import Message from appbuilder.core._exception import InvalidRequestArgumentError from appbuilder.core.components.mix_card_ocr.model import MixCardOCRRequest @unittest.skipUnless(os.getenv("TEST_CASE", "UNKNOWN") == "CPU_PARALLEL", "") class TestPlantRecognition(unittest.TestCase): def setUp(self): """ 设置环境变量 Args: None. Returns: None. """ # 从BOS存储读取样例文件 self.image_url=("https://bj.bcebos.com/v1/appbuilder/test_mix_card_ocr.jpeg?" "authorization=bce-auth-v1%2FALTAKGa8m4qCUasgoljdEDAzLm%2F2024-01-24T06" "%3A18%3A11Z%2F-1%2Fhost%2F695b8041c1ded194b9e80dbe" "1865e4393da5a3515e90d72d81ef18296bd29598") self.raw_image = requests.get(self.image_url).content self.mix_card_ocr = appbuilder.MixCardOCR() # 输入参数为一张图片 def test_run_with_image_url(self): """ 使用图片url进行单测 Args: None Returns: None """ # Create message with raw_image inp = Message(content={"url": self.image_url}) msg = self.mix_card_ocr.run(inp) self.assertIsNotNone(msg.content) def test_run_with_raw_image(self): """ 使用原始图片进行单测 Args: None Returns: None """ # Create message with raw_image inp = Message(content={"raw_image": self.raw_image}) msg = self.mix_card_ocr.run(inp) self.assertIsNotNone(msg.content) def test_tool_eval(self): result=self.mix_card_ocr.tool_eval(name='name',streaming=False,files=['test']) with self.assertRaises(InvalidRequestArgumentError): next(result) result=self.mix_card_ocr.tool_eval( name='name', streaming=True, file_names=['test'], file_urls={'test':self.image_url} ) res=next(result) self.assertEqual(res['visible_scope'],'llm') res=next(result) self.assertEqual(res['visible_scope'],'user') result=self.mix_card_ocr.tool_eval( name='name', streaming=False, file_names=['test'], file_urls={'test':self.image_url} ) def test_recognize_raise(self): mco=appbuilder.MixCardOCR() with self.assertRaises(ValueError): mcor=MixCardOCRRequest() mco._recognize(request=mcor) if __name__ == '__main__': unittest.main() ================================================ FILE: python/tests/test_mrc.py ================================================ # Copyright (c) 2023 Baidu, Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import os import unittest import appbuilder import time class TestMRC(unittest.TestCase): def setUp(self): ''' return mrc class ''' # 设置环境变量和初始化TestMRCComponent实例 self.model_name = "DeepSeek-V3.1" self.mrc = appbuilder.MRC(model=self.model_name) def test_mrc_with_custom_context_list(self): """测试run方法使用自定义格式context_out_list""" msg = "残疾人怎么办相关证件" msg = appbuilder.Message(msg) context_list = appbuilder.Message(["""如何办理残疾人通行证一、残疾人通行证办理条件: 1、持有中华人民共和国残疾人证,下肢残疾或者听力残疾; 2、持有准驾车型为C1(听力残疾)、C2(左下肢残疾、听力残疾)、C5(右下肢、双下肢残疾)的机动车驾驶证, 听力残疾人驾驶证须有“驾驶机动车应佩戴助听设备”的批注(批注请到各车管分所办理);""", """3、本人拥有本市登记核发的非营运小型载客汽车,车辆须在检验有效期内,并有有效交强险凭证, C5车辆加装操纵辅助装置后已办理变更手续。二、办理地点:北京市朝阳区左家庄北里35号: 北京市无障碍环境建设促进中心(北京市残疾人辅助器具资源中心),咨询电话:63547715 或68397831。三、所需材料:1、 有效的身份证明原件和复印件;2、残疾人证原件和复印件;3、驾驶证原件和复印件; 4、车辆行驶证原件和复印件;5、有效的机动车交强险凭证。"""]) answer = self.mrc(msg, context_list) self.assertIsNotNone(answer) time.sleep(1) def test_mrc_with_invalid_context(self): """测试run方法使用无效格式的context_list""" msg = "残疾人怎么办相关证件" msg = appbuilder.Message(msg) context_list = appbuilder.Message("无效样式") self.mrc(msg, context_list) time.sleep(1) def test_mrc_with_reject(self): """测试拒答功能开启情况""" # 测试阅读理解问答 msg = "残疾人怎么办相关证件" msg = appbuilder.Message(msg) context_list = appbuilder.Message(["""如何办理残疾人通行证一、残疾人通行证办理条件: 1、持有中华人民共和国残疾人证,下肢残疾或者听力残疾; 2、持有准驾车型为C1(听力残疾)、C2(左下肢残疾、听力残疾)、C5(右下肢、双下肢残疾)的机动车驾驶证, 听力残疾人驾驶证须有“驾驶机动车应佩戴助听设备”的批注(批注请到各车管分所办理);""", """3、本人拥有本市登记核发的非营运小型载客汽车,车辆须在检验有效期内,并有有效交强险凭证, C5车辆加装操纵辅助装置后已办理变更手续。二、办理地点:北京市朝阳区左家庄北里35号: 北京市无障碍环境建设促进中心(北京市残疾人辅助器具资源中心),咨询电话:63547715 或68397831。三、所需材料:1、 有效的身份证明原件和复印件;2、残疾人证原件和复印件;3、驾驶证原件和复印件; 4、车辆行驶证原件和复印件;5、有效的机动车交强险凭证。"""]) answer = self.mrc(msg, context_list, reject=True, clarify=True, highlight=True, friendly=True,cite=True) print(answer) def test_tool_eval_valid(self): """测试 tool 方法对有效请求的处理。""" context_list = ["""如何办理残疾人通行证一、残疾人通行证办理条件: 1、持有中华人民共和国残疾人证,下肢残疾或者听力残疾; 2、持有准驾车型为C1(听力残疾)、C2(左下肢残疾、听力残疾)、C5(右下肢、双下肢残疾)的机动车驾驶证, 听力残疾人驾驶证须有“驾驶机动车应佩戴助听设备”的批注(批注请到各车管分所办理);""", """3、本人拥有本市登记核发的非营运小型载客汽车,车辆须在检验有效期内,并有有效交强险凭证, C5车辆加装操纵辅助装置后已办理变更手续。二、办理地点:北京市朝阳区左家庄北里35号: 北京市无障碍环境建设促进中心(北京市残疾人辅助器具资源中心),咨询电话:63547715 或68397831。三、所需材料:1、 有效的身份证明原件和复印件;2、残疾人证原件和复印件;3、驾驶证原件和复印件; 4、车辆行驶证原件和复印件;5、有效的机动车交强险凭证。"""] params = { 'name': 'mrc', 'query': '残疾人怎么办相关证件', 'context_list': context_list } result = self.mrc.tool_eval(streaming=True, **params) res = [item for item in result] self.assertNotEqual(len(res), 0) result = self.mrc.tool_eval(streaming=False, **params) res = [item for item in result] def test_tool_eval_invalid(self): """测试 tool 方法对无效请求的处理。""" context_list = ["""如何办理残疾人通行证一、残疾人通行证办理条件: 1、持有中华人民共和国残疾人证,下肢残疾或者听力残疾; 2、持有准驾车型为C1(听力残疾)、C2(左下肢残疾、听力残疾)、C5(右下肢、双下肢残疾)的机动车驾驶证, 听力残疾人驾驶证须有“驾驶机动车应佩戴助听设备”的批注(批注请到各车管分所办理);""", """3、本人拥有本市登记核发的非营运小型载客汽车,车辆须在检验有效期内,并有有效交强险凭证, C5车辆加装操纵辅助装置后已办理变更手续。二、办理地点:北京市朝阳区左家庄北里35号: 北京市无障碍环境建设促进中心(北京市残疾人辅助器具资源中心),咨询电话:63547715 或68397831。三、所需材料:1、 有效的身份证明原件和复印件;2、残疾人证原件和复印件;3、驾驶证原件和复印件; 4、车辆行驶证原件和复印件;5、有效的机动车交强险凭证。"""] with self.assertRaises(ValueError): params = { 'name': 'mrc', 'query': '残疾人怎么办相关证件' } result = self.mrc.tool_eval(streaming=True, **params) next(result) with self.assertRaises(ValueError): params = { 'name': 'mrc', 'context_list': context_list } result = self.mrc.tool_eval(streaming=True, **params) next(result) if __name__ == '__main__': unittest.main() ================================================ FILE: python/tests/test_nl2pandas.py ================================================ """ Copyright (c) 2023 Baidu, Inc. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. """ import unittest import os import appbuilder from appbuilder.core.message import Message class TestNl2pandasComponent(unittest.TestCase): def setUp(self): """ 设置环境变量及必要数据。 """ self.model_name = "DeepSeek-V3.1" self.node = appbuilder.Nl2pandasComponent(model=self.model_name) self.table_info = '''表格列信息如下: 学校名 : 清华附小 , 字符串类型,代表小学学校的名称 所属地区 : 西城区 , 字符串类型,表示该小学学校所在的位置 创办时间 : 1998 , 数字值类型,表示该小学学校的创办时间 类别 : 公立小学 , 字符串类型,表示该小学学校所在的类别 学生人数 : 2000 , 数字值类型,表示该小学学校的学生数量 教职工人数 : 140 , 数字值类型,表示该小学学校的教职工数量 教学班数量 : 122 , 数字值类型,表示该小学学校的教学班数量 ''' def test_run_with_stream_and_temperature(self): """测试 stream 和 temperature 参数""" query = "海淀区有哪些学校" msg = Message(query) code = self.node(msg, table_info=self.table_info, stream=False, temperature=0.5) self.assertIsNotNone(code) def test_tool_eval_valid(self): """测试 tool 方法对有效请求的处理。""" params = { 'name': 'nl2pandas', 'query': '海淀区有哪些学校', 'table_info': self.table_info } result = self.node.tool_eval(streaming=True, **params) res = [item for item in result] self.assertNotEqual(len(res), 0) result = self.node.tool_eval(streaming=False, **params) res = [item for item in result] def test_tool_eval_invalid(self): """测试 tool 方法对无效请求的处理。""" with self.assertRaises(ValueError): params = { 'name': 'nl2pandas', 'query': '海淀区有哪些学校' } result = self.node.tool_eval(streaming=True, **params) next(result) with self.assertRaises(ValueError): params = { 'name': 'nl2pandas', 'table_info': self.table_info } result = self.node.tool_eval(streaming=True, **params) next(result) if __name__ == '__main__': unittest.main() ================================================ FILE: python/tests/test_object_recognize.py ================================================ # Copyright (c) 2023 Baidu, Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import os import unittest import requests import appbuilder from appbuilder.core._exception import InvalidRequestArgumentError @unittest.skipUnless(os.getenv("TEST_CASE", "UNKNOWN") == "CPU_PARALLEL", "") class TestObjectRecognize(unittest.TestCase): def setUp(self): """ 设置环境变量。 Args: None Returns: None. """ self.object_recognition = appbuilder.ObjectRecognition() def test_run_with_raw_image(self): """ 使用原始图片进行单测 Args: None Returns: None """ image_url = "https://bj.bcebos.com/v1/appbuilder/object_recognize_test.png?" \ "authorization=bce-auth-v1%2FALTAKGa8m4qCUasgoljdEDAzLm%2F2024-01-" \ "11T11%3A00%3A19Z%2F-1%2Fhost%2F2c31bf29205f61e58df661dc80af31a1dc" \ "1ba1de0a8f072bc5a87102bd32f9e3" raw_image = requests.get(image_url).content # Create message with raw_image message = appbuilder.Message(content={"raw_image": raw_image}) # Recognize landmark output = self.object_recognition.run(message) # Assert output is not None self.assertIsNotNone(output) def test_run_with_no_image(self): """ 测试run函数在传入无效图像的情况下的行为 Args: None Returns: None """ # create empty message message = appbuilder.Message(content={}) # Assert ValueError is raised with self.assertRaises(ValueError): self.object_recognition.run(message) def test_run_with_timeout_and_retry(self): """ 测试run方法,timeout、retry参数 Args: None Returns: None """ image_url = "https://bj.bcebos.com/v1/appbuilder/object_recognize_test.png?" \ "authorization=bce-auth-v1%2FALTAKGa8m4qCUasgoljdEDAzLm%2F2024-01-" \ "11T11%3A00%3A19Z%2F-1%2Fhost%2F2c31bf29205f61e58df661dc80af31a1dc" \ "1ba1de0a8f072bc5a87102bd32f9e3" raw_image = requests.get(image_url).content # Create message with raw_image message = appbuilder.Message(content={"raw_image": raw_image}) # Recognize landmark with timeout and retry parameters output = self.object_recognition.run(message, timeout=5.0, retry=3) # Assert output is not None self.assertIsNotNone(output) def test_run_with_invalid_url(self): """ 测试run函数在传入无效URL的情况下的行为。 Args: None Returns: None """ url = "http://example.com/invalid_url.jpg" message = appbuilder.Message({"url": url}) with self.assertRaises(appbuilder.AppBuilderServerException): self.object_recognition.run(message=message) def test_run_without_image_and_url(self): """ 测试run 函数在没有传入图像和URL的情况下的行为。 Args: None Returns: None """ message = appbuilder.Message({}) with self.assertRaises(ValueError): self.object_recognition.run(message=message) def test_tool_eval_valid(self): """测试 tool 方法对有效请求的处理。""" image_url = "https://bj.bcebos.com/v1/appbuilder/object_recognize_test.png?" \ "authorization=bce-auth-v1%2FALTAKGa8m4qCUasgoljdEDAzLm%2F2024-01-" \ "11T11%3A00%3A19Z%2F-1%2Fhost%2F2c31bf29205f61e58df661dc80af31a1dc" \ "1ba1de0a8f072bc5a87102bd32f9e3" result = self.object_recognition.tool_eval(name="object_recognition", streaming=True, img_url=image_url) res = [item for item in result] self.assertNotEqual(len(res), 0) def test_tool_eval_invalid(self): """测试 tool 方法对无效请求的处理。""" with self.assertRaises(InvalidRequestArgumentError): result = self.object_recognition.tool_eval(name="object_recognition", streaming=True) next(result) with self.assertRaises(InvalidRequestArgumentError): result=self.object_recognition.tool_eval(name='test',streaming=False,file_urls={'test_01':'test'},img_name='test') next(result) if __name__ == '__main__': unittest.main() ================================================ FILE: python/tests/test_openapi_convert.py ================================================ # Copyright (c) 2023 Baidu, Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import unittest import asyncio import json import os import sys class TestOpenAPIMCPConverter(unittest.TestCase): @unittest.skipIf(sys.version_info < (3, 10), "Only for Python >= 3.10") def setUp(self): """ 设置测试环境。 Args: 无参数,默认值为空。 Returns: 无返回值,方法中执行了环境变量的赋值操作。 """ from mcp_server.openapi import OpenAPIMCPConverter self.converter = OpenAPIMCPConverter( base_url="https://api.github.com", headers={ "Accept": "application/vnd.github.v3+json", "User-Agent": "OpenAPIMCPConverter-Test" }, timeout=30.0, max_retries=3 ) @unittest.skipIf(sys.version_info < (3, 10), "Only for Python >= 3.10") async def asyncSetUp(self): """异步设置,加载本地GitHub API规范""" import os # Get the path to the test data file current_dir = os.path.dirname(os.path.abspath(__file__)) json_spec_path = os.path.join(current_dir, 'data', 'ghes-3.0.json') await self.converter.load_spec(json_spec_path) @unittest.skipIf(sys.version_info < (3, 10), "Only for Python >= 3.10") def test_list_tools(self): """测试 list_tools 方法""" async def run_test(): await self.asyncSetUp() tools = self.converter.list_tools() self.assertIsNotNone(tools) self.assertTrue(len(tools) > 0) # 验证前5个工具的结构 for tool in tools[:5]: self.assertIn('name', tool) self.assertIn('description', tool) self.assertIn('input_schema', tool) asyncio.run(run_test()) @unittest.skipIf(sys.version_info < (3, 10), "Only for Python >= 3.10") def test_call_tool_list_repos(self): """测试调用 list_repos_for_user 工具""" async def run_test(): await self.asyncSetUp() # Get a list of available tools tools = self.converter.list_tools() tool_names = [tool['name'] for tool in tools] # Skip the test if the tool is not available if "get_/users/{username}/repos" not in tool_names: print("Skipping test_call_tool_list_repos: Tool 'get_/users/{username}/repos' not found in local test data") return result = await self.converter.call_tool( "get_/users/{username}/repos", { "username": "octocat", "type": "owner", "sort": "created", "per_page": 1 } ) self.assertIsNotNone(result) self.assertTrue(isinstance(result, list)) asyncio.run(run_test()) @unittest.skipIf(sys.version_info < (3, 10), "Only for Python >= 3.10") def test_call_tool_get_repo(self): """测试调用 get_repo 工具""" async def run_test(): await self.asyncSetUp() # Get a list of available tools tools = self.converter.list_tools() tool_names = [tool['name'] for tool in tools] # Skip the test if the tool is not available if "get_/repos/{owner}/{repo}" not in tool_names: print("Skipping test_call_tool_get_repo: Tool 'get_/repos/{owner}/{repo}' not found in local test data") return result = await self.converter.call_tool( "get_/repos/{owner}/{repo}", { "owner": "octocat", "repo": "Hello-World" } ) self.assertIsNotNone(result) self.assertIn('name', result) self.assertIn('owner', result) asyncio.run(run_test()) @unittest.skipIf(sys.version_info < (3, 10), "Only for Python >= 3.10") def test_load_yaml_spec(self): """测试加载YAML格式的API规范""" async def run_test(): import os # Get the path to the test data file current_dir = os.path.dirname(os.path.abspath(__file__)) yaml_spec_path = os.path.join(current_dir, 'data', 'ghes-3.0.yaml') # Create a new converter for YAML test from mcp_server.openapi import OpenAPIMCPConverter yaml_converter = OpenAPIMCPConverter( base_url="https://api.github.com", headers={ "Accept": "application/vnd.github.v3+json", "User-Agent": "OpenAPIMCPConverter-Test" }, timeout=30.0, max_retries=3 ) # Load the YAML spec await yaml_converter.load_spec(yaml_spec_path) # Verify tools were loaded tools = yaml_converter.list_tools() self.assertIsNotNone(tools) self.assertTrue(len(tools) > 0) # Clean up await yaml_converter.close() asyncio.run(run_test()) def tearDown(self): """清理测试环境""" async def cleanup(): await self.converter.close() asyncio.run(cleanup()) ================================================ FILE: python/tests/test_oral_query_generation.py ================================================ # Copyright (c) 2023 Baidu, Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import os import unittest import appbuilder TEST_TEXT = ('文档标题:在OPPO Reno5上使用视频超级防抖\n' '文档摘要:OPPO Reno5上的视频超级防抖,视频超级防抖3.0,多代视频防抖算法积累,这一代依旧超级防抖超级稳。 开启视频超级' '防抖 开启路径:打开「相机 > 视频 > 点击屏幕上方的“超级防抖”标识」 后置视频同时支持超级防抖和超级防抖Pro功能,开启超级' '防抖后手机屏幕将出现超级防抖Pro开关,点击即可开启或关闭。 除此之外,前置视频同样加持防抖算法,边走边拍也能稳定聚焦脸部' ',实时视频分享您的生活。') class TestOralQueryGenerationComponent(unittest.TestCase): def setUp(self): """ 设置环境变量。 Args: 无参数,默认值为空。 Returns: 无返回值,方法中执行了环境变量的赋值操作。 """ self.model_name = "DeepSeek-V3.1" secret_key = os.getenv('SECRET_KEY', None) self.query_generation = appbuilder.OralQueryGeneration(model=self.model_name, secret_key=secret_key) def test_run_with_default_params(self): """测试 run 方法使用默认参数 """ text = TEST_TEXT msg = appbuilder.Message(text) answer = self.query_generation(msg) # print(answer) self.assertIsNotNone(answer) print(f'\n[result]\n{answer.content}\n') def test_run_with_question_output_and_json_output(self): """测试 run 方法,输出query类型为问题,输出格式为json """ text = TEST_TEXT msg = appbuilder.Message(text) answer = self.query_generation(msg, query_type='问题', output_format='json') # print(answer) self.assertIsNotNone(answer) print(f'\n[result]\n{answer.content}\n') def test_run_with_phrase_output_and_str_output(self): """测试 run 方法,输出query类型为短语,输出格式为str """ text = TEST_TEXT msg = appbuilder.Message(text) answer = self.query_generation(msg, query_type='短语', output_format='str') # print(answer) self.assertIsNotNone(answer) print(f'\n[result]\n{answer.content}\n') def test_run_with_stream_and_temperature(self): """测试不同的 stream 和 temperature 参数值 """ text = TEST_TEXT msg = appbuilder.Message(text) answer = self.query_generation(msg, stream=False, temperature=0.5) # print(answer) self.assertIsNotNone(answer) print(f'\n[result]\n{answer.content}\n') def test_tool_eval_with_default_params(self): """测试 tool_eval 方法使用默认参数 """ text = TEST_TEXT answer = self.query_generation.tool_eval(name='', stream=False, text=text) # print(answer) self.assertIsNotNone(answer) print(f'\n[result]\n{answer}\n') def test_tool_eval_with_model_configs(self): """测试 tool_eval 方法使用不同temperature和top_p参数值。 """ text = TEST_TEXT model_configs = {'temperature': 0.5, 'top_p': 0.5} answer = self.query_generation.tool_eval(name='', stream=True, text=text, model_configs=model_configs) # print(answer) print(f'\n[result]\n') for ans in answer: print(ans) def test_tool_eval_with_default_params(self): """测试 tool_eval 方法使用默认参数 """ text = TEST_TEXT answer = self.query_generation.tool_eval(name='', stream=False, text=text) # print(answer) self.assertIsNotNone(answer) print(f'\n[result]\n{answer}\n') def test_tool_eval_with_model_configs(self): """测试 tool_eval 方法使用不同temperature和top_p参数值。 """ text = TEST_TEXT model_configs = {'temperature': 0.5, 'top_p': 0.5} answer = self.query_generation.tool_eval(name='', stream=True, text=text, model_configs=model_configs) # print(answer) print(f'\n[result]\n') for ans in answer: print(ans) if __name__ == '__main__': unittest.main() ================================================ FILE: python/tests/test_plant_recognize.py ================================================ # Copyright (c) 2023 Baidu, Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import os import unittest import requests import appbuilder from appbuilder.core.message import Message @unittest.skipUnless(os.getenv("TEST_CASE", "UNKNOWN") == "CPU_PARALLEL", "") class TestPlantRecognition(unittest.TestCase): def setUp(self): """ 设置环境变量 Args: None. Returns: None. """ # 从BOS存储读取样例文件 self.image_url = ("https://bj.bcebos.com/v1/appbuilder/" "palnt_recognize_test.jpg?authorization=" "bce-auth-v1%2FALTAKGa8m4qCUasgoljdEDAzLm%" "2F2024-01-23T09%3A51%3A03Z%2F-1%2Fhost%2" "Faa2217067f78f0236c8262cdd89a4b4f4b2188" "d971ca547c53d01742af4a2cbe") self.raw_image = requests.get(self.image_url).content self.plant_recognize = appbuilder.PlantRecognition() # 输入参数为一张图片 def test_run_with_image_url(self): """ 使用图片url进行单测 Args: None Returns: None """ # Create message with raw_image inp = Message(content={"url": self.image_url}) msg = self.plant_recognize.run(inp) self.assertIsNotNone(msg.content) def test_run_with_raw_image(self): """ 使用原始图片进行单测 Args: None Returns: None """ # Create message with raw_image inp = Message(content={"raw_image": self.raw_image}) msg = self.plant_recognize.run(inp) self.assertIsNotNone(msg.content) def test_tool_eval_valid(self): """测试 tool 方法对有效请求的处理。""" img_url = "https://bj.bcebos.com/v1/appbuilder/animal_recognize_test.png?" \ "authorization=bce-auth-v1%2FALTAKGa8m4qCUasgoljdEDAzLm%2F2024-01-24T" \ "12%3A19%3A16Z%2F-1%2Fhost%2F411bad53034fa8f9c6edbe5c4909d76ecf6fad68" \ "62cf937c03f8c5260d51c6ae" img_name = "test_img.jpg" file_urls = {img_name: img_url} result = self.plant_recognize.tool_eval(name="plant_recognition", streaming=True, img_name=img_name, file_urls=file_urls, origin_query="") res = [item for item in result] self.assertNotEqual(len(res), 0) def test_tool_eval_invalid(self): """测试 tool 方法对无效请求的处理。""" with self.assertRaises(ValueError): result = self.plant_recognize.tool_eval(name="plant_recognition", streaming=True, origin_query="") next(result) if __name__ == '__main__': unittest.main() ================================================ FILE: python/tests/test_playground.py ================================================ import unittest import os import appbuilder @unittest.skipUnless(os.getenv("TEST_CASE", "UNKNOWN") == "CPU_PARALLEL", "") class TestPlayground(unittest.TestCase): def setUp(self): """ 设置环境变量。 Args: 无参数,默认值为空。 Returns: 无返回值,方法中执行了环境变量的赋值操作。 """ self.model_name = "DeepSeek-V3.1" self.play = appbuilder.Playground(prompt_template="你好,{name},我是{bot_name},{bot_name}是一个{bot_type},我可以{bot_function},你可以问我{bot_question}。", model=self.model_name) def test_run_with_valid_message(self): """ 测试在消息有效时运行 """ msg = appbuilder.Message({ "name": "小明", "bot_name": "机器人", "bot_type": "聊天机器人", "bot_function": "聊天", "bot_question": "你好吗?" }) answer = self.play.run(message=msg, stream=False, temperature=1) self.assertIsNotNone(answer) def test_run_with_invalid_message(self): """ 测试在消息无效时处理 """ msg = appbuilder.Message({ "name": "小明" }) with self.assertRaises(ValueError): self.play.run(message=msg, stream=False, temperature=1) def test_run_with_string_message(self): """ 测试在消息为字符串时运行 """ msg = appbuilder.Message("你好,小明。") self.play = appbuilder.Playground(prompt_template="你好,{name}。", model=self.model_name) answer = self.play.run(message=msg, stream=False, temperature=1) self.assertIsNotNone(answer) def test_run_with_stream_and_temperature(self): """测试运行时使用参数 stream 和 temperature""" msg = appbuilder.Message({ "name": "小明", "bot_name": "机器人", "bot_type": "聊天机器人", "bot_function": "聊天", "bot_question": "你好吗?" }) answer = self.play.run(message=msg, stream=True, temperature=0.5, top_p=0.2) for ans in answer.content: self.assertIsNotNone(ans) def test_run_with_max_output_tokens(self): """测试运行时使用参数 max_output_tokens 和 disable_search""" msg = appbuilder.Message({ "name": "小明", "bot_name": "机器人", "bot_type": "聊天机器人", "bot_function": "聊天", "bot_question": "2023年北京昌平线地铁出轨事件发生在哪一天?" }) answer = self.play.run(message=msg, stream=False, temperature=1, max_output_tokens=20, disable_search=False) print(answer) token_usage = answer.token_usage.get("completion_tokens",100) self.assertLessEqual(token_usage, 20) def test_run_with_extra_params(self): """测试运行时使用额外的参数""" msg = appbuilder.Message({ "name": "小明", "bot_name": "机器人", "bot_type": "聊天机器人", "bot_function": "聊天", "bot_question": "2023年北京昌平线地铁出轨事件发生在哪一天?" }) answer = self.play.run(message=msg, stream=False, temperature=1,system="你是北京市公安局刑事侦查支队的一名警员" ) for ans in answer.content: self.assertIsNotNone(ans) if __name__ == '__main__': unittest.main() ================================================ FILE: python/tests/test_ppt_generation_from_file.py ================================================ """ Copyright (c) 2023 Baidu, Inc. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. """ import os import unittest import appbuilder TEST_INPUT = { 'file_url':'https://fsh.bcebos.com/v1/chenqingyang/data/PPT%E7%94%9F%E6%88%90%E6%B5%8B%E8%AF%95%E6%95%B0%E6%8D%AE/' '%E6%A0%B7%E4%BE%8B%E6%B5%8B%E8%AF%95%E6%96%87%E4%BB%B6/%E6%96%87%E4%BB%B6%E7%94%9F%E6%88%90PPT_%E5%8A%' '9F%E8%83%BD%E6%B5%8B%E8%AF%95%E6%96%87%E4%BB%B6.doc?authorization=bce-auth-v1%2F2ea5034b154145dc8962ca' 'e2393d71a6%2F2024-08-01T12%3A15%3A17Z%2F-1%2Fhost%2F9ceed45f60a852d3ef56f405d21916af3596b2988b8f9166fa' '6533bd79bf0f45', 'user_name':'百度千帆AppBuilder' } @unittest.skip("暂时跳过") class TestPPTGenerationFromFileComponent(unittest.TestCase): def setUp(self): """ 设置环境变量。 Args: 无参数,默认值为空。 Returns: 无返回值,方法中执行了环境变量的赋值操作。 """ self.ppt_generator = appbuilder.PPTGenerationFromFile() def test_run_with_default_params(self): """测试 run 方法使用默认参数 """ msg = appbuilder.Message(TEST_INPUT) result = self.ppt_generator(msg) # print(result) self.assertIsNotNone(result) print(f'\n[result]\n{result.content}\n') def test_tool_eval_with_default_params(self): """测试 tool_eval 方法使用默认参数 """ print(f'\n[result]\n') for chunk_data in self.ppt_generator.tool_eval(stream=True, **TEST_INPUT): print(chunk_data) if __name__ == '__main__': unittest.main() ================================================ FILE: python/tests/test_ppt_generation_from_instruction.py ================================================ """ Copyright (c) 2023 Baidu, Inc. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. """ import os import unittest import appbuilder TEST_INPUT = { 'text': '生成一个介绍北京的PPT。', 'custom_data': {}, 'complex': 1, 'user_name': '百度千帆AppBuilder' } @unittest.skip("暂时跳过") class TestPPTGenerationComponent(unittest.TestCase): def setUp(self): """ 设置环境变量。 Args: 无参数,默认值为空。 Returns: 无返回值,方法中执行了环境变量的赋值操作。 """ # os.environ['APPBUILDER_TOKEN'] = os.environ['APPBUILDER_TOKEN_PPT_GENERATION'] self.ppt_generator = appbuilder.PPTGenerationFromInstruction() def test_run_with_default_params(self): """测试 run 方法使用默认参数 """ msg = appbuilder.Message(TEST_INPUT) result = self.ppt_generator(msg) # print(result) self.assertIsNotNone(result) print(f'\n[result]\n{result.content}\n') def test_tool_eval_with_default_params(self): """测试 tool_eval 方法使用默认参数 """ print(f'\n[result]\n') for chunk_data in self.ppt_generator.tool_eval(stream=True, **TEST_INPUT): print(chunk_data) if __name__ == '__main__': unittest.main() ================================================ FILE: python/tests/test_ppt_generation_from_paper.py ================================================ """ Copyright (c) 2023 Baidu, Inc. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. """ import os import unittest import appbuilder TEST_INPUT = { 'file_key': 'https://fsh.bcebos.com/v1/chenqingyang/data/PPT%E7%94%9F%E6%88%90%E6%B5%8B%E8%AF%95%E6%95%B0%E6%8D%AE' '/%E6%A0%B7%E4%BE%8B%E6%B5%8B%E8%AF%95%E6%96%87%E4%BB%B6/%E8%AE%BA%E6%96%87%E7%94%9F%E6%88%90PPT_%E5%8' 'A%9F%E8%83%BD%E6%B5%8B%E8%AF%95%E6%96%87%E4%BB%B6.docx?authorization=bce-auth-v1%2F2ea5034b154145dc89' '62cae2393d71a6%2F2024-08-01T12%3A17%3A25Z%2F-1%2Fhost%2Fce12dce3cfc65060c16495222058e0837e0134945a073' '36b353679541f6b8002', 'style': '科技', 'color': '蓝色', 'title': '', 'pleader': '百度千帆AppBuilder', 'advisor': '百度千帆AppBuilder', 'school': '', 'school_logo': '', 'school_picture': '' } @unittest.skip("Open api request limit reached") class TestPPTGenerationFromPaperComponent(unittest.TestCase): def setUp(self): """ 设置环境变量。 Args: 无参数,默认值为空。 Returns: 无返回值,方法中执行了环境变量的赋值操作。 """ self.ppt_generator = appbuilder.PPTGenerationFromPaper() def test_run_with_default_params(self): """测试 run 方法使用默认参数 """ msg = appbuilder.Message(TEST_INPUT) result = self.ppt_generator(msg) # print(result) self.assertIsNotNone(result) print(f'\n[result]\n{result.content}\n') def test_tool_eval_with_default_params(self): """测试 tool_eval 方法使用默认参数 """ print(f'\n[result]\n') for chunk_data in self.ppt_generator.tool_eval(stream=True, **TEST_INPUT): print(chunk_data) if __name__ == '__main__': unittest.main() ================================================ FILE: python/tests/test_private_llm_component.py ================================================ import os import unittest from appbuilder.core.components.llms.base import CompletionBaseComponent, ModelArgsConfig class MockLLMComponent(CompletionBaseComponent): def __init__(self, *args, **kwargs): pass def run(self, *args, **kwargs): print("Success") class TestComponentInit(unittest.TestCase): def setUp(self): ''' return mrc class ''' # 设置环境变量和初始化TestMRCComponent实例 self.model_name = "DeepSeek-V3.1" self.component = MockLLMComponent(model=self.model_name) def test_private_llm_component_init(self): os.environ["PRIVATE_AB"] = "true" self.component.set_model_info("test_model_name", "test_model_url") os.environ["APPBUILDER_TOKEN"] = "abc" self.component.set_secret_key_and_gateway() model_config_inputs = ModelArgsConfig(**{"stream": True, "temperature": 0.01, "top_p": 1}) self.component.get_model_config(model_config_inputs) self.component.run() if __name__ == '__main__': unittest.main() ================================================ FILE: python/tests/test_qa_aicape_animal_rec.py ================================================ # Copyright (c) 2024 Baidu, Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import os import unittest import appbuilder import appbuilder @unittest.skipUnless(os.getenv("TEST_CASE", "UNKNOWN") == "CPU_PARALLEL", "") class TestAnimalRecognition(unittest.TestCase): def test_run(self): image_url = ("https://bj.bcebos.com/v1/appbuilder/animal_recognize_test.png?" "authorization=bce-auth-v1%2FALTAKGa8m4qCUasgoljdEDAzLm%2F2024-01-24T" "12%3A19%3A16Z%2F-1%2Fhost%2F411bad53034fa8f9c6edbe5c4909d76ecf6fad68" "62cf937c03f8c5260d51c6ae") animal_recognition = appbuilder.AnimalRecognition() out = animal_recognition.run(appbuilder.Message(content={"url": image_url})) self.assertIn("熊猫", str(out.content)) if __name__ == '__main__': unittest.main() ================================================ FILE: python/tests/test_qa_aicape_doc_crop_enhance.py ================================================ # Copyright (c) 2024 Baidu, Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import os import unittest import appbuilder @unittest.skipUnless(os.getenv("TEST_CASE", "UNKNOWN") == "CPU_PARALLEL", "") class TestDocCropEnhance(unittest.TestCase): def test_run(self): image_url = ( "https://bj.bcebos.com/v1/appbuilder/doc_enhance_test.png?" "authorization=bce-auth-v1%2FALTAKGa8m4qCUasgoljdEDAzLm%2F2024-01" "-24T12%3A51%3A09Z%2F-1%2Fhost%2F2020d2433da471b40dafa933d557a1e" "be8abf28df78010f865e45dfcd6dc3951") enhance_type = 0 doc_enhance = appbuilder.DocCropEnhance() out = doc_enhance.run(appbuilder.Message(content={"url": image_url}, enhance_type=enhance_type)) res = out.content self.assertIsNotNone(res["image_processed"]) self.assertIsNotNone(res["points"]) if __name__ == '__main__': unittest.main() ================================================ FILE: python/tests/test_qa_aicape_handwriting_ocr.py ================================================ # Copyright (c) 2024 Baidu, Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import os import unittest import appbuilder @unittest.skipUnless(os.getenv("TEST_CASE", "UNKNOWN") == "CPU_PARALLEL", "") class TestHandwritingOcr(unittest.TestCase): def test_run(self): image_url=("https://bj.bcebos.com/v1/appbuilder/test_handwrite_ocr.jpg?" "authorization=bce-auth-v1%2FALTAKGa8m4qCUasgoljdEDAzLm%2F2024-01-23T" "11%3A58%3A09Z%2F-1%2Fhost%2F677f93445fb65157bee11cd492ce213d5c56e7a41827e45ce7e32b0" "83d195c8b") image = image_url handwrite_ocr = appbuilder.HandwriteOCR() out = handwrite_ocr.run(appbuilder.Message(content={"url": image})) self.assertIn("我们家住的小区里有很多银杏树", str(out.content)) if __name__ == '__main__': unittest.main() ================================================ FILE: python/tests/test_qa_aicape_image_understand.py ================================================ # Copyright (c) 2024 Baidu, Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import os import unittest import appbuilder import time @unittest.skipUnless(os.getenv("TEST_CASE", "UNKNOWN") == "CPU_PARALLEL", "") class TestAnimalRecognition(unittest.TestCase): def test_run(self): image_url = ( "https://bj.bcebos.com/v1/appbuilder/test_image_understand.jpeg?authorization=bce-auth-v1%2FALTAKGa8m4qCUa" "sgoljdEDAzLm%2F2024-01-24T09%3A41%3A01Z%2F-1%2Fhost%2Fe8665506e30e0edaec4f1cc84a2507c4cb3fdb9b769de3a5bf" "e25c372b7e56e6" ) question = "图片里内容是什么?" image_understand = appbuilder.ImageUnderstand() out = image_understand.run(appbuilder.Message(content={"url": image_url, "question": question})) self.assertIn("蔬菜", str(out.content)) if __name__ == '__main__': unittest.main() ================================================ FILE: python/tests/test_qa_aicape_mixcard_ocr.py ================================================ # Copyright (c) 2024 Baidu, Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import os import unittest import appbuilder @unittest.skipUnless(os.getenv("TEST_CASE", "UNKNOWN") == "CPU_PARALLEL", "") class TestMixcardOcr(unittest.TestCase): def test_run(self): image_url = ( "https://bj.bcebos.com/v1/appbuilder/test_mix_card_ocr.jpeg?authorization=bce-auth-v1%2FALTAKGa8m4qCUasgol" "jdEDAzLm%2F2024-01-24T06%3A18%3A11Z%2F-1%2Fhost%2F695b8041c1ded194b9e80dbe1865e4393da5a3515e90d72d81ef18" "296bd29598" ) mixcard_ocr = appbuilder.MixCardOCR() out = mixcard_ocr.run(appbuilder.Message(content={"url": image_url})) self.assertIn("110103", str(out.content)) if __name__ == '__main__': unittest.main() ================================================ FILE: python/tests/test_qa_aicape_plant_rec.py ================================================ # Copyright (c) 2024 Baidu, Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import os import unittest import appbuilder @unittest.skipUnless(os.getenv("TEST_CASE", "UNKNOWN") == "CPU_PARALLEL", "") class TestPlantRecognition(unittest.TestCase): def test_run(self): image_url = ( "https://bj.bcebos.com/v1/appbuilder/palnt_recognize_test.jpg?authorization=bce-auth-v1%2FALTAKGa" "8m4qCUasgoljdEDAzLm%2F2024-01-23T09%3A51%3A03Z%2F-1%2Fhost%2Faa2217067f78f0236c8262cdd89a4b4f4b2" "188d971ca547c53d01742af4a2cbe" ) plant_recognition = appbuilder.PlantRecognition() out = plant_recognition.run(appbuilder.Message(content={"url": image_url})) self.assertTrue("plant_score_list" in out.content) self.assertIn("树", str(out.content)) if __name__ == '__main__': unittest.main() ================================================ FILE: python/tests/test_qa_aicape_qrcode_orc.py ================================================ # Copyright (c) 2024 Baidu, Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import os import unittest import appbuilder @unittest.skipUnless(os.getenv("TEST_CASE", "UNKNOWN") == "CPU_PARALLEL", "") class TestQrcodeOcr(unittest.TestCase): def test_run(self): image_url = ( "https://bj.bcebos.com/v1/appbuilder/qrcode_ocr_test.png?" "authorization=bce-auth-v1%2FALTAKGa8m4qCUasgoljdEDAzLm%2F2024-01-24T12%3A45%3A13Z%2F-1%2Fhost%2Ffc43d07b41903aeeb5a023131ba6" "e74ab057ce26d50e966dc31ff083e6a9c41b" ) location = "true" qrcode_ocr = appbuilder.QRcodeOCR() out = qrcode_ocr.run(appbuilder.Message(content={"url": image_url, "location": location})) self.assertIn("QR_CODE", str(out.content)) if __name__ == '__main__': unittest.main() ================================================ FILE: python/tests/test_qa_aicape_table_ocr.py ================================================ # Copyright (c) 2024 Baidu, Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import os import unittest import appbuilder @unittest.skipUnless(os.getenv("TEST_CASE", "UNKNOWN") == "CPU_PARALLEL", "") class TestTableOcr(unittest.TestCase): def test_run(self): image_url = ( "https://bj.bcebos.com/v1/appbuilder/table_ocr_test.png?" "authorization=bce-auth-v1%2FALTAKGa8m4qCUasgoljdEDAzLm%2F2024-01-24T12%3A37%3A09Z%2F-1%2Fhost%2Fab528a5a9120d328dc6d18c6" "064079145ff4698856f477b820147768fc2187d3" ) table_ocr = appbuilder.TableOCR() out = table_ocr.run(appbuilder.Message(content={"url": image_url})) self.assertIn("tables_result", out.content) self.assertIn("header", out.content["tables_result"][0]) self.assertIn("body", out.content["tables_result"][0]) self.assertIn("table_location", out.content["tables_result"][0]) self.assertIn("流动资金来源", str(out.content)) if __name__ == '__main__': unittest.main() ================================================ FILE: python/tests/test_qa_doc_parser_extract_table_from_doc.py ================================================ # Copyright (c) 2024 Baidu, Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import unittest import os import appbuilder from appbuilder.core.message import Message @unittest.skipUnless(os.getenv("TEST_CASE", "UNKNOWN") == "CPU_PARALLEL", "") class TestDocParserExtractTableFromDoc(unittest.TestCase): def test_run(self): test_dir = os.path.dirname(__file__) image_path = os.path.join(test_dir, "data/qa_doc_parser_extract_table_from_doc.png") return_raw = True builder = appbuilder.DocParser() msg = Message(image_path) doc = builder(msg, return_raw=return_raw).content.raw ExtractTableBuilder = appbuilder.ExtractTableFromDoc() out = ExtractTableBuilder.run(Message(doc), table_max_size=1000) self.assertIn("客户名称", str(out)) self.assertIn("有限责任公司", str(out)) if __name__ == '__main__': unittest.main() ================================================ FILE: python/tests/test_qa_llm_dialog_summary.py ================================================ # Copyright (c) 2024 Baidu, Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import os import unittest import appbuilder from appbuilder import Message @unittest.skipUnless(os.getenv("TEST_CASE", "UNKNOWN") == "CPU_PARALLEL", "") class TestDialogSummaryComponent(unittest.TestCase): def test_run(self): model_name = "DeepSeek-V3.1" text = ("客户:你好,我购买的新笔记本电脑出现了无法连接无线网络的问题。客服:你好,很抱歉听到你遇到了" "网络问题。请问你尝试过重新启动路由器和笔记本电脑吗?客户:是的,我已经尝试过,但问题仍然存在。客服:" "明白了。请问其他设备是否能够成功连接到同一网络?客户:是的,我的手机和平板电脑都可以正常连接。客服:" "感谢你的反馈。在笔记本电脑无法连接网络时,你是否收到了任何错误消息?客户:是的,我收到了一个提示说" "“无法获得有效的IP地址”。客服:好的,这是有关IP地址分配的问题。请尝试手动分配一个IP地址并查看是否" "解决问题。我可以为你提供详细的步骤。客户:好的,我愿意尝试。客户:我按照你提供的步骤手动分配了IP地址," "但问题依然存在。客服:谢谢你的尝试。我们可能需要进一步检查网络设置。你是否同意进行远程连接以便我查看电脑" "的网络配置?客户:可以。客服:我发现你的网络配置正常,但存在一个驱动程序更新可能会解决的问题。你是否同意我" "协助你更新网络驱动程序?客户:好的,请帮我更新。客户:感谢你的帮助,更新后问题已经解决了。我现在可以正常连接到" "无线网络了。客服:太好了,我很高兴能够帮到你。如果还有其他问题,随时告诉我。客户:其实,我还有一个关于电池寿命的问题。" "最近感觉电池很快就耗尽了。客服:明白了,电池寿命问题也很重要。你可以尝试通过减少屏幕亮度和关闭一些背景应用来延长电池寿命。" "另外,我可以为你提供一些建议,帮你优化电池使用。") stream = None temperature = None builder = appbuilder.DialogSummary(model=model_name) msg = Message(content=text) input_params = {} if stream is not None: input_params["stream"] = stream if temperature is not None: input_params["temperature"] = temperature res = builder(msg, **input_params) content = "".join(res.content) if stream else res.content self.assertIn("诉求", content) self.assertIn("回应", content) self.assertIn("解决情况", content) if __name__ == '__main__': unittest.main() ================================================ FILE: python/tests/test_qa_llm_get_qianfan_model_list.py ================================================ # Copyright (c) 2024 Baidu, Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import os import unittest import appbuilder # @unittest.skipUnless(os.getenv("TEST_CASE", "UNKNOWN") == "CPU_PARALLEL", "") class TestGetQianfanModelList(unittest.TestCase): def test_run(self): """ 正常用例 """ secret_key = os.environ["APPBUILDER_TOKEN"] api_type_filter = ["chat", "completions", "embeddings", "text2image"] is_available = True models = appbuilder.get_model_list( secret_key=secret_key, api_type_filter=api_type_filter, is_available=is_available ) self.assertIn("ERNIE", str(models)) self.assertGreater(len(models), 0, "Model list should not be empty") if __name__ == '__main__': unittest.main() ================================================ FILE: python/tests/test_qa_llm_is_complex_query.py ================================================ # Copyright (c) 2024 Baidu, Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import os import unittest import appbuilder @unittest.skipUnless(os.getenv("TEST_CASE", "UNKNOWN") == "CPU_PARALLEL", "") class TestIsComplexQuery(unittest.TestCase): def test_run(self): model_name = "DeepSeek-V3.1" message = "吸塑包装盒在工业化生产和物流运输中分别有什么重要性?" is_complex_query = appbuilder.IsComplexQuery(model=model_name) out = is_complex_query(appbuilder.Message(content=message)) self.assertIn("类型:复杂问题", out.content) if __name__ == '__main__': unittest.main() ================================================ FILE: python/tests/test_qa_llm_matching.py ================================================ # Copyright (c) 2024 Baidu, Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import os import unittest import appbuilder @unittest.skipUnless(os.getenv("TEST_CASE", "UNKNOWN") == "CPU_PARALLEL", "") class TestSemanticRankComponent(unittest.TestCase): def test_normal_case(self): query = "合同中展期利率与罚息利率分别是什么?" contexts = [ "借款展期部分的利率为年化利率(单利),并按下列方式确定:借款展期期限加上原借款期限达到新的利率期限档次的,从展期之日起,借款利息" "按新的期限档次利率计收,年利率执行2%。", "乙方未按照本协议的约定按期偿还展期借款本息的,甲方有权在展期利率基础上加收1%作为罚息利率,对乙方逾期借款自应还款之日(含)起按罚" "息利率计收利息,并对未按时支付的利息(含罚息)按罚息利率计收复利。", "担保人承诺按照原担保合同的约定继续对借款人在原借款合同和本借款展期协议项下的全部义务承担担保责任。担保人提供的担保为保证担保的," "保证期间变更为自本协议约定的借款展期到期之日起三年。" ] query_message = appbuilder.Message(content=query) contexts_message = appbuilder.Message(content=contexts) embedding = appbuilder.Embedding() matching = appbuilder.Matching(embedding) out_matching = matching(query_message, contexts_message) query_embedding = embedding(query_message) context_embeddings = embedding.batch(contexts_message) out_semantics = matching.semantics(query_embedding, context_embeddings) self.assertEqual(len(out_matching.content), 3) self.assertEqual(len(out_semantics.content), 3) for score in out_semantics.content: self.assertGreater(score, 0) self.assertLess(score, 1) if __name__ == '__main__': unittest.main() ================================================ FILE: python/tests/test_qa_llm_oral_query_generation.py ================================================ # Copyright (c) 2024 Baidu, Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import os import unittest import appbuilder @unittest.skipUnless(os.getenv("TEST_CASE", "UNKNOWN") == "CPU_PARALLEL", "") class TestOralQueryGeneration(unittest.TestCase): def test_normal_case(self): model_name = "DeepSeek-V3.1" text = ('文档标题:在OPPO Reno5上使用视频超级防抖\n' '文档摘要:OPPO Reno5上的视频超级防抖,视频超级防抖3.0,多代视频防抖算法积累,这一代依旧超级防抖超级稳。 开启视频超级' '防抖 开启路径:打开「相机 > 视频 > 点击屏幕上方的“超级防抖”标识」 后置视频同时支持超级防抖和超级防抖Pro功能,开启超级' '防抖后手机屏幕将出现超级防抖Pro开关,点击即可开启或关闭。 除此之外,前置视频同样加持防抖算法,边走边拍也能稳定聚焦脸部' ',实时视频分享您的生活。') query_generation = appbuilder.OralQueryGeneration(model=model_name) msg = appbuilder.Message(content=text) out = query_generation(msg) self.assertIn("OPPO", str(out.content)) if __name__ == '__main__': unittest.main() ================================================ FILE: python/tests/test_qa_llm_paddle_speech_tts.py ================================================ # Copyright (c) 2024 Baidu, Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import os import unittest import appbuilder @unittest.skipUnless(os.getenv("TEST_CASE", "UNKNOWN") == "CPU_PARALLEL", "") class TestPaddleSpeechTTS(unittest.TestCase): def test_normal_case(self): text = "吸塑包装盒在工业化生产和物流运输中分别有什么重要性" tts_model = "paddlespeech-tts" audio_type = "wav" # Setup tts = appbuilder.TTS() inp = appbuilder.Message(content={"text": text}) param_dict = { "model": tts_model, "audio_type": audio_type, } out = tts.run(inp, **param_dict) self.assertGreaterEqual(len(out.content["audio_binary"]), 0) if __name__ == '__main__': unittest.main() ================================================ FILE: python/tests/test_qa_llm_pandas.py ================================================ # Copyright (c) 2024 Baidu, Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import os import unittest import appbuilder from appbuilder import Message @unittest.skipUnless(os.getenv("TEST_CASE", "UNKNOWN") == "CPU_PARALLEL", "") class TestNl2pandasComponent(unittest.TestCase): def test_normal_case(self): model_name = "DeepSeek-V3.1" query = "海淀区的学校数量" table_info = '''表格列信息如下: 学校名 : 清华附小 , 字符串类型,代表小学学校的名称 所属地区 : 西城区 , 字符串类型,表示该小学学校所在的位置 创办时间 : 1998 , 数字值类型,表示该小学学校的创办时间 类别 : 公立小学 , 字符串类型,表示该小学学校所在的类别 学生人数 : 2000 , 数字值类型,表示该小学学校的学生数量 教职工人数 : 140 , 数字值类型,表示该小学学校的教职工数量 教学班数量 : 122 , 数字值类型,表示该小学学校的教学班数量 ''' nl2pandas = appbuilder.Nl2pandasComponent(model=model_name) msg = Message(content=query) input_params = { "table_info": table_info, } out = nl2pandas(msg, **input_params) self.assertIn("df[", out.content) if __name__ == '__main__': unittest.main() ================================================ FILE: python/tests/test_qa_llm_query_decomposition.py ================================================ # Copyright (c) 2024 Baidu, Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import os import unittest import appbuilder @unittest.skipUnless(os.getenv("TEST_CASE", "UNKNOWN") == "CPU_PARALLEL", "") class TestQueryDecomposition(unittest.TestCase): def test_normal_case(self): model_name = "DeepSeek-V3.1" query = "吸塑包装盒在工业化生产和物流运输中分别有什么重要性" query_decomposition = appbuilder.QueryDecomposition(model=model_name) msg = appbuilder.Message(content=query) out = query_decomposition(msg) self.assertGreater(len(out.content.split("\n")), 0) if __name__ == '__main__': unittest.main() ================================================ FILE: python/tests/test_qa_llm_style_rewrite.py ================================================ # Copyright (c) 2024 Baidu, Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import os import unittest import appbuilder @unittest.skipUnless(os.getenv("TEST_CASE", "UNKNOWN") == "CPU_PARALLEL", "") class TestStyleRewrite(unittest.TestCase): def test_normal_case(self): text = "文心大模型发布新版" model_name = "DeepSeek-V3.1" style = "激励话术" builder = appbuilder.StyleRewrite(model=model_name) msg = appbuilder.Message(content=text) out = builder(msg, style=style) self.assertIn("文心大模型", out.content) if __name__ == '__main__': unittest.main() ================================================ FILE: python/tests/test_qa_pair_mining.py ================================================ # Copyright (c) 2023 Baidu, Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import unittest import os import appbuilder class TestQAPairMiningComponent(unittest.TestCase): def setUp(self): """ 设置环境变量。 Args: 无参数,默认值为空。 Returns: 无返回值,方法中执行了环境变量的赋值操作。 """ self.model_name = "DeepSeek-V3.1" self.node = appbuilder.QAPairMining(model=self.model_name) def test_run_with_default_params(self): """测试 run 方法使用默认参数""" query = "2017年,工商银行根据外部宏观环境变化..." msg = appbuilder.Message(query) answer = self.node(msg) self.assertIsNotNone(answer) self.assertIn("问题", answer.content) self.assertIn("答案", answer.content) # def test_run_with_custom_params(self): # """测试 run 方法使用自定义参数""" # query = "2017年,工商银行根据外部宏观环境变化..." # msg = appbuilder.Message(query) # answer = self.node(msg, stream=True, temperature=0.5) # self.assertIsNotNone(answer) # # 检查 answer 是否符合预期 def test_run_with_invalid_params(self): """测试 run 方法使用无效参数""" query = "2017年,工商银行根据外部宏观环境变化..." msg = appbuilder.Message(query) with self.assertRaises((ValueError, TypeError)): self.node(msg, invalid_param="invalid") def test_tool_eval_valid(self): """测试 tool 方法对有效请求的处理。""" params = { 'name': 'qa_pair_mining', 'query': '2017年,工商银行根据外部宏观环境变化...' } result = self.node.tool_eval(streaming=True, **params) res = [item for item in result] self.assertNotEqual(len(res), 0) result = self.node.tool_eval(streaming=False, **params) res = [item for item in result] def test_tool_eval_invalid(self): """测试 tool 方法对无效请求的处理。""" with self.assertRaises(ValueError): params = { 'name': 'qa_pair_mining' } result = self.node.tool_eval(streaming=True, **params) next(result) if __name__ == '__main__': unittest.main() ================================================ FILE: python/tests/test_qrcode_ocr.py ================================================ # Copyright (c) 2023 Baidu, Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import unittest import os import requests import unittest import appbuilder from appbuilder.core._exception import InvalidRequestArgumentError class TestQRcodeOCR(unittest.TestCase): def setUp(self): """ 设置环境变量。 """ self.qrcode_ocr = appbuilder.QRcodeOCR() def test_run_with_raw_image(self): """ 使用原始图片进行单测 Args: None Returns: None """ image_url = "https://bj.bcebos.com/v1/appbuilder/qrcode_ocr_test.png?" \ "authorization=bce-auth-v1%2FALTAKGa8m4qCUasgoljdEDAzLm%2F2024-" \ "01-24T12%3A45%3A13Z%2F-1%2Fhost%2Ffc43d07b41903aeeb5a023131ba6" \ "e74ab057ce26d50e966dc31ff083e6a9c41b" raw_image = requests.get(image_url).content # Create message with raw_image message = appbuilder.Message(content={"raw_image": raw_image}) # Qrcode ocr output = self.qrcode_ocr.run(message) # Assert output is not None self.assertIsNotNone(output) def test_run_with_url(self): """ 使用图片 URL 进行单测 Args: None Returns: None """ image_url = "https://bj.bcebos.com/v1/appbuilder/qrcode_ocr_test.png?" \ "authorization=bce-auth-v1%2FALTAKGa8m4qCUasgoljdEDAzLm%2F2024-" \ "01-24T12%3A45%3A13Z%2F-1%2Fhost%2Ffc43d07b41903aeeb5a023131ba6" \ "e74ab057ce26d50e966dc31ff083e6a9c41b" # Create message with image URL message = appbuilder.Message(content={"url": image_url}) # Qrcode ocr output = self.qrcode_ocr.run(message) # Assert output is not None self.assertIsNotNone(output) def test_run_with_args(self): """ 测试run方法,location、timeout、retry参数 Args: None Returns: None """ image_url = "https://bj.bcebos.com/v1/appbuilder/qrcode_ocr_test.png?" \ "authorization=bce-auth-v1%2FALTAKGa8m4qCUasgoljdEDAzLm%2F2024-" \ "01-24T12%3A45%3A13Z%2F-1%2Fhost%2Ffc43d07b41903aeeb5a023131ba6" \ "e74ab057ce26d50e966dc31ff083e6a9c41b" raw_image = requests.get(image_url).content # Create message with raw_image message = appbuilder.Message(content={"raw_image": raw_image}) # Qrcode ocr with timeout and retry parameters output = self.qrcode_ocr.run(message, location="true", timeout=5.0, retry=3) # Assert output is not None self.assertIsNotNone(output) def test_run_with_invalid_input(self): """ 测试run函数在传入无效输入的情况下的行为。 Args: None Returns: None """ # create empty message message = appbuilder.Message(content={}) # Assert ValueError is raised with self.assertRaises(ValueError): self.qrcode_ocr.run(message) def test_run_with_invalid_url(self): """ 测试run函数在传入无效URL的情况下的行为。 Args: None Returns: None """ url = "http://example.com/invalid_url.jpg" message = appbuilder.Message(content={"url": url}) with self.assertRaises(appbuilder.AppBuilderServerException): self.qrcode_ocr.run(message) with self.assertRaises(InvalidRequestArgumentError): self.qrcode_ocr.run(message=message,location='test') def test_tool_eval(self): image_url = "https://bj.bcebos.com/v1/appbuilder/qrcode_ocr_test.png?" \ "authorization=bce-auth-v1%2FALTAKGa8m4qCUasgoljdEDAzLm%2F2024-" \ "01-24T12%3A45%3A13Z%2F-1%2Fhost%2Ffc43d07b41903aeeb5a023131ba6" \ "e74ab057ce26d50e966dc31ff083e6a9c41b" result=self.qrcode_ocr.tool_eval(name='name',streaming=False,files=['test']) with self.assertRaises(InvalidRequestArgumentError): next(result) result=self.qrcode_ocr.tool_eval( name='name', streaming=True, file_names=['test'], file_urls={'test':image_url} ) res=next(result) self.assertEqual(res['visible_scope'],'llm') res=next(result) self.assertEqual(res['visible_scope'],'user') result=self.qrcode_ocr.tool_eval( name='name', streaming=False, file_names=['test'], file_urls={'test':image_url}, locations = 'test' ) with self.assertRaises(InvalidRequestArgumentError): next(result) if __name__ == '__main__': unittest.main() ================================================ FILE: python/tests/test_query_decomposition.py ================================================ # Copyright (c) 2023 Baidu, Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import unittest import os import appbuilder @unittest.skipUnless(os.getenv("TEST_CASE", "UNKNOWN") == "CPU_PARALLEL", "") class TestQueryDecompositionComponent(unittest.TestCase): def setUp(self): """ 设置环境变量。 Args: 无参数,默认值为空。 Returns: 无返回值,方法中执行了环境变量的赋值操作。 """ self.model_name = "DeepSeek-V3.1" self.node = appbuilder.QueryDecomposition(model=self.model_name) def test_run_with_default_params(self): """测试 run 方法使用默认参数""" query = "吸塑包装盒在工业化生产和物流运输中分别有什么重要性?" msg = appbuilder.Message(query) answer = self.node(msg) self.assertIsNotNone(answer) # def test_run_with_custom_params(self): # """测试 run 方法使用自定义参数""" # query = "吸塑包装盒在工业化生产和物流运输中分别有什么重要性?" # msg = appbuilder.Message(query) # answer = self.node(msg, stream=True, temperature=0.5) # self.assertIsNotNone(answer) # # 检查 answer 是否符合预期 def test_run_with_invalid_params(self): """测试 run 方法使用无效参数""" query = "吸塑包装盒在工业化生产和物流运输中分别有什么重要性?" msg = appbuilder.Message(query) with self.assertRaises((ValueError, TypeError)): self.node(msg, invalid_param="invalid") def test_tool_eval_valid(self): """测试 tool 方法对有效请求的处理。""" params = { 'name': 'query_decomposition', 'query': '吸塑包装盒在工业化生产和物流运输中分别有什么重要性?' } result = self.node.tool_eval(streaming=True, **params) res = [item for item in result] self.assertNotEqual(len(res), 0) result = self.node.tool_eval(streaming=False, **params) res = [item for item in result] def test_tool_eval_invalid(self): """测试 tool 方法对无效请求的处理。""" with self.assertRaises(ValueError): params = { 'name': 'query_decomposition' } result = self.node.tool_eval(streaming=True, **params) next(result) if __name__ == '__main__': unittest.main() ================================================ FILE: python/tests/test_query_rewrite.py ================================================ # Copyright (c) 2023 Baidu, Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # !/usr/bin/env python3 import os import unittest from typing import List, Tuple import appbuilder @unittest.skipUnless(os.getenv("TEST_CASE", "UNKNOWN") == "CPU_PARALLEL", "") class TestQueryRewriteComponent(unittest.TestCase): def setUp(self): """ 初始化查询重写组件的单元测试基类。 Args: 无参数。 Returns: 无返回值。 """ # 设置环境变量和初始化TranslateComponent实例 self.model_name = "DeepSeek-V3.1" self.node = appbuilder.QueryRewrite(model=self.model_name) def test_run_with_default_params(self): """测试 run 方法使用默认参数""" query = ['我应该怎么办理护照?', '您可以查询官网或人工咨询', '我需要准备哪些材料?', '身份证、免冠照片一张以及填写完整的《中国公民因私出国(境)申请表》', '在哪里办'] msg = appbuilder.Message(query) answer = self.node(msg) self.assertIsNotNone(answer) # 可以添加更多断言来检查 answer 的特定属性 def test_run_with_custom_params(self): """测试 run 方法使用自定义参数""" query = ['我应该怎么办理护照?', '您可以查询官网或人工咨询', '我需要准备哪些材料?', '身份证、免冠照片一张以及填写完整的《中国公民因私出国(境)申请表》', '在哪里办'] msg = appbuilder.Message(query) type = "仅用户查询" answer = self.node(msg, rewrite_type=type) self.assertIsNotNone(answer) # 检查 answer 是否符合预期 def test_run_with_stream_and_temperature(self): """测试不同的 stream 和 temperature 参数值""" node = appbuilder.QueryRewrite("DeepSeek-V3.1") query = ['我应该怎么办理护照?', '您可以查询官网或人工咨询', '我需要准备哪些材料?', '身份证、免冠照片一张以及填写完整的《中国公民因私出国(境)申请表》', '在哪里办'] msg = appbuilder.Message(query) answer = node(msg, rewrite_type="带机器人回复", stream=False, temperature=0.5) self.assertIsNotNone(answer) def test_run_raise(self): with self.assertRaises(ValueError): self.node(message=None) query = ['我应该怎么办理护照?', '您可以查询官网或人工咨询'] msg=appbuilder.Message(query) with self.assertRaises(ValueError): self.node(message=msg) test_str='test'*1500 query = [test_str] msg=appbuilder.Message(query) with self.assertRaises(ValueError): self.node(message=msg) def test_tool_eval_valid(self): """测试 tool 方法对有效请求的处理。""" params = { 'name': 'query_rewrite', 'query': ['我应该怎么办理护照?', '您可以查询官网或人工咨询'] } result = self.node.tool_eval(streaming=True, **params) res = [item for item in result] self.assertNotEqual(len(res), 0) result = self.node.tool_eval(streaming=False, **params) res = [item for item in result] def test_tool_eval_invalid(self): """测试 tool 方法对无效请求的处理。""" with self.assertRaises(ValueError): params = { 'name': 'query_rewrite' } result = self.node.tool_eval(streaming=True, **params) next(result) if __name__ == '__main__': unittest.main() ================================================ FILE: python/tests/test_rag_baidu_search.py ================================================ import os import unittest import appbuilder import json @unittest.skipUnless(os.getenv("TEST_CASE", "UNKNOWN") == "CPU_PARALLEL", "") class TestRagBaiduSearch(unittest.TestCase): def setUp(self): """ return rag_with_baidu_search class """ # 设置环境变量和初始化TestMRCComponent实例 self.model_name = "DeepSeek-V3.1" self.rag_with_baidu_search = appbuilder.RAGWithBaiduSearch(model=self.model_name) def test_rag_with_baidu_search(self): msg = "残疾人怎么办相关证件" msg = appbuilder.Message(msg) is_stream = False instruction = "你是问答助手,在回答问题前需要加上“很高兴为您解答:”" instruction = appbuilder.Message(instruction) answer = self.rag_with_baidu_search(msg, reject=True, clarify=True, highlight=True, friendly=True, cite=True, temperature=0.5, stream=is_stream, instruction=instruction) self.assertIsNotNone(answer) if not is_stream: self.assertIsNotNone(answer.content) self.assertIsNotNone(answer.extra) else: for content, extra in zip(answer.content, answer.extra): self.assertIsNotNone(content) self.assertIsNotNone(extra) def test_rag_with_baidu_search_with_none_inst(self): msg = "残疾人怎么办相关证件" msg = appbuilder.Message(msg) is_stream = False instruction = None answer = self.rag_with_baidu_search(msg, reject=True, clarify=True, highlight=True, friendly=True, cite=True, temperature=0.5, top_p=0.1, stream=is_stream, instruction=instruction) self.assertIsNotNone(answer) if not is_stream: self.assertIsNotNone(answer.content) self.assertIsNotNone(answer.extra) else: for content, extra in zip(answer.content, answer.extra): self.assertIsNotNone(content) self.assertIsNotNone(extra) ================================================ FILE: python/tests/test_rag_baidu_search_pro.py ================================================ # -*- coding: utf-8 -*- """ @time : 24.5.24 PM3:44 @File: test_rag_baidu_search_pro @Author : baiyuchen @Version: python3.8 """ import os import unittest import appbuilder from appbuilder.core._exception import AppBuilderServerException @unittest.skipUnless(os.getenv("TEST_CASE", "UNKNOWN") == "CPU_PARALLEL", "") class TestRagBaiduSearch(unittest.TestCase): def setUp(self): """ return rag_with_baidu_search class """ self.model_name = "DeepSeek-V3.1" self.rag_with_baidu_search_pro = appbuilder.RagWithBaiduSearchPro(model=self.model_name) def test_rag_with_baidu_search_pro_block(self): msg = "残疾人怎么办相关证件" msg = appbuilder.Message(msg) is_stream = False instruction = "你是问答助手,在回答问题前需要加上“很高兴为您解答:”" instruction = appbuilder.Message(instruction) answer = self.rag_with_baidu_search_pro(message=msg, stream=is_stream, instruction=instruction) self.assertIsNotNone(answer) self.assertIsNotNone(answer.content) self.assertIsInstance(answer.content, str) self.assertTrue(answer.content != "") search_baidu = answer.extra.get("search_baidu") ref_content = search_baidu[0]["content"] self.assertIsNotNone(ref_content) self.assertIsInstance(ref_content, str) self.assertTrue(ref_content != "") def test_rag_with_baidu_search_pro_stream(self): msg = "残疾人怎么办相关证件" msg = appbuilder.Message(msg) is_stream = True instruction = "你是问答助手,在回答问题前需要加上“很高兴为您解答:”" instruction = appbuilder.Message(instruction) answer = self.rag_with_baidu_search_pro(message=msg, stream=is_stream, instruction=instruction) self.assertIsNotNone(answer) flag_content = False flag_ref_content = False for content in answer.content: self.assertIsNotNone(content) self.assertIsNotNone(answer.extra) self.assertIsInstance(content, str) if content != "": flag_content = True search_baidu = answer.extra.get("search_baidu") if search_baidu: ref_content = search_baidu[0]["content"] self.assertIsInstance(ref_content, str) if ref_content != "": flag_ref_content = True self.assertTrue(flag_content and flag_ref_content) def test_rag_with_baidu_search_component_RAGWithBaiduSearch(self): rwbs=appbuilder.RAGWithBaiduSearch(model='ERNIE-Bot 4.0') # test_get_search_input text='text' res_text=rwbs._get_search_input(text) self.assertEqual(res_text, 'text') text='UTF-8是一种变长字节表示的Unicode字符集编码方式,它可以使用1到4个字节来表示一个字符。' res_text=rwbs._get_search_input(text) self.assertEqual(res_text, 'UTF-8是一种变长字节表示的Unicode字符集编码方式,它可') # test run message=appbuilder.Message() message.content=""" appbuilderappbuilderappbuilderappbuilderappbuilderappbuilderappbuilderappbuilder appbuilderappbuilderappbuilderappbuilderappbuilderappbuilderappbuilderappbuilder """ with self.assertRaises(AppBuilderServerException): rwbs.run(message=message) if __name__ == '__main__': unittest.main() ================================================ FILE: python/tests/test_rerank.py ================================================ """ test rerank """ import os import time import unittest import appbuilder class TestReranker(unittest.TestCase): def setUp(self): self.reranker = appbuilder.Reranker() def test_run(self): ranked_1 = self.reranker("你好", ["他好", "hello?"]) time.sleep(1) ranked_2 = self.reranker(appbuilder.Message("你好"), appbuilder.Message(["他好", "hello?"])) self.assertEqual(ranked_1.content[0]["relevance_score"], ranked_2.content[0]["relevance_score"]) self.assertEqual(ranked_1.content[1]["relevance_score"], ranked_2.content[1]["relevance_score"]) def test_not_support_model(self): try: _ = appbuilder.Reranker(model="foo") except Exception as e: from appbuilder.core._exception import ModelNotSupportedException assert isinstance(e, ModelNotSupportedException) msg = str(e) assert "Model foo not supported" in msg if __name__ == '__main__': unittest.main() ================================================ FILE: python/tests/test_similar_question.py ================================================ # Copyright (c) 2023 Baidu, Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import unittest import os import appbuilder class TestSimilarQuestionComponent(unittest.TestCase): def setUp(self): """ 设置环境变量。 Args: 无参数,默认值为空。 Returns: 无返回值,方法中执行了环境变量的赋值操作。 """ self.model_name = "DeepSeek-V3.1" self.node = appbuilder.SimilarQuestion(model=self.model_name) def test_run_with_default_params(self): """测试 run 方法使用默认参数""" query = "我想吃冰淇淋,哪里的冰淇淋比较好吃?" msg = appbuilder.Message(query) answer = self.node(msg) self.assertIsNotNone(answer) def test_tool_eval_valid(self): """测试 tool_eval 方法使用有效参数""" query = "我想吃冰淇淋,哪里的冰淇淋比较好吃?" result = self.node.tool_eval(name="similar_question", streaming=True, query=query) res = [item for item in result] self.assertNotEqual(len(res), 0) def test_tool_eval_invalid(self): """测试 tool_eval 方法使用无效参数""" with self.assertRaises(ValueError): result = self.node.tool_eval(name="similar_question", streaming=True) next(result) if __name__ == '__main__': unittest.main() ================================================ FILE: python/tests/test_style_rewrite.py ================================================ """ Copyright (c) 2023 Baidu, Inc. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. """ import unittest import os from appbuilder.core.components.llms.style_rewrite.base import StyleChoices import appbuilder class TestStyleRewriteComponent(unittest.TestCase): def setUp(self): """ 设置环境变量。 Args: 无参数,默认值为空。 Returns: 无返回值,方法中执行了环境变量的赋值操作。 """ self.model_name = "DeepSeek-V3.1" self.node = appbuilder.StyleRewrite(model=self.model_name) self.sc=StyleChoices.YINGXIAO def test_to_chinese(self): result=self.sc.to_chinese() self.assertEqual(result,"营销话术") def test_run_with_custom_params(self): """测试 run 方法使用自定义参数""" query = "帮我写一篇关于人体工学椅的文案" msg = appbuilder.Message(query) style = "营销话术" answer = self.node(msg, style=style) self.assertIsNotNone(answer) # 检查 answer 是否符合预期 def test_tool_eval_valid(self): """测试 tool_eval 方法使用有效参数""" query = "帮我写一篇关于人体工学椅的文案" result = self.node.tool_eval(name="style_rewrite", streaming=True, query=query) res = [item for item in result] self.assertNotEqual(len(res), 0) def test_tool_eval_invalid(self): """测试 tool_eval 方法使用无效参数""" with self.assertRaises(ValueError): result = self.node.tool_eval(name="style_rewrite", streaming=True) next(result) if __name__ == '__main__': unittest.main() ================================================ FILE: python/tests/test_style_writing.py ================================================ """ Copyright (c) 2023 Baidu, Inc. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. """ import unittest import os import appbuilder import time from appbuilder.core.components.llms.style_writing.component import StyleQueryChoices, LengthChoices class TestStyleWritingComponent(unittest.TestCase): def setUp(self): """ 设置环境变量。 Args: 无参数,默认值为空。 Returns: 无返回值,方法中执行了环境变量的赋值操作。 """ self.model_name = "DeepSeek-V3.1" self.node = appbuilder.StyleWriting(model=self.model_name) self.sqc=StyleQueryChoices.BILIBILI self.lc=LengthChoices.SHORT def test_to_chinese(self): result=self.sqc.to_chinese() self.assertEqual(result,"B站") result=self.lc.to_chinese() self.assertEqual(result,"短") def test_run_with_custom_params(self): """测试 run 方法使用自定义参数""" query = "帮我写一篇关于人体工学椅的文案" msg = appbuilder.Message(query) style = "小红书" length = 100 answer = self.node(msg, style_query=style, length=length) self.assertIsNotNone(answer) # 检查 answer 是否符合预期 def test_tool_eval_valid(self): """测试 tool_eval 方法使用有效参数""" query = "帮我写一篇关于人体工学椅的文案" result = self.node.tool_eval(name="style_writing", streaming=True, query=query) res = [item for item in result] self.assertNotEqual(len(res), 0) time.sleep(1) def test_tool_eval_invalid(self): """测试 tool_eval 方法使用无效参数""" with self.assertRaises(ValueError): result = self.node.tool_eval(name="style_writing", streaming=True) next(result) if __name__ == '__main__': unittest.main() ================================================ FILE: python/tests/test_table_ocr.py ================================================ # Copyright (c) 2023 Baidu, Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import unittest import requests import appbuilder import os from appbuilder.core._exception import InvalidRequestArgumentError class TestTableOCR(unittest.TestCase): def setUp(self): """ 设置环境变量。 """ self.table_ocr = appbuilder.TableOCR() def test_run_with_raw_image(self): """ 使用原始图片进行单测 Args: None Returns: None """ image_url = "https://bj.bcebos.com/v1/appbuilder/table_ocr_test.png?" \ "authorization=bce-auth-v1%2FALTAKGa8m4qCUasgoljdEDAzLm%2F2024" \ "-01-24T12%3A37%3A09Z%2F-1%2Fhost%2Fab528a5a9120d328dc6d18c6" \ "064079145ff4698856f477b820147768fc2187d3" raw_image = requests.get(image_url).content # Create message with raw_image message = appbuilder.Message(content={"raw_image": raw_image}) # Table ocr output = self.table_ocr.run(message) # Assert output is not None self.assertIsNotNone(output) def test_run_with_url(self): """ 使用图片 URL 进行单测 Args: None Returns: None """ image_url = "https://bj.bcebos.com/v1/appbuilder/table_ocr_test.png?" \ "authorization=bce-auth-v1%2FALTAKGa8m4qCUasgoljdEDAzLm%2F2024" \ "-01-24T12%3A37%3A09Z%2F-1%2Fhost%2Fab528a5a9120d328dc6d18c6" \ "064079145ff4698856f477b820147768fc2187d3" # Create message with image URL message = appbuilder.Message(content={"url": image_url}) # Table ocr output = self.table_ocr.run(message) # Assert output is not None self.assertIsNotNone(output) def test_run_with_timeout_and_retry(self): """ 测试run方法,timeout、retry参数 Args: None Returns: None """ image_url = "https://bj.bcebos.com/v1/appbuilder/table_ocr_test.png?" \ "authorization=bce-auth-v1%2FALTAKGa8m4qCUasgoljdEDAzLm%2F2024" \ "-01-24T12%3A37%3A09Z%2F-1%2Fhost%2Fab528a5a9120d328dc6d18c6" \ "064079145ff4698856f477b820147768fc2187d3" raw_image = requests.get(image_url).content message = appbuilder.Message(content={"raw_image": raw_image}) # TableOCR with timeout and retry parameters output = self.table_ocr.run(message, timeout=5.0, retry=3) # Assert output is not None self.assertIsNotNone(output) def test_run_with_invalid_input(self): """ 测试run函数在传入无效输入的情况下的行为。 Args: None Returns: None """ # create empty message message = appbuilder.Message(content={}) # Assert ValueError is raised with self.assertRaises(ValueError): self.table_ocr.run(message) def test_run_with_invalid_url(self): """ 测试run函数在传入无效URL的情况下的行为。 Args: None Returns: None """ url = "http://example.com/invalid_url.jpg" message = appbuilder.Message(content={"url": url}) with self.assertRaises(appbuilder.AppBuilderServerException): self.table_ocr.run(message) def test_tool_eval(self): image_url = "https://bj.bcebos.com/v1/appbuilder/table_ocr_test.png?" \ "authorization=bce-auth-v1%2FALTAKGa8m4qCUasgoljdEDAzLm%2F2024" \ "-01-24T12%3A37%3A09Z%2F-1%2Fhost%2Fab528a5a9120d328dc6d18c6" \ "064079145ff4698856f477b820147768fc2187d3" result=self.table_ocr.tool_eval(name='name',streaming=False,files=['test']) with self.assertRaises(InvalidRequestArgumentError): next(result) result=self.table_ocr.tool_eval( name='name', streaming=True, file_names=['test'], file_urls={'test':image_url} ) res=next(result) self.assertEqual(res['visible_scope'],'llm') res=next(result) self.assertEqual(res['visible_scope'],'user') if __name__ == '__main__': unittest.main() ================================================ FILE: python/tests/test_tag_extraction.py ================================================ # Copyright (c) 2023 Baidu, Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License.import unittest import os import appbuilder import os import unittest @unittest.skipUnless(os.getenv("TEST_CASE", "UNKNOWN") == "CPU_PARALLEL", "") class TestTagExtractionComponent(unittest.TestCase): def setUp(self): """ 设置环境变量。 Args: 无参数,默认值为空。 Returns: 无返回值,方法中执行了环境变量的赋值操作。 """ self.model_name = "DeepSeek-V3.1" self.tag_extraction = appbuilder.TagExtraction(model=self.model_name) def test_run_with_default_params(self): """测试 run 方法使用默认参数""" query = "本实用新型公开了一种可利用热能的太阳能光伏光热一体化组件,包括太阳能电池,还包括有吸热板,太阳能电池粘附在吸热板顶面,吸热板内嵌入有热电材料制成的内芯,吸热板底面设置有蛇形管。本实用新型结构紧凑,安装方便,能充分利用太阳能电池散发的热能,具有较高的热能利用率。" msg = appbuilder.Message(query) answer = self.tag_extraction(msg) print(answer) self.assertIsNotNone(answer) def test_run_with_stream_and_temperature(self): """测试不同的 stream 和 temperature 参数值""" msg = appbuilder.Message("本实用新型公开了一种可利用热能的太阳能光伏光热一体化组件,包括太阳能电池,还包括有吸热板,太阳能电池粘附在吸热板顶面,吸热板内嵌入有热电材料制成的内芯,吸热板底面设置有蛇形管。本实用新型结构紧凑,安装方便,能充分利用太阳能电池散发的热能,具有较高的热能利用率。") answer = self.tag_extraction(msg, stream=False, temperature=0.5) self.assertIsNotNone(answer) def test_tool_eval_valid(self): """测试 tool 方法对有效请求的处理。""" params = { 'name': 'tag_extraction', 'query': '本实用新型公开了一种可利用热能的太阳能光伏光热一体化组件,包括太阳能电池,还包括有吸热板,太阳能电池粘附在吸热板顶面,吸热板内嵌入有热电材料制成的内芯,吸热板底面设置有蛇形管。本实用新型结构紧凑,安装方便,能充分利用太阳能电池散发的热能,具有较高的热能利用率。' } result = self.tag_extraction.tool_eval(streaming=True, **params) res = [item for item in result] self.assertNotEqual(len(res), 0) result = self.tag_extraction.tool_eval(streaming=False, **params) res = [item for item in result] def test_tool_eval_invalid(self): """测试 tool 方法对无效请求的处理。""" with self.assertRaises(ValueError): params = { 'name': 'tag_extraction' } result = self.tag_extraction.tool_eval(streaming=True, **params) next(result) if __name__ == '__main__': unittest.main() ================================================ FILE: python/tests/test_text_to_image.py ================================================ import unittest import os import appbuilder from appbuilder.core.components.text_to_image.model import (Text2ImageSubmitRequest, Text2ImageSubmitResponse, Text2ImageQueryRequest, Text2ImageQueryResponse, SubTaskResult) from appbuilder.core._exception import RiskInputException @unittest.skip("偶现报错暂时跳过") class TestText2ImageComponent(unittest.TestCase): def setUp(self): """ 设置环境变量。 Args: None Returns: None. """ self.text2Image = appbuilder.Text2Image() def test_run(self): """ 使用原始文本进行单测 Args: None Returns: None """ inp = appbuilder.Message(content={"prompt": "上海的经典风景"}) out = self.text2Image.run(inp) print(out) self.assertIsNotNone(out) self.assertIsInstance(out, appbuilder.Message) def test_submitText2ImageTask(self): """ submitText2ImageTask方法单测 Args: None Returns: None """ request = Text2ImageSubmitRequest() request.prompt = "上海的经典风景" request.width = 1024 request.height = 1024 request.image_num = 1 response = self.text2Image.submitText2ImageTask(request) self.assertIsNotNone(response) self.assertIsInstance(response, Text2ImageSubmitResponse) def test_queryText2ImageData(self): """ queryText2ImageData方法单测 Args: None Returns: None """ request = Text2ImageQueryRequest( task_id = "123456", ) response = self.text2Image.queryText2ImageData(request) self.assertIsNotNone(response) self.assertIsInstance(response, Text2ImageQueryResponse) def test_extract_img_urls(self): """ extract_img_urls方法单测 Args: None Returns: None """ response = Text2ImageQueryResponse() response.data.task_progress = 1.0 response.data.task_progress_detail = 0.5 response.data.sub_task_result_list = [SubTaskResult(**{'sub_task_progress_detail':0.8, 'final_image_list': [{'img_url': 'http://example.com'}]})] img_urls = self.text2Image.extract_img_urls(response) self.assertEqual(img_urls, ['http://example.com']) def test_check_service_error(self): """ check_service_error方法单测 Args: None Returns: None """ data = {"error_code": "ERROR", "error_msg": "Error message"} with self.assertRaises(appbuilder.AppBuilderServerException): self.text2Image.check_service_error("", data) if __name__ == '__main__': unittest.main() ================================================ FILE: python/tests/test_trace.py ================================================ # Copyright (c) 2024 Baidu, Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import os import unittest import appbuilder @unittest.skipUnless(os.getenv("TEST_CASE", "UNKNOWN") == "CPU_PARALLEL", "") class TestTrace(unittest.TestCase): def test_trace(self): from appbuilder.utils.trace._function import _client_tool_trace_output_deep_iterate try: test_dict = { "a": 1, "b": [2], "c": {3: "4"}, } _client_tool_trace_output_deep_iterate(output=test_dict, span=None) except: print("test_trace测试span添加dict类型") if __name__ == "__main__": unittest.main() ================================================ FILE: python/tests/test_trace_skip_raise_error.py ================================================ # Copyright (c) 2024 Baidu, Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import os import unittest from appbuilder.utils.trace.tracer_wrapper import ( session_post, client_run_trace, client_tool_trace, assistent_tool_trace, assistant_run_trace, assistent_stream_run_trace, assistent_stream_run_with_handler_trace, components_run_trace, components_run_stream_trace, list_trace, ) class TestException(Exception): def __init__(self): pass @session_post def mock_post_01(): raise Exception("mock exception") @session_post def mock_post_02(): raise TestException() @client_run_trace def mock_client_run_trace_01(): raise Exception("mock exception") @client_run_trace def mock_client_run_trace_02(): raise TestException() @client_tool_trace def mock_client_tool_trace_01(): raise Exception("mock exception") @client_tool_trace def mock_client_tool_trace_02(): raise TestException() @assistent_tool_trace def mock_assistent_tool_trace_01(): raise Exception("mock exception") @assistent_tool_trace def mock_assistent_tool_trace_02(): raise TestException() @assistant_run_trace def mock_assistant_run_trace_01(): raise Exception("mock exception") @assistant_run_trace def mock_assistant_run_trace_02(): raise TestException() @assistent_stream_run_trace def mock_assistent_stream_run_trace_01(): raise Exception("mock exception") @assistent_stream_run_trace def mock_assistent_stream_run_trace_02(): raise TestException() @assistent_stream_run_with_handler_trace def mock_assistent_stream_run_with_handler_trace_01(): raise Exception("mock exception") @assistent_stream_run_with_handler_trace def mock_assistent_stream_run_with_handler_trace_02(): raise TestException() @components_run_trace def mock_components_run_trace_01(): raise Exception("mock exception") @components_run_trace def mock_components_run_trace_02(): raise TestException() @components_run_stream_trace def mock_components_run_stream_trace_01(): raise Exception("mock exception") @components_run_stream_trace def mock_components_run_stream_trace_02(): raise TestException() @list_trace def mock_list_trace_01(): raise Exception("mock exception") @list_trace def mock_list_trace_02(): raise TestException() class TestTraceSkipRaiseError(unittest.TestCase): def setUp(self): os.environ["APPBUILDER_TRACE_DEBUG"] = "True" os.environ["APPBUILDER_SDK_TRACE_ENABLE"] = "true" def tearDown(self): del os.environ["APPBUILDER_TRACE_DEBUG"] del os.environ["APPBUILDER_SDK_TRACE_ENABLE"] def test_session_post(self): # test_session_post APPBUILDER_TRACE_DEBUG = true os.environ["APPBUILDER_TRACE_DEBUG"] = "true" with self.assertRaises(Exception): mock_post_01() # test_session_post APPBUILDER_TRACE_DEBUG = false os.environ["APPBUILDER_TRACE_DEBUG"] = "false" with self.assertRaises(Exception): mock_post_01() with self.assertRaises(TestException): mock_post_02() os.environ["APPBUILDER_SDK_TRACE_ENABLE"] = "false" with self.assertRaises(Exception): mock_post_02() def test_client_run_trace(self): # test_client_run_trace APPBUILDER_TRACE_DEBUG = true os.environ["APPBUILDER_TRACE_DEBUG"] = "true" with self.assertRaises(Exception): mock_client_run_trace_01() # test_client_run_trace APPBUILDER_TRACE_DEBUG = false os.environ["APPBUILDER_TRACE_DEBUG"] = "false" with self.assertRaises(Exception): mock_client_run_trace_01() with self.assertRaises(TestException): mock_client_run_trace_02() os.environ["APPBUILDER_SDK_TRACE_ENABLE"] = "false" with self.assertRaises(Exception): mock_client_run_trace_02() def test_client_tool_trace(self): # test_client_tool_trace APPBUILDER_TRACE_DEBUG = true os.environ["APPBUILDER_TRACE_DEBUG"] = "true" with self.assertRaises(Exception): mock_client_tool_trace_01() # test_client os.environ["APPBUILDER_TRACE_DEBUG"] = "false" with self.assertRaises(Exception): mock_client_tool_trace_01() with self.assertRaises(TestException): mock_client_tool_trace_02() os.environ["APPBUILDER_SDK_TRACE_ENABLE"] = "false" with self.assertRaises(Exception): mock_client_tool_trace_02() def test_assistent_tool_trace(self): # test_assistent_tool_trace APPBUILDER_TRACE_DEBUG = true os.environ["APPBUILDER_TRACE_DEBUG"] = "true" with self.assertRaises(Exception): mock_assistent_tool_trace_01() # test_assistent_tool_trace APPBUILDER_TRACE_DEBUG = false os.environ["APPBUILDER_TRACE_DEBUG"] = "false" with self.assertRaises(Exception): mock_assistent_tool_trace_01() with self.assertRaises(TestException): mock_assistent_tool_trace_02() os.environ["APPBUILDER_SDK_TRACE_ENABLE"] = "false" with self.assertRaises(Exception): mock_assistent_tool_trace_02() def test_assistant_run_trace(self): # test_assistant_run_trace APPBUILDER_TRACE_DEBUG = true os.environ["APPBUILDER_TRACE_DEBUG"] = "true" with self.assertRaises(Exception): mock_assistant_run_trace_01() # test_assistant_run_trace APPBUILDER_TRACE_DEBUG = false os.environ["APPBUILDER_TRACE_DEBUG"] = "false" with self.assertRaises(Exception): mock_assistant_run_trace_01() with self.assertRaises(TestException): mock_assistant_run_trace_02() os.environ["APPBUILDER_SDK_TRACE_ENABLE"] = "false" with self.assertRaises(Exception): mock_assistant_run_trace_02() def test_assistent_stream_run_trace(self): # test_assistent_stream_run_trace APPBUILDER_TRACE_DEBUG = true os.environ["APPBUILDER_TRACE_DEBUG"] = "true" with self.assertRaises(Exception): mock_assistent_stream_run_trace_01() # test_assistent_stream_run_trace APPBUILDER_TRACE_DEBUG = false os.environ["APPBUILDER_TRACE_DEBUG"] = "false" with self.assertRaises(Exception): mock_assistent_stream_run_trace_01() with self.assertRaises(TestException): mock_assistent_stream_run_trace_02() os.environ["APPBUILDER_SDK_TRACE_ENABLE"] = "false" with self.assertRaises(Exception): mock_assistent_stream_run_trace_02() def test_assistent_stream_run_with_handler_trace(self): # test_assistent_stream_run_with_handler_trace APPBUILDER_TRACE_DEBUG = true os.environ["APPBUILDER_TRACE_DEBUG"] = "true" with self.assertRaises(Exception): mock_assistent_stream_run_with_handler_trace_01() # test_assistent_stream_run_with_handler_trace APPBUILDER_TRACE_DEBUG = false os.environ["APPBUILDER_TRACE_DEBUG"] = "false" with self.assertRaises(Exception): mock_assistent_stream_run_with_handler_trace_01() with self.assertRaises(TestException): mock_assistent_stream_run_with_handler_trace_02() os.environ["APPBUILDER_SDK_TRACE_ENABLE"] = "false" with self.assertRaises(Exception): mock_assistent_stream_run_with_handler_trace_02() def test_components_run_trace(self): # test_components_run_trace APPBUILDER_TRACE_DEBUG = true os.environ["APPBUILDER_TRACE_DEBUG"] = "true" with self.assertRaises(Exception): mock_components_run_trace_01() # test_components_run_trace APPBUILDER_TRACE_DEBUG = false os.environ["APPBUILDER_TRACE_DEBUG"] = "false" with self.assertRaises(Exception): mock_components_run_trace_01() with self.assertRaises(TestException): mock_components_run_trace_02() os.environ["APPBUILDER_SDK_TRACE_ENABLE"] = "false" with self.assertRaises(Exception): mock_components_run_trace_02() def test_components_run_stream_trace(self): # test_components_run_stream_trace APPBUILDER_TRACE_DEBUG = true os.environ["APPBUILDER_TRACE_DEBUG"] = "true" with self.assertRaises(Exception): mock_components_run_stream_trace_01() # test_components_run_stream_trace APPBUILDER_TRACE_DEBUG = false os.environ["APPBUILDER_TRACE_DEBUG"] = "false" with self.assertRaises(Exception): mock_components_run_stream_trace_01() with self.assertRaises(TestException): mock_components_run_stream_trace_02() os.environ["APPBUILDER_SDK_TRACE_ENABLE"] = "false" with self.assertRaises(Exception): mock_components_run_stream_trace_02() def test_list_trace(self): # test_list_trace APPBUILDER_TRACE_DEBUG = true os.environ["APPBUILDER_TRACE_DEBUG"] = "true" with self.assertRaises(Exception): mock_list_trace_01() # test_list_trace APPBUILDER_TRACE_DEBUG = false os.environ["APPBUILDER_TRACE_DEBUG"] = "false" with self.assertRaises(Exception): mock_list_trace_01() with self.assertRaises(TestException): mock_list_trace_02() os.environ["APPBUILDER_SDK_TRACE_ENABLE"] = "false" with self.assertRaises(Exception): mock_list_trace_02() if __name__ == '__main__': unittest.main() ================================================ FILE: python/tests/test_translate.py ================================================ import unittest import appbuilder from appbuilder.core._exception import InvalidRequestArgumentError import os @unittest.skipUnless(os.getenv("TEST_CASE", "UNKNOWN") == "CPU_PARALLEL", "") class TestTranslationComponent(unittest.TestCase): def setUp(self): self.translation = appbuilder.Translation() def test_run_valid_request(self): """测试 run 方法对有效请求的处理。""" msg = appbuilder.Message(content="你好") result = self.translation(msg) self.assertEqual(result.content['from_lang'], 'zh') self.assertEqual(result.content['to_lang'], 'en') def test_run_invalid_request(self): """测试 run 方法对无效请求的处理。""" msg = appbuilder.Message(content="") with self.assertRaises(ValueError): _ = self.translation(msg) def test_tool_eval_valid(self): """测试 tool 方法对有效请求的处理。""" result = self.translation.tool_eval(name="translation", streaming=True, q="你好\n中国", to_lang="en") res = [item for item in result] self.assertNotEqual(len(res), 0) def test_tool_eval_invalid(self): """测试 tool 方法对无效请求的处理。""" with self.assertRaises(InvalidRequestArgumentError): result = self.translation.tool_eval(name="translation", streaming=True, to_lang="en") next(result) if __name__ == '__main__': unittest.main() ================================================ FILE: python/tests/test_treemind.py ================================================ # Copyright (c) 2024 Baidu, Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import os import unittest from appbuilder.core.message import Message from appbuilder import TreeMind @unittest.skip("测试API超限,暂时跳过") class TestTreeMindComponent(unittest.TestCase): def setUp(self): """ 初始化测试用例,设置环境变量和网关URL。 如果没有设置CAR_EXPERT_TOKEN环境变量,则使用空字符串。 Args: None. Returns: None. """ self.tm = TreeMind() self.query = "生成一份年度总结的思维导图" def test_treemind_component_tool_eval(self): """测试tool_eval方法的返回值是否正确 """ import time time.sleep(1) result = self.tm.tool_eval(query=self.query) self.assertIsNotNone(result) for r in result: print(r) self.assertIsNotNone(r) self.assertIn(r["type"],["text", "urls"]) def test_treemind_component_run(self): """测试run函数的返回值是否正确 """ msg = Message(content=self.query) result = self.tm.run(msg) print(result) self.assertIsNotNone(result) self.assertIsInstance(result, Message) def test_run_with_invalid_input(self): """测试run函数在传入无效输入的情况下的行为。 """ message = Message(content={}) with self.assertRaises(ValueError): self.tm.run(message) def test_tool_eval_invalid(self): """测试 tool 方法传入无效输入的情况下的行为""" with self.assertRaises(TypeError): result = self.tm.tool_eval(name="treemind", streaming=True, origin_query="") next(result) if __name__ == '__main__': unittest.main() ================================================ FILE: python/tests/test_tts.py ================================================ # Copyright (c) 2023 Baidu, Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import unittest import appbuilder from appbuilder.core._exception import InvalidRequestArgumentError import os @unittest.skip("测试API超限,暂时跳过") class TestTTS(unittest.TestCase): def setUp(self): self.tts = appbuilder.TTS() self.text_message = appbuilder.Message(content={"text": """随着科技的迅速发展"""}) def test_model_validation(self): with self.assertRaises(InvalidRequestArgumentError): self.tts.run(self.text_message, model="invalid_model") def test_text_validation(self): empty_message = appbuilder.Message(content={}) with self.assertRaises(BaseException): self.tts.run(empty_message) def test_audio_type_validation_baidu_tts(self): with self.assertRaises(InvalidRequestArgumentError): self.tts.run(self.text_message, model="baidu-tts", audio_type="flac") def test_audio_type_validation_paddlespeech_tts(self): with self.assertRaises(InvalidRequestArgumentError): self.tts.run(self.text_message, model="paddlespeech-tts", audio_type="mp3") def test_run_baidu_tts(self): out = self.tts.run(self.text_message, model="baidu-tts", audio_type="wav") self.assertTrue("audio_binary" in out.content and "audio_type" in out.content) def test_run_paddlespeech_tts(self): out = self.tts.run(self.text_message, model="paddlespeech-tts", audio_type="wav") self.assertTrue("audio_binary" in out.content and "audio_type" in out.content) def test_run_paddlespeech_tts_stream(self): out = self.tts.run(self.text_message, model="paddlespeech-tts", audio_type="pcm", stream=True) for o in out: self.assertIsNotNone(o) def test_run_error_model_tts_stream(self): with self.assertRaises(InvalidRequestArgumentError): self.tts.run(self.text_message, model="baidu-tts", audio_type="pcm", stream=True) def test_run_paddlespeech_validation_tts_stream(self): with self.assertRaises(InvalidRequestArgumentError): self.tts.run(self.text_message, model="paddlespeech-tts", audio_type="mp3", stream=True) def test_run_raise_text_field_empty(self): message=appbuilder.Message(content={"text": ""}) with self.assertRaises(InvalidRequestArgumentError): self.tts.run(message) if __name__ == "__main__": unittest.main() ================================================ FILE: python/tests/test_utils.py ================================================ # Copyright (c) 2024 Baidu, Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import os import unittest import asyncio from unittest.mock import MagicMock from appbuilder.utils.sse_util import SSEClient,AsyncSSEClient, Event from appbuilder.utils.model_util import RemoteModel,Models from appbuilder.utils.logger_util import LoggerWithLoggerId,_setup_logging,logger from threading import current_thread # 创建一个logger类 class test_logger_level(): def __init__(self): self.level='level' @unittest.skipUnless(os.getenv("TEST_CASE", "UNKNOWN") == "CPU_PARALLEL", "") class TestUtils(unittest.TestCase): def test_sse_util_SSEClient(self): mock_event_source = MagicMock() mock_event_source.__iter__.return_value = iter([ b'data: Test event 1\n\n', b'data: Last incomplete event' ]) sse_client = SSEClient(event_source=mock_event_source) event_generator = sse_client._read() self.assertEqual(next(event_generator), b'data: Test event 1\n\n') self.assertEqual(next(event_generator), b'data: Last incomplete event') # 测试是否抛出 StopIteration 异常,表示没有更多事件 with self.assertRaises(StopIteration): next(event_generator) # test_events mock_event_source.__iter__.return_value = iter([ b': Test event 1\n\n', b'test: Test event 2\n\n', b'data:Testevent3\n\n', b'data\n\n', b'event:Testevent5\n\n', ]) sse_client = SSEClient(event_source=mock_event_source) for event in sse_client.events(): pass # test_close sse_client.close() def test_sse_util_AsyncSSEClient(self): async def mock_client(): mock_event_source = MagicMock() mock_event_source.__iter__.return_value = iter([ b'data: Test event 1\n\n', b'data: Last incomplete event' ]) sse_client = AsyncSSEClient(mock_event_source) event_generator = sse_client._read() async for data in event_generator: pass # test_events mock_event_source.__aiter__.return_value = iter([ b': Test event 1\n\n', b'test: Test event 2\n\n', b'data:Testevent3\n\n', b'data\n\n', b'event:Testevent5\n\n', ]) sse_client = AsyncSSEClient(mock_event_source) async for event in sse_client.events(): pass loop = asyncio.get_event_loop() loop.run_until_complete(mock_client()) def test_sse_util_SSEClient_DEBUG(self): logger.setLoglevel("DEBUG") mock_event_source = MagicMock() mock_event_source.__iter__.return_value = iter( [b"data: Test event 1\n\n", b"data: Last incomplete event"] ) sse_client = SSEClient(event_source=mock_event_source) event_generator = sse_client._read() self.assertEqual(next(event_generator), b"data: Test event 1\n\n") self.assertEqual(next(event_generator), b"data: Last incomplete event") # 测试是否抛出 StopIteration 异常,表示没有更多事件 with self.assertRaises(StopIteration): next(event_generator) # test_events mock_event_source.__iter__.return_value = iter( [ b": Test event 1\n\n", b"test: Test event 2\n\n", b"data:Testevent3\n\n", b"data\n\n", b"event:Testevent5\n\n", ] ) sse_client = SSEClient(event_source=mock_event_source) for event in sse_client.events(): pass # test_close sse_client.close() def test_sse_util_Event(self): # test_str_ event_str=str(Event(id='id',retry=10)) assert event_str.startswith('message') def test_model_util_RemoteModel(self): # test_get_remote_name_by_short_name rm=RemoteModel(remote_name='test_remote') rm.get_remote_name_by_short_name(short_name="eb-turbo-appbuilder") def test_model_util_Models(self): # test_list models=Models() models.list(retry=-1) if __name__ == '__main__': unittest.main() ================================================ FILE: python/tests/test_utils_collector.py ================================================ # Copyright (c) 2024 Baidu, Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import os import unittest from collections import OrderedDict from appbuilder.utils.collector import Collector @unittest.skipUnless(os.getenv("TEST_CASE", "UNKNOWN") == "CPU_PARALLEL", "") class TestCollector(unittest.TestCase): def test_del_collection(self): collector = Collector() # test del_collection with not name collector.del_collection("test") # test del_collection with name collector.add_to_collection("test", 1) collector.del_collection("test") def test_other_collection(self): collector = Collector() # test if collection is None and index_key is None result=collector.get_collection("test") self.assertEqual(result, []) # test if index_key is not None collector.add_to_collection("test", 1,'test-key') result=collector.get_collection(name="test", index_key='test-key') self.assertEqual(result, 1) # test if index_key is None and collection is not None collector.add_to_collection("test01", 1) result=collector.get_collection(name="test01", index_key='test-key') self.assertEqual(result,None) # get_collection_as_dict result=collector.get_collection_as_dict("test") self.assertEqual(type(result), OrderedDict) result=collector.get_collection_as_dict("test", reverse=True) self.assertEqual(type(result), OrderedDict) result=collector.get_collection_as_dict("test02") self.assertEqual(type(result), OrderedDict) # get_all_collection_keys collector.get_all_collection_keys() # test clear_collection 清空collection collector.clear_collection("test") collector.clear_collection("test01") if __name__ == "__main__": unittest.main() ================================================ FILE: python/tests/test_utils_logger.py ================================================ # Copyright (c) 2024 Baidu, Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import os import logging import unittest from appbuilder.utils.logger_util import LoggerWithLoggerId,_setup_logging from threading import current_thread # 创建一个logger类 class test_logger_level(): def __init__(self): self.level='level' @unittest.skipUnless(os.getenv("TEST_CASE", "UNKNOWN") == "CPU_PARALLEL", "") class TestUtilsLogger(unittest.TestCase): def test_logger_util_LoggerWithLoggerId(self): # test_get_logid lwl=LoggerWithLoggerId(logger='test_logger',extra={'logid':'test_logid'},loglevel='INFO') self.assertEqual(lwl.get_logid(),None) lwl.logid_dict[current_thread().ident]='ident' self.assertEqual(lwl.get_logid(),'ident') # test_process kwargs={ 'extra':{'logid':'test_logid'} } msg,kwargs=lwl.process(msg='test_msg',kwargs=kwargs) self.assertEqual(kwargs['extra']['logid'],lwl.logid_dict[current_thread().ident]) msg,kwargs=lwl.process(msg='test_msg',kwargs={}) self.assertEqual(kwargs['extra']['logid'],lwl.logid_dict[current_thread().ident]) # test_level test_logger=test_logger_level() lwl.logger=test_logger self.assertEqual(lwl.level,'level') def test_setup_logging(self): # test_setup_logging os.environ["APPBUILDER_LOGFILE"] = "/tmp/appbuilder.log" _setup_logging() os.environ["APPBUILDER_LOGLEVEL"]="test" with self.assertRaises(ValueError): _setup_logging() def test_set_filename_and_loglevel(self): # test_set_filename lwl=LoggerWithLoggerId(logger='test_logger',extra={'logid':'test_logid'},loglevel='INFO') lwl.setLoglevel("debug") lwl.setFilename("/tmp/appbuilder.log") with self.assertRaises(ValueError): lwl.setLoglevel("test") if __name__ == '__main__': unittest.main() ================================================ FILE: python/tests/test_utils_logging_util.py ================================================ # Copyright (c) 2023 Baidu, Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import unittest import os from appbuilder.utils.logger_util import LoggerWithLoggerId,LOGGING_CONFIG @unittest.skipUnless(os.getenv("TEST_CASE", "UNKNOWN") == "CPU_PARALLEL", "") class TestTestUtilsLoggingUtil(unittest.TestCase): def setUp(self): self.logger = LoggerWithLoggerId(LOGGING_CONFIG["loggers"]["appbuilder"], {}, 'DEBUG') def test_set_auto_logid(self): self.logger.set_auto_logid() def test_set_logid(self): self.logger.set_logid('test') def test_get_logid(self): self.logger.set_auto_logid() # def test_level(self): # level=self.logger.level() def test_process(self): msg,kwargs=self.logger.process(msg='test',kwargs={}) msg,kwargs=self.logger.process(msg='test',kwargs={'extra':{'logid':'test'}}) if __name__ == '__main__': unittest.main() ================================================ FILE: python/tests/test_v2_animal_recognize.py ================================================ # Copyright (c) 2023 Baidu, Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import unittest import requests import appbuilder from appbuilder.core.components.v2 import AnimalRecognition import os @unittest.skipUnless(os.getenv("TEST_CASE", "UNKNOWN") == "CPU_PARALLEL", "") class TestAnimalRecognition(unittest.TestCase): def setUp(self): """ 设置环境变量。 """ self.animal_recognition = AnimalRecognition() def test_run_with_raw_image(self): """ 使用原始图片进行单测 Args: None Returns: None """ image_url = "https://bj.bcebos.com/v1/appbuilder/animal_recognize_test.png?" \ "authorization=bce-auth-v1%2FALTAKGa8m4qCUasgoljdEDAzLm%2F2024-01-24T" \ "12%3A19%3A16Z%2F-1%2Fhost%2F411bad53034fa8f9c6edbe5c4909d76ecf6fad68" \ "62cf937c03f8c5260d51c6ae" raw_image = requests.get(image_url).content # Create message with raw_image message = appbuilder.Message(content={"raw_image": raw_image}) # Recognize animal output = self.animal_recognition.run(message) # Assert output is not None self.assertIsNotNone(output) self.assertIsInstance(output, appbuilder.Message) self.assertIsInstance(output.content["result"], list) self.assertIsInstance(output.content["result"][0]["name"], str) def test_run_with_url(self): """ 使用图片 URL 进行单测 Args: None Returns: None """ image_url = "https://bj.bcebos.com/v1/appbuilder/animal_recognize_test.png?" \ "authorization=bce-auth-v1%2FALTAKGa8m4qCUasgoljdEDAzLm%2F2024-01-24T" \ "12%3A19%3A16Z%2F-1%2Fhost%2F411bad53034fa8f9c6edbe5c4909d76ecf6fad68" \ "62cf937c03f8c5260d51c6ae" # Create message with image URL message = appbuilder.Message(content={"url": image_url}) # Recognize animal output = self.animal_recognition.run(message) # Assert output is not None self.assertIsNotNone(output) self.assertIsInstance(output, appbuilder.Message) def test_run_with_timeout_and_retry(self): """ 测试run方法,timeout、retry参数 Args: None Returns: None """ image_url = "https://bj.bcebos.com/v1/appbuilder/animal_recognize_test.png?" \ "authorization=bce-auth-v1%2FALTAKGa8m4qCUasgoljdEDAzLm%2F2024-01-24T" \ "12%3A19%3A16Z%2F-1%2Fhost%2F411bad53034fa8f9c6edbe5c4909d76ecf6fad68" \ "62cf937c03f8c5260d51c6ae" raw_image = requests.get(image_url).content # Create message with raw_image message = appbuilder.Message(content={"url": image_url, "raw_image": raw_image}) # Recognize animal with timeout and retry parameters output = self.animal_recognition.run(message, timeout=5.0, retry=3) # Assert output is not None self.assertIsNotNone(output) def test_run_with_invalid_input(self): """ 测试run函数在传入无效输入的情况下的行为。 Args: None Returns: None """ # create empty message message = appbuilder.Message(content={}) # Assert ValueError is raised with self.assertRaises(ValueError): self.animal_recognition.run(message) def test_run_with_invalid_url(self): """ 测试run函数在传入无效URL的情况下的行为。 Args: None Returns: None """ url = "http://example.com/invalid_url.jpg" message = appbuilder.Message(content={"url": url}) with self.assertRaises(appbuilder.AppBuilderServerException): self.animal_recognition.run(message) def test_tool_eval_valid(self): """测试 tool 方法对有效请求的处理。""" img_url = "https://bj.bcebos.com/v1/appbuilder/animal_recognize_test.png?" \ "authorization=bce-auth-v1%2FALTAKGa8m4qCUasgoljdEDAzLm%2F2024-01-24T" \ "12%3A19%3A16Z%2F-1%2Fhost%2F411bad53034fa8f9c6edbe5c4909d76ecf6fad68" \ "62cf937c03f8c5260d51c6ae" img_name = "test_img.jpg" file_urls = {img_name: img_url} result = self.animal_recognition.tool_eval(img_name=img_name, img_url=img_url, file_urls=file_urls) res = [item for item in result] self.assertNotEqual(len(res), 0) def test_tool_eval_invalid(self): """测试 tool 方法对无效请求的处理。""" with self.assertRaises(ValueError): result = self.animal_recognition.tool_eval(name="animal_recognition", streaming=True, origin_query="") next(result) def test_tool_eval_raise_exception(self): """测试 tool 方法对异常情况的处理。""" with self.assertRaises(ValueError): result = self.animal_recognition.tool_eval() next(result) if __name__ == '__main__': unittest.main() ================================================ FILE: python/tests/test_v2_asr.py ================================================ # Copyright (c) 2024 Baidu, Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import os import unittest import requests import appbuilder from appbuilder.core.component import ComponentOutput from appbuilder.core._exception import InvalidRequestArgumentError from appbuilder.core.components.v2 import ASR from appbuilder.core.components.v2.asr.component import _convert as convert @unittest.skip("测试API超限,暂时跳过") class TestASR(unittest.TestCase): def setUp(self): self.audio_file_url = "https://bj.bcebos.com/v1/appbuilder/asr_test.pcm?authorization=bce-auth-v1" \ "%2FALTAKGa8m4qCUasgoljdEDAzLm%2F2024-01-11T10%3A56%3A41Z%2F-1%2Fhost" \ "%2Fa6c4d2ca8a3f0259f4cae8ae3fa98a9f75afde1a063eaec04847c99ab7d1e411" self.com = ASR() def test_asr_run(self): raw_audio = requests.get(self.audio_file_url).content inp = appbuilder.Message(content={"raw_audio": raw_audio}) out = self.com.run(inp) self.assertIsNotNone(out) print(out) def test_asr_tool_eval(self): result = self.com.tool_eval(file_url=self.audio_file_url) for res in result: self.assertIsInstance(res, ComponentOutput) print(res) def test_asr_tool_eval_error(self): result = self.com.tool_eval() with self.assertRaises(InvalidRequestArgumentError): next(result) result = self.com.tool_eval(file_name='test_path') with self.assertRaises(InvalidRequestArgumentError): next(result) def test_convert_with_mp3(self): file_type = ["mp3", "wav", "pcm", "m4a"] for type in file_type: with self.assertRaises(FileNotFoundError): path = os.path.join(os.path.dirname(__file__), "test_audio") path += ".{}".format(type) convert(path, type) if __name__ == '__main__': unittest.main() ================================================ FILE: python/tests/test_v2_component_trace.py ================================================ # Copyright (c) 2024 Baidu, Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import os import unittest from appbuilder.core.components.v2 import StyleRewrite from appbuilder.core.component import ComponentOutput from appbuilder import AppBuilderTracer @unittest.skipUnless(os.getenv("TEST_CASE", "UNKNOWN") == "CPU_PARALLEL", "") class TestStyleRewrite(unittest.TestCase): def setUp(self) -> None: self.com = StyleRewrite(model="DeepSeek-V3.1") self.tracer = AppBuilderTracer( enable_phoenix = False, enable_console = True ) def test_non_stream_tool_eval(self): self.tracer.start_trace() text = "成都是个包容的城市" style = "直播话术" out = self.com.non_stream_tool_eval(query=text, style=style) print(out) self.assertIsInstance(out, ComponentOutput) self.tracer.end_trace() if __name__ == '__main__': unittest.main() ================================================ FILE: python/tests/test_v2_dialog_summary.py ================================================ # Copyright (c) 2023 Baidu, Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import os import unittest import appbuilder from appbuilder.core.components.v2 import DialogSummary @unittest.skipUnless(os.getenv("TEST_CASE", "UNKNOWN") == "CPU_PARALLEL", "") class TestDialogSummary(unittest.TestCase): def setUp(self): """ 设置环境变量。 Args: 无参数,默认值为空。 Returns: 无返回值,方法中执行了环境变量的赋值操作。 """ self.model_name = "DeepSeek-V3.1" self.node = DialogSummary(model=self.model_name) def test_run_with_default_params(self): """测试 run 方法使用默认参数""" dialog_text = "用户:喂我想查一下我的话费\n坐席:好的女士您话费余的话还有87.49元钱\n用户:好的知道了谢谢\n坐席:嗯不客气祝您生活愉快再见" msg = appbuilder.Message(dialog_text) summary = self.node(msg) self.assertIsNotNone(summary) def test_run_with_stream_and_temperature(self): """测试不同的 stream 和 temperature 参数值""" dialog_text = "用户:喂我想查一下我的话费\n坐席:好的女士您话费余的话还有87.49元钱\n用户:好的知道了谢谢\n坐席:嗯不客气祝您生活愉快再见" msg = appbuilder.Message(dialog_text) summary = self.node(msg, stream=False, temperature=0.5) self.assertIsNotNone(summary) def test_run_with_model_names(self): """测试不同的 stream 和 temperature 参数值""" chats = appbuilder.get_model_list(api_type_filter=["chat"]) self.assertTrue("DeepSeek-V3.1" in chats) DialogSummary(model="DeepSeek-V3.1") def test_tool_eval_valid(self): """测试 tool 方法对有效请求的处理。""" params = { 'query': '用户:喂我想查一下我的话费\n坐席:好的女士您话费余的话还有87.49元钱\n用户:好的知道了谢谢\n坐席:嗯不客气祝您生活愉快再见' } result = self.node.tool_eval(**params) res = [item for item in result] self.assertNotEqual(len(res), 0) result = self.node.tool_eval(**params) res = [item for item in result] def test_tool_eval_invalid(self): """测试 tool 方法对无效请求的处理。""" with self.assertRaises(ValueError): params = { 'query': None } result = self.node.tool_eval(**params) next(result) if __name__ == '__main__': unittest.main() ================================================ FILE: python/tests/test_v2_general_ocr.py ================================================ # Copyright (c) 2024 Baidu, Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import os import requests import base64 import unittest import appbuilder from appbuilder.core.components.v2 import GeneralOCR from appbuilder.core.component import ComponentOutput from appbuilder.core._exception import InvalidRequestArgumentError @unittest.skipUnless(os.getenv("TEST_CASE", "UNKNOWN") == "CPU_PARALLEL", "") class TestGeneralOCR(unittest.TestCase): def setUp(self) -> None: self.com = GeneralOCR() def test_run(self): img_url = "https://bj.bcebos.com/v1/appbuilder/general_ocr_test.png?" \ "authorization=bce-auth-v1%2FALTAKGa8m4qCUasgoljdEDAzLm%2F2024-01-" \ "11T10%3A59%3A17Z%2F-1%2Fhost%2F081bf7bcccbda5207c82a4de074628b04ae" \ "857a27513734d765495f89ffa5f73" raw_image = requests.get(img_url).content image_base64 = base64.b64encode(raw_image) message = appbuilder.Message(content={"image_base64": image_base64}) output = self.com.run(message) print(output) def test_tool_eval(self): img_url = "https://bj.bcebos.com/v1/appbuilder/general_ocr_test.png?" \ "authorization=bce-auth-v1%2FALTAKGa8m4qCUasgoljdEDAzLm%2F2024-01-" \ "11T10%3A59%3A17Z%2F-1%2Fhost%2F081bf7bcccbda5207c82a4de074628b04ae" \ "857a27513734d765495f89ffa5f73" img_names = ["general_ocr_test.png", "test"] img_urls = [ "https://agi-dev-platform-file.bj.bcebos.com/files_qa/10b495b5ceea44e5a1e7d194f3a59ed7/uploads/file-6cxezmhc_1.jpeg?authorization=bce-auth-v1%2FALTAKGa8m4qCUasgoljdEDAzLm%2F2025-08-04T03%3A27%3A03Z%2F259200%2Fhost%2Ff420874be9fe2511a73eab458339aad110d97c55742b14fb4fabf78cc0e1d4cc", "https://agi-dev-platform-file.bj.bcebos.com/files_qa/10b495b5ceea44e5a1e7d194f3a59ed7/uploads/file-wjka6g3h_%E5%BC%80%E6%88%B7%E8%AE%B8%E5%8F%AF%E8%AF%81.jpeg?authorization=bce-auth-v1%2FALTAKGa8m4qCUasgoljdEDAzLm%2F2025-08-04T03%3A28%3A23Z%2F259200%2Fhost%2F2e3355869d9f62143051a12c2b19bc39b33d439e18839fe6dd15d0f37ab3a999"] pdf_urls = ["https://agi-dev-platform-file.bj.bcebos.com/files_qa/10b495b5ceea44e5a1e7d194f3a59ed7/uploads/file-hf7nhtdw_8_%E8%B4%A8%E9%87%8F%E6%B5%81%E9%87%8F%E8%AE%A1-1.pdf?authorization=bce-auth-v1%2FALTAKGa8m4qCUasgoljdEDAzLm%2F2025-08-04T03%3A22%3A29Z%2F259200%2Fhost%2Fd1e301ba51cbe39fbbe10a334c5e4f75d71b40522916e25205e83404b6cea791"] result = self.com.tool_eval(img_names=img_names, img_urls=img_urls, pdf_urls=pdf_urls, _sys_file_urls={'general_ocr_test.png': img_url}) for res in result: assert isinstance(res, ComponentOutput) print(res.content) def test_error_tool_eval(self): result = self.com.tool_eval(img_url='', img_name='') with self.assertRaises(InvalidRequestArgumentError): list(result) result = self.com.tool_eval(img_url='', img_name='test.jpg') with self.assertRaises(InvalidRequestArgumentError): list(result) def test_run_pdf_base64(self): pdf_url = "https://bj.bcebos.com/agi-dev-platform-sdk-test/8、质量流量计.pdf" raw_pdf = requests.get(pdf_url).content pdf_base64 = base64.b64encode(raw_pdf) general_ocr = GeneralOCR() out = general_ocr.run(appbuilder.Message(content={"pdf_base64": pdf_base64, "pdf_file_num": "3"})) self.assertIsInstance(out, appbuilder.Message) def test_run_pdf_url(self): pdf_url = "https://bj.bcebos.com/agi-dev-platform-sdk-test/8、质量流量计.pdf" general_ocr = GeneralOCR() out = general_ocr.run(appbuilder.Message(content={"pdf_url": pdf_url, "pdf_file_num": "5"})) self.assertIsInstance(out, appbuilder.Message) def test_tool_eval_pdf_url(self): pdf_url = "https://bj.bcebos.com/agi-dev-platform-sdk-test/8、质量流量计.pdf" result = self.com.tool_eval(pdf_urls=[pdf_url]) for iter in result: self.assertIsInstance(iter, ComponentOutput) def test_tool_eval_none_input(self): result = self.com.tool_eval(pdf_name="test.pdf") with self.assertRaises(InvalidRequestArgumentError): list(result) def test_rotated_image(self): image_url = "https://bj.bcebos.com/agi-dev-platform-sdk-test/8、质量流量计-1_rotated_page-0001.jpg" out = self.com.run(appbuilder.Message(content={ "image_url": image_url, "detect_direction": "true", "multidirectional_recognize": "false"} )) self.assertIsInstance(out, appbuilder.Message) if __name__ == "__main__": unittest.main() ================================================ FILE: python/tests/test_v2_hallucination_detection.py ================================================ # Copyright (c) 2023 Baidu, Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import os import unittest import appbuilder from appbuilder.core._exception import AppBuilderServerException from appbuilder.core.components.v2 import HallucinationDetection TEST_QUERY = '澳门新麻蒲烤肉店每天开门吗?' TEST_CONTEXT = \ ('澳门美食: 澳门新麻蒲韩国烤肉店\n' '在澳门一年四季之中除了火锅,烤肉也相当受欢迎。提到韩烧,有一间令我印象最深刻,就是号称韩国第一的烤肉店-新麻蒲韩国烤肉店,光是韩国的分店便多' '达四百多间,海外分店更是遍布世界各地,2016年便落户澳门筷子基区,在原本已经食肆林立的地方一起百花齐放!店内的装修跟韩国分店还完度几乎没差,让' '食客彷如置身于韩国的感觉,还要大赞其抽风系统不俗,离开时身上都不会沾上烤肉味耶!\n' '时间:周一至周日 下午5:00 - 上午3:00\n' '电话:+853 2823 4012\n' '地址:澳门筷子基船澳街海擎天第三座地下O号铺96号\n' '必食推介:\n' '护心肉二人套餐\n' '来新麻蒲必试的有两样东西,现在差不多每间烤肉店都有炉边烤蛋,但大家知道吗?原来新麻蒲就是炉边烤蛋的开创者,既然是始祖,这已经是个非吃不可的理' '由!还有一款必试的就是护心肉,即是猪的横隔膜与肝中间的部分,每头猪也只有200克这种肉,非常珍贵,其味道吃起来有种独特的肉香味,跟牛护心肉一样' '精彩!\n' '秘制猪皮\n' '很多怕胖的女生看到猪皮就怕怕,但其实猪皮含有大量胶原蛋白,营养价值很高呢!这里红通通的猪皮还经过韩国秘制酱汁处理过,会有一点点辣味。烤猪皮的' '时候也需特别注意火侯,这样吃起来才会有外脆内Q的口感!') TEST_ANSWER = '澳门新麻蒲烤肉店并不是每天开门,周日休息。' class TestHallucinationDetectionComponent(unittest.TestCase): def setUp(self): """ 设置环境变量。 Args: 无参数,默认值为空。 Returns: 无返回值,方法中执行了环境变量的赋值操作。 """ self.hallucination_detection = HallucinationDetection(model="DeepSeek-V3.1") def test_run_with_default_params(self): """测试 run 方法使用默认参数 """ query = TEST_QUERY context = TEST_CONTEXT answer = TEST_ANSWER msg = appbuilder.Message({'query': query, 'context': context, 'answer': answer}) answer = self.hallucination_detection(msg) # print(answer) self.assertIsNotNone(answer) print(f'\n[result]\n{answer.content}\n') def test_run_with_stream_and_temperature(self): """测试不同的 stream 和 temperature 参数值 """ query = TEST_QUERY context = TEST_CONTEXT answer = TEST_ANSWER msg = appbuilder.Message({'query': query, 'context': context, 'answer': answer}) answer = self.hallucination_detection(msg, stream=False, temperature=0.5) # print(answer) self.assertIsNotNone(answer) print(f'\n[result]\n{answer.content}\n') def test_tool_eval_with_default_params(self): """测试 tool_eval 方法使用默认参数 """ query = TEST_QUERY context = TEST_CONTEXT answer = TEST_ANSWER answer = self.hallucination_detection.tool_eval(query=query, context=context, answer=answer) print(answer) self.assertIsNotNone(answer) print(f'\n[result]\n{answer}\n') def test_tool_eval_with_model_configs(self): """测试 tool_eval 方法使用不同temperature和top_p参数值。 """ query = TEST_QUERY context = TEST_CONTEXT answer = TEST_ANSWER model_configs = {'temperature': 0.5, 'top_p': 0.5} answer = self.hallucination_detection.tool_eval(query=query, context=context, answer=answer, model_configs=model_configs) print(answer) self.assertIsNotNone(answer) print(f'\n[result]\n') for ans in answer: print(ans) def test_tool_eval_with_default_params(self): """测试 tool_eval 方法使用默认参数 """ query = TEST_QUERY context = TEST_CONTEXT answer = TEST_ANSWER answer = self.hallucination_detection.tool_eval(query=query, context=context, answer=answer) print(answer) self.assertIsNotNone(answer) print(f'\n[result]\n{answer}\n') def test_tool_eval_with_model_configs(self): """测试 tool_eval 方法使用不同temperature和top_p参数值。 """ query = TEST_QUERY context = TEST_CONTEXT answer = TEST_ANSWER model_configs = {'temperature': 0.5, 'top_p': 0.5} answer = self.hallucination_detection.tool_eval(query=query, context=context, answer=answer, model_configs=model_configs) # print(answer) self.assertIsNotNone(answer) print(f'\n[result]\n') for ans in answer: print(ans) if __name__ == '__main__': unittest.main() ================================================ FILE: python/tests/test_v2_handwrite_ocr.py ================================================ # Copyright (c) 2023 Baidu, Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import os import unittest import requests import appbuilder from appbuilder.core.message import Message from appbuilder.core._exception import InvalidRequestArgumentError from appbuilder.core.components.v2 import HandwriteOCR class TestHandWriteOCR(unittest.TestCase): def setUp(self): """ 设置环境变量 Args: None. Returns: None. """ # 从BOS存储读取样例文件 self.image_url=("https://bj.bcebos.com/v1/appbuilder/test_handw" "rite_ocr.jpg?authorization=bce-auth-v1%2FALTAKGa8" "m4qCUasgoljdEDAzLm%2F2024-01-23T11%3A58%3A09Z%2F-1%2Fhost%2" "F677f93445fb65157bee11cd492ce213d5c56e7a41827e45ce7e32b083d195c8b") self.raw_image = requests.get(self.image_url).content self.handwrite_ocr = HandwriteOCR() def test_run_with_image_url(self): """ 使用图片url进行单测 Args: None Returns: None """ # Create message with raw_image inp = Message(content={"url": self.image_url}) msg = self.handwrite_ocr.run(inp) self.assertIsNotNone(msg.content) def test_run_with_raw_image(self): """ 使用原始图片进行单测 Args: None Returns: None """ # Create message with raw_image inp = Message(content={"raw_image": self.raw_image}) msg = self.handwrite_ocr.run(inp) self.assertIsNotNone(msg.content) def test_tool_eval(self): result=self.handwrite_ocr.tool_eval( file_names=['test.jpg', "test_2"], file_urls = ["https://bj.bcebos.com/v1/appbuilder/test_image_understand.jpeg?authorization=bce-auth-v1%2FALTAKGa8m4qCUasgoljdEDAzLm%2F2024-01-24T09%3A41%3A01Z%2F-1%2Fhost%2Fe8665506e30e0edaec4f1cc84a2507c4cb3fdb9b769de3a5bfe25c372b7e56e6"], _sys_file_urls={'test.jpg':self.image_url} ) res=next(result) print(res) self.assertEqual(res.content[-1].visible_scope,'llm') res=next(result) self.assertEqual(res.content[-1].visible_scope,'user') if __name__ == '__main__': unittest.main() ================================================ FILE: python/tests/test_v2_image_understand.py ================================================ # Copyright (c) 2023 Baidu, Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import os import unittest import requests import appbuilder import time from appbuilder.core.message import Message from appbuilder.core._exception import NoFileUploadedExecption, InvalidRequestArgumentError from appbuilder.core.components.v2 import ImageUnderstand @unittest.skipUnless(os.getenv("TEST_CASE", "UNKNOWN") == "CPU_PARALLEL", "") class TestImageUnderstand(unittest.TestCase): def setUp(self): """ 设置环境变量 Args: None. Returns: None. """ # 从BOS存储读取样例文件 self.image_url = "https://bj.bcebos.com/v1/appbuilder/test_image_understand.jpeg?authorization=bce-auth-v1%2FALTAKGa8m4qCUasgoljdEDAzLm%2F2024-01-24T09%3A41%3A01Z%2F-1%2Fhost%2Fe8665506e30e0edaec4f1cc84a2507c4cb3fdb9b769de3a5bfe25c372b7e56e6" self.raw_image = requests.get(self.image_url).content self.image_understand = ImageUnderstand() # 输入参数为一张图片 def test_run_with_image_url(self): """ 使用图片url进行单测 Args: None Returns: None """ # Create message with raw_image inp = Message(content={"url": self.image_url, "question": "图像内容是什么?"}) msg = self.image_understand.run(inp) self.assertIsNotNone(msg.content) self.assertIsInstance(msg, Message) self.assertIsInstance(msg.content["description"], str) time.sleep(1) def test_run_with_raw_image(self): """ 使用原始图片进行单测 Args: None Returns: None """ # Create message with raw_image inp = Message(content={"raw_image": self.raw_image, "question": "图像内容是什么?"}) msg = self.image_understand.run(inp) self.assertIsNotNone(msg.content) self.assertIsInstance(msg, Message) self.assertIsInstance(msg.content["description"], str) time.sleep(1) def test_tool_eval_valid(self): """测试 tool 方法对有效请求的处理。""" img_urls = ["https://bj.bcebos.com/v1/appbuilder/animal_recognize_test.png?" \ "authorization=bce-auth-v1%2FALTAKGa8m4qCUasgoljdEDAzLm%2F2024-01-24T" \ "12%3A19%3A16Z%2F-1%2Fhost%2F411bad53034fa8f9c6edbe5c4909d76ecf6fad68" \ "62cf937c03f8c5260d51c6ae", "https://agi-dev-platform-file.bj.bcebos.com/files_qa/10b495b5ceea44e5a1e7d194f3a59ed7/uploads/file-6cxezmhc_1.jpeg?authorization=bce-auth-v1%2FALTAKGa8m4qCUasgoljdEDAzLm%2F2025-08-04T03%3A27%3A03Z%2F259200%2Fhost%2Ff420874be9fe2511a73eab458339aad110d97c55742b14fb4fabf78cc0e1d4cc"] img_name = "test_img.jpg" _sys_file_urls = {"开户许可证.jpeg": "https://agi-dev-platform-file.bj.bcebos.com/files_qa/10b495b5ceea44e5a1e7d194f3a59ed7/uploads/file-wjka6g3h_%E5%BC%80%E6%88%B7%E8%AE%B8%E5%8F%AF%E8%AF%81.jpeg?authorization=bce-auth-v1%2FALTAKGa8m4qCUasgoljdEDAzLm%2F2025-08-04T03%3A28%3A23Z%2F259200%2Fhost%2F2e3355869d9f62143051a12c2b19bc39b33d439e18839fe6dd15d0f37ab3a999"} result = self.image_understand.tool_eval(img_names=[img_name, "hh"], img_urls=img_urls, _sys_file_urls=_sys_file_urls) # for item in result: # print(item) res = [item for item in result] print(res) self.assertNotEqual(len(res), 0) time.sleep(1) def test_tool_eval_invalid(self): """测试 tool 方法对无效请求的处理。""" with self.assertRaises(InvalidRequestArgumentError): result = self.image_understand.tool_eval(name="image_understand", streaming=True, origin_query="") next(result) time.sleep(1) def test_run_language_en(self): """测试 tool 方法对无效请求的处理。""" inp = Message(content={"raw_image": self.raw_image, "question": "图像内容是什么?", "language": "en"}) self.image_understand.run(inp) time.sleep(1) def test_run_raise(self): # question is empty with self.assertRaises(ValueError): inp = Message(content={"raw_image": self.raw_image, "question": ""}) self.image_understand.run(inp) # question length bigger than 100 with self.assertRaises(ValueError): question="test"*26 inp = Message(content={"raw_image": self.raw_image, "question": question, "language": ""}) self.image_understand.run(inp) if __name__ == "__main__": unittest.main() ================================================ FILE: python/tests/test_v2_is_complex_query.py ================================================ # Copyright (c) 2023 Baidu, Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import unittest import os import appbuilder from appbuilder.core.components.v2 import IsComplexQuery @unittest.skipUnless(os.getenv("TEST_CASE", "UNKNOWN") == "CPU_PARALLEL", "") class TestIsComplexQueryComponent(unittest.TestCase): def setUp(self): """ 设置环境变量。 Args: 无参数,默认值为空。 Returns: 无返回值,方法中执行了环境变量的赋值操作。 """ self.model_name = "DeepSeek-V3.1" self.node = IsComplexQuery(model=self.model_name) def test_run_with_default_params(self): """测试 run 方法使用默认参数""" query = "吸塑包装盒在工业化生产和物流运输中分别有什么重要性?" msg = appbuilder.Message(query) answer = self.node(msg) self.assertIsNotNone(answer) # def test_run_with_custom_params(self): # """测试 run 方法使用自定义参数""" # query = "吸塑包装盒在工业化生产和物流运输中分别有什么重要性?" # msg = appbuilder.Message(query) # answer = self.node(msg, stream=True, temperature=0.5) # self.assertIsNotNone(answer) # # 检查 answer 是否符合预期 def test_run_with_invalid_params(self): """测试 run 方法使用无效参数""" query = "吸塑包装盒在工业化生产和物流运输中分别有什么重要性?" msg = appbuilder.Message(query) with self.assertRaises((ValueError, TypeError)): self.node(msg, invalid_param="invalid") def test_tool_eval_valid(self): """测试 tool 方法对有效请求的处理。""" result = self.node.tool_eval(query='吸塑包装盒在工业化生产和物流运输中分别有什么重要性?') res = [item for item in result] self.assertNotEqual(len(res), 0) result = self.node.tool_eval(query='吸塑包装盒在工业化生产和物流运输中分别有什么重要性?') res = [item for item in result] def test_tool_eval_invalid(self): """测试 tool 方法对无效请求的处理。""" with self.assertRaises(ValueError): result = self.node.tool_eval(query=None) next(result) if __name__ == '__main__': unittest.main() ================================================ FILE: python/tests/test_v2_mix_card_ocr.py ================================================ # Copyright (c) 2023 Baidu, Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import os import unittest import requests import appbuilder from appbuilder.core.message import Message from appbuilder.core._exception import InvalidRequestArgumentError from appbuilder.core.components.v2.mix_card_ocr.model import MixCardOCRRequest from appbuilder.core.components.v2.mix_card_ocr.component import MixCardOCR class TestMixCardOCR(unittest.TestCase): def setUp(self): """ 设置环境变量 Args: None. Returns: None. """ # 从BOS存储读取样例文件 self.image_url=("https://bj.bcebos.com/v1/appbuilder/test_mix_card_ocr.jpeg?" "authorization=bce-auth-v1%2FALTAKGa8m4qCUasgoljdEDAzLm%2F2024-01-24T06" "%3A18%3A11Z%2F-1%2Fhost%2F695b8041c1ded194b9e80dbe" "1865e4393da5a3515e90d72d81ef18296bd29598") self.raw_image = requests.get(self.image_url).content self.mix_card_ocr = MixCardOCR() # 输入参数为一张图片 def test_run_with_image_url(self): """ 使用图片url进行单测 Args: None Returns: None """ # Create message with raw_image inp = Message(content={"url": self.image_url}) msg = self.mix_card_ocr.run(inp) self.assertIsNotNone(msg.content) def test_run_with_raw_image(self): """ 使用原始图片进行单测 Args: None Returns: None """ # Create message with raw_image inp = Message(content={"raw_image": self.raw_image}) msg = self.mix_card_ocr.run(inp) self.assertIsNotNone(msg.content) def test_tool_eval(self): result=self.mix_card_ocr.tool_eval(file_names=['test']) with self.assertRaises(InvalidRequestArgumentError): next(result) result=self.mix_card_ocr.tool_eval( file_names=['test'], _sys_file_urls={'test':self.image_url} ) res=next(result) print("res: {}".format(res)) self.assertEqual(res.content[-1].visible_scope,'llm') res=next(result) self.assertEqual(res.content[-1].visible_scope,'user') def test_recognize_raise(self): mco=appbuilder.MixCardOCR() with self.assertRaises(ValueError): mcor=MixCardOCRRequest() mco._recognize(request=mcor) if __name__ == '__main__': unittest.main() ================================================ FILE: python/tests/test_v2_mrc.py ================================================ # Copyright (c) 2023 Baidu, Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import os import unittest import appbuilder import time from appbuilder.core.components.v2 import MRC @unittest.skipUnless(os.getenv("TEST_CASE", "UNKNOWN") == "CPU_PARALLEL", "") class TestMRC(unittest.TestCase): def setUp(self): ''' return mrc class ''' # 设置环境变量和初始化TestMRCComponent实例 self.model_name = "DeepSeek-V3.1" self.mrc = MRC(model=self.model_name) def test_mrc_with_custom_context_list(self): """测试run方法使用自定义格式context_out_list""" msg = "残疾人怎么办相关证件" msg = appbuilder.Message(msg) context_list = appbuilder.Message(["""如何办理残疾人通行证一、残疾人通行证办理条件: 1、持有中华人民共和国残疾人证,下肢残疾或者听力残疾; 2、持有准驾车型为C1(听力残疾)、C2(左下肢残疾、听力残疾)、C5(右下肢、双下肢残疾)的机动车驾驶证, 听力残疾人驾驶证须有“驾驶机动车应佩戴助听设备”的批注(批注请到各车管分所办理);""", """3、本人拥有本市登记核发的非营运小型载客汽车,车辆须在检验有效期内,并有有效交强险凭证, C5车辆加装操纵辅助装置后已办理变更手续。二、办理地点:北京市朝阳区左家庄北里35号: 北京市无障碍环境建设促进中心(北京市残疾人辅助器具资源中心),咨询电话:63547715 或68397831。三、所需材料:1、 有效的身份证明原件和复印件;2、残疾人证原件和复印件;3、驾驶证原件和复印件; 4、车辆行驶证原件和复印件;5、有效的机动车交强险凭证。"""]) answer = self.mrc(msg, context_list) self.assertIsNotNone(answer) time.sleep(1) def test_mrc_with_invalid_context(self): """测试run方法使用无效格式的context_list""" msg = "残疾人怎么办相关证件" msg = appbuilder.Message(msg) context_list = appbuilder.Message("无效样式") self.mrc(msg, context_list) time.sleep(1) def test_mrc_with_reject(self): """测试拒答功能开启情况""" # 测试阅读理解问答 msg = "残疾人怎么办相关证件" msg = appbuilder.Message(msg) context_list = appbuilder.Message(["""如何办理残疾人通行证一、残疾人通行证办理条件: 1、持有中华人民共和国残疾人证,下肢残疾或者听力残疾; 2、持有准驾车型为C1(听力残疾)、C2(左下肢残疾、听力残疾)、C5(右下肢、双下肢残疾)的机动车驾驶证, 听力残疾人驾驶证须有“驾驶机动车应佩戴助听设备”的批注(批注请到各车管分所办理);""", """3、本人拥有本市登记核发的非营运小型载客汽车,车辆须在检验有效期内,并有有效交强险凭证, C5车辆加装操纵辅助装置后已办理变更手续。二、办理地点:北京市朝阳区左家庄北里35号: 北京市无障碍环境建设促进中心(北京市残疾人辅助器具资源中心),咨询电话:63547715 或68397831。三、所需材料:1、 有效的身份证明原件和复印件;2、残疾人证原件和复印件;3、驾驶证原件和复印件; 4、车辆行驶证原件和复印件;5、有效的机动车交强险凭证。"""]) answer = self.mrc(msg, context_list, reject=True, clarify=True, highlight=True, friendly=True, cite=True) print(answer) def test_tool_eval_valid(self): """测试 tool 方法对有效请求的处理。""" context_list = ["""如何办理残疾人通行证一、残疾人通行证办理条件: 1、持有中华人民共和国残疾人证,下肢残疾或者听力残疾; 2、持有准驾车型为C1(听力残疾)、C2(左下肢残疾、听力残疾)、C5(右下肢、双下肢残疾)的机动车驾驶证, 听力残疾人驾驶证须有“驾驶机动车应佩戴助听设备”的批注(批注请到各车管分所办理);""", """3、本人拥有本市登记核发的非营运小型载客汽车,车辆须在检验有效期内,并有有效交强险凭证, C5车辆加装操纵辅助装置后已办理变更手续。二、办理地点:北京市朝阳区左家庄北里35号: 北京市无障碍环境建设促进中心(北京市残疾人辅助器具资源中心),咨询电话:63547715 或68397831。三、所需材料:1、 有效的身份证明原件和复印件;2、残疾人证原件和复印件;3、驾驶证原件和复印件; 4、车辆行驶证原件和复印件;5、有效的机动车交强险凭证。"""] params = { 'query': '残疾人怎么办相关证件', 'context_list': context_list } result = self.mrc.tool_eval(**params) res = [item for item in result] self.assertNotEqual(len(res), 0) result = self.mrc.tool_eval(**params) res = [item for item in result] def test_tool_eval_invalid(self): """测试 tool 方法对无效请求的处理。""" context_list = ["""如何办理残疾人通行证一、残疾人通行证办理条件: 1、持有中华人民共和国残疾人证,下肢残疾或者听力残疾; 2、持有准驾车型为C1(听力残疾)、C2(左下肢残疾、听力残疾)、C5(右下肢、双下肢残疾)的机动车驾驶证, 听力残疾人驾驶证须有“驾驶机动车应佩戴助听设备”的批注(批注请到各车管分所办理);""", """3、本人拥有本市登记核发的非营运小型载客汽车,车辆须在检验有效期内,并有有效交强险凭证, C5车辆加装操纵辅助装置后已办理变更手续。二、办理地点:北京市朝阳区左家庄北里35号: 北京市无障碍环境建设促进中心(北京市残疾人辅助器具资源中心),咨询电话:63547715 或68397831。三、所需材料:1、 有效的身份证明原件和复印件;2、残疾人证原件和复印件;3、驾驶证原件和复印件; 4、车辆行驶证原件和复印件;5、有效的机动车交强险凭证。"""] with self.assertRaises(ValueError): params = { 'query': '残疾人怎么办相关证件', 'context_list': None } result = self.mrc.tool_eval(**params) next(result) with self.assertRaises(ValueError): params = { 'query': None, 'context_list': context_list } result = self.mrc.tool_eval(**params) next(result) if __name__ == '__main__': unittest.main() ================================================ FILE: python/tests/test_v2_nl2pandas.py ================================================ """ Copyright (c) 2023 Baidu, Inc. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. """ import unittest import os import appbuilder from appbuilder.core.message import Message from appbuilder.core.components.v2 import Nl2pandasComponent @unittest.skipUnless(os.getenv("TEST_CASE", "UNKNOWN") == "CPU_PARALLEL", "") class TestNl2pandasComponent(unittest.TestCase): def setUp(self): """ 设置环境变量及必要数据。 """ self.model_name = "DeepSeek-V3.1" self.node = Nl2pandasComponent(model=self.model_name) self.table_info = '''表格列信息如下: 学校名 : 清华附小 , 字符串类型,代表小学学校的名称 所属地区 : 西城区 , 字符串类型,表示该小学学校所在的位置 创办时间 : 1998 , 数字值类型,表示该小学学校的创办时间 类别 : 公立小学 , 字符串类型,表示该小学学校所在的类别 学生人数 : 2000 , 数字值类型,表示该小学学校的学生数量 教职工人数 : 140 , 数字值类型,表示该小学学校的教职工数量 教学班数量 : 122 , 数字值类型,表示该小学学校的教学班数量 ''' def test_run_with_stream_and_temperature(self): """测试 stream 和 temperature 参数""" query = "海淀区有哪些学校" msg = Message(query) code = self.node(msg, table_info=self.table_info, stream=False, temperature=0.5) self.assertIsNotNone(code) def test_tool_eval_valid(self): """测试 tool 方法对有效请求的处理。""" params = { 'query': '海淀区有哪些学校', 'table_info': self.table_info } result = self.node.tool_eval(**params) res = [item for item in result] self.assertNotEqual(len(res), 0) result = self.node.tool_eval(streaming=False, **params) res = [item for item in result] def test_tool_eval_invalid(self): """测试 tool 方法对无效请求的处理。""" with self.assertRaises(ValueError): params = { 'query': '海淀区有哪些学校', 'table_info': None } result = self.node.tool_eval(**params) next(result) with self.assertRaises(ValueError): params = { 'query': None, 'table_info': self.table_info } result = self.node.tool_eval(**params) next(result) if __name__ == '__main__': unittest.main() ================================================ FILE: python/tests/test_v2_object_recognition.py ================================================ # Copyright (c) 2024 Baidu, Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import os import unittest import requests import appbuilder from appbuilder.core.component import ComponentOutput from appbuilder.core._exception import InvalidRequestArgumentError from appbuilder.core.components.v2 import ObjectRecognition from appbuilder.core._exception import AppBuilderServerException from appbuilder.core.components.object_recognize.model import ObjectRecognitionRequest @unittest.skipUnless(os.getenv("TEST_CASE", "UNKNOWN") == "CPU_PARALLEL", "") class TestObjectRecognition(unittest.TestCase): def setUp(self): self.com = ObjectRecognition() self.image_url = "https://bj.bcebos.com/v1/appbuilder/object_recognize_test.png?" \ "authorization=bce-auth-v1%2FALTAKGa8m4qCUasgoljdEDAzLm%2F2024-01-" \ "11T11%3A00%3A19Z%2F-1%2Fhost%2F2c31bf29205f61e58df661dc80af31a1dc" \ "1ba1de0a8f072bc5a87102bd32f9e3" self.func_recognize = self.com._recognize def test_run(self): raw_image = requests.get(self.image_url).content message = appbuilder.Message(content={"raw_image": raw_image, "url": self.image_url}) out = self.com.run(message) self.assertIsNotNone(out) print(out) def test_tool_eval(self): result = self.com.tool_eval(img_url=self.image_url) for res in result: self.assertIsInstance(res, ComponentOutput) print(res) def test_tool_eval_error(self): result = self.com.tool_eval(img_name='test_path') with self.assertRaises(InvalidRequestArgumentError): next(result) result = self.com.tool_eval() with self.assertRaises(InvalidRequestArgumentError): next(result) def test_recognize_error(self): with self.assertRaises(ValueError): self.func_recognize(ObjectRecognitionRequest()) with self.assertRaises(AppBuilderServerException): self.func_recognize(ObjectRecognitionRequest(url='test-url'), retry=1) if __name__ == '__main__': unittest.main() ================================================ FILE: python/tests/test_v2_oral_query_generat.py ================================================ # Copyright (c) 2024 Baidu, Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import os import unittest import appbuilder from appbuilder.core.component import ComponentOutput from appbuilder.core.components.v2 import OralQueryGeneration @unittest.skipUnless(os.getenv("TEST_CASE", "UNKNOWN") == "CPU_PARALLEL", "") class TestOralQueryGeneration(unittest.TestCase): def setUp(self): self.com = OralQueryGeneration(model="DeepSeek-V3.1") self.text = ('文档标题:在OPPO Reno5上使用视频超级防抖\n' '文档摘要:OPPO Reno5上的视频超级防抖,视频超级防抖3.0,多代视频防抖算法积累,这一代依旧超级防抖超级稳。 开启视频超级' '防抖 开启路径:打开「相机 > 视频 > 点击屏幕上方的“超级防抖”标识」 后置视频同时支持超级防抖和超级防抖Pro功能,开启超级' '防抖后手机屏幕将出现超级防抖Pro开关,点击即可开启或关闭。 除此之外,前置视频同样加持防抖算法,边走边拍也能稳定聚焦脸部' ',实时视频分享您的生活。') def test_run(self): message = appbuilder.Message(self.text) output = self.com.run(message) self.assertIsNotNone(output) print(output) def test_tool_eval(self): result = self.com.tool_eval(text = self.text) for str in result: assert isinstance(str, ComponentOutput) print(str) if __name__ == "__main__": unittest.main() ================================================ FILE: python/tests/test_v2_plant_recognize.py ================================================ # Copyright (c) 2023 Baidu, Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import os import unittest import requests import appbuilder from appbuilder.core.message import Message from appbuilder.core.component import Component from appbuilder.core.component import ComponentOutput from appbuilder.core.components.v2.plant_recognize.component import PlantRecognition # @unittest.skipUnless(os.getenv("TEST_CASE", "UNKNOWN") == "CPU_PARALLEL", "") class TestPlantRecognition(unittest.TestCase): def setUp(self): """ 设置环境变量 Args: None. Returns: None. """ # 从BOS存储读取样例文件 self.image_url = ("https://bj.bcebos.com/v1/appbuilder/" "palnt_recognize_test.jpg?authorization=" "bce-auth-v1%2FALTAKGa8m4qCUasgoljdEDAzLm%" "2F2024-01-23T09%3A51%3A03Z%2F-1%2Fhost%2" "Faa2217067f78f0236c8262cdd89a4b4f4b2188" "d971ca547c53d01742af4a2cbe") self.raw_image = requests.get(self.image_url).content self.plant_recognize = PlantRecognition() # 输入参数为一张图片 def test_run_with_image_url(self): """ 使用图片url进行单测 Args: None Returns: None """ # Create message with raw_image inp = Message(content={"url": self.image_url}) msg = self.plant_recognize.run(inp) self.assertIsNotNone(msg.content) def test_run_with_raw_image(self): """ 使用原始图片进行单测 Args: None Returns: None """ # Create message with raw_image inp = Message(content={"raw_image": self.raw_image}) msg = self.plant_recognize.run(inp) self.assertIsNotNone(msg.content) def test_tool_eval_invalid(self): """测试 tool 方法对无效请求的处理。""" with self.assertRaises(ValueError): result = self.plant_recognize.tool_eval(name="plant_recognition", streaming=True, origin_query="") next(result) def test_tool_eval(self): """测试 tool 方法的处理。""" img_url = "https://bj.bcebos.com/v1/appbuilder/animal_recognize_test.png?" \ "authorization=bce-auth-v1%2FALTAKGa8m4qCUasgoljdEDAzLm%2F2024-01-24T" \ "12%3A19%3A16Z%2F-1%2Fhost%2F411bad53034fa8f9c6edbe5c4909d76ecf6fad68" \ "62cf937c03f8c5260d51c6ae" img_name = "test_img.jpg" result = self.plant_recognize.tool_eval( img_name=img_name, img_url=img_url) for r in result: print(r) self.assertIsInstance(r, ComponentOutput) if __name__ == '__main__': unittest.main() ================================================ FILE: python/tests/test_v2_qa_pair_mining.py ================================================ # Copyright (c) 2023 Baidu, Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import unittest import os import appbuilder from appbuilder.core.components.v2 import QAPairMining @unittest.skipUnless(os.getenv("TEST_CASE", "UNKNOWN") == "CPU_PARALLEL", "") class TestQAPairMiningComponent(unittest.TestCase): def setUp(self): """ 设置环境变量。 Args: 无参数,默认值为空。 Returns: 无返回值,方法中执行了环境变量的赋值操作。 """ self.model_name = "DeepSeek-V3.1" self.node = QAPairMining(model=self.model_name) def test_run_with_default_params(self): """测试 run 方法使用默认参数""" query = "2017年,工商银行根据外部宏观环境变化..." msg = appbuilder.Message(query) answer = self.node(msg) self.assertIsNotNone(answer) self.assertIn("问题", answer.content) self.assertIn("答案", answer.content) # def test_run_with_custom_params(self): # """测试 run 方法使用自定义参数""" # query = "2017年,工商银行根据外部宏观环境变化..." # msg = appbuilder.Message(query) # answer = self.node(msg, stream=True, temperature=0.5) # self.assertIsNotNone(answer) # # 检查 answer 是否符合预期 def test_run_with_invalid_params(self): """测试 run 方法使用无效参数""" query = "2017年,工商银行根据外部宏观环境变化..." msg = appbuilder.Message(query) with self.assertRaises((ValueError, TypeError)): self.node(msg, invalid_param="invalid") def test_tool_eval_valid(self): """测试 tool 方法对有效请求的处理。""" query = "2017年,工商银行根据外部宏观环境变化..." result = self.node.tool_eval(query=query) res = [item for item in result] self.assertNotEqual(len(res), 0) result = self.node.tool_eval(query=query) res = [item for item in result] def test_tool_eval_invalid(self): """测试 tool 方法对无效请求的处理。""" with self.assertRaises(ValueError): result = self.node.tool_eval(query=None) next(result) if __name__ == '__main__': unittest.main() ================================================ FILE: python/tests/test_v2_qrcode_ocr.py ================================================ # Copyright (c) 2023 Baidu, Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import unittest import os import requests import unittest import appbuilder from appbuilder.core._exception import InvalidRequestArgumentError from appbuilder.core.components.v2 import QRcodeOCR class TestQRcodeOCR(unittest.TestCase): def setUp(self): """ 设置环境变量。 """ self.qrcode_ocr = QRcodeOCR() def test_run_with_raw_image(self): """ 使用原始图片进行单测 Args: None Returns: None """ image_url = "https://bj.bcebos.com/v1/appbuilder/qrcode_ocr_test.png?" \ "authorization=bce-auth-v1%2FALTAKGa8m4qCUasgoljdEDAzLm%2F2024-" \ "01-24T12%3A45%3A13Z%2F-1%2Fhost%2Ffc43d07b41903aeeb5a023131ba6" \ "e74ab057ce26d50e966dc31ff083e6a9c41b" raw_image = requests.get(image_url).content # Create message with raw_image message = appbuilder.Message(content={"raw_image": raw_image}) # Qrcode ocr output = self.qrcode_ocr.run(message) # Assert output is not None print(output) self.assertIsNotNone(output) def test_run_with_url(self): """ 使用图片 URL 进行单测 Args: None Returns: None """ image_url = "https://bj.bcebos.com/v1/appbuilder/qrcode_ocr_test.png?" \ "authorization=bce-auth-v1%2FALTAKGa8m4qCUasgoljdEDAzLm%2F2024-" \ "01-24T12%3A45%3A13Z%2F-1%2Fhost%2Ffc43d07b41903aeeb5a023131ba6" \ "e74ab057ce26d50e966dc31ff083e6a9c41b" # Create message with image URL message = appbuilder.Message(content={"url": image_url}) # Qrcode ocr output = self.qrcode_ocr.run(message) # Assert output is not None self.assertIsNotNone(output) def test_run_with_args(self): """ 测试run方法,location、timeout、retry参数 Args: None Returns: None """ image_url = "https://bj.bcebos.com/v1/appbuilder/qrcode_ocr_test.png?" \ "authorization=bce-auth-v1%2FALTAKGa8m4qCUasgoljdEDAzLm%2F2024-" \ "01-24T12%3A45%3A13Z%2F-1%2Fhost%2Ffc43d07b41903aeeb5a023131ba6" \ "e74ab057ce26d50e966dc31ff083e6a9c41b" raw_image = requests.get(image_url).content # Create message with raw_image message = appbuilder.Message(content={"raw_image": raw_image}) # Qrcode ocr with timeout and retry parameters output = self.qrcode_ocr.run(message, location="true", timeout=5.0, retry=3) # Assert output is not None self.assertIsNotNone(output) def test_run_with_invalid_input(self): """ 测试run函数在传入无效输入的情况下的行为。 Args: None Returns: None """ # create empty message message = appbuilder.Message(content={}) # Assert ValueError is raised with self.assertRaises(ValueError): self.qrcode_ocr.run(message) def test_run_with_invalid_url(self): """ 测试run函数在传入无效URL的情况下的行为。 Args: None Returns: None """ url = "http://example.com/invalid_url.jpg" message = appbuilder.Message(content={"url": url}) with self.assertRaises(appbuilder.AppBuilderServerException): self.qrcode_ocr.run(message) with self.assertRaises(InvalidRequestArgumentError): self.qrcode_ocr.run(message=message,location='test') def test_tool_eval(self): image_url = "https://bj.bcebos.com/v1/appbuilder/qrcode_ocr_test.png?" \ "authorization=bce-auth-v1%2FALTAKGa8m4qCUasgoljdEDAzLm%2F2024-" \ "01-24T12%3A45%3A13Z%2F-1%2Fhost%2Ffc43d07b41903aeeb5a023131ba6" \ "e74ab057ce26d50e966dc31ff083e6a9c41b" result=self.qrcode_ocr.tool_eval(file_names=['test']) with self.assertRaises(InvalidRequestArgumentError): msg = next(result) print(msg) result=self.qrcode_ocr.tool_eval( file_names=['test'], _sys_file_urls={'test':image_url}, location='True', ) res=next(result) print(res) self.assertEqual(res.content[-1].visible_scope,'llm') res=next(result) print(res) self.assertEqual(res.content[-1].visible_scope,'user') if __name__ == '__main__': unittest.main() ================================================ FILE: python/tests/test_v2_query_decomposition.py ================================================ # Copyright (c) 2023 Baidu, Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import os import unittest import appbuilder from appbuilder.core.components.v2 import QueryDecomposition @unittest.skipUnless(os.getenv("TEST_CASE", "UNKNOWN") == "CPU_PARALLEL", "") class TestQueryDecompositionComponent(unittest.TestCase): def setUp(self): """ 设置环境变量。 Args: 无参数,默认值为空。 Returns: 无返回值,方法中执行了环境变量的赋值操作。 """ self.model_name = "DeepSeek-V3.1" self.node = QueryDecomposition(model=self.model_name) def test_run_with_default_params(self): """测试 run 方法使用默认参数""" query = "吸塑包装盒在工业化生产和物流运输中分别有什么重要性?" msg = appbuilder.Message(query) answer = self.node(msg) self.assertIsNotNone(answer) # def test_run_with_custom_params(self): # """测试 run 方法使用自定义参数""" # query = "吸塑包装盒在工业化生产和物流运输中分别有什么重要性?" # msg = appbuilder.Message(query) # answer = self.node(msg, stream=True, temperature=0.5) # self.assertIsNotNone(answer) # # 检查 answer 是否符合预期 def test_run_with_invalid_params(self): """测试 run 方法使用无效参数""" query = "吸塑包装盒在工业化生产和物流运输中分别有什么重要性?" msg = appbuilder.Message(query) with self.assertRaises((ValueError, TypeError)): self.node(msg, invalid_param="invalid") def test_tool_eval_valid(self): """测试 tool 方法对有效请求的处理。""" query = "吸塑包装盒在工业化生产和物流运输中分别有什么重要性?" result = self.node.tool_eval(query) res = [item for item in result] self.assertNotEqual(len(res), 0) result = self.node.tool_eval(query) res = [item for item in result] def test_tool_eval_invalid(self): """测试 tool 方法对无效请求的处理。""" with self.assertRaises(ValueError): result = self.node.tool_eval(query=None) next(result) if __name__ == '__main__': unittest.main() ================================================ FILE: python/tests/test_v2_query_rewrite.py ================================================ # Copyright (c) 2023 Baidu, Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # !/usr/bin/env python3 import os import unittest from typing import List, Tuple import appbuilder from appbuilder.core.components.v2 import QueryRewrite @unittest.skipUnless(os.getenv("TEST_CASE", "UNKNOWN") == "CPU_PARALLEL", "") class TestQueryRewriteComponent(unittest.TestCase): def setUp(self): """ 初始化查询重写组件的单元测试基类。 Args: 无参数。 Returns: 无返回值。 """ # 设置环境变量和初始化TranslateComponent实例 self.model_name = "DeepSeek-V3.1" self.node = QueryRewrite(model=self.model_name) def test_run_with_default_params(self): """测试 run 方法使用默认参数""" query = ['我应该怎么办理护照?', '您可以查询官网或人工咨询', '我需要准备哪些材料?', '身份证、免冠照片一张以及填写完整的《中国公民因私出国(境)申请表》', '在哪里办'] msg = appbuilder.Message(query) answer = self.node(msg) self.assertIsNotNone(answer) # 可以添加更多断言来检查 answer 的特定属性 def test_run_with_custom_params(self): """测试 run 方法使用自定义参数""" query = ['我应该怎么办理护照?', '您可以查询官网或人工咨询', '我需要准备哪些材料?', '身份证、免冠照片一张以及填写完整的《中国公民因私出国(境)申请表》', '在哪里办'] msg = appbuilder.Message(query) type = "仅用户查询" answer = self.node(msg, rewrite_type=type) self.assertIsNotNone(answer) # 检查 answer 是否符合预期 def test_run_with_stream_and_temperature(self): """测试不同的 stream 和 temperature 参数值""" node = QueryRewrite("DeepSeek-V3.1") query = ['我应该怎么办理护照?', '您可以查询官网或人工咨询', '我需要准备哪些材料?', '身份证、免冠照片一张以及填写完整的《中国公民因私出国(境)申请表》', '在哪里办'] msg = appbuilder.Message(query) answer = node(msg, rewrite_type="带机器人回复", stream=False, temperature=0.5) self.assertIsNotNone(answer) def test_run_raise(self): with self.assertRaises(ValueError): self.node(message=None) query = ['我应该怎么办理护照?', '您可以查询官网或人工咨询'] msg=appbuilder.Message(query) with self.assertRaises(ValueError): self.node(message=msg) test_str='test'*1500 query = [test_str] msg=appbuilder.Message(query) with self.assertRaises(ValueError): self.node(message=msg) def test_tool_eval_valid(self): """测试 tool 方法对有效请求的处理。""" params = { 'query': ['我应该怎么办理护照?', '您可以查询官网或人工咨询'] } result = self.node.tool_eval(**params) res = [item for item in result] self.assertNotEqual(len(res), 0) result = self.node.tool_eval(streaming=False, **params) res = [item for item in result] def test_tool_eval_invalid(self): """测试 tool 方法对无效请求的处理。""" with self.assertRaises(ValueError): params = { 'query': None } result = self.node.tool_eval(**params) next(result) if __name__ == '__main__': unittest.main() ================================================ FILE: python/tests/test_v2_similar_question.py ================================================ # Copyright (c) 2024 Baidu, Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import os import unittest import requests import appbuilder from appbuilder.core.component import ComponentOutput from appbuilder.core.components.v2 import SimilarQuestion @unittest.skipUnless(os.getenv("TEST_CASE", "UNKNOWN") == "CPU_PARALLEL", "") class TestSimilarQuestion(unittest.TestCase): def setUp(self): self.com = SimilarQuestion(model="DeepSeek-V3.1") def test_run(self): query = "我想吃冰淇淋,哪里的冰淇淋比较好吃?" msg = appbuilder.Message(query) out = self.com.run(msg) self.assertIsNotNone(out) print(out) def test_tool_eval(self): query = "我想吃冰淇淋,哪里的冰淇淋比较好吃?" for output in self.com.tool_eval(query): self.assertIsInstance(output, ComponentOutput) print(output) if __name__ == '__main__': unittest.main() ================================================ FILE: python/tests/test_v2_style_rewrite.py ================================================ # Copyright (c) 2024 Baidu, Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import os import unittest import time import appbuilder from appbuilder.core.components.v2 import StyleRewrite from appbuilder.core.component import ComponentOutput @unittest.skipUnless(os.getenv("TEST_CASE", "UNKNOWN") == "CPU_PARALLEL", "") class TestStyleRewrite(unittest.TestCase): def setUp(self) -> None: self.com = StyleRewrite(model="DeepSeek-V3.1") def test_normal_case(self): time.sleep(2) text = "文心大模型发布新版" style = "激励话术" msg = appbuilder.Message(content=text) out = self.com(msg, style=style) self.assertIn("文心大模型", out.content) def test_tool_eval(self): time.sleep(2) text = "文心大模型发布新版" style = "营销话术" out = self.com.tool_eval(query=text, style=style) for item in out: self.assertIsInstance(item, ComponentOutput) def test_non_stream_tool_eval(self): text = "成都是个包容的城市" style = "直播话术" out = self.com.non_stream_tool_eval(query=text, style=style) print(out) self.assertIsInstance(out, ComponentOutput) def test_tool_eval_invalid(self): """测试 tool 方法对无效请求的处理。""" with self.assertRaises(TypeError): result = self.com.tool_eval(name="image_understand", streaming=True, origin_query="") if __name__ == '__main__': unittest.main() ================================================ FILE: python/tests/test_v2_style_writing.py ================================================ # Copyright (c) 2024 Baidu, Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import os import unittest import appbuilder from appbuilder.core.components.v2 import StyleWriting from appbuilder.core.component import ComponentOutput @unittest.skipUnless(os.getenv("TEST_CASE", "UNKNOWN") == "CPU_PARALLEL", "") class TestStyleWriting(unittest.TestCase): def setUp(self): self.com = StyleWriting(model = "DeepSeek-V3.1") def test_run(self): query = "帮我写一篇关于足球的文案" msg = appbuilder.Message(query) style = "小红书" length = 100 out = self.com.run(msg, style_query=style, length=length) print(out) def test_tool_eval(self): query = "帮我写一篇关于足球的文案" style = "小红书" length = 150 result = self.com.tool_eval(query, style, length) for res in result: assert isinstance(res, ComponentOutput) print(res) if __name__ == '__main__': unittest.main() ================================================ FILE: python/tests/test_v2_table_ocr.py ================================================ # Copyright (c) 2024 Baidu, Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import os import unittest import appbuilder from appbuilder.core.components.v2 import TableOCR from appbuilder.core.component import ComponentOutput @unittest.skipUnless(os.getenv("TEST_CASE", "UNKNOWN") == "CPU_PARALLEL", "") class TestTableOCR(unittest.TestCase): def setUp(self): self.com = TableOCR() self.image_url = "https://bj.bcebos.com/v1/appbuilder/table_ocr_test.png?"\ "authorization=bce-auth-v1%2FALTAKGa8m4qCUasgoljdEDAzLm%2F2024-01-24T12%3A37%3A09Z%2F-1%2Fhost%2Fab528a5a9120d328dc6d18c6"\ "064079145ff4698856f477b820147768fc2187d3" def test_run(self): out = self.com.run(appbuilder.Message(content={"url": self.image_url})) print(out) def test_tool_eval_01(self): result = self.com.tool_eval(file_urls = [self.image_url]) def test_tool_eval_01(self): result = self.com.tool_eval(file_urls = [self.image_url]) for res in result: assert isinstance(res, ComponentOutput) print(res.role, res.content) def test_tool_eval_02(self): _sys_file_urls = { "test-name.png": self.image_url } result = self.com.tool_eval(file_names = ["test-name.png"], _sys_file_urls = _sys_file_urls) for res in result: assert isinstance(res, ComponentOutput) print(res.role, res.content) if __name__ == '__main__': unittest.main() ================================================ FILE: python/tests/test_v2_tag_extraction.py ================================================ # Copyright (c) 2023 Baidu, Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License.import unittest import os import appbuilder import os import unittest from appbuilder.core.components.v2 import TagExtraction @unittest.skipUnless(os.getenv("TEST_CASE", "UNKNOWN") == "CPU_PARALLEL", "") class TestTagExtractionComponent(unittest.TestCase): def setUp(self): """ 设置环境变量。 Args: 无参数,默认值为空。 Returns: 无返回值,方法中执行了环境变量的赋值操作。 """ self.model_name = "DeepSeek-V3.1" self.tag_extraction = TagExtraction(model=self.model_name) def test_run_with_default_params(self): """测试 run 方法使用默认参数""" query = "本实用新型公开了一种可利用热能的太阳能光伏光热一体化组件,包括太阳能电池,还包括有吸热板,太阳能电池粘附在吸热板顶面,吸热板内嵌入有热电材料制成的内芯,吸热板底面设置有蛇形管。本实用新型结构紧凑,安装方便,能充分利用太阳能电池散发的热能,具有较高的热能利用率。" msg = appbuilder.Message(query) answer = self.tag_extraction(msg) self.assertIsNotNone(answer) def test_run_with_stream_and_temperature(self): """测试不同的 stream 和 temperature 参数值""" msg = appbuilder.Message( "本实用新型公开了一种可利用热能的太阳能光伏光热一体化组件,包括太阳能电池,还包括有吸热板,太阳能电池粘附在吸热板顶面,吸热板内嵌入有热电材料制成的内芯,吸热板底面设置有蛇形管。本实用新型结构紧凑,安装方便,能充分利用太阳能电池散发的热能,具有较高的热能利用率。") answer = self.tag_extraction(msg, stream=False, temperature=0.5) self.assertIsNotNone(answer) def test_tool_eval_valid(self): """测试 tool 方法对有效请求的处理。""" query = "本实用新型公开了一种可利用热能的太阳能光伏光热一体化组件,包括太阳能电池,还包括有吸热板,太阳能电池粘附在吸热板顶面,吸热板内嵌入有热电材料制成的内芯,吸热板底面设置有蛇形管。本实用新型结构紧凑,安装方便,能充分利用太阳能电池散发的热能,具有较高的热能利用率。" result = self.tag_extraction.tool_eval(query=query) res = [item for item in result] self.assertNotEqual(len(res), 0) result = self.tag_extraction.tool_eval(query=query) res = [item for item in result] def test_tool_eval_invalid(self): """测试 tool 方法对无效请求的处理。""" with self.assertRaises(ValueError): result = self.tag_extraction.tool_eval(query=None) next(result) if __name__ == '__main__': unittest.main() ================================================ FILE: python/tests/test_v2_text_to_image.py ================================================ # Copyright (c) 2024 Baidu, Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import os import unittest import appbuilder from appbuilder.core.components.v2 import Text2Image from appbuilder.core.component import ComponentOutput @unittest.skip("偶现报错暂时跳过") class TestText2Image(unittest.TestCase): def setUp(self): """ 设置环境变量。 Args: None Returns: None. """ self.com = Text2Image() def test_run(self): """ 使用原始文本进行单测 Args: None Returns: None """ inp = appbuilder.Message(content={"prompt": "上海的经典风景"}) out = self.com.run(inp) self.assertIsNotNone(out) self.assertIsInstance(out, appbuilder.Message) def test_tool_eval(self): """ 测试 tool_eval 方法的正确性。 Args: self: 测试类的实例。 Returns: 无返回值。 Raises: 无异常抛出。 """ result = self.com.tool_eval(query = "上海的经典风景") for res in result: self.assertIsInstance(res, ComponentOutput) print(res) if __name__ == '__main__': unittest.main() ================================================ FILE: python/tests/test_v2_translate.py ================================================ # Copyright (c) 2024 Baidu, Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import os import unittest import appbuilder from appbuilder.core.components.v2 import Translation from appbuilder.core.component import ComponentOutput @unittest.skipUnless(os.getenv("TEST_CASE", "UNKNOWN") == "CPU_PARALLEL", "") class TestTranslation(unittest.TestCase): def setUp(self) -> None: self.com = Translation() def test_run(self): msg = appbuilder.Message(content="你好") result = self.com.run(message = msg, to_lang="en") print(result) def test_tool_eval(self): result = self.com.tool_eval(q="你好", to_lang="en") for res in result: assert isinstance(res, ComponentOutput) print(res) if __name__ == '__main__': unittest.main() ================================================ FILE: python/tests/test_v2_treemind.py ================================================ # Copyright (c) 2024 Baidu, Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import os import unittest from appbuilder.core.message import Message from appbuilder.core.component import Component from appbuilder.core.component import ComponentOutput from appbuilder.core.components.v2 import TreeMind @unittest.skip("测试API超限,暂时跳过") class TestTreeMindComponent(unittest.TestCase): def setUp(self): """ 初始化测试用例,设置环境变量和网关URL。 如果没有设置CAR_EXPERT_TOKEN环境变量,则使用空字符串。 Args: None. Returns: None. """ self.tm = TreeMind() self.query = "生成一份年度总结的思维导图" def test_treemind_component_tool_eval(self): """测试tool_eval方法的返回值是否正确 """ import time time.sleep(1) result = self.tm.tool_eval(query=self.query) self.assertIsNotNone(result) for r in result: self.assertIsNotNone(r) def test_run_with_invalid_input(self): """测试run函数在传入无效输入的情况下的行为。 """ message = Message(content={}) with self.assertRaises(ValueError): self.tm.run(message) def test_tool_eval_invalid(self): """测试 tool 方法传入无效输入的情况下的行为""" with self.assertRaises(TypeError): result = self.tm.tool_eval(name="treemind", streaming=True, origin_query="") next(result) def test_tool_eval(self): result = self.tm.tool_eval(query=self.query) for r in result: self.assertIsInstance(r, ComponentOutput) if __name__ == '__main__': unittest.main() ================================================ FILE: python/tests/test_vdb_retriever.py ================================================ # Copyright (c) 2023 Baidu, Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # !/usr/bin/env python3 import os import unittest from typing import List, Tuple import appbuilder @unittest.skipUnless(os.getenv("TEST_CASE", "UNKNOWN") == "CPU_PARALLEL", "") class TestBaiduVDBRetrieverParameter(unittest.TestCase): def setUp(self) -> None: os.environ["APPBUILDER_TOKEN"] = "bce-v3/ABCDE" def test_run_parameter_query(self): query = appbuilder.Message('') retriever = appbuilder.BaiduVDBRetriever( embedding="abcde", table="abcde") with self.assertRaises(ValueError) as context: retriever.run(query) self.assertIn("Parameter `query` content is empty", str(context.exception)) def test_run_paramter_query_type(self): query = appbuilder.Message(content=12345) retriever = appbuilder.BaiduVDBRetriever( embedding="abcde", table="abcde") with self.assertRaises(ValueError) as context: retriever.run(query) self.assertIn("Parameter `query` content is not a string", str(context.exception)) def test_run_parameter_query_length(self): query = appbuilder.Message(content="a" * 1025) retriever = appbuilder.BaiduVDBRetriever( embedding="abcde", table="abcde") with self.assertRaises(ValueError) as context: retriever.run(query) self.assertIn("Parameter `query` content is too long", str(context.exception)) def test_run_parameter_topk_positive(self): query = appbuilder.Message() retriever = appbuilder.BaiduVDBRetriever( embedding="abcde", table="abcde") with self.assertRaises(ValueError) as context: retriever.run(query, top_k=-1) self.assertIn("Parameter `top_k` must be a positive integer", str(context.exception)) class TestVDBParameterCheck(unittest.TestCase): def setUp(self) -> None: os.environ["APPBUILDER_TOKEN"] = "bce-v3/ABCDE" def test_vdb_parameter_account(self): with self.assertRaises(TypeError) as context: appbuilder.BaiduVDBVectorStoreIndex( instance_id="abcde", api_key="abcde", account=123456) self.assertIn("must be a string", str(context.exception)) def test_vdb_parameter_database_name(self): with self.assertRaises(TypeError) as context: appbuilder.BaiduVDBVectorStoreIndex( instance_id="abcde", api_key="abcde", database_name=123456) self.assertIn("must be a string", str(context.exception)) def test_vdb_parameter_table_params(self): with self.assertRaises(TypeError) as context: appbuilder.BaiduVDBVectorStoreIndex( instance_id="abcde", api_key="abcde", table_params=123456) self.assertIn("must be a TableParams", str(context.exception)) def test_vdb_parameter_embedding(self): with self.assertRaises(TypeError) as context: appbuilder.BaiduVDBVectorStoreIndex( instance_id="abcde", api_key="abcde", embedding=123456) self.assertIn("must be a Embedding", str(context.exception)) if __name__ == '__main__': unittest.main() ================================================ FILE: python/utils/__init__.py ================================================ # Copyright (c) 2023 Baidu, Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. ================================================ FILE: python/utils/_bcc.py ================================================ # Copyright (c) 2024 Baidu, Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from baidubce.services.bcc import bcc_client, bcc_model from baidubce.utils import aes128_encrypt_16char_key from baidubce.http import http_methods import json import uuid class InnerBccClient(bcc_client.BccClient): def __init__(self, config=None): bcc_client.BccClient.__init__(self, config) def create_instance_by_spec( self, spec, image_id, root_disk_size_in_gb=0, root_disk_storage_type=None, ephemeral_disks=None, create_cds_list=None, network_capacity_in_mbps=0, eip_name=None, internet_charge_type=None, purchase_count=1, name=None, hostname=None, auto_seq_suffix=None, is_open_hostname_domain=None, admin_pass=None, billing=None, zone_name=None, subnet_id=None, security_group_id=None, enterprise_security_group_id=None, security_group_ids=None, enterprise_security_group_ids=None, relation_tag=None, is_open_ipv6=None, tags=None, key_pair_id=None, auto_renew_time_unit=None, auto_renew_time=0, cds_auto_renew=None, asp_id=None, bid_model=None, bid_price=None, dedicate_host_id=None, deploy_id=None, deploy_id_list=None, client_token=None, config=None, user_data=None, ): path = b"/instanceBySpec" params = {} if client_token is None: params["clientToken"] = str(uuid.uuid4()) else: params["clientToken"] = client_token if billing is None: billing = bcc_model.Billing("Postpaid") body = {"spec": spec, "imageId": image_id, "billing": billing.__dict__} if root_disk_size_in_gb != 0: body["rootDiskSizeInGb"] = root_disk_size_in_gb if root_disk_storage_type is not None: body["rootDiskStorageType"] = root_disk_storage_type if create_cds_list is not None: body["createCdsList"] = [ create_cds.__dict__ for create_cds in create_cds_list ] if network_capacity_in_mbps != 0: body["networkCapacityInMbps"] = network_capacity_in_mbps if eip_name is not None: body["eipName"] = eip_name if purchase_count > 0: body["purchaseCount"] = purchase_count if name is not None: body["name"] = name if hostname is not None: body["hostname"] = hostname if auto_seq_suffix is not None: body["autoSeqSuffix"] = auto_seq_suffix if is_open_hostname_domain is not None: body["isOpenHostnameDomain"] = is_open_hostname_domain if admin_pass is not None: secret_access_key = self.config.credentials.secret_access_key cipher_admin_pass = aes128_encrypt_16char_key( admin_pass, secret_access_key) body["adminPass"] = cipher_admin_pass if zone_name is not None: body["zoneName"] = zone_name if subnet_id is not None: body["subnetId"] = subnet_id if security_group_id is not None: body["securityGroupId"] = security_group_id if enterprise_security_group_id is not None: body["enterpriseSecurityGroupId"] = enterprise_security_group_id if security_group_ids is not None: body["securityGroupIds"] = security_group_ids if enterprise_security_group_ids is not None: body["enterpriseSecurityGroupIds"] = enterprise_security_group_ids if auto_renew_time != 0: body["autoRenewTime"] = auto_renew_time if auto_renew_time_unit is None: body["autoRenewTimeUnit"] = "month" else: body["autoRenewTimeUnit"] = auto_renew_time_unit if ephemeral_disks is not None: body["ephemeralDisks"] = [ ephemeral_disk.__dict__ for ephemeral_disk in ephemeral_disks ] if dedicate_host_id is not None: body["dedicatedHostId"] = dedicate_host_id if deploy_id is not None: body["deployId"] = deploy_id if deploy_id_list is not None: body["deployIdList"] = deploy_id_list if bid_model is not None: body["bidModel"] = bid_model if bid_price is not None: body["bidPrice"] = bid_price if key_pair_id is not None: body["keypairId"] = key_pair_id if internet_charge_type is not None: body["internetChargeType"] = internet_charge_type if asp_id is not None: body["aspId"] = asp_id if relation_tag is not None: body["relationTag"] = relation_tag if is_open_ipv6 is not None: body["isOpenIpv6"] = is_open_ipv6 if user_data is not None: body["userData"] = user_data if tags is not None: tag_list = [tag.__dict__ for tag in tags] body["tags"] = tag_list body["cdsAutoRenew"] = cds_auto_renew return self._send_request( http_methods.POST, path, json.dumps(body), params=params, config=config ) def _compute_service_id(self): return "bcc" ================================================ FILE: python/utils/bce_deploy.py ================================================ # Copyright (c) 2024 Baidu, Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import time import uuid import os import yaml import tarfile import argparse from datetime import datetime from baidubce.auth.bce_credentials import BceCredentials from baidubce.bce_client_configuration import BceClientConfiguration from baidubce.services.bos.bos_client import BosClient from baidubce.services.bcc import bcc_model from appbuilder.utils.logger_util import logger from appbuilder.utils._bcc import InnerBccClient class AppbuilderSDKInstance: def __init__(self, config_path): self.config_path = config_path self.load_config() self.credentials = BceCredentials(self.bce_config["ak"], self.bce_config["sk"]) self.bos_client = self.create_bos_client() self.bcc_client = self.create_bce_client() def load_config(self): with open(self.config_path) as f: config = yaml.load(f, Loader=yaml.FullLoader) self.config = config self.bce_config = self.config["bce_config"] self.security_group_id = self.bce_config["security_group_id"] self.admin_pass = self.bce_config["admin_pass"] self.zone_name = self.bce_config["zone_name"] self.appbuilder_config = self.config["appbuilder_config"] self.env = self.config["env"] def save_config(self, config): self.config["bce_config"]["security_group_id"] = self.security_group_id with open(self.config_path, "w") as f: yaml.dump(config, f, indent=4) def create_bce_client(self): bce_config = BceClientConfiguration( self.credentials, endpoint=self.bce_config["host"] ) return InnerBccClient(bce_config) def create_bos_client(self): bos_config = BceClientConfiguration( self.credentials, endpoint=self.bce_config["bos_host"] ) return BosClient(bos_config) def create_tar(self): local_dir = self.appbuilder_config["local_dir"] timestamp = int(time.time()) self.tar_file_name = "pkg_" + str(timestamp) + ".tar" with tarfile.open(self.tar_file_name, "w") as tar: for filename in os.listdir(local_dir): file_path = os.path.join(local_dir, filename) if os.path.isfile(file_path): tar.add(file_path, arcname=filename) def bos_upload(self): bucket_name = "appbuilder-sdk-test" if not self.bos_client.does_bucket_exist(bucket_name): self.bos_client.create_bucket(bucket_name) self.bos_client.put_object_from_file( bucket_name, self.tar_file_name, self.tar_file_name ) timestamp = int(time.time()) url = self.bos_client.generate_pre_signed_url( bucket_name, self.tar_file_name, timestamp, expiration_in_seconds=3600 ) self.tar_bos_url = url.decode("utf-8") if self.tar_bos_url == None: raise Exception("upload to bos failed") self.log.debug("upload to bos successfully! url: {}".format(self.tar_bos_url)) def clear_local(self): os.remove(self.run_script) os.remove(self.tar_file_name) def build_user_data(self): workspace = self.appbuilder_config["workspace"] user_data = ( "#!/bin/bash\\n" + "mkdir /root/test\\n" + "chmod 777 /root/test\\n" + "cd /root/test\\n" + f"wget -O {self.tar_file_name} {self.tar_bos_url}\\n" + f"tar -xvf {self.tar_file_name}\\n" + f"rm {self.tar_file_name}\\n" + f"chmod a+x {self.run_script_name}\\n" + "yum install -y docker\\n" + "docker pull registry.baidubce.com/appbuilder/appbuilder-sdk-cloud:1.0.4\\n" + f"docker run -itd --net=host -v /root/test:{workspace} --name appbuilder-sdk registry.baidubce.com/appbuilder/appbuilder-sdk-cloud:1.0.4 {workspace}/{self.run_script_name}" ) return user_data def build_run_script(self): timestamp = int(time.time()) self.run_script_name = "start_" + str(timestamp) + ".sh" self.run_script = os.path.join( self.appbuilder_config["local_dir"], self.run_script_name ) commands = [] workspace = self.appbuilder_config["workspace"] for key, value in self.env.items(): commands.append(f'export {key}="{value}"') run_cmd = " && ".join(commands) + " && " + self.appbuilder_config["run_cmd"] with open(self.run_script, "w") as file: file.write("#!/bin/sh\n") file.write(f"cd {workspace}\n") file.write(run_cmd) def create_instance(self): if self.security_group_id == None or self.security_group_id == "": self.create_security_group() now_str = datetime.now().strftime("%Y-%m-%d-%H-%M-%S") instance = self.bcc_client.create_instance_by_spec( spec=self.bce_config["spec"], # 实例规格 image_id="m-43wfwG1G", # 镜像ID # 待创建虚拟机实例的系统盘大小,单位GB,默认是40GB,范围为[40, # 2048]GB,超过40GB按照云磁盘价格收费。注意指定的系统盘大小需要满足所使用镜像最小磁盘空间限制。 root_disk_size_in_gb=self.bce_config["root_disk_size_in_gb"], network_capacity_in_mbps=1, name="instance-appbuilder-sdk-service-{}".format(now_str), hostname="host-appbuilder-sdk-service-{}".format(now_str), admin_pass=self.admin_pass, zone_name=self.zone_name, user_data=self.build_user_data(), ) self.log.debug("create instance info: {}".format(instance)) self.get_instance_id(instance) if self.instance_id == None: raise Exception("create instance failed") self.log.info("instance create successfully! id: {}".format(self.instance_id)) def get_instance_id(self, instance): self.instance_id = instance.instance_ids[0] def get_public_ip(self, instance_id=None): if instance_id == None and self.instance_id == None: return self.public_ip = None while self.public_ip is None or self.public_ip == "": time.sleep(3) response = None if instance_id != None: response = self.bcc_client.get_instance(instance_id) else: response = self.bcc_client.get_instance(self.instance_id) self.log.debug("get instance info: {}".format(response)) self.public_ip = response.instance.public_ip def create_security_group(self): client_token = str(uuid.uuid4()) # 设置安全组名称 security_group_name = "appbuilder-sdk-" + client_token # 设置安全组规则 security_group_rule = bcc_model.SecurityGroupRuleModel( "rule_" + client_token, # 设置备注 "ingress", # 设置入站/出站,取值ingress或egress,必选参数 portRange="1-65535", # 设置端口范围,默认空时为1-65535,可以指定80等单个端口 protocol="", # 设置协议类型 sourceGroupId="", # 设置源安全组ID sourceIp="", ) security_group_rule_list = [] security_group_rule_list.append(security_group_rule) response = self.bcc_client.create_security_group( name=security_group_name, rules=security_group_rule_list, client_token=client_token, ) self.security_group_id = response.security_group_id if self.security_group_id == None: raise Exception("create security group failed") self.log.info( "security group create successfully!id: {}".format(self.security_group_id) ) self.save_config(self.config) def bind_security_group(self): response = self.bcc_client.bind_instance_to_security_group( self.instance_id, self.security_group_id ) self.log.debug("bind instance to security group: {}".format(response)) def _pre_deploy(self): self.log = logger self.log.info( "The deployment to cloud feature is currently in the beta testing stage.If any issues arise, please submit an issue or contact us through our WeChat group." ) self.build_run_script() self.log.debug("build run script done!") self.create_tar() self.log.debug("create tar done!") self.bos_upload() self.log.debug("upload tar to bos done!") self.clear_local() def _deploy(self): self.create_instance() def _after_deploy(self): self.get_public_ip() self.bind_security_group() self.log.info("deployment finished! public ip: {}".format(self.public_ip)) def deploy(self): self._pre_deploy() self._deploy() self._after_deploy() def deploy(): parser = argparse.ArgumentParser(description="configuration") parser.add_argument("--conf", type=str, help="config yaml file") args = parser.parse_args() conf = args.conf instance = AppbuilderSDKInstance(conf) instance.deploy() if __name__ == "__main__": deploy() ================================================ FILE: python/utils/chainlit.md ================================================ # 欢迎使用AppBuilder-SDK🚀 您好,欢迎您体验AppBuilder-SDK的Chainlit可视化服务化功能。 ## 什么是AppBuilder-SDK👋 百度智能云千帆AppBuilder-SDK是[百度智能云千帆AppBuilder](https://appbuilder.cloud.baidu.com/)面向AI原生应用开发者提供的一站式开发平台的客户端SDK。 我们提供自底向上的:基础组件、流程编排、端到端应用 三类功能。使用百度智能云千帆AppBuilder-SDK,你可以: - 配合百度智能云千帆AppBuilder平台[网页端](https://console.bce.baidu.com/ai_apaas/app),分钟级在本地搭建包含百度工业实践的`端到端的AI原生应用` - 配合 `基础组件` & `流程编排`,积木式搭建个性化的Assistant + FunctionCall应用 - 提供 `API调用` & `交互式窗口` 两种服务化部署方式,支持快速上云,平滑嵌入到你的产品中 ## 如何使用AppBuilder-SDK & Chainlit可视化功能💻 当前SDK中的`AgentRuntime`模块基于Chainlit实现了基础的可视化功能,支持AppBuilderClient + 能力组件实现可视化交互。 - `chainlit_demo`接口支持基础组件的简单交互 - `chainlit_agent`接口支持AppBuilderClient的进阶交互,提供新建会话和上传文件的功能 如果对于可视化有更多需求,可以参考AppBuilder SDK中的代码,基于Chainlit进行二次开发。 ## 链接 🔗 - [AppBuilder官网](https://appbuilder.cloud.baidu.com/) - [AppBuilder-SDK开源代码仓库](https://github.com/baidubce/app-builder) - [AppBuilder文档中心](https://cloud.baidu.com/doc/AppBuilder/index.html) - [Chainlit文档中心](https://docs.chainlit.io/get-started/overview) ================================================ FILE: python/utils/collector.py ================================================ # Copyright (c) 2024 Baidu, Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import collections class AssistantKeys(object): ASSISTANT = "assistant" CONVERSATION = "conversation" FILE = "file" RUN = "run" MESSAGE = "message" class Collector(): _instance = None _initialized = False def __new__(cls, *args, **kwargs): """ 单例模式 """ if cls._instance is None: cls._instance = object.__new__(cls) return cls._instance def __init__(self) -> None: if self._initialized: return self._initialized = True self._collections = collections.OrderedDict() def add_to_collection(self, name, value, index_key=None): assert isinstance(name, str) if name not in self._collections: self._collections[name] = collections.OrderedDict() if index_key is not None: self._collections[name][index_key] = value else: index = len(self._collections[name]) self._collections[name][str(index)] = value def del_collection(self, name, index_key=None): assert isinstance(name, str) if name not in self._collections: return if index_key is not None: del self._collections[name][index_key] else: del self._collections[name] def get_collection(self, name, index_key=None, scope=None): collection = self._collections.get(name, None) if collection is None: if index_key is None: return [] else: return None if index_key is not None: return collection.get(index_key, None) else: return list(collection.values()) def get_collection_as_dict(self, name, reverse=False): if name in self._collections: if reverse: return collections.OrderedDict(zip(self._collections[name].values(), self._collections[name].keys())) else: return collections.OrderedDict(self._collections[name]) else: self._collections[name] = collections.OrderedDict() return self._collections[name] def get_all_collection_keys(self, name=None): return list(self._collections.keys()) def clear_collection(self, name): if name in self._collections: del self._collections[name] ================================================ FILE: python/utils/func_utils.py ================================================ # Copyright (c) 2024 Baidu, Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import warnings from functools import wraps def deprecated(reason=None, version=None): """This is a decorator which can be used to mark functions as deprecated. It will result in a warning being emitted when the function is used.""" def decorator(func): @wraps(func) def new_func(*args, **kwargs): warnings.simplefilter('always', DeprecationWarning) # turn off filter messages = "Call deprecated API {}().".format(func.__qualname__) if reason is not None: messages += " Deprecated because {}.".format(reason) if version is not None: messages += " This API will be removed after version {}.".format(version) messages += "\nDetailed information: " warnings.warn(messages, category=DeprecationWarning, stacklevel=2) warnings.simplefilter('default', DeprecationWarning) # reset filter return func(*args, **kwargs) return new_func return decorator class Singleton(type): _instances = {} def __call__(cls, *args, **kwargs): if cls not in cls._instances: cls._instances[cls] = super( Singleton, cls).__call__(*args, **kwargs) return cls._instances[cls] ================================================ FILE: python/utils/json_schema_to_model.py ================================================ import importlib.util import json import re import sys import copy from contextlib import contextmanager from pathlib import Path from tempfile import NamedTemporaryFile from types import ModuleType from datamodel_code_generator.parser.jsonschema import JsonSchemaParser from pydantic import BaseModel NON_ALPHANUMERIC = re.compile(r"[^a-zA-Z0-9]+") STARTS_WITH_NUMBER = re.compile(r'[0-9]+') UPPER_CAMEL_CASE = re.compile(r"[A-Z][a-zA-Z0-9]+") LOWER_CAMEL_CASE = re.compile(r"[a-z][a-zA-Z0-9]+") class BadJsonSchema(Exception): pass def _to_camel_case(name: str) -> str: if any(NON_ALPHANUMERIC.finditer(name)): return "".join(term.lower().title() if not STARTS_WITH_NUMBER.match(term) else term.lower() for term in NON_ALPHANUMERIC.split(name)) if UPPER_CAMEL_CASE.match(name): return name if LOWER_CAMEL_CASE.match(name): return name[0].upper() + name[1:] raise BadJsonSchema(f"Unknown case used for {name}") def _load_module_from_file(file_path: Path) -> ModuleType: spec = importlib.util.spec_from_file_location( name=file_path.stem, location=str(file_path) ) module = importlib.util.module_from_spec(spec) sys.modules[file_path.stem] = module spec.loader.exec_module(module) return module @contextmanager def _delete_file_on_completion(file_path: Path): try: yield finally: file_path.unlink(missing_ok=True) def replace_last_match(text, pattern, repl): # 使用正则表达式查找所有匹配的子字符串 matches = list(re.finditer(pattern, text)) # 如果没有找到匹配的子字符串,直接返回原始文本 if not matches: return text # 找到最后一个匹配的子字符串的位置和长度 last_match = matches[-1] start, end = last_match.span() # 替换最后一个匹配的子字符串 before = text[:start] after = text[end:] new_text = before + repl + after return new_text def sed_pydantic_str(pydantic_models_as_str:str, title: str): # 在 "from pydantic import BaseModel, Field" 这行后,添加 "from pydantic import RootModel" new_pydantic_models_as_str = re.sub(r'from pydantic import BaseModel, Field', 'from pydantic import BaseModel; from pydantic import Field, RootModel', pydantic_models_as_str) # 判断字符串中是否存在"__root__" has_root = "__root__" in new_pydantic_models_as_str if has_root: # 把最后一个的BaseModel替换为RootModel new_pydantic_models_as_str = replace_last_match(new_pydantic_models_as_str, "BaseModel", "RootModel") # 替换 __root__ 为 root new_pydantic_models_as_str = re.sub(r'\b__root__\b', r'root', new_pydantic_models_as_str) return new_pydantic_models_as_str def json_schema_to_pydantic_model(json_schema: dict, name_override: str) -> BaseModel: json_schema_as_str = json.dumps(json_schema) pydantic_models_as_str: str = JsonSchemaParser(json_schema_as_str).parse() class_title = json_schema["title"] pydantic_models_as_str = sed_pydantic_str(pydantic_models_as_str, class_title) pydantic_models_as_str = pydantic_models_as_str.replace("unique_items", "Set") with NamedTemporaryFile(suffix=".py", delete=False) as temp_file: temp_file_path = Path(temp_file.name).resolve() temp_file.write(pydantic_models_as_str.encode()) with _delete_file_on_completion(file_path=temp_file_path): module = _load_module_from_file(file_path=temp_file_path) main_model_name = _to_camel_case(name=class_title) pydantic_model: BaseModel = module.__dict__[main_model_name] # Override the pydantic model/parser name for nicer ValidationError messaging and logging pydantic_model.__name__ = name_override pydantic_model.parse_obj.__func__.__name__ = name_override return pydantic_model if __name__ == '__main__': manifests = [ { "name": "general_ocr", "description": "提供更高精度的通用文字识别能力,能够识别图片中的文字,不支持html后缀文件的输入", "parameters": { "type": "object", "properties": { "img_url": { "type": "string", "description": "待识别图片的url,根据该url能够获取图片" }, "img_name": { "type": "string", "description": "待识别图片的文件名,用于生成图片url" }, "files": { "type": "array", "items": { "type": "string", }, "uniqueItems": True } }, "anyOf": [ { "required": [ "img_url" ] }, { "required": [ "img_name" ] } ] } } ] schema = copy.deepcopy(manifests[0]['parameters']) schema['title'] = "general_ocr" model = json_schema_to_pydantic_model(json_schema=schema, name_override="GeneralOcr") print(model) print(model.schema_json()) ================================================ FILE: python/utils/logger_file_headler.py ================================================ # Copyright (c) 2024 Baidu, Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import os import time import glob import logging from datetime import datetime, timedelta class SizeAndTimeRotatingFileHandler(logging.Handler): def __init__(self, file_name, rotate_frequency='MIDNIGHT', rotate_interval=1, max_file_size=0, max_log_files=0, total_log_size=0 ): super().__init__() self.file_name = file_name self.rotate_frequency = rotate_frequency.upper() self.rotate_interval = rotate_interval self.max_file_size = max_file_size self.max_log_files = max_log_files self.total_log_size = total_log_size self.current_time = datetime.now() self.current_file = self.file_name self.stream = open(self.current_file, 'a') self.last_rollover = time.time() def _get_new_filename(self): suffix = self.current_time.strftime("%Y-%m-%d_%H-%M-%S") return f"{self.file_name}.{suffix}" def emit(self, record): if self.shouldRollover(record): self.doRollover() self.stream.write(self.format(record) + '\n') self.stream.flush() def shouldRollover(self, record): current_time = time.time() current_size = os.path.getsize(self.current_file) time_rollover = False if self.rotate_frequency == 'S': time_rollover = current_time >= self.last_rollover + self.rotate_interval elif self.rotate_frequency == 'M': time_rollover = current_time >= self.last_rollover + self.rotate_interval * 60 elif self.rotate_frequency == 'H': time_rollover = current_time >= self.last_rollover + self.rotate_interval * 3600 elif self.rotate_frequency == 'D': time_rollover = current_time >= self.last_rollover + self.rotate_interval * 86400 elif self.rotate_frequency == 'MIDNIGHT': time_rollover = datetime.fromtimestamp(current_time).date() != datetime.fromtimestamp(self.last_rollover).date() size_rollover = current_size >= self.max_file_size if self.max_file_size > 0 else False return time_rollover or size_rollover def doRollover(self): self.stream.close() self.current_time = datetime.now() new_filename = self._get_new_filename() os.rename(self.current_file, new_filename) # Rename current file to new name self.current_file = self.file_name self.stream = open(self.current_file, 'a') self.last_rollover = time.time() self.manage_log_files() def manage_log_files(self): log_files = sorted(glob.glob(f"{self.file_name}.*"), key=os.path.getmtime) while len(log_files) > self.max_log_files: oldest_log = log_files.pop(0) os.remove(oldest_log) while self._total_size(log_files) > self.total_log_size: if log_files: oldest_log = log_files.pop(0) os.remove(oldest_log) def _total_size(self, files): return sum(os.path.getsize(f) for f in files if os.path.exists(f)) def close(self): self.stream.close() super().close() ================================================ FILE: python/utils/logger_util.py ================================================ # Copyright (c) 2023 Baidu, Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """ 日志 """ import os import sys import uuid import logging import logging.handlers import logging.config from threading import current_thread from typing import Optional LOGGING_CONFIG = { "version": 1, "disable_existing_loggers": False, "formatters": { "standard": { "format": "[%(asctime)s.%(msecs)03d] %(filename)s [line:%(lineno)d] %(levelname)s [%(logid)s] %(message)s", }, }, "handlers": {}, "loggers": { "appbuilder": { "handlers": [], "level": "INFO", "propagate": True, }, }, } CONSOLE_HEADER = { "level": "INFO", "class": "logging.StreamHandler", "formatter": "standard", "stream": "ext://sys.stdout", # Use standard output } ERROR_FILE_HEADER = { "level": "ERROR", "class": "logging.FileHandler", "filename": "tmp.error.log", "formatter": "standard", } FILE_HEADER = { "level": "DEBUG", "class": "logging.FileHandler", "filename": "tmp.info.log", "formatter": "standard", } ERROR_SET_CONFIG_HEADER = { 'level': 'ERROR', 'formatter': 'standard', 'class': 'appbuilder.SizeAndTimeRotatingFileHandler', 'file_name': 'tmp.error.log', 'rotate_frequency': 'MIDDNIGHT', 'rotate_interval': 1, 'max_file_size': 5*1024*1024, 'max_log_files': 20, 'total_log_size': 100*1024*1024 } SET_CONFIG_HEADER = { 'level': 'DEBUG', 'formatter': 'standard', 'class': 'appbuilder.SizeAndTimeRotatingFileHandler', 'file_name': 'tmp.info.log', 'rotate_frequency': 'MIDDNIGHT', 'rotate_interval': 1, 'max_file_size': 5*1024*1024, 'max_log_files': 20, 'total_log_size': 100*1024*1024 } class LoggerWithLoggerId(logging.LoggerAdapter): """ logger with logid """ def __init__(self, logger, extra, loglevel): """ init """ LOGGING_CONFIG["handlers"] = {} LOGGING_CONFIG["loggers"]["appbuilder"]["handlers"] = [] log_file = os.environ.get("APPBUILDER_LOGFILE", "") log_path = os.environ.get("APPBUILDER_LOGPATH", "") loglevel = loglevel.strip().lower() if loglevel not in ["debug", "info", "warning", "error"]: raise ValueError("expected APPBUILDER_LOGLEVEL in [debug, info, warning, error], but got %s" % loglevel) loglevel = loglevel.upper() if log_path: current_pid = str(os.getpid()) full_log_path = os.path.join(log_path, "log") if not os.path.exists(full_log_path): os.makedirs(full_log_path) info_log_file = os.path.join(log_path, "log", current_pid + ".info.log") error_log_file = os.path.join(log_path, "log", current_pid + ".error.log") FILE_HEADER["filename"] = info_log_file ERROR_FILE_HEADER["filename"] = error_log_file FILE_HEADER["level"] = loglevel LOGGING_CONFIG["handlers"]["file"] = FILE_HEADER LOGGING_CONFIG["loggers"]["appbuilder"]["handlers"].append("file") if loglevel in ("DEBUG", "INFO", "WARNING"): LOGGING_CONFIG["handlers"]["error_file"] = ERROR_FILE_HEADER LOGGING_CONFIG["loggers"]["appbuilder"]["handlers"].append("error_file") elif log_file: ERROR_FILE_HEADER["filename"] = self._add_error_to_file_name(log_file) FILE_HEADER["filename"] = log_file FILE_HEADER["level"] = loglevel LOGGING_CONFIG["handlers"]["file"] = FILE_HEADER LOGGING_CONFIG["loggers"]["appbuilder"]["handlers"].append("file") if loglevel in ("DEBUG", "INFO", "WARNING"): LOGGING_CONFIG["handlers"]["error_file"] = ERROR_FILE_HEADER LOGGING_CONFIG["loggers"]["appbuilder"]["handlers"].append("error_file") CONSOLE_HEADER["level"] = loglevel LOGGING_CONFIG["handlers"]["console"] = CONSOLE_HEADER LOGGING_CONFIG["loggers"]["appbuilder"]["handlers"].append("console") LOGGING_CONFIG['loggers']['appbuilder']['level'] = loglevel logging.config.dictConfig(LOGGING_CONFIG) logging.LoggerAdapter.__init__(self, logger, extra) self.logid_dict = {} def set_auto_logid(self): """ set auto log_id """ self.logid_dict[current_thread().ident] = str(uuid.uuid4().int & (1 << 64) - 1) def set_logid(self, logid): """ set log_id """ self.logid_dict[current_thread().ident] = logid def get_logid(self): """ get log_id """ if current_thread().ident in self.logid_dict: return self.logid_dict[current_thread().ident] else: return None @property def level(self): """ level """ return self.logger.level @staticmethod def _add_error_to_file_name(filename): prefix = "error." dir_name, base_name = os.path.split(filename) new_base_name = f"{prefix}{base_name}" return os.path.join(dir_name, new_base_name) def setFilename(self, filename): """ set filename """ if "file" not in LOGGING_CONFIG["loggers"]["appbuilder"]["handlers"]: FILE_HEADER["filename"] = filename LOGGING_CONFIG["handlers"]["file"] = FILE_HEADER LOGGING_CONFIG["loggers"]["appbuilder"]["handlers"].append("file") if "error_file" not in LOGGING_CONFIG["loggers"]["appbuilder"]["handlers"]: ERROR_FILE_HEADER["filename"] = self._add_error_to_file_name(filename) LOGGING_CONFIG["handlers"]["error_file"] = ERROR_FILE_HEADER LOGGING_CONFIG["loggers"]["appbuilder"]["handlers"].append("error_file") FILE_HEADER["filename"] = filename ERROR_FILE_HEADER["filename"] = self._add_error_to_file_name(filename) LOGGING_CONFIG["handlers"]["file"] = FILE_HEADER LOGGING_CONFIG["handlers"]["error_file"] = ERROR_FILE_HEADER logging.config.dictConfig(LOGGING_CONFIG) def setLoglevel(self, level): """ set log level """ log_level = level.strip().lower() if log_level not in ["debug", "info", "warning", "error"]: raise ValueError("expected APPBUILDER_LOGLEVEL in [debug, info, warning, error], but got %s" % log_level) log_level = log_level.upper() if "file" in LOGGING_CONFIG["loggers"]["appbuilder"]["handlers"]: FILE_HEADER["level"] = log_level LOGGING_CONFIG["handlers"]["file"] = FILE_HEADER if "console" in LOGGING_CONFIG["loggers"]["appbuilder"]["handlers"] or not LOGGING_CONFIG["loggers"]["appbuilder"]["handlers"]: CONSOLE_HEADER["level"] = log_level LOGGING_CONFIG["handlers"]["console"] = CONSOLE_HEADER LOGGING_CONFIG['loggers']['appbuilder']['level'] = log_level logging.config.dictConfig(LOGGING_CONFIG) def setLogConfig(self, console_output: bool = True, loglevel: str = "DEBUG", log_path: str = "/tmp", rotate_frequency: str = "MIDNIGHT", rotate_interval: int = 1, max_file_size: Optional[int] = None, # 以B为单位 total_log_size: Optional[int] = None, # 以B为单位 max_log_files: Optional[int] = None, file_name: Optional[str] = None ): LOGGING_CONFIG["handlers"] = {} LOGGING_CONFIG["loggers"]["appbuilder"]["handlers"] = [] # log_level 数据校验 log_level = loglevel.strip().lower() if log_level not in ["debug", "info", "warning", "error"]: raise ValueError("expected APPBUILDER_LOGLEVEL in [debug, info, warning, error], but got %s" % log_level) log_level = log_level.upper() # 设置console输出日志 if console_output: CONSOLE_HEADER['level'] = loglevel LOGGING_CONFIG["handlers"]["console"] = CONSOLE_HEADER LOGGING_CONFIG["loggers"]["appbuilder"]["handlers"].append("console") else: LOGGING_CONFIG["loggers"]["appbuilder"]["propagate"] = False # 参数验证 if not max_file_size or max_file_size <= 0: max_file_size = sys.maxsize if not total_log_size or total_log_size <= 0: total_log_size = sys.maxsize if not max_log_files or max_log_files <= 0: max_log_files = sys.maxsize if rotate_interval < 1: rotate_interval = 1 rotate_frequency = rotate_frequency.strip().lower() if rotate_frequency not in ["s", "m", "h", "d", "midnight"]: raise ValueError("expected rotate_frequency in [S, M, H, D, MIDNIGHT], but got %s" % rotate_frequency) # 设置文件输出日志 # 设置日志级别 SET_CONFIG_HEADER['level'] = loglevel # 设置文件名称 if not file_name: current_pid = str(os.getpid()) else: current_pid = file_name full_log_path = os.path.join(log_path, "log") if not os.path.exists(full_log_path): os.makedirs(full_log_path) info_log_file = os.path.join(log_path, "log", current_pid + ".info.log") error_log_file = os.path.join(log_path, "log", current_pid + ".error.log") SET_CONFIG_HEADER["file_name"] = info_log_file ERROR_SET_CONFIG_HEADER["file_name"] = error_log_file # 设置滚动时间 SET_CONFIG_HEADER['rotate_frequency'] = rotate_frequency ERROR_SET_CONFIG_HEADER['rotate_frequency'] = rotate_frequency SET_CONFIG_HEADER['rotate_interval'] = rotate_interval ERROR_SET_CONFIG_HEADER['rotate_interval'] = rotate_interval # 设置最大文件大小 SET_CONFIG_HEADER['max_file_size'] = max_file_size ERROR_SET_CONFIG_HEADER['max_file_size'] = max_file_size # 设置总大小限制 SET_CONFIG_HEADER['total_log_size'] = total_log_size ERROR_SET_CONFIG_HEADER['total_log_size'] = total_log_size # 设置备份数量 SET_CONFIG_HEADER['max_log_files'] = max_log_files ERROR_SET_CONFIG_HEADER['max_log_files'] = max_log_files LOGGING_CONFIG["handlers"]["file"] = SET_CONFIG_HEADER LOGGING_CONFIG["handlers"]["error_file"] = ERROR_SET_CONFIG_HEADER LOGGING_CONFIG["loggers"]["appbuilder"]["handlers"].extend(["file", "error_file"]) LOGGING_CONFIG['loggers']['appbuilder']['level'] = loglevel logging.config.dictConfig(LOGGING_CONFIG) def process(self, msg, kwargs): """ processing """ if current_thread().ident in self.logid_dict: # in process thread if 'extra' not in kwargs: kwargs['extra'] = {'logid': self.logid_dict[current_thread().ident]} else: kwargs['extra']['logid'] = self.logid_dict[current_thread().ident] else: # in main thread if 'extra' not in kwargs: kwargs['extra'] = {'logid': 'main-' + str(uuid.uuid4().int & (1 << 64) - 1)} else: kwargs['extra']['logid'] = 'main-' + str(uuid.uuid4().int & (1 << 64) - 1) return msg, kwargs def _setup_logging(): log_level = os.environ.get("APPBUILDER_LOGLEVEL", "INFO") log_level = log_level.strip().lower() if log_level not in ["debug", "info", "warning", "error"]: raise ValueError("expected APPBUILDER_LOGLEVEL in [debug, info, warning, error], but got %s" % log_level) return LoggerWithLoggerId(logging.getLogger('appbuilder'), {'logid': ''}, log_level.upper()) def get_logger(name, level=logging.INFO): """ Get logger from logging with given name, level and format without setting logging basicConfig. Args: name (str): The logger name. level (logging.LEVEL): The base level of the logger fmt (str): Format of logger output Returns: logging.Logger: logging logger with given settings Examples: .. code-block:: python logger = log_helper.get_logger(__name__, logging.INFO, fmt='%(asctime)s-%(levelname)s: %(message)s') """ logger = logging.getLogger(name) logger.setLevel(level) handler = logging.StreamHandler(sys.stdout) formatter = logging.Formatter( fmt='%(asctime)s: %(filename)s:%(lineno)d %(message)s', datefmt='%Y-%m-%d %H:%M:%S') handler.setFormatter(formatter) logger.addHandler(handler) # stop propagate for propagating may print # log multiple times logger.propagate = False return logger logger = _setup_logging() ================================================ FILE: python/utils/model_util.py ================================================ # Copyright (c) 2023 Baidu, Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import json import proto from typing import Optional, MutableSequence from pydantic import BaseModel, Field from appbuilder.utils.func_utils import deprecated import appbuilder from appbuilder.core._client import HTTPClient from appbuilder.utils.trace.tracer_wrapper import list_trace r"""模型名称到简称的映射. """ # Note(chengmo): 模型名称到简称的映射,是一个1:n的映射关系,之前的假设是模型与简称一一对应 # 实际上,模型名称和简称之间存在多对一的关系,因此这里不能仅使用一个字典来存储名称映射信息 model_name_mapping = [ ("ERNIE-Bot 4.0", "eb-4"), ("ERNIE-Bot", "eb"), ("ERNIE-Bot-turbo", "eb-turbo"), ("EB-turbo-AppBuilder专用版", "eb-turbo-appbuilder"), ("EB-turbo-AppBuilder专用版", "ernie_speed_appbuilder"), ] class RemoteModel(object): r"""远程模型类,用于封装远程模型的名称信息. 参数: name(str): 模型名称。 short_name(str): 模型简称, 可能存在多个 """ def __init__(self, remote_name: str): self.remote_name = remote_name self.short_names = [] def register_short_name(self, short_name: str): r"""注册模型简称. 参数: short_name(str): 模型简称。 """ if short_name not in self.short_names: self.short_names.append(short_name) def get_remote_name_by_short_name(self, short_name: str) -> Optional[str]: r"""根据模型简称获取模型名称. 参数: short_name(str): 模型简称。 """ # TODO(chengmo): 使用logging 替换 print,解决print多次的问题 if short_name == "eb-turbo-appbuilder": print("Deprecate warning: model [eb-turbo-appbuilder] is deprecated, please use [DeepSeek-V3.1]") if short_name in self.short_names: return self.remote_name return None class RemoteModelCollector(): r"""远程模型收集器,用于收集远程模型信息. 是一个全局单例 有两个核心功能: 1、注册远程模型名和本地short_name 2、根据short_name获取远程模型名 """ _instance = None _initialized = False def __init__(self): if self._initialized: return self._initialized = True self.remote_models = {} def __new__(cls, *args, **kwargs): """ 单例模式 """ if cls._instance is None: cls._instance = object.__new__(cls) return cls._instance def register_remote_model_name(self, remote_name: str, short_name: str): r"""注册远程模型名和本地short_name. 参数: remote_name(str): 远程模型名称。 short_name(str): 模型简称。 """ if remote_name not in self.remote_models: self.remote_models[remote_name] = RemoteModel(remote_name) self.remote_models[remote_name].register_short_name(short_name) def get_remote_name_by_short_name(self, short_name: str) -> Optional[str]: r"""根据short_name获取远程模型名. 参数: short_name(str): 模型简称。 """ for remote_model in self.remote_models.values(): remote_name = remote_model.get_remote_name_by_short_name(short_name) if remote_name is not None: return remote_name return None remote_model_collector = RemoteModelCollector() for remote_name, short_name in model_name_mapping: remote_model_collector.register_remote_model_name(remote_name, short_name) class GetModelListRequest(proto.Message): r"""获取模型列表请求体 参数: apiTypefilter(str): 根据apiType过滤,["chat", "completions", "embeddings", "text2image"],不填包括所有的。 """ apiTypefilter: MutableSequence[str] = proto.RepeatedField( proto.STRING, number=1 ) class GetModelListResponse(proto.Message): r"""获取模型列表返回体 参数: request_id(str): 网关层的请求ID. log_id(str): 请求ID。 success(bool): 是否成功的返回。 error_code(int): 错误码。 error_msg(str): 错误信息。 result(ModelListResult): 模型列表。 """ request_id: str = proto.Field( proto.STRING, number=1, ) log_id: str = proto.Field( proto.STRING, number=2, ) success: bool = proto.Field( proto.BOOL, number=3, ) error_code: int = proto.Field( proto.INT32, number=4, ) error_msg: str = proto.Field( proto.STRING, number=5, ) result: "ModelListResult" = proto.Field( proto.MESSAGE, number=6, message="ModelListResult", ) class ModelListResult(proto.Message): r"""模型列表 参数: common(ModelData): 预置服务模型信息。 custom(ModelData): 自定义服务模型信息。 """ common: MutableSequence["ModelData"] = proto.RepeatedField( proto.MESSAGE, number=1, message="ModelData", ) custom: MutableSequence["ModelData"] = proto.RepeatedField( proto.MESSAGE, number=2, message="ModelData", ) class ModelData(proto.Message): r"""模型基本信息 参数: name(str): 服务名称。 url(int): 服务endpoint。 apiType(str): 服务类型:chat、completions、embeddings、text2image。 chargeStatus(int): 付费状态。 versionList(int): 服务版本列表。 """ name: str = proto.Field( proto.STRING, number=1, ) url: str = proto.Field( proto.STRING, number=2, ) apiType: str = proto.Field( proto.STRING, number=3, ) chargeStatus: str = proto.Field( proto.STRING, number=4, ) versionList: MutableSequence["Version"] = proto.RepeatedField( proto.MESSAGE, number=5, message="Version", ) class Version(proto.Message): r"""服务版本 参数: id(str): 服务版本id,仅自定义服务有该字段。 aiModelId(str): 发布该服务版本的模型id,仅自定义服务有该字段。 aiModelVersionId(str): 发布该服务版本的模型版本id,仅自定义服务有该字段。 trainType(str): 服务基础模型类型。 serviceStatus(str): 服务状态。 """ id: str = proto.Field( proto.STRING, number=1, ) aiModelId: str = proto.Field( proto.STRING, number=2, ) aiModelVersionId: str = proto.Field( proto.STRING, number=3, ) trainType: str = proto.Field( proto.STRING, number=4, ) serviceStatus: str = proto.Field( proto.STRING, number=5, ) class GetModelListRequestV2(BaseModel): """ 获取模型列表v2请求体 参数: refresh_type(str): 获取模型列表的方式:["tolerant", "original"] force_refresh(bool): 是否强制刷新缓存 """ refresh_type: str = Field(default="tolerant") force_refresh: bool = Field(default=False) class BaseModelInfo(BaseModel): serviceId: str = Field() name: str = Field() url: str = Field() serviceType: str = Field() chargeStatus: str = Field() protocolVersion: int = Field() supportedProtocolVersions: Optional[list] = Field(default=[2]) marker: Optional[str] = None maxContextTokens: Optional[int] = None maxInputTokens: Optional[int] = None maxOutputTokens: Optional[int] = None reasoningModel: Optional[bool] = Field() supportsSearch: Optional[bool] = Field() class CommonModelV2(BaseModelInfo, extra='allow'): """ 预置模型信息 """ isPublic: bool = Field() chargeType: str = Field() modelCallName: Optional[str] = None class CustomModelV2(BaseModelInfo, extra='allow'): """ 定制模型信息 """ runStatus: str = Field() baseModel: str = Field() modelId: str = Field() modelCallName: Optional[str] = None class GetModelListResponseResult(BaseModel): """ 获取模型列表v2返回的result字段 参数: common(list): 预置模型 custom(list): 定制模型 """ common: list[CommonModelV2] = Field(default=[]) custom: list[CustomModelV2] = Field(default=[]) class GetModelListResponseV2(BaseModel): """ 获取模型列表的响应 参数: code: int message: str result: dict, 响应结果,包含预置模型和定制模型 """ code: int = Field(default=0) message: str = Field(default="") result: GetModelListResponseResult = Field(default={}) class Models: r""" 模型工具类,提供模型列表接口。 """ def __init__(self, client: HTTPClient = None, secret_key: Optional[str] = None, gateway: str = "" ): r"""Models初始化方法. 参数: client(obj:`HTTPClient`): 客户端实例,用于发送请求。 secret_key(str,可选): 用户鉴权token, 默认从环境变量中获取: os.getenv("APPBUILDER_TOKEN", ""). gateway(str, 可选): 后端网关服务地址,默认从环境变量中获取: os.getenv("GATEWAY_URL", "") 返回: 无 """ self.http_client = client or HTTPClient(secret_key, gateway) @list_trace @deprecated(version="1.1.0") def list(self, request: GetModelListRequest = None, timeout: float = None, retry: int = 0) -> GetModelListResponse: """ 返回用户的模型列表信息。 参数: request (obj:`GetModelListRequest`):模型列表查询请求体。 timeout (float, 可选): 请求的超时时间。 retry (int, 可选): 请求的重试次数。 返回: obj:`GetModelListResponse`: 模型列表返回体。 """ url = self.http_client.service_url("/v1/bce/wenxinworkshop/service/list") if request is None: request = GetModelListRequest() data = GetModelListRequest.to_json(request) headers = self.http_client.auth_header() headers['content-type'] = 'application/json' if retry != self.http_client.retry.total: self.http_client.retry.total = retry response = self.http_client.session.post(url, data=data, headers=headers, timeout=timeout) self.http_client.check_response_header(response) data = response.json() self.http_client.check_response_json(data) request_id = self.http_client.response_request_id(response) self.__class__._check_service_error(request_id, data) response = GetModelListResponse.from_json(payload=json.dumps(data), ignore_unknown_fields=True) response.request_id = request_id return response def list_v2(self, request: GetModelListRequestV2 = None, timeout: float = None, retry: int = 0) -> GetModelListResponseV2: """ 返回用户的模型列表信息。 参数: request (obj:`GetModelListRequest`):模型列表查询请求体。 timeout (float, 可选): 请求的超时时间。 retry (int, 可选): 请求的重试次数。 返回: obj:`GetModelListResponseV2`: 模型列表返回体。 """ url = self.http_client.service_url( prefix = "/api/v1/ai_engine/copilot_engine", sub_path= "/v1/api/workspace/qianfan_models_v2/user" ) if request is None: request = GetModelListRequestV2() data = GetModelListRequestV2.model_validate(request) headers = self.http_client.auth_header() headers['content-type'] = 'application/json' if retry != self.http_client.retry.total: self.http_client.retry.total = retry response = self.http_client.session.post(url, data=data.model_dump_json(), headers=headers, timeout=timeout) self.http_client.check_response_header(response) data = response.json() self.http_client.check_response_json(data) request_id = self.http_client.response_request_id(response) self.__class__._check_service_error(request_id, data) response = GetModelListResponseV2.model_validate(data) return response @staticmethod def _check_service_error(request_id: str, data: dict): r"""服务response参数检查 参数: data (dict) : body返回 返回: 无 """ if "error_code" in data and "error_msg" in data: if data["error_code"] != 0: raise appbuilder.AppBuilderServerException( request_id=request_id, service_err_code=data["error_code"], service_err_message=data["error_msg"]) ================================================ FILE: python/utils/sse_util.py ================================================ # Copyright (c) 2023 Baidu, Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """ SSE Client util """ from appbuilder.utils.logger_util import logger import logging import aiohttp class SSEClient: """ 一个简易的SSE Client,用于接收服务端发送的SSE事件。 """ def __init__(self, event_source, char_enc="utf-8"): """ 通过现有的事件源初始化 SSE 客户端。 事件源应为二进制流,并具有 close() 方法。 这通常是实现 io.BinaryIOBase 的东西,比如 httplib 或 urllib3HTTPResponse 对象。 """ logger.debug(f"Initialized SSE client from event source {event_source}") self._event_source = event_source self._char_enc = char_enc def _read(self): """ 读取传入的事件源流并生成事件块。 不幸的是,有些服务器可能会决定在响应中将事件分解为多个HTTP块。 因此,有必要正确地将连续的响应块缝合在一起,并找到SSE分隔符(空的新行),以生成完整、正确的事件块。 """ data = b"" for chunk in self._event_source: for line in chunk.splitlines(True): data += line if data.endswith((b"\r\r", b"\n\n", b"\r\n\r\n")): yield data data = b"" if data: yield data def events(self): """ 从给定的输入流中读取 Server-Side-Event (SSE) 数据,并生成解析后的 Event 对象。 Args: 无 Returns: generator: 解析后的 Event 对象的生成器。 """ for chunk in self._read(): event = Event() # Split before decoding so splitlines() only uses \r and \n for line in chunk.splitlines(): # Decode the line. line = line.decode(self._char_enc) # Lines starting with a separator are comments and are to be # ignored. if not line.strip() or line.startswith(":"): continue logger.debug(f"raw line: {line}") data = line.split(":", 1) field = data[0] # Ignore unknown fields. if field not in event.__dict__: event.raw += line logger.debug( f"Saw invalid field {field} while parsing Server Side Event" ) continue if len(data) > 1: # From the spec: # "If value starts with a single U+0020 SPACE character, # remove it from value." if data[1].startswith(" "): value = data[1][1:] else: value = data[1] else: # If no value is present after the separator, # assume an empty value. value = "" # The data field may come over multiple lines and their values # are concatenated with each other. if field == "data": event.__dict__[field] += value + "\n" event.raw += value + "\n" else: event.__dict__[field] = value event.raw += value # Events with no data are not dispatched. if not event.data: if event.raw: # unknown error pass else: continue else: # If the data field ends with a newline, remove it. if event.data.endswith("\n"): event.data = event.data[0:-1] # Empty event names default to 'message' event.event = event.event or "message" # Dispatch the event if logger.getEffectiveLevel() == logging.DEBUG: logger.debug(f"Dispatching {event.debug_str}...") else: logger.debug(f"Dispatching {event}...") yield event def close(self): """ 手动关闭事件源流。 """ self._event_source.close() class AsyncSSEClient: """ 一个简易的SSE Client,用于接收服务端发送的SSE事件。 """ def __init__(self, response, char_enc='utf-8'): """ 通过现有的事件源response初始化 SSE 客户端。 response应为aiohttp.ClientResponse实例 """ self._response = response self._char_enc = char_enc async def _read(self): """ 读取传入的事件源流并生成事件块。 """ data = b'' async for chunk in self._response.content.iter_any(): for line in chunk.splitlines(True): data += line if data.endswith((b'\r\r', b'\n\n', b'\r\n\r\n')): yield data data = b'' if data: yield data async def events(self): """ 从给定的输入流中读取 Server-Side-Event (SSE) 数据,并生成解析后的 Event 对象。 Returns: generator: 解析后的 Event 对象的生成器。 """ async for chunk in self._read(): event = Event() # Split before decoding so splitlines() only uses \r and \n for line in chunk.splitlines(): # Decode the line. line = line.decode(self._char_enc) # Lines starting with a separator are comments and are to be ignored. if not line.strip() or line.startswith(':'): continue data = line.split(':', 1) field = data[0] # Ignore unknown fields. if field not in event.__dict__: event.raw += line continue if len(data) > 1: # From the spec: # "If value starts with a single U+0020 SPACE character, # remove it from value." if data[1].startswith(' '): value = data[1][1:] else: value = data[1] else: # If no value is present after the separator, # assume an empty value. value = '' # The data field may come over multiple lines and their values are concatenated with each other. if field == 'data': event.__dict__[field] += value + '\n' event.raw += value + '\n' else: event.__dict__[field] = value event.raw += value # Events with no data are not dispatched. if not event.data: continue # If the data field ends with a newline, remove it. if event.data.endswith('\n'): event.data = event.data[0:-1] # Empty event names default to 'message' event.event = event.event or 'message' yield event class Event(object): """ 事件流中的事件。 """ def __init__(self, id=None, event="message", data="", retry=None): self.id = id self.event = event self.data = data self.retry = retry self.raw = "" def __str__(self): s = f"{self.event} event" if self.id: s += f" #{self.id}" if self.data: s += f", {len(self.data)} byte" else: s += ", no data" if self.retry: s += f", retry in {self.retry} ms" return s @property def debug_str(self): s = f"{self.event} event" if self.id: s += f" #{self.id}" if self.data: s += f", {len(self.data)} byte, DATA<<{self.data}>>" else: s += ", no data" if self.raw: s += f", RAW<<{self.raw}>>" else: s += ", no raw" if self.retry: s += f", retry in {self.retry} ms" return s ================================================ FILE: python/utils/trace/__init__.py ================================================ # Copyright (c) 2024 Baidu, Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. ================================================ FILE: python/utils/trace/_function.py ================================================ # Copyright (c) 2024 Baidu, Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import os import time import json import inspect from opentelemetry import trace from pydantic import BaseModel from appbuilder import Message from appbuilder import AppbuilderTraceException from appbuilder.core.component import ComponentOutput import logging logging.basicConfig(level=logging.INFO) def _time(start_time,end_time,span): """ 设置时间跨度属性为两个时间点的差值(秒)。 Args: start_time (float): 开始时间的时间戳(秒为单位)。 end_time (float): 结束时间的时间戳(秒为单位)。 span (object): OpenTelemetry的Span对象,用于设置时间跨度属性。 Returns: None: 该函数不返回任何值,直接在传入的span对象上设置属性。 """ span.set_attribute('time.cost-time',str(end_time-start_time)+'s') def _build_curl_from_post(url, headers, json_body, timeout) -> str: """ 从 POST 请求参数生成 cURL 命令。 Args: url (str): 请求的 URL 地址。 headers (dict): 请求头信息,以字典形式传入。 json_body (dict): JSON 格式的请求体数据,以字典形式传入。 timeout (int, optional): 请求的超时时间(秒)。默认为 None,表示不设置超时时间。 Returns: str: 生成的 cURL 命令字符串。 """ curl = f"curl -L '{url}' \\\n" header_lines = [f"-H '{k}: {v}' \\" for k, v in headers.items() if k != 'Content-Length'] if header_lines: header_lines[-1] = header_lines[-1].rstrip(" \\") curl += "\n".join(header_lines) if json_body: body = f"'{json.dumps(json_body, ensure_ascii=False)}'" curl += f" \\\n-d {body}" if timeout is not None: curl += f" \\\n--max-time {timeout}" return curl def _post_input(args,kwargs,span): """ 使用 POST 请求发送数据并记录相关属性到 span 中。 Args: args (tuple): 元组,其中最后一个元素是发送 POST 请求的 URL。 kwargs (dict): 字典,包含以下可选参数: - headers (dict): HTTP 请求头,以字典形式表示。 - json (dict, optional): 发送的 JSON 数据体,默认为 None。 - timeout (int, optional): 请求超时时间(秒),默认为 None。 span (object): OpenTelemetry 的 span 对象,用于记录相关属性。 Returns: None: 该函数没有返回值,主要用于发送 POST 请求并记录相关信息。 """ url = kwargs.get('url',None) if not url: url = args[-1] curl=_build_curl_from_post( url=url, headers=kwargs['headers'], json_body=kwargs.get('json',None), timeout=kwargs.get('timeout',None), ) span.set_attribute("input.value","{}".format(curl)) def _input(args,kwargs,span): """ 将函数参数转化为字符串形式并存储在字典中,然后将字典转化为JSON字符串并设置为span的属性。 Args: args (tuple): 函数的位置参数元组。 kwargs (dict): 函数的关键字参数字典。 span (opentracing.Span): 用于记录日志的OpenTracing span对象。 Returns: None: 此函数没有返回值,主要用于设置span的属性。 Raises: 无特定异常抛出,但如果在处理参数或设置span属性时发生异常,将打印异常信息。 """ input_dict={} type_name = (bool,str,bytes,int,float,list,dict) sig = inspect.signature(args[0]) params = sig.parameters try: if args: for idx, value in enumerate(list(args)): if isinstance(value, type_name): input_dict[list(params)[idx-1]] = str(value) elif isinstance(value, Message): input_dict[list(params)[idx-1]] = str(value) for key, value in dict(kwargs).items(): if isinstance(value, type_name): input_dict[key] = value elif isinstance(value, Message): input_dict[key] = str(value) if input_dict: if os.environ.get('OPENINFERENCE_TRACE','true') == 'true' and os.environ.get('SENTRY_DSN', None): span.set_data("input-value",json.dumps(input_dict, ensure_ascii=False)) else: span.set_attribute("input.value",json.dumps(input_dict, ensure_ascii=False)) except Exception as e: raise AppbuilderTraceException(e) def _client_tool_trace_output_deep_iterate(output,span): """ 对输出进行深度遍历,并将结果以JSON格式记录到span的属性中 Args: output (dict, bool, str, bytes, int, float, list): 需要遍历的输出对象 span (Span): 用于记录输出结果的span对象 Returns: None """ input_dict={} type_name = (bool,str,bytes,int,float,list) if isinstance(output, dict): for key, value in output.items(): if isinstance(value, type_name): input_dict[key] = str(value) span.set_attribute("output.value",json.dumps(input_dict, ensure_ascii=False)) else: if isinstance(output, type_name): span.set_attribute("output.value",str(output)) def _client_trace_generator(generator, tracer, parent_context): """ 用于生成客户端跟踪信息的生成器函数。 Args: generator (Iterator): 消息生成器。 tracer (Tracer): OpenTelemetry 追踪器实例。 parent_context (SpanContext): 父级上下文。 Returns: Generator: 带有跟踪信息的消息生成器。 """ with tracer.start_as_current_span('AppBuilderClient-Stream-RUN', context = parent_context) as span: span.set_attribute("openinference.span.kind", 'agent') result_str = '' prompt_tokens = 0 completion_tokens = 0 total_tokens = 0 run_list = [] try: new_span = tracer.start_span('Client-Stream') for message in generator: new_span.set_attribute("openinference.span.kind", 'agent') context_message_str = "" has_reference = False context_message_list = None if hasattr(message, 'events') and message.events and hasattr(message.events[0], 'detail') and message.events[0].detail: context_message_list = message.events[0].detail.get('references', None) if context_message_list: for context_message in context_message_list: for context_message_key, context_message_value in context_message.items(): context_message_str += '{}: {}\n'.format(context_message_key, context_message_value) has_reference = True context_message_str += '\n' if has_reference: new_span.set_attribute("input.value", 'Context(上下文) For RAG:\n{}'.format(context_message_str)) new_span.set_attribute("output.value", "{}".format(message.model_dump_json(indent=4))) result_str += str(message.answer) if hasattr(message, 'events') and message.events and hasattr(message.events[0], 'event_type') and hasattr(message.events[0], 'status'): run_list.append('{}[status:{}]'.format(message.events[0].event_type, message.events[0].status)) if hasattr(message, 'events') and message.events and hasattr(message.events[0], 'usage') and message.events[0].usage: prompt_tokens = message.events[0].usage.prompt_tokens completion_tokens = message.events[0].usage.completion_tokens total_tokens = message.events[0].usage.total_tokens new_span.end() new_span = tracer.start_span('Client-Stream') yield message except Exception as e: raise AppbuilderTraceException(str(e)) finally: span.set_attribute("output.value", result_str) span.set_attribute("llm.token_count.prompt", prompt_tokens) span.set_attribute("llm.token_count.completion", completion_tokens) span.set_attribute("llm.token_count.total", total_tokens) span.set_attribute("Agent-Running-Process", '==>'.join(run_list)) def _client_run_trace_stream(tracer, func, *args, **kwargs): """ 跟踪客户端运行流处理函数,并记录相关的跟踪信息。 Args: tracer (Tracer): OpenTelemetry Tracer 实例,用于生成和设置 span。 func (Callable[..., Any]): 客户端运行的函数,通常是一个返回流处理结果的函数。 *args: 可变位置参数,传递给 func 的参数。 **kwargs: 可变关键字参数,传递给 func 的参数。 Returns: Any: 函数的返回值,通常是一个包含流处理结果的响应对象。 """ with tracer.start_as_current_span('AppBuilderClient-Stream-RUN', context=None) as parent_span: parent_context = trace.set_span_in_context(parent_span) parent_span.set_attribute("openinference.span.kind", 'Agent') start_time = time.time() result = func(*args, **kwargs) _input(args=args, kwargs=kwargs, span=parent_span) generator = result.content result.content = _client_trace_generator(generator=generator, tracer=tracer, parent_context=parent_context) end_time = time.time() _time(start_time=start_time, end_time=end_time, span=parent_span) return result def _client_run_trace_un_stream(tracer, func, *args, **kwargs): """ 执行函数func,并追踪其运行过程,同时记录相关性能指标和事件信息。 Args: tracer (Any): 追踪器对象,用于开始、结束和设置span属性。 func (Callable[..., Any]): 要执行的函数。 *args: 可变位置参数,传递给func的参数。 **kwargs: 可变关键字参数,传递给func的参数。 Returns: Any: 函数func的返回值。 """ with tracer.start_as_current_span('AppBuilderClient-RUN') as span: start_time = time.time() result = func(*args, **kwargs) span.set_attribute("openinference.span.kind", 'Agent') _input(args=args, kwargs=kwargs, span=span) run_list = [] prompt_tokens = 0 completion_tokens = 0 total_tokens = 0 span.set_attribute("output.value", result.content.answer) events = result.content.events for event in events: run_list.append('{}[status:{}]'.format(event.event_type, event.status)) if hasattr(event, 'usage') and event.usage and hasattr(event.usage, 'prompt_tokens'): prompt_tokens = event.usage.prompt_tokens completion_tokens = event.usage.completion_tokens total_tokens = event.usage.total_tokens if total_tokens: span.set_attribute("llm.token_count.prompt", prompt_tokens) span.set_attribute("llm.token_count.completion", completion_tokens) span.set_attribute("llm.token_count.total", total_tokens) span.set_attribute("Agent-Running-Process", '==>'.join(run_list)) end_time = time.time() _time(start_time=start_time, end_time=end_time, span=span) return result def _output(output, span): """ 将输出值转换为字符串并设置到span的属性中 Args: output (Any): 待输出的值,可以是任意类型,但如果是BaseModel或其子类或类对象,将使用model_dump_json方法进行序列化 span (Span): Jaeger的Span对象,用于记录跟踪信息 Returns: None: 此函数不返回任何值,但会将输出值转换为字符串并设置到span的属性中 Raises: 无: 此函数不引发任何异常 """ type_name = (bool,str,bytes,int,float,list,dict) if isinstance(output, BaseModel) or inspect.isclass(output): span.set_attribute("output.value", "{}".format(output.model_dump_json(indent=4))) elif isinstance(output, type_name): _client_tool_trace_output_deep_iterate(output=output,span=span) def _tool_name(args): """ 根据传入的函数或方法对象,返回其工具名称。 Args: args (tuple): 包含单个元素的元组,该元素为函数或方法对象。 Returns: str: 返回字符串,表示函数或方法的工具名称。 - 如果函数或方法是类的实例方法,则返回形如"类名-方法名"的字符串。 - 如果函数或方法不是类的实例方法,则直接返回函数或方法名。 """ class_name = args[0].__qualname__.split('.')[0] function_name = args[0].__name__ if class_name == function_name: return "{}".format(function_name) else: return "{}-{}".format(class_name,function_name) def _assistant_output(output, span): """ 设置span的属性,将output的模型转储为JSON格式的字符串并赋值给span的output.value属性。 Args: output (Any): 任意类型的数据,预期是包含模型转储功能的对象。 span (Span): 用于设置属性的span对象。 Returns: None: 该函数不返回任何值,而是通过修改span对象来实现功能。 """ span.set_attribute("output.value", "{}".format(output.model_dump_json(indent=4))) def _assistant_stream_run_with_handler_output(generator , tracer, parent_context): """ 执行带有处理函数输出的辅助流。 Args: generator (Generator): 一个生成器,用于产生消息。 tracer (Tracer): OpenTelemetry 追踪器实例。 parent_context (Context): 父级上下文,用于追踪的上下文。 Returns: Generator: 一个生成器,产生消息并可能包含额外的输出信息。 """ with tracer.start_as_current_span("Assistant-stream_run_with_handler", context=parent_context) as span: span.set_attribute("openinference.span.kind",'Agent') result = '' output_list = [] try: new_span = tracer.start_span('Assistant-Stream_run_with_handler') for message in generator: new_span.set_attribute("openinference.span.kind",'agent') if isinstance(message, BaseModel): new_span.set_attribute("output.value", "{}".format(message.model_dump_json(indent=4))) else: new_span.set_attribute("output.value", "{}".format(json.dumps(message, ensure_ascii=False))) if hasattr(message, 'content') and message.content and message.content[0]: if hasattr(message.content[0], 'text') and message.content[0].text: if hasattr(message.content[0].text, 'value') and message.content[0].text.value: output_list.append(message.content[0].text.value) new_span.end() new_span = tracer.start_span('Assistant-Stream_run_with_handler') yield message except Exception as e: raise AppbuilderTraceException(str(e)) finally: new_span.set_attribute("output.value",'流式运行结束') new_span.set_attribute("openinference.span.kind",'agent') new_span.end() for item in output_list: result += str(item) span.set_attribute("output.value", result) def _assistant_stream_output(output, span, tracer): """ 处理流式输出,并生成追踪信息。 Args: output (Iterator[Any]): 流式输出数据的迭代器。 span (Span): 追踪信息的Span对象。 tracer (Tracer): 追踪信息的Tracer对象。 Returns: List[Any]: 存储所有输出消息的列表。 """ result = '' run_list = [] generator_list = [] if output: new_span = tracer.start_span('Assistant-Stream_run') for message in output: generator_list.append(message) new_span.set_attribute("openinference.span.kind",'agent') if message.event == "status": new_span.set_attribute("output.value", "{}".format(message.model_dump_json(indent=4))) elif message.event == "message": new_span.set_attribute("output.value", "{}".format(message.model_dump_json(indent=4))) if hasattr(message, 'content') and message.content and hasattr(message.content[0], 'text') and message.content[0].text and hasattr(message.content[0].text, 'value'): run_list.append(message.content[0].text.value) new_span.end() new_span = tracer.start_span('Assistant-Stream_run') for item in run_list: result += str(item) new_span.set_attribute("output.value",'流式输出结束\n输出结果为:{}'.format(result)) new_span.set_attribute("openinference.span.kind",'agent') new_span.end() span.set_attribute("output.value",result) return generator_list def _components_run_output(output, span): """ 设置span的属性以记录输出信息。 Args: output (Any): 运行组件后得到的输出对象,需要包含 `token_usage` 属性(如果存在)。 span (Span): Jaeger中的span对象,用于记录追踪信息。 Returns: None: 此函数不返回任何值,而是直接修改span对象的属性。 """ if hasattr(output, 'token_usage') and output.token_usage: span.set_attribute("llm.token_count.prompt", output.token_usage.get('prompt_tokens', 0)) span.set_attribute("llm.token_count.completion", output.token_usage.get('completion_tokens', 0)) span.set_attribute("llm.token_count.total", output.token_usage.get('total_tokens', 0)) span.set_attribute("output.value", "{}".format(output.model_dump_json(indent=4))) def _post_trace(tracer, func, *args, **kwargs): """ 对指定的HTTP POST请求函数进行追踪,并生成追踪信息。 Args: tracer (Any): 追踪器实例,用于开始和结束追踪。 func (Callable[..., Any]): 需要被追踪的HTTP POST请求函数。 *args: 可变位置参数,用于传递给func函数。 **kwargs: 可变关键字参数,用于传递给func函数。 Returns: Any: func函数的返回值。 """ url = args[-1] if not isinstance(url, str): url = kwargs.get('url','') method = url.split('/')[-1] with tracer.start_as_current_span("HTTP-POST: {}".format(method)) as new_span: start_time = time.time() result=func(*args, **kwargs) end_time = time.time() new_span.set_attribute("openinference.span.kind",'tool') _time(start_time = start_time,end_time = end_time,span = new_span) _post_input(args = args, kwargs = kwargs,span = new_span) return result def _client_run_trace(tracer, func, *args, **kwargs): """ 在客户端运行跟踪函数,根据参数决定是否以流模式执行 Args: tracer (Any): 跟踪器实例 func (Callable): 需要跟踪的函数 *args (tuple): 函数的可变位置参数 **kwargs (dict): 函数的可变关键字参数 Returns: Any: 跟踪函数的执行结果,根据stream参数的值,返回_client_run_trace_stream或_client_run_trace_un_stream的返回值 Raises: 无特定异常,但可能抛出在执行函数时发生的任何异常 """ sig = inspect.signature(args[0]) params = sig.parameters stream = False if args: for idx, value in enumerate(list(args)): if list(params)[idx-1] == 'stream': stream = value if kwargs: for key, value in dict(kwargs).items(): if key == 'stream': stream = value if stream: return _client_run_trace_stream(tracer, func, *args, **kwargs) if not stream: return _client_run_trace_un_stream(tracer, func, *args, **kwargs) def _client_tool_trace(tracer, func, *args, **kwargs): """ 追踪客户端工具函数的调用,记录相关信息到追踪器。 Args: tracer (Any): 追踪器实例,用于创建和记录追踪信息。 func (Callable[..., Any]): 要追踪的客户端工具函数。 *args (Any): 传递给func的位置参数。 **kwargs (Any): 传递给func的关键字参数。 Returns: Any: func函数执行后的返回值。 """ with tracer.start_as_current_span(_tool_name(args=args)) as new_span: start_time = time.time() result=func(*args, **kwargs) end_time = time.time() _time(start_time = start_time,end_time = end_time,span = new_span) new_span.set_attribute("openinference.span.kind",'tool') _output(output=result, span = new_span) return result def _assistant_tool_trace(tracer, func, *args, **kwargs): """ 对给定的函数进行追踪,记录其执行的时间、输入和输出。 Args: tracer: OpenTelemetry的Tracer实例,用于创建span。 func: 需要追踪的函数。 *args: 传递给func的位置参数。 **kwargs: 传递给func的关键字参数。 Returns: func的返回值。 """ span_name = _tool_name(args=args) with tracer.start_as_current_span(span_name) as new_span: start_time = time.time() result=func(*args, **kwargs) end_time = time.time() _time(start_time = start_time,end_time = end_time,span = new_span) _input(args = args, kwargs = kwargs, span=new_span) new_span.set_attribute("openinference.span.kind",'tool') if result: _output(output=result, span = new_span) return result def _assistant_run_trace(tracer, func, *args, **kwargs): """ 使用给定的追踪器(tracer)对函数(func)的执行进行追踪。 Args: tracer (object): 追踪器对象,用于创建和操作追踪的span。 func (callable): 需要被追踪的函数。 *args (tuple): 传递给func的位置参数。 **kwargs (dict): 传递给func的关键字参数。 Returns: Any: 被追踪函数func的返回值。 """ with tracer.start_as_current_span("Assistant-RUN") as new_span: start_time = time.time() result=func(*args, **kwargs) end_time = time.time() _time(start_time = start_time,end_time = end_time,span = new_span) new_span.set_attribute("openinference.span.kind",'Agent') _input(args = args, kwargs = kwargs, span=new_span) _assistant_output(output=result, span = new_span) return result def _assistant_stream_trace(tracer, func, *args, **kwargs): """ 为辅助流跟踪的函数提供跟踪功能。 Args: tracer (Tracer): OpenTelemetry 的 Tracer 实例,用于生成和操作跟踪数据。 func (Callable): 需要进行流跟踪的函数。 *args: 传递给 func 的位置参数。 **kwargs: 传递给 func 的关键字参数。 Returns: Generator[Any, None, None]: 一个生成器,生成 func 函数的执行结果。 """ with tracer.start_as_current_span("Assistant-stream_run") as span: start_time = time.time() result=func(*args, **kwargs) span.set_attribute("openinference.span.kind",'Agent') _input(args = args, kwargs = kwargs, span=span) run_list = [] new_span = tracer.start_span("Assistant-stream_run") for message in result: new_span.set_attribute("openinference.span.kind",'agent') if message.event == "status": new_span.set_attribute("output.value", "{}".format(message.model_dump_json(indent=4))) elif message.event == "message": new_span.set_attribute("output.value", "{}".format(message.model_dump_json(indent=4))) if hasattr(message, 'content') and message.content and hasattr(message.content[0], 'text') and message.content[0].text and hasattr(message.content[0].text, 'value'): run_list.append(message.content[0].text.value) new_span.end() new_span = tracer.start_span('Assistant-Stream_run') yield message end_time = time.time() _time(start_time = start_time,end_time = end_time,span = span) result_str = ''.join(str(res) for res in run_list) span.set_attribute("output.value",result_str) def _assistant_stream_run_with_handler_trace(tracer, func, *args, **kwargs): """ 在带有追踪器的上下文中运行函数,并捕获函数执行过程中的输入和输出,以及耗时。 Args: tracer (Tracer): Jaeger等追踪器实例,用于追踪函数调用过程中的事件。 func (Callable): 要执行的函数。 *args: 可变位置参数,传递给func的参数。 **kwargs: 可变关键字参数,传递给func的参数。 Returns: Any: 函数func的返回值。 """ with tracer.start_as_current_span("Assistant-stream_run_with_handler", context=None) as span: parent_context = trace.set_span_in_context(span) span.set_attribute("openinference.span.kind",'Agent') start_time = time.time() result=func(*args, **kwargs) _input(args = args, kwargs = kwargs, span=span) if result: if hasattr(result, '_event_handler') and result._event_handler: event_handler = result._event_handler if hasattr(event_handler, '_iterator') and event_handler._iterator: generator = event_handler._iterator event_handler._iterator = _assistant_stream_run_with_handler_output(generator = generator, tracer = tracer, parent_context=parent_context) end_time = time.time() _time(start_time = start_time,end_time = end_time,span = span) return result def _components_run_trace_with_opentelemetry(tracer, func, *args, **kwargs): """ 使用opentelemetry追踪组件运行过程 Args: tracer (opentelemetry.trace.Tracer): OpenTelemetry追踪器对象 func (callable): 需要追踪的函数 *args: 任意数量的位置参数,用于调用func **kwargs: 任意数量的关键字参数,用于调用func Returns: Any: func函数的返回值 """ with tracer.start_as_current_span(_tool_name(args=args)) as new_span: start_time = time.time() result=func(*args, **kwargs) end_time = time.time() _time(start_time = start_time,end_time = end_time,span = new_span) new_span.set_attribute("openinference.span.kind",'tool') _input(args = args, kwargs = kwargs, span=new_span) _components_run_output(output=result, span = new_span) return result def _components_run_trace_with_sentry(func, *args, **kwargs): """ 使用 Sentry SDK 进行跟踪的函数装饰器。 Args: func: 被装饰的函数对象。 *args: 被装饰函数的参数,可变长度。 **kwargs: 被装饰函数的命名参数,可变长度。 Returns: 函数 func 的执行结果。 """ try: import sentry_sdk except: raise ImportError("sentry-sdk is not installed.") with sentry_sdk.start_span(op=_tool_name(args=args), description=_tool_name(args=args)) as new_span: new_span.set_data("Span-kind", "Components-RUN") result=func(*args, **kwargs) _input(args = args, kwargs = kwargs, span=new_span) return result def _components_stream_run_trace_with_opentelemetry(tracer, func, *args, **kwargs): """ 使用OpenTelemetry跟踪器追踪组件流运行过程 Args: tracer (opentelemetry.trace.Tracer): OpenTelemetry跟踪器实例 func (callable): 组件流函数 *args: 组件流函数所需位置参数 **kwargs: 组件流函数所需关键字参数 Returns: Generator: 组件流函数返回值的生成器 """ with tracer.start_as_current_span(_tool_name(args = args)) as span: start_time = time.time() span.set_attribute("openinference.span.kind",'tool') _input(args = args, kwargs = kwargs, span=span) run_list = [] for item in func(*args, **kwargs): with tracer.start_as_current_span('Component-Stream') as new_span: new_span.set_attribute("openinference.span.kind",'tool') if isinstance(item, ComponentOutput): new_span.set_attribute("output.value", "{}".format(item.model_dump_json(indent=4))) else: new_span.set_attribute("output.value", "{}".format(json.dumps(item, ensure_ascii=False))) if isinstance(item, dict): run_list.append(item.get('text', None)) else: run_list.append(str(item)) yield item end_time = time.time() _time(start_time = start_time,end_time = end_time,span = span) if run_list: result_str = ''.join(str(res) for res in run_list) span.set_attribute("output.value",result_str) else: span.set_attribute("output.value","流式运行结束") def _components_stream_run_trace_with_sentry(func, *args, **kwargs): """ 通过sentry追踪函数运行时的信息。 Args: func (callable): 要执行的函数。 *args: 可变位置参数,传入func的参数。 **kwargs: 可变关键字参数,传入func的参数。 Returns: Generator: 返回一个生成器,每次迭代返回func的一个返回值。 """ try: import sentry_sdk except: raise ImportError("sentry-sdk is not installed.") with sentry_sdk.start_span(op=_tool_name(args=args), description=_tool_name(args=args)) as span: span.set_data("Span-kind", "Components-Tool-Eval") _input(args = args, kwargs = kwargs, span=span) run_list = [] for item in func(*args, **kwargs): with sentry_sdk.start_span(op=_tool_name(args=args), description=_tool_name(args=args)) as new_span: new_span.set_data("Span-kind",'tool') if isinstance(item, ComponentOutput): new_span.set_data("output.value", "{}".format(item.model_dump_json(indent=4))) else: new_span.set_data("output-value", "{}".format(json.dumps(item, ensure_ascii=False))) if isinstance(item, dict): text = item.get('text', None) run_list.append(text) else: run_list.append(str(item)) yield item if run_list: result_str = ''.join(str(res) for res in run_list) span.set_data("output-value",result_str) else: span.set_data("output-value","流式运行结束") def _list_trace(tracer, func, *args, **kwargs): """ 使用给定的tracer对函数func进行追踪,并记录相关信息到span中。 Args: tracer (OpenTelemetryTracer): 用于追踪的tracer对象。 func (Callable[..., Any]): 需要被追踪的函数。 *args: 传递给func的位置参数。 **kwargs: 传递给func的关键字参数。 Returns: Any: 调用func的返回结果。 """ with tracer.start_as_current_span(_tool_name(args = args)) as new_span: result=func(*args, **kwargs) new_span.set_attribute("openinference.span.kind",'tool') new_span.set_attribute("input.value",_tool_name(args = args)) new_span.set_attribute("output.value",str(result)) return result ================================================ FILE: python/utils/trace/phoenix_wrapper.py ================================================ # Copyright (c) 2024 Baidu, Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import os import argparse import time from typing import Optional parser = argparse.ArgumentParser() parser.add_argument("--host", type=str, default="127.0.0.1", help="phoenix服务的url地址") parser.add_argument("--port", type=int, default=8080, help="phoenix服务的端口号") parser.add_argument("--timeout", type=float, default=None, help="phoenix服务的运行时间,不填写则为常驻服务,单位为秒") def launch_phoenix(host: Optional[str] = "127.0.0.1", port: Optional[int] = 8080, **kwargs): """ 启动Phoenix Launch Phoenix """ try: import phoenix except ModuleNotFoundError: raise ImportError( "尚未安装phoenix组件,尝试使用 python3 -m pip install arize-phoenix==4.5.0 -i https://pypi.tuna.tsinghua.edu.cn/simple 安装该组件") session = phoenix.launch_app(**kwargs) return session def stop_phoenix(delete_data:bool=False): """ 停止Phoenix Stop Phoenix """ try: import phoenix except ModuleNotFoundError: raise ImportError( "尚未安装phoenix组件,尝试使用 python3 -m pip install arize-phoenix==4.5.0 -i https://pypi.tuna.tsinghua.edu.cn/simple 安装该组件") phoenix.stop_app(delete_data) def runtime_main(): """ 运行主程序 Run main program """ args = parser.parse_args() os.environ['PHOENIX_PORT'] = str(args.port) os.environ['PHOENIX_HOST'] = args.host timeout = args.timeout print(" Launching AppBuilder Tracer Server By Phoenix... ") print(" Arguments: ", args) session = launch_phoenix() while True: if timeout is not None: time.sleep(timeout) break time.sleep(1) stop_phoenix() if __name__ == "__main__": runtime_main() ================================================ FILE: python/utils/trace/tracer.py ================================================ # Copyright (c) 2024 Baidu, Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import os from importlib import import_module from opentelemetry import trace from opentelemetry.instrumentation.instrumentor import BaseInstrumentor from opentelemetry.sdk.trace import TracerProvider from opentelemetry.exporter.otlp.proto.http.trace_exporter import OTLPSpanExporter from opentelemetry.sdk.trace.export import ( SpanExporter, SimpleSpanProcessor, ConsoleSpanExporter ) from wrapt import wrap_function_wrapper from appbuilder.utils.trace._function import( _post_trace, _client_run_trace, _client_tool_trace, _assistant_tool_trace, _assistant_run_trace, _assistant_stream_trace, _assistant_stream_run_with_handler_trace, _components_run_trace_with_opentelemetry, _components_run_trace_with_sentry, _components_stream_run_trace_with_opentelemetry, _components_stream_run_trace_with_sentry, _list_trace, ) from appbuilder import logger _MODULE_1 = 'appbuilder' _MODULE_2 = 'appbuilder-sdk-ext' class AppbuilderInstrumentor(BaseInstrumentor): """ Instrumentor for appbuilder and appbuilder-sdk-ext. """ _instance = None _instrumented = False def __new__(cls, *args, **kwargs): if cls._instance is None: cls._instance = super().__new__(cls) return cls._instance __slots__ = ( "_original_session_post", '_original_client_run', '_original_client_tool', '_original_assistant_tool', '_original_assistant_run', '_original_assistant_stream_run', '_original_assistant_stream_run_with_handler', '_orignal_components_run', '_original_components_stream_run', '_original_list', ) def instrumentation_dependencies(self): pass def _instrument(self, **kwargs): """ 为指定模块的函数添加跟踪功能。 Args: **kwargs: 可选参数,用于提供跟踪器提供程序。 Returns: None Raises: ImportError: 如果从文件中缺少`run_trace`、`tool_eval_streaming_trace`和`assistant_trace`方法,则引发此异常。 Exception: 如果未找到`appbuilder`和`appbuilder-sdk-ext`模块,则引发此异常。 """ if self._instrumented: return self._instrumented = True # 判断是否启用Sentry跟踪,如果启用,则创建虚拟的的Tracer,仅对Components组件生效 if os.environ.get('ENABLE_SENTRY_TRACE', None) == 'true' and os.environ.get('SENTRY_DSN', None): try: import sentry_sdk except: raise ImportError("sentry-sdk is not installed.") self.sentry_trace = True else: self.sentry_trace = False if self.sentry_trace: tracer = None else: if not (tracer_provider := kwargs.get("tracer_provider")): tracer_provider = trace.get_tracer_provider() tracer = trace.get_tracer( instrumenting_module_name=__name__, tracer_provider=tracer_provider, ) # 保存原始函数的引用 try: from .tracer_wrapper import ( session_post_func, client_run_trace_func, client_tool_trace_func, assistent_tool_trace_func, assistant_run_trace_func, assistent_stream_run_trace_func, assistant_stream_run_with_handler_trace_func, components_run_trace_func, components_run_stream_trace_func, list_trace_func, ) self._original_session_post = session_post_func self._original_client_run = client_run_trace_func self._original_client_tool = client_tool_trace_func self._original_assistant_tool = assistent_tool_trace_func self._original_assistant_run = assistant_run_trace_func self._original_assistant_stream_run = assistent_stream_run_trace_func self._original_assistant_stream_run_with_handler = assistant_stream_run_with_handler_trace_func self._orignal_components_run = components_run_trace_func self._original_components_stream_run = components_run_stream_trace_func self._original_list = list_trace_func except: raise ImportError( "Please check if the run_trace, tool_eval_streaming_trace, and assistant_trace methods are missing from the file.") # 保证trace对appbuilder与appbuilder-sdk-ext的兼容性 try: appbuilder = import_module(_MODULE_1) except: appbuilder = None def _appbuilder_session_post(wrapped, instance, args, kwargs): return _post_trace(tracer, self._original_session_post, *args, **kwargs) def _appbuilder_client_run_trace(wrapped, instance, args, kwargs): return _client_run_trace(tracer, self._original_client_run, *args, **kwargs) def _appbuilder_client_tool_trace(wrapped, instance, args, kwargs): return _client_tool_trace(tracer, self._original_client_tool, *args, **kwargs) def _appbuilder_assistant_tool_trace(wrapped, instance, args, kwargs): return _assistant_tool_trace(tracer, self._original_assistant_tool, *args, **kwargs) def _appbuilder_assistant_run_trace(wrapped, instance, args, kwargs): return _assistant_run_trace(tracer, self._original_assistant_run, *args, **kwargs) def _appbuilder_assistant_stream_run_trace(wrapped, instance, args, kwargs): return _assistant_stream_trace(tracer, self._original_assistant_stream_run, *args, **kwargs) def _appbuilder_assistant_stream_run_with_handler_trace(wrapped, instance, args, kwargs): return _assistant_stream_run_with_handler_trace(tracer, self._original_assistant_stream_run_with_handler, *args, **kwargs) def _appbuilder_components_run_trace(wrapped, instance, args, kwargs): return _components_run_trace_with_opentelemetry(tracer, self._orignal_components_run, *args, **kwargs) def _appbuilder_components_run_trace_with_sentry(wrapped, instance, args, kwargs): return _components_run_trace_with_sentry(self._orignal_components_run, *args, **kwargs) def _appbuilder_components_run_stream_trace(wrapped, instance, args, kwargs): return _components_stream_run_trace_with_opentelemetry(tracer, self._original_components_stream_run, *args, **kwargs) def _appbuilder_components_run_stream_trace_with_sentry(wrapped, instance, args, kwargs): return _components_stream_run_trace_with_sentry(self._original_components_stream_run, *args, **kwargs) def _appbuilder_list_trace(wrapped, instance, args, kwargs): return _list_trace(tracer, self._original_list, *args, **kwargs) # 引用相关函数并替换 if appbuilder: if not self.sentry_trace: wrap_function_wrapper( module = _MODULE_1, name='utils.trace.tracer_wrapper.session_post_func', wrapper=_appbuilder_session_post ) wrap_function_wrapper( module = _MODULE_1, name = 'utils.trace.tracer_wrapper.client_run_trace_func', wrapper= _appbuilder_client_run_trace ) wrap_function_wrapper( module = _MODULE_1, name = 'utils.trace.tracer_wrapper.client_tool_trace_func', wrapper = _appbuilder_client_tool_trace ) wrap_function_wrapper( module= _MODULE_1, name = 'utils.trace.tracer_wrapper.assistent_tool_trace_func', wrapper= _appbuilder_assistant_tool_trace ) wrap_function_wrapper( module= _MODULE_1, name = 'utils.trace.tracer_wrapper.assistant_run_trace_func', wrapper= _appbuilder_assistant_run_trace ) wrap_function_wrapper( module= _MODULE_1, name = 'utils.trace.tracer_wrapper.assistent_stream_run_trace_func', wrapper= _appbuilder_assistant_stream_run_trace ) wrap_function_wrapper( module= _MODULE_1, name = 'utils.trace.tracer_wrapper.assistant_stream_run_with_handler_trace_func', wrapper= _appbuilder_assistant_stream_run_with_handler_trace ) wrap_function_wrapper( module= _MODULE_1, name = 'utils.trace.tracer_wrapper.list_trace_func', wrapper= _appbuilder_list_trace ) wrap_function_wrapper( module= _MODULE_1, name = 'utils.trace.tracer_wrapper.components_run_trace_func', wrapper= _appbuilder_components_run_trace ) wrap_function_wrapper( module= _MODULE_1, name = 'utils.trace.tracer_wrapper.components_run_stream_trace_func', wrapper= _appbuilder_components_run_stream_trace ) else: wrap_function_wrapper( module= _MODULE_1, name = 'utils.trace.tracer_wrapper.components_run_trace_func', wrapper= _appbuilder_components_run_trace_with_sentry ) wrap_function_wrapper( module= _MODULE_1, name = 'utils.trace.tracer_wrapper.components_run_stream_trace_func', wrapper= _appbuilder_components_run_stream_trace_with_sentry ) if not appbuilder: raise Exception("appbuilder not found") def _uninstrument(self): """ 恢复原始函数,移除之前添加的追踪代码。 Args: 无参数。 Returns: 无返回值。 Raises: 无异常抛出,但如果在尝试恢复原始函数时遇到任何问题,将打印一条错误消息"appbuilder not found"。 """ # 恢复原始函数 try: from appbuilder.utils.trace.tracer_wrapper import ( session_post_func, client_run_trace_func, client_tool_trace_func, assistent_tool_trace_func, assistant_run_trace_func, assistant_stream_run_with_handler_trace_func, components_run_trace_func, components_run_stream_trace_func, list_trace_func, ) session_post_func = self._original_session_post client_run_trace_func = self._original_client_run client_tool_trace_func = self._original_client_tool assistent_tool_trace_func = self._original_assistant_tool assistant_run_trace_func = self._original_assistant_run assistant_stream_run_with_handler_trace_func = self._original_assistant_stream_run_with_handler components_run_trace_func = self._orignal_components_run components_run_stream_trace_func = self._original_components_stream_run list_trace_func = self._original_list except: print("appbuilder not found") def create_tracer_provider(enable_phoenix: bool = True, enable_console: bool = False, host: str = "127.0.0.1", port: int = 8080, method: str = "/v1/traces"): """ 创建一个用于跟踪的TracerProvider对象,并可选择性地添加span处理器,以便将跟踪数据发送到指定的端点或控制台。 Args: enable_phoenix (bool, optional): 是否启用Phoenix,以在本地可视化界面展示trace数据。默认为True。 enable_console (bool, optional): 是否启用控制台输出,以在控制台展示trace数据。默认为False。 host (str, optional): Phoenix可视化界面的主机地址。默认为"127.0.0.1"。 port (int, optional): Phoenix可视化界面的端口号。默认为8080。 method (str, optional): Phoenix可视化界面的请求路径。默认为"/v1/traces"。 Returns: TracerProvider: 创建的TracerProvider对象,可用于创建跟踪的Span对象。 """ tracer_provider = TracerProvider() if enable_phoenix: # 将trace数据在本地可视化界面展示 endpoint = f"{host}:{port}{method}" logger.info("OTLPSpanExporter endpoint: {}".format(endpoint)) tracer_provider.add_span_processor( SimpleSpanProcessor(OTLPSpanExporter(endpoint))) if enable_console: # 将trace数据在控制台展示 tracer_provider.add_span_processor( SimpleSpanProcessor(ConsoleSpanExporter())) return tracer_provider class AppBuilderTracer(): _instance = None _trace_start = False def __new__(cls, *args, **kwargs): if cls._instance is None: cls._instance = super().__new__(cls) return cls._instance def __init__(self, enable_phoenix: bool = True, enable_console: bool = False, host: str = "http://localhost", port: int = 8080, method="/v1/traces") -> None: """ 初始化函数,用于设置追踪系统相关参数。 Args: enable_phoenix (bool, optional): 是否启用Phoenix服务。默认为True。 enable_console (bool, optional): 是否启用控制台输出。默认为False。 host (str, optional): 可视化追踪系统服务的地址。默认为"http://localhost"。 port (int, optional): 可视化追踪系统服务的端口号。默认为8080。 method (str, optional): 可视化追踪系统服务的方法路径。默认为"/v1/traces"。 Returns: None: 无返回值。 """ self._tracer_provider = create_tracer_provider( enable_phoenix=enable_phoenix, enable_console=enable_console, host=host, port=port, method=method ) self._instrumentor = AppbuilderInstrumentor() @property def tracer_provider(self): return self._tracer_provider @property def instrumentor(self): return self._instrumentor def add_custom_processor(self, processor): self._tracer_provider.add_span_processor(processor) def start_trace(self): if self._trace_start: return logger.info("AppBuilder Starting trace...") os.environ["APPBUILDER_SDK_TRACE_ENABLE"] = "true" self._instrumentor._instrument(tracer_provider=self._tracer_provider) def end_trace(self): logger.info("AppBuilder Ending trace...") del os.environ["APPBUILDER_SDK_TRACE_ENABLE"] self._instrumentor._uninstrument() def __enter__(self): self.start_trace() return self def __exit__(self, exc_type, exc_val, exc_tb): self.end_trace() ================================================ FILE: python/utils/trace/tracer_wrapper.py ================================================ # Copyright (c) 2024 Baidu, Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import os import sys import traceback #import _testcapi from functools import wraps def _whether_enable_trace(): if os.environ.get('ENABLE_SENTRY_TRACE', None) == 'true' and os.environ.get('SENTRY_DSN', None): return True elif os.environ.get('APPBUILDER_SDK_TRACE_ENABLE', None) == 'true': return True else: return False def session_post_func(func, *args, **kwargs): return func(*args, **kwargs) def client_run_trace_func(func, *args, **kwargs): return func(*args, **kwargs) def client_tool_trace_func(func, *args, **kwargs): return func(*args, **kwargs) def assistent_tool_trace_func(func, *args, **kwargs): return func(*args, **kwargs) def assistant_run_trace_func(func, *args, **kwargs): return func(*args, **kwargs) def assistant_stream_run_with_handler_trace_func(func, *args, **kwargs): return func(*args, **kwargs) def assistent_stream_run_trace_func(func, *args, **kwargs): return func(*args, **kwargs) def components_run_trace_func(func, *args, **kwargs): return func(*args, **kwargs) def components_run_stream_trace_func(func, *args, **kwargs): return func(*args, **kwargs) def list_trace_func(func, *args, **kwargs): return func(*args, **kwargs) def session_post(func): """ 将指定的函数装饰为使用 session_post_func 发送 POST 请求的函数。 Args: func (Callable): 被装饰的函数。 Returns: Callable: 返回一个新的函数,该函数会在被调用时通过 session_post_func 发送 POST 请求。 Raises: Exception: 如果在发送 POST 请求时发生异常,并且环境变量 APPBUILDER_TRACE_DEBUG 被设置为 "true",则直接抛出异常; 否则,尝试捕获异常并生成自定义的异常信息后抛出。 Note: 如果环境变量 APPBUILDER_TRACE_DEBUG 被设置为 "true",则在发生异常时将直接抛出原始异常。 否则,会尝试过滤掉与 "appbuilder/utils/trace" 相关的堆栈跟踪,并生成自定义的异常信息后抛出。 如果在生成自定义异常信息的过程中发生异常,则会直接抛出原始异常。 """ @wraps(func) def wrapper(*args, **kwargs): if _whether_enable_trace(): try: return session_post_func(func, *args, **kwargs) except Exception as e: if os.getenv("APPBUILDER_TRACE_DEBUG", "None").lower() == "true": raise else: exc_type, exc_value, exc_traceback = sys.exc_info() tb = traceback.extract_tb(exc_traceback) filtered_tb = [frame for frame in tb if "appbuilder/utils/trace" not in frame.filename] formatted_lines = traceback.format_list(filtered_tb) formatted_lines += traceback.format_exception_only(exc_type, exc_value) custom_traceback = ''.join(formatted_lines) exception_type = type(e) try: try: exception_type('\n'+custom_traceback) except Exception: raise e from None raise exception_type('\n'+custom_traceback) from None except: tp, exc, tb = sys.exc_info() #_testcapi.set_exc_info(tp, exc, tb.tb_next) del tp, exc, tb raise else: try: return func(*args, **kwargs) except: tp, exc, tb = sys.exc_info() #_testcapi.set_exc_info(tp, exc, tb.tb_next) del tp, exc, tb raise return wrapper def client_run_trace(func): """ 对传入的函数进行装饰,添加客户端运行跟踪功能。 Args: func (callable): 需要被装饰的函数。 Returns: callable: 返回一个包装后的函数,该函数在执行时会调用 client_run_trace_func 函数, 并传入原始函数及其参数。 Raises: Exception: 如果在发送 POST 请求时发生异常,并且环境变量 APPBUILDER_TRACE_DEBUG 被设置为 "true",则直接抛出异常; 否则,尝试捕获异常并生成自定义的异常信息后抛出。 Note: 如果环境变量 APPBUILDER_TRACE_DEBUG 被设置为 "true",则在发生异常时将直接抛出原始异常。 否则,会尝试过滤掉与 "appbuilder/utils/trace" 相关的堆栈跟踪,并生成自定义的异常信息后抛出。 如果在生成自定义异常信息的过程中发生异常,则会直接抛出原始异常。 """ @wraps(func) def wrapper(*args, **kwargs): if _whether_enable_trace(): try: return client_run_trace_func(func, *args, **kwargs) except Exception as e: if os.getenv("APPBUILDER_TRACE_DEBUG", "None").lower() == "true": raise else: exc_type, exc_value, exc_traceback = sys.exc_info() tb = traceback.extract_tb(exc_traceback) filtered_tb = [frame for frame in tb if "appbuilder/utils/trace" not in frame.filename] formatted_lines = traceback.format_list(filtered_tb) formatted_lines += traceback.format_exception_only(exc_type, exc_value) custom_traceback = ''.join(formatted_lines) exception_type = type(e) try: try: exception_type('\n'+custom_traceback) except Exception: raise e from None raise exception_type('\n'+custom_traceback) from None except: tp, exc, tb = sys.exc_info() # _testcapi.set_exc_info(tp, exc, tb.tb_next) del tp, exc, tb raise else: try: return func(*args, **kwargs) except: tp, exc, tb = sys.exc_info() # _testcapi.set_exc_info(tp, exc, tb.tb_next) del tp, exc, tb raise return wrapper def client_tool_trace(func): """ 装饰器函数,用于跟踪客户端工具函数的调用情况。 Args: func (callable): 需要被跟踪的函数。 Returns: callable: 返回一个装饰器函数,该函数会调用原函数并记录相关信息。 Raises: Exception: 如果在发送 POST 请求时发生异常,并且环境变量 APPBUILDER_TRACE_DEBUG 被设置为 "true",则直接抛出异常; 否则,尝试捕获异常并生成自定义的异常信息后抛出。 Note: 如果环境变量 APPBUILDER_TRACE_DEBUG 被设置为 "true",则在发生异常时将直接抛出原始异常。 否则,会尝试过滤掉与 "appbuilder/utils/trace" 相关的堆栈跟踪,并生成自定义的异常信息后抛出。 如果在生成自定义异常信息的过程中发生异常,则会直接抛出原始异常。 """ @wraps(func) def wrapper(*args, **kwargs): if _whether_enable_trace(): try: return client_tool_trace_func(func, *args, **kwargs) except Exception as e: if os.getenv("APPBUILDER_TRACE_DEBUG", "None").lower() == "true": raise else: exc_type, exc_value, exc_traceback = sys.exc_info() tb = traceback.extract_tb(exc_traceback) filtered_tb = [frame for frame in tb if "appbuilder/utils/trace" not in frame.filename] formatted_lines = traceback.format_list(filtered_tb) formatted_lines += traceback.format_exception_only(exc_type, exc_value) custom_traceback = ''.join(formatted_lines) exception_type = type(e) try: try: exception_type('\n'+custom_traceback) except Exception: raise e from None raise exception_type('\n'+custom_traceback) from None except: tp, exc, tb = sys.exc_info() # _testcapi.set_exc_info(tp, exc, tb.tb_next) del tp, exc, tb raise else: try: return func(*args, **kwargs) except: tp, exc, tb = sys.exc_info() # _testcapi.set_exc_info(tp, exc, tb.tb_next) del tp, exc, tb raise return wrapper def assistent_tool_trace(func): """ 用于辅助追踪函数执行情况的装饰器。 Args: func (Callable[..., Any]): 需要被装饰的函数,接受任意数量和类型的参数。 Returns: Callable[..., Any]: 返回一个函数,该函数会在调用原函数前后记录一些信息, 然后将原函数的返回值返回。 Raises: Exception: 如果在发送 POST 请求时发生异常,并且环境变量 APPBUILDER_TRACE_DEBUG 被设置为 "true",则直接抛出异常; 否则,尝试捕获异常并生成自定义的异常信息后抛出。 Note: 如果环境变量 APPBUILDER_TRACE_DEBUG 被设置为 "true",则在发生异常时将直接抛出原始异常。 否则,会尝试过滤掉与 "appbuilder/utils/trace" 相关的堆栈跟踪,并生成自定义的异常信息后抛出。 如果在生成自定义异常信息的过程中发生异常,则会直接抛出原始异常。 """ @wraps(func) def wrapper(*args, **kwargs): if _whether_enable_trace(): try: return assistent_tool_trace_func(func, *args, **kwargs) except Exception as e: if os.getenv("APPBUILDER_TRACE_DEBUG", "None").lower() == "true": raise else: exc_type, exc_value, exc_traceback = sys.exc_info() tb = traceback.extract_tb(exc_traceback) filtered_tb = [frame for frame in tb if "appbuilder/utils/trace" not in frame.filename] formatted_lines = traceback.format_list(filtered_tb) formatted_lines += traceback.format_exception_only(exc_type, exc_value) custom_traceback = ''.join(formatted_lines) exception_type = type(e) try: try: exception_type('\n'+custom_traceback) except Exception: raise e from None raise exception_type('\n'+custom_traceback) from None except: tp, exc, tb = sys.exc_info() # _testcapi.set_exc_info(tp, exc, tb.tb_next) del tp, exc, tb raise else: try: return func(*args, **kwargs) except: tp, exc, tb = sys.exc_info() # _testcapi.set_exc_info(tp, exc, tb.tb_next) del tp, exc, tb raise return wrapper def assistant_run_trace(func): """ 对函数进行装饰,用于在函数执行前后进行日志跟踪。 Args: func (Callable): 需要进行日志跟踪的函数。 Returns: Callable: 经过装饰后,带有日志跟踪功能的函数。 Raises: Exception: 如果在发送 POST 请求时发生异常,并且环境变量 APPBUILDER_TRACE_DEBUG 被设置为 "true",则直接抛出异常; 否则,尝试捕获异常并生成自定义的异常信息后抛出。 Note: 如果环境变量 APPBUILDER_TRACE_DEBUG 被设置为 "true",则在发生异常时将直接抛出原始异常。 否则,会尝试过滤掉与 "appbuilder/utils/trace" 相关的堆栈跟踪,并生成自定义的异常信息后抛出。 如果在生成自定义异常信息的过程中发生异常,则会直接抛出原始异常。 """ @wraps(func) def wrapper(*args, **kwargs): if _whether_enable_trace(): try: return assistant_run_trace_func(func, *args, **kwargs) except Exception as e: if os.getenv("APPBUILDER_TRACE_DEBUG", "None").lower() == "true": raise else: exc_type, exc_value, exc_traceback = sys.exc_info() tb = traceback.extract_tb(exc_traceback) filtered_tb = [frame for frame in tb if "appbuilder/utils/trace" not in frame.filename] formatted_lines = traceback.format_list(filtered_tb) formatted_lines += traceback.format_exception_only(exc_type, exc_value) custom_traceback = ''.join(formatted_lines) exception_type = type(e) try: try: exception_type('\n'+custom_traceback) except Exception: raise e from None raise exception_type('\n'+custom_traceback) from None except: tp, exc, tb = sys.exc_info() # _testcapi.set_exc_info(tp, exc, tb.tb_next) del tp, exc, tb raise else: try: return func(*args, **kwargs) except: tp, exc, tb = sys.exc_info() # _testcapi.set_exc_info(tp, exc, tb.tb_next) del tp, exc, tb raise return wrapper def assistent_stream_run_trace(func): """ 对目标函数进行包装,以启用辅助流执行追踪功能。 Args: func (Callable): 需要包装的目标函数,必须是一个可调用的对象。 Returns: Callable: 包装后的函数对象,调用时将执行辅助流执行追踪,并返回目标函数的执行结果。 Raises: Exception: 如果在发送 POST 请求时发生异常,并且环境变量 APPBUILDER_TRACE_DEBUG 被设置为 "true",则直接抛出异常; 否则,尝试捕获异常并生成自定义的异常信息后抛出。 Note: 如果环境变量 APPBUILDER_TRACE_DEBUG 被设置为 "true",则在发生异常时将直接抛出原始异常。 否则,会尝试过滤掉与 "appbuilder/utils/trace" 相关的堆栈跟踪,并生成自定义的异常信息后抛出。 如果在生成自定义异常信息的过程中发生异常,则会直接抛出原始异常。 """ @wraps(func) def wrapper(*args, **kwargs): if _whether_enable_trace(): try: return assistent_stream_run_trace_func(func, *args, **kwargs) except Exception as e: if os.getenv("APPBUILDER_TRACE_DEBUG", "None").lower() == "true": raise else: exc_type, exc_value, exc_traceback = sys.exc_info() tb = traceback.extract_tb(exc_traceback) filtered_tb = [frame for frame in tb if "appbuilder/utils/trace" not in frame.filename] formatted_lines = traceback.format_list(filtered_tb) formatted_lines += traceback.format_exception_only(exc_type, exc_value) custom_traceback = ''.join(formatted_lines) exception_type = type(e) try: try: exception_type('\n'+custom_traceback) except Exception: raise e from None raise exception_type('\n'+custom_traceback) from None except: tp, exc, tb = sys.exc_info() # _testcapi.set_exc_info(tp, exc, tb.tb_next) del tp, exc, tb raise else: try: return func(*args, **kwargs) except: tp, exc, tb = sys.exc_info() # _testcapi.set_exc_info(tp, exc, tb.tb_next) del tp, exc, tb raise return wrapper def assistent_stream_run_with_handler_trace(func): """ 为函数添加助手流运行和处理器跟踪的装饰器。 Args: func (Callable): 需要被装饰的函数,即助手流运行的入口函数。 Returns: Callable: 返回一个包装后的函数,该函数在调用时会执行assistant_stream_run_with_handler_trace_func函数, 并将原始函数func及其参数传递给它。 Raises: Exception: 如果在发送 POST 请求时发生异常,并且环境变量 APPBUILDER_TRACE_DEBUG 被设置为 "true",则直接抛出异常; 否则,尝试捕获异常并生成自定义的异常信息后抛出。 Note: 如果环境变量 APPBUILDER_TRACE_DEBUG 被设置为 "true",则在发生异常时将直接抛出原始异常。 否则,会尝试过滤掉与 "appbuilder/utils/trace" 相关的堆栈跟踪,并生成自定义的异常信息后抛出。 如果在生成自定义异常信息的过程中发生异常,则会直接抛出原始异常。 """ @wraps(func) def wrapper(*args, **kwargs): if _whether_enable_trace(): try: return assistant_stream_run_with_handler_trace_func(func, *args, **kwargs) except Exception as e: if os.getenv("APPBUILDER_TRACE_DEBUG", "None").lower() == "true": raise else: exc_type, exc_value, exc_traceback = sys.exc_info() tb = traceback.extract_tb(exc_traceback) filtered_tb = [frame for frame in tb if "appbuilder/utils/trace" not in frame.filename] formatted_lines = traceback.format_list(filtered_tb) formatted_lines += traceback.format_exception_only(exc_type, exc_value) custom_traceback = ''.join(formatted_lines) exception_type = type(e) try: try: exception_type('\n'+custom_traceback) except Exception: raise e from None raise exception_type('\n'+custom_traceback) from None except: tp, exc, tb = sys.exc_info() # _testcapi.set_exc_info(tp, exc, tb.tb_next) del tp, exc, tb raise else: try: return func(*args, **kwargs) except: tp, exc, tb = sys.exc_info() # _testcapi.set_exc_info(tp, exc, tb.tb_next) del tp, exc, tb raise return wrapper def components_run_trace(func): """ 为函数添加组件运行跟踪的装饰器。 Args: func (Callable[..., Any]): 需要添加跟踪的函数。 Returns: Callable[..., Any]: 装饰后的函数,当被调用时,会调用 components_run_trace_func 并传入原始函数和参数。 Raises: Exception: 如果在发送 POST 请求时发生异常,并且环境变量 APPBUILDER_TRACE_DEBUG 被设置为 "true",则直接抛出异常; 否则,尝试捕获异常并生成自定义的异常信息后抛出。 Note: 如果环境变量 APPBUILDER_TRACE_DEBUG 被设置为 "true",则在发生异常时将直接抛出原始异常。 否则,会尝试过滤掉与 "appbuilder/utils/trace" 相关的堆栈跟踪,并生成自定义的异常信息后抛出。 如果在生成自定义异常信息的过程中发生异常,则会直接抛出原始异常。 """ @wraps(func) def wrapper(*args, **kwargs): if _whether_enable_trace(): try: return components_run_trace_func(func, *args, **kwargs) except Exception as e: if os.getenv("APPBUILDER_TRACE_DEBUG", "None").lower() == "true": raise else: exc_type, exc_value, exc_traceback = sys.exc_info() tb = traceback.extract_tb(exc_traceback) filtered_tb = [frame for frame in tb if "appbuilder/utils/trace" not in frame.filename] formatted_lines = traceback.format_list(filtered_tb) formatted_lines += traceback.format_exception_only(exc_type, exc_value) custom_traceback = ''.join(formatted_lines) exception_type = type(e) try: try: exception_type('\n'+custom_traceback) except Exception: raise e from None raise exception_type('\n'+custom_traceback) from None except: tp, exc, tb = sys.exc_info() # _testcapi.set_exc_info(tp, exc, tb.tb_next) del tp, exc, tb raise else: try: return func(*args, **kwargs) except: tp, exc, tb = sys.exc_info() # _testcapi.set_exc_info(tp, exc, tb.tb_next) del tp, exc, tb raise return wrapper def components_run_stream_trace(func): """ 为给定的函数添加流追踪功能,用于追踪函数内部组件的运行情况。 Args: func (callable): 需要添加流追踪功能的函数。 Returns: callable: 返回一个装饰器函数,当被装饰的函数被调用时,会执行流追踪功能。 Raises: Exception: 如果在发送 POST 请求时发生异常,并且环境变量 APPBUILDER_TRACE_DEBUG 被设置为 "true",则直接抛出异常; 否则,尝试捕获异常并生成自定义的异常信息后抛出。 Note: 如果环境变量 APPBUILDER_TRACE_DEBUG 被设置为 "true",则在发生异常时将直接抛出原始异常。 否则,会尝试过滤掉与 "appbuilder/utils/trace" 相关的堆栈跟踪,并生成自定义的异常信息后抛出。 如果在生成自定义异常信息的过程中发生异常,则会直接抛出原始异常。 """ @wraps(func) def wrapper(*args, **kwargs): if _whether_enable_trace(): try: return components_run_stream_trace_func(func, *args, **kwargs) except Exception as e: if os.getenv("APPBUILDER_TRACE_DEBUG", "None").lower() == "true": raise else: exc_type, exc_value, exc_traceback = sys.exc_info() tb = traceback.extract_tb(exc_traceback) filtered_tb = [frame for frame in tb if "appbuilder/utils/trace" not in frame.filename] formatted_lines = traceback.format_list(filtered_tb) formatted_lines += traceback.format_exception_only(exc_type, exc_value) custom_traceback = ''.join(formatted_lines) exception_type = type(e) try: try: exception_type('\n'+custom_traceback) except Exception: raise e from None raise exception_type('\n'+custom_traceback) from None except: tp, exc, tb = sys.exc_info() # _testcapi.set_exc_info(tp, exc, tb.tb_next) del tp, exc, tb raise else: try: return func(*args, **kwargs) except: tp, exc, tb = sys.exc_info() # _testcapi.set_exc_info(tp, exc, tb.tb_next) del tp, exc, tb raise return wrapper def list_trace(func): """ 为函数添加列表追踪的装饰器。 Args: func (Callable[..., Any]): 需要被装饰的函数,接受任意数量和类型的参数。 Returns: Callable[..., Any]: 返回一个装饰器函数,该函数在被调用时会执行原始函数并记录相关信息。 Raises: Exception: 如果在发送 POST 请求时发生异常,并且环境变量 APPBUILDER_TRACE_DEBUG 被设置为 "true",则直接抛出异常; 否则,尝试捕获异常并生成自定义的异常信息后抛出。 Note: 如果环境变量 APPBUILDER_TRACE_DEBUG 被设置为 "true",则在发生异常时将直接抛出原始异常。 否则,会尝试过滤掉与 "appbuilder/utils/trace" 相关的堆栈跟踪,并生成自定义的异常信息后抛出。 如果在生成自定义异常信息的过程中发生异常,则会直接抛出原始异常。 """ @wraps(func) def wrapper(*args, **kwargs): if _whether_enable_trace(): try: return list_trace_func(func, *args, **kwargs) except Exception as e: if os.getenv("APPBUILDER_TRACE_DEBUG", "None").lower() == "true": raise else: exc_type, exc_value, exc_traceback = sys.exc_info() tb = traceback.extract_tb(exc_traceback) filtered_tb = [frame for frame in tb if "appbuilder/utils/trace" not in frame.filename] formatted_lines = traceback.format_list(filtered_tb) formatted_lines += traceback.format_exception_only(exc_type, exc_value) custom_traceback = ''.join(formatted_lines) exception_type = type(e) try: try: exception_type('\n'+custom_traceback) except Exception: raise e from None raise exception_type('\n'+custom_traceback) from None except: tp, exc, tb = sys.exc_info() # _testcapi.set_exc_info(tp, exc, tb.tb_next) del tp, exc, tb raise else: try: return func(*args, **kwargs) except: tp, exc, tb = sys.exc_info() # _testcapi.set_exc_info(tp, exc, tb.tb_next) del tp, exc, tb raise return wrapper ================================================ FILE: requirements.txt ================================================ requests proto-plus>=1.22.3 pydantic>=2.6.4 numpy openpyxl pymochow>=1.1.2 PyYAML bce-python-sdk pycryptodome opentelemetry-exporter-otlp>=1.23.0 opentelemetry-instrumentation>=0.44b0 opentelemetry-sdk>=1.23.0 opentelemetry-api>=1.23.0 pydub>=0.10.0 ffmpeg aiohttp urllib3<2.0.0 mcp==1.3.0 ================================================ FILE: setup.py ================================================ # Copyright (c) 2023 Baidu, Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """ Setup script. Authors: dongdaxiang(dongdaxiang@baidu.com) Date: 2023/12/01 11:19:24 """ import os import shutil import datetime from setuptools import setup, find_packages with open('requirements.txt') as f: requirements = f.read().splitlines() now = datetime.datetime.now() timestamp_str = now.strftime("%Y%m%d_%H%M%S") package_dir = f"appbuilder_sdk_{timestamp_str}" if not os.path.exists(package_dir): os.makedirs(package_dir) shutil.copytree("python", os.path.join(package_dir, "appbuilder")) shutil.copy("requirements.txt", package_dir) packages = find_packages(where=package_dir) package_data = {} print(packages) for package in packages: if package.startswith('appbuilder.utils'): package_data[package] = ["*.md"] serve_require = ["chainlit~=1.0.200", "flask~=2.3.2", "flask-restful==0.3.9", "arize-phoenix==4.5.0"] trace_require = ["SQLAlchemy==2.0.31"] test_require = ["python-dotenv"] langchain_require = ["langchain==0.3.0", "datamodel-code-generator==0.25.8"] mcp_require = ["mcp>=1.2.1"] all_require = serve_require + trace_require + test_require + langchain_require + mcp_require setup( name="appbuilder-sdk", # NOTE(chengmo): 修改此版本号时,请注意同时修改 __init__.py 中的 __version__ version="1.1.5", author="dongdaxiang", author_email="dongdaxiang@baidu.com", packages=packages, package_data=package_data, package_dir={'': package_dir}, install_requires=requirements, python_requires=">=3.9", extras_require={ "serve": serve_require, "trace": trace_require, "test": test_require, "langchain": langchain_require, "mcp": mcp_require, "all": all_require }, entry_points={ "console_scripts": [ "appbuilder_bce_deploy=appbuilder.utils.bce_deploy:deploy", "appbuilder_trace_server=appbuilder.utils.trace.phoenix_wrapper:runtime_main" ] }, description="百度智能云千帆AppBuilder-SDK", long_description="百度智能云千帆AppBuilder, 开箱即用的组件与框架, 高效开发你的AI原生应用, 更多信息请登录: https://appbuilder.cloud.baidu.com/", url="https://github.com/baidubce/app-builder", ) shutil.rmtree(package_dir)