5. Advanced Prompt

  1. Defining Structured Output: The example starts by defining structures for the expected output:

    type AnalysisResult struct {
        Perspectives []Perspective `json:"perspectives"`
        Summary      string        `json:"summary"`
    }
    
    type Perspective struct {
        Name         string   `json:"name"`
        Implications []string `json:"implications"`
    }

    These structures will be used to parse the JSON response from the LLM.

  2. Creating an LLM Instance: The example creates an LLM instance with detailed configuration:

    llmClient, err := gollm.NewLLM(
        gollm.SetProvider("openai"),
        gollm.SetModel("gpt-4o-mini"),
        gollm.SetTemperature(0.7),
        gollm.SetMaxTokens(1000),
        gollm.SetTimeout(30*time.Second),
        gollm.SetMaxRetries(3),
        gollm.SetRetryDelay(1*time.Second),
        gollm.SetDebugLevel(gollm.LogLevelInfo),
        gollm.SetAPIKey(apiKey),
    )
  3. Defining Reusable Directives: The example defines a set of reusable directives for balanced analysis:

    balancedAnalysisDirectives := []string{
        "Consider technological, economic, social, and ethical implications",
        "Provide at least one potential positive and one potential negative outcome for each perspective",
        "Ensure the analysis is balanced and objective",
    }
  4. Creating a Custom Prompt Template: A custom prompt template is created for balanced analysis:

    balancedAnalysisTemplate := gollm.NewPromptTemplate(
        "BalancedAnalysis",
        "Analyze a topic from multiple perspectives",
        `Analyze the following topic from multiple perspectives: {{.Topic}}
    
    Please structure your response as a JSON object with the following format:
    {
      "perspectives": [
        {
          "name": "Perspective Name",
          "implications": [
            "Positive implication",
            "Negative implication"
          ]
        }
      ],
      "summary": "A brief, balanced summary of the analysis"
    }`,
        gollm.WithPromptOptions(
            gollm.WithDirectives(balancedAnalysisDirectives...),
            gollm.WithMaxLength(500),
        ),
    )

    This template includes the JSON structure for the expected output.

  5. Analyzing Multiple Topics: The example defines a list of topics and analyzes each one:

    topics := []string{
        "The impact of artificial intelligence on job markets",
        "The role of social media in modern democracy",
        "The transition to renewable energy sources",
    }
    
    for _, topic := range topics {
        // Execute the prompt template
        prompt, err := balancedAnalysisTemplate.Execute(map[string]interface{}{
            "Topic": topic,
        })
    
        // Generate the analysis
        analysisJSON, err := llmClient.Generate(ctx, prompt, gollm.WithJSONSchemaValidation())
    
        // Parse the JSON response
        var result AnalysisResult
        err = json.Unmarshal([]byte(analysisJSON), &result)
    
        // Print the structured analysis
        // ...
    }

    For each topic, it executes the template, generates an analysis, parses the JSON response, and prints the structured analysis.

  6. Demonstrating Additional Features: The example showcases additional gollm package features:

    a. Summarization:

    summary, err := gollm.Summarize(ctx, llmClient, analysisJSON, gollm.WithMaxLength(50))

    b. Chain of Thought reasoning:

    keyPoints, err := gollm.ChainOfThought(ctx, llmClient, fmt.Sprintf("Extract 3 key points from this analysis:\n%s", analysisJSON))
  7. Error Handling and Retries: The example demonstrates error handling by intentionally causing an error:

    _, err = gollm.QuestionAnswer(ctx, llmClient, "This is an intentionally long prompt that exceeds the token limit to demonstrate error handling.")
    if err != nil {
        fmt.Printf("Expected error occurred: %v\n", err)
    }

In summary, this advanced example demonstrates:

  • Defining structured output using Go structs

  • Creating a custom prompt template with specific JSON output format

  • Analyzing multiple topics using the same template

  • Parsing and processing structured JSON responses

  • Using additional gollm features like Summarize and ChainOfThought

  • Error handling and retry mechanisms

This example is particularly useful for developers who need to work with structured outputs from LLMs, want to create reusable analysis templates, and leverage advanced features of the gollm package for complex NLP tasks.

Last updated