-
Notifications
You must be signed in to change notification settings - Fork 171
Push llm event address #3664
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
Merged
+895
−131
Merged
Push llm event address #3664
Changes from all commits
Commits
Show all changes
18 commits
Select commit
Hold shift + click to select a range
0fe616d
Push llm event address
estringana ddb5115
Add missing operations
estringana c826cf7
Add tests
estringana 70dac6e
Make appsec mock to work in memory
estringana 0b41651
Move push address to prehook
estringana 123295c
Create fake response
estringana b5e2c9a
Update snapshots
estringana 6028af2
Fix Mysql implementation of mock
estringana b64379c
Fix addEvent signature
estringana 86bde1a
Explain the values of the array
estringana 905ba6a
Add integration tests for llm events
estringana 0eb5a02
Fix port
estringana 3c92b67
Make it compatible with php 7.0
estringana 193aafa
Amend comments from PR
estringana 277957f
Avoid creating not required span
estringana e618728
Fix tests
estringana dc468ff
Amend pr comments
estringana ba5e2ab
Merge branch 'master' into estringana/add-openai-integration
estringana 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
153 changes: 153 additions & 0 deletions
153
...ts/integration/src/main/groovy/com/datadog/appsec/php/mock_openai/MockOpenAIServer.groovy
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,153 @@ | ||
| package com.datadog.appsec.php.mock_openai | ||
|
|
||
| import groovy.json.JsonSlurper | ||
| import groovy.transform.CompileStatic | ||
| import groovy.util.logging.Slf4j | ||
| import io.javalin.Javalin | ||
| import io.javalin.http.Context | ||
| import org.testcontainers.lifecycle.Startable | ||
|
|
||
| @Slf4j | ||
| @CompileStatic | ||
| class MockOpenAIServer implements Startable { | ||
| Javalin httpServer | ||
|
|
||
| @Override | ||
| void start() { | ||
| this.httpServer = Javalin.create(config -> { | ||
| config.showJavalinBanner = false | ||
| }) | ||
|
|
||
| // Support both /path and /v1/path for OpenAI client compatibility | ||
| this.httpServer.post('/chat/completions', this.&handleChatCompletions) | ||
| this.httpServer.post('/v1/chat/completions', this.&handleChatCompletions) | ||
| this.httpServer.post('/completions', this.&handleCompletions) | ||
| this.httpServer.post('/v1/completions', this.&handleCompletions) | ||
| this.httpServer.post('/responses', this.&handleResponses) | ||
| this.httpServer.post('/v1/responses', this.&handleResponses) | ||
|
|
||
| this.httpServer.error(404, ctx -> { | ||
| log.info("Unmatched OpenAI mock request: ${ctx.method()} ${ctx.path()}") | ||
| ctx.status(404).json(['error': 'Not Found']) | ||
| }) | ||
| this.httpServer.error(405, ctx -> { | ||
| ctx.status(405).json(['error': 'Method Not Allowed']) | ||
| }) | ||
|
|
||
| this.httpServer.start(0) | ||
| } | ||
|
|
||
| int getPort() { | ||
| this.httpServer.port() | ||
| } | ||
|
|
||
| @Override | ||
| void stop() { | ||
| if (httpServer != null) { | ||
| this.httpServer.stop() | ||
| this.httpServer = null | ||
| } | ||
| } | ||
|
|
||
| private static Map<String, ?> parseBody(Context ctx) { | ||
| String raw = ctx.body() | ||
| if (raw == null || raw.isEmpty()) { | ||
| return [:] | ||
| } | ||
| try { | ||
| def decoded = new JsonSlurper().parseText(raw) | ||
| return decoded instanceof Map ? (Map<String, ?>) decoded : [:] | ||
| } catch (Exception e) { | ||
| return [:] | ||
| } | ||
| } | ||
|
|
||
| private static Map<String, ?> fakeUsage() { | ||
| [ | ||
| 'prompt_tokens' : 1, | ||
| 'completion_tokens': 2, | ||
| 'total_tokens' : 3, | ||
| ] | ||
| } | ||
|
|
||
| private void handleChatCompletions(Context ctx) { | ||
| Map<String, ?> body = parseBody(ctx) | ||
| String model = (body['model'] as String) ?: 'gpt-4.1' | ||
| ctx.json([ | ||
| 'id' : 'chatcmpl-fake-internal', | ||
| 'object' : 'chat.completion', | ||
| 'created': (long)(System.currentTimeMillis() / 1000), | ||
| 'model' : model, | ||
| 'choices': [ | ||
| [ | ||
| 'index' : 0, | ||
| 'message' : [ | ||
| 'role' : 'assistant', | ||
| 'content': 'Fake response from internal_server mock.', | ||
| ], | ||
| 'finish_reason': 'stop', | ||
| ], | ||
| ], | ||
| 'usage' : fakeUsage(), | ||
| ]) | ||
| } | ||
|
|
||
| private void handleCompletions(Context ctx) { | ||
| Map<String, ?> body = parseBody(ctx) | ||
| String model = (body['model'] as String) ?: 'text-davinci-003' | ||
| ctx.json([ | ||
| 'id' : 'cmpl-fake-internal', | ||
| 'object' : 'text_completion', | ||
| 'created': (long)(System.currentTimeMillis() / 1000), | ||
| 'model' : model, | ||
| 'choices': [ | ||
| [ | ||
| 'text' : 'Fake completion from internal_server mock.', | ||
| 'index' : 0, | ||
| 'finish_reason': 'stop', | ||
| 'logprobs' : null, | ||
| ], | ||
| ], | ||
| 'usage' : fakeUsage(), | ||
| ]) | ||
| } | ||
|
|
||
| private void handleResponses(Context ctx) { | ||
| Map<String, ?> body = parseBody(ctx) | ||
| String model = (body['model'] as String) ?: 'gpt-4.1' | ||
| ctx.json([ | ||
| 'id' : 'resp-fake-internal', | ||
| 'object' : 'response', | ||
| 'created_at' : (long)(System.currentTimeMillis() / 1000), | ||
| 'status' : 'completed', | ||
| 'model' : model, | ||
| 'output' : [ | ||
| [ | ||
| 'type' : 'message', | ||
| 'id' : 'msg-fake-internal', | ||
| 'role' : 'assistant', | ||
| 'status' : 'completed', | ||
| 'content': [ | ||
| [ | ||
| 'type' : 'output_text', | ||
| 'text' : 'Fake response from internal_server mock.', | ||
| 'annotations': [], | ||
| ], | ||
| ], | ||
| ], | ||
| ], | ||
| 'output_text' : 'Fake response from internal_server mock.', | ||
| 'parallel_tool_calls' : false, | ||
| 'tool_choice' : 'none', | ||
| 'tools' : [], | ||
| 'store' : true, | ||
| 'usage' : [ | ||
| 'input_tokens' : 1, | ||
| 'input_tokens_details' : ['cached_tokens': 0], | ||
| 'output_tokens' : 2, | ||
| 'output_tokens_details' : ['reasoning_tokens': 0], | ||
| 'total_tokens' : 3, | ||
| ], | ||
| ]) | ||
| } | ||
| } | ||
107 changes: 107 additions & 0 deletions
107
...ests/integration/src/test/groovy/com/datadog/appsec/php/integration/LlmEventsTests.groovy
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,107 @@ | ||
| package com.datadog.appsec.php.integration | ||
|
|
||
| import com.datadog.appsec.php.docker.AppSecContainer | ||
| import com.datadog.appsec.php.docker.FailOnUnmatchedTraces | ||
| import com.datadog.appsec.php.mock_openai.MockOpenAIServer | ||
| import com.datadog.appsec.php.docker.InspectContainerHelper | ||
| import com.datadog.appsec.php.model.Span | ||
| import com.datadog.appsec.php.model.Trace | ||
| import org.junit.jupiter.api.BeforeAll | ||
| import org.junit.jupiter.api.Test | ||
| import org.junit.jupiter.api.TestMethodOrder | ||
| import org.junit.jupiter.api.condition.EnabledIf | ||
| import org.testcontainers.junit.jupiter.Container | ||
| import org.testcontainers.junit.jupiter.Testcontainers | ||
|
|
||
| import java.io.InputStream | ||
|
|
||
| import static org.testcontainers.containers.Container.ExecResult | ||
| import java.net.http.HttpRequest | ||
| import java.net.http.HttpResponse | ||
|
|
||
| import static com.datadog.appsec.php.integration.TestParams.getPhpVersion | ||
| import static com.datadog.appsec.php.integration.TestParams.getVariant | ||
| import static com.datadog.appsec.php.integration.TestParams.phpVersionAtLeast | ||
| import com.datadog.appsec.php.TelemetryHelpers | ||
| import static java.net.http.HttpResponse.BodyHandlers.ofString | ||
|
|
||
| @Testcontainers | ||
| @EnabledIf('isExpectedVersion') | ||
| class LlmEventsTests { | ||
| static final String MODEL = 'gpt-4.1' | ||
| static boolean expectedVersion = phpVersionAtLeast('8.2') && !variant.contains('zts') | ||
|
|
||
| AppSecContainer getContainer() { | ||
| getClass().CONTAINER | ||
| } | ||
|
|
||
| public static final MockOpenAIServer mockOpenAIServer = new MockOpenAIServer() | ||
estringana marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
|
||
| @Container | ||
| @FailOnUnmatchedTraces | ||
| public static final AppSecContainer CONTAINER = | ||
| new AppSecContainer( | ||
| workVolume: this.name, | ||
| baseTag: 'apache2-mod-php', | ||
| phpVersion: phpVersion, | ||
| phpVariant: variant, | ||
| www: 'llm', | ||
| ) { | ||
| { | ||
| dependsOn mockOpenAIServer | ||
| } | ||
|
|
||
| @Override | ||
| void configure() { | ||
| super.configure() | ||
| org.testcontainers.Testcontainers.exposeHostPorts(mockOpenAIServer.port) | ||
| withEnv('OPENAI_BASE_URL', "http://host.testcontainers.internal:${mockOpenAIServer.port}/v1") | ||
| } | ||
| } | ||
|
|
||
| static void main(String[] args) { | ||
| InspectContainerHelper.run(CONTAINER) | ||
| } | ||
|
|
||
| /** Common assertions for LLM endpoint spans. */ | ||
| static void assertLlmSpan(Trace trace, String model) { | ||
| Span span = trace.first() | ||
| assert span.meta.'appsec.events.llm.call.provider' == 'openai' | ||
| assert span.meta.'appsec.events.llm.call.model' == model | ||
| assert span.metrics._sampling_priority_v1 == 2.0d | ||
| } | ||
|
|
||
| @Test | ||
| void 'OpenAI latest responses create'() { | ||
| def trace = container.traceFromRequest("/llm.php?model=${MODEL}&operation=openai-latest-responses.create") { HttpResponse<InputStream> resp -> | ||
| assert resp.statusCode() == 200 | ||
| } | ||
| assertLlmSpan(trace, MODEL) | ||
| } | ||
|
|
||
| @Test | ||
| void 'OpenAI latest chat completions create'() { | ||
| def trace = container.traceFromRequest("/llm.php?model=${MODEL}&operation=openai-latest-chat.completions.create") { HttpResponse<InputStream> resp -> | ||
| assert resp.statusCode() == 200 | ||
| } | ||
| assertLlmSpan(trace, MODEL) | ||
| } | ||
|
|
||
| @Test | ||
| void 'OpenAI latest completions create'() { | ||
| def trace = container.traceFromRequest("/llm.php?model=${MODEL}&operation=openai-latest-completions.create") { HttpResponse<InputStream> resp -> | ||
| assert resp.statusCode() == 200 | ||
| } | ||
| assertLlmSpan(trace, MODEL) | ||
| } | ||
|
|
||
| @Test | ||
| void 'Root has no LLM tags'() { | ||
| def trace = container.traceFromRequest('/hello.php') { HttpResponse<InputStream> resp -> | ||
| assert resp.statusCode() == 200 | ||
| } | ||
| Span span = trace.first() | ||
| assert !span.meta.containsKey('appsec.events.llm.call.provider') | ||
| assert !span.meta.containsKey('appsec.events.llm.call.model') | ||
| } | ||
estringana marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| } | ||
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,8 @@ | ||
| { | ||
| "name": "datadog/appsec-integration-tests", | ||
| "type": "project", | ||
| "require": { | ||
| "openai-php/client": "*", | ||
| "guzzlehttp/guzzle": "*" | ||
| } | ||
| } |
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,6 @@ | ||
| #!/bin/bash -e | ||
|
|
||
| cd /var/www | ||
|
|
||
| composer install --no-dev | ||
| chown -R www-data.www-data vendor |
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,8 @@ | ||
| <?php | ||
| header('Content-Encoding: foobar'); | ||
| header('Content-Language: en'); | ||
|
|
||
| $content = "Hello world!"; | ||
|
|
||
| echo $content; | ||
|
|
Oops, something went wrong.
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.
same effect could be gotten in groovy by not making
PORTprivate(with no access modifiers, it generates setters/getters)