### Setup Repository Scripts Source: https://github.com/go-kratos/blades/blob/main/cmd/docs/vendor/github.com/openai/openai-go/v3/CONTRIBUTING.md Run these scripts to install dependencies and build the SDK. Ensure you have Go 1.22+ installed. ```sh ./scripts/bootstrap ./scripts/lint ``` -------------------------------- ### Install Match Package Source: https://github.com/go-kratos/blades/blob/main/cmd/docs/vendor/github.com/tidwall/match/README.md Use 'go get' to install the latest version of the match package. ```go go get -u github.com/tidwall/match ``` -------------------------------- ### Blades Quick Start Guide Source: https://github.com/go-kratos/blades/blob/main/cmd/blades/README.md Initialize the Blades workspace, set API keys, configure agent settings, and start chatting. ```sh # 1. Initialise workspace (creates ~/.blades with all template files) blades init # 2. Set your API key export ANTHROPIC_API_KEY=sk-... # or OPENAI_API_KEY / GEMINI_API_KEY # 3. Edit config and agent recipe $EDITOR ~/.blades/config.yaml $EDITOR ~/.blades/agent.yaml # 4. Start chatting blades chat ``` -------------------------------- ### Run Local Example Source: https://github.com/go-kratos/blades/blob/main/cmd/docs/vendor/github.com/openai/openai-go/v3/CONTRIBUTING.md Execute a local example by navigating to its directory and running it with `go run`. ```sh go run ./examples/ ``` -------------------------------- ### Install Cobra Library Source: https://github.com/go-kratos/blades/blob/main/cmd/docs/vendor/github.com/spf13/cobra/README.md Use 'go get' to install the latest version of the Cobra library. ```bash go get -u github.com/spf13/cobra@latest ``` -------------------------------- ### Add Example to Examples Directory Source: https://github.com/go-kratos/blades/blob/main/cmd/docs/vendor/github.com/openai/openai-go/v3/CONTRIBUTING.md Add new examples to the `examples/` directory. These files are not modified by the code generator. ```go package main func main() { // ... } ``` -------------------------------- ### Mock Server Setup for Tests Source: https://github.com/go-kratos/blades/blob/main/cmd/docs/vendor/github.com/openai/openai-go/v3/CONTRIBUTING.md Most tests require a mock server. Install Node.js and npm, then use `npx prism mock` against your OpenAPI spec. ```sh npx prism mock path/to/your/openapi.yml ``` -------------------------------- ### Complete Blades Framework Configuration Example Source: https://github.com/go-kratos/blades/blob/main/_autodocs/configuration.md This example demonstrates setting up an agent with a model, skills, tools, and middleware, then executing a task using a runner and session. ```go import ( "github.com/go-kratos/blades" "github.com/go-kratos/blades/contrib/anthropic" "github.com/go-kratos/blades/flow" "github.com/go-kratos/blades/skills" ) func main() { // Configure model model := anthropic.NewModel("claude-3-sonnet", anthropic.Config{ APIKey: os.Getenv("ANTHROPIC_API_KEY"), }) // Load skills skillList, _ := skills.NewFromDir("./skills") // Configure session with compression compressor := &WindowCompressor{MaxMessages: 30} session := blades.NewSession( blades.WithContextCompressor(compressor), ) // Configure agent agent, _ := blades.NewAgent("MainAgent", blades.WithModel(model), blades.WithDescription("Main orchestrator"), blades.WithInstruction("You are a helpful assistant managing complex workflows."), blades.WithSkills(skillList...), blades.WithTools(customTool1, customTool2), blades.WithMaxIterations(15), blades.WithContext(true), blades.WithMiddleware(loggingMiddleware, retryMiddleware), ) // Execute runner := blades.NewRunner(agent) response, _ := runner.Run(context.Background(), blades.UserMessage("Help me with this task"), blades.WithSession(session), blades.WithResume(true), ) } ``` -------------------------------- ### Quick Start Go Agent Example Source: https://github.com/go-kratos/blades/blob/main/_autodocs/README.md This Go code demonstrates how to create an AI agent using the Blades library, configure it with a specific model (Anthropic's Claude 3.5 Sonnet), set an instruction, and execute a user query. Ensure the ANTHROPIC_API_KEY environment variable is set. ```go package main import ( "context" "log" "os" "github.com/go-kratos/blades" "github.com/go-kratos/blades/contrib/anthropic" ) func main() { // Create model provider model := anthropic.NewModel("claude-3-5-sonnet-20241022", anthropic.Config{ APIKey: os.Getenv("ANTHROPIC_API_KEY"), }) // Create agent agent, _ := blades.NewAgent("ChatBot", blades.WithModel(model), blades.WithInstruction("You are a helpful assistant."), ) // Execute runner := blades.NewRunner(agent) response, _ := runner.Run(context.Background(), blades.UserMessage("What is the capital of France?"), ) log.Println(response.Text()) } ``` -------------------------------- ### Install Pretty Go Package Source: https://github.com/go-kratos/blades/blob/main/cmd/docs/vendor/github.com/tidwall/pretty/README.md Use 'go get' to install the Pretty package. This command retrieves the library for use in your Go projects. ```sh go get -u github.com/tidwall/pretty ``` -------------------------------- ### Install OpenAI Go Library Source: https://github.com/go-kratos/blades/blob/main/cmd/docs/vendor/github.com/openai/openai-go/v3/README.md Import the OpenAI Go library. Use `go get -u` to pin a specific version. ```go import ( "github.com/openai/openai-go/v3" ) // imported as openai ``` ```sh go get -u 'github.com/openai/openai-go/v2@v3.8.1' ``` -------------------------------- ### Install SJSON Go Package Source: https://github.com/go-kratos/blades/blob/main/cmd/docs/vendor/github.com/tidwall/sjson/README.md Use `go get` to install the SJSON library for your Go project. ```sh go get -u github.com/tidwall/sjson ``` -------------------------------- ### Install Claude Provider for Blades Source: https://github.com/go-kratos/blades/blob/main/contrib/anthropic/README.md Install the Claude provider for Blades using go get. ```bash go get github.com/go-kratos/blades/contrib/claude ``` -------------------------------- ### Agent with Tools Example Source: https://github.com/go-kratos/blades/blob/main/_autodocs/quick-start-examples.md Demonstrates how to create an agent that can use tools. This example shows a weather bot that uses a 'get-weather' tool to fetch weather information. ```go package main import ( "context" "encoding/json" "log" "os" "github.com/go-kratos/blades" "github.com/go-kratos/blades/contrib/anthropic" "github.com/go-kratos/blades/tools" ) type WeatherReq struct { Location string `json:"location"` } type WeatherResp struct { Temperature float64 `json:"temperature"` Condition string `json:"condition"` } func main() { model := anthropic.NewModel("claude-3-5-sonnet-20241022", anthropic.Config{ APIKey: os.Getenv("ANTHROPIC_API_KEY"), }) // Create weather tool weatherTool, _ := tools.NewFunc( "get-weather", "Get current weather for a location", func(ctx context.Context, req WeatherReq) (WeatherResp, error) { // Simulate weather API call return WeatherResp{ Temperature: 22.5, Condition: "Sunny", }, nil }, ) // Create agent with tool agent, _ := blades.NewAgent("WeatherBot", blades.WithModel(model), blades.WithTools(weatherTool), blades.WithInstruction("You can check weather using the get-weather tool."), ) runner := blades.NewRunner(agent) response, _ := runner.Run(context.Background(), blades.UserMessage("What's the weather in Paris?"), ) log.Println(response.Text()) } ``` -------------------------------- ### Install Gemini Provider Source: https://github.com/go-kratos/blades/blob/main/contrib/gemini/README.md Install the Gemini provider for Blades using go get. ```bash go get github.com/go-kratos/blades/contrib/gemini ``` -------------------------------- ### Install GJSON Source: https://github.com/go-kratos/blades/blob/main/cmd/docs/vendor/github.com/tidwall/gjson/README.md Install the GJSON library using the Go toolchain. ```sh go get -u github.com/tidwall/gjson ``` -------------------------------- ### Sequential Workflow Example Source: https://github.com/go-kratos/blades/blob/main/_autodocs/quick-start-examples.md Illustrates how to create a sequential workflow using specialized agents. This example chains a 'Researcher' agent with a 'Writer' agent to generate content. ```go package main import ( "context" "log" "os" "github.com/go-kratos/blades" "github.com/go-kratos/blades/contrib/anthropic" "github.com/go-kratos/blades/flow" ) func main() { model := anthropic.NewModel("claude-3-5-sonnet-20241022", anthropic.Config{ APIKey: os.Getenv("ANTHROPIC_API_KEY"), }) // Create specialized agents researcher, _ := blades.NewAgent("Researcher", blades.WithModel(model), blades.WithDescription("Researches topics"), blades.WithInstruction("Research and provide detailed information."), ) writer, _ := blades.NewAgent("Writer", blades.WithModel(model), blades.WithDescription("Writes content"), blades.WithInstruction("Write engaging content based on research."), ) // Create sequential pipeline pipeline, _ := flow.NewSequentialAgent(flow.SequentialConfig{ Name: "ContentPipeline", Description: "Research then write", SubAgents: []blades.Agent{researcher, writer}, }) runner := blades.NewRunner(pipeline) response, _ := runner.Run(context.Background(), blades.UserMessage("Write about machine learning"), ) log.Println(response.Text()) } ``` -------------------------------- ### SSH Configuration Example Source: https://github.com/go-kratos/blades/blob/main/cmd/blades/internal/workspace/templates/workspace/TOOLS.md Example of how to define SSH host aliases and their corresponding IP addresses and usernames. ```markdown ### SSH - home-server → 192.168.1.10, user: admin ``` -------------------------------- ### Complete Graph Example Source: https://github.com/go-kratos/blades/blob/main/_autodocs/api-reference-graph.md This example demonstrates building a complete graph execution flow. It includes defining nodes with handlers, adding edges to define the flow, and setting conditions on edges. The graph is then compiled and executed. ```go import "github.com/go-kratos/blades/graph" func main() { g := graph.New(graph.WithParallel(true)) // Define nodes g.AddNode("fetch", graph.HandlerFunc(func(ctx context.Context, state graph.State) (graph.State, error) { // Fetch data state["data"] = []string{"item1", "item2", "item3"} return state, nil })) g.AddNode("validate", graph.HandlerFunc(func(ctx context.Context, state graph.State) (graph.State, error) { data, _ := state["data"].([]string) if len(data) == 0 { return state, errors.New("no data") } state["valid"] = true return state, nil })) g.AddNode("process", graph.HandlerFunc(func(ctx context.Context, state graph.State) (graph.State, error) { data, _ := state["data"].([]string) var processed []string for _, item := range data { processed = append(processed, strings.ToUpper(item)) } state["processed"] = processed return state, nil })) g.AddNode("save", graph.HandlerFunc(func(ctx context.Context, state graph.State) (graph.State, error) { // Save results state["saved"] = true return state, nil })) // Define flow g.AddEdge("fetch", "validate") g.AddEdge("validate", "process", graph.WithEdgeCondition(func(ctx context.Context, state graph.State) bool { valid, _ := state["valid"].(bool) return valid }), ) g.AddEdge("process", "save") // Compile and execute executor, err := g.Compile() if err != nil { log.Fatal(err) } finalState, err := executor.Execute(context.Background(), graph.State{}) if err != nil { log.Fatal(err) } fmt.Println("Final state:", finalState) } ``` -------------------------------- ### Install Blades from Source Source: https://github.com/go-kratos/blades/blob/main/cmd/blades/README.md Install the Blades CLI from its source code. Requires Go 1.24+. ```sh git clone https://github.com/go-kratos/blades cd blades/cmd/blades go install . ``` -------------------------------- ### Device Nickname Example Source: https://github.com/go-kratos/blades/blob/main/cmd/blades/internal/workspace/templates/workspace/TOOLS.md Example of how to assign nicknames to devices for easier reference. ```markdown ### Devices - living-room-speaker → Kitchen HomePod mini ``` -------------------------------- ### Basic Pattern Matching Examples Source: https://github.com/go-kratos/blades/blob/main/cmd/docs/vendor/github.com/tidwall/match/README.md Demonstrates basic usage of the Match function with different wildcard patterns. ```go match.Match("hello", "*llo") match.Match("jello", "?ello") match.Match("hello", "h*o") ``` -------------------------------- ### Example: Sequential Agent Workflow Source: https://github.com/go-kratos/blades/blob/main/_autodocs/api-reference-flow.md Demonstrates creating and running a sequential agent pipeline for content creation. Ensure all necessary agents (Researcher, Writer, Editor) are initialized. ```go import "github.com/go-kratos/blades/flow" researcher, _ := blades.NewAgent("Researcher", ...) writer, _ := blades.NewAgent("Writer", ...) editor, _ := blades.NewAgent("Editor", ...) pipeline, _ := flow.NewSequentialAgent(flow.SequentialConfig{ Name: "ContentPipeline", Description: "Research, write, and edit content", SubAgents: []blades.Agent{researcher, writer, editor}, }) runner := blades.NewRunner(pipeline) response, _ := runner.Run(context.Background(), blades.UserMessage("Write an article about AI")) ``` -------------------------------- ### Install uuid Package Source: https://github.com/go-kratos/blades/blob/main/cmd/docs/vendor/github.com/google/uuid/README.md Use this command to install the uuid package for your Go project. ```shell go get github.com/google/uuid ``` -------------------------------- ### SKILL.md format example Source: https://github.com/go-kratos/blades/blob/main/_autodocs/api-reference-skills.md Defines the structure and content of the SKILL.md file, including YAML frontmatter for metadata and markdown for instructions and usage examples. ```yaml --- name: my-skill description: "A brief description of this skill" license: "MIT" compatibility: "Compatible with Claude 3+" metadata: category: "productivity" version: "1.0" --- # Skill Instructions The agent should use this skill when... ## Usage Examples [Usage examples here] ``` -------------------------------- ### Streaming Response Example in Go Source: https://github.com/go-kratos/blades/blob/main/_autodocs/quick-start-examples.md This example demonstrates how to receive streaming responses from a Blades agent. Ensure the ANTHROPIC_API_KEY environment variable is set. ```go package main import ( "context" "fmt" "log" "os" "github.com/go-kratos/blades" "github.com/go-kratos/blades/contrib/anthropic" ) func main() { model := anthropic.NewModel("claude-3-5-sonnet-20241022", anthropic.Config{ APIKey: os.Getenv("ANTHROPIC_API_KEY"), }) agent, _ := blades.NewAgent("StreamingBot", blades.WithModel(model), ) runner := blades.NewRunner(agent) // Stream responses stream := runner.RunStream(context.Background(), blades.UserMessage("Write a short poem about AI"), ) for msg, err := range stream { if err != nil { log.Fatal(err) } fmt.Print(msg.Text()) } } ``` -------------------------------- ### Example Middleware Composition Source: https://github.com/go-kratos/blades/blob/main/_autodocs/api-reference-middleware.md Demonstrates how to create custom logging and retry middlewares and chain them together using ChainMiddlewares. The chained middleware is then applied to a new agent. ```go loggingMiddleware := func(next blades.Handler) blades.Handler { return blades.HandleFunc(func(ctx context.Context, inv *blades.Invocation) blades.Generator[*blades.Message, error] { log.Println("Starting invocation:", inv.ID) return next.Handle(ctx, inv) }) } retryMiddleware := func(next blades.Handler) blades.Handler { return blades.HandleFunc(func(ctx context.Context, inv *blades.Invocation) blades.Generator[*blades.Message, error] { // Wrap next.Handle with retry logic return next.Handle(ctx, inv) }) } chained := blades.ChainMiddlewares(loggingMiddleware, retryMiddleware) agent, _ := blades.NewAgent("Agent", blades.WithModel(model), blades.WithMiddleware(chained), ) ``` -------------------------------- ### Blades Configuration Example (config.yaml) Source: https://github.com/go-kratos/blades/blob/main/cmd/blades/README.md Provides a sample configuration file for Blades, demonstrating settings for LLM providers and optional channel integrations like Lark/Feishu and Weixin. ```yaml providers: - name: anthropic provider: anthropic models: [claude-sonnet-4-6] apiKey: ${ANTHROPIC_API_KEY} # env-var expansion supported # Optional: exec tool overrides (see template) # exec: # timeoutSeconds: 60 # restrictToWorkspace: true # Optional: Lark/Feishu channel (WebSocket only) for `blades daemon` # channels: # lark: # enabled: true # appID: ${LARK_APP_ID} # appSecret: ${LARK_APP_SECRET} # # Optional: Weixin/iLink channel (long polling) for `blades daemon` # channels: # weixin: # enabled: true # # accountID: user@im.wechat # # botToken: ${WEIXIN_BOT_TOKEN} # optional when not using QR login # # baseURL: https://ilinkai.weixin.qq.com # # routeTag: "" # # accountDir: ~/.blades/weixin/account # # stateDir: ~/.blades/weixin # # mediaDir: ~/.blades/weixin/media # # cdnBaseURL: https://your-cdn.example.com # # allowFrom: ["user@im.wechat"] ``` -------------------------------- ### Example Usage of NewDeepAgent Source: https://github.com/go-kratos/blades/blob/main/_autodocs/api-reference-flow.md Demonstrates how to create and use a Deep Agent for project management. It shows initializing sub-agents, configuring the deep agent, and running a task. ```go import "github.com/go-kratos/blades/flow" researcherAgent, _ := blades.NewAgent("Researcher", ...) writerAgent, _ := blades.NewAgent("Writer", ...) deepAgent, err := flow.NewDeepAgent(flow.DeepConfig{ Name: "ProjectManager", Model: model, Description: "Manages complex projects with delegation", Instruction: "Break down the project into tasks, delegate to specialists", Tools: []tools.Tool{searchTool, writeTool}, SubAgents: []blades.Agent{researcherAgent, writerAgent}, MaxIterations: 20, }) if err != nil { log.Fatal(err) } runner := blades.NewRunner(deepAgent) response, _ := runner.Run(context.Background(), blades.UserMessage("Create a comprehensive research report on quantum computing")) ``` -------------------------------- ### Skill directory structure example Source: https://github.com/go-kratos/blades/blob/main/_autodocs/api-reference-skills.md Illustrates the expected file and directory layout for a skill. A SKILL.md file is mandatory for defining the skill's metadata and instructions. ```text my-skill/ ├── SKILL.md # Required: frontmatter and instructions ├── README.md # Optional: additional documentation ├── references/ # Optional: file references │ └── example.txt ├── assets/ # Optional: binary assets │ └── model.pkl └── scripts/ # Optional: script files └── process.py ``` -------------------------------- ### Dot vs Pipe Separator Examples Source: https://github.com/go-kratos/blades/blob/main/cmd/docs/vendor/github.com/tidwall/gjson/SYNTAX.md Demonstrates the equivalence and differences between '.' and '|' separators in GJSON paths, especially when used with array indexing and queries. ```go friends.0.first "Dale" friends|0.first "Dale" friends.0|first "Dale" friends|0|first "Dale" friends|# 3 friends.# 3 friends.#(last="Murphy")# [{"first": "Dale", "last": "Murphy", "age": 44},{"first": "Jane", "last": "Murphy", "age": 47}] friends.#(last="Murphy")#.first ["Dale","Jane"] friends.#(last="Murphy")#|first friends.#(last="Murphy")#.0 [] friends.#(last="Murphy")#|0 {"first": "Dale", "last": "Murphy", "age": 44} friends.#(last="Murphy")#.# [] friends.#(last="Murphy")#|# 2 ``` -------------------------------- ### Toolset.Instruction Source: https://github.com/go-kratos/blades/blob/main/_autodocs/api-reference-skills.md Returns a combined instruction string that can be used to guide an agent on how to utilize the skills within the Toolset. ```APIDOC ## Toolset.Instruction ### Description Returns the combined instruction for using all skills. ### Signature ```go func (t *Toolset) Instruction() string ``` ### Returns - **string** - The combined instruction string. ### Example ```go toolset, _ := skills.NewToolset(skillList) instruction := toolset.Instruction() fmt.Println(instruction) agent, _ := blades.NewAgent("SkillAgent", blades.WithModel(model), blades.WithInstruction(instruction), blades.WithTools(toolset.Tools()...), ) ``` ``` -------------------------------- ### Implement MCPResolver for Tool Resolution Source: https://github.com/go-kratos/blades/blob/main/_autodocs/api-reference-tools.md Example implementation of the Resolver interface for querying an MCP server. This is useful when tools need to be dynamically fetched from an external service. ```go type MCPResolver struct { serverURL string } func (r *MCPResolver) Resolve(ctx context.Context) ([]tools.Tool, error) { // Query MCP server for available tools tools := make([]tools.Tool, 0) // ... fetch and convert tools return tools, nil } agent, _ := blades.NewAgent("MCPAgent", blades.WithModel(model), blades.WithToolsResolver(&MCPResolver{ serverURL: "http://mcp-server:8080", }), ) ``` -------------------------------- ### GJSON Path Wildcard Examples Source: https://github.com/go-kratos/blades/blob/main/cmd/docs/vendor/github.com/tidwall/gjson/SYNTAX.md Use wildcard characters '*' (zero or more characters) and '?' (exactly one character) within keys for flexible matching. ```go child*.2 "Jack" c?ildren.0 "Sara" ``` -------------------------------- ### Create and Use Routing Agent Source: https://github.com/go-kratos/blades/blob/main/_autodocs/api-reference-flow.md Example demonstrating how to create specialized agents (Technical, Billing, General Support) and then configure a Routing Agent to direct user messages to the appropriate sub-agent. It shows the creation of agents, the routing agent configuration, and running a query through the router. ```go import "github.com/go-kratos/blades/flow" technicalAgent, _ := blades.NewAgent("TechnicalSupport", blades.WithModel(model), blades.WithInstruction("Help with technical problems"), blades.WithDescription("Handles technical support queries"), ) billingAgent, _ := blades.NewAgent("BillingSupport", blades.WithModel(model), blades.WithInstruction("Handle billing inquiries"), blades.WithDescription("Handles billing and account questions"), ) generalAgent, _ := blades.NewAgent("GeneralSupport", blades.WithModel(model), blades.WithInstruction("Provide general assistance"), blades.WithDescription("Handles general questions"), ) router, err := flow.NewRoutingAgent(flow.RoutingConfig{ Name: "SupportRouter", Description: "Routes support requests to specialized agents", Model: model, SubAgents: []blades.Agent{technicalAgent, billingAgent, generalAgent}, }) if err != nil { log.Fatal(err) } runner := blades.NewRunner(router) response, _ := runner.Run(context.Background(), blades.UserMessage("I can't log into my account")) ``` -------------------------------- ### Basic GJSON Path Examples Source: https://github.com/go-kratos/blades/blob/main/cmd/docs/vendor/github.com/tidwall/gjson/SYNTAX.md Retrieve values by object name or array index. Use dot notation for nested objects and numeric indices for arrays. ```go name.last "Anderson" name.first "Tom" age 37 children ["Sara","Alex","Jack"] children.0 "Sara" children.1 "Alex" friends.1 {"first": "Roger", "last": "Craig", "age": 68} friends.1.first "Roger" ``` -------------------------------- ### Example: Parallel Agent Workflow Source: https://github.com/go-kratos/blades/blob/main/_autodocs/api-reference-flow.md Illustrates setting up and running a parallel agent for multi-faceted analysis. This pattern is suitable when multiple agents can work on different aspects of a task concurrently. ```go import "github.com/go-kratos/blades/flow" searchAgent, _ := blades.NewAgent("Search", ...) analyzeAgent, _ := blades.NewAgent("Analyze", ...) summarizeAgent, _ := blades.NewAgent("Summarize", ...) parallel, _ := flow.NewParallelAgent(flow.ParallelConfig{ Name: "MultiAnalysis", Description: "Search, analyze, and summarize in parallel", SubAgents: []blades.Agent{searchAgent, analyzeAgent, summarizeAgent}, }) runner := blades.NewRunner(parallel) response, _ := runner.Run(context.Background(), blades.UserMessage("Analyze this topic")) ``` -------------------------------- ### Build a Graph Workflow Source: https://github.com/go-kratos/blades/blob/main/_autodocs/quick-start-examples.md Construct a directed graph to define a workflow with nodes and edges. This example demonstrates creating nodes for input, validation, and transformation, with conditional execution. ```go package main import ( "context" "errors" "log" "os" "strings" "github.com/go-kratos/blades/graph" ) func main() { g := graph.New(graph.WithParallel(true)) // Add nodes g.AddNode("input", graph.HandlerFunc(func(ctx context.Context, state graph.State) (graph.State, error) { state["text"] = "hello world" return state, nil })) g.AddNode("validate", graph.HandlerFunc(func(ctx context.Context, state graph.State) (graph.State, error) { text, _ := state["text"].(string) if text == "" { return state, errors.New("empty input") } state["valid"] = true return state, nil })) g.AddNode("transform", graph.HandlerFunc(func(ctx context.Context, state graph.State) (graph.State, error) { text, _ := state["text"].(string) state["result"] = strings.ToUpper(text) return state, nil })) // Connect nodes g.AddEdge("input", "validate") g.AddEdge("validate", "transform", graph.WithEdgeCondition(func(ctx context.Context, state graph.State) bool { valid, _ := state["valid"].(bool) return valid }), ) // Execute executor, _ := g.Compile() finalState, _ := executor.Execute(context.Background(), graph.State{}) log.Println("Result:", finalState["result"]) } ``` -------------------------------- ### Get Nested Array Values in Go Source: https://github.com/go-kratos/blades/blob/main/cmd/docs/vendor/github.com/tidwall/gjson/README.md Access values within nested arrays using the '#.key' path. This example retrieves all last names from a list of programmers. ```go result := gjson.Get(json, "programmers.#.lastName") for _, name := range result.Array() { println(name.String()) } ``` -------------------------------- ### Configure Agent with Tools Source: https://github.com/go-kratos/blades/blob/main/_autodocs/INDEX.md Illustrates how to initialize an agent with a list of tools it can use. The 'tool1' and 'tool2' variables should be pre-defined tool objects. ```go agent, _ := blades.NewAgent("Agent", blades.WithModel(model), blades.WithTools(tool1, tool2), ) ``` -------------------------------- ### Create an Agent with Model, Instruction, and Tools Source: https://github.com/go-kratos/blades/blob/main/_autodocs/README.md Instantiate a new agent with a specified name, language model, system prompt, and a set of tools for it to use. ```go agent, _ := blades.NewAgent("MyAgent", blades.WithModel(model), blades.WithInstruction("System prompt here"), blades.WithTools(tool1, tool2), ) ``` -------------------------------- ### Configure Agent with Skills Source: https://github.com/go-kratos/blades/blob/main/_autodocs/INDEX.md Demonstrates initializing an agent with skills loaded from a directory. The './skills' path should contain skill definitions, and 'skills...' expands the loaded skills. ```go skills, _ := skills.NewFromDir("./skills") agent, _ := blades.NewAgent("Agent", blades.WithModel(model), blades.WithSkills(skills...), ) ``` -------------------------------- ### TTS Preference Example Source: https://github.com/go-kratos/blades/blob/main/cmd/blades/internal/workspace/templates/workspace/TOOLS.md Example of specifying a preferred Text-to-Speech (TTS) voice. ```markdown ### TTS - Preferred voice: "Nova" ``` -------------------------------- ### Get Response Source: https://github.com/go-kratos/blades/blob/main/cmd/docs/vendor/github.com/openai/openai-go/v3/api.md Retrieves a specific response by its ID. This operation corresponds to the `Get` method of the `ResponseService`. ```APIDOC ## GET /responses/{response_id} ### Description Retrieves a specific response by its ID. ### Method GET ### Endpoint /responses/{response_id} ### Parameters #### Path Parameters - **response_id** (string) - Required - The ID of the response to retrieve. #### Query Parameters - **query** (responses.ResponseGetParams) - Optional - Parameters for retrieving the response. ### Response #### Success Response (200) - **response** (responses.Response) - The requested response object. - **error** (error) - An error if the operation failed. ``` -------------------------------- ### Initialize Azure OpenAI Client in Go Source: https://github.com/go-kratos/blades/blob/main/cmd/docs/vendor/github.com/openai/openai-go/v3/README.md Demonstrates how to initialize the OpenAI client for Azure using either TokenCredential or an API Key. Ensure you have the necessary Azure SDK for Go credentials configured. ```go package main import ( "github.com/Azure/azure-sdk-for-go/sdk/azidentity" "github.com/openai/openai-go/v3" "github.com/openai/openai-go/v3/azure" ) func main() { const azureOpenAIEndpoint = "https://.openai.azure.com" // The latest API versions, including previews, can be found here: // https://learn.microsoft.com/en-us/azure/ai-services/openai/reference#rest-api-versionng const azureOpenAIAPIVersion = "2024-06-01" tokenCredential, err := azidentity.NewDefaultAzureCredential(nil) if err != nil { fmt.Printf("Failed to create the DefaultAzureCredential: %s", err) os.Exit(1) } client := openai.NewClient( azure.WithEndpoint(azureOpenAIEndpoint, azureOpenAIAPIVersion), // Choose between authenticating using a TokenCredential or an API Key azure.WithTokenCredential(tokenCredential), // or azure.WithAPIKey(azureOpenAIAPIKey), ) } ``` -------------------------------- ### Install Cobra CLI Generator Source: https://github.com/go-kratos/blades/blob/main/cmd/docs/vendor/github.com/spf13/cobra/README.md Install the cobra-cli tool to bootstrap Cobra applications and command files. ```bash go install github.com/spf13/cobra-cli@latest ``` -------------------------------- ### Get Video Source: https://github.com/go-kratos/blades/blob/main/cmd/docs/vendor/github.com/openai/openai-go/v3/api.md Retrieves a specific video by its ID. This operation corresponds to the `GET /videos/{video_id}` endpoint. ```APIDOC ## GET /videos/{video_id} ### Description Retrieves a specific video by its ID. ### Method GET ### Endpoint /videos/{video_id} ### Parameters #### Path Parameters - **videoID** (string) - Required - The ID of the video to retrieve. ### Response #### Success Response (200) - **Video** (openai.Video) - The requested video object. - **error** (error) - An error if the operation failed. ``` -------------------------------- ### Loading and Running a Recipe Agent in Go Source: https://github.com/go-kratos/blades/blob/main/recipe/README.md Demonstrates how to register a model, load a YAML spec, build an agent with parameters, and run it using the Blades runner. ```go modelRegistry := recipe.NewModelRegistry() modelRegistry.Register("gpt-4o", openai.NewModel("gpt-4o", openai.Config{ APIKey: os.Getenv("OPENAI_API_KEY"), })) spec, _ := recipe.LoadFromFile("agent.yaml") agent, _ := recipe.Build(spec, recipe.WithModelRegistry(modelRegistry), recipe.WithParams(map[string]any{"language": "go"}), ) runner := blades.NewRunner(agent) output, _ := runner.Run(ctx, blades.UserMessage("Review this code: ...")) ``` -------------------------------- ### Start Interactive Chat Source: https://github.com/go-kratos/blades/blob/main/cmd/blades/README.md Starts an interactive streaming conversation. Supports session management and a simple mode. ```sh blades chat blades chat --session my-project blades chat --simple ``` -------------------------------- ### Get Vector Store Source: https://github.com/go-kratos/blades/blob/main/cmd/docs/vendor/github.com/openai/openai-go/v3/api.md Retrieves a specific vector store by its ID. Use this to get details about an existing vector store. ```APIDOC ## GET /vector_stores/{vector_store_id} ### Description Retrieves a specific vector store by its ID. ### Method GET ### Endpoint /vector_stores/{vector_store_id} ### Parameters #### Path Parameters - **vector_store_id** (string) - Required - The unique identifier of the vector store to retrieve. ### Response #### Success Response (200) - **VectorStore** (openai.VectorStore) - The requested vector store object. ### Request Example ```go client.VectorStores.Get(ctx, "vs_abc123") ``` ### Response Example ```json { "id": "vs_abc123", "created_at": 1678886400, "name": "My Vector Store", "file_counts": { "in_progress": 0, "total": 0 }, "status": "completed", "expires_at": null, "last_usage_at": null, "metadata": {}, "usage_bytes": 0, "bytes_available": 1073741824, "bytes_assigned": 0 } ``` ``` -------------------------------- ### Example Graph State Initialization and Update Source: https://github.com/go-kratos/blades/blob/main/_autodocs/api-reference-graph.md Demonstrates how to initialize a graph state with various data types and how to update a value within the state. Ensure type assertions are used when retrieving values. ```go state := graph.State{ "counter": 0, "items": []string{"a", "b", "c"}, "config": map[string]any{ "timeout": 30, "retry": true, }, } // Update state in handler state["counter"] = state["counter"].(int) + 1 ``` -------------------------------- ### Create and Run a Basic Agent Source: https://github.com/go-kratos/blades/blob/main/_autodocs/INDEX.md Demonstrates the basic usage of creating an agent and running a single user message. Ensure the 'blades' package is imported. ```go agent, _ := blades.NewAgent("MyAgent", blades.WithModel(model)) runner := blades.NewRunner(agent) response, _ := runner.Run(ctx, blades.UserMessage("Hello")) fmt.Println(response.Text()) ``` -------------------------------- ### Get Conversation Item Source: https://github.com/go-kratos/blades/blob/main/cmd/docs/vendor/github.com/openai/openai-go/v3/api.md Retrieves a specific item from a conversation. This method corresponds to the GET /conversations/{conversation_id}/items/{item_id} endpoint. ```APIDOC ## GET /conversations/{conversation_id}/items/{item_id} ### Description Retrieves a specific item within a conversation. ### Method GET ### Endpoint /conversations/{conversation_id}/items/{item_id} ### Parameters #### Path Parameters - **conversation_id** (string) - Required - The ID of the conversation. - **item_id** (string) - Required - The ID of the item to retrieve. #### Query Parameters - **query** (conversations.ItemGetParams) - Optional - Parameters for retrieving the item. ### Response #### Success Response (200) - **ConversationItemUnion** (conversations.ConversationItemUnion) - The requested conversation item. #### Response Example ```json { "example": "response body" } ``` ``` -------------------------------- ### Create Assistant - Go Source: https://github.com/go-kratos/blades/blob/main/cmd/docs/vendor/github.com/openai/openai-go/v3/api.md Use this method to create a new assistant. It requires a context and parameters for the assistant's configuration. ```go client.Beta.Assistants.New(ctx context.Context, body openai.BetaAssistantNewParams) (openai.Assistant, error) ``` -------------------------------- ### Load Skills from Directory Source: https://github.com/go-kratos/blades/blob/main/_autodocs/api-reference-skills.md Loads all skills from a specified local directory. Ensure the directory exists and contains valid skill files. ```go import "github.com/go-kratos/blades/skills" skillList, err := skills.NewFromDir("./agent-skills") if err != nil { log.Fatal(err) } agent, _ := blades.NewAgent("MyAgent", blades.WithModel(model), blades.WithSkills(skillList...), ) ``` -------------------------------- ### File Uploads with OpenAI Go Client Source: https://github.com/go-kratos/blades/blob/main/cmd/docs/vendor/github.com/openai/openai-go/v3/README.md Demonstrates how to prepare file uploads for the OpenAI API using io.Reader. Shows examples for files from the file system, strings, and custom file names/content types. ```go // A file from the file system file, err := os.Open("input.jsonl") openai.FileNewParams{ File: file, Purpose: openai.FilePurposeFineTune, } ``` ```go // A file from a string openai.FileNewParams{ File: strings.NewReader("my file contents"), Purpose: openai.FilePurposeFineTune, } ``` ```go // With a custom filename and contentType openai.FileNewParams{ File: openai.File(strings.NewReader(`{"hello": "foo"}`), "file.go", "application/json"), Purpose: openai.FilePurposeFineTune, } ``` -------------------------------- ### Efficiently Get Raw JSON Bytes Source: https://github.com/go-kratos/blades/blob/main/cmd/docs/vendor/github.com/tidwall/gjson/README.md Provides a pattern to get the raw JSON bytes of a result without allocation by utilizing the `result.Index` field when working with `gjson.GetBytes`. ```go var json []byte = ... result := gjson.GetBytes(json, path) var raw []byte if result.Index > 0 { raw = json[result.Index:result.Index+len(result.Raw)] } else { raw = []byte(result.Raw) } ``` -------------------------------- ### Create and Run a Basic Chat Agent Source: https://github.com/go-kratos/blades/blob/main/_autodocs/quick-start-examples.md Demonstrates how to create a basic chat agent with a specific model and instruction, then execute a single user message and log the response. Ensure the ANTHROPIC_API_KEY environment variable is set. ```go package main import ( "context" "log" "os" "github.com/go-kratos/blades" "github.com/go-kratos/blades/contrib/anthropic" ) func main() { // Create model provider model := anthropic.NewModel("claude-3-5-sonnet-20241022", anthropic.Config{ APIKey: os.Getenv("ANTHROPIC_API_KEY"), }) // Create agent agent, err := blades.NewAgent("ChatBot", blades.WithModel(model), blades.WithInstruction("You are a helpful assistant."), ) if err != nil { log.Fatal(err) } // Create runner and execute runner := blades.NewRunner(agent) response, err := runner.Run(context.Background(), blades.UserMessage("What is the capital of France?"), ) if err != nil { log.Fatal(err) } log.Println(response.Text()) } ``` -------------------------------- ### Get Thread Source: https://github.com/go-kratos/blades/blob/main/cmd/docs/vendor/github.com/openai/openai-go/v3/api.md Retrieves a thread by its ID. ```APIDOC ## GET /threads/{thread_id} ### Description Retrieves a thread by its ID. ### Method GET ### Endpoint /threads/{thread_id} ### Parameters #### Path Parameters - **threadID** (string) - Required - The ID of the thread to retrieve. ### Response #### Success Response (200) - **Thread** (openai.Thread) - The thread object. ### Request Example ```go thread, err := client.Beta.Threads.Get(ctx, "thread_abc123") ``` ### Response Example ```json { "id": "thread_abc123", "object": "thread", "created_at": 1699000000, "metadata": {} } ``` ``` -------------------------------- ### Get Conversation Source: https://github.com/go-kratos/blades/blob/main/cmd/docs/vendor/github.com/openai/openai-go/v3/api.md Retrieves a specific conversation by its ID. ```APIDOC ## GET /conversations/{conversation_id} ### Description Retrieves a specific conversation. ### Method GET ### Endpoint /conversations/{conversation_id} ### Parameters #### Path Parameters - **conversation_id** (string) - Required - The ID of the conversation to retrieve. ### Response #### Success Response (200) - **Conversation** (conversations.Conversation) - The requested conversation object. - **error** (error) - An error if the retrieval failed. ``` -------------------------------- ### Get Thread Source: https://github.com/go-kratos/blades/blob/main/cmd/docs/vendor/github.com/openai/openai-go/v3/api.md Retrieves a specific thread by its ID. ```APIDOC ## GET /chatkit/threads/{thread_id} ### Description Retrieves a specific thread using its unique identifier. ### Method GET ### Endpoint `/chatkit/threads/{thread_id}` ### Parameters #### Path Parameters - **thread_id** (string) - Required - The unique identifier of the thread to retrieve. ### Response #### Success Response (200) - **ChatKitThread** (openai.ChatKitThread) - The retrieved thread object. #### Response Example ```json { "id": "thread_abc123", "object": "thread", "created_at": 1678905600, "metadata": {}, "tool_resources": {}, "tool_choice": {}, "truncation_strategy": {}, "expires_at": null, "last_at": 1678905600, "max_messages": null, "max_tokens": null, "messages": { "object": "list", "data": [], "first_id": null, "last_id": null, "has_more": false } } ``` ``` -------------------------------- ### File Checkpointer Implementation Source: https://github.com/go-kratos/blades/blob/main/_autodocs/api-reference-graph.md Provides a concrete implementation of the 'Checkpointer' interface using the file system. This example shows how to marshal state to JSON for saving and unmarshal it for loading. It also demonstrates how to integrate a custom checkpointer with the graph executor. ```go type FileCheckpointer struct { BasePath string } func (f *FileCheckpointer) Save(ctx context.Context, execID string, nodeID string, state graph.State) error { path := filepath.Join(f.BasePath, execID+".json") data, _ := json.Marshal(state) return os.WriteFile(path, data, 0644) } func (f *FileCheckpointer) Load(ctx context.Context, execID string) (graph.State, error) { path := filepath.Join(f.BasePath, execID+".json") data, err := os.ReadFile(path) if err != nil { return nil, err } var state graph.State json.Unmarshal(data, &state) return state, nil } checkpointer := &FileCheckpointer{BasePath: "./checkpoints"} executor, _ := g.Compile(graph.WithCheckpointer(checkpointer)) ``` -------------------------------- ### Get Chat Completion Source: https://github.com/go-kratos/blades/blob/main/cmd/docs/vendor/github.com/openai/openai-go/v3/api.md Retrieves a specific chat completion by its ID. ```APIDOC ## GET /chat/completions/{completion_id} ### Description Retrieves a specific chat completion by its ID. ### Method GET ### Endpoint /chat/completions/{completion_id} ### Parameters #### Path Parameters - **completion_id** (string) - Required - The ID of the completion to retrieve. ### Response #### Success Response (200) - **ChatCompletion** (openai.ChatCompletion) - The requested chat completion object. - **error** (error) - An error if the request failed. ``` -------------------------------- ### Get Session ID Source: https://github.com/go-kratos/blades/blob/main/_autodocs/api-reference-session.md Retrieves the unique identifier for the current session. ```go func (s *sessionInMemory) ID() string ``` -------------------------------- ### Basic Chat Agent with OpenAI Source: https://github.com/go-kratos/blades/blob/main/README.md Demonstrates how to create a simple chat agent using the OpenAI model provider. Ensure OPENAI_API_KEY environment variable is set. ```go package main import ( "context" "log" "os" "github.com/go-kratos/blades" "github.com/go-kratos/blades/contrib/openai" ) func main() { // Configure OpenAI API key and base URL using environment variables: model := openai.NewModel("gpt-5", openai.Config{ APIKey: os.Getenv("OPENAI_API_KEY"), }) agent := blades.NewAgent( "Blades Agent", blades.WithModel(model), blades.WithInstruction("You are a helpful assistant that provides detailed and accurate information."), ) // Create a Prompt with user message input := blades.UserMessage("What is the capital of France?") // Run the Agent with the Prompt runner := blades.NewRunner(agent) output, err := runner.Run(context.Background(), input) if err != nil { log.Fatal(err) } // Print the agent's response log.Println(output.Text()) } ``` -------------------------------- ### Get Container Source: https://github.com/go-kratos/blades/blob/main/cmd/docs/vendor/github.com/openai/openai-go/v3/api.md Retrieves a specific container by its ID. Requires a context and the container ID. ```APIDOC ## GET /containers/{container_id} ### Description Retrieves a specific container by its ID. ### Method GET ### Endpoint /containers/{container_id} ### Parameters #### Path Parameters - **container_id** (string) - Required - The ID of the container to retrieve. ### Response #### Success Response (200) - **ContainerGetResponse** (openai.ContainerGetResponse) - The response object containing container details. ``` -------------------------------- ### Agent with Dynamic Instructions Source: https://github.com/go-kratos/blades/blob/main/_autodocs/patterns-and-best-practices.md Use instruction providers to enable context-aware agent behavior. The agent's instructions can adapt based on runtime context, such as user role, without needing to recreate the agent. ```go agent, _ := blades.NewAgent("ContextAgent", blades.WithModel(model), blades.WithInstructionProvider(func(ctx context.Context) (string, error) { userRole, _ := ctx.Value("role").(string) return fmt.Sprintf("You are a %s assistant", userRole), nil }), ) ``` -------------------------------- ### Create a new Toolset from skills Source: https://github.com/go-kratos/blades/blob/main/_autodocs/api-reference-skills.md Use this function to initialize a Toolset by providing a list of skills. Ensure all necessary skills are loaded before calling this function. ```go func NewToolset(skillList []Skill) (*Toolset, error) ``` ```go import "github.com/go-kratos/blades/skills" skillList, _ := skills.NewFromDir("./skills") toolset, err := skills.NewToolset(skillList) if err != nil { log.Fatal(err) } tools := toolset.Tools() fmt.Printf("Available tools: %d\n", len(tools)) ``` -------------------------------- ### Get Batch Source: https://github.com/go-kratos/blades/blob/main/cmd/docs/vendor/github.com/openai/openai-go/v3/api.md Retrieves a specific batch by its ID. Requires context and the batch ID. ```APIDOC ## GET /batches/{batch_id} ### Description Retrieves a specific batch by its ID. ### Method GET ### Endpoint /batches/{batch_id} ### Parameters #### Path Parameters - **batch_id** (string) - Required - The unique identifier of the batch. ### Response #### Success Response (200) - **Batch** (openai.Batch) - The requested batch object. - **error** (error) - An error if the retrieval failed. ``` -------------------------------- ### Retrieve Assistant Source: https://github.com/go-kratos/blades/blob/main/cmd/docs/vendor/github.com/openai/openai-go/v3/api.md Retrieves an assistant. Use this endpoint to get a specific assistant by its ID. ```APIDOC ## GET /assistants/{assistant_id} ### Description Retrieves an assistant. ### Method GET ### Endpoint /assistants/{assistant_id} ### Parameters #### Path Parameters - **assistant_id** (string) - Required - The ID of the assistant to retrieve. ### Response #### Success Response (200) - **Assistant** (openai.Assistant) - The assistant object. ``` -------------------------------- ### Configure Agent with Instruction Template Variables Source: https://github.com/go-kratos/blades/blob/main/_autodocs/configuration.md Use Go template syntax within agent instructions to dynamically set behavior based on session state. This allows for personalized agent responses. ```go agent, _ := blades.NewAgent("PersonalizedBot", blades.WithModel(model), blades.WithInstruction(`You are a {{.Role}} assistant. Language preference: {{.Language}}. Timezone: {{.Timezone}}.`), ) session := blades.NewSession() session.SetState("Role", "technical support") session.SetState("Language", "Spanish") session.SetState("Timezone", "UTC-5") runner := blades.NewRunner(agent) runner.Run(ctx, msg, blades.WithSession(session)) ```