-
Notifications
You must be signed in to change notification settings - Fork 511
feat: add SAP AI Core provider via Orchestration Service #1610
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
Huimintai
wants to merge
4
commits into
kagent-dev:main
Choose a base branch
from
Huimintai:support-sap-gen-ai-hub
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
4 commits
Select commit
Hold shift + click to select a range
a3d75fb
feat: add SAP AI Core provider via Orchestration Service
e65b343
feat: add SAP AI Core support to Go ADK runtime
63561fa
Merge branch 'main' into support-sap-gen-ai-hub
Huimintai f0a63c0
fix: address review comments for SAP AI Core provider support
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,188 @@ | ||
| package models | ||
|
|
||
| import ( | ||
| "context" | ||
| "encoding/json" | ||
| "fmt" | ||
| "net/http" | ||
| "net/url" | ||
| "os" | ||
| "strings" | ||
| "sync" | ||
| "time" | ||
|
|
||
| "github.com/go-logr/logr" | ||
| ) | ||
|
|
||
| type SAPAICoreConfig struct { | ||
| Model string | ||
| BaseUrl string | ||
| ResourceGroup string | ||
| AuthUrl string | ||
| Headers map[string]string | ||
| } | ||
|
|
||
| type SAPAICoreModel struct { | ||
| Config SAPAICoreConfig | ||
| Logger logr.Logger | ||
|
|
||
| mu sync.Mutex | ||
| token string | ||
| tokenExpiresAt time.Time | ||
| deploymentURL string | ||
| deploymentURLAt time.Time | ||
| httpClient *http.Client | ||
| } | ||
|
|
||
| func NewSAPAICoreModelWithLogger(config SAPAICoreConfig, logger logr.Logger) (*SAPAICoreModel, error) { | ||
| if config.BaseUrl == "" { | ||
| return nil, fmt.Errorf("SAP AI Core requires base_url") | ||
| } | ||
| if config.ResourceGroup == "" { | ||
| config.ResourceGroup = "default" | ||
| } | ||
| return &SAPAICoreModel{ | ||
| Config: config, | ||
| Logger: logger, | ||
| httpClient: &http.Client{Timeout: 5 * time.Minute}, | ||
| }, nil | ||
| } | ||
|
|
||
| func (m *SAPAICoreModel) ensureToken(ctx context.Context) (string, error) { | ||
| m.mu.Lock() | ||
| defer m.mu.Unlock() | ||
|
|
||
| if m.token != "" && time.Now().Before(m.tokenExpiresAt.Add(-2*time.Minute)) { | ||
| return m.token, nil | ||
| } | ||
|
|
||
| clientID := os.Getenv("SAP_AI_CORE_CLIENT_ID") | ||
| clientSecret := os.Getenv("SAP_AI_CORE_CLIENT_SECRET") | ||
| if m.Config.AuthUrl == "" || clientID == "" || clientSecret == "" { | ||
| return "", fmt.Errorf("SAP AI Core requires auth_url + SAP_AI_CORE_CLIENT_ID/SECRET env vars") | ||
| } | ||
|
|
||
| tokenURL := strings.TrimRight(m.Config.AuthUrl, "/") | ||
| if !strings.HasSuffix(tokenURL, "/oauth/token") { | ||
| tokenURL += "/oauth/token" | ||
| } | ||
|
|
||
| formData := url.Values{ | ||
| "grant_type": {"client_credentials"}, | ||
| "client_id": {clientID}, | ||
| "client_secret": {clientSecret}, | ||
| } | ||
| req, err := http.NewRequestWithContext(ctx, "POST", tokenURL, strings.NewReader(formData.Encode())) | ||
| if err != nil { | ||
| return "", fmt.Errorf("failed to create OAuth2 token request: %w", err) | ||
| } | ||
| req.Header.Set("Content-Type", "application/x-www-form-urlencoded") | ||
|
|
||
| resp, err := m.httpClient.Do(req) | ||
| if err != nil { | ||
| return "", fmt.Errorf("OAuth2 token request failed: %w", err) | ||
| } | ||
| defer resp.Body.Close() | ||
|
|
||
| if resp.StatusCode != http.StatusOK { | ||
| return "", &orchHTTPError{StatusCode: resp.StatusCode, URL: tokenURL} | ||
| } | ||
|
|
||
| var tokenResp struct { | ||
| AccessToken string `json:"access_token"` | ||
| ExpiresIn int `json:"expires_in"` | ||
| } | ||
| if err := json.NewDecoder(resp.Body).Decode(&tokenResp); err != nil { | ||
| return "", fmt.Errorf("failed to decode OAuth2 token response: %w", err) | ||
| } | ||
|
|
||
| m.token = tokenResp.AccessToken | ||
| if tokenResp.ExpiresIn > 0 { | ||
| m.tokenExpiresAt = time.Now().Add(time.Duration(tokenResp.ExpiresIn) * time.Second) | ||
| } else { | ||
| m.tokenExpiresAt = time.Now().Add(12 * time.Hour) | ||
| } | ||
| return m.token, nil | ||
| } | ||
|
|
||
| func (m *SAPAICoreModel) invalidateToken() { | ||
| m.mu.Lock() | ||
| defer m.mu.Unlock() | ||
| m.token = "" | ||
| m.tokenExpiresAt = time.Time{} | ||
| } | ||
|
|
||
| func (m *SAPAICoreModel) resolveDeploymentURL(ctx context.Context) (string, error) { | ||
| m.mu.Lock() | ||
| if m.deploymentURL != "" && time.Now().Before(m.deploymentURLAt.Add(time.Hour)) { | ||
| u := m.deploymentURL | ||
| m.mu.Unlock() | ||
| return u, nil | ||
| } | ||
| m.mu.Unlock() | ||
|
|
||
| token, err := m.ensureToken(ctx) | ||
| if err != nil { | ||
| return "", err | ||
| } | ||
|
|
||
| reqURL := fmt.Sprintf("%s/v2/lm/deployments", m.Config.BaseUrl) | ||
| req, err := http.NewRequestWithContext(ctx, "GET", reqURL, nil) | ||
| if err != nil { | ||
| return "", err | ||
| } | ||
| req.Header.Set("Authorization", "Bearer "+token) | ||
| req.Header.Set("AI-Resource-Group", m.Config.ResourceGroup) | ||
|
|
||
| resp, err := m.httpClient.Do(req) | ||
| if err != nil { | ||
| return "", fmt.Errorf("failed to list deployments: %w", err) | ||
| } | ||
| defer resp.Body.Close() | ||
|
|
||
| if resp.StatusCode != http.StatusOK { | ||
| return "", &orchHTTPError{StatusCode: resp.StatusCode, URL: reqURL} | ||
| } | ||
|
|
||
| var result struct { | ||
| Resources []struct { | ||
| ID string `json:"id"` | ||
| ScenarioID string `json:"scenarioId"` | ||
| Status string `json:"status"` | ||
| DeploymentURL string `json:"deploymentUrl"` | ||
| CreatedAt string `json:"createdAt"` | ||
| } `json:"resources"` | ||
| } | ||
| if err := json.NewDecoder(resp.Body).Decode(&result); err != nil { | ||
| return "", fmt.Errorf("failed to decode deployments: %w", err) | ||
| } | ||
|
|
||
| var best string | ||
| var bestCreated string | ||
| for _, d := range result.Resources { | ||
| if d.ScenarioID == "orchestration" && d.Status == "RUNNING" && d.DeploymentURL != "" { | ||
| if d.CreatedAt > bestCreated { | ||
| best = d.DeploymentURL | ||
| bestCreated = d.CreatedAt | ||
| } | ||
| } | ||
| } | ||
| if best == "" { | ||
| return "", fmt.Errorf("no running orchestration deployment found in SAP AI Core") | ||
| } | ||
|
|
||
| m.mu.Lock() | ||
| m.deploymentURL = best | ||
| m.deploymentURLAt = time.Now() | ||
| m.mu.Unlock() | ||
|
|
||
| m.Logger.Info("Resolved SAP AI Core orchestration deployment", "url", best) | ||
| return best, nil | ||
| } | ||
|
|
||
| func (m *SAPAICoreModel) invalidateDeploymentURL() { | ||
| m.mu.Lock() | ||
| defer m.mu.Unlock() | ||
| m.deploymentURL = "" | ||
| m.deploymentURLAt = time.Time{} | ||
| } | ||
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
There are no unit tests for any of the new code. At minimum we need coverage for:
genaiContentsToOrchTemplate— message conversion with text, tool calls, and function responsesbuildOrchestrationBody— request body construction with various config options_build_orchestration_template(Python equivalent)handleStreamand_stream_request)Please add unit tests for the Go and Python implementations.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Resolved