### Go SDK ToolCall Example Source: https://github.com/baidubce/app-builder/blob/master/docs/Application/Agent/BasicKnowledge/agent.md This Go code demonstrates initializing the App Builder client, creating a conversation, defining a tool for weather information, running a query with the tool, and then providing the tool's output to get a final answer. Ensure you set the APPBUILDER_TOKEN and GATEWAY_URL_V2 environment variables. ```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) } ``` -------------------------------- ### Example Application List Output Source: https://github.com/baidubce/app-builder/blob/master/cookbooks/mcp/app_mcp_server.ipynb Sample output format when listing applications. ```bash 909*****-***a-****-****-*********2c93 我的Agent应用 697*****-***9-****-****-*********360b 我的Agent应用 963*****-***2-****-****-*********21d1 我的Agent应用 34f*****-***b-****-****-*********3df2 我的Agent应用 773*****-***8-****-****-*********62df 图像识别示例 ``` -------------------------------- ### Basic Usage Example Source: https://github.com/baidubce/app-builder/blob/master/docs/BasisModule/Components/landmark_recognize/README.md A Python code example demonstrating how to use the Landmark Recognition API. ```APIDOC ## Basic Usage Example ### Description This example shows how to perform landmark recognition using the provided Python SDK. ### Code Example ```python import os import requests import appbuilder # Please obtain your API key from the Qianfan AppBuilder official website. # See: 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"] = 'your_appbuilder_token' # Read sample image from BOS storage image_url = "https://bj.bcebos.com/v1/appbuilder/landmark_test.jpeg?authorization=bce-auth-v1%2FALTAKGa8m4qCUasgoljdEDAzLm%2F2024-01-11T10%3A59%3A56Z%2F-1%2Fhost%2Fc249a068c6f321b91da0d0fd629b26ded58dcac2b6a3674f32378f5eb8df1ed0" raw_image = requests.get(image_url).content # Input parameter is an image inp = appbuilder.Message(content={"raw_image": raw_image}) # Perform landmark recognition landmark_recognize = appbuilder.LandmarkRecognition() out = landmark_recognize.run(inp) # Print the recognition result print(out.content) # e.g., {"landmark": "尼罗河"} ``` ``` -------------------------------- ### Install AppBuilder SDK Source: https://github.com/baidubce/app-builder/blob/master/cookbooks/components/gbi.ipynb Install the required SDK package. ```python # !pip install appbuilder-sdk ``` -------------------------------- ### Install AppBuilder SDK with Serve Extra Source: https://github.com/baidubce/app-builder/blob/master/cookbooks/components/rag_with_baidusearch.ipynb Install the AppBuilder SDK with the 'serve' extra, which is required for using AgentRuntime to launch Chainlit pages or HTTP services. ```python !pip install 'appbuilder-sdk[serve]' ``` -------------------------------- ### Initialize and Use SimilarQuestion Source: https://github.com/baidubce/app-builder/blob/master/python/core/components/llms/similar_question/README.md Quickly start using the SimilarQuestion component by initializing it with your API token and a model. Then, pass your message to the initialized object to get similar questions. ```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: {}".format(answer.content)) ``` -------------------------------- ### Example Log Output for Knowledge Base Creation Source: https://github.com/baidubce/app-builder/blob/master/cookbooks/mcp/knowledge_base_mcp_server.ipynb This is an example of the log output when successfully creating a knowledge base using the AppBuilder SDK. ```text DEBUG:appbuilder:create knowledge base success: 909*****-***a-****-****-*********2c93 ``` -------------------------------- ### Install Python SDK Source: https://github.com/baidubce/app-builder/blob/master/cookbooks/components/agent_runtime.ipynb Install the appbuilder SDK with the necessary dependencies for AgentRuntime service components. Requires Python 3.8 or higher. ```bash pip install appbuilder-sdk 'appbuilder-sdk[serve]' ``` -------------------------------- ### Example Log Output Source: https://github.com/baidubce/app-builder/blob/master/cookbooks/mcp/baidu_map.ipynb Sample debug output generated after running the integration script. ```bash [2025-04-17 21:50:38,955.955] async_event_handler.py [line:563] DEBUG [main-11524059179509233548] Agent 非流式回答: 根据您的位置信息,北京亮马河大厦的经纬度为:**北纬39.95139408407192,东经116.47114501090634**。如果您有其他出行需求或问题,请随时告诉我,我会尽力为您提供帮助。 DEBUG:appbuilder:Agent 非流式回答: 根据您的位置信息,北京亮马河大厦的经纬度为:**北纬39.95139408407192,东经116.47114501090634**。如果您有其他出行需求或问题,请随时告诉我,我会尽力为您提供帮助。 ``` -------------------------------- ### Install Display Driver in Windows Source: https://github.com/baidubce/app-builder/blob/master/cookbooks/end2end_application/rag/qa_system_2_dialogue.ipynb This Python code snippet demonstrates how to programmatically interact with an agent to get instructions for installing a display driver in Windows. It also shows how to extract and print the name of a referenced document based on its ID from the agent's response. ```python response_message = agent.run( conversation_id = conversation_id, query="如何在windows系统中安装显示器驱动", ) print("智能客服问答助手的回复是:{} ".format(response_message.content.answer)) reference_doc_id = '2' reference_doc_name = "" for event in response_message.content.events: if event.event_type == "RAGAgent" and 'references' in event.detail: references = event.detail.get('references') for reference_doc in references: if reference_doc.get('id', '0') == reference_doc_id: reference_doc_name = reference_doc.get('document_name', '') break print("智能客服问答助手的回复中,角标 {} 对应参考文档是:{}".format(reference_doc_id, reference_doc_name)) ``` -------------------------------- ### Query Knowledge Base Example Source: https://github.com/baidubce/app-builder/blob/master/docs/BasisModule/Platform/KnowledgeBase/knowledgebase.md Demonstrates how to initialize the KnowledgeBase client and perform a query with specific pipeline configurations. ```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) ``` -------------------------------- ### Run with ToolChoice in Go Source: https://github.com/baidubce/app-builder/blob/master/docs/Application/Agent/ToolChoice/tool_choice.md Demonstrates how to set up the client and execute a request with ToolChoice using the Go SDK. ```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)) } } } ``` -------------------------------- ### GET /documents/all - Get All Documents Source: https://github.com/baidubce/app-builder/blob/master/docs/BasisModule/Platform/KnowledgeBase/knowledgebase.md Retrieves all documents from a specified knowledge base. ```APIDOC ## GET /documents/all ### Description Retrieves all documents from a specified knowledge base. ### Method GET ### Endpoint /documents/all ### Parameters #### Query Parameters - **knowledge_base_id** (string) - Required - The ID of the knowledge base. ### Response #### Success Response (200) - Returns a list of Document objects. **Document Object**: - **id** (str) - Document ID. - **name** (str) - Document name. - **created_at** (str) - Document creation timestamp. - **word_count** (int) - Number of words in the document. - **enabled** (bool) - Whether the document is enabled. - **meta** (DocumentMeta) - Document metadata, including source, file_id, url, mime_type, and file_size. ### Request Example ```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) doc_list = my_knowledge.get_all_documents(my_knowledge_base_id) for message in doc_list: print(message) ``` ``` -------------------------------- ### Create and Prepare Service Directory Source: https://github.com/baidubce/app-builder/blob/master/cookbooks/advanced_application/cloud_deploy.ipynb This command creates the 'sample' directory and the 'sample.py' file within it, as specified in the 'local_dir' configuration. ```bash # 创建配置中的local_dir目录 mkdir sample touch sample/sample.py ``` -------------------------------- ### Install AppBuilder-SDK Source: https://github.com/baidubce/app-builder/blob/master/NEW_README.md Install or upgrade the AppBuilder-SDK using pip. Ensure Python version is 3.9+. ```bash python3 -m pip install --upgrade appbuilder-sdk ``` -------------------------------- ### Initialize and Run RAG in Go Source: https://github.com/baidubce/app-builder/blob/master/docs/Application/RAG/BasicKnowledge/rag.md Demonstrates configuring the SDK, initializing the RAG instance, and iterating through the streaming response until completion. ```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) } } ``` -------------------------------- ### Initialize App Builder Client Source: https://github.com/baidubce/app-builder/blob/master/docs/Application/Agent/BasicKnowledge/agent.md Demonstrates how to create a new instance of the App Builder Client with necessary configuration. ```APIDOC ## NewAppBuilderClient() ### Description Initializes a new App Builder Client. ### Method `NewAppBuilderClient(app_id string, config SDKConfig)` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```go client := NewAppBuilderClient("your_app_id", sdkConfig) ``` ### Response #### Success Response (200) - **client** (AppBuilderClient) - An initialized App Builder client instance. #### Response Example None ``` -------------------------------- ### Install AppBuilder SDK Dependencies Source: https://github.com/baidubce/app-builder/blob/master/cookbooks/mcp/app_mcp_server.ipynb Install the necessary Python packages to enable AppBuilder-SDK and MCP support. ```bash !python3 -m pip install httpx appbuilder-sdk mcp ``` -------------------------------- ### Initialize and Execute NL2Sql Source: https://github.com/baidubce/app-builder/blob/master/cookbooks/components/gbi.ipynb Example of initializing NL2Sql with a custom prompt template and executing a 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("-----------------") print(f"llm result: {nl2sql_result_message5.content.llm_result}") ``` -------------------------------- ### Non-Streaming Call Example Source: https://github.com/baidubce/app-builder/blob/master/docs/Application/Agent/BasicKnowledge/agent.md Example demonstrating how to perform a non-streaming call to the AppBuilderClient's run method. ```Python import appbuilder import os # Please go to the Qianfan AppBuilder official website to create a key. See: https://cloud.baidu.com/doc/AppBuilder/s/Olq6grrt6#1%E3%80%81%E5%88%9B%E5%BB%BA%E5%AF%86%E9%92%A5 # Set environment variables os.environ["APPBUILDER_TOKEN"] = 'YOUR_APPBUILDER_TOKEN' app_id = 'YOUR_APP_ID' # Published AppBuilder application ID, can be found in the console # Initialize the agent builder = appbuilder.AppBuilderClient(app_id) # Create a conversation conversation_id = builder.create_conversation() # Run the conversation (non-streaming) out = builder.run(conversation_id, "北京今天天气怎么样") # Print the conversation result print(out.content.answer) ``` -------------------------------- ### Go ToolChoice Example Source: https://github.com/baidubce/app-builder/blob/master/docs/BasisModule/Platform/Application/appbuilder_client.md This Go code demonstrates how to initialize the App Builder client, create a conversation, and make a tool call using ToolChoice. Ensure that the 'APPBUILDER_TOKEN' and 'GATEWAY_URL_V2' environment variables are set, and replace placeholder values for 'appID' with your actual application ID. The tool name and input parameters should match the components configured in your application. ```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(appbuilder.AppBuilderClientRunRequest{ ConversationID: conversationID, AppID: appID, Query: "", EndUserID: &end_user_id, Stream: false, ToolChoice: &appbuilder.ToolChoice{ Type: "function", Function: appbuilder.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)) } } } ``` -------------------------------- ### Create and Manage Knowledge Base with AppBuilder SDK Source: https://context7.com/baidubce/app-builder/llms.txt Demonstrates creating a new knowledge base, uploading documents with custom processing options, listing documents, and performing knowledge retrieval. ```python import appbuilder import os os.environ["APPBUILDER_TOKEN"] = "your_appbuilder_token" # Create knowledge base knowledge = appbuilder.KnowledgeBase() resp = knowledge.create_knowledge_base( name="my_knowledge_base", description="测试知识库", type="public" # Optional: public, bes, vdb ) knowledge_base_id = resp.id print("知识库ID:", knowledge_base_id) # Instantiate existing knowledge base my_knowledge = appbuilder.KnowledgeBase(knowledge_base_id) # Upload document to knowledge base my_knowledge.upload_documents( id=knowledge_base_id, content_format="rawText", file_path="./document.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"]) ) ) # Get document list doc_list = my_knowledge.get_documents_list() print("文档列表:", doc_list) # Knowledge base retrieval from appbuilder.core.console.knowledge_base import data_class result = knowledge.query_knowledge_base( query="民法典第三条的内容", knowledgebase_ids=[knowledge_base_id], type="fulltext", # Optional: fulltext, semantic, hybird top=5 ) for chunk in result.chunks: print(f"匹配内容: {chunk.content}") print(f"相关度: {chunk.rank_score}") ``` -------------------------------- ### Table Schema Example Source: https://github.com/baidubce/app-builder/blob/master/docs/BasisModule/Components/gbi/nl2sql/README.md An example of a MySQL table schema definition used for initializing the NL2Sql component. ```sql 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 ``` -------------------------------- ### Go RAG Example Source: https://github.com/baidubce/app-builder/blob/master/docs/Application/RAG/BasicKnowledge/rag.md Example code demonstrating how to use the RAG API in Go for querying information. ```APIDOC ## Go RAG API Usage ### Description This example demonstrates how to initialize and use the RAG (Retrieval Augmented Generation) feature in Go. It covers setting up authentication, configuring the SDK, creating a RAG instance, running a query, and iterating through the streamed response. ### Method N/A (Client-side SDK usage) ### Endpoint N/A (Client-side SDK usage) ### Parameters #### Environment Variables - **APPBUILDER_TOKEN** (string) - Required - Your App Builder authentication token. - **GATEWAY_URL** (string) - Optional - The base URL for the App Builder API. Defaults to `https://appbuilder.baidu.com`. #### SDK Configuration (`appbuilder.NewSDKConfig`) - **token** (string) - Your App Builder authentication token. - **gatewayURL** (string) - The base URL for the App Builder API. #### RAG Initialization (`appbuilder.NewRAG`) - **appID** (string) - Required - The ID of your created RAG application. - **config** (`SDKConfig`) - Required - SDK configuration object. #### Run Method (`rag.Run`) - **conversationID** (string) - Required - The ID of the conversation to continue. If empty, a new conversation is started. - **query** (string) - Required - The user's query. - **stream** (bool) - Required - Set to `true` for streaming responses, `false` for a single response. Streaming is recommended. #### Run Method Response (`i.Next()`) - **RAGAnswer** - A struct containing the response details. - **Answer** (string) - The answer chunk from the RAG model. - **ConversationID** (string) - The current conversation ID. - **Events** ([]RAGEvent) - A list of events associated with the response. - **Event** (string) - The name of the event. - **EventStatus** (string) - The status of the event. - **EventType** (string) - The type of the event. - **Text** (json.RawMessage) - The content of the event. - **error** - An error object if the operation failed. `io.EOF` indicates successful completion of streaming. ### Request Example ```go // Setting environment variables for authentication and gateway URL os.Setenv("APPBUILDER_TOKEN", "YOUR_SECRET_KEY") os.Setenv("GATEWAY_URL", "") // Optional, uses default if empty // Creating SDK configuration config, err := appbuilder.NewSDKConfig("", "") if err != nil { // Handle error } // Initializing RAG instance appID := "YOUR_APP_ID" rag, err := appbuilder.NewRAG(appID, config) if err != nil { // Handle error } // Executing a streaming query // conversationID is empty for a new conversation // query is the user's input // stream is set to true i, err := rag.Run("", "What are the performance specs of cars?", true) if err != nil { // Handle error } completedAnswer := "" var answer *appbuilder.RAGAnswer for answer, err = i.Next(); err == nil; answer, err = i.Next() { completedAnswer += answer.Answer } if errors.Is(err, io.EOF) { fmt.Println("RAG query completed successfully.") fmt.Println("Full Answer: ", completedAnswer) } else { // Handle error during iteration } ``` ### Response #### Success Response (Streaming) - **RAGIterator** - An iterator to process streamed responses. - **Next()** - Returns a `RAGAnswer` struct and an error. #### Response Example (Streaming Output) ```go // The completedAnswer variable will accumulate the streamed response chunks. // Example: "The car's 0-60 mph time is 4.5 seconds, and its top speed is 180 mph." ``` #### Error Handling - Errors are returned as `error` types. `io.EOF` signifies the end of the stream. ``` -------------------------------- ### Run AppBuilder Client with Local MCP Server Source: https://github.com/baidubce/app-builder/blob/master/cookbooks/mcp/client.ipynb This example demonstrates how to use the AppBuilder client with a locally downloaded MCP server file. It sets up environment variables for authentication, connects to the server, and then uses the `AsyncAppBuilderClient` to create a conversation and run a query with specified tools. The `AsyncToolCallEventHandler` is used to handle tool calls asynchronously. Make sure to replace placeholders like 'YOUR_APPBUILDER_TOKEN' and 'YOUR_APP_ID' with your actual credentials. The code also includes a `time.sleep` to keep the browser open after navigation and ensures the HTTP session is closed. ```python import os import time import asyncio import appbuilder from appbuilder.core.console.appbuilder_client.async_event_handler import ( AsyncToolCallEventHandler, ) from appbuilder.mcp_server.client import MCPClient os.environ["APPBUILDER_TOKEN"] = "YOUR_APPBUILDER_TOKEN" os.environ["APP_ID"] = "YOUR_APP_ID" async def main(): app_id = os.environ.get("APP_ID") assert app_id is not None, "APP_ID is not set" appbuilder_client = appbuilder.AsyncAppBuilderClient(app_id) mcp_client = MCPClient() # server.py 是上述步骤中下载的mcp组件文件 await mcp_client.connect_to_server("./server.py") tools = mcp_client.tools event_handler = AsyncToolCallEventHandler(mcp_client, functions=[]) conversation_id = await appbuilder_client.create_conversation() with await appbuilder_client.run_with_handler( conversation_id=conversation_id, query="先搜索关于文心一言4.5模型的新闻,取出其中一个url,再用playwright_navigate打开这个url", tools=tools, event_handler=event_handler, ) as run: await run.until_done() print("浏览网页,我们在此稍作停留,您可通过其他方式常驻该进程以保持网页") time.sleep(5) await appbuilder_client.http_client.session.close() if __name__ == "__main__": appbuilder.logger.setLoglevel("DEBUG") loop = asyncio.get_event_loop() loop.run_until_complete(main()) ``` -------------------------------- ### Java RAG Example Source: https://github.com/baidubce/app-builder/blob/master/docs/Application/RAG/BasicKnowledge/rag.md Example code demonstrating how to use the RAG API in Java for querying information. ```APIDOC ## Java RAG API Usage ### Description This example demonstrates how to initialize and use the RAG (Retrieval Augmented Generation) feature in Java. It shows how to set up authentication, create a RAG instance, run a query, and process the streamed response. ### Method N/A (Client-side SDK usage) ### Endpoint N/A (Client-side SDK usage) ### Parameters #### System Properties - **APPBUILDER_TOKEN** (string) - Required - Your App Builder authentication token. #### RAG Initialization - **appId** (string) - Required - The ID of your created RAG application. #### RAG Run Method - **query** (string) - Required - The user's query. - **conversationID** (string) - Optional - The ID of the conversation to continue. If empty, a new conversation is started. - **stream** (boolean) - Required - Set to `true` for streaming responses, `false` for a single response. Streaming is recommended. ### Request Example ```java // Setting authentication token System.setProperty("APPBUILDER_TOKEN", "YOUR_SECRET_KEY"); // Initializing RAG with App ID String appId = "YOUR_APP_ID"; RAG rag = new RAG(appId); // Running a query with streaming enabled RAGIterator itor = rag.run("What are the property prices nearby?", "", true); ``` ### Response #### Success Response (Streaming) - **RAGIterator** - An iterator to process streamed responses. - **next()** - Returns a `RAGResponse` object. - **getResult().getAnswer()** (string) - The answer chunk from the RAG model. #### Response Example (Streaming Output) ``` // Output will be streamed here, chunk by chunk. // Example: "The average price for a 2-bedroom apartment in the city center is approximately $500,000." ``` #### Error Handling - `AppBuilderServerException` may be thrown during initialization or execution. ``` -------------------------------- ### Implement SimilarQuestion Component with Manifests Source: https://github.com/baidubce/app-builder/blob/master/docs/DevelopGuide/HowToContributeCode/README.md Example of a component class defining metadata, manifests, and the tool_eval method for streaming output. ```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) ``` -------------------------------- ### Playground Response Example Source: https://github.com/baidubce/app-builder/blob/master/docs/BasisModule/Components/llms/playground/README.md This is an example of a JSON response from the Playground component, indicating the result of the model's execution. ```json {"result": "北京科技馆。"} ``` -------------------------------- ### Initialize and Use StyleWriting Component Source: https://github.com/baidubce/app-builder/blob/master/docs/BasisModule/Components/llms/style_writing/README.md Demonstrates the basic setup, authentication, and invocation of the StyleWriting component to generate styled text. ```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) ``` -------------------------------- ### Retrieve Knowledge Base Chunks Example Source: https://github.com/baidubce/app-builder/blob/master/docs/BasisModule/Platform/KnowledgeBase/knowledgebase.md Demonstrates initializing the KnowledgeBase client and retrieving chunks for a specific document. ```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) ``` -------------------------------- ### Streaming Call Example Source: https://github.com/baidubce/app-builder/blob/master/docs/Application/Agent/BasicKnowledge/agent.md Example demonstrating how to perform a streaming call to the AppBuilderClient's run method and process the response. ```Python import appbuilder from appbuilder.core.console.appbuilder_client import data_class import os # Please go to the Qianfan AppBuilder official website to create a key. See: https://cloud.baidu.com/doc/AppBuilder/s/Olq6grrt6#1%E3%80%81%E5%88%9B%E5%BB%BA%E5%AF%86%E9%92%A5 # Set environment variables os.environ["APPBUILDER_TOKEN"] = 'YOUR_APPBUILDER_TOKEN' app_id = 'YOUR_APP_ID' # Published AppBuilder application ID # Initialize the agent client = appbuilder.AppBuilderClient(app_id) # Create a conversation conversation_id = client.create_conversation() # Upload a document introducing a certain car product # file_id = client.upload_local_file(conversation_id, "/path/to/pdf/file") # Start a conversation, referencing the uploaded document (optional) # Note: file_ids is not mandatory. If you don't need to reference specific documents, leave file_ids empty. message = client.run(conversation_id, "汽车性能参数怎么样", file_ids=[], stream=True) answer = "" # Process the streaming response for chunk in message: # Each chunk is an AppBuilderClientAnswer object # You can process the answer and events as they arrive if chunk.content.answer: print(chunk.content.answer, end='') answer += chunk.content.answer if chunk.content.events: for event in chunk.content.events: # Process each event if necessary print(f"\nEvent Status: {event.status}") if event.detail: print(f"Event Detail: {event.detail}") if event.usage: print(f"Usage: {event.usage.total_tokens} tokens") print("\nStreaming finished.") ``` -------------------------------- ### Create Assistant, Thread, and Run Source: https://github.com/baidubce/app-builder/blob/master/cookbooks/pipeline/run.ipynb Demonstrates creating an assistant, a new conversation thread, adding a message, and initiating a run. The assistant is configured with specific instructions. ```python # 首先创建一个asstistant assistant = appbuilder.assistant.assistants.create( name="test_assistant", description="test assistant", instructions="每句话回复前都加上我是秦始皇" ) # 创建一个thread会话 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, ) # 打印对话运行信息 print(run_result) ``` -------------------------------- ### Install AppBuilder and MCP Dependencies Source: https://github.com/baidubce/app-builder/blob/master/cookbooks/mcp/server.ipynb Install the necessary Python packages for AppBuilder and MCP Server. Ensure you are using Python 3.12 or later. ```bash !python3 -m pip install appbuilder-sdk -i https://mirrors.aliyun.com/pypi/simple/ !python3 -m pip install mcp -i https://mirrors.aliyun.com/pypi/simple/ ``` -------------------------------- ### Initialize and Execute SelectTable Source: https://github.com/baidubce/app-builder/blob/master/cookbooks/components/gbi.ipynb Example of initializing SelectTable with a custom prompt template and executing a 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}") ``` -------------------------------- ### AppBuilder Starting Trace Log Source: https://github.com/baidubce/app-builder/blob/master/cookbooks/live_broadcast_material/2024_08_22/trace.ipynb This log message confirms that the AppBuilder has initiated a tracing process. It's helpful for debugging the start of trace operations. ```log [2024-08-21 20:30:10,684.684] tracer.py [line:351] INFO [main-10829791027654713596] AppBuilder Starting trace... ``` ```log INFO:appbuilder:AppBuilder Starting trace... ``` -------------------------------- ### Initialize and Run Text2Image Source: https://github.com/baidubce/app-builder/blob/master/docs/BasisModule/Components/text_to_image/README.md Set up authentication and initialize the Text2Image component. Then, create a message with prompt and image parameters to generate an image. ```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': ['...']} ``` -------------------------------- ### Start AgentRuntime HTTP Service Source: https://github.com/baidubce/app-builder/blob/master/cookbooks/components/rag_with_baidusearch.ipynb Start an HTTP service for the AgentRuntime. This makes the agent accessible via HTTP requests, enabling integration with other applications. ```python agent.serve(port=8092) ``` -------------------------------- ### Basic Usage and Initialization Source: https://github.com/baidubce/app-builder/blob/master/docs/BasisModule/Components/matching/README.md Demonstrates the fundamental usage of the Matching component, including initialization and a code example for matching and ranking texts based on query similarity. ```APIDOC ## Basic Usage ### Code Example for Matching and Ranking This example shows how to match and rank texts based on their similarity to a query. ```python import os import appbuilder # Set your AppBuilder token os.environ["APPBUILDER_TOKEN"] = 'YOUR_APPBUILDER_TOKEN' # Initialize components embedding = appbuilder.Embedding() matching = appbuilder.Matching(embedding) # Define query and contexts query = appbuilder.Message("你好") contexts = appbuilder.Message(["世界", "你好"]) # Perform matching contexts_matched = matching(query, contexts) print(contexts_matched.content) ``` ### Expected Output ``` ['你好', '世界'] ``` ### Authentication Before using the component, please apply for and set authentication parameters. Refer to the [Component Usage Guide](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 # Set the token in the environment os.environ["APPBUILDER_TOKEN"] = "bce-YOURTOKEN" ``` ### Initialization Parameters | Parameter Name | Parameter Type | Required | Description | | -------------- | -------------- | -------- | --------------------------------------------------------------------------- | | embedding | Embedding | Optional | An Embedding component used for initializing the vector calculation function of Matching. The base model currently only supports `embedding-v1`. Defaults to `embedding-v1` if not specified. | `appbuilder.Embedding()` ```